blob: 68da466e857ff2aa5893666c26b1546ab674609a [file] [log] [blame]
/**
*
* Copyright (c) 2011, 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
*
*
* This copyright notice shows up in the generated Java code
*
*/
package org.eclipse.osbp.xtext.entitymock.jvmmodel
import com.google.inject.Inject
import java.util.ArrayList
import java.util.List
import java.util.Map
import java.util.Set
import org.apache.commons.lang.StringUtils
import org.apache.commons.lang.WordUtils
import org.eclipse.osbp.core.api.persistence.IPersistenceService
import org.eclipse.osbp.datainterchange.api.IDataInterchange
import org.eclipse.osbp.dsl.entity.xtext.extensions.ModelExtensions
import org.eclipse.osbp.dsl.semantic.common.types.LEnum
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.runtime.common.event.IEventDispatcher
import org.eclipse.osbp.ui.api.customfields.IBlobService
import org.eclipse.osbp.utils.annotation.CommonUtils
import org.eclipse.osbp.utils.common.EntityUtils
import org.eclipse.osbp.utils.entityhelper.DataType
import org.eclipse.osbp.xtext.datainterchange.jvmmodel.DataDSLJvmModelInferrer
import org.eclipse.osbp.xtext.entitymock.Date
import org.eclipse.osbp.xtext.entitymock.DateIterate
import org.eclipse.osbp.xtext.entitymock.EntityMock
import org.eclipse.osbp.xtext.entitymock.EntityMockAttributeByObject
import org.eclipse.osbp.xtext.entitymock.EntityMockAttributeByReference
import org.eclipse.osbp.xtext.entitymock.EntityMockAttributeFiller
import org.eclipse.osbp.xtext.entitymock.EntityMockEntity
import org.eclipse.osbp.xtext.entitymock.EntityMockEntityFunctionParameter
import org.eclipse.osbp.xtext.entitymock.EntityMockObject
import org.eclipse.osbp.xtext.entitymock.EntityMockObjectArrayValue
import org.eclipse.osbp.xtext.entitymock.EntityMockObjectEmbed
import org.eclipse.osbp.xtext.entitymock.EntityMockObjectEnum
import org.eclipse.osbp.xtext.entitymock.EntityMockObjectFill
import org.eclipse.osbp.xtext.entitymock.EntityMockObjectFunction
import org.eclipse.osbp.xtext.entitymock.EntityMockObjectPlainValue
import org.eclipse.osbp.xtext.entitymock.EntityMockObjectResourceValue
import org.eclipse.osbp.xtext.entitymock.EntityMockPackage
import org.eclipse.osbp.xtext.entitymock.EntityMockResource
import org.eclipse.osbp.xtext.entitymock.EntityMockResourceDataRow
import org.eclipse.osbp.xtext.entitymock.EntityMockTemplate
import org.eclipse.osbp.xtext.entitymock.IEntityMockObjectUsable
import org.eclipse.osbp.xtext.entitymock.IntegerIterate
import org.eclipse.osbp.xtext.entitymock.PropertyFillerBoolean
import org.eclipse.osbp.xtext.entitymock.PropertyFillerDateFuture
import org.eclipse.osbp.xtext.entitymock.PropertyFillerDatePast
import org.eclipse.osbp.xtext.entitymock.PropertyFillerDateRange
import org.eclipse.osbp.xtext.entitymock.PropertyFillerSignedDoubleRandom
import org.eclipse.osbp.xtext.entitymock.PropertyFillerSignedDoubleRange
import org.eclipse.osbp.xtext.entitymock.PropertyFillerSignedIntegerRandom
import org.eclipse.osbp.xtext.entitymock.PropertyFillerSignedIntegerRange
import org.eclipse.osbp.xtext.entitymock.PropertyFillerTextParagraphs
import org.eclipse.osbp.xtext.entitymock.PropertyFillerTextRandom
import org.eclipse.osbp.xtext.entitymock.PropertyFillerTextSentences
import org.eclipse.osbp.xtext.entitymock.PropertyFillerTextWords
import org.eclipse.osbp.xtext.entitymock.PropertyFillerUnsignedDoubleRandom
import org.eclipse.osbp.xtext.entitymock.PropertyFillerUnsignedDoubleRange
import org.eclipse.osbp.xtext.entitymock.PropertyFillerUnsignedIntegerRandom
import org.eclipse.osbp.xtext.entitymock.PropertyFillerUnsignedIntegerRange
import org.eclipse.osbp.xtext.entitymock.common.ABaseMockEntity
import org.eclipse.osbp.xtext.entitymock.common.ABaseMockObject
import org.eclipse.osbp.xtext.entitymock.common.ABaseMockResource
import org.eclipse.osbp.xtext.entitymock.common.AEntityMockDataGenerator
import org.eclipse.osbp.xtext.entitymock.common.IEntityMockDataDbFiller
import org.eclipse.osbp.xtext.entitymock.common.IEntityMockDataGenerator
import org.eclipse.xtext.common.types.JvmEnumerationType
import org.eclipse.xtext.common.types.JvmField
import org.eclipse.xtext.common.types.JvmTypeReference
import org.eclipse.xtext.common.types.JvmVisibility
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.osgi.service.component.annotations.Component
import org.slf4j.Logger
/**
* <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>
*/
@SuppressWarnings("restriction")
class EntityMockDSLJvmModelInferrer extends AbstractModelInferrer {
/**
* convenience API to build and initialize JVM types and their members.
*/
@Inject extension JvmTypesBuilder
@Inject extension DataDSLJvmModelInferrer
@Inject extension IQualifiedNameProvider
@Inject extension EntityUtils
@Inject ModelExtensions entityExtensions
@Inject extension CommonUtils
// @Inject extension AnnotationExtension
@Inject DataType dtType
/**
* The dispatch method {@code infer} is called for each instance of the
* given element's type that is contained in a resource.
*/
def dispatch void infer(EntityMock mock, IJvmDeclaredTypeAcceptor acceptor, boolean isPreIndexingPhase) {
// --- generate one class for each mock resource
mock.resources?.resources?.forEach [ mockResource |
try {
mock.generateMockResource(acceptor, mockResource)
} catch (Exception e) {
e.printStackTrace();
}
]
// --- generate one class for each mock object defined
mock.objects?.objects?.forEach [ mockObject |
try {
mock.generateMockObject(acceptor, mockObject)
} catch (Exception e) {
e.printStackTrace();
}
]
// --- generate a class for each mock entity
mock.entities?.entities?.forEach [ mockEntity |
try {
mock.generateMockEntity(acceptor, mockEntity)
} catch (Exception e) {
e.printStackTrace();
}
]
// --- generate the mock generator
try {
mock.generateMockDataGenerator(acceptor)
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* generate the full qualified mock package name corresponding to the imported entities
*/
def String entityMockName(EntityMock mock) {
return '''«(mock.eContainer as EntityMockPackage).fullyQualifiedName.toString».«mock.name»Mock'''
}
/**
* generate the class name for a template mock object
*/
def String entityMockName(EntityMockTemplate template, EntityMock mock) {
return (template.object as EntityMockObject).entityMockName(mock)
}
/**
* generate the class name for a mock resource class
*/
def String entityMockName(EntityMockResource resource, EntityMock mock) {
return '''«(mock.eContainer as EntityMockPackage).fullyQualifiedName.toString».«mock.name»Resource«WordUtils.capitalize(resource.name)»'''
}
/**
* generate the class name for a mock object class
*/
def String entityMockName(EntityMockObject object, EntityMock mock) {
return '''«(mock.eContainer as EntityMockPackage).fullyQualifiedName.toString».«mock.name»Object«WordUtils.capitalize(object.name)»'''
}
/**
* generate the class name for a mock entity
*/
def String entityMockName(EntityMockEntity entity, EntityMock mock) {
return '''«(mock.eContainer as EntityMockPackage).fullyQualifiedName.toString».«mock.name»Entity«WordUtils.capitalize(entity.name)»'''
}
/**
* get the entity name referenced by a mock entity
*/
def String entityName(EntityMockEntity entity) {
return entity.entityRef.entityName
}
/**
* get the entity name
*/
def String entityName(LEntity entity) {
return entity.name
}
/**
* get the entity name
*/
def String enumName(LEnum lenum) {
return lenum.name
}
/**
* get the full qualified entity name referenced by a mock entity
*/
def String entityFQN(EntityMockEntity entity) {
return EntityUtils.getFQNForLEntity(entity.entityRef)
}
/**
* get the full qualified dto name referenced by a mock entity
*/
def String entityDtoFQN(EntityMockEntity entity) {
return EntityUtils.getDtoFQNForLEntity(entity.entityRef)
}
/**
* get the full qualified dto class name referenced by a mock entity
*/
def String entityDtoFQNClass(EntityMockEntity entity) {
return entity.entityRef.entityDtoFQNClass
}
/**
* get the full qualified entity class name
*/
def String entityDtoFQNClass(LEntity entity) {
return '''«EntityUtils.getDtoFQNForLEntity(entity)».class'''
}
/**
* generate a mock object class
*/
def void generateMockObject(EntityMock model, IJvmDeclaredTypeAcceptor acceptor, EntityMockObject mockObject) {
var mockClass = model.toClass(mockObject.entityMockName(model))
acceptor.accept(mockClass) [
fileHeader = model.documentation
superTypes += _typeReferenceBuilder.typeRef(ABaseMockObject)
var JvmField field = null
field = model.toField("log", _typeReferenceBuilder.typeRef(Logger))[
setInitializer(
[append('''LoggerFactory.getLogger("mock")''')])]
field.static = true
members += field
// --- class attribute for each enumeration defined, almost identical to plain values
for (enumeration : mockObject.enumerations) {
if (enumeration.usingResource instanceof EntityMockResource) {
val resource = enumeration.usingResource as EntityMockResource
members += mockObject.toField('''«enumeration.name»_resource''',
_typeReferenceBuilder.typeRef(ABaseMockResource)) [
setInitializer(
[
append('''new «resource.entityMockName(model)»()''')
])
documentation = enumeration.documentation
visibility = JvmVisibility::PRIVATE
static = true
]
}
}
// --- for each attribute
for (attribute : mockObject.attributes) {
switch attribute {
// --- class attribute for each plain value list, almost identical to enumerations
EntityMockObjectPlainValue: {
val List<String> items = new ArrayList
for (value : attribute.values) {
items.add('''"«value»"''')
}
members += mockObject.toField('''«attribute.name»_items''',
_typeReferenceBuilder.typeRef(typeof(Object[]))) [
setInitializer(
[
append('''{«StringUtils.join(items, ",")»}''')
])
documentation = attribute.documentation
visibility = JvmVisibility::PRIVATE
static = true
]
}
EntityMockObjectResourceValue: {
}
// --- class attribute for each array value list, using enumerations as first level index
EntityMockObjectArrayValue: {
val List<String> enums = new ArrayList
val keyType = {
if (attribute.enumeration.usingResource instanceof EntityMockResource) {
"String"
} else {
'''«EntityUtils.getDtoFQNForLEnum(attribute.enumeration.usingResource)»'''.toString
}
}
for (enumItem : attribute.items) {
val List<String> items = new ArrayList
for (value : enumItem.values) {
items.add('''"«value»"''')
}
if (enumItem.datarow instanceof EntityMockResourceDataRow) {
enums.add(
'''put("«enumItem.datarow.name»", new Object[] {«StringUtils.join(items, ",")»});''')
} else {
enums.add(
'''put(«keyType».«enumItem.datarow.name», new Object[] {«StringUtils.join(items, ",")»});''')
}
}
members += mockObject.toField('''«attribute.name»_items''', _typeReferenceBuilder.typeRef(Map)) [
setInitializer(
[
append(
'''
new HashMap<«keyType», Object[]>() {{
«StringUtils.join(enums, "\r\n")»
}}''')
])
documentation = attribute.documentation
visibility = JvmVisibility::PRIVATE
static = true
]
}
EntityMockObjectEmbed: {
}
EntityMockObjectFill: {
var type = attribute.fillerType
switch type {
// --- class attribute for each filler using random text
PropertyFillerTextRandom: {
val List<String> items = new ArrayList
for (item : type.items) {
items.add('''"«item»"''')
}
members += mockObject.toField('''«attribute.name»_items''',
_typeReferenceBuilder.typeRef(typeof(Object[]))) [
setInitializer(
[
append('''{«StringUtils.join(items, ",")»}''')
])
documentation = attribute.documentation
visibility = JvmVisibility::PRIVATE
static = true
]
}
// --- class attribute for each filler using random double
PropertyFillerSignedDoubleRandom: {
val List<String> items = new ArrayList
for (item : type.items) {
items.add('''«item»''')
}
members += mockObject.toField('''«attribute.name»_items''',
_typeReferenceBuilder.typeRef(typeof(double[]))) [
setInitializer(
[
append('''{«StringUtils.join(items, ",")»}''')
])
documentation = attribute.documentation
visibility = JvmVisibility::PRIVATE
static = true
]
}
// --- class attribute for each filler using random double
PropertyFillerUnsignedDoubleRandom: {
val List<String> items = new ArrayList
for (item : type.items) {
items.add('''«item»''')
}
members += mockObject.toField('''«attribute.name»_items''',
_typeReferenceBuilder.typeRef(typeof(double[]))) [
setInitializer(
[
append('''{«StringUtils.join(items, ",")»}''')
])
documentation = attribute.documentation
visibility = JvmVisibility::PRIVATE
static = true
]
}
// --- class attribute for each filler using random integer
PropertyFillerSignedIntegerRandom: {
val List<String> items = new ArrayList
for (item : type.items) {
items.add('''«item»''')
}
members += mockObject.toField('''«attribute.name»_items''',
_typeReferenceBuilder.typeRef(typeof(int[]))) [
setInitializer(
[
append('''{«StringUtils.join(items, ",")»}''')
])
documentation = attribute.documentation
visibility = JvmVisibility::PRIVATE
static = true
]
}
// --- class attribute for each filler using random integer
PropertyFillerUnsignedIntegerRandom: {
val List<String> items = new ArrayList
for (item : type.items) {
items.add('''«item»''')
}
members += mockObject.toField('''«attribute.name»_items''',
_typeReferenceBuilder.typeRef(typeof(int[]))) [
setInitializer(
[
append('''{«StringUtils.join(items, ",")»}''')
])
documentation = attribute.documentation
visibility = JvmVisibility::PRIVATE
static = true
]
}
}
}
}
}
// --- for each calculcation
for (calculation : mockObject.calculations) {
members += mockObject.toMethod('''calculate_«calculation.name»''', calculation.oftype) [
visibility = JvmVisibility.PROTECTED
for (param : calculation.params) {
var type = param.parameterType
// var fqn = type.fullyQualifiedName
parameters += param.toParameter(param.name.name, type);
}
final = true
body = calculation.body
]
}
// --- generate a single data row
members += mockObject.toMethod('''generateDataRow''', _typeReferenceBuilder.typeRef(Void::TYPE)) [
visibility = JvmVisibility.PROTECTED
final = true
body = [
// --- each enumeration, almost the same as a plain value
for (enumeration : mockObject.enumerations) {
var doc = enumeration.documentation
if (doc instanceof String && !doc.trim.isEmpty) {
append(
'''
/** «doc» */
''')
}
if (enumeration.usingResource instanceof EntityMockResource) {
append(
'''
generateAttribute("«enumeration.name»", «enumeration.name»_resource.getDataRows().toArray());
''')
} else {
val lenum = enumeration.usingResource
append(
'''
generateAttribute("«enumeration.name»",«EntityUtils.getDtoFQNForLEnum(lenum)».values());
'''
)
}
}
// --- for each attribute
for (attribute : mockObject.attributes) {
var doc = attribute.documentation
if (doc instanceof String && !doc.trim.isEmpty) {
append(
'''
/** «doc» */
''')
}
switch attribute {
// --- each plain value, almost the same as an enumeration
EntityMockObjectPlainValue: {
append(
'''
generateAttribute("«attribute.name»", «attribute.name»_items);
''')
}
EntityMockObjectResourceValue: {
if (attribute.resourceEnum.usingResource instanceof EntityMockResource) {
append(
'''
setFixAttribute("«attribute.name»", «attribute.resourceEnum.name»_resource.getAttribute(getAttribute("«attribute.
resourceEnum.name»").toString(), "«attribute.resourceAttribute.name»"));
'''
)
} else {
append(
'''
setFixAttribute("«attribute.name»", getAttribute("«attribute.resourceEnum.name»"));
'''
)
}
}
// --- each array value, using the previously generated enumeration
EntityMockObjectArrayValue: {
append(
'''
generateAttribute("«attribute.name»", "«attribute.enumeration.name»", «attribute.name»_items);
'''
)
}
// --- generating an embedded mock object
EntityMockObjectEmbed: {
append(
'''
generateAttribute("«attribute.name»", new «attribute.object.entityMockName(model)»());
''')
}
// --- generating using filler text depending on filler type
EntityMockObjectFill: {
// TODO: re-implement filler from datamart generator
var type = attribute.fillerType
switch type {
PropertyFillerDateFuture: {
append(
'''
generateDateAttribute("«attribute.name»", 0 ,«type.dateFutureYears»);
''')
}
PropertyFillerDatePast: {
append(
'''
generateDateAttribute("«attribute.name»", -«type.datePastYears», 0);
''')
}
PropertyFillerDateRange: {
append(
'''
generateDateAttribute("«attribute.name»", «type.dateBeginYears», «type. dateEndYears»);
''')
}
PropertyFillerBoolean: {
append(
'''
generateBooleanAttribute("«attribute.name»");
''')
}
PropertyFillerSignedDoubleRange: {
var beginRange = '''«type.beginRange»'''
var endRange = '''«type.endRange»'''
if (type.beginRangeRef !== null) {
beginRange = '''get_"«type.beginRangeRef.name»"()'''
}
if (type.endRangeRef !== null) {
endRange = '''get_"«type.endRangeRef.name»"()'''
}
append(
'''
generateSignedAttribute("«attribute.name»", «type.decimals», «beginRange», «endRange», «type.
rounded»);
''')
}
PropertyFillerSignedDoubleRandom: {
append(
'''
generateAttribute("«attribute.name»", «attribute.name»_items);
''')
}
PropertyFillerUnsignedDoubleRange: {
var beginRange = '''«type.beginRange»'''
var endRange = '''«type.endRange»'''
if (type.beginRangeRef !== null) {
beginRange = '''(double)get_"«type.beginRangeRef.name»"()'''
}
if (type.endRangeRef !== null) {
endRange = '''(double)get_"«type.endRangeRef.name»"()'''
}
append(
'''
generateUnsignedAttribute("«attribute.name»", «type.decimals», «beginRange», «endRange», «type.
rounded»);
''')
}
PropertyFillerUnsignedDoubleRandom: {
append(
'''
generateAttribute("«attribute.name»", «attribute.name»_items);
''')
}
PropertyFillerSignedIntegerRange: {
var beginRange = '''«type.beginRange»'''
var endRange = '''«type.endRange»'''
if (type.beginRangeRef !== null) {
beginRange = '''(int)get_"«type.beginRangeRef.name»"()'''
}
if (type.endRangeRef !== null) {
endRange = '''(int)get_"«type.endRangeRef.name»"()'''
}
append(
'''
generateSignedAttribute("«attribute.name»", «beginRange», «endRange», «type.
rounded»);
''')
}
PropertyFillerSignedIntegerRandom: {
append(
'''
generateAttribute("«attribute.name»", «attribute.name»_items);
''')
}
PropertyFillerUnsignedIntegerRange: {
var beginRange = '''«type.beginRange»'''
var endRange = '''«type.endRange»'''
if (type.beginRangeRef !== null) {
beginRange = '''(int)get_"«type.beginRangeRef.name»"()'''
}
if (type.endRangeRef !== null) {
endRange = '''(int)get_"«type.endRangeRef.name»"()'''
}
append(
'''
generateUnsignedAttribute("«attribute.name»", «beginRange», «endRange», «type.
rounded»);
''')
}
PropertyFillerUnsignedIntegerRandom: {
append(
'''
generateAttribute("«attribute.name»", «attribute.name»_items);
''')
}
PropertyFillerTextRandom: {
append(
'''
generateAttribute("«attribute.name»", «attribute.name»_items);
''')
}
PropertyFillerTextParagraphs: {
append(
'''
generateParagraphsAttribute("«attribute.name»", «type.count»);
''')
}
PropertyFillerTextSentences: {
append(
'''
generateSentencesAttribute("«attribute.name»", «type.count»);
''')
}
PropertyFillerTextWords: {
append(
'''
generateWordsAttribute("«attribute.name»", «type.count»);
''')
}
}
}
}
}
// --- for each calculcation
for (calculation : mockObject.calculations) {
var doc = calculation.documentation
if (doc instanceof String && !doc.trim.isEmpty) {
append(
'''
/** «doc» */
''')
}
var paramString = ''''''
for (param : calculation.params) {
if (!paramString.isEmpty) {
paramString = '''«paramString»,'''
}
if (param.parameterType.type instanceof JvmEnumerationType) {
paramString = '''«paramString» «param.parameterType.identifier».valueOf(getAttribute("«param.
name.name»").toString())'''
} else {
paramString = '''«paramString»(«param.parameterType.identifier»)getAttribute("«param.
name.name»")'''
}
}
append(
'''
try {
setFixAttribute("«calculation.name»", calculate_«calculation.name»(«paramString»));
}
catch (NullPointerException npe) {}
catch (Exception e) {
log.error(e.getLocalizedMessage()+e.getCause());
}
'''
)
}
]
]
]
}
def String getName(IEntityMockObjectUsable attribute) {
switch attribute {
EntityMockObjectFunction: {
return '''«attribute.name»'''
}
EntityMockObjectEnum: {
return '''«attribute.name»'''
}
EntityMockObjectPlainValue: {
return '''«attribute.name»'''
}
EntityMockObjectArrayValue: {
return '''«attribute.name»'''
}
EntityMockObjectEmbed: {
return '''«attribute.name»'''
}
EntityMockObjectFill: {
return '''«attribute.name»'''
}
EntityMockObjectResourceValue: {
return '''«attribute.name»'''
}
}
return null
}
/**
* generate a mock entity class
*/
def void generateMockEntity(EntityMock model, IJvmDeclaredTypeAcceptor acceptor, EntityMockEntity mockEntity) {
var mockClass = model.toClass(mockEntity.entityMockName(model))
acceptor.accept(mockClass) [
fileHeader = model.documentation
superTypes += _typeReferenceBuilder.typeRef(ABaseMockEntity)
var JvmField field = null
field = model.toField("log", _typeReferenceBuilder.typeRef(Logger))[
setInitializer(
[append('''LoggerFactory.getLogger("mock")''')])]
field.static = true
members += field
if (mockEntity.byResource !== null) {
members += model.toField('''«mockEntity.byResource.name»_resource''',
_typeReferenceBuilder.typeRef(ABaseMockResource)) [
setInitializer(
[
append('''new «mockEntity.byResource.entityMockName(model)»()''')
])
documentation = mockEntity.byResource.documentation
visibility = JvmVisibility::PRIVATE
static = true
]
}
// --- the constructor
members += model.toConstructor [
parameters +=
mockEntity.toParameter("mockDataGenerator", _typeReferenceBuilder.typeRef(AEntityMockDataGenerator))
body = [
append('''super(mockDataGenerator, "«mockEntity.entityRef.persistenceUnit»");''')
]
]
// --- class variables for each template mock object needed
for (template : mockEntity.templates) {
members += model.toField('''«template.name»_template''',
_typeReferenceBuilder.typeRef(ABaseMockObject)) [
setInitializer(
[
append('''new «template.entityMockName(model)»()''')
])
documentation = template.documentation
visibility = JvmVisibility::PRIVATE
static = true
]
}
// --- check all attributes, if class variables are necessary
for (attribute : mockEntity.attributes) {
switch attribute {
EntityMockAttributeByObject: {
}
EntityMockAttributeFiller: {
var type = attribute.fillerType
switch type {
// --- for random text, remember all available options
PropertyFillerTextRandom: {
val List<String> items = new ArrayList
for (item : type.items) {
items.add('''"«item»"''')
}
members += model.toField('''«attribute.attributeRef.name»_items''',
_typeReferenceBuilder.typeRef(typeof(Object[]))) [
setInitializer(
[
append('''{«StringUtils.join(items, ",")»}''')
])
documentation = attribute.documentation
visibility = JvmVisibility::PRIVATE
static = true
]
}
// --- for random doubles, remember all available options
PropertyFillerSignedDoubleRandom: {
val List<String> items = new ArrayList
for (item : type.items) {
items.add('''«item»''')
}
members += model.toField('''«attribute.attributeRef.name»_items''',
_typeReferenceBuilder.typeRef(typeof(double[]))) [
setInitializer(
[
append('''{«StringUtils.join(items, ",")»}''')
])
documentation = attribute.documentation
visibility = JvmVisibility::PRIVATE
static = true
]
}
// --- for random doubles, remember all available options
PropertyFillerUnsignedDoubleRandom: {
val List<String> items = new ArrayList
for (item : type.items) {
items.add('''«item»''')
}
members += model.toField('''«attribute.attributeRef.name»_items''',
_typeReferenceBuilder.typeRef(typeof(double[]))) [
setInitializer(
[
append('''{«StringUtils.join(items, ",")»}''')
])
documentation = attribute.documentation
visibility = JvmVisibility::PRIVATE
static = true
]
}
// --- for random integers, remember all available options
PropertyFillerSignedIntegerRandom: {
val List<String> items = new ArrayList
for (item : type.items) {
items.add('''«item»''')
}
members += model.toField('''«attribute.attributeRef.name»_items''',
_typeReferenceBuilder.typeRef(typeof(int[]))) [
setInitializer(
[
append('''{«StringUtils.join(items, ",")»}''')
])
documentation = attribute.documentation
visibility = JvmVisibility::PRIVATE
static = true
]
}
// --- for random integers, remember all available options
PropertyFillerUnsignedIntegerRandom: {
val List<String> items = new ArrayList
for (item : type.items) {
items.add('''«item»''')
}
members += model.toField('''«attribute.attributeRef.name»_items''',
_typeReferenceBuilder.typeRef(typeof(int[]))) [
setInitializer(
[
append('''{«StringUtils.join(items, ",")»}''')
])
documentation = attribute.documentation
visibility = JvmVisibility::PRIVATE
static = true
]
}
}
}
EntityMockAttributeByReference: {
}
}
}
if (mockEntity.byResource !== null) {
members += model.toMethod('''getDataRows''', _typeReferenceBuilder.typeRef(Set)) [
visibility = JvmVisibility.PUBLIC
final = true
body = [
append('''return «mockEntity.byResource.name»_resource.getDataRows();''')
]
]
members += model.toMethod('''generateEntity''', _typeReferenceBuilder.typeRef(Object)) [
visibility = JvmVisibility.PUBLIC
parameters += model.toParameter("dataRow", _typeReferenceBuilder.typeRef(Object))
final = true
body = [
// --- generate that entity
append(
'''
reset();
«mockEntity.entityDtoFQN» internal = new «mockEntity.entityDtoFQN»();
entity = internal;
generateData();
try {
''')
// --- for each entity attribute, just copy from the internal mock data
for (attribute : mockEntity.byResourceAttributes) {
append(
'''
internal.set«WordUtils.capitalize(attribute.attributeRef.name)»(«attribute.
attributeRef.baseMockDataTypeCasting(
'''
«mockEntity.byResource.name»_resource.getAttribute(dataRow.toString(), "«attribute.resourceAttribute.name»")''')»);
''')
}
append(
'''
}
catch (Exception e) {
log.error(e.getLocalizedMessage()+e.getCause());
}
return entity;''')
]
]
}
// --- for each calculcation
for (calculation : mockEntity.calculations) {
members += model.toMethod('''calculate_«calculation.attributeRef.name»''',
calculation.attributeRef.jvmTypeRef) [
visibility = JvmVisibility.PROTECTED
for (param : calculation.params) {
parameters += param.toParameter(param.getParamName("__"), param.jvmType);
}
final = true
body = calculation.body
]
}
// --- generate a single data row in the same manner as a mock object
members += model.toMethod('''generateDataRow''', _typeReferenceBuilder.typeRef(Void::TYPE)) [
visibility = JvmVisibility.PROTECTED
final = true
body = [
// --- first generate all requested template mock objects
for (template : mockEntity.templates) {
append(
'''
generateAttribute("«template.name»", «template.name»_template);
''')
}
// --- now all attributes
for (attribute : mockEntity.attributes) {
switch attribute {
// --- referencing to template mock objects
EntityMockAttributeByObject: {
var sourceKey = attribute.reference.template.name
for (embed : attribute.reference.embedded) {
sourceKey = '''«sourceKey».«embed.name»'''
}
val refAttribute = attribute.reference.attribute
if (refAttribute instanceof EntityMockObjectEnum)
sourceKey = '''«sourceKey».«(refAttribute as EntityMockObjectEnum).name»'''
if (refAttribute instanceof EntityMockObjectPlainValue)
sourceKey = '''«sourceKey».«(refAttribute as EntityMockObjectPlainValue).name»'''
if (refAttribute instanceof EntityMockObjectResourceValue)
sourceKey = '''«sourceKey».«(refAttribute as EntityMockObjectResourceValue).name»'''
if (refAttribute instanceof EntityMockObjectArrayValue)
sourceKey = '''«sourceKey».«(refAttribute as EntityMockObjectArrayValue).name»'''
if (refAttribute instanceof EntityMockObjectEmbed)
sourceKey = '''«sourceKey».«(refAttribute as EntityMockObjectEmbed).name»'''
if (refAttribute instanceof EntityMockObjectFill)
sourceKey = '''«sourceKey».«(refAttribute as EntityMockObjectFill).name»'''
if (refAttribute instanceof EntityMockObjectFunction)
sourceKey = '''«sourceKey».«(refAttribute as EntityMockObjectFunction).name»'''
append(
'''
generateAttribute("«attribute.attributeRef.name»", "«sourceKey»");
''')
}
// --- filled by filler providers by filler type
EntityMockAttributeFiller: {
var type = attribute.fillerType
switch type {
PropertyFillerDateFuture: {
append(
'''
generateDateAttribute("«attribute.attributeRef.name»", 0 ,«type.
dateFutureYears»);
''')
}
PropertyFillerDatePast: {
append(
'''
generateDateAttribute("«attribute.attributeRef.name»", -«type.
datePastYears», 0);
''')
}
PropertyFillerDateRange: {
append(
'''
generateDateAttribute("«attribute.attributeRef.name»", «type.
dateBeginYears», «type.dateEndYears»);
''')
}
PropertyFillerBoolean: {
append(
'''
generateBooleanAttribute("«attribute.attributeRef.name»");
''')
}
PropertyFillerSignedDoubleRange: {
var beginRange = '''«type.beginRange»'''
var endRange = '''«type.endRange»'''
if (type.beginRangeRef !== null) {
beginRange = '''get_"«type.beginRangeRef.name»"()'''
}
if (type.endRangeRef !== null) {
endRange = '''get_"«type.endRangeRef.name»"()'''
}
append(
'''
generateSignedAttribute("«attribute.attributeRef.name»", «type.decimals», «beginRange», «endRange», «type.
rounded»);
''')
}
PropertyFillerSignedDoubleRandom: {
append(
'''
generateAttribute("«attribute.attributeRef.name»", «attribute.
attributeRef.name»_items);
''')
}
PropertyFillerUnsignedDoubleRange: {
var beginRange = '''«type.beginRange»'''
var endRange = '''«type.endRange»'''
if (type.beginRangeRef !== null) {
beginRange = '''(double)get_"«type.beginRangeRef.name»"()'''
}
if (type.endRangeRef !== null) {
endRange = '''(double)get_"«type.endRangeRef.name»"()'''
}
append(
'''
generateUnsignedAttribute("«attribute.attributeRef.name»", «type.decimals», «beginRange», «endRange», «type.
rounded»);
''')
}
PropertyFillerUnsignedDoubleRandom: {
append(
'''
generateAttribute("«attribute.attributeRef.name»", «attribute.
attributeRef.name»_items);
''')
}
PropertyFillerSignedIntegerRange: {
var beginRange = '''«type.beginRange»'''
var endRange = '''«type.endRange»'''
if (type.beginRangeRef !== null) {
beginRange = '''(int)get_"«type.beginRangeRef.name»"()'''
}
if (type.endRangeRef !== null) {
endRange = '''(int)get_"«type.endRangeRef.name»"()'''
}
append(
'''
generateSignedAttribute("«attribute.attributeRef.name»", «beginRange», «endRange», «type.
rounded»);
''')
}
PropertyFillerSignedIntegerRandom: {
append(
'''
generateAttribute("«attribute.attributeRef.name»", «attribute.
attributeRef.name»_items);
''')
}
PropertyFillerUnsignedIntegerRange: {
var beginRange = '''«type.beginRange»'''
var endRange = '''«type.endRange»'''
if (type.beginRangeRef !== null) {
beginRange = '''(int)get_"«type.beginRangeRef.name»"()'''
}
if (type.endRangeRef !== null) {
endRange = '''(int)get_"«type.endRangeRef.name»"()'''
}
append(
'''
generateUnsignedAttribute("«attribute.attributeRef.name»", «beginRange», «endRange», «type.
rounded»);
''')
}
PropertyFillerUnsignedIntegerRandom: {
append(
'''
generateAttribute("«attribute.attributeRef.name»", «attribute.
attributeRef.name»_items);
''')
}
PropertyFillerTextRandom: {
append(
'''
generateAttribute("«attribute.attributeRef.name»", «attribute.
attributeRef.name»_items);
''')
}
PropertyFillerTextParagraphs: {
append(
'''
generateParagraphsAttribute("«attribute.attributeRef.name»", «type.count»);
''')
}
PropertyFillerTextSentences: {
append(
'''
generateSentencesAttribute("«attribute.attributeRef.name»", «type.count»);
''')
}
PropertyFillerTextWords: {
append(
'''
generateWordsAttribute("«attribute.attributeRef.name»", «type.count»);
''')
}
}
}
// --- referencing to other mock entities
EntityMockAttributeByReference: {
if (attribute.mockedEntity === null) {
append(
'''
generateAttribute("«attribute.attributeRef.name»", «EntityUtils.
getDtoFQNForLEntity(attribute.attributeRef.type)».class, «((attribute.
optionalFor as double) / 100.0)»);
''')
} else {
append(
'''
generateAttribute("«attribute.attributeRef.name»", "«attribute.mockedEntity.
name»", «((attribute.optionalFor as double) / 100.0)»);
''')
}
}
}
}
// --- for each entity attribute, just copy from the internal mock data
for (calculation : mockEntity.calculations) {
var doc = calculation.documentation
if (doc instanceof String && !doc.trim.isEmpty) {
append(
'''
/** «doc» */
''')
}
var paramString = ''''''
for (param : calculation.params) {
if (!paramString.isEmpty) {
paramString = '''«paramString»,'''
}
if (param.attributeRef !== null) {
paramString = '''«paramString»(«param.jvmType.identifier»)getAttribute("«param.
getParamName(".")»")'''
} else if (param.isReferenceOnExistingDto) {
paramString = '''«paramString»(«param.jvmType.identifier»)((«EntityUtils.
getDtoFQNForLEntity(param.nestedAttribute.reference.type)»)getAttribute("«param.
nestedAttribute.attribute.name»", mockDataGenerator, persistenceUnit)).get«param.
nestedAttribute.reference.name.toFirstUpper»()'''
} else {
paramString = '''«paramString»(«param.jvmType.identifier»)getAttribute("«param.
getParamName(".")»", mockDataGenerator, persistenceUnit)'''
}
}
append(
'''
try {
setFixAttribute("«calculation.attributeRef.name»", calculate_«calculation.attributeRef.name»(«paramString»));
}
catch (NullPointerException npe) {}
catch (Exception e) {
log.error(e.getLocalizedMessage()+e.getCause());
}
'''
)
}
]
]
if (mockEntity.byResource === null) {
// --- generate an entity based on the values generated before via generateDataRow(), just copying values into the entity
members += model.toMethod('''generateEntity''', _typeReferenceBuilder.typeRef(Object)) [
visibility = JvmVisibility.PUBLIC
parameters += mockEntity.toParameter("dataRow", _typeReferenceBuilder.typeRef(Object))
final = true
body = [
append(
'''
reset();
''')
// --- if an iterator is set
if (mockEntity.iterator !== null) {
append(
'''
setFixAttribute("«mockEntity.iterator.name»", dataRow);
''')
}
// --- generate that entity
append(
'''
«mockEntity.entityDtoFQN» internal = new «mockEntity.entityDtoFQN»();
entity = internal;
generateData();
mockDataGenerator.addDtoMockData(internal, getMockData());
try {
''')
// --- for each entity attribute, just copy from the internal mock data
for (attribute : mockEntity.attributes) {
switch attribute {
EntityMockAttributeByObject: {
append(''' internal.set«WordUtils.capitalize(attribute.attributeRef.name)»(«attribute.
attributeRef.baseMockDataTypeCasting(
'''
getMockData().get("«attribute.attributeRef.name»")''')»);
''')
}
EntityMockAttributeFiller: {
append(''' internal.set«WordUtils.capitalize(attribute.attributeRef.name)»(«attribute.
attributeRef.baseMockDataTypeCasting(
'''getMockData().get("«attribute.attributeRef.name»")''')»);
''')
}
EntityMockAttributeByReference: {
append(''' internal.set«WordUtils.capitalize(attribute.attributeRef.name)»((«EntityUtils.
getDtoFQNForLEntity(attribute.attributeRef.type)»)getMockData().get("«attribute.
attributeRef.name»"));
''')
}
}
}
// --- for each entity attribute, just copy from the internal mock data
for (calculation : mockEntity.calculations) {
append(''' internal.set«WordUtils.capitalize(calculation.attributeRef.name)»(«calculation.
attributeRef.baseMockDataTypeCasting(
'''getMockData().get("«calculation.attributeRef.name»")''')»);
''')
}
append(
'''
}
catch (Exception e) {
log.error(e.getLocalizedMessage()+e.getCause());
}
return entity;''')
]
]
}
]
}
def boolean isReferenceOnExistingDto(EntityMockEntityFunctionParameter param) {
val entityMock = param.eContainer.eContainer as EntityMockEntity
for (attribute : entityMock.attributes) {
if (attribute instanceof EntityMockAttributeByReference) {
if (attribute.mockedEntity === null) {
if (attribute.attributeRef.type.equals(param.nestedAttribute.reference.eContainer)) {
return true
}
}
}
}
return false
}
def JvmTypeReference getJvmType(EntityMockEntityFunctionParameter param) {
if (param.attributeRef !== null) {
return param.attributeRef.jvmTypeRef
} else {
return entityExtensions.toTypeReference(param.nestedAttribute.attribute)
}
}
def String getParamName(EntityMockEntityFunctionParameter param, String separator) {
var paramName = ''''''
if (param.attributeRef !== null) {
paramName = '''«param.attributeRef.name»'''
} else {
paramName = '''«param.nestedAttribute.reference.name»«separator»'''
paramName = '''«paramName»«param.nestedAttribute.attribute.name»'''
}
return paramName
}
/**
* generate the JVM type reference needed for of the entity attribute
*/
def JvmTypeReference jvmTypeRef(LEntityAttribute attribute) {
var etype = dtType.getBasicType(attribute)
switch (etype) {
case BOOLEAN:
return _typeReferenceBuilder.typeRef(boolean)
case BYTE:
return _typeReferenceBuilder.typeRef(byte)
case DATE:
return _typeReferenceBuilder.typeRef(java.util.Date)
case FLOAT:
return _typeReferenceBuilder.typeRef(float)
case DOUBLE:
return _typeReferenceBuilder.typeRef(double)
case SHORT:
return _typeReferenceBuilder.typeRef(short)
case INTEGER:
return _typeReferenceBuilder.typeRef(int)
case LONG:
return _typeReferenceBuilder.typeRef(long)
//case TIME: return _typeReferenceBuilder.typeRef(Time)
case STRING:
return _typeReferenceBuilder.typeRef(String)
default:
return _typeReferenceBuilder.typeRef(Object)
}
}
/**
* generate the code for casting a mock data to the data type of the entity attribute
*/
def String baseMockDataTypeCasting(LEntityAttribute attribute, String getting) {
if (attribute.type instanceof LEnum) {
return '''«EntityUtils.getDtoFQNForLEnum(attribute.type as LEnum)».valueOf(«getting».toString())'''
}
if (attribute.type instanceof LBean) {
return '''(«EntityUtils.getDtoFQNForLBean(attribute.type as LBean)»)(«getting»)'''
}
var etype = dtType.getBasicType(attribute)
switch (etype) {
case BOOLEAN: return '''asBoolean(«getting»)'''
case BYTE: return '''asByte(«getting»)'''
case DATE: return '''asDate(«getting»)'''
case FLOAT: return '''asFloat(«getting»)'''
case DOUBLE: return '''asDouble(«getting»)'''
case SHORT: return '''asShort(«getting»)'''
case INTEGER: return '''asInt(«getting»)'''
case LONG: return '''asLong(«getting»)'''
case TIME: return '''asTime(«getting»)'''
default: return '''asString(«getting»)'''
}
}
val public static ENTITY_MOCK_GENERATOR = "EntityMockGenerator"
def String asString(Date date) {
if (date.yesterday) {
return '''"yesterday"'''
}
if (date.today) {
return '''"today"'''
}
if (date.tomorrow) {
return '''"tomorrow"'''
}
return '''"''' + String.format("%04d-%02d-%02d", date.year, date.month, date.day) + '''"'''
}
/**
* generate the main mock data generator for the EntityMockPackage
*/
def void generateMockDataGenerator(EntityMock mock, IJvmDeclaredTypeAcceptor acceptor) {
var mockClass = mock.toClass(mock.entityMockName)
acceptor.accept(mockClass) [
fileHeader = mock.documentation
var annotationRef = _annotationTypesBuilder.annotationRef(typeof(Component))
annotationRef.addAnnAttr(mock, "service", _typeReferenceBuilder.typeRef(IEntityMockDataGenerator) as JvmTypeReference)
annotationRef.addAnnAttr(mock, "immediate", true)
annotations += annotationRef
superTypes += _typeReferenceBuilder.typeRef(AEntityMockDataGenerator)
it.final = true
var JvmField field = null
field = mock.toField("log", _typeReferenceBuilder.typeRef(Logger))[
setInitializer(
[append('''LoggerFactory.getLogger("mock")''')])]
field.final = true
field.static = true
members += field
members += mock.toMethod('''getRunWithPriority''', _typeReferenceBuilder.typeRef(int)) [
annotations += _annotationTypesBuilder.annotationRef(Override)
body = [
var count = IEntityMockDataGenerator.DEFAULT_PRIORITY;
if (mock.runPriority > 0) {
count = mock.runPriority
}
append(
'''
return «count»;
'''
)
]
]
members += mock.toMethod('''getDataInterchangeSteps''', _typeReferenceBuilder.typeRef(int)) [
annotations += _annotationTypesBuilder.annotationRef(Override)
body = [
var count = 0;
if (mock.datainterchanges !== null) {
count = mock.datainterchanges.datainterchanges.size
}
append(
'''
return «count»;
'''
)
]
]
members += mock.toMethod('''getEntityMockSteps''', _typeReferenceBuilder.typeRef(int)) [
annotations += _annotationTypesBuilder.annotationRef(Override)
body = [
var count = 0;
if (mock.entities !== null) {
count = mock.entities.entities.size
}
append(
'''
return «count»;
'''
)
]
]
members += mock.toMethod('''runDataInterchanges''', _typeReferenceBuilder.typeRef(Void::TYPE)) [
parameters += mock.toParameter("persistenceService", _typeReferenceBuilder.typeRef(IPersistenceService))
parameters += mock.toParameter("dataInterchange", _typeReferenceBuilder.typeRef(IDataInterchange))
parameters += mock.toParameter("eventDispatcher", _typeReferenceBuilder.typeRef(IEventDispatcher))
parameters += mock.toParameter("blobService", _typeReferenceBuilder.typeRef(IBlobService))
parameters +=
mock.toParameter("entityMockDbFiller", _typeReferenceBuilder.typeRef(IEntityMockDataDbFiller))
body = [
if (mock.datainterchanges !== null) {
for (runDatainterchange : mock.datainterchanges.datainterchanges) {
append(
'''
try {
entityMockDbFiller.notifyInitializationStep("datainterchange «runDatainterchange.datainterchangeRef.name»", 1, 0.3);
«runDatainterchange.datainterchangeRef.getBasicRunConfiguration(true, runDatainterchange.getFileURL, "import")»
entityMockDbFiller.notifyInitializationStep("datainterchange «runDatainterchange.datainterchangeRef.name»", 0, 0.4);
«runDatainterchange.datainterchangeRef.defaultVariableName».run(entityMockDbFiller);
entityMockDbFiller.notifyInitializationStep("datainterchange «runDatainterchange.datainterchangeRef.name»", 0, 0.9);
}
catch (Exception e) {
log.error(e.getLocalizedMessage()+e.getCause());
}
''')
}
}
]
]
members += mock.toMethod('''getMockData''', _typeReferenceBuilder.typeRef(Map)) [
parameters += mock.toParameter("entityMockDbFiller", _typeReferenceBuilder.typeRef(IEntityMockDataDbFiller))
parameters += mock.toParameter("persistenceService", _typeReferenceBuilder.typeRef(IPersistenceService))
parameters += mock.toParameter("blobService", _typeReferenceBuilder.typeRef(IBlobService))
body = [
append(
'''initialize();
''')
// --- list of all mock entities mocked to far
var mockEntitiesDone = new ArrayList<EntityMockEntity>
// --- list of all mock entities that have to be mocked
var mockEntitiesToDo = new ArrayList<EntityMockEntity>
mockEntitiesToDo.addAll(mock.entities?.entities)
var breakTodo = false
// --- either all mock entities are already mocked or a break condition has been reached
while (!mockEntitiesToDo.isEmpty && !breakTodo) {
var handled = 0
var mockEntitesStepping = mockEntitiesToDo.toArray
// --- every mock entity, that has to be mocked
for (mockEntityO : mockEntitesStepping) {
var mockEntity = mockEntityO as EntityMockEntity
// --- check, if this mock entity can be mocked considering references
if (mockEntity.canBeHandled(mockEntitiesDone)) {
// --- remember, that something has been mocked in this inner loop
handled++
if (mockEntity.iterate instanceof IntegerIterate) {
var iterate = mockEntity.iterate as IntegerIterate
// --- generate the mocking part
append(
'''
entityMockDbFiller.notifyInitializationStep("generate «mockEntity.entityMockName(mock)»", 1, 0.3);
«mockEntity.entityMockName(mock)» entity«mockEntity.name» = new «mockEntity.entityMockName(mock)»(this);
Iterator<Integer> iterator«mockEntity.name» = new IntegerIterator(«iterate.from», «iterate.until», «iterate.step»);
List list«mockEntity.name» = new ArrayList<«mockEntity.entityDtoFQN»>();
entityMockDbFiller.notifyInitializationStep("generate «mockEntity.entityMockName(mock)»", 0, 0.6);
persistenceService.registerPersistenceUnit(entity«mockEntity.name».getPersistenceUnit(), «mockEntity.entityFQN».class);
while (iterator«mockEntity.name».hasNext()) {
list«mockEntity.name».add(entity«mockEntity.name».generateEntity(iterator«mockEntity.name».next()));
}
addMockObjects("«mockEntity.name»", «mockEntity.entityDtoFQNClass», "«mockEntity.entityRef.persistenceUnit»", list«mockEntity.
name»);
entityMockDbFiller.notifyInitializationStep("generate «mockEntity.entityMockName(mock)»", 0, 0.9);
''')
}
if (mockEntity.iterate instanceof DateIterate) {
var iterate = mockEntity.iterate as DateIterate
// --- generate the mocking part
append(
'''
entityMockDbFiller.notifyInitializationStep("generate «mockEntity.entityMockName(mock)»", 1, 0.3);
«mockEntity.entityMockName(mock)» entity«mockEntity.name» = new «mockEntity.entityMockName(mock)»(this);
Iterator<Date> iterator«mockEntity.name» = new DateIterator(«iterate.from.asString», «iterate.until.asString», «iterate.
stepCount», "«iterate.stepType»");
List list«mockEntity.name» = new ArrayList<«mockEntity.entityDtoFQN»>();
entityMockDbFiller.notifyInitializationStep("generate «mockEntity.entityMockName(mock)»", 0, 0.6);
persistenceService.registerPersistenceUnit(entity«mockEntity.name».getPersistenceUnit(), «mockEntity.entityFQN».class);
while (iterator«mockEntity.name».hasNext()) {
list«mockEntity.name».add(entity«mockEntity.name».generateEntity(iterator«mockEntity.name».next()));
}
addMockObjects("«mockEntity.name»", «mockEntity.entityDtoFQNClass», "«mockEntity.entityRef.persistenceUnit»", list«mockEntity.
name»);
entityMockDbFiller.notifyInitializationStep("generate «mockEntity.entityMockName(mock)»", 0, 0.9);
''')
} else if (mockEntity.byResource !== null) {
// --- generate the copy part
// --- generate the mocking part
append(
'''
entityMockDbFiller.notifyInitializationStep("generate «mockEntity.entityMockName(mock)»", 1, 0.3);
«mockEntity.entityMockName(mock)» entity«mockEntity.name» = new «mockEntity.entityMockName(mock)»(this);
List list«mockEntity.name» = new ArrayList<«mockEntity.entityDtoFQN»>();
Iterator iterator«mockEntity.name» = entity«mockEntity.name».getDataRows().iterator();
entityMockDbFiller.notifyInitializationStep("generate «mockEntity.entityMockName(mock)»", 0, 0.6);
persistenceService.registerPersistenceUnit(entity«mockEntity.name».getPersistenceUnit(), «mockEntity.entityFQN».class);
while (iterator«mockEntity.name».hasNext()) {
list«mockEntity.name».add(entity«mockEntity.name».generateEntity(iterator«mockEntity.name».next()));
}
addMockObjects("«mockEntity.name»", «mockEntity.entityDtoFQNClass», "«mockEntity.entityRef.persistenceUnit»", list«mockEntity.
name»);
entityMockDbFiller.notifyInitializationStep("generate «mockEntity.entityMockName(mock)»", 0, 0.9);
''')
// --- if blob mapping has to be generated too
if (mockEntity.createBlobMapping) {
append(
'''
entityMockDbFiller.notifyInitializationStep("generate «mockEntity.entityMockName(mock)»Blobs", 0, 0.93);
List list«mockEntity.name»Blobs = new ArrayList<org.eclipse.osbp.blob.dtos.BlobDto>();
entityMockDbFiller.notifyInitializationStep("generate «mockEntity.entityMockName(mock)»Blobs", 0, 0.96);
for (Object list«mockEntity.name»Object : list«mockEntity.name») {
if (list«mockEntity.name»Object instanceof org.eclipse.osbp.blob.dtos.BlobMappingDto) {
org.eclipse.osbp.blob.dtos.BlobMappingDto blobMappingDto = (org.eclipse.osbp.blob.dtos.BlobMappingDto)list«mockEntity.
name»Object;
try {
InputStream inputStream = new BufferedInputStream(this.getClass().getClassLoader().getResourceAsStream("/resources/entitymock/"+blobMappingDto.getFileName()));
if (inputStream != null) {
List<Object> blobs = blobService.createBlobMappingBlobs(inputStream, blobMappingDto.getMimeTypeId());
for(Object obj:blobs) {
blobMappingDto.addToBlobsRef((org.eclipse.osbp.blob.dtos.BlobDto)obj);
list«mockEntity.name»Blobs.add((org.eclipse.osbp.blob.dtos.BlobDto)obj);
}
}
}
catch (Exception e) {
log.error(e.getLocalizedMessage()+e.getCause());
}
}
}
addMockObjects("«mockEntity.name»Blobs", org.eclipse.osbp.blob.dtos.BlobDto.class, "blob", list«mockEntity.name»Blobs);
entityMockDbFiller.notifyInitializationStep("generate «mockEntity.entityMockName(mock)»Blobs", 0, 0.99);
''')
}
} else {
// --- generate the mocking part
append(
'''
entityMockDbFiller.notifyInitializationStep("generate «mockEntity.entityMockName(mock)»", 1, 0.3);
«mockEntity.entityMockName(mock)» entity«mockEntity.name» = new «mockEntity.entityMockName(mock)»(this);
Iterator<Integer> iterator«mockEntity.name» = new IntegerIterator(1, getFillerProvider().signedinteger(«mockEntity.minRows», «mockEntity.
maxRows»));
List list«mockEntity.name» = new ArrayList<«mockEntity.entityDtoFQN»>();
entityMockDbFiller.notifyInitializationStep("generate «mockEntity.entityMockName(mock)»", 0, 0.6);
persistenceService.registerPersistenceUnit(entity«mockEntity.name».getPersistenceUnit(), «mockEntity.entityFQN».class);
while (iterator«mockEntity.name».hasNext()) {
list«mockEntity.name».add(entity«mockEntity.name».generateEntity(iterator«mockEntity.name».next()));
}
addMockObjects("«mockEntity.name»", «mockEntity.entityDtoFQNClass», "«mockEntity.entityRef.persistenceUnit»", list«mockEntity.
name»);
entityMockDbFiller.notifyInitializationStep("generate «mockEntity.entityMockName(mock)»", 0, 0.9);
''')
}
// --- remember this mock entity as being mocked
mockEntitiesDone.add(mockEntity as EntityMockEntity)
// --- remove this mock entity from "to be mocked"
mockEntitiesToDo.remove(mockEntity)
}
}
// --- if nothing could be mocked in the inner loop, break the outer loop
breakTodo = (handled == 0)
}
append(
'''
return mockDataClassMap;''')
]
]
]
}
/**
* checks if the mockEntityTodo can be handled, considering all requested references to other mock entities,
* which may already been mocked
*/
def boolean canBeHandled(EntityMockEntity mockEntityTodo, ArrayList<EntityMockEntity> mockEntitiesDone) {
if (mockEntityTodo.byResource !== null) {
return true
}
for (attribute : mockEntityTodo.attributes) {
// --- check every reference to another mock entity
if (attribute instanceof EntityMockAttributeByReference) {
var referencedMockEntity = (attribute as EntityMockAttributeByReference).mockedEntity
// --- if the referenced entity should be mocked and it not has been mocked so far
if ((referencedMockEntity !== null) && !mockEntitiesDone.contains(referencedMockEntity)) {
// --- if any referenced entity has not been mocked so far, this mock entity can't be mocked at this time
return false
}
}
}
return true
}
/**
* generate a mock object class
*/
def void generateMockResource(EntityMock model, IJvmDeclaredTypeAcceptor acceptor, EntityMockResource mockResource) {
var mockClass = model.toClass(mockResource.entityMockName(model))
acceptor.accept(mockClass) [
fileHeader = model.documentation
superTypes += _typeReferenceBuilder.typeRef(ABaseMockResource)
var JvmField field = null
field = model.toField("log", _typeReferenceBuilder.typeRef(Logger))[
setInitializer(
[append('''LoggerFactory.getLogger("mock")''')])]
field.final = true
field.static = true
members += field
members += model.toConstructor [
body = [
val List<String> attributes = new ArrayList
for (attribute : mockResource.attributes) {
attributes.add('''"«attribute.name»"''')
}
append(
'''
setAttributes(«StringUtils.join(attributes, ",")»);
''')
for (datarow : mockResource.datarows) {
val List<String> values = new ArrayList
values.add('''"«datarow.name»"''')
for (value : datarow.values) {
values.add('''"«value»"''')
}
append(
'''
addDataRow(«StringUtils.join(values, ",")»);
''')
}
]
]
]
}
}