blob: 6e81e7ff737ba9b14cb091092583c84e1680232c [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 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Christophe Loetz (Loetz GmbH&Co.KG) - initial implementation
*
*
* This copyright notice shows up in the generated Java code
*
*/
package org.eclipse.osbp.xtext.datainterchange.jvmmodel
import com.vaadin.ui.Button
import com.vaadin.ui.CssLayout
import com.vaadin.ui.Label
import com.vaadin.ui.Panel
import com.vaadin.ui.VerticalLayout
import java.io.OutputStream
import java.nio.file.Path
import java.util.ArrayList
import java.util.HashMap
import java.util.List
import java.util.Locale
import java.util.Map
import java.util.concurrent.ExecutorService
import javax.annotation.PostConstruct
import javax.annotation.PreDestroy
import javax.inject.Inject
import javax.persistence.EntityManager
import javax.xml.transform.Transformer
import javax.xml.transform.TransformerFactory
import org.eclipse.core.runtime.IPath
import org.eclipse.e4.core.contexts.IEclipseContext
import org.eclipse.e4.ui.di.Focus
import org.eclipse.e4.ui.model.application.MApplication
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.LLowerBound
import org.eclipse.osbp.dsl.semantic.common.types.LReference
import org.eclipse.osbp.dsl.semantic.entity.LEntity
import org.eclipse.osbp.dsl.semantic.entity.LEntityReference
import org.eclipse.osbp.osgi.hybrid.api.AbstractHybridVaaclipseView
import org.eclipse.osbp.runtime.common.event.EventDispatcherEvent
import org.eclipse.osbp.runtime.common.event.IEventDispatcher
import org.eclipse.osbp.ui.api.customfields.IBlobService
import org.eclipse.osbp.ui.api.e4.IE4Focusable
import org.eclipse.osbp.ui.api.metadata.IDSLMetadataService
import org.eclipse.osbp.ui.api.user.IUser
import org.eclipse.osbp.xtext.datainterchange.AttributeFilter
import org.eclipse.osbp.xtext.datainterchange.DataInterchange
import org.eclipse.osbp.xtext.datainterchange.DataInterchangeBean
import org.eclipse.osbp.xtext.datainterchange.DataInterchangeBlobMapping
import org.eclipse.osbp.xtext.datainterchange.DataInterchangeFileCSV
import org.eclipse.osbp.xtext.datainterchange.DataInterchangeFilter
import org.eclipse.osbp.xtext.datainterchange.DataInterchangeGroup
import org.eclipse.osbp.xtext.datainterchange.DataInterchangeJoin
import org.eclipse.osbp.xtext.datainterchange.DataInterchangeJoinAttr
import org.eclipse.osbp.xtext.datainterchange.DataInterchangePackage
import org.eclipse.osbp.xtext.datainterchange.EntityManagerMode
import org.eclipse.osbp.xtext.datainterchange.ReferenceFilter
import org.eclipse.osbp.xtext.datainterchange.ReferenceFilterWithAttr
import org.eclipse.osbp.xtext.datainterchange.ReferenceFilterWithOutAttr
import org.eclipse.osbp.xtext.datainterchange.common.WorkerThreadRunnable
import org.eclipse.osbp.xtext.datainterchange.common.WorkerThreadRunnable.Direction
import org.eclipse.osbp.xtext.entitymock.common.IEntityImportInitializationListener
import org.eclipse.osbp.xtext.i18n.DSLOutputConfigurationProvider
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.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.framework.BundleEvent
import org.osgi.framework.BundleListener
import org.slf4j.Logger
/**
* <p>
* Data Interchange Repository Domain Specific Language
* This inferrer infers models of extension .data and generates code to be used by any data interchanging process
* to facilitate the communication with external data sources and drains.
* </p>
*
* @author Joerg Riegel
*/
class DataDSLJvmModelInferrer extends AbstractModelInferrer {
@Inject extension JvmTypesBuilder
@Inject extension IQualifiedNameProvider
@Inject extension DataDSLModelGenerator dg
@Inject extension ModelExtensions
/* ramp up NTHREADS and threads are finished start more but up to this limit */
var NTHREADS = 10;
var exportParamIdx = 0;
/**
* infer model on package base. Will be called for every defined package.
*
* @param group
* An instance of {@link DataInterchangeGroup}
* @param acceptor
* the xtext acceptor interface
* @param isPreIndexingPhase
* true if in preindexing phase
*/
def dispatch void infer(DataInterchangeGroup group, IJvmDeclaredTypeAcceptor acceptor, boolean isPreIndexingPhase) {
(group.eContainer as DataInterchangePackage).generatePckgName(acceptor)
// create a view
var cls = group.toClass(group.name + "TriggerView");
cls.simpleName = cls.simpleName.toFirstUpper
acceptor.accept(cls,
[
superTypes += _typeReferenceBuilder.typeRef(AbstractHybridVaaclipseView)
superTypes += _typeReferenceBuilder.typeRef(BundleListener)
superTypes += _typeReferenceBuilder.typeRef(IUser.UserLocaleListener)
superTypes += _typeReferenceBuilder.typeRef(IEventDispatcher.Receiver)
superTypes += _typeReferenceBuilder.typeRef(IE4Focusable)
packageName = DataDSLModelGenerator.pckgName
it.fileHeader = group.documentation
it.toFields(group)
it.toConstructor(group)
it.toOperations(group)
])
// create classes
group.datInts.forEach[dataInterchange|
var clsName2 = DataDSLModelGenerator.pckgName+"."+dataInterchange.name
acceptor.accept(dataInterchange.toClass(clsName2),
[
superTypes += _typeReferenceBuilder.typeRef(WorkerThreadRunnable)
annotations += _annotationTypesBuilder.annotationRef(SuppressWarnings, "serial")
packageName = DataDSLModelGenerator.pckgName
it.fileHeader = group.documentation
it.toConstructor(dataInterchange)
it.toFields(dataInterchange)
it.toOperations(dataInterchange)
])
]
}
/**
* generate the fields in the inferred class.
*
* @param type
* the xtext generic types list
* @param pkg
* the current package inferred {@link DataInterchangePackage}
*/
def void toFields(JvmGenericType type, DataInterchangeGroup group) {
var JvmField field = null
field = group.toField("sidebar", _typeReferenceBuilder.typeRef(VerticalLayout))
type.members += field
field = group.toField("log", _typeReferenceBuilder.typeRef(Logger)) [setInitializer([ append('''LoggerFactory.getLogger(«group.fullyQualifiedName.lastSegment.toFirstUpper»TriggerView.class)''') ])]
field.final = true
field.static = true
type.members += field
field = group.toField("menu", _typeReferenceBuilder.typeRef(CssLayout))
type.members += field
field = group.toField("menuPanel", _typeReferenceBuilder.typeRef(Panel))
type.members += field
field = group.toField("branding", _typeReferenceBuilder.typeRef(CssLayout))
type.members += field
field = group.toField("persistenceService", _typeReferenceBuilder.typeRef(IPersistenceService)) [
annotations += _annotationTypesBuilder.annotationRef(Inject)
]
type.members += field
field = group.toField("progressBars", _typeReferenceBuilder.typeRef(Map, _typeReferenceBuilder.typeRef(String), _typeReferenceBuilder.typeRef(WorkerThreadRunnable)))
type.members += field
field = group.toField("executorService", _typeReferenceBuilder.typeRef(ExecutorService))
field.static = true
type.members += field
field = group.toField("dslMetadataService", _typeReferenceBuilder.typeRef(IDSLMetadataService)) [annotations += _annotationTypesBuilder.annotationRef(Inject)]
type.members += field
field = group.toField("dataInterchange", _typeReferenceBuilder.typeRef(IDataInterchange)) [annotations += _annotationTypesBuilder.annotationRef(Inject)]
type.members += field
field = group.toField("eventDispatcher", _typeReferenceBuilder.typeRef(IEventDispatcher))[annotations += _annotationTypesBuilder.annotationRef(Inject)]
type.members += field
field = group.toField("blobService", _typeReferenceBuilder.typeRef(IBlobService))[annotations += _annotationTypesBuilder.annotationRef(Inject)]
type.members += field
field = group.toField("user", _typeReferenceBuilder.typeRef(IUser))[annotations += _annotationTypesBuilder.annotationRef(Inject)]
type.members += field
field = group.toField("logo", _typeReferenceBuilder.typeRef(Label))
type.members += field
field = group.toField("buttons",
_typeReferenceBuilder.typeRef(HashMap, _typeReferenceBuilder.typeRef(Button), _typeReferenceBuilder.typeRef(ArrayList, _typeReferenceBuilder.typeRef(String))))
type.members += field
field = group.toField("panels",
_typeReferenceBuilder.typeRef(HashMap, _typeReferenceBuilder.typeRef(Panel), _typeReferenceBuilder.typeRef(ArrayList, _typeReferenceBuilder.typeRef(String))))
type.members += field
}
/**
* <p>build the constructors to be used by an e4 application.</p>
*
*/
def void toConstructor(JvmDeclaredType type, DataInterchangeGroup group) {
type.members += group.toConstructor([
annotations += _annotationTypesBuilder.annotationRef(Inject)
parameters += group.toParameter("parent", _typeReferenceBuilder.typeRef(VerticalLayout))
parameters += group.toParameter("context", _typeReferenceBuilder.typeRef(IEclipseContext))
parameters += group.toParameter("app", _typeReferenceBuilder.typeRef(MApplication))
body = [ append('''super(parent,context,app);''')]
])
}
/**
* generate the fields in the inferred class.
*
* @param type
* the xtext generic types list
* @param pkg
* the current package inferred {@link DataInterchangePackage}
*/
def void toOperations(JvmGenericType type, DataInterchangeGroup group) {
// create view
type.members += group.toMethod("createView", _typeReferenceBuilder.typeRef(Void::TYPE), [
parameters += group.toParameter("parent", _typeReferenceBuilder.typeRef(VerticalLayout))
body = [ append('''«group.createView»''')]
])
// create components
type.members += group.toMethod("createComponents", _typeReferenceBuilder.typeRef(Void::TYPE), [
body = [ append('''''')]
])
// is duplicate
type.members += group.toMethod("isDuplicate", _typeReferenceBuilder.typeRef(boolean), [
parameters += group.toParameter("name", _typeReferenceBuilder.typeRef(String))
body = [ append('''«isDuplicate»''')]
])
// find layout
type.members += group.toMethod("findButtonLayout", _typeReferenceBuilder.typeRef(VerticalLayout), [
parameters += group.toParameter("button", _typeReferenceBuilder.typeRef(Button))
body = [ append('''«findButtonLayout»''')]
])
// remove progressbar
type.members += group.toMethod("removeProgressBar", _typeReferenceBuilder.typeRef(Void::TYPE), [
parameters += group.toParameter("workerName", _typeReferenceBuilder.typeRef(String))
body = [ append('''«removeProgressBar»''')]
])
// on bundle stopping - shutdown executorService
type.members += group.toMethod("bundleChanged", _typeReferenceBuilder.typeRef(Void::TYPE), [
annotations += _annotationTypesBuilder.annotationRef(Override)
parameters += group.toParameter("event", _typeReferenceBuilder.typeRef(BundleEvent))
body = [ append('''«bundleChanged»''')]
])
// activate
type.members += group.toMethod("activate", _typeReferenceBuilder.typeRef(Void::TYPE),
[
annotations += _annotationTypesBuilder.annotationRef(PostConstruct)
body = [append(
'''
super.initView();
user.addUserLocaleListener(this);
eventDispatcher.addEventReceiver(this);''')]
])
// deactivate
type.members += group.toMethod("deactivate", _typeReferenceBuilder.typeRef(Void::TYPE),
[
annotations += _annotationTypesBuilder.annotationRef(PreDestroy)
body = [append(
'''
user.removeUserLocaleListener(this);
eventDispatcher.removeEventReceiver(this);
super.destroyView();''')]
])
// focus
type.members += group.toMethod("setFocus", _typeReferenceBuilder.typeRef(Void::TYPE), [
annotations += _annotationTypesBuilder.annotationRef(Focus)
body = [append(
'''
Component parent = getParent();
while(!(parent instanceof Panel) && parent != null) {
parent = parent.getParent();
}
if(parent != null) {
((Panel)parent).focus();
}''')]
])
// locale notification
type.members += group.toMethod("localeChanged", _typeReferenceBuilder.typeRef(Void::TYPE),
[
visibility = JvmVisibility.PUBLIC
annotations += _annotationTypesBuilder.annotationRef(Override)
parameters += group.toParameter("locale", _typeReferenceBuilder.typeRef(Locale))
body = [append('''«group.localeChanged»''')]
])
// event notification
type.members += group.toMethod("receiveEvent", _typeReferenceBuilder.typeRef(Void::TYPE),
[
visibility = JvmVisibility.PUBLIC
annotations += _annotationTypesBuilder.annotationRef(Override)
parameters += group.toParameter("event", _typeReferenceBuilder.typeRef(EventDispatcherEvent))
body = [append('''«receiveEvent»''')]
])
}
/**
* let the app wait for finishing the workers before allowing to stop bundle.
*
* @return code fragment
*/
def String bundleChanged() {
var body = ""
body = '''
«body»
if (event.getType() == BundleEvent.STOPPING) {
log.debug("bundle is stopping");
// This will make the executorService accept no new threads
// and finish all existing threads in the queue
if (executorService != null) {
executorService.shutdown();
// Wait until all threads are finished
try {
executorService.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log.debug("all executors finished");
}
'''
return body
}
/**
* find the right button layout for a given button.
*
* @return code fragment
*/
def String findButtonLayout() {
var body = ""
body = '''
«body»
for (Panel panel : panels.keySet()) {
HorizontalLayout buttonCollector = (HorizontalLayout) panel.getContent();
int count = buttonCollector.getComponentCount();
for (int i = 0; i < count; i++) {
VerticalLayout buttonLayout = (VerticalLayout) buttonCollector.getComponent(i);
Button b = (Button) buttonLayout.getComponent(0);
if (b == button) {
return buttonLayout;
}
}
}
return null;
'''
return body
}
/**
* find out if a given thread-id is already running.
*
* @return code fragment
*/
def String isDuplicate() {
var body = ""
body = '''
«body»
boolean found = false;
for(String threadName : progressBars.keySet()) {
if (name.equals(threadName)) {
found = true;
break;
}
}
return found;
'''
return body
}
def String descriptionI18nKey(DataInterchange dataInterchange) {
if ((dataInterchange.descriptionValue === null) || dataInterchange.descriptionValue.isEmpty) {
dataInterchange.name
}
else {
dataInterchange.descriptionValue
}
}
/**
* build an e4 compatible view and create necessary components.
*
* @param pkg
* the current package inferred {@link DataInterchangePackage}
* @return code fragment
*/
def String createView(DataInterchangeGroup group) {
var body = '''
getContext().set(IE4Focusable.class, this);
buttons = new HashMap<>();
panels = new HashMap<>();
Bundle bundle = FrameworkUtil.getBundle(getClass());
if (bundle != null) {
BundleContext ctx = bundle.getBundleContext();
if (ctx != null) {
ctx.addBundleListener(this);
}
}
FrameworkUtil.getBundle(getClass()).getBundleContext().addBundleListener(this);
executorService = Executors.newFixedThreadPool(«NTHREADS»);
progressBars = new HashMap<String,WorkerThreadRunnable>();
sidebar=new VerticalLayout();
menu=new CssLayout();
branding=new CssLayout();
menuPanel = new Panel();
menuPanel.setSizeFull();
parent.setPrimaryStyleName("osbp");
parent.setId("parent");
parent.setSizeFull();
sidebar.setSpacing(true);
sidebar.setId("sidebar");
parent.addComponent(sidebar);
parent.setExpandRatio(sidebar, 1.0f);
// create sidebar
sidebar.addStyleName("osbpsidebar");
sidebar.setSizeFull();
sidebar.addComponent(branding);
// branding title
branding.addStyleName("branding");
logo = new Label();
logo.setContentMode(ContentMode.HTML);
logo.setSizeUndefined();
branding.addComponent(logo);
// add menu
menuPanel.setContent(menu);
sidebar.addComponent(menuPanel);
sidebar.setExpandRatio(menuPanel, 1.0f);
'''
body = '''
«body»
// add menu items
Button b;
VerticalLayout buttonLayout;
Panel buttonPanel;
HorizontalLayout buttonCollector;
'''
for (dataInterchange : group.datInts) {
body = '''
«body»
buttonPanel = new Panel();
buttonPanel.addStyleName("os-group-panel os-caption-large");
buttonPanel.setCaption("«dataInterchange.name»");
buttonCollector = new HorizontalLayout();
buttonCollector.setMargin(true);
buttonPanel.setContent(buttonCollector);
panels.put(buttonPanel, new ArrayList<String>(Arrays.asList(new String[] {"«dataInterchange.name»","«dataInterchange.descriptionI18nKey»"})));
b = new NativeButton();
b.setHtmlContentAllowed(true);
buttons.put(b, new ArrayList<String>(Arrays.asList(new String[] {"«DataDSLModelGenerator.CAPTION__REPFIX_I18NKEY_IMPORT»", "«dataInterchange.name»","«dataInterchange.descriptionI18nKey»"})));
b.addStyleName("icon-download os-nocaption");
b.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
log.debug("pressed «dataInterchange.name» import");
«dataInterchange.getBasicClassnameLine(false)»
«dataInterchange.getBasicRunConfigurationDefaults("import")»
«dataInterchange.defaultVariableName».setName(UUID.randomUUID().toString());
«dataInterchange.defaultVariableName».setEventDispatcher(eventDispatcher);
«dataInterchange.defaultVariableName».setUi(UI.getCurrent());
«dataInterchange.defaultVariableName».setDirection(WorkerThreadRunnable.Direction.IMPORT);
findButtonLayout(event.getButton()).addComponent(«dataInterchange.defaultVariableName».getProgressBarArea());
progressBars.put(«dataInterchange.defaultVariableName».getName(), «dataInterchange.defaultVariableName»);
executorService.execute(«dataInterchange.defaultVariableName»);
log.debug("«dataInterchange.name» import added to executor queue");
}
});
buttonLayout = new VerticalLayout();
buttonLayout.addComponent(b);
buttonCollector.addComponent(buttonLayout);
menu.addComponent(buttonPanel);
'''
body = '''
«body»
b = new NativeButton();
b.setHtmlContentAllowed(true);
buttons.put(b, new ArrayList<String>(Arrays.asList(new String[] {"«DataDSLModelGenerator.CAPTION__REPFIX_I18NKEY_EXPORT»", "«dataInterchange.name»","«dataInterchange.descriptionI18nKey»"})));
b.addStyleName("icon-upload os-nocaption");
b.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
log.debug("pressed «dataInterchange.name» export");
«dataInterchange.getBasicClassnameLine(false)»
«dataInterchange.getBasicRunConfigurationDefaults("export")»
«dataInterchange.defaultVariableName».setName(UUID.randomUUID().toString());
«dataInterchange.defaultVariableName».setEventDispatcher(eventDispatcher);
«dataInterchange.defaultVariableName».setUi(UI.getCurrent());
«dataInterchange.defaultVariableName».setDirection(WorkerThreadRunnable.Direction.EXPORT);
findButtonLayout(event.getButton()).addComponent(«dataInterchange.defaultVariableName».getProgressBarArea());
progressBars.put(«dataInterchange.defaultVariableName».getName(), «dataInterchange.defaultVariableName»);
executorService.execute(«dataInterchange.defaultVariableName»);
log.debug("«dataInterchange.name» export added to executor queue");
}
});
buttonLayout = new VerticalLayout();
buttonLayout.addComponent(b);
buttonCollector.addComponent(buttonLayout);
menu.addComponent(buttonPanel);
'''
}
body = '''
«body»
menu.addStyleName("menu");
menu.setSizeUndefined();
'''
return body
}
def String getDefaultVariableName(DataInterchange dataInterchange) {
return dataInterchange.name.toFirstLower
}
def String getBasicClassnameLine(DataInterchange dataInterchange, boolean fqClass) {
var className = ""
if (fqClass) {
className = (dataInterchange.eContainer.eContainer as DataInterchangePackage).name + "." + dataInterchange.name
}
else {
className = dataInterchange.name
}
return
'''
«className» «dataInterchange.getDefaultVariableName» = new «className»();
'''
}
def String getBasicRunConfigurationDefaults(DataInterchange dataInterchange, String direction ) {
return
'''
«dataInterchange.getDefaultVariableName».setPersistenceService(persistenceService);
«dataInterchange.getDefaultVariableName».setDataInterchange(dataInterchange);
«dataInterchange.getDefaultVariableName».setEventDispatcher(eventDispatcher);
«dataInterchange.getDefaultVariableName».setBlobService(blobService);
«if(direction.equals(Direction.IMPORT.name)){
'''«dataInterchange.getDefaultVariableName».setDeleteFileAfterImport(«dataInterchange.isDeleteFileAfterImport»);'''
'''
}
def String getBasicRunConfiguration(DataInterchange dataInterchange, boolean fqClass, String direction, DataInterchange baseInterchange) {
var URL = dataInterchange.produceAppropiateInterchangeURL(null)
return
'''
«dataInterchange.getBasicClassnameLine(fqClass)»
«getConfigFileURL((dataInterchange.eContainer as DataInterchangeGroup).name)»
«if(direction.empty){
dataInterchange.getConfigFileURLA(false, URL, null)
}
else if(baseInterchange === null || (baseInterchange !== null && direction.equals(Direction.EXPORT.name))){
dataInterchange.getConfigFileURLA(fqClass, URL, Direction.EXPORT)
} else if(direction.equals(Direction.IMPORT.name)){
dataInterchange.getConfigFileURLA(fqClass, URL, Direction.IMPORT)
}
»
«dataInterchange.getBasicRunConfigurationDefaults(direction)»
'''
}
def String getConfigFileURL(String groupname){
return
'''
String url = ProductConfiguration.getDatainterchangeConfiguration();
if(url == null || url.isEmpty()) {
url = System.getProperty("user.home")+"/.osbee/"+"«groupname»Config.xml";
}
if(!url.endsWith(".xml") ) {
if(!(url.endsWith("/") || url.endsWith("\\")) ) {
url = url+File.separator;
}
url = url+"«groupname»Config.xml";
}
'''
}
def String getConfigFileURLA(DataInterchange dataInterchange, boolean fqClass, String fileURL, Direction direction){
var String directionName = ""
if (null === direction ) {
directionName = "\"+direction.name().toLowerCase()+\""
} else {
directionName = direction.name.toLowerCase()
}
var String setFileUrl='''setFileURL'''
if ( fqClass )
setFileUrl='''«dataInterchange.getDefaultVariableName».setFileURL'''
return
'''
File file = new File(url);
if(file.exists()) {
FileInputStream fileInput;
try {
fileInput = new FileInputStream(file);
Properties properties = new Properties();
properties.loadFromXML(fileInput);
fileInput.close();
if(properties.getProperty("«dataInterchange.name»-«directionName»") == null) {
«setFileUrl»("«fileURL»");
} else {
«setFileUrl»(properties.getProperty("«dataInterchange.name»-«directionName»"));
}
} catch (IOException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log.error("{}", sw.toString());
}
} else {
«setFileUrl»("«fileURL»");
}
'''
}
def String getConfigFileURLB(DataInterchange dataInterchange, String fileURL, Direction direction){
var String directionName = ""
if (null === direction ) {
directionName = "\"+direction.name().toLowerCase()+\""
} else {
directionName = direction.name.toLowerCase()
}
return
'''
File file = new File(url);
if(file.exists()) {
FileInputStream fileInput;
try {
fileInput = new FileInputStream(file);
Properties properties = new Properties();
properties.loadFromXML(fileInput);
fileInput.close();
if(properties.getProperty("«dataInterchange.name»-«directionName»") == null) {
«dataInterchange.getDefaultVariableName».setFileURL("«fileURL»");
} else {
«dataInterchange.getDefaultVariableName».setFileURL(properties.getProperty("«dataInterchange.name»-«directionName»"));
}
} catch (IOException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log.error("{}", sw.toString());
}
} else {
«dataInterchange.getDefaultVariableName».setFileURL("«fileURL»");
}
'''
}
/**
* <p>build the constructor for each class.</p>
*
* @param pkg
* the current datainterchange inferred {@link DataInterchange}
*/
def void toConstructor(JvmDeclaredType type, DataInterchange dataInterchange) {
type.members += dataInterchange.toConstructor([
body = [append('''
setName("«dataInterchange.name»");
''')]
])
}
/**
* <p>build the class variables.</p>
*
*/
def void toFields(JvmDeclaredType type, DataInterchange dataInterchange) {
var JvmField field = null
field = dataInterchange.toField("log", _typeReferenceBuilder.typeRef(Logger)) [setInitializer([ append('''LoggerFactory.getLogger("dataInterchange")''') ])]
field.final = true
field.static = true
type.members += field
field = dataInterchange.toField("dataInterchange", _typeReferenceBuilder.typeRef(IDataInterchange))
type.members += field
field = dataInterchange.toField("em", _typeReferenceBuilder.typeRef(EntityManager))
type.members += field
field = dataInterchange.toField("file", _typeReferenceBuilder.typeRef(OutputStream))
type.members += field
field = dataInterchange.toField("out", _typeReferenceBuilder.typeRef(OutputStream))
type.members += field
field = dataInterchange.toField("exportPath", _typeReferenceBuilder.typeRef(Path))
type.members += field
field = dataInterchange.toField("transformerFactory", _typeReferenceBuilder.typeRef(TransformerFactory)) [setInitializer([ append('''TransformerFactory.newInstance()''') ])]
type.members += field
field = dataInterchange.toField("transformer", _typeReferenceBuilder.typeRef(Transformer))
type.members += field
field = dataInterchange.toField("smooks", _typeReferenceBuilder.typeRef(Object))
type.members += field
if(dataInterchange.fileEndpoint instanceof DataInterchangeFileCSV && dataInterchange.path !== null && dataInterchange.path.size > 1){
var idx = 0
var firstEntity = dataInterchange.path.get(0)
for(bean : dataInterchange.path){
if(bean !== firstEntity){
field = dataInterchange.toField("smooks"+idx, _typeReferenceBuilder.typeRef(Object))
type.members += field
field = dataInterchange.toField("exportPath"+idx++, _typeReferenceBuilder.typeRef(Path))
type.members += field
}
}
}
}
/**
* <p>build the methods.</p>
*
*/
def void toOperations(JvmDeclaredType type, DataInterchange dataInterchange) {
type.members += dataInterchange.toGetter("dataInterchange", _typeReferenceBuilder.typeRef(IDataInterchange))
type.members += dataInterchange.toSetter("dataInterchange", _typeReferenceBuilder.typeRef(IDataInterchange))
type.members += dataInterchange.toMethod("run", _typeReferenceBuilder.typeRef(Void::TYPE), [
annotations += _annotationTypesBuilder.annotationRef(Override)
body = [ append('''run(null);''')]
])
type.members += dataInterchange.toMethod("run", _typeReferenceBuilder.typeRef(Void::TYPE), [
parameters += dataInterchange.toParameter("importListener", _typeReferenceBuilder.typeRef(IEntityImportInitializationListener))
body = [ append('''«dataInterchange.performInterchange»''')]
])
type.members += dataInterchange.toMethod("init", _typeReferenceBuilder.typeRef(boolean), [
visibility = JvmVisibility.PROTECTED
parameters += dataInterchange.toParameter("direction", _typeReferenceBuilder.typeRef(WorkerThreadRunnable.Direction))
body = [ append('''«dataInterchange.init»''')]
])
type.members += dataInterchange.toMethod("getExportPath", _typeReferenceBuilder.typeRef(Path), [
visibility = JvmVisibility.PUBLIC
body = [ append(''' return exportPath;''')]
])
}
/**
* init factory to create the core import process.
* setup listeners for UI communication.
* setup persistence layer.
*
* @param pkg
* the current datainterchange inferred {@link DataInterchange}
* @return code fragment
*/
def String init(DataInterchange dataInterchange) {
var firstBean = (dataInterchange.path.iterator.next as DataInterchangeBean)
var multicsv_smook = ''''''
var idx = 0
if(dataInterchange.fileEndpoint instanceof DataInterchangeFileCSV && dataInterchange.path !== null && dataInterchange.path.size > 1){
multicsv_smook = multicsv_smook.concat('''
if( "export".equals(direction.toString().toLowerCase() ) ) {
''')
for(bean : dataInterchange.path){
if(bean !== firstBean){
multicsv_smook = multicsv_smook.concat(
'''
smooks«idx++» = dataInterchange.open(FrameworkUtil.getBundle(getClass()),"«DSLOutputConfigurationProvider.SMOOKS_OUTPUT_DIRECTORY»/«dataInterchange.name»_«bean.entity.name»-"+direction.toString().toLowerCase()+".xml");
''')
}
}
multicsv_smook = multicsv_smook.concat('''
}
''')
}
var URL = dataInterchange.produceAppropiateInterchangeURL(null)
var body =
'''
try {
transformerFactory.setAttribute("indent-number", 4);
transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml");
// init
setProgressIndeterminated(true);
if (log.isDebugEnabled()) log.debug("initializing datainterchange factory");
// get entity manager
if (log.isDebugEnabled()) log.debug("opening entity manager to persist results");
em = getPersistenceService().getEntityManagerFactory("«firstBean.entity.persistenceUnit»").createEntityManager();
if(dataInterchange != null) {
smooks = dataInterchange.open(FrameworkUtil.getBundle(getClass()),"«DSLOutputConfigurationProvider.SMOOKS_OUTPUT_DIRECTORY»/«dataInterchange.name»-"+direction.toString().toLowerCase()+".xml");
«multicsv_smook»
dataInterchange.setEventListener(this);
dataInterchange.setEntityManager(smooks, em);
}
«IF dataInterchange.createReport»
if (log.isDebugEnabled()) log.debug("reporting is on - impacting performance");
if(dataInterchange != null) {
String location = FrameworkUtil.getBundle(this.getClass()).getLocation()+"«DSLOutputConfigurationProvider.SMOOKS_OUTPUT_DIRECTORY»/«dataInterchange.name»-"+direction.toString().toLowerCase()+"-report.html";
location = location.replace("reference:file:/", "");
dataInterchange.enableReport(smooks, location);
}
«ENDIF»
«getConfigFileURL((dataInterchange.eContainer as DataInterchangeGroup).name)»
«dataInterchange.getConfigFileURLA(false, URL, null) »
} catch (TransformerConfigurationException | SAXException | IOException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log.error("{}", sw.toString());
return false;
}
if(direction == Direction.EXPORT) {
Object[] data = createExportFileComponents("«firstBean.entity.name»", null, true);
exportPath = (Path)data[0];
file = (OutputStream)data[1];
out = (OutputStream)data[2];
}
return true;
'''
return body
}
/**
* use factory to create the core import process.
* setup listeners for UI communication.
* setup persistence layer.
*
* @param pkg
* the current datainterchange inferred {@link DataInterchange}
* @return code fragment
*/
def String performInterchange(DataInterchange dataInterchange) {
var firstEntityBean = (dataInterchange.path.iterator.next as DataInterchangeBean)
var body = '''
if(!init(getDirection())) {
return;
}
if(dataInterchange == null) {
log.error("dataInterchange is not present - download from www.osbee.org");
return;
}
try {
if (log.isDebugEnabled()) log.debug("{} - START - Task execution on [{}] ...", Thread.currentThread().getName().toUpperCase(), getFileURL().getPath().substring(1));
log.info(getDirection().name()+" - Start of «dataInterchange.name».");
if(getDirection()==WorkerThreadRunnable.Direction.IMPORT) {
'''
body = '''
«body»
if (importListener != null) {
importListener.notifyInitializationStep("datainterchange «dataInterchange.name.toFirstUpper» load.", 0.4, 0.45, 0, 0);
}
'''
for (path:dataInterchange.path) {
for (lookup:path.lookup) {
if (lookup.cached) {
body = '''
«body»
em.setProperty(PersistenceUnitProperties.CACHE_SIZE_+"«lookup.entity.fullyQualifiedName»", "«lookup.cacheSize»");
'''
}
}
}
// import beans as list if no mark latest, other wise as a single bean
body = '''
«body»
«IF dataInterchange.mode!=EntityManagerMode.PERSIST || firstEntityBean.hasBlob || firstEntityBean.isMarkLatestImport»
Object result = null;
«ENDIF»
if (log.isDebugEnabled()) log.debug("filtering starts");
InputStream contents = dataInterchange.openStream(getFileURL());
setLength(contents.available());
setAvgElementSize(«IF dataInterchange.elementSize==0»10«ELSE»«dataInterchange.elementSize»«ENDIF»);
«IF dataInterchange.mode==EntityManagerMode.PERSIST && !firstEntityBean.hasBlob && !firstEntityBean.isMarkLatestImport»
em.getTransaction().begin();
dataInterchange.importSource(smooks, contents, null«IF dataInterchange.fileEndpoint.encoding !== null», "«dataInterchange.fileEndpoint.encoding»"«ENDIF»);
em.getTransaction().commit();
«ELSE»
result = dataInterchange.importSource(smooks, contents, "«firstEntityBean.entity.name»«IF !firstEntityBean.isMarkLatestImport»List«ENDIF»"«IF dataInterchange.fileEndpoint.encoding !== null», "«dataInterchange.fileEndpoint.encoding»"«ENDIF»);
«ENDIF»
if (log.isDebugEnabled()) log.debug("filtering finished");
'''
if (!firstEntityBean.isMarkLatestImport) {
if(dataInterchange.mode!=EntityManagerMode.PERSIST || firstEntityBean.hasBlob) {
body = '''«body»«dataInterchange.persistPart1(firstEntityBean)»'''
body = '''«body»«dataInterchange.createBlob(firstEntityBean)»'''
body = '''«body»«dataInterchange.persistPart2(firstEntityBean)»'''
}
}
if (firstEntityBean.isMarkLatestImport) {
body = '''
«body»
if(result != null) {
«firstEntityBean.entity.fullyQualifiedName» «firstEntityBean.entity.name.toFirstLower» = («firstEntityBean.entity.fullyQualifiedName») result;
'''
body = '''«body»«dataInterchange.createBlob(firstEntityBean)»'''
body = '''«body»«dataInterchange.persistPart3(firstEntityBean)»'''
}
body = '''
«body»
«IF dataInterchange.hasPostFunction && dataInterchange.postFunction.afterImport»
log.info("post interchange function execution started ... >>> «dataInterchange.postFunction.doExecuteFunction.fullyQualifiedName»");
«dataInterchange.postFunction.doExecuteFunction.fullyQualifiedName»(getFilter(), Paths.get(getFileURL().getPath().substring(1)));
log.info("post interchange function execution done ... >>> «dataInterchange.postFunction.doExecuteFunction.fullyQualifiedName»");
«ENDIF»
if(isDeleteFileAfterImport()){
deleteFile(Paths.get(getFileURL().getPath().substring(1)), "DeleteFileAfterImport -"); // interchange file
}
'''
var root = dataInterchange.path.findFirst[!it.isMarkLatestImport]
if(root !== null) {
var String exportPaths = '''exportPath'''
if(dataInterchange.fileEndpoint instanceof DataInterchangeFileCSV && dataInterchange.path !== null && dataInterchange.path.size >= 2){
var idx = 0
for(b : dataInterchange.path){
if(idx + 1 < dataInterchange.path.size){
exportPaths = exportPaths.concat(''', exportPath«idx++»''')
}
}
}
body = '''
«body»
} else {
if (log.isDebugEnabled()) log.debug("prepare export");
«IF dataInterchange.hasActionFilter»«dataInterchange.determineInterchangeFilter»«ENDIF»
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
«IF dataInterchange.isJoinNeeded»
«dataInterchange.generateJoin»
«ELSE»
CriteriaQuery<Long> countQuery = criteriaBuilder.createQuery(Long.class);
Root<«root.entity.fullyQualifiedName»> fr = countQuery.from(«root.entity.fullyQualifiedName».class);
«countQuery("fr", "countQuery", dataInterchange)»
CriteriaQuery<«root.entity.fullyQualifiedName»> criteriaQuery = criteriaBuilder.createQuery(«root.entity.fullyQualifiedName».class);
Root<«root.entity.fullyQualifiedName»> beanRoot = criteriaQuery.from(«root.entity.fullyQualifiedName».class);
CriteriaQuery<«root.entity.fullyQualifiedName»> select = criteriaQuery.select(beanRoot);
«exportQuery("beanRoot", "select", dataInterchange)»
TypedQuery<«root.entity.fullyQualifiedName»> typedQuery = em.createQuery(select);
List<«root.entity.fullyQualifiedName»> allResults = typedQuery.getResultList();
Long count = em.createQuery(countQuery).getSingleResult();
«ENDIF»
if(count > 0) {
if (log.isDebugEnabled()) log.debug("evaluate root entity count");
setLength(count*«IF dataInterchange.elementSize==0»10«ELSE»«dataInterchange.elementSize»«ENDIF»);
setAvgElementSize(1);
if (log.isDebugEnabled()) log.debug("root entity count is "+count.toString());
StringWriter writer = new StringWriter();
if(dataInterchange != null) {
dataInterchange.exportSource(smooks, allResults, writer);
}
out.write(writer.toString().getBytes(«IF dataInterchange.fileEndpoint.encoding !== null»"«dataInterchange.fileEndpoint.encoding»"«ENDIF»));
String newname = exportPath.getFileName().toString();
renameFile(exportPath, newname.substring(0, newname.length()-3));
«IF firstEntityBean.markLatestExport»
if(allResults != null && !allResults.isEmpty()){
CriteriaQuery cq = criteriaBuilder.createQuery();
Root<«root.entity.fullyQualifiedName»> fr1 = cq.from(«root.entity.fullyQualifiedName».class);
List<String> ids = em.createQuery(cq.select(fr1.get("«root.entity.idAttributeName»"))«IF dataInterchange.exportFilter !== null»«buildAppropriateFilter("fr1", dataInterchange.exportFilter, null, false, false)»«ENDIF»).getResultList();
if (log.isDebugEnabled()) log.debug("mark results as latest export");
em.setProperty(QueryHints.PESSIMISTIC_LOCK, PessimisticLock.Lock);
em.getTransaction().begin();
em.createQuery("update «firstEntityBean.entity.name» set «firstEntityBean.latestExpProperty.name» = 1 where «root.entity.idAttributeName» in :ids").setParameter("ids", ids).executeUpdate();
if (log.isDebugEnabled()) log.debug("committing mark export");
em.getTransaction().commit();
}
«ENDIF»
«IF (dataInterchange.fileEndpoint instanceof DataInterchangeFileCSV && dataInterchange.path !== null && dataInterchange.path.size >= 2)»
List<«root.entity.fullyQualifiedName»> allResultIds = em.createQuery(criteriaQuery.select(beanRoot.get("«getBeanEntityIDAttribut(root.entity)»"))).getResultList();
«ENDIF»
«IF dataInterchange.fileEndpoint instanceof DataInterchangeFileCSV && dataInterchange.path !== null && dataInterchange.path.size >= 2»
«dataInterchange.csvMultiFileExport»
«ENDIF»
«IF dataInterchange.hasPostFunction && !dataInterchange.postFunction.afterImport»
log.info("post interchange function execution started ... >>> «dataInterchange.postFunction.doExecuteFunction.fullyQualifiedName»");
«dataInterchange.postFunction.doExecuteFunction.fullyQualifiedName»(getFilter(), Arrays.asList(«exportPaths»));
log.info("post interchange function execution done ... >>> «dataInterchange.postFunction.doExecuteFunction.fullyQualifiedName»");
«ENDIF»
}
else{
deleteFile(exportPath, "EXPORT - ");
log.info("created file ["+exportPath.getFileName()+"] has been deleted for having no data!");
}
log.info("export finished");
}
log.info(getDirection().name()+" of «dataInterchange.name» successfully ended!");
'''
} else {
body = '''
«body»
}'''
}
for (path:dataInterchange.path) {
var entity = path.entity
body = '''
«body»
if(getEventDispatcher() != null) {
EventDispatcherEvent «entity.name.toLowerCase»Event = new EventDispatcherEvent(null, EventDispatcherCommand.REFRESH, "«entity.fullyQualifiedName»", "«dataInterchange.fullyQualifiedName»");
getEventDispatcher().sendEvent(«entity.name.toLowerCase»Event);
}
'''
}
body = '''
«body»
} catch (RuntimeException | IOException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log.error(getDirection().name()+" Execution of «dataInterchange.name»: failed due to: {}", sw.toString());
setExecutionFailed(true);
log.info("import failed");
«IF dataInterchange.hasPostFunction && dataInterchange.postFunction.afterImport»
log.info("post interchange function execution started ... >>> «dataInterchange.postFunction.doExecuteFunction.fullyQualifiedName»");
«dataInterchange.postFunction.doExecuteFunction.fullyQualifiedName»(getFilter(), Paths.get(getFileURL().getPath().substring(1)));
log.info("post interchange function execution done ... >>> «dataInterchange.postFunction.doExecuteFunction.fullyQualifiedName»");
«ENDIF»
«IF dataInterchange.isDeleteFileAfterImport»
Path filePath = Paths.get(getFileURL().getPath().substring(1));
if(Files.exists(filePath) && getDirection()==WorkerThreadRunnable.Direction.IMPORT) {
renameFile(filePath, "FAILEDIMPORT"+ getFormatter().format(new Date(System.currentTimeMillis())) + filePath.getFileName().toString()+ ".LOCKED");
}
«ENDIF»
} finally {
if(file != null) {
try {
out.close();
file.close();
} catch (IOException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log.error("«dataInterchange.name»:{}", sw.toString());
}
}
if(dataInterchange != null) {
dataInterchange.close(smooks);
}
if (em != null) {
em.close();
}
// remove progress bar
if(getEventDispatcher() != null) {
EventDispatcherEvent evnt = new EventDispatcherEvent(null, EventDispatcherCommand.FINISHED, getName(), "DataInterchangeWorkerThread");
getEventDispatcher().sendEvent(evnt);
}
if (log.isDebugEnabled()) log.debug("datainterchange finished");
}
setProgressIndeterminated(false);
setExecutionDone(true);
if (log.isDebugEnabled()) log.debug("{} - END - Task execution on [{}].", Thread.currentThread().getName().toUpperCase(), getFileURL().getPath().substring(1));
'''
return body
}
def createBlob(DataInterchange dataInterchange, DataInterchangeBean firstEntityBean) {
var body = ""
if(firstEntityBean.hasBlob && dataInterchange.mode!=EntityManagerMode.REMOVE){
for(mapping:firstEntityBean.mappings){
if(mapping instanceof DataInterchangeBlobMapping){
var m = (mapping as DataInterchangeBlobMapping)
var blobFileName = '''«firstEntityBean.entity.name.toFirstLower».get«m.property.name.toFirstUpper»()«IF m.blobFileExtension !== null» + ".«m.blobFileExtension»"«ENDIF»'''
body = '''
try (InputStream inputStream = new BufferedInputStream(
«IF m.blobPath === null»
this.getClass().getClassLoader().getResourceAsStream("/«firstEntityBean.entity.name»/" + «blobFileName»)
«ELSE»
new FileInputStream("«m.blobPath»/" + «blobFileName»)«ENDIF»)) {
String «firstEntityBean.entity.name.toFirstLower»_«m.property.name»Id = getBlobService().createBlobMapping(
inputStream,
«firstEntityBean.entity.name.toFirstLower».get«m.property.name.toFirstUpper»(),
"«m.mimeType»"
);
«firstEntityBean.entity.name.toFirstLower».set«m.property.name.toFirstUpper»(«firstEntityBean.entity.name.toFirstLower»_«m.property.name»Id);
} catch (IOException e) {
log.error(e.getLocalizedMessage());
}
'''
}
}
}
return body
}
protected def boolean hasBlob(DataInterchangeBean path) {
for(mapping : path.mappings) {
if(mapping instanceof DataInterchangeBlobMapping) {
return true
}
}
}
def persistPart1(DataInterchange dataInterchange, DataInterchangeBean firstEntityBean)
'''
em.clear(); // detach eventually attached objects
if(result != null) {
List<«firstEntityBean.entity.fullyQualifiedName»> «firstEntityBean.entity.name.toFirstLower»List = Arrays.asList((«firstEntityBean.entity.fullyQualifiedName»[]) result);
em.getTransaction().begin();
if (log.isDebugEnabled()) log.debug("persisting results");
int total = «firstEntityBean.entity.name.toFirstLower»List.size();
int count = 0;
long lastStep = System.currentTimeMillis();
if (importListener != null) {
importListener.notifyInitializationStep("datainterchange «dataInterchange.name.toFirstUpper»", 0.4, 0.5, count, total);
}
for(«firstEntityBean.entity.fullyQualifiedName» «firstEntityBean.entity.name.toFirstLower»:«firstEntityBean.entity.name.toFirstLower»List) {
'''
def persistPart2(DataInterchange dataInterchange, DataInterchangeBean firstEntityBean)
'''
try {
«IF dataInterchange.mode==EntityManagerMode.PERSIST»em.persist(«firstEntityBean.entity.name.toFirstLower»);
«ELSEIF dataInterchange.mode==EntityManagerMode.MERGE»em.merge(«firstEntityBean.entity.name.toFirstLower»);
«ELSEIF dataInterchange.mode==EntityManagerMode.REMOVE»«firstEntityBean.entity.fullyQualifiedName» toBeRemoved = em.merge(«firstEntityBean.entity.name.toFirstLower»);
em.remove(toBeRemoved);«ENDIF»
}
catch (ConstraintViolationException cve) {
log.error("«firstEntityBean.entity.name.toFirstLower» #"+(count+1)+"/"+total+": "+cve.getLocalizedMessage());
for (ConstraintViolation<?> violation : cve.getConstraintViolations()) {
Object value = violation.getInvalidValue();
if (value == null) {
value = "<null>";
}
log.error("- property:"
+violation.getLeafBean().toString()+"."+violation.getPropertyPath().toString()
+" value:'"+value.toString()
+" violation:"+violation.getMessage());
}
}
count++;
long thisStep = System.currentTimeMillis();
if ((importListener != null) && ((count % importListener.getInitializationSubStepNotifySize() == 0) || (thisStep-lastStep > 2500))) {
lastStep = System.currentTimeMillis();
importListener.notifyInitializationStep("datainterchange «dataInterchange.name.toFirstUpper»", 0.4, 0.5, count, total);
}
}
if (importListener != null) {
importListener.notifyInitializationStep("datainterchange «dataInterchange.name.toFirstUpper»", 0.4, 0.5, count, total);
}
if (log.isDebugEnabled()) log.debug("committing results");
em.getTransaction().commit();
if (log.isDebugEnabled()) log.debug("results persisted");
}
'''
def persistPart3(DataInterchange dataInterchange, DataInterchangeBean firstEntityBean)
'''
em.getTransaction().begin();
if (log.isDebugEnabled()) log.debug("storing results");
«IF dataInterchange.mode==EntityManagerMode.PERSIST»em.persist(«firstEntityBean.entity.name.toFirstLower»);
«ELSEIF dataInterchange.mode==EntityManagerMode.MERGE»em.merge(«firstEntityBean.entity.name.toFirstLower»);
«ELSEIF dataInterchange.mode==EntityManagerMode.REMOVE»«firstEntityBean.entity.fullyQualifiedName» toBeRemoved = em.merge(«firstEntityBean.entity.name.toFirstLower»);
em.remove(toBeRemoved);«ENDIF»
if (log.isDebugEnabled()) log.debug("committing results");
em.getTransaction().commit();
if (log.isDebugEnabled()) log.debug("mark results as latest import");
em.setProperty(QueryHints.PESSIMISTIC_LOCK, PessimisticLock.Lock);
em.getTransaction().begin();
em.createQuery("update «firstEntityBean.entity.name» set «firstEntityBean.latestProperty.name» = 0").executeUpdate();
em.createQuery("update «firstEntityBean.entity.name» set «firstEntityBean.latestProperty.name» = 1 where id= :id").setParameter("id", «firstEntityBean.entity.name.toFirstLower».getId()).executeUpdate();
if (log.isDebugEnabled()) log.debug("committing mark");
em.getTransaction().commit();
if (log.isDebugEnabled()) log.debug("results persisted");
}
'''
/**
* handle the worker progress bar. provide the appropriate code.
*
* @return code fragment
*/
def String removeProgressBar() {
var body = ""
body = '''
«body»
// a worker notified this view that it is finished
if (progressBars.containsKey(workerName)) {
final WorkerThreadRunnable worker = progressBars.get(workerName);
((VerticalLayout)worker.getProgressBarArea().getParent()).removeComponent(worker.getProgressBarArea());
progressBars.remove(workerName);
}
'''
return body
}
def localeChanged(DataInterchangeGroup group)
'''
if(logo != null) {
logo.setValue(dslMetadataService.translate(locale.toLanguageTag(), "«group.name»"));
}
if(buttons != null) {
for(Button button: buttons.keySet()) {
ArrayList i18nKeys = buttons.get(button);
button.setDescription(dslMetadataService.translate(locale.toLanguageTag(),(String)i18nKeys.get(0))+" "+dslMetadataService.translate(locale.toLanguageTag(),(String)i18nKeys.get(2)));
}
for(Panel panel:panels.keySet()){
ArrayList i18nKeys = panels.get(panel);
panel.setCaption(dslMetadataService.translate(locale.toLanguageTag(),(String)i18nKeys.get(1)));
}
}'''
def String receiveEvent() {
var body = ""
body = '''
«body»
switch(event.getCommand()) {
case FINISHED:
removeProgressBar(event.getTopic());
break;
}
'''
return body
}
def String buildExportFilterWhereClause(DataInterchangeFilter filter, String rootname, boolean actionfilter, boolean log){
var body = ""
var attrFilter = ""
var refFilter = ""
if(filter !== null && filter.attrFilter !== null){
exportParamIdx = 0;
attrFilter = filter.attrFilter.buildSubCondition(rootname, actionfilter, log)
}
if(filter !== null && filter.refFilter !== null){
exportParamIdx = 0;
refFilter = filter.refFilter.buildSubCondition2(rootname, actionfilter, log)
}
if(attrFilter !== null && !attrFilter.empty && refFilter !== null && !refFilter.empty){
body = '''«IF log»«attrFilter» and «refFilter»«ELSE»criteriaBuilder.and(«attrFilter» , «refFilter»)«ENDIF»'''
}
if(attrFilter !== null && !attrFilter.empty && (refFilter === null || refFilter.empty)){
body = attrFilter
}
if(refFilter !== null && !refFilter.empty && (attrFilter === null || attrFilter.empty)){
body = refFilter
}
return body
}
def String buildSubCondition(AttributeFilter filter, String rootname, boolean actionfilter, boolean log){
// the criteria has to be built for an action filter and each parameter value has to be fetched
// from the eclipse context, hence from the parameter list !!!
var String part1 = null
if(filter !== null && filter !== null && filter.refProperty !== null && filter.operator !== null){
var type = filter.refProperty.type.toTypeReference.qualifiedName
var defaultOrModelValue = '''"«IF filter.value !== null && !filter.value.empty»«filter.getValue»«ENDIF»"'''
var actionFilterCriteriaValue = '''«IF type.equals("java.util.Date")»getFilter().get("param«exportParamIdx»").getExpression(criteriaBuilder)«ELSE»getCriteriaValue(getFilter().get("param«exportParamIdx»").getValue(), «defaultOrModelValue»)«ENDIF»'''
switch(filter.operator){
case ISNOTNULL:
part1 = '''«IF log»«filter.getRefProperty.name» ISNOTNULL"«ELSE»«rootname».get("«filter.getRefProperty.name»").isNotNull()«ENDIF»'''
case ISNULL:
part1 = '''«IF log»«filter.getRefProperty.name» ISNULL"«ELSE»«rootname».get("«filter.getRefProperty.name»").isNull()«ENDIF»'''
case EQUALS:
if(log){
part1 = '''«filter.refProperty.name»«IF actionfilter» EQUALS "+«actionFilterCriteriaValue»«ELSE» EQUALS '«filter.value»'«ENDIF»'''
if(actionfilter){exportParamIdx++}
}
else {
part1 = '''criteriaBuilder.equal(«rootname».get("«filter.getRefProperty.name»"), «IF actionfilter»«actionFilterCriteriaValue»«ELSE»«defaultOrModelValue»«ENDIF»)'''
if(actionfilter){exportParamIdx++}
}
case NOTEQUALS:
if(log){
part1 = '''«filter.getRefProperty.name»«IF actionfilter» NOTEQUALS "+«actionFilterCriteriaValue»«ELSE» NOTEQUALS '«filter.value»'«ENDIF»'''
if(actionfilter){exportParamIdx++}
}
else{
part1 = '''criteriaBuilder.notEqual(«rootname».get("«filter.getRefProperty.name»"), «actionFilterCriteriaValue»)'''
if(actionfilter){exportParamIdx++}
}
case GREATERTHAN:
if(actionfilter){
part1 = '''criteriaBuilder.greaterThan(«rootname».get("«filter.getRefProperty.name»"), «actionFilterCriteriaValue»)'''
exportParamIdx++
}
else if(log){
part1 = '''«filter.getRefProperty.name»«IF actionfilter» GREATERTHAN "+ «actionFilterCriteriaValue» «ELSE» GREATERTHAN '«filter.value»'«ENDIF»'''
exportParamIdx++
}
else if(filter.getValue !== null && !filter.getValue.empty){
part1 = '''criteriaBuilder.greaterThan(«rootname».get("«filter.getRefProperty.name»"), "«filter.getValue»")'''
}
else{ part1 = null}
case GREATERTHANOREQUALTO:
if(actionfilter){
part1 = '''criteriaBuilder.greaterThanOrEqualTo(«rootname».get("«filter.getRefProperty.name»"), «actionFilterCriteriaValue»)'''
exportParamIdx++
}
else if(log){
part1 = '''«filter.getRefProperty.name»«IF actionfilter» GREATERTHANOREQUALTO "+ «actionFilterCriteriaValue») «ELSE» GREATERTHANOREQUALTO '«filter.value»'«ENDIF»'''
exportParamIdx++
}
else if(filter.getValue !== null && !filter.getValue.empty){
part1 = '''criteriaBuilder.greaterThanOrEqualTo(«rootname».get("«filter.getRefProperty.name»"), "«filter.getValue»")'''
}
else{ part1 = null}
case LESSTHAN:
if(actionfilter){
part1 = '''criteriaBuilder.lessThan(«rootname».get("«filter.getRefProperty.name»"), «actionFilterCriteriaValue»)'''
exportParamIdx++
}
else if(log){
part1 = '''«filter.getRefProperty.name»«IF actionfilter» LESSTHAN "+ «actionFilterCriteriaValue»«ELSE» LESSTHAN '«filter.value»'«ENDIF»'''
exportParamIdx++
}
else if(filter.getValue !== null && !filter.getValue.empty){
part1 = '''criteriaBuilder.lessThan(«rootname».get("«filter.getRefProperty.name»"), "«filter.getValue»")'''
}
else{ part1 = null}
case LESSTHANOREQUALTO:
if(actionfilter){
part1 = '''criteriaBuilder.lessThanOrEqualTo(«rootname».get("«filter.getRefProperty.name»"), «actionFilterCriteriaValue»)'''
exportParamIdx++
}
else if(log){
part1 = '''«filter.getRefProperty.name»«IF actionfilter» LESSTHANOREQUALTO "+«actionFilterCriteriaValue» «ELSE» LESSTHANOREQUALTO '«filter.value»'«ENDIF»'''
exportParamIdx++
}
else if(filter.getValue !== null && !filter.getValue.empty){
part1 = '''criteriaBuilder.lessThanOrEqualTo(«rootname».get("«filter.getRefProperty.name»"), "«filter.getValue»")'''
}
else{ part1 = null}
default: { part1 = null }
}
if(part1 !== null && filter.operator2 !== null && filter.subCondition !== null && filter.subCondition.refProperty !== null ){
switch(filter.getOperator2){
case AND: return '''«IF log»«part1» +" AND"+ «filter.subCondition.buildSubCondition(rootname, actionfilter, log)»«ELSE»criteriaBuilder.and(«part1» , «filter.subCondition.buildSubCondition(rootname, actionfilter, log)»)«ENDIF»'''
case OR : return '''«IF log»«part1» +" OR"+«filter.subCondition.buildSubCondition(rootname, actionfilter, log)»«ELSE»criteriaBuilder.or(«filter.subCondition.buildSubCondition(rootname, actionfilter, log)» , «part1»)«ENDIF»'''
default: {return part1 }
}
}
}
return part1
}
def String buildSubCondition2(ReferenceFilter filter, String rootname, boolean actionfilter, boolean log){
// the criteria has to be built for an action filter and each parameter value has to be fetched
// from the eclipse context, hence from the parameter list !!!
var part1 = ""
if(filter !== null && filter !== null && filter.getRef !== null && filter.operator !== null){
switch(filter.operator){
case ISNOTNULL: part1 = filter.refIsNotNull(log, rootname)
case ISNULL: part1 = filter.refIsNull(log, rootname)
case EQUALS: part1 = filter.refEquals(log, rootname, actionfilter)
case NOTEQUALS: part1 = filter.refNotEquals(log, rootname, actionfilter)
case GREATERTHAN: part1 = filter.refGreaterThan(log, rootname, actionfilter)
case GREATERTHANOREQUALTO: part1 = filter.refGreaterThanOrEquals(log, rootname, actionfilter)
case LESSTHAN: part1 = filter.refLessThan(log, rootname, actionfilter)
case LESSTHANOREQUALTO: part1 = filter.refLessThanOrEquals(log, rootname, actionfilter)
default: { part1 = null }
}
if(part1 !== null && filter.operator2 !== null && filter.subCondition !== null && filter.subCondition.getRef !== null ){
switch(filter.getOperator2){
case AND: return '''«IF log»«part1» +" AND"+ «filter.subCondition.buildSubCondition2(rootname, actionfilter, log)»«ELSE»criteriaBuilder.and(«part1» , «filter.subCondition.buildSubCondition2(rootname, actionfilter, log)»)«ENDIF»'''
case OR : return '''«IF log»«part1» +" OR"+«filter.subCondition.buildSubCondition2(rootname, actionfilter, log)»«ELSE»criteriaBuilder.or(«filter.subCondition.buildSubCondition2(rootname, actionfilter, log)» , «part1»)«ENDIF»'''
default: {return part1 }
}
}
}
return part1
}
def String refLessThan(ReferenceFilter filter, boolean log, String rootname, boolean actionfilter){
var result = ''''''
if(filter !== null && filter.ref !== null){
var type = filter.getRef.type.toTypeReference.qualifiedName // check this here
var defaultOrModelValue = '''"«IF filter.value !== null && !filter.value.empty»«filter.getValue»«ENDIF»"'''
var actionFilterCriteriaValue = '''«IF type.equals("java.util.Date")»getFilter().get("param«exportParamIdx»").getExpression(criteriaBuilder)«ELSE»getCriteriaValue(getFilter().get("param«exportParamIdx»").getValue(), «defaultOrModelValue»)«ENDIF»'''
if(filter instanceof ReferenceFilterWithAttr){
if(filter.refProperty !== null){ //TODO getAttribute or getListAttr
result = '''criteriaBuilder.lessThan(«filter.ref.entity.name.toFirstLower»«filter.ref.type.name.toFirstUpper»Join.get(«filter.ref.type.name.toFirstLower»EType.getSingularAttribute("«filter.refProperty.name»")), «IF actionfilter»«actionFilterCriteriaValue»«ELSE»«defaultOrModelValue»«ENDIF»)'''
//TODO correct log statement result = '''«IF log»«filter.getRef.name».«filter.refProperty.name»«IF actionfilter» LESSTHAN "+getFilter().get("param«exportParamIdx»").getValue()«ELSE» LESSTHAN '«filter.value»'«ENDIF»«ENDIF»'''
}
}
else if(filter instanceof ReferenceFilterWithOutAttr){
result = '''criteriaBuilder.lessThan(«rootname».get("«filter.ref.name»")), «IF actionfilter»«actionFilterCriteriaValue»«ELSE»«defaultOrModelValue»«ENDIF»)'''
//TODO correct log statement result = '''«IF log»«filter.getRef.name»«IF actionfilter» LESSTHAN "+getFilter().get("param«exportParamIdx»").getValue()«ELSE» LESSTHAN '«filter.value»'«ENDIF»«ENDIF»'''
}
exportParamIdx++
}
return result
}
def String refLessThanOrEquals(ReferenceFilter filter, boolean log, String rootname, boolean actionfilter){
var result = ''''''
if(filter !== null && filter.ref !== null){
var type = filter.getRef.type.toTypeReference.qualifiedName // check this here
var defaultOrModelValue = '''"«IF filter.value !== null && !filter.value.empty»«filter.getValue»«ENDIF»"'''
var actionFilterCriteriaValue = '''«IF type.equals("java.util.Date")»getFilter().get("param«exportParamIdx»").getExpression(criteriaBuilder)«ELSE»getCriteriaValue(getFilter().get("param«exportParamIdx»").getValue(), «defaultOrModelValue»)«ENDIF»'''
if(filter instanceof ReferenceFilterWithAttr){
if(filter.refProperty !== null){
result = '''criteriaBuilder.lessThanOrEqualTo(«filter.ref.entity.name.toFirstLower»«filter.ref.type.name.toFirstUpper»Join.get(«filter.ref.type.name.toFirstLower»EType.getSingularAttribute("«filter.refProperty.name»")), «IF actionfilter»«actionFilterCriteriaValue»«ELSE»«defaultOrModelValue»«ENDIF»)'''
//TODO correct log statement result = '''«IF log»«filter.getRef.name».«filter.refProperty.name»«IF actionfilter» LESSTHANOREQUALTO "+getFilter().get("param«exportParamIdx»").getValue()«ELSE» LESSTHANOREQUALTO '«filter.value»'«ENDIF»«ENDIF»'''
}
}
else if(filter instanceof ReferenceFilterWithOutAttr){
result = '''criteriaBuilder.lessThanOrEqualTo(«rootname».get("«filter.ref.name»")), «IF actionfilter»«actionFilterCriteriaValue»«ELSE»«defaultOrModelValue»«ENDIF»)'''
//TODO correct log statement result = '''«IF log»«filter.getRef.name»«IF actionfilter» LESSTHANOREQUALTO "+getFilter().get("param«exportParamIdx»").getValue()«ELSE» LESSTHANOREQUALTO '«filter.value»'«ENDIF»«ENDIF»'''
}
exportParamIdx++
}
return result
}
def String refGreaterThan(ReferenceFilter filter, boolean log, String rootname, boolean actionfilter){
var result = ''''''
if(filter !== null && filter.ref !== null){
var type = filter.getRef.type.toTypeReference.qualifiedName // check this here
var defaultOrModelValue = '''"«IF filter.value !== null && !filter.value.empty»«filter.getValue»«ENDIF»"'''
var actionFilterCriteriaValue = '''«IF type.equals("java.util.Date")»getFilter().get("param«exportParamIdx»").getExpression(criteriaBuilder)«ELSE»getCriteriaValue(getFilter().get("param«exportParamIdx»").getValue(), «defaultOrModelValue»)«ENDIF»'''
if(filter instanceof ReferenceFilterWithAttr){
if(filter.refProperty !== null){
result = '''criteriaBuilder.greaterThan(«filter.ref.entity.name.toFirstLower»«filter.ref.type.name.toFirstUpper»Join.get(«filter.ref.type.name.toFirstLower»EType.getSingularAttribute("«filter.refProperty.name»")), «IF actionfilter»«actionFilterCriteriaValue»«ELSE»«defaultOrModelValue»«ENDIF»)'''
//TODO correct log statement result = '''«IF log»«filter.getRef.name».«filter.refProperty.name»«IF actionfilter» GREATERTHAN "+getFilter().get("param«exportParamIdx»").getValue()«ELSE» GREATERTHAN '«filter.value»'«ENDIF»«ENDIF»'''
}
}
else if(filter instanceof ReferenceFilterWithOutAttr){
result = '''criteriaBuilder.greaterThan(«rootname».get("«filter.ref.name»")), «IF actionfilter»«actionFilterCriteriaValue»«ELSE»«defaultOrModelValue»«ENDIF»)'''
//TODO correct log statement result = '''«IF log»«filter.getRef.name»«IF actionfilter» GREATERTHAN "+getFilter().get("param«exportParamIdx»").getValue()«ELSE» GREATERTHAN '«filter.value»'«ENDIF»«ENDIF»'''
}
exportParamIdx++
}
return result
}
def String refGreaterThanOrEquals(ReferenceFilter filter, boolean log, String rootname, boolean actionfilter){
var result = ''''''
if(filter !== null && filter.ref !== null){
var type = filter.getRef.type.toTypeReference.qualifiedName // check this here
var defaultOrModelValue = '''"«IF filter.value !== null && !filter.value.empty»«filter.getValue»«ENDIF»"'''
var actionFilterCriteriaValue = '''«IF type.equals("java.util.Date")»getFilter().get("param«exportParamIdx»").getExpression(criteriaBuilder)«ELSE»getCriteriaValue(getFilter().get("param«exportParamIdx»").getValue(), «defaultOrModelValue»)«ENDIF»'''
if(filter instanceof ReferenceFilterWithAttr){
if(filter.refProperty !== null){
result = '''criteriaBuilder.greaterThanOrEqualTo(«filter.ref.entity.name.toFirstLower»«filter.ref.type.name.toFirstUpper»Join.get(«filter.ref.type.name.toFirstLower»EType.getSingularAttribute("«filter.refProperty.name»")), «IF actionfilter»«actionFilterCriteriaValue»«ELSE»«defaultOrModelValue»«ENDIF»)'''
//TODO correct log statement result = '''«IF log»«filter.getRef.name».«filter.refProperty.name»«IF actionfilter» GREATERTHANOREQUALTO "+getFilter().get("param«exportParamIdx»").getValue()«ELSE» GREATERTHANOREQUALTO '«filter.value»'«ENDIF»«ENDIF»'''
}
}
else if(filter instanceof ReferenceFilterWithOutAttr){
result = '''criteriaBuilder.greaterThanOrEqualTo(«rootname».get("«filter.ref.name»")), «IF actionfilter»«actionFilterCriteriaValue»«ELSE»«defaultOrModelValue»«ENDIF»)'''
//TODO correct log statement result = '''«IF log»«filter.getRef.name»«IF actionfilter» GREATERTHANOREQUALTO "+getFilter().get("param«exportParamIdx»").getValue()«ELSE» GREATERTHANOREQUALTO '«filter.value»'«ENDIF»«ENDIF»'''
}
exportParamIdx++
}
return result
}
def String refEquals(ReferenceFilter filter, boolean log, String rootname, boolean actionfilter){
var result = ''''''
if(filter !== null && filter.ref !== null){
var type = filter.getRef.type.toTypeReference.qualifiedName // check this here
var defaultOrModelValue = '''"«IF filter.value !== null && !filter.value.empty»«filter.getValue»«ENDIF»"'''
var actionFilterCriteriaValue = '''«IF type.equals("java.util.Date")»getFilter().get("param«exportParamIdx»").getExpression(criteriaBuilder)«ELSE»getCriteriaValue(getFilter().get("param«exportParamIdx»").getValue(), «defaultOrModelValue»)«ENDIF»'''
if(filter instanceof ReferenceFilterWithAttr){
if(filter.refProperty !== null){
result = '''criteriaBuilder.equal(«filter.ref.entity.name.toFirstLower»«filter.ref.type.name.toFirstUpper»Join.get(«filter.ref.type.name.toFirstLower»EType.getSingularAttribute("«filter.refProperty.name»")), «IF actionfilter»«actionFilterCriteriaValue»«ELSE»«defaultOrModelValue»«ENDIF»)'''
//TODO correct log statement result = '''«IF log»«filter.getRef.name».«filter.refProperty.name»«IF actionfilter» EQUALS "+getFilter().get("param«exportParamIdx»").getValue()«ELSE» EQUALS '«filter.value»'«ENDIF»«ENDIF»'''
}
}
else if(filter instanceof ReferenceFilterWithOutAttr){
result = '''criteriaBuilder.equal(«rootname».get("«filter.ref.name»")), «IF actionfilter»«actionFilterCriteriaValue»«ELSE»«defaultOrModelValue»«ENDIF»)'''
//TODO correct log statement result = '''«IF log»«filter.getRef.name»«IF actionfilter» EQUALS "+getFilter().get("param«exportParamIdx»").getValue()«ELSE» EQUALS '«filter.value»'«ENDIF»«ENDIF»'''
}
exportParamIdx++
}
return result
}
def String refNotEquals(ReferenceFilter filter, boolean log, String rootname, boolean actionfilter){
var result = ''''''
if(filter !== null && filter.ref !== null){
var type = filter.getRef.type.toTypeReference.qualifiedName // check this here
var defaultOrModelValue = '''"«IF filter.value !== null && !filter.value.empty»«filter.getValue»«ENDIF»"'''
var actionFilterCriteriaValue = '''«IF type.equals("java.util.Date")»getFilter().get("param«exportParamIdx»").getExpression(criteriaBuilder)«ELSE»getCriteriaValue(getFilter().get("param«exportParamIdx»").getValue(), «defaultOrModelValue»)«ENDIF»'''
if(filter instanceof ReferenceFilterWithAttr){
if(filter.refProperty !== null){
result = '''criteriaBuilder.notEqual(«filter.ref.entity.name.toFirstLower»«filter.ref.type.name.toFirstUpper»Join.get(«filter.ref.type.name.toFirstLower»EType.getSingularAttribute("«filter.refProperty.name»")), «IF actionfilter»«actionFilterCriteriaValue»«ELSE»«defaultOrModelValue»«ENDIF»)'''
//TODO correct log statement result = '''«IF log»«filter.getRef.name».«filter.refProperty.name»«IF actionfilter» NOTEQUALS "+getFilter().get("param«exportParamIdx»").getValue()«ELSE» NOTEQUALS '«filter.value»'«ENDIF»«ENDIF»'''
}
}
else if(filter instanceof ReferenceFilterWithOutAttr){
result = '''criteriaBuilder.notEqual(«rootname».get("«filter.ref.name»")), «IF actionfilter»«actionFilterCriteriaValue»«ELSE»«defaultOrModelValue»«ENDIF»)'''
//TODO correct log statement result = '''«IF log»«filter.getRef.name»«IF actionfilter» NOTEQUALS "+getFilter().get("param«exportParamIdx»").getValue()«ELSE» NOTEQUALS '«filter.value»'«ENDIF»«ENDIF»'''
}
exportParamIdx++
}
return result
}
def String refIsNull(ReferenceFilter filter, boolean log, String rootname){
var result = ''''''
if(filter !== null && filter.ref !== null){
if(filter instanceof ReferenceFilterWithAttr){
if(filter.refProperty !== null){
result = '''«IF log»«filter.ref.name».«filter.refProperty.name» isNull"«ELSE»«filter.ref.entity.name.toFirstLower»«filter.ref.type.name.toFirstUpper»Join.get(«filter.ref.type.name.toFirstLower»EType.getSingularAttribute("«filter.refProperty.name»")).isNull()«ENDIF»'''
}
}
else if(filter instanceof ReferenceFilterWithOutAttr){
result = '''«IF log»«filter.ref.name» isNull"«ELSE»«rootname».get("«filter.ref.name»").isNull()«ENDIF»'''
}
}
return result
}
def String refIsNotNull(ReferenceFilter filter, boolean log, String rootname){
var result = ''''''
if(filter !== null && filter.ref !== null){
if(filter instanceof ReferenceFilterWithAttr){
if(filter.refProperty !== null){
result = '''«IF log»«filter.ref.name».«filter.refProperty.name» isNotNull"«ELSE»«filter.ref.entity.name.toFirstLower»«filter.ref.type.name.toFirstUpper»Join.get(«filter.ref.type.name.toFirstLower»EType.getSingularAttribute("«filter.refProperty.name»")).isNotNull()«ENDIF»'''
}
}
else if(filter instanceof ReferenceFilterWithOutAttr){
result = '''«IF log»«filter.ref.name» isNotNull"«ELSE»«rootname».get("«filter.ref.name»").isNotNull()«ENDIF»'''
}
}
return result
}
/**
* build a graph for all entities in path
*/
def buildJoins(DataInterchange interchange) {
val joinGraph = new JoinGraph<LEntity>
// add all entities as nodes that are not indicators for last imported
interchange.path.filter[!it.isMarkLatestImport].forEach[joinGraph.addNode(it.entity)]
// add all possible oneToMany relations between the given entities
interchange.path.filter[!it.isMarkLatestImport].forEach[
val source = it.entity
// do not test relations with itself
interchange.path.filter[!it.entity.equals(source)].forEach[
val dest = it.entity
// get only references of type oneToMany where source and destination match
source.features.filter[
ref|ref instanceof LReference && ref.toMany && ref.type instanceof LEntity && ref.type.toName.equals(dest.toName)
].forEach[ref|
// add the join with name that was found
joinGraph.addJoin(source, dest, ref.name)
]
]
]
// calculate all possible paths of the given path
var joinManager = new ManageJoins<LEntity>(joinGraph);
var joins = joinManager.getAllJoins(interchange.path.findFirst[!it.isMarkLatestImport].entity)
// create join commands for criterabuilder if path not empty
val output = new StringBuilder
joins.filter[!it.empty].forEach[path|
output.append("from")
path.forEach[join|
output.append('''.fetch("«join»", JoinType.LEFT)''')
]
output.append(";\n")
]
return output.toString
}
/**
* Gives the file path of a data interchange unit without its file name.
*/
def String getDataInterchangeDirectoryUrlPath(DataInterchange interchange){
return dg.getDataInterchangeDirectoryUrlPath(interchange)
}
/**
* Returns the path of the given file name or directory name.
*/
def IPath findProjectFileOrFolderLocation(String projectname, String fname, boolean isFile) {
return dg.findProjectFileOrFolderLocation(projectname, fname, isFile)
}
/**
* Gives the file name of a data interchange unit.
*/
def String getDataInterchangeFileName(DataInterchange interchange){
return dg.getDataInterchangeFileName(interchange)
}
/**
* Build the apporpriate filter depending on whether both export and/or action filters
* have been defined for the criteria builer or log output.
*/
def String buildAppropriateFilter(String rootname, DataInterchangeFilter exportfilter, DataInterchangeFilter actionfilter, boolean forActionFilter, boolean forLog){
var result = ""
if(exportfilter !== null && actionfilter !== null){
var part1 = exportfilter.buildExportFilterWhereClause(rootname, false, forLog)
var part2 = actionfilter.buildExportFilterWhereClause(rootname, forActionFilter, forLog)
if(forLog){
result = '''EXPORTFILTER: «part1» , ACTIONFILTER: «part2»'''
}
else{
result = '''criteriaBuilder.and(«part1» «IF !part2.empty»,«part2»«ENDIF»)'''
}
}
else if(exportfilter !== null && actionfilter === null){
result = '''«exportfilter.buildExportFilterWhereClause(rootname, false, forLog)»'''
}
else if(exportfilter === null && actionfilter !== null){
result = '''«actionfilter.buildExportFilterWhereClause(rootname, forActionFilter, forLog)»'''
}
if(!forLog){
return '''«IF result!== null && !result.empty».where(«result»)«ENDIF»'''
}
return result
}
def boolean hasExportFilter(DataInterchange interchange){
var filter = if(interchange !== null) interchange.exportFilter else null
if(filter !== null){
if(filter.attrFilter !== null && filter.attrFilter.refProperty !== null){
return true
}
else if(filter.refFilter !== null && filter.refFilter.getRef !== null){
return true
}
}
return false
}
def boolean hasActionFilter(DataInterchange interchange){
var filter = if(interchange !== null) interchange.actionFilter else null
if(filter !== null){
if(filter.attrFilter !== null && filter.attrFilter.refProperty !== null){
return true
}
else if(filter.refFilter !== null && filter.refFilter.getRef !== null){
return true
}
}
return false
}
/**
* Returns the appropriate count query for the given datainterchange.
*/
def String countQuery(String rootname, String queryname, DataInterchange interchange){
if(interchange.hasActionFilter){
return
'''
if(isActionFilterExecutionNeeded()){
«queryname»«buildAppropriateFilter(rootname, if(interchange.hasExportFilter)interchange.exportFilter else null, interchange.actionFilter, true, false)».select(criteriaBuilder.count(«rootname»));
}else{
«queryname»«buildAppropriateFilter(rootname, if(interchange.hasExportFilter)interchange.exportFilter else null, null, false, false)».select(criteriaBuilder.count(«rootname»));
}
'''
}
return '''«queryname»«IF interchange.hasExportFilter»«buildAppropriateFilter(rootname, interchange.exportFilter, null, false, false)»«ENDIF».select(criteriaBuilder.count(«rootname»));'''
}
/**
* Returns the appropriate export query for the given datainterchange bean.
*/
def String exportQuery(String rootname, String queryname, DataInterchange interchange){
if(interchange.hasActionFilter){
var where1 = buildAppropriateFilter(rootname, if(interchange.hasExportFilter) interchange.exportFilter else null, interchange.actionFilter, true, false)
// var log1 = buildAppropriateFilter(rootname, if(interchange.hasExportFilter) interchange.exportFilter else null, interchange.actionFilter, true, true)
var where2 = buildAppropriateFilter(rootname, if(interchange.hasExportFilter) interchange.exportFilter else null, null, false, false)
// var log2 = buildAppropriateFilter(rootname, if(interchange.hasExportFilter) interchange.exportFilter else null, null, false, true)
return
'''
«IF where1 !== null && !where1.empty»
if(isActionFilterExecutionNeeded()){
«queryname»«where1»;
}«ENDIF»
«IF where2 !== null && !where2.empty»
else{
«queryname»«where2»;
}«ENDIF»
'''
}
if(interchange.hasExportFilter){
var where = buildAppropriateFilter(rootname, interchange.exportFilter, null, false, false)
// var log = buildAppropriateFilter(rootname, interchange.exportFilter, null, false, true)
if(where !== null && !where.empty){
return
'''
«queryname»«where»;
'''
}
}
return ''''''
}
def determineInterchangeFilter(DataInterchange interchange){
var result = ""
var parameterList = interchange.actionFilter.getFilterAttributesAndReferences
for(var i=0; i<parameterList.size; i++){
result= result.concat('''
filters.put("param«i»", new Parameter("«parameterList.get(i).name»", "«parameterList.get(i).value»"));
''')
}
if(!result.isEmpty){
result = '''
if(getFilter() == null){
HashMap<String, Parameter> filters = new HashMap<String, Parameter>();
«result»
setFilter(filters);
}
'''
}
return result
}
def List<WorkerThreadRunnable.Parameter> getFilterAttributesAndReferences(DataInterchangeFilter filter){
var results = <WorkerThreadRunnable.Parameter>newArrayList
if(filter !== null && filter.attrFilter !== null){
results.addAll(filter.attrFilter.attributes)
}
if(filter !== null && filter.refFilter !== null){
results.addAll(filter.refFilter.refAttributes)
}
return results
}
def List<WorkerThreadRunnable.Parameter> getAttributes(AttributeFilter filter){
var results = <WorkerThreadRunnable.Parameter>newArrayList
if(filter !== null && filter.refProperty !== null){
results.add(new WorkerThreadRunnable.Parameter(filter.refProperty.name, filter.value))
if(filter.subCondition !== null){
results.addAll(filter.subCondition.attributes)
}
}
return results
}
def List<WorkerThreadRunnable.Parameter> getRefAttributes(ReferenceFilter filter){
var results = <WorkerThreadRunnable.Parameter>newArrayList
if(filter !== null && filter.getRef !== null){
if(filter instanceof ReferenceFilterWithAttr){
if(filter.refProperty !== null) {
results.add(new WorkerThreadRunnable.Parameter(filter.getRef.name+"."+filter.refProperty.name, filter.value))
}
}
else if(filter instanceof ReferenceFilterWithOutAttr){
if(filter.getRef !== null) {
results.add(new WorkerThreadRunnable.Parameter(filter.getRef.name, filter.value))
}
}
if(filter.subCondition !== null){
results.addAll(filter.subCondition.refAttributes)
}
}
return results
}
def List<ReferenceFilter> getAllRefAttributes(ReferenceFilter filter){
var results = <ReferenceFilter>newArrayList
if(filter !== null && filter.getRef !== null){
if(filter instanceof ReferenceFilterWithAttr){
if(filter.refProperty !== null) {
results.add(filter)
}
}
else if(filter instanceof ReferenceFilterWithOutAttr){
if(filter.getRef !== null) {
results.add(filter)
}
}
if(filter.subCondition !== null){
results.addAll(filter.subCondition.allRefAttributes)
}
}
return results
}
def String csvMultiFileExport(DataInterchange dataInterchange){
if(dataInterchange !== null){
var result = ""
val firstBean = dataInterchange.path.get(0)
var idx = 0
var extract = <String>newArrayList
if(dataInterchange.path !== null && dataInterchange.path.size > 1){
for(bean : dataInterchange.path){
if(bean !== firstBean ){
extract.add( dataInterchange.csvCountQueries(firstBean, bean, idx, "####") )
idx++
}
}
result = getNextContent(extract)
}else{
result = dataInterchange.csvCountQueries(firstBean, firstBean, idx, "")
}
return result
}
return ''''''
}
def String getNextContent( List<String> allcontent){
var idx = 0
var start = allcontent.get(idx)
while( idx+1 < allcontent.size) {
start = start.replace("####", ''' «allcontent.get(idx+1)»''')
idx++
}
return start.replace("####", "");
}
def String exportQueryForBean(DataInterchangeBean bean, DataInterchange dataInterchange, int idx){
var firstBean = dataInterchange.path.get(0)
// var preBean = dataInterchange.previousBean(bean)
// var baseEntityName = '''«IF idx == 0 »allResultIds«ELSE»all«preBean.entity.name»ids«ENDIF»''';
var baseEntityName = '''allResultIds''';
var refName = getAppropriateRefName(firstBean, bean)
return
'''
CriteriaQuery<«bean.entity.fullyQualifiedName»> «bean.entity.name.toFirstLower»Query = criteriaBuilder.createQuery(«bean.entity.fullyQualifiedName».class);
Root<«bean.entity.fullyQualifiedName»> «bean.entity.name»Root = «bean.entity.name.toFirstLower»Query.from(«bean.entity.fullyQualifiedName».class);
CriteriaQuery<«bean.entity.fullyQualifiedName»> «bean.entity.name.toFirstLower»Select = «bean.entity.name.toFirstLower»Query.select(«bean.entity.name»Root);
«IF !refName.empty»«bean.entity.name.toFirstLower»Select.where(«bean.entity.name»Root.get("«refName»").in(«baseEntityName»));«ENDIF»
TypedQuery<«bean.entity.fullyQualifiedName»> «bean.entity.name.toFirstLower»TypedQuery = em.createQuery(«bean.entity.name.toFirstLower»Select);
List<«bean.entity.fullyQualifiedName»> all«bean.entity.name.toFirstUpper»Results = «bean.entity.name.toFirstLower»TypedQuery.getResultList();
««« «dataInterchange.beanEntityIdList(bean, idx)»
'''
}
def String csvCountQueries(DataInterchange dataInterchange, DataInterchangeBean firstBean, DataInterchangeBean bean, int idx, String subpart){
// var preBean = dataInterchange.previousBean(bean)
// var baseEntityName = '''«IF idx == 0 »allResultIds«ELSE»all«preBean.entity.name»ids«ENDIF»''';
var baseEntityName = '''allResultIds''';
var refName = getAppropriateRefName(firstBean, bean)
return
'''
CriteriaQuery<Long> countQuery«idx» = criteriaBuilder.createQuery(Long.class);
Root<«bean.entity.fullyQualifiedName»> from«idx» = countQuery«idx».from(«bean.entity.fullyQualifiedName».class);
Long count«idx» = em.createQuery(countQuery«idx»«IF !refName.empty».where(from«idx».get("«refName»").in(«baseEntityName»))«ENDIF».select(criteriaBuilder.count(from«idx»))).getSingleResult();
«dataInterchange.csvExports(firstBean, bean, idx, subpart)»
'''
}
/**
* Determines from which existing references and possibly defined relation
* which appropriate ref_name to provide.
*/
def String getAppropriateRefName(DataInterchangeBean previousBean, DataInterchangeBean bean){
if(bean !== null && bean.refDataSource !== null){
// var many = if(bean.refDataSource.multiplicity !== null) bean.refDataSource.multiplicity.lower.equals(LLowerBound.MANY) else false
//TODO check and test thoroughly
return bean.refDataSource.opposite.name
}
var refs = <LEntityReference>newArrayList
if(previousBean !== null && bean !== null && previousBean !== bean){
for(ref : previousBean.entity.allReferences){
if(ref.type == bean.entity){
refs.add(ref)
}
}
}
if(refs.size == 1){
return refs.get(0).opposite.name
}
else if(refs.size > 1 && bean.refDataSource === null){
return refs.get(0).opposite.name
}
return ""
}
def String csvExports(DataInterchange dataInterchange, DataInterchangeBean firstBean, DataInterchangeBean bean, int idx, String subpart){
var filename = if(bean.fileName !== null && !bean.fileName.empty) bean.fileName else dataInterchange.getDataInterchangeFileName.replace(".csv", "_"+firstBean.entity.name+"_"+bean.entity.name+".csv")
return
'''
if(count«idx» > 0) {
log.info("sub-export for entity «bean.entity.name» started");
«exportQueryForBean(bean, dataInterchange, idx)»
//create the new file for «bean.entity.name»
Object[] data«idx» = createExportFileComponents("«bean.entity.name»", "«filename»" , false);
exportPath«idx» = (Path) data«idx»[0];
OutputStream file«idx» = (OutputStream) data«idx»[1];
OutputStream out«idx» = (OutputStream) data«idx»[2];
StringWriter writer«idx» = new StringWriter();
if(dataInterchange != null) {
dataInterchange.setEntityManager(smooks«idx», em);
dataInterchange.exportSource(smooks«idx», all«bean.entity.name.toFirstUpper»Results, writer«idx»);
}
if(out«idx» != null && file«idx» != null){
out«idx».write(writer«idx».toString().getBytes());
String newname«idx» = exportPath«idx».getFileName().toString();
renameFile(exportPath«idx», newname«idx».substring(0, newname«idx».length()-3));
}
if(out«idx» != null){
out«idx».close();
}
if(file«idx» != null){
file«idx».close();
}
if(writer«idx» != null){
writer«idx».close();
}
«subpart»
}
else{
log.info("No data to export for «bean.entity.name». No sub-export for entity «bean.entity.name» executed!");
}
'''
}
def boolean hasPostFunction(DataInterchange interchange){
if(interchange !== null && interchange.postFunction !== null){
return true
}
return false
}
def String getBeanEntityIDAttribut(LEntity entity){
if(entity !== null){
for(refProperty : entity.allFeatures){
if(refProperty.UUID || refProperty.id) {
return refProperty.name
}
}
return "id" //as defaultParam TODO add logic for ID-attribute with column name not like 'id'
}
return null
}
def String beanEntityIdList(DataInterchange dataInterchange, DataInterchangeBean bean, int idx){
var preBean = dataInterchange.previousBean(bean)
var refName = getAppropriateRefName(preBean, bean)
// var baseEntityName = '''«IF idx == 0 »allResultIds«ELSE»all«preBean.entity.name»ids«ENDIF»''';
var baseEntityName = '''allResultIds''';
return '''List<«bean.entity.fullyQualifiedName»> all«bean.entity.name»ids = em.createQuery(«bean.entity.name.toFirstLower»Query.where(«bean.entity.name»Root.get("«refName»").in(«baseEntityName»)).select(«bean.entity.name»Root.get("id"))).getResultList();'''
}
def DataInterchangeBean previousBean(DataInterchange dataInterchange, DataInterchangeBean bean){
if(dataInterchange !== null && dataInterchange.path !== null && !dataInterchange.path.empty && bean !== null){
var firstBean = dataInterchange.path.get(0)
if(firstBean === bean){
// only for the special cases of markLatestImport or markLatestExport
if((firstBean.markLatestExport || firstBean.markLatestImport) && dataInterchange.path.size >=2){
return dataInterchange.path.get(1);
}
return bean
}
for(b : dataInterchange.path){
if(bean === b){
var idx = dataInterchange.path.indexOf(b)
if(idx !== -1 && idx-1 >= 0){
return dataInterchange.path.get(idx-1)
}
}
}
}
return null
}
def boolean isJoinNeeded(DataInterchange dataInterchange){
if(dataInterchange.hasExportJoin || dataInterchange.hasRefFilterWithAttribute){
return true
}
return false
}
def boolean hasRefFilterWithAttribute(DataInterchange dataInterchange){
if(dataInterchange.hasExportFilter || dataInterchange.hasActionFilter){
var filter = dataInterchange.exportFilter.refFilter
if(filter !== null){
if(filter instanceof ReferenceFilterWithAttr){
if(filter.refProperty !== null) {
return true
}
}
var sub = filter.subCondition
while(sub !== null){
if(sub instanceof ReferenceFilterWithAttr){
if(sub.refProperty !== null) {
return true
}
}
sub = sub.subCondition
}
}
}
return false
}
def String generateJoin(DataInterchange dataInterchange){
if(dataInterchange !== null && dataInterchange.path !== null && !dataInterchange.path.empty){
var baseBean = dataInterchange.previousBean(dataInterchange.path.get(0))
var baseEntity = if(baseBean !== null) baseBean.entity else dataInterchange.path.get(0).entity
var metamodel =
'''
Metamodel metamodel = em.getMetamodel();
EntityType<«baseEntity.fullyQualifiedName»> «baseEntity.name.toFirstLower»EType = metamodel.entity(«baseEntity.fullyQualifiedName».class);
'''
for(ref : baseEntity.allReferences){
var many = if(ref.multiplicity !== null) ref.multiplicity.lower.equals(LLowerBound.MANY) else false
metamodel = metamodel.concat(
'''
EntityType<«ref.type.fullyQualifiedName»> «ref.type.name.toFirstLower»EType = metamodel.entity(«ref.type.fullyQualifiedName».class);
«IF many»List«ENDIF»Join<«baseEntity.fullyQualifiedName», «ref.type.fullyQualifiedName»> «baseEntity.name.toFirstLower»«ref.type.name.toFirstUpper»Join = beanRoot.join(«baseEntity.name.toFirstLower»EType.get«IF many»List«ELSE»SingularAttribute«ENDIF»("«ref.name»", «ref.type.fullyQualifiedName».class));
''')
}
return
'''
CriteriaQuery<«baseEntity.fullyQualifiedName»> criteriaQuery = criteriaBuilder.createQuery(«baseEntity.fullyQualifiedName».class);
Root<«baseEntity.fullyQualifiedName»> beanRoot = criteriaQuery.from(«baseEntity.fullyQualifiedName».class);
«metamodel»
«exportQuery("beanRoot", "criteriaQuery", dataInterchange)»
TypedQuery<«baseEntity.fullyQualifiedName»> beanTypedQuery = em.createQuery(criteriaQuery);
List<«baseEntity.fullyQualifiedName»> allResults = beanTypedQuery.getResultList();
Long count = (allResults != null && allResults.isEmpty()) ? allResults.size() + 0L : 0L;
'''
}
return ''''''
}
def boolean hasExportJoin(DataInterchange dataInterchange){
if( dataInterchange.exportFilter !== null && dataInterchange.exportFilter.join !== null && dataInterchange.exportFilter.join.beanAttr1 !== null
&& dataInterchange.exportFilter.join.joinRef !== null && dataInterchange.exportFilter.join.beanAttr2 !== null){
return true
}
return false
}
def String joinAttributeName(DataInterchangeJoinAttr attr, boolean baseAttr) {
if(attr !== null){
var LEntity joinEntity = null
if(attr.eContainer instanceof DataInterchangeJoin){
joinEntity = (attr.eContainer as DataInterchangeJoin).joinRef.entity
}
if(baseAttr && attr.refProperty !== null){
return attr.refProperty.name.toLowerCase
}
else if(baseAttr && attr.ref !== null){
return attr.ref.name.toLowerCase
}
}
return null
}
}