diff --git a/JasperReports/META-INF/MANIFEST.MF b/JasperReports/META-INF/MANIFEST.MF index 8ff2a25b86..d53ef053d5 100644 --- a/JasperReports/META-INF/MANIFEST.MF +++ b/JasperReports/META-INF/MANIFEST.MF @@ -9,7 +9,6 @@ Export-Package: org.compiere.interfaces, org.compiere.utils Require-Bundle: org.adempiere.base;bundle-version="1.0.0", org.adempiere.JasperReportsTools;bundle-version="1.0.0", - org.adempiere.client;bundle-version="1.0.0", com.springsource.javax.ejb;bundle-version="3.0.0", org.adempiere.tools;bundle-version="1.0.0" Bundle-RequiredExecutionEnvironment: JavaSE-1.6 diff --git a/JasperReports/build.xml b/JasperReports/build.xml index 8fef7d8e67..5e2ef32015 100644 --- a/JasperReports/build.xml +++ b/JasperReports/build.xml @@ -15,7 +15,7 @@ - + diff --git a/JasperReports/src/org/compiere/report/ReportStarter.java b/JasperReports/src/org/compiere/report/ReportStarter.java index 6ef7656a10..a5eccd6fb4 100644 --- a/JasperReports/src/org/compiere/report/ReportStarter.java +++ b/JasperReports/src/org/compiere/report/ReportStarter.java @@ -102,7 +102,7 @@ public class ReportStarter implements ProcessCall, ClientProcess private static CLogger log = CLogger.getCLogger(ReportStarter.class); private static File REPORT_HOME = null; - private static JRViewerProvider viewerProvider = new SwingJRViewerProvider(); + private static JRViewerProvider viewerProvider = null; private static JasperPrint jasperPrint; static { @@ -492,7 +492,7 @@ public class ReportStarter implements ProcessCall, ClientProcess if (!processInfo.isBatch()) { // Get printer job - PrinterJob printerJob = org.compiere.print.CPrinter.getPrinterJob(printerName); + PrinterJob printerJob = PrintUtil.getPrinterJob(printerName); // Set print request attributes // Paper Attributes: diff --git a/JasperReportsClient/.classpath b/JasperReportsClient/.classpath new file mode 100644 index 0000000000..ad32c83a78 --- /dev/null +++ b/JasperReportsClient/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/JasperReportsClient/.project b/JasperReportsClient/.project new file mode 100644 index 0000000000..3f933fbaf4 --- /dev/null +++ b/JasperReportsClient/.project @@ -0,0 +1,28 @@ + + + JasperReportsClient + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/JasperReportsClient/.settings/org.eclipse.jdt.core.prefs b/JasperReportsClient/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..36d6e191a4 --- /dev/null +++ b/JasperReportsClient/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Thu Aug 19 17:50:42 MYT 2010 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/JasperReportsClient/.settings/org.eclipse.pde.core.prefs b/JasperReportsClient/.settings/org.eclipse.pde.core.prefs new file mode 100644 index 0000000000..07d7fc10bd --- /dev/null +++ b/JasperReportsClient/.settings/org.eclipse.pde.core.prefs @@ -0,0 +1,4 @@ +#Thu Aug 19 17:50:42 MYT 2010 +eclipse.preferences.version=1 +pluginProject.extensions=false +resolve.requirebundle=false diff --git a/JasperReportsClient/META-INF/MANIFEST.MF b/JasperReportsClient/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..5d39231275 --- /dev/null +++ b/JasperReportsClient/META-INF/MANIFEST.MF @@ -0,0 +1,12 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: JasperReportsClient +Bundle-SymbolicName: org.adempiere.apps.JasperReportsClient +Bundle-Version: 1.0.0.qualifier +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Require-Bundle: org.adempiere.base;bundle-version="1.0.0", + org.adempiere.client;bundle-version="1.0.0", + org.adempiere.JasperReports;bundle-version="1.0.0", + org.adempiere.JasperReportsTools;bundle-version="1.0.0", + org.adempiere.tools;bundle-version="1.0.0" +Import-Package: org.osgi.framework diff --git a/JasperReportsClient/build.properties b/JasperReportsClient/build.properties new file mode 100644 index 0000000000..34d2e4d2da --- /dev/null +++ b/JasperReportsClient/build.properties @@ -0,0 +1,4 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + . diff --git a/JasperReportsClient/build.xml b/JasperReportsClient/build.xml new file mode 100644 index 0000000000..cd52deab04 --- /dev/null +++ b/JasperReportsClient/build.xml @@ -0,0 +1,36 @@ + + + + + + + + + + This buildfile is used to build the client subproject within + the Adempiere project. + + + + + + + + + + + + + + + + + + + + + diff --git a/JasperReports/src/org/compiere/report/JasperReportViewer.java b/JasperReportsClient/src/org/compiere/report/JasperReportViewer.java similarity index 100% rename from JasperReports/src/org/compiere/report/JasperReportViewer.java rename to JasperReportsClient/src/org/compiere/report/JasperReportViewer.java diff --git a/JasperReportsClient/src/org/compiere/report/JasperReportsClientActivator.java b/JasperReportsClient/src/org/compiere/report/JasperReportsClientActivator.java new file mode 100644 index 0000000000..d0a990c3f0 --- /dev/null +++ b/JasperReportsClient/src/org/compiere/report/JasperReportsClientActivator.java @@ -0,0 +1,31 @@ +/** + * + */ +package org.compiere.report; + +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; + +/** + * @author hengsin + * + */ +public class JasperReportsClientActivator implements BundleActivator { + + /** + * default constructor + */ + public JasperReportsClientActivator() { + super(); + } + + @Override + public void start(BundleContext arg0) throws Exception { + ReportStarter.setReportViewerProvider(new SwingJRViewerProvider()); + } + + @Override + public void stop(BundleContext arg0) throws Exception { + } + +} diff --git a/JasperReports/src/org/compiere/report/JasperViewer.java b/JasperReportsClient/src/org/compiere/report/JasperViewer.java similarity index 100% rename from JasperReports/src/org/compiere/report/JasperViewer.java rename to JasperReportsClient/src/org/compiere/report/JasperViewer.java diff --git a/JasperReports/src/org/compiere/report/SwingJRViewerProvider.java b/JasperReportsClient/src/org/compiere/report/SwingJRViewerProvider.java similarity index 100% rename from JasperReports/src/org/compiere/report/SwingJRViewerProvider.java rename to JasperReportsClient/src/org/compiere/report/SwingJRViewerProvider.java diff --git a/JasperReportsTools/build.xml b/JasperReportsTools/build.xml index 7e2706fa36..b08a6c21a3 100644 --- a/JasperReportsTools/build.xml +++ b/JasperReportsTools/build.xml @@ -15,7 +15,7 @@ - + diff --git a/JasperReportsWebApp/build.xml b/JasperReportsWebApp/build.xml index 94e72ce191..54a188337b 100644 --- a/JasperReportsWebApp/build.xml +++ b/JasperReportsWebApp/build.xml @@ -16,7 +16,7 @@ - + diff --git a/base/.classpath b/base/.classpath index 18e548a771..b06fc7f852 100644 --- a/base/.classpath +++ b/base/.classpath @@ -1,14 +1,10 @@ - - - - diff --git a/base/META-INF/MANIFEST.MF b/base/META-INF/MANIFEST.MF index 83572c6db9..859eeb45ad 100644 --- a/base/META-INF/MANIFEST.MF +++ b/base/META-INF/MANIFEST.MF @@ -15,7 +15,6 @@ Export-Package: com.akunagroup.uk.postcode, org.adempiere.pipo, org.adempiere.pipo.exception, org.adempiere.pipo.handler, - org.adempiere.plaf, org.adempiere.print.export, org.adempiere.process, org.adempiere.process.rpl, @@ -31,14 +30,12 @@ Export-Package: com.akunagroup.uk.postcode, org.compiere.impexp, org.compiere.interfaces, org.compiere.model, - org.compiere.plaf, org.compiere.print, org.compiere.print.layout, org.compiere.process, org.compiere.report, org.compiere.report.core, org.compiere.sla, - org.compiere.swing, org.compiere.tools, org.compiere.util, org.compiere.wf @@ -48,5 +45,6 @@ Require-Bundle: org.adempiere.tools;bundle-version="1.0.0", Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Eclipse-ExtensibleAPI: true Import-Package: net.sf.cglib.proxy, - org.eclipse.core.runtime;version="3.4.0" + org.eclipse.core.runtime;version="3.4.0", + org.osgi.framework diff --git a/base/build.xml b/base/build.xml index fdb45b3145..77645cb756 100644 --- a/base/build.xml +++ b/base/build.xml @@ -33,7 +33,7 @@ - + diff --git a/base/plugin.xml b/base/plugin.xml index 8041937132..c3fd247a4e 100644 --- a/base/plugin.xml +++ b/base/plugin.xml @@ -4,7 +4,7 @@ - - + + diff --git a/base/schema/ResourceFinder.exsd b/base/schema/ResourceFinder.exsd index a2f30d7849..65d4ff9c8a 100644 --- a/base/schema/ResourceFinder.exsd +++ b/base/schema/ResourceFinder.exsd @@ -18,7 +18,7 @@ - + @@ -47,7 +47,7 @@ - + diff --git a/base/schema/org.adempiere.base.Callout.exsd b/base/schema/org.adempiere.base.Callout.exsd index f80d1e9141..77b937be15 100644 --- a/base/schema/org.adempiere.base.Callout.exsd +++ b/base/schema/org.adempiere.base.Callout.exsd @@ -21,7 +21,7 @@ Instead, you specify Table and Column in the extension declaration. - + @@ -50,7 +50,7 @@ Instead, you specify Table and Column in the extension declaration. - + diff --git a/base/schema/org.adempiere.base.ModelValidator.exsd b/base/schema/org.adempiere.base.ModelValidator.exsd new file mode 100644 index 0000000000..b8257af113 --- /dev/null +++ b/base/schema/org.adempiere.base.ModelValidator.exsd @@ -0,0 +1,102 @@ + + + + + + + + + [Enter description of this extension point.] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + [Enter the first release in which this extension point appears.] + + + + + + + + + [Enter extension point usage example here.] + + + + + + + + + [Enter API information here.] + + + + + + + + + [Enter information about supplied implementation of this extension point.] + + + + + diff --git a/base/schema/org.adempiere.as.IApplicationServer.exsd b/base/schema/org.adempiere.base.Process.exsd similarity index 88% rename from base/schema/org.adempiere.as.IApplicationServer.exsd rename to base/schema/org.adempiere.base.Process.exsd index 3009c74a74..415b4b112b 100644 --- a/base/schema/org.adempiere.as.IApplicationServer.exsd +++ b/base/schema/org.adempiere.base.Process.exsd @@ -3,7 +3,7 @@ - + [Enter description of this extension point.] @@ -18,7 +18,7 @@ - + @@ -27,7 +27,7 @@ - + @@ -47,15 +47,15 @@ - + - + - + diff --git a/base/src/org/adempiere/base/Core.java b/base/src/org/adempiere/base/Core.java index 2b204f7d71..0d64ce8709 100644 --- a/base/src/org/adempiere/base/Core.java +++ b/base/src/org/adempiere/base/Core.java @@ -3,6 +3,9 @@ package org.adempiere.base; import java.net.URL; import java.util.List; +import org.compiere.model.ModelValidator; +import org.compiere.process.ProcessCall; + /** * This is a facade class for the Service Locator. * It provides simple access to all core services. @@ -11,7 +14,7 @@ import java.util.List; */ public class Core { - public static final String OSGI_PREFIX = "osgi://"; + public static final String OSGI_PREFIX = "osgi:"; public static IResourceFinder getResourceFinder() { return new IResourceFinder() { @@ -40,5 +43,22 @@ public class Core { return className.startsWith(OSGI_PREFIX); } + public static ProcessCall getProcess(String className) { + if (isExtension(className)) + className = className.substring(Core.OSGI_PREFIX.length()); + + ServiceQuery query = new ServiceQuery(); + query.put("id", className); + return Service.locate(ProcessCall.class, "org.adempiere.base.Process", query); + } + + public static ModelValidator getModelValidator(String className) { + if (isExtension(className)) + className = className.substring(Core.OSGI_PREFIX.length()); + + ServiceQuery query = new ServiceQuery(); + query.put("id", className); + return Service.locate(ModelValidator.class, "org.adempiere.base.ModelValidator", query); + } } diff --git a/base/src/org/adempiere/base/IColumnCallout.java b/base/src/org/adempiere/base/IColumnCallout.java index baaa3bed4a..49e3c00e80 100755 --- a/base/src/org/adempiere/base/IColumnCallout.java +++ b/base/src/org/adempiere/base/IColumnCallout.java @@ -24,7 +24,7 @@ import org.compiere.model.GridTab; /** * Column Callout Interface */ -public interface IColumnCallout extends IService +public interface IColumnCallout { /** * Start Callout. diff --git a/base/src/org/adempiere/base/IDictionaryService.java b/base/src/org/adempiere/base/IDictionaryService.java index 00b894c91a..518634e37d 100644 --- a/base/src/org/adempiere/base/IDictionaryService.java +++ b/base/src/org/adempiere/base/IDictionaryService.java @@ -15,7 +15,9 @@ *****************************************************************************/ package org.adempiere.base; -import java.io.InputStream; +import java.io.File; + +import org.osgi.framework.BundleContext; /** * A dictionary service provides for easy handling of dynamic Adempiere @@ -24,6 +26,6 @@ import java.io.InputStream; * @author Joerg Viola * */ -public interface IDictionaryService extends IService { - void merge(InputStream model) throws Exception; +public interface IDictionaryService { + void merge(BundleContext context, File packageFile) throws Exception; } diff --git a/base/src/org/adempiere/base/IResourceFinder.java b/base/src/org/adempiere/base/IResourceFinder.java index 12d751d355..a99ea7b76b 100644 --- a/base/src/org/adempiere/base/IResourceFinder.java +++ b/base/src/org/adempiere/base/IResourceFinder.java @@ -18,7 +18,7 @@ package org.adempiere.base; import java.net.URL; -public interface IResourceFinder extends IService { +public interface IResourceFinder { URL getResource(String name); diff --git a/base/src/org/adempiere/base/IService.java b/base/src/org/adempiere/base/IService.java deleted file mode 100644 index 5745fce41f..0000000000 --- a/base/src/org/adempiere/base/IService.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.adempiere.base; - -public interface IService { - -} diff --git a/base/src/org/adempiere/base/IServiceLocator.java b/base/src/org/adempiere/base/IServiceLocator.java index b9ba7a0205..45f8ecc984 100644 --- a/base/src/org/adempiere/base/IServiceLocator.java +++ b/base/src/org/adempiere/base/IServiceLocator.java @@ -29,12 +29,12 @@ import java.util.List; * */ public interface IServiceLocator { - T locate(Class type); - T locate(Class type, String id); - T locate(Class type, ServiceQuery query); - T locate(Class type, String id, ServiceQuery query); - List list(Class type); - List list(Class type, String id); - List list(Class type, ServiceQuery query); - List list(Class type, String id, ServiceQuery query); + T locate(Class type); + T locate(Class type, String extensionPointId); + T locate(Class type, ServiceQuery query); + T locate(Class type, String extensionPointId, ServiceQuery query); + List list(Class type); + List list(Class type, String extensionPointId); + List list(Class type, ServiceQuery query); + List list(Class type, String extensionPointId, ServiceQuery query); } diff --git a/base/src/org/adempiere/base/Service.java b/base/src/org/adempiere/base/Service.java index ccc6be139b..dcdbdecbe3 100644 --- a/base/src/org/adempiere/base/Service.java +++ b/base/src/org/adempiere/base/Service.java @@ -57,35 +57,35 @@ public class Service { } } - public static T locate(Class type) { + public static T locate(Class type) { return locate(type, type.getName()); } - public static T locate(Class type, String id) { + public static T locate(Class type, String id) { return locator().locate(type, id); } - public static T locate(Class type, ServiceQuery query) { + public static T locate(Class type, ServiceQuery query) { return locate(type, type.getName(), query); } - public static T locate(Class type, String id, ServiceQuery query) { + public static T locate(Class type, String id, ServiceQuery query) { return locator().locate(type, id, query); } - public static List list(Class type) { + public static List list(Class type) { return list(type, type.getName()); } - public static List list(Class type, String id) { + public static List list(Class type, String id) { return locator().list(type, id); } - public static List list(Class type, ServiceQuery query) { + public static List list(Class type, ServiceQuery query) { return locator().list(type, type.getName(), query); } - public static List list(Class type, String id, ServiceQuery query) { + public static List list(Class type, String id, ServiceQuery query) { return locator().list(type, id, query); } } diff --git a/base/src/org/adempiere/base/equinox/EquinoxServiceLocator.java b/base/src/org/adempiere/base/equinox/EquinoxServiceLocator.java index 78abb0541d..1a730d3669 100644 --- a/base/src/org/adempiere/base/equinox/EquinoxServiceLocator.java +++ b/base/src/org/adempiere/base/equinox/EquinoxServiceLocator.java @@ -18,7 +18,6 @@ package org.adempiere.base.equinox; import java.util.List; -import org.adempiere.base.IService; import org.adempiere.base.IServiceLocator; import org.adempiere.base.ServiceQuery; @@ -33,44 +32,44 @@ import org.adempiere.base.ServiceQuery; */ public class EquinoxServiceLocator implements IServiceLocator { - public List list(Class type) { + public List list(Class type) { return list(type, type.getName()); } @Override - public List list(Class type, String id) { - ExtensionList list = new ExtensionList(type, id); + public List list(Class type, String extensionPointId) { + ExtensionList list = new ExtensionList(type, extensionPointId); return list.asList(); } - public List list(Class type, ServiceQuery query) { + public List list(Class type, ServiceQuery query) { return list(type, type.getName(), query); } @Override - public List list(Class type, String id, + public List list(Class type, String extensionPointId, ServiceQuery query) { - ExtensionList list = new ExtensionList(type, id, query); + ExtensionList list = new ExtensionList(type, extensionPointId, query); return list.asList(); } - public T locate(Class type) { + public T locate(Class type) { return locate(type, type.getName()); } @Override - public T locate(Class type, String id) { - ExtensionList list = new ExtensionList(type, id); + public T locate(Class type, String extensionPointId) { + ExtensionList list = new ExtensionList(type, extensionPointId); return list.first(); } - public T locate(Class type, ServiceQuery query) { + public T locate(Class type, ServiceQuery query) { return locate(type, type.getName(), query); } @Override - public T locate(Class type, String id, ServiceQuery query) { - ExtensionList list = new ExtensionList(type, type.getName(), query); + public T locate(Class type, String extensionPointId, ServiceQuery query) { + ExtensionList list = new ExtensionList(type, extensionPointId, query); return list.first(); } } diff --git a/base/src/org/adempiere/base/equinox/ExtensionList.java b/base/src/org/adempiere/base/equinox/ExtensionList.java index 885c938ddd..b9e70686a6 100644 --- a/base/src/org/adempiere/base/equinox/ExtensionList.java +++ b/base/src/org/adempiere/base/equinox/ExtensionList.java @@ -86,16 +86,16 @@ public class ExtensionList implements Iterable{ private IConfigurationElement[] elements; private HashMap filters = new HashMap(); - public ExtensionList(Class clazz, String id) { + public ExtensionList(Class clazz, String extensionPointId) { try { - elements = Platform.getExtensionRegistry().getConfigurationElementsFor(id); + elements = Platform.getExtensionRegistry().getConfigurationElementsFor(extensionPointId); } catch (Exception ex) { System.out.println(ex.getMessage()); } } - public ExtensionList(Class type, String name, ServiceQuery query) { - this(type, name); + public ExtensionList(Class type, String extensionPointId, ServiceQuery query) { + this(type, extensionPointId); for (String key : query.keySet()) { addFilter(key, query.get(key)); } @@ -105,8 +105,8 @@ public class ExtensionList implements Iterable{ return new ExtensionIterator(); } - public void addFilter(String name, String value) { - filters.put(name, value); + public void addFilter(String attribute, String value) { + filters.put(attribute, value); } public T first() { diff --git a/base/src/org/adempiere/util/ModelInterfaceGenerator.java b/base/src/org/adempiere/util/ModelInterfaceGenerator.java index fcf640411e..f27cc104d1 100644 --- a/base/src/org/adempiere/util/ModelInterfaceGenerator.java +++ b/base/src/org/adempiere/util/ModelInterfaceGenerator.java @@ -195,11 +195,16 @@ public class ModelInterfaceGenerator .append(" /** TableName=").append(tableName).append(" */\n") .append(" public static final String Table_Name = \"").append(tableName).append("\";\n") - .append(" /** AD_Table_ID=").append(AD_Table_ID).append(" */\n") - .append(" public static final int Table_ID = MTable.getTable_ID(Table_Name);\n") + .append(" /** AD_Table_ID=").append(AD_Table_ID).append(" */\n"); + + //MTable.getTable_ID unnecessary for official ID + if (AD_Table_ID <= MTable.MAX_OFFICIAL_ID) + start.append(" public static final int Table_ID = ").append(AD_Table_ID).append(";\n"); + else + start.append(" public static final int Table_ID = MTable.getTable_ID(Table_Name);\n"); //.append(" protected KeyNamePair Model = new KeyNamePair(Table_ID, Table_Name);\n") - .append(" KeyNamePair Model = new KeyNamePair(Table_ID, Table_Name);\n") // INFO - Should this be here??? + start.append(" KeyNamePair Model = new KeyNamePair(Table_ID, Table_Name);\n") // INFO - Should this be here??? .append(" /** AccessLevel = ").append(accessLevelInfo).append("\n") .append(" */\n") diff --git a/base/src/org/adempiere/util/ProcessUtil.java b/base/src/org/adempiere/util/ProcessUtil.java index 3ce3c9038e..4442264630 100644 --- a/base/src/org/adempiere/util/ProcessUtil.java +++ b/base/src/org/adempiere/util/ProcessUtil.java @@ -8,6 +8,7 @@ import java.util.logging.Level; import javax.script.ScriptEngine; +import org.adempiere.base.Core; import org.compiere.model.MProcess; import org.compiere.model.MRule; import org.compiere.process.ProcessCall; @@ -119,39 +120,46 @@ public final class ProcessUtil { if (proc.getJasperReport() != null) className = JASPER_STARTER_CLASS; } - //Get Class - Class processClass = null; - //use context classloader if available - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - if (classLoader == null) - classLoader = ProcessUtil.class.getClassLoader(); - try - { - processClass = classLoader.loadClass(className); - } - catch (ClassNotFoundException ex) - { - log.log(Level.WARNING, className, ex); - pi.setSummary ("ClassNotFound", true); - return false; - } - //Get Process ProcessCall process = null; - try - { - process = (ProcessCall)processClass.newInstance(); - } - catch (Exception ex) - { - log.log(Level.WARNING, "Instance for " + className, ex); - pi.setSummary ("InstanceError", true); - return false; + if (Core.isExtension(className)) { + process = Core.getProcess(className); } - if (processClass == null) { - pi.setSummary("No Instance for " + pi.getClassName(), true); - return false; + if (process == null) { + //Get Class + Class processClass = null; + //use context classloader if available + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + if (classLoader == null) + classLoader = ProcessUtil.class.getClassLoader(); + try + { + processClass = classLoader.loadClass(className); + } + catch (ClassNotFoundException ex) + { + log.log(Level.WARNING, className, ex); + pi.setSummary ("ClassNotFound", true); + return false; + } + + if (processClass == null) { + pi.setSummary("No Instance for " + pi.getClassName(), true); + return false; + } + + //Get Process + try + { + process = (ProcessCall)processClass.newInstance(); + } + catch (Exception ex) + { + log.log(Level.WARNING, "Instance for " + className, ex); + pi.setSummary ("InstanceError", true); + return false; + } } boolean success = false; diff --git a/base/src/org/compiere/db/CConnection.java b/base/src/org/compiere/db/CConnection.java index 0058aff66e..ab005af411 100644 --- a/base/src/org/compiere/db/CConnection.java +++ b/base/src/org/compiere/db/CConnection.java @@ -112,14 +112,9 @@ public class CConnection implements Serializable, Cloneable if (s_cc == null) { if (cc == null) cc = new CConnection(apps_host); - CConnectionDialog ccd = new CConnectionDialog (cc); - s_cc = ccd.getConnection (); - if (!s_cc.isDatabaseOK() && !ccd.isCancel()) { - s_cc.testDatabase(true); - } - // set also in ALogin and Ctrl - Ini.setProperty (Ini.P_CONNECTION, s_cc.toStringLong ()); - Ini.saveProperties (Ini.isClient ()); + s_cc = cc; + Ini.setProperty(Ini.P_CONNECTION, cc.toStringLong()); + Ini.saveProperties(Ini.isClient()); } } else @@ -1395,34 +1390,4 @@ public class CConnection implements Serializable, Cloneable c.m_info = info; return c; } - - /************************************************************************** - * Testing - * @param args ignored - */ - public static void main (String[] args) - { - boolean server = true; - if (args.length == 0) - System.out.println("CConnection "); - else - server = "server".equals(args[0]); - System.out.println("CConnection - " + (server ? "server" : "client")); - // - if (server) { - Adempiere.startup(false); - } else { - Adempiere.startup(true); - } - // - System.out.println ("Connection = "); - // CConnection[name=localhost{dev-dev1-adempiere},AppsHost=localhost,AppsPort=1099,type=Oracle,DBhost=dev,DBport=1521,DBname=dev1,BQ=false,FW=false,FWhost=,FWport=1630,UID=adempiere,PWD=adempiere] -// System.out.println (Ini.getProperty (Ini.P_CONNECTION)); - - CConnection cc = CConnection.get (); -// System.out.println (">> " + cc.toStringLong ()); - Connection con = cc.getConnection (false, - Connection.TRANSACTION_READ_COMMITTED); - new CConnectionDialog(cc); - } // main } // CConnection diff --git a/base/src/org/compiere/model/Callout.java b/base/src/org/compiere/model/Callout.java index 3ddfcf7b20..59501e7024 100644 --- a/base/src/org/compiere/model/Callout.java +++ b/base/src/org/compiere/model/Callout.java @@ -18,8 +18,6 @@ package org.compiere.model; import java.util.Properties; -import org.adempiere.base.IService; - /** * Callout Interface for Callout. * Used in MTab and ImpFormatRow diff --git a/base/src/org/compiere/model/GridWindow.java b/base/src/org/compiere/model/GridWindow.java index f390e891d4..b00b0a23d5 100644 --- a/base/src/org/compiere/model/GridWindow.java +++ b/base/src/org/compiere/model/GridWindow.java @@ -41,7 +41,6 @@ import org.apache.ecs.xhtml.table; import org.apache.ecs.xhtml.td; import org.apache.ecs.xhtml.th; import org.apache.ecs.xhtml.tr; -import org.compiere.plaf.CompiereColor; import org.compiere.util.CLogger; import org.compiere.util.DB; import org.compiere.util.Env; @@ -267,14 +266,14 @@ public class GridWindow implements Serializable /** * Get Color - * @return AdempiereColor or null + * @return MColor or null */ - public CompiereColor getColor() + public MColor getColor() { if (m_vo.AD_Color_ID == 0) return null; MColor mc = new MColor(m_vo.ctx, m_vo.AD_Color_ID, null); - return mc.getAdempiereColor(); + return mc; } // getColor /** diff --git a/base/src/org/compiere/model/MColor.java b/base/src/org/compiere/model/MColor.java index 5c13c9ab3c..6c191a7f43 100644 --- a/base/src/org/compiere/model/MColor.java +++ b/base/src/org/compiere/model/MColor.java @@ -17,13 +17,9 @@ package org.compiere.model; import java.awt.Color; -import java.math.BigDecimal; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; -import java.util.logging.Level; - -import org.compiere.plaf.CompiereColor; /** * Color Persistent Object Model @@ -94,63 +90,13 @@ public class MColor extends X_AD_Color return "NULL"; return value.toString(); } // saveNewSpecial - - - /************************************************************************** - * Get AdempiereColor. - * see org.compiere.grid.ed.VColor#getAdempiereColor - * @return AdempiereColor - */ - public CompiereColor getAdempiereColor() - { - if (get_ID() == 0) - return null; - - // Color Type - String ColorType = (String)getColorType(); - if (ColorType == null) - { - log.log(Level.SEVERE, "MColor.getAdempiereColor - No ColorType"); - return null; - } - CompiereColor cc = null; - // - if (ColorType.equals(CompiereColor.TYPE_FLAT)) - { - cc = new CompiereColor(getColor(true), true); - } - else if (ColorType.equals(CompiereColor.TYPE_GRADIENT)) - { - int RepeatDistance = getRepeatDistance(); - String StartPoint = getStartPoint(); - int startPoint = StartPoint == null ? 0 : Integer.parseInt(StartPoint); - cc = new CompiereColor(getColor(true), getColor(false), startPoint, RepeatDistance); - } - else if (ColorType.equals(CompiereColor.TYPE_LINES)) - { - int LineWidth = getLineWidth(); - int LineDistance = getLineDistance(); - cc = new CompiereColor(getColor(false), getColor(true), LineWidth, LineDistance); - } - else if (ColorType.equals(CompiereColor.TYPE_TEXTURE)) - { - int AD_Image_ID = getAD_Image_ID(); - String url = getURL(AD_Image_ID); - if (url == null) - return null; - BigDecimal ImageAlpha = getImageAlpha(); - float compositeAlpha = ImageAlpha == null ? 0.7f : ImageAlpha.floatValue(); - cc = new CompiereColor(url, getColor(true), compositeAlpha); - } - return cc; - } // getAdempiereColor - + /** * Get Color * @param primary true if primary false if secondary * @return Color */ - private Color getColor (boolean primary) + public Color getColor (boolean primary) { int red = primary ? getRed() : getRed_1(); int green = primary ? getGreen() : getGreen_1(); @@ -164,7 +110,7 @@ public class MColor extends X_AD_Color * @param AD_Image_ID image * @return URL as String or null */ - private String getURL (int AD_Image_ID) + public String getURL (int AD_Image_ID) { if (AD_Image_ID == 0) return null; diff --git a/base/src/org/compiere/model/MLookup.java b/base/src/org/compiere/model/MLookup.java index 2bd4a64967..a297d205f9 100644 --- a/base/src/org/compiere/model/MLookup.java +++ b/base/src/org/compiere/model/MLookup.java @@ -694,7 +694,8 @@ public final class MLookup extends Lookup implements Serializable // Bug 1843862 - Lookups not working on Report Viewer window // globalqss - when called from Viewer window ignore error about unparsabe context variables // there is no context in report viewer windows - if (Ini.isClient() == false || !Env.getWindow(m_info.WindowNo).getClass().getName().equals("org.compiere.print.Viewer")) { + //TODO: need different approach that is not client dependent + if (Ini.isClient() == false /*|| !Env.getWindow(m_info.WindowNo).getClass().getName().equals("org.compiere.print.Viewer")*/) { m_lookup.clear(); return; } diff --git a/base/src/org/compiere/model/MTable.java b/base/src/org/compiere/model/MTable.java index 850f0535c5..c44920ae6d 100644 --- a/base/src/org/compiere/model/MTable.java +++ b/base/src/org/compiere/model/MTable.java @@ -56,6 +56,8 @@ public class MTable extends X_AD_Table */ private static final long serialVersionUID = -2367316254623142732L; + public final static int MAX_OFFICIAL_ID = 999999; + /** * Get Table from Cache * @param ctx context diff --git a/base/src/org/compiere/model/ModelValidationEngine.java b/base/src/org/compiere/model/ModelValidationEngine.java index 79d0b75676..3d53b678dd 100644 --- a/base/src/org/compiere/model/ModelValidationEngine.java +++ b/base/src/org/compiere/model/ModelValidationEngine.java @@ -26,6 +26,7 @@ import java.util.logging.Level; import javax.script.ScriptEngine; +import org.adempiere.base.Core; import org.adempiere.model.ImportValidator; import org.adempiere.process.ImportProcess; import org.compiere.acct.Fact; @@ -144,8 +145,16 @@ public class ModelValidationEngine try { // - Class clazz = Class.forName(className); - ModelValidator validator = (ModelValidator)clazz.newInstance(); + ModelValidator validator = null; + if (Core.isExtension(className)) + { + validator = Core.getModelValidator(className); + } + if (validator == null) + { + Class clazz = Class.forName(className); + validator = (ModelValidator)clazz.newInstance(); + } initialize(validator, client); } catch (Exception e) diff --git a/base/src/org/compiere/print/IReportEngineEventListener.java b/base/src/org/compiere/print/IReportEngineEventListener.java new file mode 100644 index 0000000000..23be03077e --- /dev/null +++ b/base/src/org/compiere/print/IReportEngineEventListener.java @@ -0,0 +1,19 @@ +package org.compiere.print; + +public interface IReportEngineEventListener { + + /** + * @param event + */ + public void onPrintFormatChanged(ReportEngineEvent event); + + /** + * @param event + */ + public void onQueryChanged(ReportEngineEvent event); + + /** + * @param event + */ + public void onPageSetupChanged(ReportEngineEvent event); +} diff --git a/base/src/org/compiere/print/PrintUtil.java b/base/src/org/compiere/print/PrintUtil.java index da676d1317..947dfe59ce 100644 --- a/base/src/org/compiere/print/PrintUtil.java +++ b/base/src/org/compiere/print/PrintUtil.java @@ -43,6 +43,7 @@ import org.compiere.util.CLogMgt; import org.compiere.util.CLogger; import org.compiere.util.DB; import org.compiere.util.Env; +import org.compiere.util.Ini; import org.compiere.util.Language; import org.compiere.util.Msg; @@ -77,6 +78,15 @@ public class PrintUtil return DocFlavor.SERVICE_FORMATTED.PAGEABLE; } // getDefaultFlavor + /** + * Get Print Services for all flavor and pratt + * @return print services + */ + public static PrintService[] getAllPrintServices() + { + return PrintServiceLookup.lookupPrintServices(null,null); + } + /** * Get Print Services for standard flavor and pratt * @return print services @@ -96,6 +106,75 @@ public class PrintUtil } // getPrintServices + /** + * Return default PrinterJob + * @return PrinterJob + */ + public static PrinterJob getPrinterJob() + { + return getPrinterJob(Ini.getProperty(Ini.P_PRINTER)); + } // getPrinterJob + + /** + * Return PrinterJob with selected printer name. + * @param printerName if null, get default printer (Ini) + * @return PrinterJob + */ + public static PrinterJob getPrinterJob (String printerName) + { + PrinterJob pj = null; + PrintService ps = null; + try + { + pj = PrinterJob.getPrinterJob(); + + // find printer service + if (printerName == null || printerName.length() == 0) + printerName = Ini.getProperty(Ini.P_PRINTER); + if (printerName != null && printerName.length() != 0) + { + // System.out.println("CPrinter.getPrinterJob - searching " + printerName); + PrintService[] services = getAllPrintServices(); + for (int i = 0; i < services.length; i++) + { + String serviceName = services[i].getName(); + if (printerName.equals(serviceName)) + { + ps = services[i]; + // System.out.println("CPrinter.getPrinterJob - found " + printerName); + break; + } + // System.out.println("CPrinter.getPrinterJob - not: " + serviceName); + } + } // find printer service + + try + { + if (ps != null) + pj.setPrintService(ps); + } + catch (Exception e) + { + log.warning("Could not set Print Service: " + e.toString()); + } + // + PrintService psUsed = pj.getPrintService(); + if (psUsed == null) + log.warning("Print Service not Found"); + else + { + String serviceName = psUsed.getName(); + if (printerName != null && !printerName.equals(serviceName)) + log.warning("Not found: " + printerName + " - Used: " + serviceName); + } + } + catch (Exception e) + { + log.warning("Could not create for " + printerName + ": " + e.toString()); + } + return pj; + } // getPrinterJob + /*************************************************************************/ /** @@ -115,7 +194,7 @@ public class PrintUtil if (jobName != null) name += jobName; // - PrinterJob job = CPrinter.getPrinterJob(printerName); + PrinterJob job = getPrinterJob(printerName); job.setJobName (name); job.setPageable (pageable); // Attributes @@ -139,7 +218,7 @@ public class PrintUtil */ static public void print (Pageable pageable, PrintRequestAttributeSet prats) { - PrinterJob job = CPrinter.getPrinterJob(); + PrinterJob job = getPrinterJob(); job.setPageable(pageable); print (job, prats, true, false); } // print diff --git a/base/src/org/compiere/print/ReportEngine.java b/base/src/org/compiere/print/ReportEngine.java index a79516e4ab..9a2bbaf26f 100644 --- a/base/src/org/compiere/print/ReportEngine.java +++ b/base/src/org/compiere/print/ReportEngine.java @@ -31,6 +31,8 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.List; import java.util.Locale; import java.util.Properties; import java.util.logging.Level; @@ -155,9 +157,7 @@ public class ReportEngine implements PrintServiceAttributeListener /** Layout */ private LayoutEngine m_layout = null; /** Printer */ - private String m_printerName = Ini.getProperty(Ini.P_PRINTER); - /** View */ - private View m_view = null; + private String m_printerName = Ini.getProperty(Ini.P_PRINTER); /** Transaction Name */ private String m_trxName = null; /** Where filter */ @@ -167,6 +167,18 @@ public class ReportEngine implements PrintServiceAttributeListener private boolean m_summary = false; + private List eventListeners = new ArrayList(); + + public void addEventListener(IReportEngineEventListener listener) + { + eventListeners.add(listener); + } + + public boolean removeEventListener(IReportEngineEventListener listener) + { + return eventListeners.remove(listener); + } + /** * Set PrintFormat. * If Layout was created, re-create layout @@ -181,8 +193,12 @@ public class ReportEngine implements PrintServiceAttributeListener m_layout.setPrintFormat(pf, false); m_layout.setPrintData(m_printData, m_query, true); // format changes data } - if (m_view != null) - m_view.revalidate(); + + IReportEngineEventListener[] listeners = eventListeners.toArray(new IReportEngineEventListener[0]); + for(IReportEngineEventListener listener : listeners) + { + listener.onPrintFormatChanged(new ReportEngineEvent(this)); + } } // setPrintFormat /** @@ -199,8 +215,12 @@ public class ReportEngine implements PrintServiceAttributeListener setPrintData(); if (m_layout != null) m_layout.setPrintData(m_printData, m_query, true); - if (m_view != null) - m_view.revalidate(); + + IReportEngineEventListener[] listeners = eventListeners.toArray(new IReportEngineEventListener[0]); + for(IReportEngineEventListener listener : listeners) + { + listener.onQueryChanged(new ReportEngineEvent(this)); + } } // setQuery /** @@ -329,20 +349,6 @@ public class ReportEngine implements PrintServiceAttributeListener } // getColumnCount - /************************************************************************** - * Get View Panel - * @return view panel - */ - public View getView() - { - if (m_layout == null) - layout(); - if (m_view == null) - m_view = new View (m_layout); - return m_view; - } // getView - - /************************************************************************** * Print Report */ @@ -434,8 +440,8 @@ queued-job-count = 0 (class javax.print.attribute.standard.QueuedJobCount) private PrinterJob getPrinterJob (String printerName) { if (printerName != null && printerName.length() > 0) - return CPrinter.getPrinterJob(printerName); - return CPrinter.getPrinterJob(m_printerName); + return PrintUtil.getPrinterJob(printerName); + return PrintUtil.getPrinterJob(m_printerName); } // getPrinterJob /** @@ -447,8 +453,12 @@ queued-job-count = 0 (class javax.print.attribute.standard.QueuedJobCount) if (m_layout == null) layout(); m_layout.pageSetupDialog(getPrinterJob(m_printerName)); - if (m_view != null) - m_view.revalidate(); + + IReportEngineEventListener[] listeners = eventListeners.toArray(new IReportEngineEventListener[0]); + for(IReportEngineEventListener listener : listeners) + { + listener.onPageSetupChanged(new ReportEngineEvent(this)); + } } // pageSetupDialog /** diff --git a/base/src/org/compiere/print/ReportEngineEvent.java b/base/src/org/compiere/print/ReportEngineEvent.java new file mode 100644 index 0000000000..e53f9512bb --- /dev/null +++ b/base/src/org/compiere/print/ReportEngineEvent.java @@ -0,0 +1,26 @@ +package org.compiere.print; + +import java.util.EventObject; + +public class ReportEngineEvent extends EventObject { + + /** + * generated serial version Id + */ + private static final long serialVersionUID = 5414130140480852195L; + + /** + * @param source + */ + public ReportEngineEvent(ReportEngine source) { + super(source); + } + + /** + * @return report engine + */ + public ReportEngine getReportEngine() { + return (ReportEngine) getSource(); + } + +} diff --git a/base/src/org/compiere/util/ASyncProcess.java b/base/src/org/compiere/util/ASyncProcess.java index d3aace841f..d637300df0 100644 --- a/base/src/org/compiere/util/ASyncProcess.java +++ b/base/src/org/compiere/util/ASyncProcess.java @@ -64,5 +64,4 @@ public interface ASyncProcess * @param pi ProcessInfo */ public void executeASync (ProcessInfo pi); - } // ASyncProcess diff --git a/base/src/org/compiere/util/CLogMgt.java b/base/src/org/compiere/util/CLogMgt.java index 93bd91c5aa..07c53230a0 100644 --- a/base/src/org/compiere/util/CLogMgt.java +++ b/base/src/org/compiere/util/CLogMgt.java @@ -78,8 +78,8 @@ public class CLogMgt ListhandlerNames = new ArrayList(); try { - Logger rootLogger = Logger.getLogger(getRootLoggerName()); - rootLogger.setUseParentHandlers(false); + Logger rootLogger = getRootLogger(); + // System.out.println(rootLogger.getName() + " (" + rootLogger + ")"); Handler[] handlers = rootLogger.getHandlers(); for (int i = 0; i < handlers.length; i ++) @@ -189,8 +189,7 @@ public class CLogMgt */ protected static Handler[] getHandlers() { - Logger rootLogger = Logger.getLogger(getRootLoggerName()); - rootLogger.setUseParentHandlers(false); + Logger rootLogger = getRootLogger(); Handler[] handlers = rootLogger.getHandlers(); return handlers; } // getHandlers @@ -203,7 +202,7 @@ public class CLogMgt { if (handler == null) return; - Logger rootLogger = Logger.getLogger(getRootLoggerName()); + Logger rootLogger = getRootLogger(); rootLogger.addHandler(handler); // log.log(Level.CONFIG, "Handler=" + handler); @@ -216,8 +215,7 @@ public class CLogMgt */ protected static void setFormatter (java.util.logging.Formatter formatter) { - Logger rootLogger = Logger.getLogger(getRootLoggerName()); - rootLogger.setUseParentHandlers(false); + Logger rootLogger = getRootLogger(); Handler[] handlers = rootLogger.getHandlers(); for (int i = 0; i < handlers.length; i++) { @@ -232,8 +230,7 @@ public class CLogMgt */ protected static void setFilter (Filter filter) { - Logger rootLogger = Logger.getLogger(getRootLoggerName()); - rootLogger.setUseParentHandlers(false); + Logger rootLogger = getRootLogger(); Handler[] handlers = rootLogger.getHandlers(); for (int i = 0; i < handlers.length; i++) { @@ -273,8 +270,7 @@ public class CLogMgt { if (level == null) return; - Logger rootLogger = Logger.getLogger(getRootLoggerName()); - rootLogger.setUseParentHandlers(false); + Logger rootLogger = getRootLogger(); rootLogger.setLevel(level); Handler[] handlers = rootLogger.getHandlers(); if (handlers == null || handlers.length == 0) @@ -340,7 +336,7 @@ public class CLogMgt */ public static Level getLevel() { - Logger rootLogger = Logger.getLogger(getRootLoggerName()); + Logger rootLogger = getRootLogger(); return rootLogger.getLevel(); } // getLevel @@ -350,7 +346,7 @@ public class CLogMgt */ public static int getLevelAsInt() { - Logger rootLogger = Logger.getLogger(getRootLoggerName()); + Logger rootLogger = getRootLogger(); return rootLogger.getLevel().intValue(); } // getLevel @@ -417,8 +413,7 @@ public class CLogMgt */ public static void enable (boolean enableLogging) { - Logger rootLogger = Logger.getLogger(getRootLoggerName()); - rootLogger.setUseParentHandlers(false); + Logger rootLogger = getRootLogger(); if (enableLogging) setLevel(rootLogger.getLevel()); @@ -674,7 +669,22 @@ public class CLogMgt return "-no local host info -"; } // getLocalHost - + private static Logger getRootLogger() + { + Logger rootLogger = Logger.getLogger(getRootLoggerName()); + if (rootLogger.getUseParentHandlers()) + { + rootLogger.setUseParentHandlers(false); + } + //set default level + if (rootLogger.getLevel() == null) + { + rootLogger.setLevel(Level.WARNING); + } + + return rootLogger; + } + /************************************************************************** * CLogMgt */ diff --git a/base/src/org/compiere/util/Env.java b/base/src/org/compiere/util/Env.java index 179801c1de..40ad512f10 100644 --- a/base/src/org/compiere/util/Env.java +++ b/base/src/org/compiere/util/Env.java @@ -16,7 +16,6 @@ *****************************************************************************/ package org.compiere.util; -import java.awt.Component; import java.awt.Container; import java.awt.Graphics; import java.awt.Image; @@ -33,29 +32,27 @@ import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; -import java.util.HashSet; +import java.util.Enumeration; import java.util.Iterator; +import java.util.List; import java.util.Properties; import java.util.Set; import java.util.logging.Level; import javax.swing.ImageIcon; -import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; -import javax.swing.RepaintManager; -import javax.swing.SwingUtilities; import org.adempiere.base.Core; import org.adempiere.base.IResourceFinder; import org.adempiere.util.ServerContextProvider; import org.compiere.db.CConnection; +import org.compiere.model.GridWindowVO; import org.compiere.model.MClient; import org.compiere.model.MLookupCache; import org.compiere.model.MRole; import org.compiere.model.MSession; import org.compiere.model.PO; -import org.compiere.swing.CFrame; /** * System Environment and static variables. @@ -72,6 +69,8 @@ public final class Env { private final static ContextProvider clientContextProvider = new DefaultContextProvider(); + private static List eventListeners = new ArrayList(); + /** * @param provider * @deprecated @@ -80,6 +79,23 @@ public final class Env { } + /** + * @param listener + */ + public static void addEventListener(IEnvEventListener listener) + { + eventListeners.add(listener); + } + + /** + * @param listener + * @return boolean + */ + public static boolean removeEventListener(IEnvEventListener listener) + { + return eventListeners.remove(listener); + } + /** * Exit System * @param status System exit status (usually 0 for no error) @@ -124,35 +140,12 @@ public final class Env */ public static void reset (boolean finalCall) { - if (Ini.isClient()) + IEnvEventListener[] listeners = eventListeners.toArray(new IEnvEventListener[0]); + for(IEnvEventListener listener : listeners) { - closeWindows(); - - // Dismantle windows - /** - for (int i = 0; i < s_windows.size(); i++) - { - Container win = (Container)s_windows.get(i); - if (win.getClass().getName().endsWith("AMenu")) // Null pointer - ; - else if (win instanceof Window) - ((Window)win).dispose(); - else - win.removeAll(); - } - **/ - //bug [ 1574630 ] - if (s_windows.size() > 0) { - if (!finalCall) { - Container c = s_windows.get(0); - s_windows.clear(); - createWindowNo(c); - } else { - s_windows.clear(); - } - } + listener.onReset(finalCall); } - + // Clear all Context if (finalCall) getCtx().clear(); @@ -1179,8 +1172,11 @@ public final class Env MLookupCache.cacheReset(WindowNo); // MLocator.cacheReset(WindowNo); // - if (Ini.isClient()) - removeWindow(WindowNo); + IEnvEventListener[] listeners = eventListeners.toArray(new IEnvEventListener[0]); + for(IEnvEventListener listener : listeners) + { + listener.onClearWindowContext(WindowNo); + } } // clearWinContext /** @@ -1351,79 +1347,7 @@ public final class Env } /*************************************************************************/ - - // Array of active Windows - private static ArrayList s_windows = new ArrayList(20); - - /** - * Add Container and return WindowNo. - * The container is a APanel, AWindow or JFrame/JDialog - * @param win window - * @return WindowNo used for context - */ - public static int createWindowNo(Container win) - { - int retValue = s_windows.size(); - s_windows.add(win); - return retValue; - } // createWindowNo - - /** - * Search Window by comparing the Frames - * @param container container - * @return WindowNo of container or 0 - */ - public static int getWindowNo (Container container) - { - if (container == null) - return 0; - JFrame winFrame = getFrame(container); - if (winFrame == null) - return 0; - - // loop through windows - for (int i = 0; i < s_windows.size(); i++) - { - Container cmp = (Container)s_windows.get(i); - if (cmp != null) - { - JFrame cmpFrame = getFrame(cmp); - if (winFrame.equals(cmpFrame)) - return i; - } - } - return 0; - } // getWindowNo - - /** - * Return the JFrame pointer of WindowNo - or null - * @param WindowNo window - * @return JFrame of WindowNo - */ - public static JFrame getWindow (int WindowNo) - { - JFrame retValue = null; - try - { - retValue = getFrame ((Container)s_windows.get(WindowNo)); - } - catch (Exception e) - { - getLogger().log(Level.SEVERE, e.toString()); - } - return retValue; - } // getWindow - - /** - * Remove window from active list - * @param WindowNo window - */ - private static void removeWindow (int WindowNo) - { - if (WindowNo < s_windows.size()) - s_windows.set(WindowNo, null); - } // removeWindow - + /** * Clean up context for Window (i.e. delete it) * @param WindowNo window @@ -1441,24 +1365,6 @@ public final class Env getCtx().clear(); } // clearContext - - /************************************************************************** - * Get Frame of Window - * @param container Container - * @return JFrame of container or null - */ - public static JFrame getFrame (Container container) - { - Container element = container; - while (element != null) - { - if (element instanceof JFrame) - return (JFrame)element; - element = element.getParent(); - } - return null; - } // getFrame - /** * Get Graphics of container or its parent. * The element may not have a Graphic if not displayed yet, @@ -1596,92 +1502,6 @@ public final class Env return osName.indexOf ("windows") != -1; } // isWindows - - /** Array of hidden Windows */ - private static ArrayList s_hiddenWindows = new ArrayList(); - /** Closing Window Indicator */ - private static boolean s_closingWindows = false; - - /** - * Hide Window - * @param window window - * @return true if window is hidden, otherwise close it - */ - static public boolean hideWindow(CFrame window) - { - if (!Ini.isCacheWindow() || s_closingWindows) - return false; - for (int i = 0; i < s_hiddenWindows.size(); i++) - { - CFrame hidden = s_hiddenWindows.get(i); - getLogger().info(i + ": " + hidden); - if (hidden.getAD_Window_ID() == window.getAD_Window_ID()) - return false; // already there - } - if (window.getAD_Window_ID() != 0) // workbench - { - if (s_hiddenWindows.add(window)) - { - window.setVisible(false); - getLogger().info(window.toString()); - // window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_ICONIFIED)); - if (s_hiddenWindows.size() > 10) { - CFrame toClose = s_hiddenWindows.remove(0); // sort of lru - try { - s_closingWindows = true; - toClose.dispose(); - } finally { - s_closingWindows = false; - } - } - return true; - } - } - return false; - } // hideWindow - - /** - * Show Window - * @param AD_Window_ID window - * @return true if window re-displayed - */ - static public CFrame showWindow (int AD_Window_ID) - { - for (int i = 0; i < s_hiddenWindows.size(); i++) - { - CFrame hidden = s_hiddenWindows.get(i); - if (hidden.getAD_Window_ID() == AD_Window_ID) - { - s_hiddenWindows.remove(i); - getLogger().info(hidden.toString()); - hidden.setVisible(true); - // De-iconify window - teo_sarca [ 1707221 ] - int state = hidden.getExtendedState(); - if ((state & CFrame.ICONIFIED) > 0) - hidden.setExtendedState(state & ~CFrame.ICONIFIED); - // - hidden.toFront(); - return hidden; - } - } - return null; - } // showWindow - - /** - * Clode Windows. - */ - static void closeWindows () - { - s_closingWindows = true; - for (int i = 0; i < s_hiddenWindows.size(); i++) - { - CFrame hidden = s_hiddenWindows.get(i); - hidden.dispose(); - } - s_hiddenWindows.clear(); - s_closingWindows = false; - } // closeWindows - /** * Sleep * @param sec seconds @@ -1700,46 +1520,6 @@ public final class Env getLogger().info("End"); } // sleep - /** - * Update all windows after look and feel changes. - * @since 2006-11-27 - */ - public static SetupdateUI() - { - Set updated = new HashSet(); - for (Container c : s_windows) - { - Window w = getFrame(c); - if (w == null) continue; - if (updated.contains(w)) continue; - SwingUtilities.updateComponentTreeUI(w); - w.validate(); - RepaintManager mgr = RepaintManager.currentManager(w); - Component childs[] = w.getComponents(); - for (Component child : childs) { - if (child instanceof JComponent) - mgr.markCompletelyDirty((JComponent)child); - } - w.repaint(); - updated.add(w); - } - for (Window w : s_hiddenWindows) - { - if (updated.contains(w)) continue; - SwingUtilities.updateComponentTreeUI(w); - w.validate(); - RepaintManager mgr = RepaintManager.currentManager(w); - Component childs[] = w.getComponents(); - for (Component child : childs) { - if (child instanceof JComponent) - mgr.markCompletelyDirty((JComponent)child); - } - w.repaint(); - updated.add(w); - } - return updated; - } - /** * Prepare the context for calling remote server (for e.g, ejb), * only default and global variables are pass over. @@ -1764,6 +1544,63 @@ public final class Env return p; } + /** Window Cache */ + private static CCache s_windowsvo + = new CCache("AD_Window", 10); + + /** + * Get Window Model + * + * @param WindowNo Window No + * @param AD_Window_ID window + * @param AD_Menu_ID menu + * @return Model Window Value Obkect + */ + public static GridWindowVO getMWindowVO (int WindowNo, int AD_Window_ID, int AD_Menu_ID) + { + getLogger().config("Window=" + WindowNo + ", AD_Window_ID=" + AD_Window_ID); + GridWindowVO mWindowVO = null; + if (AD_Window_ID != 0 && Ini.isCacheWindow()) // try cache + { + mWindowVO = s_windowsvo.get(AD_Window_ID); + if (mWindowVO != null) + { + mWindowVO = mWindowVO.clone(WindowNo); + getLogger().info("Cached=" + mWindowVO); + } + } + + // Create Window Model on Client + if (mWindowVO == null) + { + getLogger().config("create local"); + mWindowVO = GridWindowVO.create (Env.getCtx(), WindowNo, AD_Window_ID, AD_Menu_ID); + if (mWindowVO != null) + s_windowsvo.put(AD_Window_ID, mWindowVO); + } // from Client + if (mWindowVO == null) + return null; + + // Check (remote) context + if (!mWindowVO.ctx.equals(Env.getCtx())) + { + // Remote Context is called by value, not reference + // Add Window properties to context + Enumeration keyEnum = mWindowVO.ctx.keys(); + while (keyEnum.hasMoreElements()) + { + String key = (String)keyEnum.nextElement(); + if (key.startsWith(WindowNo+"|")) + { + String value = mWindowVO.ctx.getProperty (key); + Env.setContext(Env.getCtx(), key, value); + } + } + // Sync Context + mWindowVO.setCtx(Env.getCtx()); + } + return mWindowVO; + } // getWindow /************************************************************************** * Static Variables diff --git a/base/src/org/compiere/util/IEnvEventListener.java b/base/src/org/compiere/util/IEnvEventListener.java new file mode 100644 index 0000000000..09d8cb3671 --- /dev/null +++ b/base/src/org/compiere/util/IEnvEventListener.java @@ -0,0 +1,8 @@ +package org.compiere.util; + +public interface IEnvEventListener { + + public void onClearWindowContext(int windowNo); + + public void onReset(boolean finalCall); +} diff --git a/base/src/org/compiere/util/Ini.java b/base/src/org/compiere/util/Ini.java index 63e1ffb36b..d5e4a5fd3f 100644 --- a/base/src/org/compiere/util/Ini.java +++ b/base/src/org/compiere/util/Ini.java @@ -34,7 +34,6 @@ import java.util.Collection; import java.util.Enumeration; import java.util.Properties; import java.util.logging.Level; -import java.util.logging.Logger; import javax.jnlp.BasicService; import javax.jnlp.FileContents; @@ -44,8 +43,6 @@ import javax.jnlp.UnavailableServiceException; import javax.naming.InitialContext; import javax.naming.NamingException; -import org.adempiere.plaf.AdempiereLookAndFeel; -import org.adempiere.plaf.AdempiereThemeInnova; import org.compiere.model.ModelValidationEngine; /** @@ -101,10 +98,10 @@ public final class Ini implements Serializable /** Look & Feel */ public static final String P_UI_LOOK = "UILookFeel"; - private static final String DEFAULT_UI_LOOK = AdempiereLookAndFeel.NAME; + private static final String DEFAULT_UI_LOOK = "Adempiere"; /** UI Theme */ - private static final String DEFAULT_UI_THEME = AdempiereThemeInnova.NAME; + private static final String DEFAULT_UI_THEME = "Adempiere Theme"; /** UI Theme */ public static final String P_UI_THEME = "UITheme"; @@ -233,8 +230,9 @@ public final class Ini implements Serializable private static String s_propertyFileName = null; - /** Logger */ - private static Logger log = null; + private static CLogger getLogger() { + return CLogger.getCLogger(Ini.class.getName()); + } /** * Save INI parameters to disk @@ -266,15 +264,15 @@ public final class Ini implements Serializable } catch (Exception e) { - log.log(Level.SEVERE, "Cannot save Properties to " + fileName + " - " + e.toString()); + getLogger().log(Level.SEVERE, "Cannot save Properties to " + fileName + " - " + e.toString()); return; } catch (Throwable t) { - log.log(Level.SEVERE, "Cannot save Properties to " + fileName + " - " + t.toString()); + getLogger().log(Level.SEVERE, "Cannot save Properties to " + fileName + " - " + t.toString()); return; } - log.finer(fileName); + getLogger().finer(fileName); } } // save @@ -284,7 +282,6 @@ public final class Ini implements Serializable */ public static void loadProperties (boolean reload) { - log = Logger.getLogger(Ini.class.getName()); if (reload || s_prop.size() == 0) { if (isWebStartClient()) @@ -309,7 +306,7 @@ public final class Ini implements Serializable ps = (PersistenceService)ServiceManager.lookup("javax.jnlp.PersistenceService"); } catch (UnavailableServiceException e) { ps = null; - log.log(Level.SEVERE, e.toString()); + getLogger().log(Level.SEVERE, e.toString()); return false; } @@ -317,7 +314,7 @@ public final class Ini implements Serializable try { fc = ps.get(getCodeBase()); } catch (MalformedURLException e) { - log.log(Level.SEVERE, e.toString()); + getLogger().log(Level.SEVERE, e.toString()); return false; } catch (FileNotFoundException e) { try { @@ -328,7 +325,7 @@ public final class Ini implements Serializable } } catch (IOException e) { - log.log(Level.SEVERE, e.toString()); + getLogger().log(Level.SEVERE, e.toString()); return false; } @@ -340,15 +337,12 @@ public final class Ini implements Serializable } catch (Throwable t) { - log.log(Level.SEVERE, t.toString()); + getLogger().log(Level.SEVERE, t.toString()); loadOK = false; } if (!loadOK || s_prop.getProperty(P_TODAY, "").equals("")) { firstTime = true; - if (isShowLicenseDialog()) - if (!IniDialog.accept()) - System.exit(-1); } checkProperties(); @@ -370,7 +364,7 @@ public final class Ini implements Serializable ps = (PersistenceService)ServiceManager.lookup("javax.jnlp.PersistenceService"); } catch (UnavailableServiceException e) { ps = null; - log.log(Level.SEVERE, e.toString()); + getLogger().log(Level.SEVERE, e.toString()); return; } @@ -383,7 +377,7 @@ public final class Ini implements Serializable } catch (Throwable t) { - log.log(Level.SEVERE, "Cannot save Properties to " + getCodeBase() + " - " + t.toString()); + getLogger().log(Level.SEVERE, "Cannot save Properties to " + getCodeBase() + " - " + t.toString()); return; } @@ -435,26 +429,23 @@ public final class Ini implements Serializable } catch (FileNotFoundException e) { - log.warning(filename + " not found"); + getLogger().warning(filename + " not found"); loadOK = false; } catch (Exception e) { - log.log(Level.SEVERE, filename + " - " + e.toString()); + getLogger().log(Level.SEVERE, filename + " - " + e.toString()); loadOK = false; } catch (Throwable t) { - log.log(Level.SEVERE, filename + " - " + t.toString()); + getLogger().log(Level.SEVERE, filename + " - " + t.toString()); loadOK = false; } if (!loadOK || s_prop.getProperty(P_TODAY, "").equals("")) { - log.config(filename); + getLogger().config(filename); firstTime = true; - if (isShowLicenseDialog()) - if (!IniDialog.accept()) - System.exit(-1); } checkProperties(); @@ -463,7 +454,7 @@ public final class Ini implements Serializable if (!loadOK || firstTime) saveProperties(true); s_loaded = true; - log.info(filename + " #" + s_prop.size()); + getLogger().info(filename + " #" + s_prop.size()); s_propertyFileName = filename; return firstTime; @@ -500,11 +491,11 @@ public final class Ini implements Serializable if (!file.delete()) file.deleteOnExit(); s_prop = new Properties(); - log.config (fileName); + getLogger().config (fileName); } catch (Exception e) { - log.log (Level.WARNING, "Cannot delete Property file", e); + getLogger().log (Level.WARNING, "Cannot delete Property file", e); } } } // deleteProperties @@ -573,7 +564,7 @@ public final class Ini implements Serializable */ public static void setProperty (String key, String value) { - // log.finer(key + "=" + value); + // getLogger().finer(key + "=" + value); if (s_prop == null) s_prop = new Properties(); if (key.equals(P_WARNING) || key.equals(P_WARNING_de)) @@ -629,7 +620,7 @@ public final class Ini implements Serializable return ""; // String value = SecureEngine.decrypt(retStr); - // log.finer(key + "=" + value); + // getLogger().finer(key + "=" + value); if (value == null) return ""; return value; @@ -758,7 +749,7 @@ public final class Ini implements Serializable env = (String) context.lookup("java:comp/env/"+ADEMPIERE_HOME); } catch (NamingException e) { // teo_sarca: if you uncomment the line below you will get an NPE when generating models - //log.fine( "Not found 'java:comp/env/"+ADEMPIERE_HOME+"' in Initial Context. " +e.getMessage()); + //getLogger().fine( "Not found 'java:comp/env/"+ADEMPIERE_HOME+"' in Initial Context. " +e.getMessage()); } } diff --git a/base/src/org/compiere/util/Trace.java b/base/src/org/compiere/util/Trace.java index 47070f9251..9d3a70506f 100644 --- a/base/src/org/compiere/util/Trace.java +++ b/base/src/org/compiere/util/Trace.java @@ -17,9 +17,6 @@ package org.compiere.util; import java.util.ArrayList; -import java.util.logging.Logger; - -import org.compiere.db.CConnectionDialog; /** * Trace Information @@ -30,7 +27,7 @@ import org.compiere.db.CConnectionDialog; public class Trace { /** Logger */ - private static CLogger log = CLogger.getCLogger (CConnectionDialog.class); + private static CLogger log = CLogger.getCLogger (Trace.class); /** * Get Caller Array diff --git a/client/.classpath b/client/.classpath index 5d65d12599..8dec8f8698 100644 --- a/client/.classpath +++ b/client/.classpath @@ -1,9 +1,7 @@ - - - + diff --git a/client/META-INF/MANIFEST.MF b/client/META-INF/MANIFEST.MF index 32d709aee2..841131ba86 100644 --- a/client/META-INF/MANIFEST.MF +++ b/client/META-INF/MANIFEST.MF @@ -7,6 +7,7 @@ Bundle-ClassPath: client.jar Export-Package: de.schaeffer.compiere.tools, org.adempiere.apps.graph, org.adempiere.osgi, + org.adempiere.plaf, org.compiere, org.compiere.acct, org.compiere.apps, @@ -19,11 +20,14 @@ Export-Package: de.schaeffer.compiere.tools, org.compiere.images, org.compiere.install, org.compiere.minigrid, + org.compiere.plaf, org.compiere.pos, org.compiere.print, + org.compiere.swing, org.eevolution.form Require-Bundle: org.adempiere.base;bundle-version="1.0.0", - org.adempiere.tools;bundle-version="1.0.0" + org.adempiere.tools;bundle-version="1.0.0", + org.adempiere.ui.base;bundle-version="1.0.0" Eclipse-ExtensibleAPI: true Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Import-Package: org.eclipse.core.runtime;version="3.4.0", diff --git a/base/Swingset.bat b/client/Swingset.bat similarity index 100% rename from base/Swingset.bat rename to client/Swingset.bat diff --git a/client/build.xml b/client/build.xml index 6b8f0d861e..371d7fc393 100644 --- a/client/build.xml +++ b/client/build.xml @@ -29,7 +29,7 @@ - + diff --git a/client/plugin.xml b/client/plugin.xml index 3a52fae1c2..1132256ec1 100644 --- a/client/plugin.xml +++ b/client/plugin.xml @@ -2,6 +2,7 @@ + - + - + [Enter description of this extension point.] @@ -18,7 +18,7 @@ - + @@ -27,7 +27,7 @@ - + @@ -47,7 +47,7 @@ - + diff --git a/client/src/org/adempiere/client/Client.java b/client/src/org/adempiere/client/Client.java index 0fd064200e..aeb72a6dc1 100644 --- a/client/src/org/adempiere/client/Client.java +++ b/client/src/org/adempiere/client/Client.java @@ -11,8 +11,8 @@ public class Client { if (Core.isExtension(className)) className = className.substring(Core.OSGI_PREFIX.length()); ServiceQuery query = new ServiceQuery(); - query.put("class", className); - return Service.locate(FormPanel.class, query ); + query.put("id", className); + return Service.locate(FormPanel.class, "org.adempiere.apps.Form", query); } } diff --git a/client/src/org/adempiere/osgi/IMenuAction.java b/client/src/org/adempiere/osgi/IMenuAction.java index b47dc1dce5..f8478fcaae 100644 --- a/client/src/org/adempiere/osgi/IMenuAction.java +++ b/client/src/org/adempiere/osgi/IMenuAction.java @@ -2,9 +2,7 @@ package org.adempiere.osgi; import javax.swing.JMenuBar; -import org.adempiere.base.IService; - -public interface IMenuAction extends IService { +public interface IMenuAction { public void addAction(JMenuBar menuBar); diff --git a/base/src/org/adempiere/plaf/AdempiereButtonListener.java b/client/src/org/adempiere/plaf/AdempiereButtonListener.java similarity index 100% rename from base/src/org/adempiere/plaf/AdempiereButtonListener.java rename to client/src/org/adempiere/plaf/AdempiereButtonListener.java diff --git a/base/src/org/adempiere/plaf/AdempiereComboBoxUI.java b/client/src/org/adempiere/plaf/AdempiereComboBoxUI.java similarity index 100% rename from base/src/org/adempiere/plaf/AdempiereComboBoxUI.java rename to client/src/org/adempiere/plaf/AdempiereComboBoxUI.java diff --git a/base/src/org/adempiere/plaf/AdempiereComboPopup.java b/client/src/org/adempiere/plaf/AdempiereComboPopup.java similarity index 100% rename from base/src/org/adempiere/plaf/AdempiereComboPopup.java rename to client/src/org/adempiere/plaf/AdempiereComboPopup.java diff --git a/base/src/org/adempiere/plaf/AdempiereLabelUI.java b/client/src/org/adempiere/plaf/AdempiereLabelUI.java similarity index 100% rename from base/src/org/adempiere/plaf/AdempiereLabelUI.java rename to client/src/org/adempiere/plaf/AdempiereLabelUI.java diff --git a/base/src/org/adempiere/plaf/AdempiereLookAndFeel.java b/client/src/org/adempiere/plaf/AdempiereLookAndFeel.java similarity index 100% rename from base/src/org/adempiere/plaf/AdempiereLookAndFeel.java rename to client/src/org/adempiere/plaf/AdempiereLookAndFeel.java diff --git a/base/src/org/adempiere/plaf/AdempiereLookAndFeelAddons.java b/client/src/org/adempiere/plaf/AdempiereLookAndFeelAddons.java similarity index 100% rename from base/src/org/adempiere/plaf/AdempiereLookAndFeelAddons.java rename to client/src/org/adempiere/plaf/AdempiereLookAndFeelAddons.java diff --git a/base/src/org/adempiere/plaf/AdempierePLAF.java b/client/src/org/adempiere/plaf/AdempierePLAF.java similarity index 100% rename from base/src/org/adempiere/plaf/AdempierePLAF.java rename to client/src/org/adempiere/plaf/AdempierePLAF.java diff --git a/base/src/org/adempiere/plaf/AdempiereTabbedPaneUI.java b/client/src/org/adempiere/plaf/AdempiereTabbedPaneUI.java similarity index 100% rename from base/src/org/adempiere/plaf/AdempiereTabbedPaneUI.java rename to client/src/org/adempiere/plaf/AdempiereTabbedPaneUI.java diff --git a/base/src/org/adempiere/plaf/AdempiereTaskPaneUI.java b/client/src/org/adempiere/plaf/AdempiereTaskPaneUI.java similarity index 100% rename from base/src/org/adempiere/plaf/AdempiereTaskPaneUI.java rename to client/src/org/adempiere/plaf/AdempiereTaskPaneUI.java diff --git a/base/src/org/adempiere/plaf/AdempiereTheme.java b/client/src/org/adempiere/plaf/AdempiereTheme.java similarity index 100% rename from base/src/org/adempiere/plaf/AdempiereTheme.java rename to client/src/org/adempiere/plaf/AdempiereTheme.java diff --git a/base/src/org/adempiere/plaf/AdempiereThemeInnova.java b/client/src/org/adempiere/plaf/AdempiereThemeInnova.java similarity index 100% rename from base/src/org/adempiere/plaf/AdempiereThemeInnova.java rename to client/src/org/adempiere/plaf/AdempiereThemeInnova.java diff --git a/base/src/org/adempiere/plaf/PLAFEditor.java b/client/src/org/adempiere/plaf/PLAFEditor.java similarity index 100% rename from base/src/org/adempiere/plaf/PLAFEditor.java rename to client/src/org/adempiere/plaf/PLAFEditor.java diff --git a/base/src/org/adempiere/plaf/PLAFEditorPanel.java b/client/src/org/adempiere/plaf/PLAFEditorPanel.java similarity index 100% rename from base/src/org/adempiere/plaf/PLAFEditorPanel.java rename to client/src/org/adempiere/plaf/PLAFEditorPanel.java diff --git a/base/src/org/adempiere/plaf/icons/CL16.gif b/client/src/org/adempiere/plaf/icons/CL16.gif similarity index 100% rename from base/src/org/adempiere/plaf/icons/CL16.gif rename to client/src/org/adempiere/plaf/icons/CL16.gif diff --git a/base/src/org/adempiere/plaf/icons/CL32.gif b/client/src/org/adempiere/plaf/icons/CL32.gif similarity index 100% rename from base/src/org/adempiere/plaf/icons/CL32.gif rename to client/src/org/adempiere/plaf/icons/CL32.gif diff --git a/base/src/org/adempiere/plaf/icons/Cancel24.gif b/client/src/org/adempiere/plaf/icons/Cancel24.gif similarity index 100% rename from base/src/org/adempiere/plaf/icons/Cancel24.gif rename to client/src/org/adempiere/plaf/icons/Cancel24.gif diff --git a/base/src/org/adempiere/plaf/icons/Computer.gif b/client/src/org/adempiere/plaf/icons/Computer.gif similarity index 100% rename from base/src/org/adempiere/plaf/icons/Computer.gif rename to client/src/org/adempiere/plaf/icons/Computer.gif diff --git a/base/src/org/adempiere/plaf/icons/Error.gif b/client/src/org/adempiere/plaf/icons/Error.gif similarity index 100% rename from base/src/org/adempiere/plaf/icons/Error.gif rename to client/src/org/adempiere/plaf/icons/Error.gif diff --git a/base/src/org/adempiere/plaf/icons/File.gif b/client/src/org/adempiere/plaf/icons/File.gif similarity index 100% rename from base/src/org/adempiere/plaf/icons/File.gif rename to client/src/org/adempiere/plaf/icons/File.gif diff --git a/base/src/org/adempiere/plaf/icons/FloppyDrive.gif b/client/src/org/adempiere/plaf/icons/FloppyDrive.gif similarity index 100% rename from base/src/org/adempiere/plaf/icons/FloppyDrive.gif rename to client/src/org/adempiere/plaf/icons/FloppyDrive.gif diff --git a/base/src/org/adempiere/plaf/icons/HardDrive.gif b/client/src/org/adempiere/plaf/icons/HardDrive.gif similarity index 100% rename from base/src/org/adempiere/plaf/icons/HardDrive.gif rename to client/src/org/adempiere/plaf/icons/HardDrive.gif diff --git a/base/src/org/adempiere/plaf/icons/HomeFolder.gif b/client/src/org/adempiere/plaf/icons/HomeFolder.gif similarity index 100% rename from base/src/org/adempiere/plaf/icons/HomeFolder.gif rename to client/src/org/adempiere/plaf/icons/HomeFolder.gif diff --git a/base/src/org/adempiere/plaf/icons/Inform.gif b/client/src/org/adempiere/plaf/icons/Inform.gif similarity index 100% rename from base/src/org/adempiere/plaf/icons/Inform.gif rename to client/src/org/adempiere/plaf/icons/Inform.gif diff --git a/base/src/org/adempiere/plaf/icons/NewFolder.gif b/client/src/org/adempiere/plaf/icons/NewFolder.gif similarity index 100% rename from base/src/org/adempiere/plaf/icons/NewFolder.gif rename to client/src/org/adempiere/plaf/icons/NewFolder.gif diff --git a/base/src/org/adempiere/plaf/icons/Ok24.gif b/client/src/org/adempiere/plaf/icons/Ok24.gif similarity index 100% rename from base/src/org/adempiere/plaf/icons/Ok24.gif rename to client/src/org/adempiere/plaf/icons/Ok24.gif diff --git a/base/src/org/adempiere/plaf/icons/Question.gif b/client/src/org/adempiere/plaf/icons/Question.gif similarity index 100% rename from base/src/org/adempiere/plaf/icons/Question.gif rename to client/src/org/adempiere/plaf/icons/Question.gif diff --git a/base/src/org/adempiere/plaf/icons/TreeClosed.gif b/client/src/org/adempiere/plaf/icons/TreeClosed.gif similarity index 100% rename from base/src/org/adempiere/plaf/icons/TreeClosed.gif rename to client/src/org/adempiere/plaf/icons/TreeClosed.gif diff --git a/base/src/org/adempiere/plaf/icons/TreeLeaf.gif b/client/src/org/adempiere/plaf/icons/TreeLeaf.gif similarity index 100% rename from base/src/org/adempiere/plaf/icons/TreeLeaf.gif rename to client/src/org/adempiere/plaf/icons/TreeLeaf.gif diff --git a/base/src/org/adempiere/plaf/icons/TreeOpen.gif b/client/src/org/adempiere/plaf/icons/TreeOpen.gif similarity index 100% rename from base/src/org/adempiere/plaf/icons/TreeOpen.gif rename to client/src/org/adempiere/plaf/icons/TreeOpen.gif diff --git a/base/src/org/adempiere/plaf/icons/UpFolder.gif b/client/src/org/adempiere/plaf/icons/UpFolder.gif similarity index 100% rename from base/src/org/adempiere/plaf/icons/UpFolder.gif rename to client/src/org/adempiere/plaf/icons/UpFolder.gif diff --git a/base/src/org/adempiere/plaf/icons/Warn.gif b/client/src/org/adempiere/plaf/icons/Warn.gif similarity index 100% rename from base/src/org/adempiere/plaf/icons/Warn.gif rename to client/src/org/adempiere/plaf/icons/Warn.gif diff --git a/client/src/org/compiere/acct/AcctViewer.java b/client/src/org/compiere/acct/AcctViewer.java index 2827738ae4..40f7a8ff77 100644 --- a/client/src/org/compiere/acct/AcctViewer.java +++ b/client/src/org/compiere/acct/AcctViewer.java @@ -102,7 +102,7 @@ public class AcctViewer extends CFrame super (Msg.getMsg(Env.getCtx(), "AcctViewer")); log.info("AD_Table_ID=" + AD_Table_ID + ", Record_ID=" + Record_ID); setDefaultCloseOperation(DISPOSE_ON_CLOSE); - m_data = new AcctViewerData (Env.getCtx(), Env.createWindowNo(this), + m_data = new AcctViewerData (Env.getCtx(), AEnv.createWindowNo(this), AD_Client_ID, AD_Table_ID); AEnv.addToWindowManager(this); // diff --git a/client/src/org/compiere/apps/ADialog.java b/client/src/org/compiere/apps/ADialog.java index 9d0b06d4a4..f948926084 100644 --- a/client/src/org/compiere/apps/ADialog.java +++ b/client/src/org/compiere/apps/ADialog.java @@ -70,7 +70,7 @@ public final class ADialog // Window parent = Env.getParent(c); if (parent == null) - parent = Env.getWindow(WindowNo); + parent = AEnv.getWindow(WindowNo); // if (showDialog && parent != null) { @@ -111,7 +111,7 @@ public final class ADialog // Window parent = Env.getParent(c); if (parent == null) - parent = Env.getWindow(WindowNo); + parent = AEnv.getWindow(WindowNo); // if (showDialog && parent != null) { @@ -164,7 +164,7 @@ public final class ADialog // Window parent = Env.getParent(c); if (parent == null) - parent = Env.getWindow(WindowNo); + parent = AEnv.getWindow(WindowNo); // if (showDialog && parent != null) { @@ -219,7 +219,7 @@ public final class ADialog // Window parent = Env.getParent(c); if (parent == null) - parent = Env.getWindow(WindowNo); + parent = AEnv.getWindow(WindowNo); // if (showDialog && parent != null) { @@ -235,7 +235,7 @@ public final class ADialog JOptionPane.ERROR_MESSAGE); } else - JOptionPane.showMessageDialog(Env.getWindow(WindowNo), + JOptionPane.showMessageDialog(AEnv.getWindow(WindowNo), out.toString() + "\n", // message Env.getHeader(ctx, WindowNo), // title JOptionPane.ERROR_MESSAGE); @@ -273,7 +273,7 @@ public final class ADialog // Window parent = Env.getParent(c); if (parent == null) - parent = Env.getWindow(WindowNo); + parent = AEnv.getWindow(WindowNo); boolean retValue = false; if (showDialog && parent != null) @@ -340,7 +340,7 @@ public final class ADialog // Window parent = Env.getParent(c); if (parent == null) - parent = Env.getWindow(WindowNo); + parent = AEnv.getWindow(WindowNo); // if (showDialog && parent != null) { diff --git a/client/src/org/compiere/apps/AEnv.java b/client/src/org/compiere/apps/AEnv.java index db3710b716..5751f15a20 100644 --- a/client/src/org/compiere/apps/AEnv.java +++ b/client/src/org/compiere/apps/AEnv.java @@ -29,7 +29,8 @@ import java.awt.event.ActionListener; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import java.util.Enumeration; +import java.util.ArrayList; +import java.util.HashSet; import java.util.Set; import java.util.logging.Level; @@ -47,7 +48,6 @@ import javax.swing.SwingUtilities; import org.compiere.db.CConnection; import org.compiere.grid.ed.Calculator; import org.compiere.interfaces.Server; -import org.compiere.model.GridWindowVO; import org.compiere.model.MMenu; import org.compiere.model.MQuery; import org.compiere.model.MRole; @@ -55,7 +55,6 @@ import org.compiere.process.DocumentEngine; import org.compiere.swing.CButton; import org.compiere.swing.CFrame; import org.compiere.swing.CMenuItem; -import org.compiere.util.CCache; import org.compiere.util.CLogMgt; import org.compiere.util.CLogger; import org.compiere.util.DB; @@ -77,6 +76,95 @@ import org.compiere.util.Splash; */ public final class AEnv { + // Array of active Windows + private static ArrayList s_windows = new ArrayList(20); + + /** Array of hidden Windows */ + private static ArrayList s_hiddenWindows = new ArrayList(); + + /** Closing Window Indicator */ + private static boolean s_closingWindows = false; + + /** + * Hide Window + * @param window window + * @return true if window is hidden, otherwise close it + */ + static public boolean hideWindow(CFrame window) + { + if (!Ini.isCacheWindow() || s_closingWindows) + return false; + for (int i = 0; i < s_hiddenWindows.size(); i++) + { + CFrame hidden = s_hiddenWindows.get(i); + log.info(i + ": " + hidden); + if (hidden.getAD_Window_ID() == window.getAD_Window_ID()) + return false; // already there + } + if (window.getAD_Window_ID() != 0) // workbench + { + if (s_hiddenWindows.add(window)) + { + window.setVisible(false); + log.info(window.toString()); + // window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_ICONIFIED)); + if (s_hiddenWindows.size() > 10) { + CFrame toClose = s_hiddenWindows.remove(0); // sort of lru + try { + s_closingWindows = true; + toClose.dispose(); + } finally { + s_closingWindows = false; + } + } + return true; + } + } + return false; + } // hideWindow + + /** + * Show Window + * @param AD_Window_ID window + * @return true if window re-displayed + */ + static public CFrame showWindow (int AD_Window_ID) + { + for (int i = 0; i < s_hiddenWindows.size(); i++) + { + CFrame hidden = s_hiddenWindows.get(i); + if (hidden.getAD_Window_ID() == AD_Window_ID) + { + s_hiddenWindows.remove(i); + log.info(hidden.toString()); + hidden.setVisible(true); + // De-iconify window - teo_sarca [ 1707221 ] + int state = hidden.getExtendedState(); + if ((state & CFrame.ICONIFIED) > 0) + hidden.setExtendedState(state & ~CFrame.ICONIFIED); + // + hidden.toFront(); + return hidden; + } + } + return null; + } // showWindow + + /** + * Clode Windows. + */ + static void closeWindows () + { + s_closingWindows = true; + for (int i = 0; i < s_hiddenWindows.size(); i++) + { + CFrame hidden = s_hiddenWindows.get(i); + hidden.dispose(); + } + s_hiddenWindows.clear(); + s_closingWindows = false; + } // closeWindows + /** * Show window: de-iconify and bring it to front * @author teo_sarca [ 1707221 ] @@ -355,11 +443,11 @@ public final class AEnv // File Menu ------------------------ if (actionCommand.equals("PrintScreen")) { - PrintScreenPainter.printScreen (Env.getFrame(c)); + PrintScreenPainter.printScreen (getFrame(c)); } else if (actionCommand.equals("ScreenShot")) { - ScreenShot.createJPEG(Env.getFrame(c), null); + ScreenShot.createJPEG(getFrame(c), null); } // else if (actionCommand.equals("Report")) // { @@ -369,28 +457,28 @@ public final class AEnv { if (ADialog.ask(WindowNo, c, "ExitApplication?")) { - AMenu aMenu = (AMenu)Env.getWindow(0); + AMenu aMenu = (AMenu)getWindow(0); aMenu.dispose() ; } } else if (actionCommand.equals("Logout")) { - AMenu aMenu = (AMenu)Env.getWindow(0); + AMenu aMenu = (AMenu)getWindow(0); aMenu.logout(); } // View Menu ------------------------ else if (actionCommand.equals("InfoProduct") && AEnv.canAccessInfo("PRODUCT")) { - org.compiere.apps.search.Info.showProduct (Env.getFrame(c), WindowNo); + org.compiere.apps.search.Info.showProduct (getFrame(c), WindowNo); } else if (actionCommand.equals("InfoBPartner") && AEnv.canAccessInfo("BPARTNER")) { - org.compiere.apps.search.Info.showBPartner (Env.getFrame(c), WindowNo); + org.compiere.apps.search.Info.showBPartner (getFrame(c), WindowNo); } else if (actionCommand.equals("InfoAsset") && AEnv.canAccessInfo("ASSET")) { - org.compiere.apps.search.Info.showAsset (Env.getFrame(c), WindowNo); + org.compiere.apps.search.Info.showAsset (getFrame(c), WindowNo); } else if (actionCommand.equals("InfoAccount") && MRole.getDefault().isShowAcct() && @@ -400,12 +488,12 @@ public final class AEnv } else if (actionCommand.equals("InfoSchedule") && AEnv.canAccessInfo("SCHEDULE")) { - new org.compiere.apps.search.InfoSchedule (Env.getFrame(c), null, false); + new org.compiere.apps.search.InfoSchedule (getFrame(c), null, false); } //FR [ 1966328 ] else if (actionCommand.equals("InfoMRP") && AEnv.canAccessInfo("MRP")) { - CFrame frame = (CFrame) Env.getFrame(c); + CFrame frame = (CFrame) getFrame(c); int m_menu_id = MMenu.getMenu_ID("MRP Info"); AMenu menu = AEnv.getAMenu(frame); AMenuStartItem form = new AMenuStartItem (m_menu_id, true, Msg.translate(Env.getCtx(), "MRP Info"), menu); // async load @@ -413,7 +501,7 @@ public final class AEnv } else if (actionCommand.equals("InfoCRP") && AEnv.canAccessInfo("CRP")) { - CFrame frame = (CFrame) Env.getFrame(c); + CFrame frame = (CFrame) getFrame(c); int m_menu_id = MMenu.getMenu_ID("CRP Info"); AMenu menu = AEnv.getAMenu(frame); AMenuStartItem form = new AMenuStartItem (m_menu_id, true, Msg.translate(Env.getCtx(), "CRP Info"), menu); // async load @@ -421,27 +509,27 @@ public final class AEnv } else if (actionCommand.equals("InfoOrder") && AEnv.canAccessInfo("ORDER")) { - org.compiere.apps.search.Info.showOrder (Env.getFrame(c), WindowNo, ""); + org.compiere.apps.search.Info.showOrder (getFrame(c), WindowNo, ""); } else if (actionCommand.equals("InfoInvoice") && AEnv.canAccessInfo("INVOICE")) { - org.compiere.apps.search.Info.showInvoice (Env.getFrame(c), WindowNo, ""); + org.compiere.apps.search.Info.showInvoice (getFrame(c), WindowNo, ""); } else if (actionCommand.equals("InfoInOut") && AEnv.canAccessInfo("INOUT")) { - org.compiere.apps.search.Info.showInOut (Env.getFrame(c), WindowNo, ""); + org.compiere.apps.search.Info.showInOut (getFrame(c), WindowNo, ""); } else if (actionCommand.equals("InfoPayment") && AEnv.canAccessInfo("PAYMENT")) { - org.compiere.apps.search.Info.showPayment (Env.getFrame(c), WindowNo, ""); + org.compiere.apps.search.Info.showPayment (getFrame(c), WindowNo, ""); } else if (actionCommand.equals("InfoCashLine") && AEnv.canAccessInfo("CASHJOURNAL")) { - org.compiere.apps.search.Info.showCashLine (Env.getFrame(c), WindowNo, ""); + org.compiere.apps.search.Info.showCashLine (getFrame(c), WindowNo, ""); } else if (actionCommand.equals("InfoAssignment") && AEnv.canAccessInfo("RESOURCE")) { - org.compiere.apps.search.Info.showAssignment (Env.getFrame(c), WindowNo, ""); + org.compiere.apps.search.Info.showAssignment (getFrame(c), WindowNo, ""); } @@ -452,32 +540,32 @@ public final class AEnv } else if (actionCommand.equals("Home")) { - showWindow(Env.getWindow(0)); + showWindow(getWindow(0)); } // Tools Menu ------------------------ else if (actionCommand.equals("Calculator")) { - Calculator calc = new org.compiere.grid.ed.Calculator(Env.getFrame(c)); + Calculator calc = new org.compiere.grid.ed.Calculator(getFrame(c)); calc.setDisposeOnEqual(false); AEnv.showCenterScreen (calc); } else if (actionCommand.equals("Calendar")) { - AEnv.showCenterScreen (new org.compiere.grid.ed.Calendar(Env.getFrame(c))); + AEnv.showCenterScreen (new org.compiere.grid.ed.Calendar(getFrame(c))); } else if (actionCommand.equals("Editor")) { - AEnv.showCenterScreen (new org.compiere.grid.ed.Editor(Env.getFrame(c))); + AEnv.showCenterScreen (new org.compiere.grid.ed.Editor(getFrame(c))); } else if (actionCommand.equals("Script")) { - new BeanShellEditor(Env.getFrame(c)); + new BeanShellEditor(getFrame(c)); } else if (actionCommand.equals("Preference")) { if (role.isShowPreference()) { - AEnv.showCenterScreen(new Preference (Env.getFrame(c), WindowNo)); + AEnv.showCenterScreen(new Preference (getFrame(c), WindowNo)); } } @@ -488,11 +576,11 @@ public final class AEnv } else if (actionCommand.equals("EMailSupport")) { - ADialog.createSupportEMail(Env.getFrame(c), Env.getFrame(c).getTitle(), "\n\n"); + ADialog.createSupportEMail(getFrame(c), getFrame(c).getTitle(), "\n\n"); } else if (actionCommand.equals("About")) { - AEnv.showCenterScreen(new AboutBox(Env.getFrame(c))); + AEnv.showCenterScreen(new AboutBox(getFrame(c))); } else return false; @@ -658,7 +746,7 @@ public final class AEnv */ public static void addToWindowManager(CFrame frame) { - JFrame top = Env.getWindow(0); + JFrame top = getWindow(0); if (top instanceof AMenu) { ((AMenu)top).getWindowManager().add(frame); @@ -672,7 +760,7 @@ public final class AEnv */ public static AMenu getAMenu(CFrame frame) { - JFrame top = Env.getWindow(0); + JFrame top = getWindow(0); if (top instanceof AMenu) { return (AMenu)top; @@ -826,64 +914,6 @@ public final class AEnv return CConnection.get().getServerVersion(); } // getServerVersion - /** Window Cache */ - private static CCache s_windows - = new CCache("AD_Window", 10); - - /** - * Get Window Model - * - * @param WindowNo Window No - * @param AD_Window_ID window - * @param AD_Menu_ID menu - * @return Model Window Value Obkect - */ - public static GridWindowVO getMWindowVO (int WindowNo, int AD_Window_ID, int AD_Menu_ID) - { - log.config("Window=" + WindowNo + ", AD_Window_ID=" + AD_Window_ID); - GridWindowVO mWindowVO = null; - if (AD_Window_ID != 0 && Ini.isCacheWindow()) // try cache - { - mWindowVO = s_windows.get(AD_Window_ID); - if (mWindowVO != null) - { - mWindowVO = mWindowVO.clone(WindowNo); - log.info("Cached=" + mWindowVO); - } - } - - // Create Window Model on Client - if (mWindowVO == null) - { - log.config("create local"); - mWindowVO = GridWindowVO.create (Env.getCtx(), WindowNo, AD_Window_ID, AD_Menu_ID); - if (mWindowVO != null) - s_windows.put(AD_Window_ID, mWindowVO); - } // from Client - if (mWindowVO == null) - return null; - - // Check (remote) context - if (!mWindowVO.ctx.equals(Env.getCtx())) - { - // Remote Context is called by value, not reference - // Add Window properties to context - Enumeration keyEnum = mWindowVO.ctx.keys(); - while (keyEnum.hasMoreElements()) - { - String key = (String)keyEnum.nextElement(); - if (key.startsWith(WindowNo+"|")) - { - String value = mWindowVO.ctx.getProperty (key); - Env.setContext(Env.getCtx(), key, value); - } - } - // Sync Context - mWindowVO.setCtx(Env.getCtx()); - } - return mWindowVO; - } // getWindow - /** * Post Immediate * @param WindowNo window @@ -940,8 +970,8 @@ public final class AEnv */ public static void updateUI() { - Set updated = Env.updateUI(); - JFrame top = Env.getWindow(0); + Set updated = updateUI0(); + JFrame top = getWindow(0); if (top instanceof AMenu) { CFrame[] frames = ((AMenu)top).getWindowManager().getWindows(); @@ -1008,5 +1038,159 @@ public final class AEnv return result; } // canAccessInfo + + /** + * Update all windows after look and feel changes. + * @since 2006-11-27 + */ + public static SetupdateUI0() + { + Set updated = new HashSet(); + for (Container c : s_windows) + { + Window w = getFrame(c); + if (w == null) continue; + if (updated.contains(w)) continue; + SwingUtilities.updateComponentTreeUI(w); + w.validate(); + RepaintManager mgr = RepaintManager.currentManager(w); + Component childs[] = w.getComponents(); + for (Component child : childs) { + if (child instanceof JComponent) + mgr.markCompletelyDirty((JComponent)child); + } + w.repaint(); + updated.add(w); + } + for (Window w : s_hiddenWindows) + { + if (updated.contains(w)) continue; + SwingUtilities.updateComponentTreeUI(w); + w.validate(); + RepaintManager mgr = RepaintManager.currentManager(w); + Component childs[] = w.getComponents(); + for (Component child : childs) { + if (child instanceof JComponent) + mgr.markCompletelyDirty((JComponent)child); + } + w.repaint(); + updated.add(w); + } + return updated; + } + /** + * Add Container and return WindowNo. + * The container is a APanel, AWindow or JFrame/JDialog + * @param win window + * @return WindowNo used for context + */ + public static int createWindowNo(Container win) + { + int retValue = s_windows.size(); + s_windows.add(win); + return retValue; + } // createWindowNo + + /** + * Search Window by comparing the Frames + * @param container container + * @return WindowNo of container or 0 + */ + public static int getWindowNo (Container container) + { + if (container == null) + return 0; + JFrame winFrame = getFrame(container); + if (winFrame == null) + return 0; + + // loop through windows + for (int i = 0; i < s_windows.size(); i++) + { + Container cmp = (Container)s_windows.get(i); + if (cmp != null) + { + JFrame cmpFrame = getFrame(cmp); + if (winFrame.equals(cmpFrame)) + return i; + } + } + return 0; + } // getWindowNo + + /** + * Return the JFrame pointer of WindowNo - or null + * @param WindowNo window + * @return JFrame of WindowNo + */ + public static JFrame getWindow (int WindowNo) + { + JFrame retValue = null; + try + { + retValue = getFrame ((Container)s_windows.get(WindowNo)); + } + catch (Exception e) + { + log.log(Level.SEVERE, e.toString()); + } + return retValue; + } // getWindow + + /** + * Remove window from active list + * @param WindowNo window + */ + public static void removeWindow (int WindowNo) + { + if (WindowNo < s_windows.size()) + s_windows.set(WindowNo, null); + } // removeWindow + + /************************************************************************** + * Get Frame of Window + * @param container Container + * @return JFrame of container or null + */ + public static JFrame getFrame (Container container) + { + Container element = container; + while (element != null) + { + if (element instanceof JFrame) + return (JFrame)element; + element = element.getParent(); + } + return null; + } // getFrame + + public static void reset(boolean finalCall) + { + closeWindows(); + + // Dismantle windows + /** + for (int i = 0; i < s_windows.size(); i++) + { + Container win = (Container)s_windows.get(i); + if (win.getClass().getName().endsWith("AMenu")) // Null pointer + ; + else if (win instanceof Window) + ((Window)win).dispose(); + else + win.removeAll(); + } + **/ + //bug [ 1574630 ] + if (s_windows.size() > 0) { + if (!finalCall) { + Container c = s_windows.get(0); + s_windows.clear(); + createWindowNo(c); + } else { + s_windows.clear(); + } + } + } } // AEnv diff --git a/client/src/org/compiere/apps/ALogin.java b/client/src/org/compiere/apps/ALogin.java index 13ae81530d..4608a176a8 100644 --- a/client/src/org/compiere/apps/ALogin.java +++ b/client/src/org/compiere/apps/ALogin.java @@ -88,7 +88,7 @@ public final class ALogin extends CDialog super (parent, "Login", true); // Modal log.finer(""); setDefaultCloseOperation(DISPOSE_ON_CLOSE); - m_WindowNo = Env.createWindowNo (null); + m_WindowNo = AEnv.createWindowNo (null); res = ResourceBundle.getBundle(RESOURCE); // try diff --git a/client/src/org/compiere/apps/AMenu.java b/client/src/org/compiere/apps/AMenu.java index 58240cbb8e..7640eaa82a 100644 --- a/client/src/org/compiere/apps/AMenu.java +++ b/client/src/org/compiere/apps/AMenu.java @@ -62,6 +62,8 @@ import org.compiere.model.MSysConfig; import org.compiere.model.MSystem; import org.compiere.model.MTreeNode; import org.compiere.model.MUser; +import org.compiere.print.ReportCtl; +import org.compiere.print.SwingViewerProvider; import org.compiere.swing.CButton; import org.compiere.swing.CFrame; import org.compiere.swing.CPanel; @@ -70,6 +72,7 @@ import org.compiere.swing.CTabbedPane; import org.compiere.util.CLogger; import org.compiere.util.DB; import org.compiere.util.Env; +import org.compiere.util.IEnvEventListener; import org.compiere.util.Ini; import org.compiere.util.Language; import org.compiere.util.Msg; @@ -89,7 +92,7 @@ import org.compiere.util.Splash; * */ public final class AMenu extends CFrame - implements ActionListener, PropertyChangeListener, ChangeListener + implements ActionListener, PropertyChangeListener, ChangeListener, IEnvEventListener { /** * generated serialVersionUID @@ -109,7 +112,7 @@ public final class AMenu extends CFrame log.info("CodeBase=" + Adempiere.getCodeBase()); Splash splash = Splash.getSplash(); // - m_WindowNo = Env.createWindowNo(this); + m_WindowNo = AEnv.createWindowNo(this); // Login initSystem (splash); // login splash.setText(Msg.getMsg(m_ctx, "Loading")); @@ -189,6 +192,10 @@ public final class AMenu extends CFrame infoUpdaterThread = new Thread(infoUpdater, "InfoUpdater"); infoUpdaterThread.start(); // + Env.addEventListener(this); + // + ReportCtl.setReportViewerProvider(new SwingViewerProvider()); + // splash.dispose(); splash = null; } // AMenu @@ -810,4 +817,15 @@ public final class AMenu extends CFrame } } + + @Override + public void onClearWindowContext(int windowNo) { + AEnv.removeWindow(windowNo); + } + + @Override + public void onReset(boolean finalCall) { + AEnv.reset(finalCall); + } + } // AMenu diff --git a/client/src/org/compiere/apps/AMenuStartItem.java b/client/src/org/compiere/apps/AMenuStartItem.java index 7909f3de42..7f6640c7e1 100644 --- a/client/src/org/compiere/apps/AMenuStartItem.java +++ b/client/src/org/compiere/apps/AMenuStartItem.java @@ -226,7 +226,7 @@ public class AMenuStartItem extends Thread implements ActionListener */ private void startWindow(int AD_Workbench_ID, int AD_Window_ID) { - AWindow frame = (AWindow)Env.showWindow(AD_Window_ID); + AWindow frame = (AWindow)AEnv.showWindow(AD_Window_ID); if (frame != null) { m_menu.getWindowManager().add(frame); return; diff --git a/client/src/org/compiere/apps/APanel.java b/client/src/org/compiere/apps/APanel.java index 362612b883..bbc89d7344 100644 --- a/client/src/org/compiere/apps/APanel.java +++ b/client/src/org/compiere/apps/APanel.java @@ -462,7 +462,7 @@ public final class APanel extends CPanel } //Window - AMenu aMenu = (AMenu)Env.getWindow(0); + AMenu aMenu = (AMenu)AEnv.getWindow(0); m_WindowMenu = new WindowMenu(aMenu.getWindowManager(), m_window); menuBar.add(m_WindowMenu); aShowAllWindow = addAction("ShowAllWindow", null, KeyStroke.getKeyStroke(KeyEvent.VK_W, KeyEvent.CTRL_MASK), false); @@ -682,7 +682,7 @@ public final class APanel extends CPanel for (int wb = 0; wb < m_mWorkbench.getWindowCount(); wb++) { // Get/set WindowNo - m_curWindowNo = Env.createWindowNo (this); // Timing: ca. 1.5 sec + m_curWindowNo = AEnv.createWindowNo (this); // Timing: ca. 1.5 sec m_mWorkbench.setWindowNo(wb, m_curWindowNo); // Set AutoCommit for this Window Env.setAutoCommit(m_ctx, m_curWindowNo, Env.isAutoCommit(m_ctx)); @@ -717,7 +717,7 @@ public final class APanel extends CPanel { includedMap = new HashMap(4); // - GridWindowVO wVO = AEnv.getMWindowVO(m_curWindowNo, m_mWorkbench.getWindowID(wb), 0); + GridWindowVO wVO = Env.getMWindowVO(m_curWindowNo, m_mWorkbench.getWindowID(wb), 0); if (wVO == null) { ADialog.error(0, null, "AccessTableNoView", "(No Window Model Info)"); @@ -795,7 +795,7 @@ public final class APanel extends CPanel else // normal tab { GridController gc = new GridController(); // Timing: ca. .1 sec - CompiereColor cc = mWindow.getColor(); + CompiereColor cc = CompiereColor.getCompiereColor(mWindow.getColor()); if (cc != null) gc.setBackgroundColor(cc); // set color on Window level gc.initGrid(gTab, false, m_curWindowNo, this, mWindow, (tab != 0)); // will set color on Tab level @@ -1092,7 +1092,7 @@ public final class APanel extends CPanel if (require) { GridField[] findFields = mTab.getFields(); - Find find = new Find (Env.getFrame(this), m_curWindowNo, mTab.getName(), + Find find = new Find (AEnv.getFrame(this), m_curWindowNo, mTab.getName(), mTab.getAD_Tab_ID(), mTab.getAD_Table_ID(), mTab.getTableName(), where.toString(), findFields, 10); // no query below 10 query = find.getQuery(); @@ -1287,7 +1287,7 @@ public final class APanel extends CPanel { m_isLocked = busy; // - JFrame frame = Env.getFrame(this); + JFrame frame = AEnv.getFrame(this); if (frame == null) // during init return; if (frame instanceof AWindow) @@ -1722,7 +1722,7 @@ public final class APanel extends CPanel else if (cmd.equals(aHome.getName())) { // show main menu - teo_sarca [ 1706409, 1707221 ] setBusy(false, false); - AEnv.showWindow(Env.getWindow(0)); + AEnv.showWindow(AEnv.getWindow(0)); return; } else if (cmd.equals(aFirst.getName())) @@ -1821,7 +1821,7 @@ public final class APanel extends CPanel } // actionPerformed private void cmd_logout() { - JFrame top = Env.getWindow(0); + JFrame top = AEnv.getWindow(0); if (top instanceof AMenu) { ((AMenu)top).logout(); } @@ -2233,7 +2233,7 @@ public final class APanel extends CPanel pi.setAD_Client_ID (Env.getAD_Client_ID(m_ctx)); pi.setPrintPreview(printPreview); - ProcessCtl.process(this, m_curWindowNo, pi, null); // calls lockUI, unlockUI + ClientProcessCtrl.process(this, m_curWindowNo, pi, null); // calls lockUI, unlockUI statusBar.setStatusLine(pi.getSummary(), pi.isError()); } // cmd_print @@ -2247,7 +2247,7 @@ public final class APanel extends CPanel cmd_save(false); // Gets Fields from AD_Field_v GridField[] findFields = GridField.createFields(m_ctx, m_curWindowNo, 0, m_curTab.getAD_Tab_ID()); - Find find = new Find (Env.getFrame(this), m_curWindowNo, m_curTab.getName(), + Find find = new Find (AEnv.getFrame(this), m_curWindowNo, m_curTab.getName(), m_curTab.getAD_Tab_ID(), m_curTab.getAD_Table_ID(), m_curTab.getTableName(), m_curTab.getWhereExtended(), findFields, 1); MQuery query = find.getQuery(); @@ -2278,7 +2278,7 @@ public final class APanel extends CPanel } // Attachment va = - new Attachment (Env.getFrame(this), m_curWindowNo, + new Attachment (AEnv.getFrame(this), m_curWindowNo, m_curTab.getAD_AttachmentID(), m_curTab.getAD_Table_ID(), record_ID, null); // m_curTab.loadAttachments(); // reload @@ -2314,7 +2314,7 @@ public final class APanel extends CPanel String description = infoName + ": " + infoDisplay; // // AChat va = - new AChat (Env.getFrame(this), m_curWindowNo, + new AChat (AEnv.getFrame(this), m_curWindowNo, m_curTab.getCM_ChatID(), m_curTab.getAD_Table_ID(), record_ID, description, null); // @@ -2336,7 +2336,7 @@ public final class APanel extends CPanel // Control Pressed if ((m_lastModifiers & InputEvent.CTRL_MASK) != 0) { - new RecordAccessDialog(Env.getFrame(this), m_curTab.getAD_Table_ID(), record_ID); + new RecordAccessDialog(AEnv.getFrame(this), m_curTab.getAD_Table_ID(), record_ID); } else { @@ -2359,7 +2359,7 @@ public final class APanel extends CPanel Point pt = new Point (0, aHistory.getButton().getBounds().height); SwingUtilities.convertPointToScreen(pt, aHistory.getButton()); - VOnlyCurrentDays ocd = new VOnlyCurrentDays(Env.getFrame(this), pt); + VOnlyCurrentDays ocd = new VOnlyCurrentDays(AEnv.getFrame(this), pt); if (!ocd.isCancel()) { m_onlyCurrentDays = ocd.getCurrentDays(); if (m_onlyCurrentDays == 1) // Day @@ -2393,7 +2393,7 @@ public final class APanel extends CPanel private void cmd_help() { log.info(""); - Help hlp = new Help (Env.getFrame(this), this.getTitle(), m_mWorkbench.getMWindow(getWindowIndex())); + Help hlp = new Help (AEnv.getFrame(this), this.getTitle(), m_mWorkbench.getMWindow(getWindowIndex())); hlp.setVisible(true); } // cmd_help @@ -2409,7 +2409,7 @@ public final class APanel extends CPanel if (exit && ADialog.ask(m_curWindowNo, this, "ExitApplication?")) exitSystem = true; - Env.getFrame(this).dispose(); // calls this dispose + AEnv.getFrame(this).dispose(); // calls this dispose if (exitSystem) AEnv.exit(0); @@ -2656,14 +2656,14 @@ public final class APanel extends CPanel return; } else { - ProcessModalDialog dialog = new ProcessModalDialog(m_ctx, Env.getWindow(m_curWindowNo), Env.getHeader(m_ctx, m_curWindowNo), + ProcessModalDialog dialog = new ProcessModalDialog(m_ctx, AEnv.getWindow(m_curWindowNo), Env.getHeader(m_ctx, m_curWindowNo), this, m_curWindowNo, vButton.getProcess_ID(), table_ID, record_ID, startWOasking); if (dialog.isValidDialog()) { dialog.validate(); dialog.pack(); - AEnv.showCenterWindow(Env.getWindow(m_curWindowNo), dialog); + AEnv.showCenterWindow(AEnv.getWindow(m_curWindowNo), dialog); } } } // actionButton @@ -2874,5 +2874,4 @@ public final class APanel extends CPanel public boolean isNested() { return isNested; } - } // APanel diff --git a/client/src/org/compiere/apps/AWindow.java b/client/src/org/compiere/apps/AWindow.java index 2539eeaf81..416253ad0b 100644 --- a/client/src/org/compiere/apps/AWindow.java +++ b/client/src/org/compiere/apps/AWindow.java @@ -180,7 +180,7 @@ public class AWindow extends CFrame */ public void dispose() { - if (Env.hideWindow(this)) + if (AEnv.hideWindow(this)) return; log.info(toString()); if (m_APanel != null) diff --git a/client/src/org/compiere/apps/BeanShellEditor.java b/client/src/org/compiere/apps/BeanShellEditor.java index 7dabb3bcb1..58c799736c 100644 --- a/client/src/org/compiere/apps/BeanShellEditor.java +++ b/client/src/org/compiere/apps/BeanShellEditor.java @@ -111,7 +111,7 @@ public class BeanShellEditor extends CDialog implements ActionListener m_owner = owner; m_WindowNo = WindowNo; if (m_WindowNo == 0) - m_WindowNo = Env.createWindowNo(this); + m_WindowNo = AEnv.createWindowNo(this); log.info("Window=" + m_WindowNo); try { diff --git a/client/src/org/compiere/apps/ClientProcessCtrl.java b/client/src/org/compiere/apps/ClientProcessCtrl.java new file mode 100644 index 0000000000..8f39202729 --- /dev/null +++ b/client/src/org/compiere/apps/ClientProcessCtrl.java @@ -0,0 +1,95 @@ +package org.compiere.apps; + +import java.awt.Container; + +import org.compiere.model.MPInstance; +import org.compiere.process.ProcessInfo; +import org.compiere.util.ASyncProcess; +import org.compiere.util.CLogger; +import org.compiere.util.Env; +import org.compiere.util.Msg; +import org.compiere.util.Trx; + +public class ClientProcessCtrl { + + /** Static Logger */ + private static CLogger log = CLogger.getCLogger (ClientProcessCtrl.class); + + /** + * Process Control + * + * - Get Instance ID + * - Get Parameters + * - execute (lock - start process - unlock) + * + * Creates a ProcessCtl instance, which calls + * lockUI and unlockUI if parent is a ASyncProcess + *
+ * Called from APanel.cmd_print, APanel.actionButton and + * VPaySelect.cmd_generate + * + * @param parent ASyncProcess & Container + * @param WindowNo window no + * @param pi ProcessInfo process info + * @param trx Transaction + * @return worker started ProcessCtl instance or null for workflow + */ + public static ProcessCtl process (ASyncProcess parent, int WindowNo, ProcessInfo pi, Trx trx) + { + log.fine("WindowNo=" + WindowNo + " - " + pi); + + MPInstance instance = null; + try + { + instance = new MPInstance(Env.getCtx(), pi.getAD_Process_ID(), pi.getRecord_ID()); + } + catch (Exception e) + { + pi.setSummary (e.getLocalizedMessage()); + pi.setError (true); + log.warning(pi.toString()); + return null; + } + catch (Error e) + { + pi.setSummary (e.getLocalizedMessage()); + pi.setError (true); + log.warning(pi.toString()); + return null; + } + if (!instance.save()) + { + pi.setSummary (Msg.getMsg(Env.getCtx(), "ProcessNoInstance")); + pi.setError (true); + return null; + } + pi.setAD_PInstance_ID (instance.getAD_PInstance_ID()); + + // Get Parameters (Dialog) + ProcessParameter para = new ProcessParameter (AEnv.getFrame((Container)parent), WindowNo, pi); + if (para.initDialog()) + { + para.setVisible(true); + if (!para.isOK()) + { + pi.setSummary (Msg.getMsg(Env.getCtx(), "ProcessCancelled")); + pi.setError (true); + return null; + } + } + + // execute + ProcessCtl worker = new ProcessCtl(parent, WindowNo, pi, trx); + if (parent != null) + { + //asynchrous + worker.start(); + } + else + { + //synchrous + worker.run(); + } + return worker; + } // execute +} diff --git a/client/src/org/compiere/apps/FieldRecordInfo.java b/client/src/org/compiere/apps/FieldRecordInfo.java index 2306cba212..fb88a8dc26 100644 --- a/client/src/org/compiere/apps/FieldRecordInfo.java +++ b/client/src/org/compiere/apps/FieldRecordInfo.java @@ -355,7 +355,7 @@ public class FieldRecordInfo extends CDialog */ public static void start(GridField mField) { int WindowNo = mField.getWindowNo(); - Frame frame = Env.getWindow(WindowNo); + Frame frame = AEnv.getWindow(WindowNo); new FieldRecordInfo(frame, mField.getColumnName(), mField.getGridTab().getAD_Table_ID(), mField.getAD_Column_ID(), mField.getGridTab().getRecord_ID()); } diff --git a/client/src/org/compiere/apps/GroovyEditor.java b/client/src/org/compiere/apps/GroovyEditor.java index 3ef8b6fd25..53a781855e 100644 --- a/client/src/org/compiere/apps/GroovyEditor.java +++ b/client/src/org/compiere/apps/GroovyEditor.java @@ -101,7 +101,7 @@ public class GroovyEditor extends CDialog implements ActionListener m_owner = owner; m_WindowNo = WindowNo; if (m_WindowNo == 0) - m_WindowNo = Env.createWindowNo(this); + m_WindowNo = AEnv.createWindowNo(this); log.info("Window=" + m_WindowNo); try { diff --git a/client/src/org/compiere/apps/ProcessCtl.java b/client/src/org/compiere/apps/ProcessCtl.java index 1f1670d9c8..bf782f3f33 100644 --- a/client/src/org/compiere/apps/ProcessCtl.java +++ b/client/src/org/compiere/apps/ProcessCtl.java @@ -17,32 +17,17 @@ package org.compiere.apps; import java.awt.Container; -import java.io.InvalidClassException; -import java.lang.reflect.UndeclaredThrowableException; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.util.logging.Level; import javax.swing.JFrame; import javax.swing.SwingUtilities; -import org.adempiere.util.ProcessUtil; -import org.compiere.db.CConnection; -import org.compiere.interfaces.Server; import org.compiere.model.MPInstance; -import org.compiere.model.MRule; -import org.compiere.print.ReportCtl; -import org.compiere.process.ClientProcess; import org.compiere.process.ProcessInfo; -import org.compiere.process.ProcessInfoUtil; import org.compiere.util.ASyncProcess; import org.compiere.util.CLogger; -import org.compiere.util.DB; import org.compiere.util.Env; -import org.compiere.util.Ini; import org.compiere.util.Msg; import org.compiere.util.Trx; -import org.compiere.wf.MWFProcess; /** * Process Interface Controller. @@ -58,7 +43,7 @@ import org.compiere.wf.MWFProcess; *
  • FR [ 1807922 ] Pocess threads should have a better name *
  • BF [ 1960523 ] Server Process functionality not working */ -public class ProcessCtl implements Runnable +public class ProcessCtl extends AbstractProcessCtl { /** * Process Control @@ -111,7 +96,7 @@ public class ProcessCtl implements Runnable pi.setAD_PInstance_ID (instance.getAD_PInstance_ID()); // Get Parameters (Dialog) - ProcessParameter para = new ProcessParameter (Env.getFrame((Container)parent), WindowNo, pi); + ProcessParameter para = new ProcessParameter (AEnv.getFrame((Container)parent), WindowNo, pi); if (para.initDialog()) { para.setVisible(true); @@ -223,278 +208,54 @@ public class ProcessCtl implements Runnable */ public ProcessCtl (ASyncProcess parent, int WindowNo, ProcessInfo pi, Trx trx) { - windowno = WindowNo; - m_parent = parent; - m_pi = pi; - m_trx = trx; // handeled correctly + super(parent, WindowNo, pi, trx); } // ProcessCtl - /** Windowno */ - int windowno; - /** Parenr */ - ASyncProcess m_parent; - /** Process Info */ - ProcessInfo m_pi; - private Trx m_trx; private Waiting m_waiting; - private boolean m_IsServerProcess = false; /** Static Logger */ private static CLogger log = CLogger.getCLogger (ProcessCtl.class); - /** - * Run this process in a new thread - */ - public void start() - { - Thread thread = new Thread(this); - // Set thread name - teo_sarca FR [ 1807922 ] - if (m_pi != null) - thread.setName(m_pi.getTitle()+"-"+m_pi.getAD_PInstance_ID()); - thread.start(); - } - - /** - * Execute Process Instance and Lock UI. - * Calls lockUI and unlockUI if parent is a ASyncProcess - *
    -	 *		- Get Process Information
    -	 *      - Call Class
    -	 *		- Submit SQL Procedure
    -	 *		- Run SQL Procedure
    -	 *	
    - */ - public void run () - { - log.fine("AD_PInstance_ID=" + m_pi.getAD_PInstance_ID() - + ", Record_ID=" + m_pi.getRecord_ID()); - - // Lock - lock(); - // try {System.out.println(">> sleeping ..");sleep(20000);System.out.println(".. sleeping <<");} catch (Exception e) {} - - // Get Process Information: Name, Procedure Name, ClassName, IsReport, IsDirectPrint - String ProcedureName = ""; - String JasperReport = ""; - int AD_ReportView_ID = 0; - int AD_Workflow_ID = 0; - boolean IsReport = false; - boolean IsDirectPrint = false; - boolean isPrintPreview = m_pi.isPrintPreview(); - - // - String sql = "SELECT p.Name, p.ProcedureName,p.ClassName, p.AD_Process_ID," // 1..4 - + " p.isReport,p.IsDirectPrint,p.AD_ReportView_ID,p.AD_Workflow_ID," // 5..8 - + " CASE WHEN COALESCE(p.Statistic_Count,0)=0 THEN 0 ELSE p.Statistic_Seconds/p.Statistic_Count END CASE," - + " p.IsServerProcess, p.JasperReport " - + "FROM AD_Process p" - + " INNER JOIN AD_PInstance i ON (p.AD_Process_ID=i.AD_Process_ID) " - + "WHERE p.IsActive='Y'" - + " AND i.AD_PInstance_ID=?"; - if (!Env.isBaseLanguage(Env.getCtx(), "AD_Process")) - sql = "SELECT t.Name, p.ProcedureName,p.ClassName, p.AD_Process_ID," // 1..4 - + " p.isReport, p.IsDirectPrint,p.AD_ReportView_ID,p.AD_Workflow_ID," // 5..8 - + " CASE WHEN COALESCE(p.Statistic_Count,0)=0 THEN 0 ELSE p.Statistic_Seconds/p.Statistic_Count END CASE," - + " p.IsServerProcess, p.JasperReport " - + "FROM AD_Process p" - + " INNER JOIN AD_PInstance i ON (p.AD_Process_ID=i.AD_Process_ID) " - + " INNER JOIN AD_Process_Trl t ON (p.AD_Process_ID=t.AD_Process_ID" - + " AND t.AD_Language='" + Env.getAD_Language(Env.getCtx()) + "') " - + "WHERE p.IsActive='Y'" - + " AND i.AD_PInstance_ID=?"; - // - PreparedStatement pstmt = null; - ResultSet rs = null; - try - { - pstmt = DB.prepareStatement(sql, - ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, null); - pstmt.setInt(1, m_pi.getAD_PInstance_ID()); - rs = pstmt.executeQuery(); - if (rs.next()) - { - m_pi.setTitle (rs.getString(1)); - if (m_waiting != null) - m_waiting.setTitle(m_pi.getTitle()); - ProcedureName = rs.getString(2); - m_pi.setClassName (rs.getString(3)); - m_pi.setAD_Process_ID (rs.getInt(4)); - // Report - if ("Y".equals(rs.getString(5))) - { - IsReport = true; - if ("Y".equals(rs.getString(6)) && !Ini.isPropertyBool(Ini.P_PRINTPREVIEW) - && !isPrintPreview ) - IsDirectPrint = true; - } - AD_ReportView_ID = rs.getInt(7); - AD_Workflow_ID = rs.getInt(8); - // - int estimate = rs.getInt(9); - if (estimate != 0) - { - m_pi.setEstSeconds (estimate + 1); // admin overhead - if (m_waiting != null) - m_waiting.setTimerEstimate(m_pi.getEstSeconds()); - } - m_IsServerProcess = "Y".equals(rs.getString(10)); - JasperReport = rs.getString(11); - } - else - log.log(Level.SEVERE, "No AD_PInstance_ID=" + m_pi.getAD_PInstance_ID()); - } - catch (Throwable e) - { - m_pi.setSummary (Msg.getMsg(Env.getCtx(), "ProcessNoProcedure") + " " + e.getLocalizedMessage(), true); - unlock(); - log.log(Level.SEVERE, "run", e); - return; - } - finally - { - DB.close(rs, pstmt); - rs = null; pstmt = null; - } - - // No PL/SQL Procedure - if (ProcedureName == null) - ProcedureName = ""; - - - /********************************************************************** - * Workflow - */ - if (AD_Workflow_ID > 0) - { - startWorkflow (AD_Workflow_ID); - unlock(); - return; - } - - // Clear Jasper Report class if default - to be executed later - boolean isJasper = false; - if (JasperReport != null && JasperReport.trim().length() > 0) { - isJasper = true; - if (ProcessUtil.JASPER_STARTER_CLASS.equals(m_pi.getClassName())) { - m_pi.setClassName(null); - } - } - - /********************************************************************** - * Start Optional Class - */ - if (m_pi.getClassName() != null) - { - if (isJasper) - { - m_pi.setReportingProcess(true); - } - - // Run Class - if (!startProcess()) - { - unlock(); - return; - } - - // No Optional SQL procedure ... done - if (!IsReport && ProcedureName.length() == 0) - { - unlock (); - return; - } - // No Optional Report ... done - if (IsReport && AD_ReportView_ID == 0 && ! isJasper) - { - unlock (); - return; - } - } - - /********************************************************************** - * Report submission - */ - // Optional Pre-Report Process - if (IsReport && ProcedureName.length() > 0) - { - m_pi.setReportingProcess(true); - if (!startDBProcess(ProcedureName)) - { - unlock(); - return; - } - } // Pre-Report - - if (isJasper) - { - m_pi.setReportingProcess(true); - m_pi.setClassName(ProcessUtil.JASPER_STARTER_CLASS); - startProcess(); - unlock(); - return; - } - - if (IsReport) - { - m_pi.setReportingProcess(true); - // Start Report ----------------------------------------------- - boolean ok = ReportCtl.start(m_parent, windowno, m_pi, IsDirectPrint); - m_pi.setSummary("Report", !ok); - unlock (); - } - /********************************************************************** - * Process submission - */ - else - { - if (!startDBProcess (ProcedureName)) - { - unlock(); - return; - } - // Success - getResult - ProcessInfoUtil.setSummaryFromDB(m_pi); - unlock(); - } // *** Process submission *** - // log.fine(Log.l3_Util, "ProcessCtl.run - done"); - } // run - /** * Lock UI & show Waiting */ - private void lock () + protected void lock () { // log.info("..."); //m_parent is null for synchrous execution - if (m_parent != null) + if (getParent() != null) { - if (m_parent instanceof Container) + if (getParent() instanceof Container) { //swing client - JFrame frame = Env.getFrame((Container)m_parent); + JFrame frame = AEnv.getFrame((Container)getParent()); if (frame instanceof AWindow) - ((AWindow)frame).setBusyTimer(m_pi.getEstSeconds()); + ((AWindow)frame).setBusyTimer(getProcessInfo().getEstSeconds()); else - m_waiting = new Waiting (frame, Msg.getMsg(Env.getCtx(), "Processing"), false, m_pi.getEstSeconds()); - SwingUtilities.invokeLater(new Runnable() - { + m_waiting = new Waiting (frame, Msg.getMsg(Env.getCtx(), "Processing"), false, getProcessInfo().getEstSeconds()); + ProcessUpdateRunnable runnable = new ProcessUpdateRunnable() { + @Override public void run() { + if (m_waiting != null) + { + m_waiting.toFront(); + m_waiting.setVisible(true); + } + log.finer("lock"); - m_parent.lockUI(m_pi); + parent.lockUI(pi); } - }); - if (m_waiting != null) - { - m_waiting.toFront(); - m_waiting.setVisible(true); - } + }; + runnable.setParent(getParent()); + runnable.setProcessInfo(getProcessInfo()); + SwingUtilities.invokeLater(runnable); } else { //other client log.finer("lock"); - m_parent.lockUI(m_pi); + getParent().lockUI(getProcessInfo()); } } } // lock @@ -503,221 +264,69 @@ public class ProcessCtl implements Runnable * Unlock UI & dispose Waiting. * Called from run() */ - private void unlock () + protected void unlock () { // log.info("..."); - if (m_pi.isBatch()) - m_pi.setIsTimeout(true); - if (m_parent != null) + if (getProcessInfo().isBatch()) + getProcessInfo().setIsTimeout(true); + if (getParent() != null) { - if (m_parent instanceof Container) + if (getParent() instanceof Container) { - //swing client - SwingUtilities.invokeLater(new Runnable() + ProcessUpdateRunnable runnable = new ProcessUpdateRunnable() { + @Override public void run() { - String summary = m_pi.getSummary(); + // Remove Waiting/Processing Indicator + if (m_waiting != null) + m_waiting.dispose(); + m_waiting = null; + + String summary = pi.getSummary(); log.finer("unlock - " + summary); if (summary != null && summary.indexOf('@') != -1) - m_pi.setSummary(Msg.parseTranslation(Env.getCtx(), summary)); - m_parent.unlockUI(m_pi); - } - }); - // Remove Waiting/Processing Indicator - if (m_waiting != null) - m_waiting.dispose(); - m_waiting = null; + pi.setSummary(Msg.parseTranslation(Env.getCtx(), summary)); + parent.unlockUI(pi); + } + }; + runnable.setParent(getParent()); + runnable.setProcessInfo(getProcessInfo()); + SwingUtilities.invokeLater(runnable); } else { //other client - m_parent.unlockUI(m_pi); + getParent().unlockUI(getProcessInfo()); } } } // unlock - - /************************************************************************** - * Start Workflow. - * - * @param AD_Workflow_ID workflow - * @return true if started - */ - private boolean startWorkflow (int AD_Workflow_ID) - { - log.fine(AD_Workflow_ID + " - " + m_pi); - boolean started = false; - if (m_IsServerProcess) - { - Server server = CConnection.get().getServer(); - try - { - if (server != null) - { // See ServerBean - m_pi = server.workflow (Env.getRemoteCallCtx(Env.getCtx()), m_pi, AD_Workflow_ID); - log.finest("server => " + m_pi); - started = true; - } - } - catch (Exception ex) - { - log.log(Level.SEVERE, "AppsServer error", ex); - started = false; - } - } - // Run locally - if (!started && !m_IsServerProcess) - { - if (m_trx != null) - m_pi.setTransactionName(m_trx.getTrxName()); - MWFProcess wfProcess = ProcessUtil.startWorkFlow(Env.getCtx(), m_pi, AD_Workflow_ID); - started = wfProcess != null; - } - return started; - } // startWorkflow + @Override + protected void updateProgressWindowTimerEstimate(int estSeconds) { + if (m_waiting != null) + m_waiting.setTimerEstimate(getProcessInfo().getEstSeconds()); + } - /************************************************************************** - * Start Java Process Class. - * instanciate the class implementing the interface ProcessCall. - * The class can be a Server/Client class (when in Package - * org adempiere.process or org.compiere.model) or a client only class - * (e.g. in org.compiere.report) - * - * @return true if success - */ - private boolean startProcess () + @Override + protected void updateProgressWindowTitle(String title) { + if (m_waiting != null) + m_waiting.setTitle(getProcessInfo().getTitle()); + } + + abstract class ProcessUpdateRunnable implements Runnable { - log.fine(m_pi.toString()); - boolean started = false; + protected ProcessInfo pi = null; + protected ASyncProcess parent = null; - //hengsin, bug [ 1633995 ] - boolean clientOnly = false; - if (! m_pi.getClassName().toLowerCase().startsWith(MRule.SCRIPT_PREFIX)) { - try { - Class processClass = Class.forName(m_pi.getClassName()); - if (ClientProcess.class.isAssignableFrom(processClass)) - clientOnly = true; - } catch (Exception e) {} + public void setProcessInfo(ProcessInfo pi) + { + this.pi = pi; } - if (m_IsServerProcess && !clientOnly) + public void setParent(ASyncProcess parent) { - Server server = CConnection.get().getServer(); - try - { - if (server != null) - { - // See ServerBean - m_pi = server.process (Env.getRemoteCallCtx(Env.getCtx()), m_pi); - log.finest("server => " + m_pi); - started = true; - } - } - catch (UndeclaredThrowableException ex) - { - Throwable cause = ex.getCause(); - if (cause != null) - { - if (cause instanceof InvalidClassException) - log.log(Level.SEVERE, "Version Server <> Client: " - + cause.toString() + " - " + m_pi, ex); - else - log.log(Level.SEVERE, "AppsServer error(1b): " - + cause.toString() + " - " + m_pi, ex); - } - else - log.log(Level.SEVERE, " AppsServer error(1) - " - + m_pi, ex); - started = false; - } - catch (Exception ex) - { - Throwable cause = ex.getCause(); - if (cause == null) - cause = ex; - log.log(Level.SEVERE, "AppsServer error - " + m_pi, cause); - started = false; - } + this.parent = parent; } - // Run locally - if (!started && (!m_IsServerProcess || clientOnly )) - { - if (m_pi.getClassName().toLowerCase().startsWith(MRule.SCRIPT_PREFIX)) { - return ProcessUtil.startScriptProcess(Env.getCtx(), m_pi, m_trx); - } else { - return ProcessUtil.startJavaProcess(Env.getCtx(), m_pi, m_trx); - } - } - return !m_pi.isError(); - } // startProcess - - - /************************************************************************** - * Start Database Process - * @param ProcedureName PL/SQL procedure name - * @return true if success - */ - private boolean startDBProcess (String ProcedureName) - { - // execute on this thread/connection - log.fine(ProcedureName + "(" + m_pi.getAD_PInstance_ID() + ")"); - boolean started = false; - String trxName = m_trx != null ? m_trx.getTrxName() : null; - if (m_IsServerProcess) - { - Server server = CConnection.get().getServer(); - try - { - if (server != null) - { // See ServerBean - m_pi = server.dbProcess(m_pi, ProcedureName); - log.finest("server => " + m_pi); - started = true; - } - } - catch (UndeclaredThrowableException ex) - { - Throwable cause = ex.getCause(); - if (cause != null) - { - if (cause instanceof InvalidClassException) - log.log(Level.SEVERE, "Version Server <> Client: " - + cause.toString() + " - " + m_pi, ex); - else - log.log(Level.SEVERE, "AppsServer error(1b): " - + cause.toString() + " - " + m_pi, ex); - } - else - { - log.log(Level.SEVERE, " AppsServer error(1) - " - + m_pi, ex); - cause = ex; - } - m_pi.setSummary (Msg.getMsg(Env.getCtx(), "ProcessRunError") + " " + cause.getLocalizedMessage()); - m_pi.setError (true); - return false; - } - catch (Exception ex) - { - Throwable cause = ex.getCause(); - if (cause == null) - cause = ex; - log.log(Level.SEVERE, "AppsServer error - " + m_pi, cause); - m_pi.setSummary (Msg.getMsg(Env.getCtx(), "ProcessRunError") + " " + cause.getLocalizedMessage()); - m_pi.setError (true); - return false; - } - } - - //try locally - if (!started) - { - return ProcessUtil.startDatabaseProcedure(m_pi, ProcedureName, m_trx); - } - // log.fine(Log.l4_Data, "ProcessCtl.startProcess - done"); - return true; - } // startDBProcess - - + } } // ProcessCtl diff --git a/client/src/org/compiere/apps/ProcessDialog.java b/client/src/org/compiere/apps/ProcessDialog.java index 907dfcbd10..946032a84c 100644 --- a/client/src/org/compiere/apps/ProcessDialog.java +++ b/client/src/org/compiere/apps/ProcessDialog.java @@ -100,7 +100,7 @@ public class ProcessDialog extends CFrame log.info("Process=" + AD_Process_ID + "; SOTrx=" + isSOTrx); enableEvents(AWTEvent.WINDOW_EVENT_MASK); m_AD_Process_ID = AD_Process_ID; - m_WindowNo = Env.createWindowNo (this); + m_WindowNo = AEnv.createWindowNo (this); Env.setContext(Env.getCtx(), m_WindowNo, "IsSOTrx", isSOTrx ? "Y" : "N"); try { @@ -468,7 +468,7 @@ public class ProcessDialog extends CFrame for (int i = 0; i < m_ids.length; i++) { int M_InOut_ID = m_ids[i]; - ReportCtl.startDocumentPrint(ReportEngine.SHIPMENT, M_InOut_ID, this, Env.getWindowNo(this), true); + ReportCtl.startDocumentPrint(ReportEngine.SHIPMENT, M_InOut_ID, this, AEnv.getWindowNo(this), true); } ADialogDialog d = new ADialogDialog (this, Env.getHeader(Env.getCtx(), m_WindowNo), @@ -497,7 +497,7 @@ public class ProcessDialog extends CFrame for (int i = 0; i < m_ids.length; i++) { int AD_Invoice_ID = m_ids[i]; - ReportCtl.startDocumentPrint(ReportEngine.INVOICE, AD_Invoice_ID, this, Env.getWindowNo(this), true); + ReportCtl.startDocumentPrint(ReportEngine.INVOICE, AD_Invoice_ID, this, AEnv.getWindowNo(this), true); } ADialogDialog d = new ADialogDialog (this, Env.getHeader(Env.getCtx(), m_WindowNo), diff --git a/client/src/org/compiere/apps/StatusBar.java b/client/src/org/compiere/apps/StatusBar.java index 7f1d394e8d..ffd41e1128 100644 --- a/client/src/org/compiere/apps/StatusBar.java +++ b/client/src/org/compiere/apps/StatusBar.java @@ -262,7 +262,7 @@ public class StatusBar extends CPanel implements IStatusBar return; // String title = Msg.getMsg(Env.getCtx(), "Who") + m_text; - RecordInfo info = new RecordInfo (Env.getFrame(this), title, m_dse); + RecordInfo info = new RecordInfo (AEnv.getFrame(this), title, m_dse); AEnv.showCenterScreen(info); } // addStatusComponent diff --git a/client/src/org/compiere/apps/WindowMenu.java b/client/src/org/compiere/apps/WindowMenu.java index 6ac59f1802..6021afef24 100644 --- a/client/src/org/compiere/apps/WindowMenu.java +++ b/client/src/org/compiere/apps/WindowMenu.java @@ -266,7 +266,7 @@ public class WindowMenu extends JMenu { } if ( !(frame instanceof AMenu) ) { - JFrame frame = Env.getWindow(0); + JFrame frame = AEnv.getWindow(0); if (frame != null && frame instanceof AMenu) { menu = new ChildMenuItem((AMenu)frame); menu.setState(false); @@ -338,7 +338,7 @@ public class WindowMenu extends JMenu { int width = ( s.width - 30 ) / 3; int height = ( s.height - 30 ) / 3; int count = 0; - JFrame frame = Env.getWindow(0); + JFrame frame = AEnv.getWindow(0); if (frame != null && frame instanceof AMenu) { JXTitledPanel box = createImageBox(p, dialog, width, height, (CFrame)frame); diff --git a/client/src/org/compiere/apps/form/FormFrame.java b/client/src/org/compiere/apps/form/FormFrame.java index ef48824de4..fdf0b4c9f9 100644 --- a/client/src/org/compiere/apps/form/FormFrame.java +++ b/client/src/org/compiere/apps/form/FormFrame.java @@ -93,7 +93,7 @@ public class FormFrame extends CFrame } }); - m_WindowNo = Env.createWindowNo (this); + m_WindowNo = AEnv.createWindowNo (this); setGlassPane(m_glassPane); try { @@ -219,7 +219,7 @@ public class FormFrame extends CFrame } // Window - AMenu aMenu = (AMenu)Env.getWindow(0); + AMenu aMenu = (AMenu)AEnv.getWindow(0); JMenu mWindow = new WindowMenu(aMenu.getWindowManager(), this); menuBar.add(mWindow); @@ -367,7 +367,7 @@ public class FormFrame extends CFrame sb.append("

    ").append(m_Description).append("

    "); if (m_Help != null && m_Help.length() > 0) sb.append("

    ").append(m_Help); - Help hlp = new Help (Env.getFrame(this), this.getTitle(), sb.toString()); + Help hlp = new Help (AEnv.getFrame(this), this.getTitle(), sb.toString()); hlp.setVisible(true); } // actionHelp diff --git a/client/src/org/compiere/apps/form/FormPanel.java b/client/src/org/compiere/apps/form/FormPanel.java index f0adf52f76..dae1ca1b5d 100644 --- a/client/src/org/compiere/apps/form/FormPanel.java +++ b/client/src/org/compiere/apps/form/FormPanel.java @@ -16,7 +16,6 @@ *****************************************************************************/ package org.compiere.apps.form; -import org.adempiere.base.IService; /** * Form Panel Interface. @@ -24,7 +23,7 @@ import org.adempiere.base.IService; * @author Jorg Janke * @version $Id: FormPanel.java,v 1.2 2006/07/30 00:51:28 jjanke Exp $ */ -public interface FormPanel extends IService +public interface FormPanel { /** * Initialize Panel diff --git a/client/src/org/compiere/apps/form/VGenPanel.java b/client/src/org/compiere/apps/form/VGenPanel.java index 918ef527a9..34df10603d 100644 --- a/client/src/org/compiere/apps/form/VGenPanel.java +++ b/client/src/org/compiere/apps/form/VGenPanel.java @@ -30,6 +30,7 @@ import javax.swing.event.TableModelListener; import org.adempiere.plaf.AdempierePLAF; import org.compiere.apps.ADialog; import org.compiere.apps.ADialogDialog; +import org.compiere.apps.AEnv; import org.compiere.apps.ConfirmPanel; import org.compiere.apps.ProcessCtl; import org.compiere.apps.StatusBar; @@ -243,7 +244,7 @@ public class VGenPanel extends CPanel implements ActionListener, ChangeListener, public void generate() { info.setText(genForm.generate()); - ProcessCtl worker = new ProcessCtl(this, Env.getWindowNo(this), genForm.getProcessInfo(), genForm.getTrx()); + ProcessCtl worker = new ProcessCtl(this, AEnv.getWindowNo(this), genForm.getProcessInfo(), genForm.getTrx()); worker.start(); // } @@ -306,7 +307,7 @@ public class VGenPanel extends CPanel implements ActionListener, ChangeListener, new Viewer(m_frame.getGraphicsConfiguration(), re); } else - ReportCtl.startDocumentPrint(genForm.getReportEngineType(), Record_ID, this, Env.getWindowNo(this), true); + ReportCtl.startDocumentPrint(genForm.getReportEngineType(), Record_ID, this, AEnv.getWindowNo(this), true); } ADialogDialog d = new ADialogDialog (m_frame, diff --git a/client/src/org/compiere/apps/form/VPayPrint.java b/client/src/org/compiere/apps/form/VPayPrint.java index eba87abe79..1ecf7f2c08 100644 --- a/client/src/org/compiere/apps/form/VPayPrint.java +++ b/client/src/org/compiere/apps/form/VPayPrint.java @@ -31,6 +31,7 @@ import javax.swing.JButton; import javax.swing.JFileChooser; import org.compiere.apps.ADialog; +import org.compiere.apps.AEnv; import org.compiere.apps.ConfirmPanel; import org.compiere.grid.ed.VNumber; import org.compiere.model.MPaySelectionCheck; @@ -389,7 +390,7 @@ public class VPayPrint extends PayPrint implements FormPanel, ActionListener { MPaySelectionCheck check = m_checks[i]; // ReportCtrl will check BankAccountDoc for PrintFormat - boolean ok = ReportCtl.startDocumentPrint(ReportEngine.CHECK, check.get_ID(), null, Env.getWindowNo(panel), directPrint); + boolean ok = ReportCtl.startDocumentPrint(ReportEngine.CHECK, check.get_ID(), null, AEnv.getWindowNo(panel), directPrint); if (!somethingPrinted && ok) somethingPrinted = true; } @@ -413,7 +414,7 @@ public class VPayPrint extends PayPrint implements FormPanel, ActionListener for (int i = 0; i < m_checks.length; i++) { MPaySelectionCheck check = m_checks[i]; - ReportCtl.startDocumentPrint(ReportEngine.REMITTANCE, check.get_ID(), null, Env.getWindowNo(panel), directPrint); + ReportCtl.startDocumentPrint(ReportEngine.REMITTANCE, check.get_ID(), null, AEnv.getWindowNo(panel), directPrint); } } // remittance diff --git a/client/src/org/compiere/apps/search/VSchedulePanel.java b/client/src/org/compiere/apps/search/VSchedulePanel.java index 41c77b4920..83dfcb49ab 100644 --- a/client/src/org/compiere/apps/search/VSchedulePanel.java +++ b/client/src/org/compiere/apps/search/VSchedulePanel.java @@ -37,6 +37,7 @@ import java.util.GregorianCalendar; import javax.swing.JComponent; +import org.compiere.apps.AEnv; import org.compiere.grid.ed.VAssignmentDialog; import org.compiere.model.MAssignmentSlot; import org.compiere.model.MResourceAssignment; @@ -378,7 +379,7 @@ public class VSchedulePanel extends JComponent implements MouseListener if (!mas.isAssignment()) return; // - VAssignmentDialog vad = new VAssignmentDialog (Env.getFrame(this), + VAssignmentDialog vad = new VAssignmentDialog (AEnv.getFrame(this), m_slots[i].getMAssignment(), false, m_createNew); m_infoSchedule.mAssignmentCallback(vad.getMResourceAssignment()); return; @@ -391,7 +392,7 @@ public class VSchedulePanel extends JComponent implements MouseListener ma.setAssignDateFrom(TimeUtil.getDayTime(TimeUtil.addDays(m_startDate, dayIndex), m_timePanel.getTimeSlot(timeIndex).getStartTime())); ma.setQty(new BigDecimal(1)); - VAssignmentDialog vad = new VAssignmentDialog (Env.getFrame(this), ma, false, m_createNew); + VAssignmentDialog vad = new VAssignmentDialog (AEnv.getFrame(this), ma, false, m_createNew); m_infoSchedule.mAssignmentCallback(vad.getMResourceAssignment()); return; } diff --git a/client/src/org/compiere/apps/wf/NodeMenu.java b/client/src/org/compiere/apps/wf/NodeMenu.java new file mode 100644 index 0000000000..ff633a6e8b --- /dev/null +++ b/client/src/org/compiere/apps/wf/NodeMenu.java @@ -0,0 +1,113 @@ +/** + * + */ +package org.compiere.apps.wf; + +import java.awt.Point; + +import javax.swing.JPopupMenu; + +import org.compiere.util.Env; +import org.compiere.util.Msg; +import org.compiere.wf.MWFNode; +import org.compiere.wf.MWFNodeNext; +import org.compiere.wf.MWorkflow; +import org.netbeans.api.visual.action.PopupMenuProvider; +import org.netbeans.api.visual.widget.Widget; + +/** + * @author hengsin + * + */ +public class NodeMenu implements PopupMenuProvider { + + private WFContentPanel panel; + private MWorkflow m_wf; + + /** + * + */ + public NodeMenu(WFContentPanel panel, MWorkflow wf) { + this.panel = panel; + m_wf = wf; + } + + /* (non-Javadoc) + * @see org.netbeans.api.visual.action.PopupMenuProvider#getPopupMenu(org.netbeans.api.visual.widget.Widget, java.awt.Point) + */ + public JPopupMenu getPopupMenu(Widget w, Point p) { + WFNodeWidget widget = (WFNodeWidget) w; + MWFNode node = widget.getModel(); + JPopupMenu m_LinePopupMenu = new JPopupMenu(node.getName()); + if (node.getAD_Client_ID() == Env.getAD_Client_ID(Env.getCtx())) + { + String title = Msg.getMsg(Env.getCtx(), "DeleteNode") + + ": " + node.getName(); + addMenuItem(m_LinePopupMenu, title, node, -1); + m_LinePopupMenu.addSeparator(); + } + MWFNode[] nodes = m_wf.getNodes(true, Env.getAD_Client_ID(Env.getCtx())); + MWFNodeNext[] lines = node.getTransitions(Env.getAD_Client_ID(Env.getCtx())); + // Add New Line + for (int n = 0; n < nodes.length; n++) + { + MWFNode nn = nodes[n]; + if (nn.getAD_WF_Node_ID() == node.getAD_WF_Node_ID()) + continue; // same + boolean found = false; + for (int i = 0; i < lines.length; i++) + { + MWFNodeNext line = lines[i]; + if (nn.getAD_WF_Node_ID() == line.getAD_WF_Next_ID()) + { + found = true; + break; + } + } + if (!found) + { + String title = Msg.getMsg(Env.getCtx(), "AddLine") + + ": " + node.getName() + " -> " + nn.getName(); + addMenuItem(m_LinePopupMenu, title, node, nn.getAD_WF_Node_ID()); + } + } + m_LinePopupMenu.addSeparator(); + // Delete Lines + for (int i = 0; i < lines.length; i++) + { + MWFNodeNext line = lines[i]; + if (line.getAD_Client_ID() != Env.getAD_Client_ID(Env.getCtx())) + continue; + MWFNode next = MWFNode.get(Env.getCtx(), line.getAD_WF_Next_ID()); + String title = Msg.getMsg(Env.getCtx(), "DeleteLine") + + ": " + node.getName() + " -> " + next.getName(); + addMenuItem(m_LinePopupMenu, title, line); + } + return m_LinePopupMenu; + } + + /** + * Add Menu Item to - add new line to node + * @param menu base menu + * @param title title + */ + private void addMenuItem (JPopupMenu menu, String title, MWFNode node, int AD_WF_NodeTo_ID) + { + WFPopupItem item = new WFPopupItem (title, node, AD_WF_NodeTo_ID); + menu.add(item); + item.addActionListener(panel); + } // addMenuItem + + /** + * Add Menu Item to - delete line + * @param menu base menu + * @param title title + */ + private void addMenuItem (JPopupMenu menu, String title, MWFNodeNext line) + { + WFPopupItem item = new WFPopupItem (title, line); + menu.add(item); + item.addActionListener(panel); + } // addMenuItem + +} diff --git a/client/src/org/compiere/apps/wf/SceneMainMenu.java b/client/src/org/compiere/apps/wf/SceneMainMenu.java new file mode 100644 index 0000000000..be21c54f14 --- /dev/null +++ b/client/src/org/compiere/apps/wf/SceneMainMenu.java @@ -0,0 +1,44 @@ +/** + * + */ +package org.compiere.apps.wf; + +import java.awt.Point; + +import javax.swing.JPopupMenu; + +import org.compiere.swing.CMenuItem; +import org.compiere.util.Env; +import org.compiere.util.Msg; +import org.netbeans.api.visual.action.PopupMenuProvider; +import org.netbeans.api.visual.widget.Widget; + +/** + * @author hengsin + * + */ +public class SceneMainMenu implements PopupMenuProvider { + + private JPopupMenu m_NewPopupMenu = new JPopupMenu(); + private CMenuItem m_NewMenuNode = new CMenuItem(Msg.getMsg(Env.getCtx(), "CreateNewNode")); + + public static final String ADD_NEW_NODE_ACTION = "addNewNodeAction"; + + /** + * @param wfContentPanel + * + */ + public SceneMainMenu(WFContentPanel wfContentPanel) { + m_NewMenuNode.setActionCommand(ADD_NEW_NODE_ACTION); + m_NewMenuNode.addActionListener(wfContentPanel); + m_NewPopupMenu.add(m_NewMenuNode); + } + + /* (non-Javadoc) + * @see org.netbeans.api.visual.action.PopupMenuProvider#getPopupMenu(org.netbeans.api.visual.widget.Widget, java.awt.Point) + */ + public JPopupMenu getPopupMenu(Widget arg0, Point arg1) { + return m_NewPopupMenu; + } + +} diff --git a/client/src/org/compiere/apps/wf/WFContentPanel.java b/client/src/org/compiere/apps/wf/WFContentPanel.java index 9c09e10568..0c135014f3 100644 --- a/client/src/org/compiere/apps/wf/WFContentPanel.java +++ b/client/src/org/compiere/apps/wf/WFContentPanel.java @@ -1,597 +1,221 @@ -/****************************************************************************** - * Product: Adempiere ERP & CRM Smart Business Solution * - * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * - * This program is free software; you can redistribute it and/or modify it * - * under the terms version 2 of the GNU General Public License as published * - * by the Free Software Foundation. This program is distributed in the hope * - * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * - * See the GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License along * - * with this program; if not, write to the Free Software Foundation, Inc., * - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * - * For the text or an alternative of this public license, you may reach us * - * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * - * or via info@compiere.org or http://www.compiere.org/license.html * - *****************************************************************************/ -package org.compiere.apps.wf; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.MouseMotionListener; -import java.awt.font.TextLayout; -import java.util.ArrayList; - -import javax.swing.JMenuItem; -import javax.swing.JOptionPane; -import javax.swing.JPopupMenu; -import javax.swing.SwingUtilities; - -import org.compiere.swing.CMenuItem; -import org.compiere.swing.CPanel; -import org.compiere.util.CLogger; -import org.compiere.util.Env; -import org.compiere.util.Msg; -import org.compiere.util.Util; -import org.compiere.wf.MWFNode; -import org.compiere.wf.MWFNodeNext; -import org.compiere.wf.MWorkflow; - -/** - * Workflow Content Panel. - * - * - * @author Jorg Janke - * @version $Id: WFContentPanel.java,v 1.2 2006/07/30 00:51:28 jjanke Exp $ - */ -public class WFContentPanel extends CPanel - implements MouseListener, MouseMotionListener, ActionListener -{ - /** - * - */ - private static final long serialVersionUID = 4868946962536126669L; - - /** - * WFContentPanel - */ - public WFContentPanel (WFPanel parent) - { - super (new WFLayoutManager()); - m_parent = parent; - // setBorder (BorderFactory.createEmptyBorder(5,5,5,5)); - // setBackground(Color.red); - // setBackground(new Color(236,236,236)); - // setOpaque(false); - // - m_NewPopupMenu.add(m_NewMenuNode); - m_NewMenuNode.addActionListener(this); - } // WFContentPanel - - private WFPanel m_parent = null; - /** Logger */ - private static CLogger log = CLogger.getCLogger(WFContentPanel.class); - /** Node List */ - private ArrayList m_nodes = new ArrayList(); - /** Line List */ - private ArrayList m_lines = new ArrayList(); - /** Last Pressed Point */ - private Point m_draggedStart = null; - /** Last Dragged Node */ - private WFNode m_draggedNode = null; - /** Dragged */ - private boolean m_dragged = false; - - /** ReadWrite */ - private boolean m_readWrite = false; - /** The Workflow */ - private MWorkflow m_wf = null; - - private JPopupMenu m_NewPopupMenu = new JPopupMenu(); - private CMenuItem m_NewMenuNode = new CMenuItem(Msg.getMsg(Env.getCtx(), "CreateNewNode")); - - private JPopupMenu m_LinePopupMenu = null; - - /** - * Set Read/Write - * @param readWrite read/write - */ - public void setReadWrite (boolean readWrite) - { - m_readWrite = readWrite; - if (m_readWrite) - addMouseListener(this); - else - removeMouseListener(this); - } // setReadWrite - - /** - * Set Workflow - * @param wf workflow - */ - public void setWorkflow (MWorkflow wf) - { - m_wf = wf; - } // setWorkflow - - - /** - * Remove All and their listeners - */ - public void removeAll () - { - m_nodes.clear(); - m_lines.clear(); - Component[] components = getComponents(); - for (int i = 0; i < components.length; i++) - { - Component component = components[i]; - component.removeMouseListener(this); - component.removeMouseMotionListener(this); - } - super.removeAll (); - } // removeAll - - - /** - * Add Component and add Mouse Listener - * @param comp component - * @param rw read/write - * @return component - */ - public Component add (Component comp, boolean rw) - { - // Line - if (comp instanceof WFLine) - { - m_lines.add((WFLine)comp); - return comp; - } - // Node - if (comp instanceof WFNode) - { - m_nodes.add((WFNode)comp); - comp.addMouseListener(this); - if (m_readWrite && rw) // can be moved - comp.addMouseMotionListener(this); - } - return super.add (comp); - } // add - - /** - * Create Lines. - * Called by WF Layout Manager - */ - protected void createLines() - { - log.fine("Lines #" + m_lines.size()); - for (int i = 0; i < m_lines.size(); i++) - { - WFLine line = (WFLine)m_lines.get(i); - Rectangle from = findBounds (line.getAD_WF_Node_ID()); - Rectangle to = findBounds (line.getAD_WF_Next_ID()); - line.setFromTo(from, to); - // same bounds as parent - // line.setBounds(0,0, width, height); - } // for all lines - } - - /** - * Get Bounds of WF Node Icon - * @param AD_WF_Node_ID node id - * @return bounds of node with ID or null - */ - private Rectangle findBounds (int AD_WF_Node_ID) - { - for (int i = 0; i < m_nodes.size(); i++) - { - WFNode node = (WFNode)m_nodes.get(i); - if (node.getAD_WF_Node_ID() == AD_WF_Node_ID) - return node.getBounds(); - } - return null; - } // findBounds - - - /** - * Get Component At point - * @param p point - * @return Node (ignore lines) - */ - public Component getComponentAt (Point p) - { - return getComponentAt (p.x, p.y); - } // getComponentAt - - /** - * Get Node at x/y - * @param x x - * @param y y - * @return Node (ignore lines) - */ - public Component getComponentAt (int x, int y) - { - Component comp = super.getComponentAt (x, y); - if (comp instanceof WFNode) - return comp; - for (int i = 0; i < m_nodes.size(); i++) - { - WFNode node = (WFNode)m_nodes.get(i); - int xx = x - node.getX(); - int yy = y - node.getY(); - if (node.contains(xx, yy)) - return node; - } - return comp; - } // getComponentAt - - - /************************************************************************** - * Mouse Clicked. - * Pressed - Released - Clicked. - * @param e event - */ - public void mouseClicked (MouseEvent e) - { - if (m_readWrite && SwingUtilities.isRightMouseButton(e)) - { - int AD_Client_ID = Env.getAD_Client_ID(Env.getCtx()); - if (e.getSource() == this && m_wf != null) - { - m_NewPopupMenu.show(this, e.getX(), e.getY()); - } - else if (e.getSource() instanceof WFNode) - { - MWFNode node = ((WFNode)e.getSource()).getModel(); - m_LinePopupMenu = new JPopupMenu(node.getName()); - if (node.getAD_Client_ID() == AD_Client_ID) - { - String title = Msg.getMsg(Env.getCtx(), "DeleteNode") + - ": " + node.getName(); - addMenuItem(m_LinePopupMenu, title, node, -1); - m_LinePopupMenu.addSeparator(); - } - MWFNode[] nodes = m_wf.getNodes(true, AD_Client_ID); - MWFNodeNext[] lines = node.getTransitions(AD_Client_ID); - // Add New Line - for (int n = 0; n < nodes.length; n++) - { - MWFNode nn = nodes[n]; - if (nn.getAD_WF_Node_ID() == node.getAD_WF_Node_ID()) - continue; // same - boolean found = false; - for (int i = 0; i < lines.length; i++) - { - MWFNodeNext line = lines[i]; - if (nn.getAD_WF_Node_ID() == line.getAD_WF_Next_ID()) - { - found = true; - break; - } - } - if (!found) - { - String title = Msg.getMsg(Env.getCtx(), "AddLine") - + ": " + node.getName() + " -> " + nn.getName(); - addMenuItem(m_LinePopupMenu, title, node, nn.getAD_WF_Node_ID()); - } - } - m_LinePopupMenu.addSeparator(); - // Delete Lines - for (int i = 0; i < lines.length; i++) - { - MWFNodeNext line = lines[i]; - if (line.getAD_Client_ID() != AD_Client_ID) - continue; - MWFNode next = MWFNode.get(Env.getCtx(), line.getAD_WF_Next_ID()); - String title = Msg.getMsg(Env.getCtx(), "DeleteLine") - + ": " + node.getName() + " -> " + next.getName(); - addMenuItem(m_LinePopupMenu, title, line); - } - m_LinePopupMenu.show(this, e.getX(), e.getY()); - } - } - - // Selection - else if (e.getSource() instanceof WFNode) - { - WFNode selected = (WFNode)e.getSource(); - log.fine(selected.toString()); - for (int i = 0; i < m_nodes.size(); i++) - { - WFNode node = (WFNode)m_nodes.get(i); - if (selected.getAD_WF_Node_ID() == node.getAD_WF_Node_ID()) - node.setSelected(true); - else - node.setSelected(false); - } - } - m_dragged = false; - } // mouseClicked - - - /** - * Mouse Entered - * @param e event - */ - public void mouseEntered (MouseEvent e) - { - } // mouseEntered - - /** - * Mouse Exited - * @param e event - */ - public void mouseExited (MouseEvent e) - { - } // mouseExited - - /** - * Mouse Pressed. - * Initial drag - * @param e event - */ - public void mousePressed (MouseEvent e) - { - if (e.getSource() instanceof WFNode) - { - WFNode node = (WFNode)e.getSource(); - if (node.isEditable()) - { - m_draggedNode = node; - m_draggedStart = SwingUtilities.convertPoint(m_draggedNode, e.getX(), e.getY(), this); - } - else - { - m_dragged = false; - m_draggedNode = null; - m_draggedStart = null; - } - } - } // mousePressed - - - /********************************** - * Mouse Dragged - * @param e event - */ - public void mouseDragged (MouseEvent e) - { - // Nothing selected - if (m_draggedNode == null || e.getSource() != m_draggedNode) - { - if (e.getSource() instanceof WFNode) - { - WFNode node = (WFNode)e.getSource(); - if (node.isEditable()) - m_draggedNode = node; - m_draggedStart = null; - } - } - // Move Node - if (m_draggedNode != null) - { - m_dragged = true; - if (m_draggedStart == null) - m_draggedStart = SwingUtilities.convertPoint(m_draggedNode, e.getX(), e.getY(), this); - // If not converted to coordinate system of parent, it gets jumpy - Point mousePosition = SwingUtilities.convertPoint(m_draggedNode, e.getX(), e.getY(), this); - int xDelta = mousePosition.x - m_draggedStart.x; - int yDelta = mousePosition.y - m_draggedStart.y; - Point newLocation = m_draggedNode.getLocation(); - newLocation.x += xDelta; - if (newLocation.x < 0) - newLocation.x = 0; - newLocation.y += yDelta; - if (newLocation.y < 0) - newLocation.y = 0; - m_draggedNode.setLocation(newLocation.x, newLocation.y); - // log.fine("mouseDragged - " + m_draggedNode + " - " + e); - // log.fine("mouseDragged - Delta=" + xDelta + "/" + yDelta); - m_draggedStart = mousePosition; - invalidate(); - validate(); - repaint(); - } - } // mouseDragged - - /** - * Mouse Released. - * Finals dragging - * @param e event - */ - public void mouseReleased (MouseEvent e) - { - // log.fine("mouseReleased - " + m_draggedNode); - m_dragged = false; - m_draggedNode = null; - m_draggedStart = null; - repaint(); - } // mouseReleased - - /** - * Mouse Moved - * @param e event - */ - public void mouseMoved (MouseEvent e) - { - } // mouseMoved - - - /************************************************************************** - * Paint Component. - * Paint Lines directly as not added. - * @param g graphics - */ - protected void paintComponent (Graphics g) - { - super.paintComponent(g); - // Paint Lines - for (int i = 0; i < m_lines.size(); i++) - { - WFLine line = (WFLine)m_lines.get(i); - line.paint(g); - } - // Paint Position = right next to the box - if (m_dragged && m_draggedNode != null) - { - Point loc = m_draggedNode.getLocation(); - String text = "(" + loc.x + "," + loc.y +")"; - Graphics2D g2D = (Graphics2D)g; - Font font = new Font("Dialog", Font.PLAIN, 10); - g2D.setColor(Color.magenta); - TextLayout layout = new TextLayout (text, font, g2D.getFontRenderContext()); - loc.x += m_draggedNode.getWidth(); - loc.y += layout.getAscent(); - layout.draw(g2D, loc.x, loc.y); - } - } // paintComponents - - /** - * Add Menu Item to - add new line to node - * @param menu base menu - * @param title title - */ - private void addMenuItem (JPopupMenu menu, String title, MWFNode node, int AD_WF_NodeTo_ID) - { - WFPopupItem item = new WFPopupItem (title, node, AD_WF_NodeTo_ID); - menu.add(item); - item.addActionListener(this); - } // addMenuItem - - /** - * Add Menu Item to - delete line - * @param menu base menu - * @param title title - */ - private void addMenuItem (JPopupMenu menu, String title, MWFNodeNext line) - { - WFPopupItem item = new WFPopupItem (title, line); - menu.add(item); - item.addActionListener(this); - } // addMenuItem - - /** - * Action Listener - * @param e event - */ - public void actionPerformed (ActionEvent e) - { - log.info(e.toString()); - - // Add new Node - if (e.getSource()== m_NewMenuNode) - { - log.info("Create New Node"); - String nameLabel = Util.cleanAmp(Msg.getMsg(Env.getCtx(), "Name")); - String name = JOptionPane.showInputDialog(this, - nameLabel, // message - Msg.getMsg(Env.getCtx(), "CreateNewNode"), // title - JOptionPane.QUESTION_MESSAGE); - if (name != null && name.length() > 0) - { - int AD_Client_ID = Env.getAD_Client_ID(Env.getCtx()); - MWFNode node = new MWFNode(m_wf, name, name); - node.setClientOrg(AD_Client_ID, 0); - node.save(); - m_parent.load(m_wf.getAD_Workflow_ID(), true); - } - } - // Add/Delete Line - else if (e.getSource() instanceof WFPopupItem) - { - WFPopupItem item = (WFPopupItem)e.getSource(); - item.execute(); - } - - } // actionPerformed - - - /************************************************************************** - * WF Content Panel Popup Item - * @author Jorg Janke - * @version $Id: WFContentPanel.java,v 1.2 2006/07/30 00:51:28 jjanke Exp $ - */ - class WFPopupItem extends JMenuItem - { - /** - * - */ - private static final long serialVersionUID = 4634863991042969718L; - - /** - * Add Line Item - * @param title title - * @param node node - * @param AD_WF_NodeTo_ID line to - */ - public WFPopupItem (String title, MWFNode node, int AD_WF_NodeTo_ID) - { - super (title); - m_node = node; - m_AD_WF_NodeTo_ID = AD_WF_NodeTo_ID; - } // WFPopupItem - - /** - * Delete Line Item - * @param title title - * @param line line to be deleted - */ - public WFPopupItem (String title, MWFNodeNext line) - { - super (title); - m_line = line; - } // WFPopupItem - - /** The Node */ - private MWFNode m_node; - /** The Line */ - private MWFNodeNext m_line; - /** The Next Node ID */ - private int m_AD_WF_NodeTo_ID; - - /** - * Execute - */ - public void execute() - { - // Add Line - if (m_node != null && m_AD_WF_NodeTo_ID > 0) - { - int AD_Client_ID = Env.getAD_Client_ID(Env.getCtx()); - MWFNodeNext newLine = new MWFNodeNext(m_node, m_AD_WF_NodeTo_ID); - newLine.setClientOrg(AD_Client_ID, 0); - newLine.save(); - log.info("Add Line to " + m_node + " -> " + newLine); - m_parent.load(m_wf.getAD_Workflow_ID(), true); - } - // Delete Node - else if (m_node != null && m_AD_WF_NodeTo_ID == -1) - { - log.info("Delete Node: " + m_node); - m_node.delete(false); - m_parent.load(m_wf.getAD_Workflow_ID(), true); - } - // Delete Line - else if (m_line != null) - { - log.info("Delete Line: " + m_line); - m_line.delete(false); - m_parent.load(m_wf.getAD_Workflow_ID(), true); - } - else - log.severe("No Action??"); - } // execute - - } // WFPopupItem - -} // WFContentPanel +package org.compiere.apps.wf; + + +import java.awt.Point; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.HashMap; +import java.util.Map; + +import javax.swing.JOptionPane; + +import org.compiere.model.X_AD_Workflow; +import org.compiere.swing.CPanel; +import org.compiere.util.Env; +import org.compiere.util.Msg; +import org.compiere.util.Util; +import org.compiere.wf.MWFNode; +import org.compiere.wf.MWFNodeNext; +import org.compiere.wf.MWorkflow; +import org.netbeans.api.visual.action.ActionFactory; +import org.netbeans.api.visual.action.MoveProvider; +import org.netbeans.api.visual.action.WidgetAction; +import org.netbeans.api.visual.graph.layout.GraphLayout; +import org.netbeans.api.visual.layout.LayoutFactory; +import org.netbeans.api.visual.layout.SceneLayout; +import org.netbeans.api.visual.widget.Widget; + +public class WFContentPanel extends CPanel implements ActionListener, MoveProvider { + + /** + * + */ + private static final long serialVersionUID = 4589292821059374372L; + + private WidgetAction moveAction = ActionFactory.createMoveAction(new WFNodeMoveStrategy(), this); + + private WorkflowGraphScene graphScene = new WorkflowGraphScene(); + private WFPanel m_parent; + private int currentRow = 1; + private int currentColumn = 0; + private int noOfColumns = 4; + + private MWorkflow m_wf; + private boolean readWrite = false; + + public final static int NODE_WIDTH = 180; + public final static int NODE_HEIGHT = 120; + + private Map matrix = null; + + public WFContentPanel (WFPanel parent) { + super(); + m_parent = parent; + matrix = new HashMap(); + } + + public void setReadWrite(boolean readWrite) { + this.readWrite = readWrite; + } + + public void setWorkflow(MWorkflow mWf) { + m_wf = mWf; + } + + public void addNode(MWFNode node) { + int oldRow = currentRow; + int oldColumn = currentColumn; + if (node.getXPosition() > 0 && node.getYPosition() > 0) { + currentColumn = node.getXPosition(); + currentRow = node.getYPosition(); + if (currentColumn > noOfColumns) { + currentColumn = 1; + currentRow ++; + } + } else if (currentColumn == noOfColumns) { + currentColumn = 1; + if (m_wf.getWorkflowType().equals(X_AD_Workflow.WORKFLOWTYPE_General)) { + currentRow++; + } else { + currentRow = currentRow + 2; + } + } else { + if (m_wf.getWorkflowType().equals(X_AD_Workflow.WORKFLOWTYPE_General) || currentColumn == 0) { + currentColumn++; + } else { + currentColumn = currentColumn + 2; + if (currentColumn > noOfColumns) { + currentColumn = 1; + currentRow = currentRow + 2; + } + } + } + Integer[] nodes = matrix.get(currentRow); + if (nodes == null) { + nodes = new Integer[noOfColumns]; + matrix.put(currentRow, nodes); + } else { + //detect collision + while (nodes[currentColumn - 1] != null) { + if (nodes[currentColumn - 1] == node.getAD_WF_Node_ID()) { + break; + } else if (currentColumn == noOfColumns) { + currentColumn = 1; + currentRow ++; + nodes = matrix.get(currentRow); + if (nodes == null) { + nodes = new Integer[noOfColumns]; + matrix.put(currentRow, nodes); + } + } else { + currentColumn ++; + } + } + } + + WFNodeWidget w = (WFNodeWidget) graphScene.addNode(node.getAD_WF_Node_ID()); + w.setColumn(currentColumn); + w.setRow(currentRow); + + nodes[currentColumn - 1] = node.getAD_WF_Node_ID(); + + if (readWrite && node.getAD_Client_ID() == Env.getAD_Client_ID(Env.getCtx())) { + w.getActions().addAction(ActionFactory.createPopupMenuAction(new NodeMenu(this, m_wf))); + w.getActions().addAction(moveAction); + } + + if (currentRow < oldRow) { + currentRow = oldRow; + currentColumn = oldColumn; + } else if ( currentRow == oldRow && currentColumn < oldColumn) { + currentColumn = oldColumn; + } + } + + public void addEdge(MWFNodeNext edge) { + graphScene.addEdge(edge); + graphScene.setEdgeSource(edge, edge.getAD_WF_Node_ID()); + graphScene.setEdgeTarget(edge, edge.getAD_WF_Next_ID()); + } + + public void relayout() { + GraphLayout graphLayout = new WFGraphLayout(); + graphLayout.setAnimated(false); + SceneLayout sceneGraphLayout = LayoutFactory.createSceneGraphLayout (graphScene, graphLayout); + sceneGraphLayout.invokeLayout (); + + this.add(graphScene.createView()); + + if (readWrite) { + graphScene.getActions().addAction(ActionFactory.createPopupMenuAction(new SceneMainMenu(this))); + } + } + + @Override + public void removeAll() { + super.removeAll(); + graphScene = new WorkflowGraphScene(); + currentColumn = 0; + currentRow = 1; + matrix = new HashMap(); + } + + public WorkflowGraphScene getGraphScene() { + return graphScene; + } + + private void createNewNode() { + String nameLabel = Util.cleanAmp(Msg.getMsg(Env.getCtx(), "Name")); + String name = JOptionPane.showInputDialog(this, + nameLabel, // message + Msg.getMsg(Env.getCtx(), "CreateNewNode"), // title + JOptionPane.QUESTION_MESSAGE); + if (name != null && name.length() > 0) + { + int AD_Client_ID = Env.getAD_Client_ID(Env.getCtx()); + MWFNode node = new MWFNode(m_wf, name, name); + node.setClientOrg(AD_Client_ID, 0); + node.saveEx(); + m_parent.load(m_wf.getAD_Workflow_ID(), true); + } + } + + public void actionPerformed(ActionEvent e) { + if (e.getActionCommand().equals(SceneMainMenu.ADD_NEW_NODE_ACTION)) + { + createNewNode(); + } + //Add/Delete Line + else if (e.getSource() instanceof WFPopupItem) + { + WFPopupItem item = (WFPopupItem)e.getSource(); + item.execute(m_parent); + } + } + + public Point getOriginalLocation(Widget widget) { + return widget.getLocation(); + } + + public void movementFinished(Widget widget) { + WFNodeWidget nodeWidget = (WFNodeWidget) widget; + Point location = widget.getPreferredLocation(); + int x = location.x / WFGraphLayout.COLUMN_WIDTH + 1; + int y = location.y / WFGraphLayout.ROW_HEIGHT + 1; + Integer[] nodes = matrix.get(y); + if (nodes == null || nodes[x - 1] == null || + nodes[x - 1] == nodeWidget.getModel().getAD_WF_Node_ID()) { + nodeWidget.getModel().setXPosition(x); + nodeWidget.getModel().setYPosition(y); + nodeWidget.getModel().saveEx(); + } + m_parent.load(m_wf.getAD_Workflow_ID(), true); + } + + public void movementStarted(Widget widget) { + } + + public void setNewLocation(Widget widget, Point point) { + widget.setPreferredLocation(point); + } +} diff --git a/client/src/org/compiere/apps/wf/WFIcon.java b/client/src/org/compiere/apps/wf/WFIcon.java deleted file mode 100644 index 37580bbad8..0000000000 --- a/client/src/org/compiere/apps/wf/WFIcon.java +++ /dev/null @@ -1,115 +0,0 @@ -/****************************************************************************** - * Product: Adempiere ERP & CRM Smart Business Solution * - * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * - * This program is free software; you can redistribute it and/or modify it * - * under the terms version 2 of the GNU General Public License as published * - * by the Free Software Foundation. This program is distributed in the hope * - * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * - * See the GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License along * - * with this program; if not, write to the Free Software Foundation, Inc., * - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * - * For the text or an alternative of this public license, you may reach us * - * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * - * or via info@compiere.org or http://www.compiere.org/license.html * - *****************************************************************************/ -package org.compiere.apps.wf; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Graphics; -import java.awt.Graphics2D; - -import javax.swing.Icon; - -import org.compiere.model.MTreeNode; - - -/** - * Work Flow Icon - * - * @author Jorg Janke - * @version $Id: WFIcon.java,v 1.2 2006/07/30 00:51:28 jjanke Exp $ - */ -public class WFIcon implements Icon -{ - /** - * Constructor - * @param type see MTreeNode.TYPE_ - */ - public WFIcon (int type) - { - if (type > 0 && type < MTreeNode.IMAGES.length) - m_type = type; - } // WFIcon - - /** - * Constructor - * @param action image indicator - */ - public WFIcon (String action) - { - if (action != null) - m_type = MTreeNode.getImageIndex(action); - } // WFIcon - - - private static int WIDTH = 20; // Image is 16x16 - private static int HEIGHT = 20; - - /** Image Index */ - private int m_type = 0; - - /** - * Draw the icon at the specified location. Icon implementations - * may use the Component argument to get properties useful for - * painting, e.g. the foreground or background color. - * - * @param c Component - * @param g Graphics - * @param x X - * @param y Y - * @see javax.swing.Icon#paintIcon(Component, Graphics, int, int) - */ - public void paintIcon (Component c, Graphics g, int x, int y) - { - Graphics2D g2D = (Graphics2D)g; - Icon icon = MTreeNode.getIcon(m_type); - if (icon != null) - { - int xI = x + ((WIDTH - icon.getIconWidth()) / 2); - int yI = y + ((HEIGHT - icon.getIconHeight()) / 2); - icon.paintIcon(c, g, xI, yI); - } - else // draw dot - { - int size = 10; - int xI = x + ((WIDTH - size) / 2); - int yI = y + ((HEIGHT - size) / 2); - g2D.setColor(Color.magenta); - g2D.fillOval(xI, yI, size, size); - } - } // PaintIcon - - /** - * Returns the icon's width. - * @return an int specifying the fixed width of the icon. - * @see javax.swing.Icon#getIconWidth() - */ - public int getIconWidth() - { - return WIDTH; - } // getIconWidth - - /** - * Returns the icon's height. - * @return an int specifying the fixed height of the icon. - * @see javax.swing.Icon#getIconHeight() - */ - public int getIconHeight() - { - return HEIGHT; - } // getIconHeight - -} // WFIcon diff --git a/client/src/org/compiere/apps/wf/WFLayoutManager.java b/client/src/org/compiere/apps/wf/WFLayoutManager.java deleted file mode 100644 index d1cea74699..0000000000 --- a/client/src/org/compiere/apps/wf/WFLayoutManager.java +++ /dev/null @@ -1,209 +0,0 @@ -/****************************************************************************** - * Product: Adempiere ERP & CRM Smart Business Solution * - * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * - * This program is free software; you can redistribute it and/or modify it * - * under the terms version 2 of the GNU General Public License as published * - * by the Free Software Foundation. This program is distributed in the hope * - * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * - * See the GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License along * - * with this program; if not, write to the Free Software Foundation, Inc., * - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * - * For the text or an alternative of this public license, you may reach us * - * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * - * or via info@compiere.org or http://www.compiere.org/license.html * - *****************************************************************************/ -package org.compiere.apps.wf; - -import java.awt.Component; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.Insets; -import java.awt.LayoutManager; -import java.awt.Point; - -import org.compiere.util.CLogger; - -/** - * WorkFlow Layout Manager - * - * @author Jorg Janke - * @version $Id: WFLayoutManager.java,v 1.2 2006/07/30 00:51:28 jjanke Exp $ - */ -public class WFLayoutManager implements LayoutManager -{ - /** - * Constructor - */ - public WFLayoutManager() - { - } // WFLayoutManager - - /** Logger */ - private static CLogger log = CLogger.getCLogger(WFLayoutManager.class); - /** Cached Size */ - private Dimension m_size = null; - - /** - * If the layout manager uses a per-component string, - * adds the component comp to the layout, - * associating it - * with the string specified by name. - * - * @param name the string to be associated with the component - * @param comp the component to be added - * @see java.awt.LayoutManager#addLayoutComponent(String, Component) - */ - public void addLayoutComponent (String name, Component comp) - { - invalidateLayout(); - } // addLayoutComponent - - /** - * Removes the specified component from the layout. - * @param comp the component to be removed - * @see java.awt.LayoutManager#removeLayoutComponent(Component) - */ - public void removeLayoutComponent(Component comp) - { - if (comp == null) - return; - invalidateLayout(); - } // removeLayoutComponent - - /** - * Calculates the preferred size dimensions for the specified - * container, given the components it contains. - * @param parent the container to be laid out - * @return preferred size - * @see #minimumLayoutSize - */ - public Dimension preferredLayoutSize(Container parent) - { - if (m_size == null) - layoutContainer(parent); - return m_size; - } // preferredLayoutSize - - /** - * Calculates the minimum size dimensions for the specified - * container, given the components it contains. - * @param parent the component to be laid out - * @return preferred size - * @see #preferredLayoutSize - */ - public Dimension minimumLayoutSize(Container parent) - { - return preferredLayoutSize(parent); - } // minimumLayoutSize - - - /************************************************************************** - * Lays out the specified container. - * @param parent the container to be laid out - * @see java.awt.LayoutManager#layoutContainer(Container) - */ - public void layoutContainer (Container parent) - { - Insets insets = parent.getInsets(); - // - int width = insets.left; - int height = insets.top; - - // We need to layout - if (needLayout(parent)) - { - int x = 5; - int y = 5; - // Go through all components - for (int i = 0; i < parent.getComponentCount(); i++) - { - Component comp = parent.getComponent(i); - if (comp.isVisible() && comp instanceof WFNode) - { - Dimension ps = comp.getPreferredSize(); - comp.setLocation(x, y); - comp.setBounds(x, y, ps.width, ps.height); - // - width = x + ps.width; - height = y + ps.height; - // next pos - if (x == 5) - x = 230; - else - { - x = 5; - y += 100; - } - // x += ps.width-20; - // y += ps.height+20; - } - } - } - else // we have an Layout - { - // Go through all components - for (int i = 0; i < parent.getComponentCount(); i++) - { - Component comp = parent.getComponent(i); - if (comp.isVisible() && comp instanceof WFNode) - { - Dimension ps = comp.getPreferredSize(); - Point loc = comp.getLocation(); - int maxWidth = comp.getX() + ps.width; - int maxHeight = comp.getY() + ps.height; - if (width < maxWidth) - width = maxWidth; - if (height < maxHeight) - height = maxHeight; - comp.setBounds(loc.x, loc.y, ps.width, ps.height); - } - } // for all components - } // have layout - - - // Create Lines - WFContentPanel panel = (WFContentPanel)parent; - panel.createLines(); - - // Calculate size - width += insets.right; - height += insets.bottom; - - // return size - m_size = new Dimension(width, height); - log.finer("Size=" + m_size); - } // layoutContainer - - /** - * Need Layout - * @param parent parent - * @return true if we need to layout - */ - private boolean needLayout (Container parent) - { - Point p00 = new Point(0,0); - // Go through all components - for (int i = 0; i < parent.getComponentCount(); i++) - { - Component comp = parent.getComponent(i); - if (comp instanceof WFNode && comp.getLocation().equals(p00)) - { - log.fine(comp.toString()); - return true; - } - } - return false; - } // needLayout - - /** - * Invalidates the layout, indicating that if the layout manager - * has cached information it should be discarded. - */ - private void invalidateLayout() - { - m_size = null; - } // invalidateLayout - -} // WFLayoutManager diff --git a/client/src/org/compiere/apps/wf/WFLine.java b/client/src/org/compiere/apps/wf/WFLine.java deleted file mode 100644 index 5c5f3dfa80..0000000000 --- a/client/src/org/compiere/apps/wf/WFLine.java +++ /dev/null @@ -1,355 +0,0 @@ -/****************************************************************************** - * Product: Adempiere ERP & CRM Smart Business Solution * - * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * - * This program is free software; you can redistribute it and/or modify it * - * under the terms version 2 of the GNU General Public License as published * - * by the Free Software Foundation. This program is distributed in the hope * - * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * - * See the GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License along * - * with this program; if not, write to the Free Software Foundation, Inc., * - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * - * For the text or an alternative of this public license, you may reach us * - * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * - * or via info@compiere.org or http://www.compiere.org/license.html * - *****************************************************************************/ -package org.compiere.apps.wf; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.Polygon; -import java.awt.Rectangle; -import java.awt.font.TextLayout; - -import javax.swing.SwingConstants; - -import org.compiere.util.CLogger; -import org.compiere.wf.MWFNodeNext; - - -/** - * Work Flow Line between Nodes. - * Coordinates based on WFContentPanel. - * - * @author Jorg Janke - * @version $Id: WFLine.java,v 1.2 2006/07/30 00:51:28 jjanke Exp $ - */ -public class WFLine extends Component -{ - /** - * - */ - private static final long serialVersionUID = 7599996355185021897L; - - /** - * Create Line - * @param next model - */ - public WFLine (MWFNodeNext next) - { - m_next = next; - // setOpaque(false); - setFocusable(false); - // - m_description = next.getDescription(); - if (m_description != null && m_description.length() > 0) - m_description = "{" + String.valueOf(next.getSeqNo()) - + ": " + m_description + "}"; - } // WFLine - - /** Model */ - private MWFNodeNext m_next = null; - /** From Node */ - private Rectangle m_from = null; - /** To Node */ - private Rectangle m_to = null; - /** Descriprion */ - private String m_description = null; - /** Visited value */ - private boolean m_visited = false; - /** Logger */ - private static CLogger log = CLogger.getCLogger(WFLine.class); - - /** - * Get From rectangle - * @return from node rectangle - */ - public Rectangle getFrom() - { - return m_from; - } // getFrom - - /** - * Get To rectangle - * @return to node rectangle - */ - public Rectangle getTo() - { - return m_to; - } // getTo - - /** - * Set From/To rectangle. - * Called from WFLayoutManager.layoutContainer - * @param from from node rectangle - * @param to to node rectangle - */ - public void setFromTo (Rectangle from, Rectangle to) - { - m_from = from; - m_to = to; - } // setFrom - - /** - * Get From Node ID - * @return from node id - */ - public int getAD_WF_Node_ID() - { - return m_next.getAD_WF_Node_ID(); // Node -> - } // getAD_WF_Node_ID - - /** - * Get To Node ID - * @return to node id - */ - public int getAD_WF_Next_ID() - { - return m_next.getAD_WF_Next_ID(); // -> Next - } // getAD_WF_Next_ID - - /** - * Set Visited. - * @param visited visited - */ - public void setVisited (boolean visited) - { - m_visited = visited; - } // setVisited - - /** - * From: Right - To: Top = left \ down - */ - private boolean isRightTop() // \ - { - return (m_from.x+m_from.width <= m_to.x // right.bottom - left.top - && m_from.y+m_from.height <= m_to.y); - } - /** - * From: Bottom - To: Top = top | down - */ - private boolean isBottomTop() // | - { - return (m_from.y+m_from.height <= m_to.y); - } - /** - * From: Top - To: Bottom = bottom / up - */ - private boolean isTopBottom() // | - { - return (m_to.y+m_to.height <= m_from.y); - } - /** - * From: Left - To: Right = right o <- o left - */ - private boolean isLeftRight() // -> - { - return (m_to.x+m_to.width <= m_from.x); - } - - - /************************************************************************** - * Paint it. - * Coordinates based on WFContentPanel. - * @param g Graph - */ - public void paint (Graphics g) - { - if (m_from == null || m_to == null) - return; - - Polygon arrow = new Polygon(); - Point from = null; - Point to = null; - - // - if (isRightTop()) - { - from = addPoint (arrow, m_from, SwingConstants.RIGHT, true); - to = addPoint (arrow, m_to, SwingConstants.TOP, false); - } - else if (isBottomTop()) - { - from = addPoint (arrow, m_from, SwingConstants.BOTTOM, true); - to = addPoint (arrow, m_to, SwingConstants.TOP, false); - } - // - else if (isTopBottom()) - { - from = addPoint (arrow, m_from, SwingConstants.TOP, true); - to = addPoint (arrow, m_to, SwingConstants.BOTTOM, false); - } - else if (isLeftRight()) - { - from = addPoint (arrow, m_from, SwingConstants.LEFT, true); - to = addPoint (arrow, m_to, SwingConstants.RIGHT, false); - } - else // if (isRightLeft()) - { - from = addPoint (arrow, m_from, SwingConstants.RIGHT, true); - to = addPoint (arrow, m_to, SwingConstants.LEFT, false); - } - - /** - * Paint Arrow: - * Unconditional: no fill - black text - * Conditional: red fill - red text - * Visited: green line - * NotVisited: black line - * Split/Join: AND: Magenta Dot -- XOR: - - */ - if (!m_next.isUnconditional()) - { - g.setColor(Color.red); - g.fillPolygon(arrow); // fill - } - if (m_visited) - g.setColor(Color.green); - else - g.setColor(Color.black); - g.drawPolygon(arrow); // line - - // Paint Dot for AND From - if (m_next.isFromSplitAnd()) - { - g.setColor(Color.magenta); - g.fillOval(from.x-3, from.y-3, 6, 6); - } - // Paint Dot for AND To - if (m_next.isToJoinAnd()) - { - g.setColor(Color.magenta); - g.fillOval(to.x-3, to.y-3, 6, 6); - } - - // Paint Description in red - if (m_description != null) - { - Graphics2D g2D = (Graphics2D)g; - Font font = new Font("Dialog", Font.PLAIN, 9); - if (m_next.isUnconditional()) - g2D.setColor(Color.black); - else - g2D.setColor(Color.red); - TextLayout layout = new TextLayout (m_description, font, g2D.getFontRenderContext()); - - // Mid Point - int x = 0; - if (from.x < to.x) - x = from.x + ((to.x - from.x) / 2); - else - x = to.x + ((from.x - to.x) / 2); - int y = 0; - if (from.y < to.y) - y = from.y + ((to.y - from.y) / 2); - else - y = to.y + ((from.y - to.y) / 2); - - // Adjust | - y -= (layout.getAscent() - 3); // above center - - // Adjust - - x -= (layout.getAdvance() / 2); // center - if (x < 2) - x = 2; - - layout.draw(g2D, x, y); - } - - } // paintComponent - - /** - * Get Point of Rectangle - * @param arrow Polygon to draw arrow - * @param rect Rectangle (icon) - * @param pos SwingConstants.BOTTOM / TOP / RIGHT / LEFT - * @param from if true from (base) else to (tip) of arrow - * @return point docking position two point away - */ - private Point addPoint (Polygon arrow, Rectangle rect, int pos, boolean from) - { - int x = rect.x; - int y = rect.y; - Point point = null; - - if (pos == SwingConstants.TOP) - { - x += rect.width/2; - if (from) - { - arrow.addPoint(x-2, y); - arrow.addPoint(x+2, y); - } - else - arrow.addPoint(x, y); - point = new Point (x, y-2); - } - else if (pos == SwingConstants.RIGHT) - { - x += rect.width; - y += rect.height/2; - if (from) - { - arrow.addPoint(x, y-2); - arrow.addPoint(x, y+2); - } - else - arrow.addPoint(x, y); - point = new Point (x+2, y); - } - else if (pos == SwingConstants.LEFT) - { - y += rect.height/2; - if (from) - { - arrow.addPoint(x, y-2); - arrow.addPoint(x, y+2); - } - else - arrow.addPoint(x, y); - point = new Point (x-2, y); - } - else // if (pos == SwingConstants.BOTTOM) - { - x += rect.width/2; - y += rect.height; - if (from) - { - arrow.addPoint(x-2, y); - arrow.addPoint(x+2, y); - } - else - arrow.addPoint(x, y); - point = new Point (x, y+2); - } - return point; - } // getPoint - - /** - * String Representation - * @return info - */ - public String toString() - { - StringBuffer sb = new StringBuffer("WFLine["); - sb.append(getAD_WF_Node_ID()).append("->").append(getAD_WF_Next_ID()); - sb.append("]"); - return sb.toString(); - } // toString - -} // WFLine diff --git a/client/src/org/compiere/apps/wf/WFNode.java b/client/src/org/compiere/apps/wf/WFNode.java deleted file mode 100644 index 4881722144..0000000000 --- a/client/src/org/compiere/apps/wf/WFNode.java +++ /dev/null @@ -1,278 +0,0 @@ -/****************************************************************************** - * Product: Adempiere ERP & CRM Smart Business Solution * - * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * - * This program is free software; you can redistribute it and/or modify it * - * under the terms version 2 of the GNU General Public License as published * - * by the Free Software Foundation. This program is distributed in the hope * - * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * - * See the GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License along * - * with this program; if not, write to the Free Software Foundation, Inc., * - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * - * For the text or an alternative of this public license, you may reach us * - * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * - * or via info@compiere.org or http://www.compiere.org/license.html * - *****************************************************************************/ -package org.compiere.apps.wf; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.font.LineBreakMeasurer; -import java.awt.font.TextAttribute; -import java.awt.font.TextLayout; -import java.text.AttributedCharacterIterator; -import java.text.AttributedString; - -import javax.swing.BorderFactory; -import javax.swing.JComponent; -import javax.swing.border.BevelBorder; -import javax.swing.border.Border; - -import org.compiere.util.CLogger; -import org.compiere.util.Env; -import org.compiere.wf.MWFNode; - -/** - * Graphical Work Flow Node. - * Listen to PropertyChange for selection - * - * @author Jorg Janke - * @version $Id: WFNode.java,v 1.2 2006/07/30 00:51:28 jjanke Exp $ - */ -public class WFNode extends JComponent -{ - /** - * - */ - private static final long serialVersionUID = -3267215731910132678L; - - - /** - * Create WF Node - * @param node model - */ - public WFNode (MWFNode node) - { - super(); - setOpaque(true); - m_node = node; - setName(m_node.getName()); - m_icon = new WFIcon(node.getAction()); - m_name = m_node.getName(true); - setBorder(s_border); - - // Tool Tip - String description = node.getDescription(true); - if (description != null && description.length() > 0) - setToolTipText(description); - else - setToolTipText(node.getName(true)); - - // Location - setBounds(node.getXPosition(), node.getYPosition(), s_size.width, s_size.height); - log.config(node.getAD_WF_Node_ID() - + "," + node.getName() + " - " + getLocation()); - setSelected(false); - setVisited(false); - } // WFNode - - /** Selected Property value */ - public static String PROPERTY_SELECTED = "selected"; - /** Standard (raised) Border */ - private static Border s_border = BorderFactory.createBevelBorder(BevelBorder.RAISED); - /** Selected (lowered) Border */ - private static Border s_borderSelected = BorderFactory.createBevelBorder(BevelBorder.LOWERED); - /** Size of the Node */ - private static Dimension s_size = new Dimension (120, 50); - /** Logger */ - private static CLogger log = CLogger.getCLogger(WFNode.class); - - /** ID */ - private MWFNode m_node = null; - /** Icon */ - private WFIcon m_icon = null; - /** Name to paint */ - private String m_name = null; - /** Selected Value */ - private boolean m_selected = false; - /** Visited Value */ - private boolean m_visited = false; - /** Was node moved */ - private boolean m_moved = false; - - - /************************************************************************** - * Set Selected. - * Selected: blue foreground - lowered border - * UnSelected: black foreground - raised border - * @param selected selected - */ - public void setSelected (boolean selected) - { - firePropertyChange(PROPERTY_SELECTED, m_selected, selected); - m_selected = selected; - if (m_selected) - { - setBorder (s_borderSelected); - setForeground(Color.blue); - } - else - { - setBorder (s_border); - setForeground (Color.black); - } - } // setSelected - - /** - * Set Visited. - * Visited: green background - * NotVisited: - * @param visited visited - */ - public void setVisited (boolean visited) - { - m_visited = visited; - if (m_visited) - { - setBackground(Color.green); - } - else - { - setBackground(Color.lightGray); - } - } // setVisited - - /** - * Get Selected - * @return selected - */ - public boolean isSelected() - { - return m_selected; - } // isSelected - - /** - * Get Client ID - * @return Client ID - */ - public int getAD_Client_ID() - { - return m_node.getAD_Client_ID(); - } // getAD_Client_ID - - /** - * Is the node Editable - * @return yes if the Client is the same - */ - public boolean isEditable() - { - return getAD_Client_ID() == Env.getAD_Client_ID(Env.getCtx()); - } // isEditable - - - /** - * Get Node ID - * @return Node ID - */ - public int getAD_WF_Node_ID() - { - return m_node.getAD_WF_Node_ID(); - } // getAD_WF_Node_ID - - /** - * Get Node Model - * @return Node Model - */ - public MWFNode getModel() - { - return m_node; - } // getModel - - /** - * Set Location - also for Node. - * @param x x - * @param y y - */ - public void setLocation (int x, int y) - { - super.setLocation (x, y); - m_node.setPosition(x, y); - } - - /** - * String Representation - * @return info - */ - public String toString() - { - StringBuffer sb = new StringBuffer("WFNode["); - sb.append(getAD_WF_Node_ID()).append("-").append(m_name) - .append(",").append(getBounds()) - .append("]"); - return sb.toString(); - } // toString - - /** - * Get Font. - * Italics if not editable - * @return font - */ - public Font getFont () - { - Font base = new Font(null); - if (!isEditable()) - return base; - // Return Bold Italic Font - return new Font(base.getName(), Font.ITALIC | Font.BOLD, base.getSize()); - } // getFont - - /************************************************************************** - * Get Preferred Size - * @return size - */ - public Dimension getPreferredSize () - { - return s_size; - } // getPreferredSize - - /** - * Paint Component - * @param g Graphics - */ - protected void paintComponent (Graphics g) - { - Graphics2D g2D = (Graphics2D)g; - Rectangle bounds = getBounds(); - m_icon.paintIcon(this, g2D, 0, 0); - // Paint Text - Color color = getForeground(); - g2D.setPaint(color); - Font font = getFont(); - // - AttributedString aString = new AttributedString(m_name); - aString.addAttribute(TextAttribute.FONT, font); - aString.addAttribute(TextAttribute.FOREGROUND, color); - AttributedCharacterIterator iter = aString.getIterator(); - // - LineBreakMeasurer measurer = new LineBreakMeasurer(iter, g2D.getFontRenderContext()); - float width = s_size.width - m_icon.getIconWidth() - 2; - TextLayout layout = measurer.nextLayout(width); - float xPos = m_icon.getIconWidth(); - float yPos = layout.getAscent() + 2; - // - layout.draw(g2D, xPos, yPos); - width = s_size.width - 4; // 2 pt - while (measurer.getPosition() < iter.getEndIndex()) - { - layout = measurer.nextLayout(width); - yPos += layout.getAscent() + layout.getDescent() + layout.getLeading(); - layout.draw(g2D, 2, yPos); - } - } // paintComponent - -} // WFNode diff --git a/client/src/org/compiere/apps/wf/WFNodeMoveStrategy.java b/client/src/org/compiere/apps/wf/WFNodeMoveStrategy.java new file mode 100644 index 0000000000..9679a2e872 --- /dev/null +++ b/client/src/org/compiere/apps/wf/WFNodeMoveStrategy.java @@ -0,0 +1,15 @@ +package org.compiere.apps.wf; + +import java.awt.Point; + +import org.netbeans.api.visual.action.MoveStrategy; +import org.netbeans.api.visual.widget.Widget; + +public class WFNodeMoveStrategy implements MoveStrategy { + + public Point locationSuggested(Widget widget, Point originalLocation, Point suggestedLocation) { + return new Point (suggestedLocation.x - suggestedLocation.x % WFGraphLayout.COLUMN_WIDTH , + suggestedLocation.y - suggestedLocation.y % WFGraphLayout.ROW_HEIGHT); + } + +} diff --git a/client/src/org/compiere/apps/wf/WFPanel.java b/client/src/org/compiere/apps/wf/WFPanel.java index 8bb723087d..65f95cadc6 100644 --- a/client/src/org/compiere/apps/wf/WFPanel.java +++ b/client/src/org/compiere/apps/wf/WFPanel.java @@ -17,6 +17,7 @@ package org.compiere.apps.wf; import java.awt.BorderLayout; +import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; @@ -25,9 +26,10 @@ import java.awt.Insets; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; +import java.util.ArrayList; +import java.util.List; import java.util.Properties; +import java.util.Set; import java.util.logging.Level; import javax.swing.JButton; @@ -43,7 +45,6 @@ import org.compiere.apps.AMenuStartItem; import org.compiere.apps.AWindow; import org.compiere.apps.form.FormFrame; import org.compiere.apps.form.FormPanel; -import org.compiere.grid.ed.AutoCompletion; import org.compiere.model.MQuery; import org.compiere.model.MRole; import org.compiere.model.MTable; @@ -60,32 +61,28 @@ import org.compiere.util.Util; import org.compiere.wf.MWFNode; import org.compiere.wf.MWFNodeNext; import org.compiere.wf.MWorkflow; +import org.netbeans.api.visual.model.ObjectSceneEvent; +import org.netbeans.api.visual.model.ObjectSceneEventType; +import org.netbeans.api.visual.model.ObjectSceneListener; +import org.netbeans.api.visual.model.ObjectState; +import org.netbeans.api.visual.widget.Widget; /** * WorkFlow Panel * * @author Jorg Janke * @version $Id: WFPanel.java,v 1.2 2006/07/30 00:51:28 jjanke Exp $ - * + * * @author Teo Sarca, www.arhipac.ro *

  • FR [ 2048081 ] Mf. Workflow editor should display only mf. workflows - *
  • BF [ 2844102 ] Workfow Editor is displaying manufacturing routings too - * https://sourceforge.net/tracker/?func=detail&aid=2844102&group_id=176962&atid=879332 */ public class WFPanel extends CPanel - implements PropertyChangeListener, ActionListener, FormPanel + implements ActionListener, FormPanel, ObjectSceneListener { /** - * + * */ private static final long serialVersionUID = 4478193785606693055L; - - /** Workflow WhereClause : General, Document Process, Document Value */ - private static final String WORKFLOW_WhereClause = "WorkflowType IN (" - +DB.TO_STRING(MWorkflow.WORKFLOWTYPE_General) - +","+DB.TO_STRING(MWorkflow.WORKFLOWTYPE_DocumentProcess) - +","+DB.TO_STRING(MWorkflow.WORKFLOWTYPE_DocumentValue) - +")"; /** @@ -94,7 +91,7 @@ public class WFPanel extends CPanel */ public WFPanel() { - this (null, WORKFLOW_WhereClause, -1); + this (null, null, -1); } // WFPanel /** @@ -103,7 +100,7 @@ public class WFPanel extends CPanel */ public WFPanel (AMenu menu) { - this(menu, WORKFLOW_WhereClause, -1); + this(menu, null, -1); } /** @@ -140,10 +137,10 @@ public class WFPanel extends CPanel /** Context */ private Properties m_ctx = Env.getCtx(); /** Active Node */ - private WFNode m_activeNode = null; + private MWFNode m_activeNode = null; /** ReadWrite Mode (see WFNode) */ private boolean m_readWrite = false; - + /** Workflows List Where Clause */ private String m_WF_whereClause = null; /** Workflow Window ID */ @@ -151,7 +148,7 @@ public class WFPanel extends CPanel /** Logger */ private static CLogger log = CLogger.getCLogger(WFPanel.class); - + // UI private BorderLayout mainLayout = new BorderLayout(); private CPanel southPanel = new CPanel(); @@ -171,8 +168,9 @@ public class WFPanel extends CPanel private CButton bSaveLayout = AEnv.getButton ("Save"); private CButton bZoom = AEnv.getButton("Zoom"); private CButton bIgnore = AEnv.getButton("Ignore"); - - + private WFNodeWidget selectedWidget; + + /** * Static Init *
    @@ -278,7 +276,6 @@ public class WFPanel extends CPanel
     		KeyNamePair[] pp = DB.getKeyNamePairs(sql, true);
     		//
     		workflow = new CComboBox(pp);
    -		AutoCompletion.enable(workflow);
     		loadPanel.add(workflow);
     		workflow.addActionListener(this);
     		//
    @@ -291,8 +288,8 @@ public class WFPanel extends CPanel
     		loadPanel.add(bZoom);
     		bZoom.addActionListener(this);
     	}	//	loadPanel
    -	
    -	
    +
    +
     	/**************************************************************************
     	 * 	Load Workflow & Nodes
     	 * 	@param readWrite if true, you can move nodes
    @@ -304,7 +301,7 @@ public class WFPanel extends CPanel
     			return;
     		load (pp.getKey(), readWrite);
     	}	//	load
    -	
    +
     	/**
     	 * 	Load Workflow & Nodes
     	 * 	@param AD_Workflow_ID ID
    @@ -320,23 +317,33 @@ public class WFPanel extends CPanel
     		m_wf = new MWorkflow (Env.getCtx(), AD_Workflow_ID, null);
     		centerPanel.removeAll();
     		centerPanel.setReadWrite(readWrite);
    +		centerPanel.getGraphScene().addObjectSceneListener(this, ObjectSceneEventType.OBJECT_SELECTION_CHANGED);
    +
     		if (readWrite)
     			centerPanel.setWorkflow(m_wf);
    -		//	Add Nodes for Paint
    +		
    +		// Add Nodes
     		MWFNode[] nodes = m_wf.getNodes(true, AD_Client_ID);
    +		List added = new ArrayList();
     		for (int i = 0; i < nodes.length; i++)
     		{
    -			WFNode wfn = new WFNode (nodes[i]);
    -			wfn.addPropertyChangeListener(WFNode.PROPERTY_SELECTED, this);
     			boolean rw = readWrite 		//	in editor mode & owned
     				&& (AD_Client_ID == nodes[i].getAD_Client_ID());
    -			centerPanel.add (wfn, rw);
    -			//	Add Lines
    +			if (!added.contains(nodes[i].getAD_WF_Node_ID()))
    +				centerPanel.addNode(nodes[i]);			
    +		}
    +		
    +		// Add Lines
    +		for (int i = 0; i < nodes.length; i++)
    +		{
     			MWFNodeNext[] nexts = nodes[i].getTransitions(AD_Client_ID);
     			for (int j = 0; j < nexts.length; j++)
    -				centerPanel.add (new WFLine (nexts[j]), false);
    +			{
    +				centerPanel.addEdge(nexts[j]);
    +			}
     		}
    -		//	Info Text
    +		
    +		// Info Text
     		StringBuffer msg = new StringBuffer("");
     		msg.append("

    ").append(m_wf.getName(true)).append("

    "); String s = m_wf.getDescription(true); @@ -350,22 +357,10 @@ public class WFPanel extends CPanel infoTextPane.setCaretPosition(0); // Layout - centerPanel.validate(); - centerPanel.repaint(); + centerPanel.relayout(); validate(); } // load - /** - * Property Change Listener - * @param e event - * @see java.beans.PropertyChangeListener#propertyChange(PropertyChangeEvent) - */ - public void propertyChange (PropertyChangeEvent e) - { - if (e.getNewValue() == Boolean.TRUE) - start ((WFNode)e.getSource()); - } // propertyChange - /** * Action Listener * @param e event @@ -416,17 +411,16 @@ public class WFPanel extends CPanel * Start Node * @param node node */ - public void start (WFNode node) + public void start (MWFNode node) { log.fine("Node=" + node); - MWFNode model = node.getModel(); // Info Text StringBuffer msg = new StringBuffer(""); - msg.append("

    ").append(model.getName(true)).append("

    "); - String s = model.getDescription(true); + msg.append("

    ").append(node.getName(true)).append("

    "); + String s = node.getDescription(true); if (s != null && s.length() > 0) msg.append("").append(s).append(""); - s = model.getHelp(true); + s = node.getHelp(true); if (s != null && s.length() > 0) msg.append("
    ").append(s); msg.append(""); @@ -435,7 +429,7 @@ public class WFPanel extends CPanel // Load Window if (m_menu != null) - (new AMenuStartItem(model.getAD_WF_Node_ID(), false, model.getName(true), m_menu)).start(); // async load + (new AMenuStartItem(node.getAD_WF_Node_ID(), false, node.getName(true), m_menu)).start(); // async load // m_activeNode = node; // @@ -457,19 +451,15 @@ public class WFPanel extends CPanel if (AD_WF_Node_ID == 0) return; // - for (int i = 0; i < centerPanel.getComponentCount(); i++) - { - Component comp = centerPanel.getComponent(i); - if (comp instanceof WFNode) - { - WFNode node = (WFNode)comp; - if (node.getAD_WF_Node_ID() == AD_WF_Node_ID) - { - start (node); - return; - } - } // WFNode - } // for all components + Object object = centerPanel.getGraphScene().findWidget(AD_WF_Node_ID); + if (object != null) { + WFNodeWidget widget = (WFNodeWidget) object; + widget.setBackground (Color.CYAN); + if (selectedWidget != null) + selectedWidget.setBackground(Color.WHITE); + selectedWidget = widget; + start(widget.getModel()); + } } // start /** @@ -497,7 +487,7 @@ public class WFPanel extends CPanel if (m_WF_Window_ID <= 0) { throw new AdempiereException("@NotFound@ @AD_Window_ID@"); } - + MQuery query = null; if (m_wf != null) query = MQuery.getEqualQuery("AD_Workflow_ID", m_wf.getAD_Workflow_ID()); @@ -538,4 +528,51 @@ public class WFPanel extends CPanel } // main + //ObjectSceneListener + public void focusChanged(ObjectSceneEvent arg0, Object arg1, Object arg2) { + // TODO Auto-generated method stub + + } + + public void highlightingChanged(ObjectSceneEvent arg0, Set arg1, + Set arg2) { + // TODO Auto-generated method stub + + } + + public void hoverChanged(ObjectSceneEvent arg0, Object arg1, Object arg2) { + // TODO Auto-generated method stub + + } + + public void objectAdded(ObjectSceneEvent arg0, Object arg1) { + // TODO Auto-generated method stub + + } + + public void objectRemoved(ObjectSceneEvent arg0, Object arg1) { + // TODO Auto-generated method stub + + } + + public void objectStateChanged(ObjectSceneEvent event, Object changedObject, + ObjectState previousState, ObjectState newState) { + Widget w = (Widget) changedObject; + System.out.println("location="+w.getLocation()); + } + + public void selectionChanged(ObjectSceneEvent event, Set prevSelection, + Set selection) { + if (selection != null && selection.size() > 0) { + Object selected = selection.toArray()[selection.size() - 1]; + WFNodeWidget widget = (WFNodeWidget) centerPanel.getGraphScene().findWidget(selected); + widget.setBackground (Color.CYAN); + if (selectedWidget != null) + selectedWidget.setBackground(Color.WHITE); + selectedWidget = widget; + start(widget.getModel()); + } + } + + } // WFPanel diff --git a/client/src/org/compiere/apps/wf/WFPopupItem.java b/client/src/org/compiere/apps/wf/WFPopupItem.java new file mode 100644 index 0000000000..559366a30e --- /dev/null +++ b/client/src/org/compiere/apps/wf/WFPopupItem.java @@ -0,0 +1,85 @@ +package org.compiere.apps.wf; + +import javax.swing.JMenuItem; +import javax.swing.SwingUtilities; + +import org.compiere.util.CLogger; +import org.compiere.util.Env; +import org.compiere.wf.MWFNode; +import org.compiere.wf.MWFNodeNext; + +public class WFPopupItem extends JMenuItem { + + /** + * + */ + private static final long serialVersionUID = 4634863991042969718L; + private int m_AD_Workflow_ID; + + private static final CLogger log = CLogger.getCLogger(WFPopupItem.class); + + /** + * Add Line Item + * @param title title + * @param node node + * @param AD_WF_NodeTo_ID line to + */ + public WFPopupItem (String title, MWFNode node, int AD_WF_NodeTo_ID) + { + super (title); + m_node = node; + m_AD_WF_NodeTo_ID = AD_WF_NodeTo_ID; + m_AD_Workflow_ID = node.getAD_Workflow_ID(); + } // WFPopupItem + + /** + * Delete Line Item + * @param title title + * @param line line to be deleted + */ + public WFPopupItem (String title, MWFNodeNext line) + { + super (title); + m_line = line; + } // WFPopupItem + + /** The Node */ + private MWFNode m_node; + /** The Line */ + private MWFNodeNext m_line; + /** The Next Node ID */ + private int m_AD_WF_NodeTo_ID; + + /** + * Execute + */ + public void execute(final WFPanel wfp) + { + // Add Line + if (m_node != null && m_AD_WF_NodeTo_ID > 0) + { + int AD_Client_ID = Env.getAD_Client_ID(Env.getCtx()); + MWFNodeNext newLine = new MWFNodeNext(m_node, m_AD_WF_NodeTo_ID); + newLine.setClientOrg(AD_Client_ID, 0); + newLine.save(); + log.info("Add Line to " + m_node + " -> " + newLine); + wfp.load(m_AD_Workflow_ID, true); + } + // Delete Node + else if (m_node != null && m_AD_WF_NodeTo_ID == -1) + { + log.info("Delete Node: " + m_node); + m_node.delete(false); + wfp.load(m_AD_Workflow_ID, true); + } + // Delete Line + else if (m_line != null) + { + log.info("Delete Line: " + m_line); + m_line.delete(false); + wfp.load(m_AD_Workflow_ID, true); + } + else + log.warning("No Action??"); + } // execute +} diff --git a/base/src/org/compiere/db/CConnectionDialog.java b/client/src/org/compiere/db/CConnectionDialog.java similarity index 100% rename from base/src/org/compiere/db/CConnectionDialog.java rename to client/src/org/compiere/db/CConnectionDialog.java diff --git a/base/src/org/compiere/db/CConnectionEditor.java b/client/src/org/compiere/db/CConnectionEditor.java similarity index 100% rename from base/src/org/compiere/db/CConnectionEditor.java rename to client/src/org/compiere/db/CConnectionEditor.java diff --git a/base/src/org/compiere/dbPort/ConvertDialog.java b/client/src/org/compiere/dbPort/ConvertDialog.java similarity index 100% rename from base/src/org/compiere/dbPort/ConvertDialog.java rename to client/src/org/compiere/dbPort/ConvertDialog.java diff --git a/client/src/org/compiere/grid/VCreateFromDialog.java b/client/src/org/compiere/grid/VCreateFromDialog.java index 0ee15d7162..23b2d9ead9 100644 --- a/client/src/org/compiere/grid/VCreateFromDialog.java +++ b/client/src/org/compiere/grid/VCreateFromDialog.java @@ -26,6 +26,7 @@ import javax.swing.event.TableModelListener; import javax.swing.table.TableModel; import org.compiere.apps.ADialog; +import org.compiere.apps.AEnv; import org.compiere.apps.AppsAction; import org.compiere.apps.ConfirmPanel; import org.compiere.apps.StatusBar; @@ -33,7 +34,6 @@ import org.compiere.minigrid.MiniTable; import org.compiere.swing.CButton; import org.compiere.swing.CDialog; import org.compiere.swing.CPanel; -import org.compiere.util.Env; import org.compiere.util.Trx; import org.compiere.util.TrxRunnable; @@ -53,7 +53,7 @@ public class VCreateFromDialog extends CDialog implements ActionListener, TableM public VCreateFromDialog(CreateFrom createFrom, int windowNo, boolean modal) { - super(Env.getWindow(windowNo), modal); + super(AEnv.getWindow(windowNo), modal); this.createFrom = createFrom; this.windowNo = windowNo; diff --git a/client/src/org/compiere/grid/VCreateFromInvoiceUI.java b/client/src/org/compiere/grid/VCreateFromInvoiceUI.java index bb39b6c8ad..70c6665551 100644 --- a/client/src/org/compiere/grid/VCreateFromInvoiceUI.java +++ b/client/src/org/compiere/grid/VCreateFromInvoiceUI.java @@ -70,7 +70,7 @@ public class VCreateFromInvoiceUI extends CreateFromInvoice implements ActionLis log.log(Level.SEVERE, "", e); setInitOK(false); } - AEnv.positionCenterWindow(Env.getWindow(p_WindowNo), dialog); + AEnv.positionCenterWindow(AEnv.getWindow(p_WindowNo), dialog); } // VCreateFrom /** Window No */ diff --git a/client/src/org/compiere/grid/VCreateFromRMAUI.java b/client/src/org/compiere/grid/VCreateFromRMAUI.java index 72aea94213..f5b6e41f8f 100644 --- a/client/src/org/compiere/grid/VCreateFromRMAUI.java +++ b/client/src/org/compiere/grid/VCreateFromRMAUI.java @@ -64,7 +64,7 @@ public class VCreateFromRMAUI extends CreateFromRMA implements VetoableChangeLis log.log(Level.SEVERE, "", e); setInitOK(false); } - AEnv.positionCenterWindow(Env.getWindow(p_WindowNo), dialog); + AEnv.positionCenterWindow(AEnv.getWindow(p_WindowNo), dialog); } // VCreateFrom /** Window No */ diff --git a/client/src/org/compiere/grid/VCreateFromShipmentUI.java b/client/src/org/compiere/grid/VCreateFromShipmentUI.java index 6a473c3259..33f67cfbe2 100644 --- a/client/src/org/compiere/grid/VCreateFromShipmentUI.java +++ b/client/src/org/compiere/grid/VCreateFromShipmentUI.java @@ -89,7 +89,7 @@ public class VCreateFromShipmentUI extends CreateFromShipment implements ActionL log.log(Level.SEVERE, "", e); setInitOK(false); } - AEnv.positionCenterWindow(Env.getWindow(p_WindowNo), dialog); + AEnv.positionCenterWindow(AEnv.getWindow(p_WindowNo), dialog); } // VCreateFrom /** Window No */ diff --git a/client/src/org/compiere/grid/VCreateFromStatementUI.java b/client/src/org/compiere/grid/VCreateFromStatementUI.java index 171900db9b..ea9dc18a4f 100644 --- a/client/src/org/compiere/grid/VCreateFromStatementUI.java +++ b/client/src/org/compiere/grid/VCreateFromStatementUI.java @@ -80,7 +80,7 @@ public class VCreateFromStatementUI extends CreateFromStatement implements Actio log.log(Level.SEVERE, "", e); setInitOK(false); } - AEnv.positionCenterWindow(Env.getWindow(p_WindowNo), dialog); + AEnv.positionCenterWindow(AEnv.getWindow(p_WindowNo), dialog); } // VCreateFrom /** Window No */ diff --git a/client/src/org/compiere/grid/VPayment.java b/client/src/org/compiere/grid/VPayment.java index 09c5d88cfe..4b6210d1ce 100644 --- a/client/src/org/compiere/grid/VPayment.java +++ b/client/src/org/compiere/grid/VPayment.java @@ -123,7 +123,7 @@ public class VPayment extends CDialog */ public VPayment (int WindowNo, GridTab mTab, VButton button) { - super(Env.getWindow(WindowNo), Msg.getMsg(Env.getCtx(), "Payment"), true); + super(AEnv.getWindow(WindowNo), Msg.getMsg(Env.getCtx(), "Payment"), true); m_WindowNo = WindowNo; m_isSOTrx = "Y".equals(Env.getContext(Env.getCtx(), WindowNo, "IsSOTrx")); m_mTab = mTab; @@ -139,7 +139,7 @@ public class VPayment extends CDialog m_initOK = false; } // - AEnv.positionCenterWindow(Env.getWindow(WindowNo), this); + AEnv.positionCenterWindow(AEnv.getWindow(WindowNo), this); } // VPayment /** Window */ diff --git a/client/src/org/compiere/grid/ed/Calculator.java b/client/src/org/compiere/grid/ed/Calculator.java index 4b880bdee3..faf845f1d1 100644 --- a/client/src/org/compiere/grid/ed/Calculator.java +++ b/client/src/org/compiere/grid/ed/Calculator.java @@ -45,6 +45,7 @@ import javax.swing.SwingConstants; import org.adempiere.plaf.AdempierePLAF; import org.compiere.apps.ADialog; +import org.compiere.apps.AEnv; import org.compiere.model.MConversionRate; import org.compiere.swing.CDialog; import org.compiere.swing.CPanel; @@ -83,7 +84,7 @@ public final class Calculator extends CDialog super(frame, title, true); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); // Get WindowNo for Currency - m_WindowNo = Env.getWindowNo(frame); + m_WindowNo = AEnv.getWindowNo(frame); // m_DisplayType = displayType; if (!DisplayType.isNumeric(m_DisplayType)) diff --git a/client/src/org/compiere/grid/ed/Editor.java b/client/src/org/compiere/grid/ed/Editor.java index 42028fbecf..463a08682b 100644 --- a/client/src/org/compiere/grid/ed/Editor.java +++ b/client/src/org/compiere/grid/ed/Editor.java @@ -81,7 +81,7 @@ public class Editor extends CDialog public static String startEditor(Container jc, String header, String text, boolean editable, int maxSize) { // Find frame - JFrame frame = Env.getFrame(jc); + JFrame frame = AEnv.getFrame(jc); String hdr = header; if (hdr == null || hdr.length() == 0) hdr = Msg.getMsg(Env.getCtx(), "Editor"); diff --git a/client/src/org/compiere/grid/ed/VAccount.java b/client/src/org/compiere/grid/ed/VAccount.java index 22202985cf..c6a457e873 100644 --- a/client/src/org/compiere/grid/ed/VAccount.java +++ b/client/src/org/compiere/grid/ed/VAccount.java @@ -40,6 +40,7 @@ import javax.swing.LookAndFeel; import javax.swing.SwingUtilities; import org.adempiere.plaf.AdempierePLAF; +import org.compiere.apps.AEnv; import org.compiere.apps.FieldRecordInfo; import org.compiere.model.GridField; import org.compiere.model.MAccountLookup; @@ -320,7 +321,7 @@ public final class VAccount extends JComponent { C_AcctSchema_ID = Env.getContextAsInt(Env.getCtx(), "$C_AcctSchema_ID"); } - VAccountDialog ad = new VAccountDialog (Env.getFrame(this), m_title, + VAccountDialog ad = new VAccountDialog (AEnv.getFrame(this), m_title, m_mAccount, C_AcctSchema_ID); setCursor(Cursor.getDefaultCursor()); // diff --git a/client/src/org/compiere/grid/ed/VAccountDialog.java b/client/src/org/compiere/grid/ed/VAccountDialog.java index b78ab99c0a..6e0d7a56a2 100644 --- a/client/src/org/compiere/grid/ed/VAccountDialog.java +++ b/client/src/org/compiere/grid/ed/VAccountDialog.java @@ -121,7 +121,7 @@ public final class VAccountDialog extends CDialog + ", C_ValidCombination_ID=" + mAccount.C_ValidCombination_ID); m_mAccount = mAccount; m_C_AcctSchema_ID = C_AcctSchema_ID; - m_WindowNo = Env.createWindowNo (this); + m_WindowNo = AEnv.createWindowNo (this); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); try { @@ -273,7 +273,7 @@ public final class VAccountDialog extends CDialog // Model int AD_Window_ID = 153; // Maintain Account Combinations - GridWindowVO wVO = AEnv.getMWindowVO (m_WindowNo, AD_Window_ID, 0); + GridWindowVO wVO = Env.getMWindowVO (m_WindowNo, AD_Window_ID, 0); if (wVO == null) return false; m_mWindow = new GridWindow (wVO); diff --git a/client/src/org/compiere/grid/ed/VAssignment.java b/client/src/org/compiere/grid/ed/VAssignment.java index b6061eec3a..ec1f3846dd 100644 --- a/client/src/org/compiere/grid/ed/VAssignment.java +++ b/client/src/org/compiere/grid/ed/VAssignment.java @@ -40,6 +40,7 @@ import javax.swing.LookAndFeel; import javax.swing.SwingUtilities; import org.adempiere.plaf.AdempierePLAF; +import org.compiere.apps.AEnv; import org.compiere.apps.FieldRecordInfo; import org.compiere.apps.search.InfoSchedule; import org.compiere.model.GridField; @@ -392,13 +393,13 @@ public class VAssignment extends JComponent // Start VAssignment Dialog if (S_ResourceAssignment_ID != 0) { - VAssignmentDialog vad = new VAssignmentDialog (Env.getFrame(this), ma, true, true); + VAssignmentDialog vad = new VAssignmentDialog (AEnv.getFrame(this), ma, true, true); ma = vad.getMResourceAssignment(); } // Start InfoSchedule directly else { - InfoSchedule is = new InfoSchedule(Env.getFrame(this), ma, true); + InfoSchedule is = new InfoSchedule(AEnv.getFrame(this), ma, true); ma = is.getMResourceAssignment(); } diff --git a/client/src/org/compiere/grid/ed/VDate.java b/client/src/org/compiere/grid/ed/VDate.java index ad71199fc6..a04bafc57e 100644 --- a/client/src/org/compiere/grid/ed/VDate.java +++ b/client/src/org/compiere/grid/ed/VDate.java @@ -541,7 +541,7 @@ public class VDate extends JComponent log.config("Date=" + value); // Find frame - Frame frame = Env.getFrame(jc); + Frame frame = AEnv.getFrame(jc); // Actual Call Calendar cal = new Calendar(frame, title, value, displayType); AEnv.showCenterWindow(frame, cal); diff --git a/client/src/org/compiere/grid/ed/VDocAction.java b/client/src/org/compiere/grid/ed/VDocAction.java index 03ba6972c9..12c8a4758b 100644 --- a/client/src/org/compiere/grid/ed/VDocAction.java +++ b/client/src/org/compiere/grid/ed/VDocAction.java @@ -72,7 +72,7 @@ public class VDocAction extends CDialog */ public VDocAction (int WindowNo, GridTab mTab, VButton button, int Record_ID) { - super(Env.getWindow(WindowNo), Msg.translate(Env.getCtx(), "DocAction"), true); + super(AEnv.getWindow(WindowNo), Msg.translate(Env.getCtx(), "DocAction"), true); log.config(""); m_WindowNo = WindowNo; m_mTab = mTab; @@ -93,7 +93,7 @@ public class VDocAction extends CDialog // dynInit(Record_ID); // - AEnv.positionCenterWindow(Env.getWindow(WindowNo), this); + AEnv.positionCenterWindow(AEnv.getWindow(WindowNo), this); } // VDocAction // diff --git a/client/src/org/compiere/grid/ed/VImage.java b/client/src/org/compiere/grid/ed/VImage.java index d55d1ebdbb..38d6259b8e 100644 --- a/client/src/org/compiere/grid/ed/VImage.java +++ b/client/src/org/compiere/grid/ed/VImage.java @@ -26,6 +26,7 @@ import java.beans.PropertyVetoException; import javax.swing.ImageIcon; import javax.swing.JButton; +import org.compiere.apps.AEnv; import org.compiere.model.MImage; import org.compiere.util.CLogger; import org.compiere.util.Env; @@ -216,7 +217,7 @@ public class VImage extends JButton */ public void actionPerformed (ActionEvent e) { - VImageDialog vid = new VImageDialog(Env.getWindow(m_WindowNo), m_mImage); + VImageDialog vid = new VImageDialog(AEnv.getWindow(m_WindowNo), m_mImage); vid.setVisible(true); int AD_Image_ID = vid.getAD_Image_ID(); Integer newValue = null; diff --git a/client/src/org/compiere/grid/ed/VLocation.java b/client/src/org/compiere/grid/ed/VLocation.java index e70f2be01e..9854c933ad 100644 --- a/client/src/org/compiere/grid/ed/VLocation.java +++ b/client/src/org/compiere/grid/ed/VLocation.java @@ -35,6 +35,7 @@ import javax.swing.LookAndFeel; import javax.swing.SwingUtilities; import org.adempiere.plaf.AdempierePLAF; +import org.compiere.apps.AEnv; import org.compiere.apps.FieldRecordInfo; import org.compiere.model.GridField; import org.compiere.model.GridTab; @@ -351,7 +352,7 @@ public class VLocation extends JComponent m_value = null; // create new // log.config( "actionPerformed - " + m_value); - VLocationDialog ld = new VLocationDialog(Env.getFrame(this), + VLocationDialog ld = new VLocationDialog(AEnv.getFrame(this), Msg.getMsg(Env.getCtx(), "Location"), m_value); ld.setVisible(true); Object oldValue = getValue(); diff --git a/client/src/org/compiere/grid/ed/VLocator.java b/client/src/org/compiere/grid/ed/VLocator.java index 0e76487133..408358fbc5 100644 --- a/client/src/org/compiere/grid/ed/VLocator.java +++ b/client/src/org/compiere/grid/ed/VLocator.java @@ -406,7 +406,7 @@ public class VLocator extends JComponent // m_mLocator.setOnly_Warehouse_ID(only_Warehouse_ID); m_mLocator.setOnly_Product_ID(getOnly_Product_ID()); - VLocatorDialog ld = new VLocatorDialog(Env.getFrame(this), + VLocatorDialog ld = new VLocatorDialog(AEnv.getFrame(this), Msg.translate(Env.getCtx(), m_columnName), m_mLocator, M_Locator_ID, isMandatory(), only_Warehouse_ID); // display diff --git a/client/src/org/compiere/grid/ed/VLocatorDialog.java b/client/src/org/compiere/grid/ed/VLocatorDialog.java index a1b05215a0..8d5208a86b 100644 --- a/client/src/org/compiere/grid/ed/VLocatorDialog.java +++ b/client/src/org/compiere/grid/ed/VLocatorDialog.java @@ -78,7 +78,7 @@ public class VLocatorDialog extends CDialog int M_Locator_ID, boolean mandatory, int only_Warehouse_ID) { super (frame, title, true); - m_WindowNo = Env.getWindowNo(frame); + m_WindowNo = AEnv.getWindowNo(frame); try { jbInit(); diff --git a/client/src/org/compiere/grid/ed/VLookup.java b/client/src/org/compiere/grid/ed/VLookup.java index 10ece795e3..adac9685c8 100644 --- a/client/src/org/compiere/grid/ed/VLookup.java +++ b/client/src/org/compiere/grid/ed/VLookup.java @@ -819,7 +819,7 @@ public class VLookup extends JComponent if (m_lookup == null) return; // leave button disabled m_text.requestFocus(); // closes other editors - Frame frame = Env.getFrame(this); + Frame frame = AEnv.getFrame(this); /** * Three return options: @@ -1305,7 +1305,7 @@ public class VLookup extends JComponent */ private void actionBPartner (boolean newRecord) { - VBPartner vbp = new VBPartner (Env.getFrame(this), m_lookup.getWindowNo()); + VBPartner vbp = new VBPartner (AEnv.getFrame(this), m_lookup.getWindowNo()); int BPartner_ID = 0; // if update, get current value if (!newRecord) diff --git a/client/src/org/compiere/grid/ed/VMemo.java b/client/src/org/compiere/grid/ed/VMemo.java index 612861acd5..f1302cf488 100644 --- a/client/src/org/compiere/grid/ed/VMemo.java +++ b/client/src/org/compiere/grid/ed/VMemo.java @@ -36,6 +36,7 @@ import javax.swing.LookAndFeel; import javax.swing.SwingUtilities; import org.adempiere.plaf.AdempierePLAF; +import org.compiere.apps.AEnv; import org.compiere.apps.ScriptEditor; import org.compiere.swing.CMenuItem; import org.compiere.swing.CTextArea; @@ -194,7 +195,7 @@ public class VMemo extends CTextArea String s = null; if (m_columnName.equals("Script") || m_columnName.endsWith("_Script")) s = ScriptEditor.start ( - Env.getFrame(this.getParent()), + AEnv.getFrame(this.getParent()), Msg.translate(Env.getCtx(), m_columnName), getText(), isEditable(), findWindowNo()); else @@ -213,7 +214,7 @@ public class VMemo extends CTextArea private int findWindowNo() { Container c = this.getParent(); - return c != null ? Env.getWindowNo(c) : 0; + return c != null ? AEnv.getWindowNo(c) : 0; } /** diff --git a/client/src/org/compiere/grid/ed/VNumber.java b/client/src/org/compiere/grid/ed/VNumber.java index 788e008f4c..3ab659526d 100644 --- a/client/src/org/compiere/grid/ed/VNumber.java +++ b/client/src/org/compiere/grid/ed/VNumber.java @@ -731,7 +731,7 @@ public final class VNumber extends JComponent } // Find frame - Frame frame = Env.getFrame(jc); + Frame frame = AEnv.getFrame(jc); // Actual Call Calculator calc = new Calculator(frame, title, displayType, format, startValue); diff --git a/client/src/org/compiere/grid/ed/VPAttribute.java b/client/src/org/compiere/grid/ed/VPAttribute.java index 217d3809cf..31d4b4e8fb 100644 --- a/client/src/org/compiere/grid/ed/VPAttribute.java +++ b/client/src/org/compiere/grid/ed/VPAttribute.java @@ -36,6 +36,7 @@ import javax.swing.LookAndFeel; import javax.swing.SwingUtilities; import org.adempiere.plaf.AdempierePLAF; +import org.compiere.apps.AEnv; import org.compiere.apps.FieldRecordInfo; import org.compiere.model.GridField; import org.compiere.model.GridTab; @@ -415,7 +416,7 @@ public class VPAttribute extends JComponent } else { - VPAttributeDialog vad = new VPAttributeDialog (Env.getFrame (this), + VPAttributeDialog vad = new VPAttributeDialog (AEnv.getFrame (this), M_AttributeSetInstance_ID, M_Product_ID, m_C_BPartner_ID, productWindow, m_AD_Column_ID, m_WindowNo); if (vad.isChanged()) diff --git a/client/src/org/compiere/grid/ed/VPAttributeDialog.java b/client/src/org/compiere/grid/ed/VPAttributeDialog.java index 589fdbdcde..853c5b9296 100644 --- a/client/src/org/compiere/grid/ed/VPAttributeDialog.java +++ b/client/src/org/compiere/grid/ed/VPAttributeDialog.java @@ -135,7 +135,7 @@ public class VPAttributeDialog extends CDialog + ", M_Product_ID=" + M_Product_ID + ", C_BPartner_ID=" + C_BPartner_ID + ", ProductW=" + productWindow + ", Column=" + AD_Column_ID); - m_WindowNo = Env.createWindowNo (this); + m_WindowNo = AEnv.createWindowNo (this); m_M_AttributeSetInstance_ID = M_AttributeSetInstance_ID; m_M_Product_ID = M_Product_ID; m_C_BPartner_ID = C_BPartner_ID; diff --git a/client/src/org/compiere/grid/ed/VText.java b/client/src/org/compiere/grid/ed/VText.java index bdd16088fe..df61da9049 100644 --- a/client/src/org/compiere/grid/ed/VText.java +++ b/client/src/org/compiere/grid/ed/VText.java @@ -34,6 +34,7 @@ import javax.swing.LookAndFeel; import javax.swing.SwingUtilities; import org.adempiere.plaf.AdempierePLAF; +import org.compiere.apps.AEnv; import org.compiere.apps.FieldRecordInfo; import org.compiere.apps.ScriptEditor; import org.compiere.model.GridField; @@ -185,7 +186,7 @@ public class VText extends CTextArea String s = null; if (m_columnName.equals("Script") || m_columnName.endsWith("_Script")) s = ScriptEditor.start ( - Env.getFrame(this.getParent()), + AEnv.getFrame(this.getParent()), Msg.translate(Env.getCtx(), m_columnName), getText(), isEditable(), findWindowNo()); else @@ -208,7 +209,7 @@ public class VText extends CTextArea private int findWindowNo() { Container c = this.getParent(); - return c != null ? Env.getWindowNo(c) : 0; + return c != null ? AEnv.getWindowNo(c) : 0; } /** diff --git a/client/src/org/compiere/grid/ed/VTextLong.java b/client/src/org/compiere/grid/ed/VTextLong.java index cd0a08c1bf..1b3117eade 100644 --- a/client/src/org/compiere/grid/ed/VTextLong.java +++ b/client/src/org/compiere/grid/ed/VTextLong.java @@ -36,6 +36,7 @@ import javax.swing.LookAndFeel; import javax.swing.SwingUtilities; import org.adempiere.plaf.AdempierePLAF; +import org.compiere.apps.AEnv; import org.compiere.apps.FieldRecordInfo; import org.compiere.model.GridField; import org.compiere.swing.CMenuItem; @@ -100,7 +101,7 @@ public class VTextLong extends CTextPane public static String startEditor(Container jc, String header, String text, boolean editable) { // Find frame - JFrame frame = Env.getFrame(jc); + JFrame frame = AEnv.getFrame(jc); // Start it HTMLEditor ed = new HTMLEditor (frame, header, text, editable); String s = ed.getHtmlText(); diff --git a/client/src/org/compiere/grid/ed/ValuePreference.java b/client/src/org/compiere/grid/ed/ValuePreference.java index 9887f07c35..83f01e8fb8 100644 --- a/client/src/org/compiere/grid/ed/ValuePreference.java +++ b/client/src/org/compiere/grid/ed/ValuePreference.java @@ -118,7 +118,7 @@ public class ValuePreference extends CDialog int AD_Client_ID = Env.getAD_Client_ID(Env.getCtx()); int AD_Org_ID = Env.getContextAsInt(Env.getCtx(), WindowNo, "AD_Org_ID"); int AD_User_ID = Env.getAD_User_ID(Env.getCtx()); - Frame frame = Env.getWindow(WindowNo); + Frame frame = AEnv.getWindow(WindowNo); // Create Editor ValuePreference vp = new ValuePreference (frame, WindowNo, diff --git a/client/src/org/compiere/grid/tree/VTreePanel.java b/client/src/org/compiere/grid/tree/VTreePanel.java index 093b12fdd4..48528536fd 100644 --- a/client/src/org/compiere/grid/tree/VTreePanel.java +++ b/client/src/org/compiere/grid/tree/VTreePanel.java @@ -65,6 +65,7 @@ import javax.swing.tree.TreePath; import org.adempiere.plaf.AdempierePLAF; import org.adempiere.plaf.AdempiereTaskPaneUI; import org.compiere.apps.ADialog; +import org.compiere.apps.AEnv; import org.compiere.model.MTree; import org.compiere.model.MTreeNode; import org.compiere.swing.CButton; @@ -78,8 +79,6 @@ import org.compiere.util.CLogger; import org.compiere.util.DB; import org.compiere.util.Env; import org.compiere.util.Msg; -import org.compiere.util.Trx; -import org.compiere.util.TrxRunnable; import org.jdesktop.swingx.JXTaskPane; import org.jdesktop.swingx.JXTaskPaneContainer; @@ -1005,7 +1004,7 @@ public final class VTreePanel extends CPanel */ private void setBusy (boolean busy) { - JFrame frame = Env.getFrame(this); + JFrame frame = AEnv.getFrame(this); log.info("frame: " + frame); if (frame == null) // during init return; diff --git a/base/src/org/compiere/plaf/Adempiere200x100.gif b/client/src/org/compiere/plaf/Adempiere200x100.gif similarity index 100% rename from base/src/org/compiere/plaf/Adempiere200x100.gif rename to client/src/org/compiere/plaf/Adempiere200x100.gif diff --git a/base/src/org/compiere/plaf/AquaTheme.java b/client/src/org/compiere/plaf/AquaTheme.java similarity index 100% rename from base/src/org/compiere/plaf/AquaTheme.java rename to client/src/org/compiere/plaf/AquaTheme.java diff --git a/base/src/org/compiere/plaf/CharcoalTheme.java b/client/src/org/compiere/plaf/CharcoalTheme.java similarity index 100% rename from base/src/org/compiere/plaf/CharcoalTheme.java rename to client/src/org/compiere/plaf/CharcoalTheme.java diff --git a/base/src/org/compiere/plaf/CompiereButtonListener.java b/client/src/org/compiere/plaf/CompiereButtonListener.java similarity index 100% rename from base/src/org/compiere/plaf/CompiereButtonListener.java rename to client/src/org/compiere/plaf/CompiereButtonListener.java diff --git a/base/src/org/compiere/plaf/CompiereButtonUI.java b/client/src/org/compiere/plaf/CompiereButtonUI.java similarity index 100% rename from base/src/org/compiere/plaf/CompiereButtonUI.java rename to client/src/org/compiere/plaf/CompiereButtonUI.java diff --git a/base/src/org/compiere/plaf/CompiereCheckBoxMenuItemUI.java b/client/src/org/compiere/plaf/CompiereCheckBoxMenuItemUI.java similarity index 100% rename from base/src/org/compiere/plaf/CompiereCheckBoxMenuItemUI.java rename to client/src/org/compiere/plaf/CompiereCheckBoxMenuItemUI.java diff --git a/base/src/org/compiere/plaf/CompiereCheckBoxUI.java b/client/src/org/compiere/plaf/CompiereCheckBoxUI.java similarity index 100% rename from base/src/org/compiere/plaf/CompiereCheckBoxUI.java rename to client/src/org/compiere/plaf/CompiereCheckBoxUI.java diff --git a/base/src/org/compiere/plaf/CompiereColor.java b/client/src/org/compiere/plaf/CompiereColor.java similarity index 92% rename from base/src/org/compiere/plaf/CompiereColor.java rename to client/src/org/compiere/plaf/CompiereColor.java index 49106e970b..84f8c85e83 100644 --- a/base/src/org/compiere/plaf/CompiereColor.java +++ b/client/src/org/compiere/plaf/CompiereColor.java @@ -29,8 +29,10 @@ import java.awt.TexturePaint; import java.awt.Window; import java.awt.image.BufferedImage; import java.io.Serializable; +import java.math.BigDecimal; import java.net.URL; import java.util.ResourceBundle; +import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JComponent; @@ -43,6 +45,7 @@ import javax.swing.UIManager; import javax.swing.plaf.ColorUIResource; import org.adempiere.plaf.AdempierePLAF; +import org.compiere.model.MColor; import org.compiere.swing.ColorBlind; import org.compiere.swing.ThemeUtils; import org.compiere.util.KeyNamePair; @@ -221,6 +224,53 @@ public class CompiereColor implements Serializable return cc; } // parse + /************************************************************************** + * Get CompiereColor. + * @return CompiereColor + */ + public static CompiereColor getCompiereColor(MColor color) + { + if (color == null || color.get_ID() == 0) + return null; + + // Color Type + String ColorType = (String)color.getColorType(); + if (ColorType == null) + { + log.log(Level.SEVERE, "MColor.getAdempiereColor - No ColorType"); + return null; + } + CompiereColor cc = null; + // + if (ColorType.equals(CompiereColor.TYPE_FLAT)) + { + cc = new CompiereColor(color.getColor(true), true); + } + else if (ColorType.equals(CompiereColor.TYPE_GRADIENT)) + { + int RepeatDistance = color.getRepeatDistance(); + String StartPoint = color.getStartPoint(); + int startPoint = StartPoint == null ? 0 : Integer.parseInt(StartPoint); + cc = new CompiereColor(color.getColor(true), color.getColor(false), startPoint, RepeatDistance); + } + else if (ColorType.equals(CompiereColor.TYPE_LINES)) + { + int LineWidth = color.getLineWidth(); + int LineDistance = color.getLineDistance(); + cc = new CompiereColor(color.getColor(false), color.getColor(true), LineWidth, LineDistance); + } + else if (ColorType.equals(CompiereColor.TYPE_TEXTURE)) + { + int AD_Image_ID = color.getAD_Image_ID(); + String url = color.getURL(AD_Image_ID); + if (url == null) + return null; + BigDecimal ImageAlpha = color.getImageAlpha(); + float compositeAlpha = ImageAlpha == null ? 0.7f : ImageAlpha.floatValue(); + cc = new CompiereColor(url, color.getColor(true), compositeAlpha); + } + return cc; + } // getAdempiereColor /************************************************************************* * Create Gradient Background Color (Window System Color - White) diff --git a/base/src/org/compiere/plaf/CompiereComboBoxUI.java b/client/src/org/compiere/plaf/CompiereComboBoxUI.java similarity index 100% rename from base/src/org/compiere/plaf/CompiereComboBoxUI.java rename to client/src/org/compiere/plaf/CompiereComboBoxUI.java diff --git a/base/src/org/compiere/plaf/CompiereComboPopup.java b/client/src/org/compiere/plaf/CompiereComboPopup.java similarity index 100% rename from base/src/org/compiere/plaf/CompiereComboPopup.java rename to client/src/org/compiere/plaf/CompiereComboPopup.java diff --git a/base/src/org/compiere/plaf/CompiereLabelUI.java b/client/src/org/compiere/plaf/CompiereLabelUI.java similarity index 100% rename from base/src/org/compiere/plaf/CompiereLabelUI.java rename to client/src/org/compiere/plaf/CompiereLabelUI.java diff --git a/base/src/org/compiere/plaf/CompiereLookAndFeel.java b/client/src/org/compiere/plaf/CompiereLookAndFeel.java similarity index 100% rename from base/src/org/compiere/plaf/CompiereLookAndFeel.java rename to client/src/org/compiere/plaf/CompiereLookAndFeel.java diff --git a/base/src/org/compiere/plaf/CompiereMenuBarUI.java b/client/src/org/compiere/plaf/CompiereMenuBarUI.java similarity index 100% rename from base/src/org/compiere/plaf/CompiereMenuBarUI.java rename to client/src/org/compiere/plaf/CompiereMenuBarUI.java diff --git a/base/src/org/compiere/plaf/CompiereMenuItemUI.java b/client/src/org/compiere/plaf/CompiereMenuItemUI.java similarity index 100% rename from base/src/org/compiere/plaf/CompiereMenuItemUI.java rename to client/src/org/compiere/plaf/CompiereMenuItemUI.java diff --git a/base/src/org/compiere/plaf/CompiereMenuUI.java b/client/src/org/compiere/plaf/CompiereMenuUI.java similarity index 100% rename from base/src/org/compiere/plaf/CompiereMenuUI.java rename to client/src/org/compiere/plaf/CompiereMenuUI.java diff --git a/base/src/org/compiere/plaf/CompierePanelUI.java b/client/src/org/compiere/plaf/CompierePanelUI.java similarity index 100% rename from base/src/org/compiere/plaf/CompierePanelUI.java rename to client/src/org/compiere/plaf/CompierePanelUI.java diff --git a/base/src/org/compiere/plaf/CompiereRadioButtonUI.java b/client/src/org/compiere/plaf/CompiereRadioButtonUI.java similarity index 100% rename from base/src/org/compiere/plaf/CompiereRadioButtonUI.java rename to client/src/org/compiere/plaf/CompiereRadioButtonUI.java diff --git a/base/src/org/compiere/plaf/CompiereRootPaneUI.java b/client/src/org/compiere/plaf/CompiereRootPaneUI.java similarity index 100% rename from base/src/org/compiere/plaf/CompiereRootPaneUI.java rename to client/src/org/compiere/plaf/CompiereRootPaneUI.java diff --git a/base/src/org/compiere/plaf/CompiereScrollPaneUI.java b/client/src/org/compiere/plaf/CompiereScrollPaneUI.java similarity index 100% rename from base/src/org/compiere/plaf/CompiereScrollPaneUI.java rename to client/src/org/compiere/plaf/CompiereScrollPaneUI.java diff --git a/base/src/org/compiere/plaf/CompiereSplitPaneDivider.java b/client/src/org/compiere/plaf/CompiereSplitPaneDivider.java similarity index 100% rename from base/src/org/compiere/plaf/CompiereSplitPaneDivider.java rename to client/src/org/compiere/plaf/CompiereSplitPaneDivider.java diff --git a/base/src/org/compiere/plaf/CompiereSplitPaneUI.java b/client/src/org/compiere/plaf/CompiereSplitPaneUI.java similarity index 100% rename from base/src/org/compiere/plaf/CompiereSplitPaneUI.java rename to client/src/org/compiere/plaf/CompiereSplitPaneUI.java diff --git a/base/src/org/compiere/plaf/CompiereTabbedPaneUI.java b/client/src/org/compiere/plaf/CompiereTabbedPaneUI.java similarity index 100% rename from base/src/org/compiere/plaf/CompiereTabbedPaneUI.java rename to client/src/org/compiere/plaf/CompiereTabbedPaneUI.java diff --git a/base/src/org/compiere/plaf/CompiereTableHeaderUI.java b/client/src/org/compiere/plaf/CompiereTableHeaderUI.java similarity index 100% rename from base/src/org/compiere/plaf/CompiereTableHeaderUI.java rename to client/src/org/compiere/plaf/CompiereTableHeaderUI.java diff --git a/base/src/org/compiere/plaf/CompiereTextAreaUI.java b/client/src/org/compiere/plaf/CompiereTextAreaUI.java similarity index 100% rename from base/src/org/compiere/plaf/CompiereTextAreaUI.java rename to client/src/org/compiere/plaf/CompiereTextAreaUI.java diff --git a/base/src/org/compiere/plaf/CompiereTheme.java b/client/src/org/compiere/plaf/CompiereTheme.java similarity index 100% rename from base/src/org/compiere/plaf/CompiereTheme.java rename to client/src/org/compiere/plaf/CompiereTheme.java diff --git a/base/src/org/compiere/plaf/CompiereThemeBlueMetal.java b/client/src/org/compiere/plaf/CompiereThemeBlueMetal.java similarity index 100% rename from base/src/org/compiere/plaf/CompiereThemeBlueMetal.java rename to client/src/org/compiere/plaf/CompiereThemeBlueMetal.java diff --git a/base/src/org/compiere/plaf/CompiereThemeEditor.java b/client/src/org/compiere/plaf/CompiereThemeEditor.java similarity index 100% rename from base/src/org/compiere/plaf/CompiereThemeEditor.java rename to client/src/org/compiere/plaf/CompiereThemeEditor.java diff --git a/base/src/org/compiere/plaf/CompiereThemeIce.java b/client/src/org/compiere/plaf/CompiereThemeIce.java similarity index 100% rename from base/src/org/compiere/plaf/CompiereThemeIce.java rename to client/src/org/compiere/plaf/CompiereThemeIce.java diff --git a/base/src/org/compiere/plaf/CompiereToggleButtonUI.java b/client/src/org/compiere/plaf/CompiereToggleButtonUI.java similarity index 100% rename from base/src/org/compiere/plaf/CompiereToggleButtonUI.java rename to client/src/org/compiere/plaf/CompiereToggleButtonUI.java diff --git a/base/src/org/compiere/plaf/CompiereToolBarUI.java b/client/src/org/compiere/plaf/CompiereToolBarUI.java similarity index 100% rename from base/src/org/compiere/plaf/CompiereToolBarUI.java rename to client/src/org/compiere/plaf/CompiereToolBarUI.java diff --git a/base/src/org/compiere/plaf/CompiereToolTipUI.java b/client/src/org/compiere/plaf/CompiereToolTipUI.java similarity index 100% rename from base/src/org/compiere/plaf/CompiereToolTipUI.java rename to client/src/org/compiere/plaf/CompiereToolTipUI.java diff --git a/base/src/org/compiere/plaf/CompiereUtils.java b/client/src/org/compiere/plaf/CompiereUtils.java similarity index 100% rename from base/src/org/compiere/plaf/CompiereUtils.java rename to client/src/org/compiere/plaf/CompiereUtils.java diff --git a/base/src/org/compiere/plaf/CompiereViewportUI.java b/client/src/org/compiere/plaf/CompiereViewportUI.java similarity index 100% rename from base/src/org/compiere/plaf/CompiereViewportUI.java rename to client/src/org/compiere/plaf/CompiereViewportUI.java diff --git a/base/src/org/compiere/plaf/ContrastTheme.java b/client/src/org/compiere/plaf/ContrastTheme.java similarity index 100% rename from base/src/org/compiere/plaf/ContrastTheme.java rename to client/src/org/compiere/plaf/ContrastTheme.java diff --git a/base/src/org/compiere/plaf/EmeraldTheme.java b/client/src/org/compiere/plaf/EmeraldTheme.java similarity index 100% rename from base/src/org/compiere/plaf/EmeraldTheme.java rename to client/src/org/compiere/plaf/EmeraldTheme.java diff --git a/base/src/org/compiere/plaf/PlafRes.java b/client/src/org/compiere/plaf/PlafRes.java similarity index 100% rename from base/src/org/compiere/plaf/PlafRes.java rename to client/src/org/compiere/plaf/PlafRes.java diff --git a/base/src/org/compiere/plaf/PlafRes_ar.java b/client/src/org/compiere/plaf/PlafRes_ar.java similarity index 100% rename from base/src/org/compiere/plaf/PlafRes_ar.java rename to client/src/org/compiere/plaf/PlafRes_ar.java diff --git a/base/src/org/compiere/plaf/PlafRes_bg.java b/client/src/org/compiere/plaf/PlafRes_bg.java similarity index 100% rename from base/src/org/compiere/plaf/PlafRes_bg.java rename to client/src/org/compiere/plaf/PlafRes_bg.java diff --git a/base/src/org/compiere/plaf/PlafRes_ca.java b/client/src/org/compiere/plaf/PlafRes_ca.java similarity index 100% rename from base/src/org/compiere/plaf/PlafRes_ca.java rename to client/src/org/compiere/plaf/PlafRes_ca.java diff --git a/base/src/org/compiere/plaf/PlafRes_da.java b/client/src/org/compiere/plaf/PlafRes_da.java similarity index 100% rename from base/src/org/compiere/plaf/PlafRes_da.java rename to client/src/org/compiere/plaf/PlafRes_da.java diff --git a/base/src/org/compiere/plaf/PlafRes_de.java b/client/src/org/compiere/plaf/PlafRes_de.java similarity index 100% rename from base/src/org/compiere/plaf/PlafRes_de.java rename to client/src/org/compiere/plaf/PlafRes_de.java diff --git a/base/src/org/compiere/plaf/PlafRes_el.java b/client/src/org/compiere/plaf/PlafRes_el.java similarity index 100% rename from base/src/org/compiere/plaf/PlafRes_el.java rename to client/src/org/compiere/plaf/PlafRes_el.java diff --git a/base/src/org/compiere/plaf/PlafRes_es.java b/client/src/org/compiere/plaf/PlafRes_es.java similarity index 100% rename from base/src/org/compiere/plaf/PlafRes_es.java rename to client/src/org/compiere/plaf/PlafRes_es.java diff --git a/base/src/org/compiere/plaf/PlafRes_fa.java b/client/src/org/compiere/plaf/PlafRes_fa.java similarity index 100% rename from base/src/org/compiere/plaf/PlafRes_fa.java rename to client/src/org/compiere/plaf/PlafRes_fa.java diff --git a/base/src/org/compiere/plaf/PlafRes_fr.java b/client/src/org/compiere/plaf/PlafRes_fr.java similarity index 100% rename from base/src/org/compiere/plaf/PlafRes_fr.java rename to client/src/org/compiere/plaf/PlafRes_fr.java diff --git a/base/src/org/compiere/plaf/PlafRes_hr.java b/client/src/org/compiere/plaf/PlafRes_hr.java similarity index 100% rename from base/src/org/compiere/plaf/PlafRes_hr.java rename to client/src/org/compiere/plaf/PlafRes_hr.java diff --git a/base/src/org/compiere/plaf/PlafRes_hu.java b/client/src/org/compiere/plaf/PlafRes_hu.java similarity index 100% rename from base/src/org/compiere/plaf/PlafRes_hu.java rename to client/src/org/compiere/plaf/PlafRes_hu.java diff --git a/base/src/org/compiere/plaf/PlafRes_in.java b/client/src/org/compiere/plaf/PlafRes_in.java similarity index 100% rename from base/src/org/compiere/plaf/PlafRes_in.java rename to client/src/org/compiere/plaf/PlafRes_in.java diff --git a/base/src/org/compiere/plaf/PlafRes_it.java b/client/src/org/compiere/plaf/PlafRes_it.java similarity index 100% rename from base/src/org/compiere/plaf/PlafRes_it.java rename to client/src/org/compiere/plaf/PlafRes_it.java diff --git a/base/src/org/compiere/plaf/PlafRes_ja.java b/client/src/org/compiere/plaf/PlafRes_ja.java similarity index 100% rename from base/src/org/compiere/plaf/PlafRes_ja.java rename to client/src/org/compiere/plaf/PlafRes_ja.java diff --git a/base/src/org/compiere/plaf/PlafRes_ms.java b/client/src/org/compiere/plaf/PlafRes_ms.java similarity index 100% rename from base/src/org/compiere/plaf/PlafRes_ms.java rename to client/src/org/compiere/plaf/PlafRes_ms.java diff --git a/base/src/org/compiere/plaf/PlafRes_nl.java b/client/src/org/compiere/plaf/PlafRes_nl.java similarity index 100% rename from base/src/org/compiere/plaf/PlafRes_nl.java rename to client/src/org/compiere/plaf/PlafRes_nl.java diff --git a/base/src/org/compiere/plaf/PlafRes_no.java b/client/src/org/compiere/plaf/PlafRes_no.java similarity index 100% rename from base/src/org/compiere/plaf/PlafRes_no.java rename to client/src/org/compiere/plaf/PlafRes_no.java diff --git a/base/src/org/compiere/plaf/PlafRes_pl.java b/client/src/org/compiere/plaf/PlafRes_pl.java similarity index 100% rename from base/src/org/compiere/plaf/PlafRes_pl.java rename to client/src/org/compiere/plaf/PlafRes_pl.java diff --git a/base/src/org/compiere/plaf/PlafRes_pt.java b/client/src/org/compiere/plaf/PlafRes_pt.java similarity index 100% rename from base/src/org/compiere/plaf/PlafRes_pt.java rename to client/src/org/compiere/plaf/PlafRes_pt.java diff --git a/base/src/org/compiere/plaf/PlafRes_ro.java b/client/src/org/compiere/plaf/PlafRes_ro.java similarity index 100% rename from base/src/org/compiere/plaf/PlafRes_ro.java rename to client/src/org/compiere/plaf/PlafRes_ro.java diff --git a/base/src/org/compiere/plaf/PlafRes_ru.java b/client/src/org/compiere/plaf/PlafRes_ru.java similarity index 100% rename from base/src/org/compiere/plaf/PlafRes_ru.java rename to client/src/org/compiere/plaf/PlafRes_ru.java diff --git a/base/src/org/compiere/plaf/PlafRes_sl.java b/client/src/org/compiere/plaf/PlafRes_sl.java similarity index 100% rename from base/src/org/compiere/plaf/PlafRes_sl.java rename to client/src/org/compiere/plaf/PlafRes_sl.java diff --git a/base/src/org/compiere/plaf/PlafRes_sr.java b/client/src/org/compiere/plaf/PlafRes_sr.java similarity index 100% rename from base/src/org/compiere/plaf/PlafRes_sr.java rename to client/src/org/compiere/plaf/PlafRes_sr.java diff --git a/base/src/org/compiere/plaf/PlafRes_sv.java b/client/src/org/compiere/plaf/PlafRes_sv.java similarity index 100% rename from base/src/org/compiere/plaf/PlafRes_sv.java rename to client/src/org/compiere/plaf/PlafRes_sv.java diff --git a/base/src/org/compiere/plaf/PlafRes_th.java b/client/src/org/compiere/plaf/PlafRes_th.java similarity index 100% rename from base/src/org/compiere/plaf/PlafRes_th.java rename to client/src/org/compiere/plaf/PlafRes_th.java diff --git a/base/src/org/compiere/plaf/PlafRes_vi.java b/client/src/org/compiere/plaf/PlafRes_vi.java similarity index 100% rename from base/src/org/compiere/plaf/PlafRes_vi.java rename to client/src/org/compiere/plaf/PlafRes_vi.java diff --git a/base/src/org/compiere/plaf/PlafRes_zh.java b/client/src/org/compiere/plaf/PlafRes_zh.java similarity index 100% rename from base/src/org/compiere/plaf/PlafRes_zh.java rename to client/src/org/compiere/plaf/PlafRes_zh.java diff --git a/base/src/org/compiere/plaf/PlafRes_zh_CN.java b/client/src/org/compiere/plaf/PlafRes_zh_CN.java similarity index 100% rename from base/src/org/compiere/plaf/PlafRes_zh_CN.java rename to client/src/org/compiere/plaf/PlafRes_zh_CN.java diff --git a/base/src/org/compiere/plaf/RubyTheme.java b/client/src/org/compiere/plaf/RubyTheme.java similarity index 100% rename from base/src/org/compiere/plaf/RubyTheme.java rename to client/src/org/compiere/plaf/RubyTheme.java diff --git a/base/src/org/compiere/plaf/icons/CL16.gif b/client/src/org/compiere/plaf/icons/CL16.gif similarity index 100% rename from base/src/org/compiere/plaf/icons/CL16.gif rename to client/src/org/compiere/plaf/icons/CL16.gif diff --git a/base/src/org/compiere/plaf/icons/CL32.gif b/client/src/org/compiere/plaf/icons/CL32.gif similarity index 100% rename from base/src/org/compiere/plaf/icons/CL32.gif rename to client/src/org/compiere/plaf/icons/CL32.gif diff --git a/base/src/org/compiere/plaf/icons/Cancel24.gif b/client/src/org/compiere/plaf/icons/Cancel24.gif similarity index 100% rename from base/src/org/compiere/plaf/icons/Cancel24.gif rename to client/src/org/compiere/plaf/icons/Cancel24.gif diff --git a/base/src/org/compiere/plaf/icons/Error.gif b/client/src/org/compiere/plaf/icons/Error.gif similarity index 100% rename from base/src/org/compiere/plaf/icons/Error.gif rename to client/src/org/compiere/plaf/icons/Error.gif diff --git a/base/src/org/compiere/plaf/icons/Inform.gif b/client/src/org/compiere/plaf/icons/Inform.gif similarity index 100% rename from base/src/org/compiere/plaf/icons/Inform.gif rename to client/src/org/compiere/plaf/icons/Inform.gif diff --git a/base/src/org/compiere/plaf/icons/Ok24.gif b/client/src/org/compiere/plaf/icons/Ok24.gif similarity index 100% rename from base/src/org/compiere/plaf/icons/Ok24.gif rename to client/src/org/compiere/plaf/icons/Ok24.gif diff --git a/base/src/org/compiere/plaf/icons/Question.gif b/client/src/org/compiere/plaf/icons/Question.gif similarity index 100% rename from base/src/org/compiere/plaf/icons/Question.gif rename to client/src/org/compiere/plaf/icons/Question.gif diff --git a/base/src/org/compiere/plaf/icons/Warn.gif b/client/src/org/compiere/plaf/icons/Warn.gif similarity index 100% rename from base/src/org/compiere/plaf/icons/Warn.gif rename to client/src/org/compiere/plaf/icons/Warn.gif diff --git a/base/src/org/compiere/plaf/package.html b/client/src/org/compiere/plaf/package.html similarity index 100% rename from base/src/org/compiere/plaf/package.html rename to client/src/org/compiere/plaf/package.html diff --git a/base/src/org/compiere/plaf/sounds/FrameClose.wav b/client/src/org/compiere/plaf/sounds/FrameClose.wav similarity index 100% rename from base/src/org/compiere/plaf/sounds/FrameClose.wav rename to client/src/org/compiere/plaf/sounds/FrameClose.wav diff --git a/base/src/org/compiere/plaf/sounds/FrameMaximize.wav b/client/src/org/compiere/plaf/sounds/FrameMaximize.wav similarity index 100% rename from base/src/org/compiere/plaf/sounds/FrameMaximize.wav rename to client/src/org/compiere/plaf/sounds/FrameMaximize.wav diff --git a/base/src/org/compiere/plaf/sounds/FrameMinimize.wav b/client/src/org/compiere/plaf/sounds/FrameMinimize.wav similarity index 100% rename from base/src/org/compiere/plaf/sounds/FrameMinimize.wav rename to client/src/org/compiere/plaf/sounds/FrameMinimize.wav diff --git a/base/src/org/compiere/plaf/sounds/FrameRestoreDown.wav b/client/src/org/compiere/plaf/sounds/FrameRestoreDown.wav similarity index 100% rename from base/src/org/compiere/plaf/sounds/FrameRestoreDown.wav rename to client/src/org/compiere/plaf/sounds/FrameRestoreDown.wav diff --git a/base/src/org/compiere/plaf/sounds/FrameRestoreUp.wav b/client/src/org/compiere/plaf/sounds/FrameRestoreUp.wav similarity index 100% rename from base/src/org/compiere/plaf/sounds/FrameRestoreUp.wav rename to client/src/org/compiere/plaf/sounds/FrameRestoreUp.wav diff --git a/base/src/org/compiere/plaf/sounds/MenuItemCommand.wav b/client/src/org/compiere/plaf/sounds/MenuItemCommand.wav similarity index 100% rename from base/src/org/compiere/plaf/sounds/MenuItemCommand.wav rename to client/src/org/compiere/plaf/sounds/MenuItemCommand.wav diff --git a/base/src/org/compiere/plaf/sounds/OptionPaneError.wav b/client/src/org/compiere/plaf/sounds/OptionPaneError.wav similarity index 100% rename from base/src/org/compiere/plaf/sounds/OptionPaneError.wav rename to client/src/org/compiere/plaf/sounds/OptionPaneError.wav diff --git a/base/src/org/compiere/plaf/sounds/OptionPaneInformation.wav b/client/src/org/compiere/plaf/sounds/OptionPaneInformation.wav similarity index 100% rename from base/src/org/compiere/plaf/sounds/OptionPaneInformation.wav rename to client/src/org/compiere/plaf/sounds/OptionPaneInformation.wav diff --git a/base/src/org/compiere/plaf/sounds/OptionPaneQuestion.wav b/client/src/org/compiere/plaf/sounds/OptionPaneQuestion.wav similarity index 100% rename from base/src/org/compiere/plaf/sounds/OptionPaneQuestion.wav rename to client/src/org/compiere/plaf/sounds/OptionPaneQuestion.wav diff --git a/base/src/org/compiere/plaf/sounds/OptionPaneWarning.wav b/client/src/org/compiere/plaf/sounds/OptionPaneWarning.wav similarity index 100% rename from base/src/org/compiere/plaf/sounds/OptionPaneWarning.wav rename to client/src/org/compiere/plaf/sounds/OptionPaneWarning.wav diff --git a/base/src/org/compiere/plaf/sounds/PopupMenuPopup.wav b/client/src/org/compiere/plaf/sounds/PopupMenuPopup.wav similarity index 100% rename from base/src/org/compiere/plaf/sounds/PopupMenuPopup.wav rename to client/src/org/compiere/plaf/sounds/PopupMenuPopup.wav diff --git a/base/src/org/compiere/plaf/vincent.jpg b/client/src/org/compiere/plaf/vincent.jpg similarity index 100% rename from base/src/org/compiere/plaf/vincent.jpg rename to client/src/org/compiere/plaf/vincent.jpg diff --git a/client/src/org/compiere/pos/POSKeyboard.java b/client/src/org/compiere/pos/POSKeyboard.java index 612bb330ec..fba70ece31 100644 --- a/client/src/org/compiere/pos/POSKeyboard.java +++ b/client/src/org/compiere/pos/POSKeyboard.java @@ -79,7 +79,7 @@ public class POSKeyboard extends CDialog implements ActionListener, PosKeyListen } public POSKeyboard(PosBasePanel posPanel, int keyLayoutId) { - super(Env.getFrame(posPanel), true); + super(AEnv.getFrame(posPanel), true); keylayout = MPOSKeyLayout.get(posPanel.getCtx(), keyLayoutId); init( keyLayoutId ); } diff --git a/client/src/org/compiere/pos/PosApplication.java b/client/src/org/compiere/pos/PosApplication.java index 3b147f249e..f765d6e80d 100644 --- a/client/src/org/compiere/pos/PosApplication.java +++ b/client/src/org/compiere/pos/PosApplication.java @@ -64,7 +64,7 @@ public class PosApplication { System.exit(1); MSession.get (Env.getCtx(), true); // Start Session - int m_WindowNo = Env.createWindowNo(frame); + int m_WindowNo = AEnv.createWindowNo(frame); // Default Image frame.setIconImage(Adempiere.getImage16()); diff --git a/client/src/org/compiere/pos/PosLogin.java b/client/src/org/compiere/pos/PosLogin.java index 15a657b0c7..bff6adecb5 100644 --- a/client/src/org/compiere/pos/PosLogin.java +++ b/client/src/org/compiere/pos/PosLogin.java @@ -8,6 +8,7 @@ import javax.swing.KeyStroke; import net.miginfocom.swing.MigLayout; +import org.compiere.apps.AEnv; import org.compiere.apps.AppsAction; import org.compiere.model.MUser; import org.compiere.swing.CButton; @@ -34,7 +35,7 @@ public class PosLogin extends CDialog implements ActionListener { */ public PosLogin (PosBasePanel posPanel) { - super (Env.getFrame(posPanel),Msg.translate(posPanel.getCtx(), "Login"), true); + super (AEnv.getFrame(posPanel),Msg.translate(posPanel.getCtx(), "Login"), true); init(); this.posPanel = posPanel; } diff --git a/client/src/org/compiere/pos/PosPayment.java b/client/src/org/compiere/pos/PosPayment.java index f6a43b2c88..01ab9d303c 100644 --- a/client/src/org/compiere/pos/PosPayment.java +++ b/client/src/org/compiere/pos/PosPayment.java @@ -43,6 +43,7 @@ import net.miginfocom.swing.MigLayout; import org.adempiere.plaf.AdempierePLAF; import org.compiere.apps.ADialog; +import org.compiere.apps.AEnv; import org.compiere.apps.AppsAction; import org.compiere.model.MCurrency; import org.compiere.model.MLookup; @@ -193,7 +194,7 @@ public class PosPayment extends CDialog implements PosKeyListener, VetoableChang private CButton f_bCancel; public PosPayment(PosBasePanel posPanel) { - super(Env.getFrame(posPanel),true); + super(AEnv.getFrame(posPanel),true); p_posPanel = posPanel; p_pos = posPanel.p_pos; p_ctx = p_pos.getCtx(); diff --git a/client/src/org/compiere/pos/PosQuery.java b/client/src/org/compiere/pos/PosQuery.java index e3e4e1204a..14150d83a1 100644 --- a/client/src/org/compiere/pos/PosQuery.java +++ b/client/src/org/compiere/pos/PosQuery.java @@ -25,6 +25,7 @@ import javax.swing.KeyStroke; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; +import org.compiere.apps.AEnv; import org.compiere.apps.AppsAction; import org.compiere.apps.ConfirmPanel; import org.compiere.minigrid.MiniTable; @@ -80,7 +81,7 @@ public abstract class PosQuery extends CDialog implements MouseListener, ListSel */ public PosQuery (PosBasePanel posPanel) { - super(Env.getFrame(posPanel), true); + super(AEnv.getFrame(posPanel), true); p_posPanel = posPanel; p_pos = posPanel.p_pos; p_ctx = p_pos.getCtx(); diff --git a/client/src/org/compiere/pos/SubOrder.java b/client/src/org/compiere/pos/SubOrder.java index 9378c0e516..4e1c912638 100644 --- a/client/src/org/compiere/pos/SubOrder.java +++ b/client/src/org/compiere/pos/SubOrder.java @@ -39,6 +39,7 @@ import net.miginfocom.swing.MigLayout; import org.adempiere.plaf.AdempierePLAF; import org.compiere.apps.ADialog; +import org.compiere.apps.AEnv; import org.compiere.grid.ed.VNumber; import org.compiere.model.MBPartner; import org.compiere.model.MBPartnerInfo; @@ -608,7 +609,7 @@ public class SubOrder extends PosSubPanel PrintLabel.printLabelTicket(order.getC_Order_ID(), p_pos.getAD_PrintLabel_ID()); */ //print standard document - ReportCtl.startDocumentPrint(ReportEngine.ORDER, order.getC_Order_ID(), null, Env.getWindowNo(this), true); + ReportCtl.startDocumentPrint(ReportEngine.ORDER, order.getC_Order_ID(), null, AEnv.getWindowNo(this), true); } catch (Exception e) diff --git a/client/src/org/compiere/print/AReport.java b/client/src/org/compiere/print/AReport.java index f5215d64b9..e74de89c5b 100644 --- a/client/src/org/compiere/print/AReport.java +++ b/client/src/org/compiere/print/AReport.java @@ -28,6 +28,7 @@ import javax.swing.JComponent; import javax.swing.JPopupMenu; import org.compiere.apps.ADialog; +import org.compiere.apps.ClientProcessCtrl; import org.compiere.apps.ProcessCtl; import org.compiere.model.MQuery; import org.compiere.model.MRole; @@ -230,7 +231,7 @@ public class AReport implements ActionListener ProcessInfo pi = new ProcessInfo ("", pf.getJasperProcess_ID(), pf.getAD_Table_ID(), Record_ID); // Execute Process - ProcessCtl worker = ProcessCtl.process(parent, WindowNo, pi, null); + ProcessCtl worker = ClientProcessCtrl.process(parent, WindowNo, pi, null); } else { diff --git a/base/src/org/compiere/print/CPrinter.java b/client/src/org/compiere/print/CPrinter.java similarity index 61% rename from base/src/org/compiere/print/CPrinter.java rename to client/src/org/compiere/print/CPrinter.java index 2a86c411bd..527634d799 100644 --- a/base/src/org/compiere/print/CPrinter.java +++ b/client/src/org/compiere/print/CPrinter.java @@ -41,7 +41,9 @@ public class CPrinter extends CComboBox implements ActionListener */ private static final long serialVersionUID = -6366208617152587573L; - + /** Available Printer Services */ + private static PrintService[] s_services = PrintUtil.getAllPrintServices(); + /** * Get Print (Services) Names * @return Printer Name array @@ -49,7 +51,7 @@ public class CPrinter extends CComboBox implements ActionListener public static String[] getPrinterNames() { // Refresh print services every time the combobox is constructed - s_services = PrintServiceLookup.lookupPrintServices(null,null); + s_services = PrintUtil.getAllPrintServices(); String[] retValue = new String[s_services.length]; for (int i = 0; i < s_services.length; i++) @@ -57,80 +59,7 @@ public class CPrinter extends CComboBox implements ActionListener return retValue; } // getPrintServiceNames - - /** - * Return default PrinterJob - * @return PrinterJob - */ - public static PrinterJob getPrinterJob() - { - return getPrinterJob(Ini.getProperty(Ini.P_PRINTER)); - } // getPrinterJob - - /** - * Return PrinterJob with selected printer name. - * @param printerName if null, get default printer (Ini) - * @return PrinterJob - */ - public static PrinterJob getPrinterJob (String printerName) - { - PrinterJob pj = null; - PrintService ps = null; - try - { - pj = PrinterJob.getPrinterJob(); - - // find printer service - if (printerName == null || printerName.length() == 0) - printerName = Ini.getProperty(Ini.P_PRINTER); - if (printerName != null && printerName.length() != 0) - { - // System.out.println("CPrinter.getPrinterJob - searching " + printerName); - for (int i = 0; i < s_services.length; i++) - { - String serviceName = s_services[i].getName(); - if (printerName.equals(serviceName)) - { - ps = s_services[i]; - // System.out.println("CPrinter.getPrinterJob - found " + printerName); - break; - } - // System.out.println("CPrinter.getPrinterJob - not: " + serviceName); - } - } // find printer service - - try - { - if (ps != null) - pj.setPrintService(ps); - } - catch (Exception e) - { - log.warning("Could not set Print Service: " + e.toString()); - } - // - PrintService psUsed = pj.getPrintService(); - if (psUsed == null) - log.warning("Print Service not Found"); - else - { - String serviceName = psUsed.getName(); - if (printerName != null && !printerName.equals(serviceName)) - log.warning("Not found: " + printerName + " - Used: " + serviceName); - } - } - catch (Exception e) - { - log.warning("Could not create for " + printerName + ": " + e.toString()); - } - return pj; - } // getPrinterJob - - - /** Available Printer Services */ -// private static PrintService[] s_services = PrinterJob.lookupPrintServices(); - private static PrintService[] s_services = PrintServiceLookup.lookupPrintServices(null,null); - + /** Logger */ private static CLogger log = CLogger.getCLogger (CPrinter.class); diff --git a/client/src/org/compiere/print/SwingViewerProvider.java b/client/src/org/compiere/print/SwingViewerProvider.java index 7c4cbaefc9..aaab4c0de0 100644 --- a/client/src/org/compiere/print/SwingViewerProvider.java +++ b/client/src/org/compiere/print/SwingViewerProvider.java @@ -18,8 +18,8 @@ package org.compiere.print; import javax.swing.JFrame; +import org.compiere.apps.AEnv; import org.compiere.apps.AMenu; -import org.compiere.util.Env; /** * @@ -30,7 +30,7 @@ public class SwingViewerProvider implements ReportViewerProvider { public void openViewer(ReportEngine re) { Viewer viewer = new Viewer(re); - JFrame top = Env.getWindow(0); + JFrame top = AEnv.getWindow(0); if (top instanceof AMenu) ((AMenu)top).getWindowManager().add(viewer); } diff --git a/base/src/org/compiere/print/View.java b/client/src/org/compiere/print/View.java similarity index 100% rename from base/src/org/compiere/print/View.java rename to client/src/org/compiere/print/View.java diff --git a/client/src/org/compiere/print/Viewer.java b/client/src/org/compiere/print/Viewer.java index ec4d58fb7a..3c5fc618f9 100644 --- a/client/src/org/compiere/print/Viewer.java +++ b/client/src/org/compiere/print/Viewer.java @@ -124,7 +124,7 @@ import org.compiere.util.ValueNamePair; * */ public class Viewer extends CFrame - implements ActionListener, ChangeListener, WindowStateListener + implements ActionListener, ChangeListener, WindowStateListener, IReportEngineEventListener { /** * @@ -150,7 +150,7 @@ public class Viewer extends CFrame { super(gc); log.info(""); - m_WindowNo = Env.createWindowNo(this); + m_WindowNo = AEnv.createWindowNo(this); m_reportEngine = re; m_AD_Table_ID = re.getPrintFormat().getAD_Table_ID(); if (!MRole.getDefault().isCanReport(m_AD_Table_ID)) @@ -161,7 +161,8 @@ public class Viewer extends CFrame m_isCanExport = MRole.getDefault().isCanExport(m_AD_Table_ID); try { - m_viewPanel = re.getView(); + m_viewPanel = new View(re.getLayout()); + re.addEventListener(this); m_ctx = m_reportEngine.getCtx(); jbInit(); dynInit(); @@ -591,7 +592,7 @@ public class Viewer extends CFrame AEnv.addMenuItem("Preference", null, null, mTools, this); // Window - AMenu aMenu = (AMenu)Env.getWindow(0); + AMenu aMenu = (AMenu)AEnv.getWindow(0); JMenu mWindow = new WindowMenu(aMenu.getWindowManager(), this); menuBar.add(mWindow); @@ -1332,5 +1333,23 @@ public class Viewer extends CFrame new Viewer(re); } // main + @Override + public void onPrintFormatChanged(ReportEngineEvent event) { + if (m_viewPanel != null) + m_viewPanel.revalidate(); + } + + @Override + public void onQueryChanged(ReportEngineEvent event) { + if (m_viewPanel != null) + m_viewPanel.revalidate(); + } + + @Override + public void onPageSetupChanged(ReportEngineEvent event) { + if (m_viewPanel != null) + m_viewPanel.revalidate(); + } + } // Viewer diff --git a/base/src/org/compiere/report/core/ResultTable.java b/client/src/org/compiere/report/core/ResultTable.java similarity index 100% rename from base/src/org/compiere/report/core/ResultTable.java rename to client/src/org/compiere/report/core/ResultTable.java diff --git a/base/src/org/compiere/report/core/ResultTableCellEditor.java b/client/src/org/compiere/report/core/ResultTableCellEditor.java similarity index 100% rename from base/src/org/compiere/report/core/ResultTableCellEditor.java rename to client/src/org/compiere/report/core/ResultTableCellEditor.java diff --git a/base/src/org/compiere/report/core/ResultTableCellRenderer.java b/client/src/org/compiere/report/core/ResultTableCellRenderer.java similarity index 100% rename from base/src/org/compiere/report/core/ResultTableCellRenderer.java rename to client/src/org/compiere/report/core/ResultTableCellRenderer.java diff --git a/base/src/org/compiere/swing/CButton.java b/client/src/org/compiere/swing/CButton.java similarity index 100% rename from base/src/org/compiere/swing/CButton.java rename to client/src/org/compiere/swing/CButton.java diff --git a/base/src/org/compiere/swing/CCheckBox.java b/client/src/org/compiere/swing/CCheckBox.java similarity index 100% rename from base/src/org/compiere/swing/CCheckBox.java rename to client/src/org/compiere/swing/CCheckBox.java diff --git a/base/src/org/compiere/swing/CCheckBoxMenuItem.java b/client/src/org/compiere/swing/CCheckBoxMenuItem.java similarity index 100% rename from base/src/org/compiere/swing/CCheckBoxMenuItem.java rename to client/src/org/compiere/swing/CCheckBoxMenuItem.java diff --git a/base/src/org/compiere/swing/CColumnControlButton.java b/client/src/org/compiere/swing/CColumnControlButton.java similarity index 100% rename from base/src/org/compiere/swing/CColumnControlButton.java rename to client/src/org/compiere/swing/CColumnControlButton.java diff --git a/base/src/org/compiere/swing/CComboBox.java b/client/src/org/compiere/swing/CComboBox.java similarity index 100% rename from base/src/org/compiere/swing/CComboBox.java rename to client/src/org/compiere/swing/CComboBox.java diff --git a/base/src/org/compiere/swing/CDialog.java b/client/src/org/compiere/swing/CDialog.java similarity index 100% rename from base/src/org/compiere/swing/CDialog.java rename to client/src/org/compiere/swing/CDialog.java diff --git a/base/src/org/compiere/swing/CEditor.java b/client/src/org/compiere/swing/CEditor.java similarity index 100% rename from base/src/org/compiere/swing/CEditor.java rename to client/src/org/compiere/swing/CEditor.java diff --git a/base/src/org/compiere/swing/CField.java b/client/src/org/compiere/swing/CField.java similarity index 100% rename from base/src/org/compiere/swing/CField.java rename to client/src/org/compiere/swing/CField.java diff --git a/base/src/org/compiere/swing/CFieldEditor.java b/client/src/org/compiere/swing/CFieldEditor.java similarity index 100% rename from base/src/org/compiere/swing/CFieldEditor.java rename to client/src/org/compiere/swing/CFieldEditor.java diff --git a/base/src/org/compiere/swing/CFieldPopup.java b/client/src/org/compiere/swing/CFieldPopup.java similarity index 100% rename from base/src/org/compiere/swing/CFieldPopup.java rename to client/src/org/compiere/swing/CFieldPopup.java diff --git a/base/src/org/compiere/swing/CFrame.java b/client/src/org/compiere/swing/CFrame.java similarity index 100% rename from base/src/org/compiere/swing/CFrame.java rename to client/src/org/compiere/swing/CFrame.java diff --git a/base/src/org/compiere/swing/CLabel.java b/client/src/org/compiere/swing/CLabel.java similarity index 100% rename from base/src/org/compiere/swing/CLabel.java rename to client/src/org/compiere/swing/CLabel.java diff --git a/base/src/org/compiere/swing/CMenuItem.java b/client/src/org/compiere/swing/CMenuItem.java similarity index 100% rename from base/src/org/compiere/swing/CMenuItem.java rename to client/src/org/compiere/swing/CMenuItem.java diff --git a/base/src/org/compiere/swing/CPanel.java b/client/src/org/compiere/swing/CPanel.java similarity index 100% rename from base/src/org/compiere/swing/CPanel.java rename to client/src/org/compiere/swing/CPanel.java diff --git a/base/src/org/compiere/swing/CPassword.java b/client/src/org/compiere/swing/CPassword.java similarity index 100% rename from base/src/org/compiere/swing/CPassword.java rename to client/src/org/compiere/swing/CPassword.java diff --git a/base/src/org/compiere/swing/CScrollPane.java b/client/src/org/compiere/swing/CScrollPane.java similarity index 100% rename from base/src/org/compiere/swing/CScrollPane.java rename to client/src/org/compiere/swing/CScrollPane.java diff --git a/base/src/org/compiere/swing/CTabbedPane.java b/client/src/org/compiere/swing/CTabbedPane.java similarity index 100% rename from base/src/org/compiere/swing/CTabbedPane.java rename to client/src/org/compiere/swing/CTabbedPane.java diff --git a/base/src/org/compiere/swing/CTable.java b/client/src/org/compiere/swing/CTable.java similarity index 100% rename from base/src/org/compiere/swing/CTable.java rename to client/src/org/compiere/swing/CTable.java diff --git a/base/src/org/compiere/swing/CTextArea.java b/client/src/org/compiere/swing/CTextArea.java similarity index 100% rename from base/src/org/compiere/swing/CTextArea.java rename to client/src/org/compiere/swing/CTextArea.java diff --git a/base/src/org/compiere/swing/CTextField.java b/client/src/org/compiere/swing/CTextField.java similarity index 100% rename from base/src/org/compiere/swing/CTextField.java rename to client/src/org/compiere/swing/CTextField.java diff --git a/base/src/org/compiere/swing/CTextPane.java b/client/src/org/compiere/swing/CTextPane.java similarity index 100% rename from base/src/org/compiere/swing/CTextPane.java rename to client/src/org/compiere/swing/CTextPane.java diff --git a/base/src/org/compiere/swing/CToggleButton.java b/client/src/org/compiere/swing/CToggleButton.java similarity index 100% rename from base/src/org/compiere/swing/CToggleButton.java rename to client/src/org/compiere/swing/CToggleButton.java diff --git a/base/src/org/compiere/swing/CollapsiblePanel.java b/client/src/org/compiere/swing/CollapsiblePanel.java similarity index 100% rename from base/src/org/compiere/swing/CollapsiblePanel.java rename to client/src/org/compiere/swing/CollapsiblePanel.java diff --git a/base/src/org/compiere/swing/ColorBlind.java b/client/src/org/compiere/swing/ColorBlind.java similarity index 100% rename from base/src/org/compiere/swing/ColorBlind.java rename to client/src/org/compiere/swing/ColorBlind.java diff --git a/base/src/org/compiere/swing/ColorEditor.java b/client/src/org/compiere/swing/ColorEditor.java similarity index 100% rename from base/src/org/compiere/swing/ColorEditor.java rename to client/src/org/compiere/swing/ColorEditor.java diff --git a/base/src/org/compiere/swing/ExtendedTheme.java b/client/src/org/compiere/swing/ExtendedTheme.java similarity index 100% rename from base/src/org/compiere/swing/ExtendedTheme.java rename to client/src/org/compiere/swing/ExtendedTheme.java diff --git a/base/src/org/compiere/swing/FontChooser.java b/client/src/org/compiere/swing/FontChooser.java similarity index 100% rename from base/src/org/compiere/swing/FontChooser.java rename to client/src/org/compiere/swing/FontChooser.java diff --git a/base/src/org/compiere/swing/ShadowBorder.java b/client/src/org/compiere/swing/ShadowBorder.java similarity index 100% rename from base/src/org/compiere/swing/ShadowBorder.java rename to client/src/org/compiere/swing/ShadowBorder.java diff --git a/base/src/org/compiere/swing/StackedBox.java b/client/src/org/compiere/swing/StackedBox.java similarity index 100% rename from base/src/org/compiere/swing/StackedBox.java rename to client/src/org/compiere/swing/StackedBox.java diff --git a/base/src/org/compiere/swing/TableCellNone.java b/client/src/org/compiere/swing/TableCellNone.java similarity index 100% rename from base/src/org/compiere/swing/TableCellNone.java rename to client/src/org/compiere/swing/TableCellNone.java diff --git a/base/src/org/compiere/swing/ThemeUtils.java b/client/src/org/compiere/swing/ThemeUtils.java similarity index 100% rename from base/src/org/compiere/swing/ThemeUtils.java rename to client/src/org/compiere/swing/ThemeUtils.java diff --git a/base/src/org/compiere/swing/package.html b/client/src/org/compiere/swing/package.html similarity index 100% rename from base/src/org/compiere/swing/package.html rename to client/src/org/compiere/swing/package.html diff --git a/base/src/org/compiere/util/IniDialog.java b/client/src/org/compiere/util/IniDialog.java similarity index 100% rename from base/src/org/compiere/util/IniDialog.java rename to client/src/org/compiere/util/IniDialog.java diff --git a/base/src/org/compiere/util/MiniBrowser.java b/client/src/org/compiere/util/MiniBrowser.java similarity index 100% rename from base/src/org/compiere/util/MiniBrowser.java rename to client/src/org/compiere/util/MiniBrowser.java diff --git a/client/src/org/eevolution/form/VInOutInvoiceGen.java b/client/src/org/eevolution/form/VInOutInvoiceGen.java index 04a744485d..d07c7f0666 100755 --- a/client/src/org/eevolution/form/VInOutInvoiceGen.java +++ b/client/src/org/eevolution/form/VInOutInvoiceGen.java @@ -40,6 +40,7 @@ import javax.swing.event.TableModelListener; import org.adempiere.plaf.AdempierePLAF; import org.compiere.apps.ADialog; import org.compiere.apps.ADialogDialog; +import org.compiere.apps.AEnv; import org.compiere.apps.ConfirmPanel; import org.compiere.apps.ProcessCtl; import org.compiere.apps.StatusBar; @@ -615,7 +616,7 @@ public class VInOutInvoiceGen extends CPanel } // Execute Process - ProcessCtl worker = new ProcessCtl(this, Env.getWindowNo(this), pi, trx); + ProcessCtl worker = new ProcessCtl(this, AEnv.getWindowNo(this), pi, trx); worker.start(); // complete tasks in unlockUI / generateShipments_complete // } // generateShipments @@ -665,7 +666,7 @@ public class VInOutInvoiceGen extends CPanel for (int i = 0; i < ids.length; i++) { int M_InOut_ID = ids[i]; - ReportCtl.startDocumentPrint(ReportEngine.SHIPMENT, M_InOut_ID, this, Env.getWindowNo(this), true); + ReportCtl.startDocumentPrint(ReportEngine.SHIPMENT, M_InOut_ID, this, AEnv.getWindowNo(this), true); } ADialogDialog d = new ADialogDialog (m_frame, Env.getHeader(Env.getCtx(), m_WindowNo), @@ -781,7 +782,7 @@ public class VInOutInvoiceGen extends CPanel } // Execute Process - ProcessCtl worker = new ProcessCtl(this, Env.getWindowNo(this), pi, trx); + ProcessCtl worker = new ProcessCtl(this, AEnv.getWindowNo(this), pi, trx); worker.start(); // complete tasks in unlockUI / generateInvoice_complete } // generateInvoices @@ -829,7 +830,7 @@ public class VInOutInvoiceGen extends CPanel for (int i = 0; i < ids.length; i++) { int C_Invoice_ID = ids[i]; - ReportCtl.startDocumentPrint(ReportEngine.INVOICE, C_Invoice_ID, this, Env.getWindowNo(this), true); + ReportCtl.startDocumentPrint(ReportEngine.INVOICE, C_Invoice_ID, this, AEnv.getWindowNo(this), true); } ADialogDialog d = new ADialogDialog (m_frame, Env.getHeader(Env.getCtx(), m_WindowNo), @@ -894,5 +895,4 @@ public class VInOutInvoiceGen extends CPanel public void executeASync (ProcessInfo pi) { } // executeASync - } // VInOutGen diff --git a/base/swing.properties b/client/swing.properties similarity index 100% rename from base/swing.properties rename to client/swing.properties diff --git a/extend/build.xml b/extend/build.xml index dc250aa56a..531d9081a0 100644 --- a/extend/build.xml +++ b/extend/build.xml @@ -95,7 +95,7 @@ - + diff --git a/extend/src/test/functional/MColorTest.java b/extend/src/test/functional/MColorTest.java index 05fe7fd8bf..20767e1982 100644 --- a/extend/src/test/functional/MColorTest.java +++ b/extend/src/test/functional/MColorTest.java @@ -14,7 +14,6 @@ package test.functional; import org.compiere.model.MColor; -import org.compiere.plaf.CompiereColor; import org.compiere.util.Env; import test.AdempiereTestCase; @@ -34,8 +33,7 @@ public class MColorTest extends AdempiereTestCase public void testQuery() throws Exception { MColor clr = new MColor(getCtx(),1,getTrxName()); //red1 put in dummy record that has COLORTYPE = 'R' for and ADImageID = 101 - CompiereColor url = clr.getAdempiereColor(); - assertTrue("Color must be right", url.toString().length()>0); + assertTrue("Color must be right", clr.getAD_Image_ID() > 0); } diff --git a/install/Adempiere/RUN_setup.sh b/install/Adempiere/RUN_setup.sh index 22feeab34b..d21afd87ef 100644 --- a/install/Adempiere/RUN_setup.sh +++ b/install/Adempiere/RUN_setup.sh @@ -33,7 +33,7 @@ find . -name '*.sh' -exec chmod a+x '{}' \; # cd utils #. ./RUN_SignDatabaseBuild.sh -. ./RUN_UnixEnv.sh +. utils/RUN_UnixEnv.sh echo . echo For problems, check log file in base directory diff --git a/install/Adempiere/RUN_silentsetup.sh b/install/Adempiere/RUN_silentsetup.sh index 7997a52ccd..f4fe2bd39c 100644 --- a/install/Adempiere/RUN_silentsetup.sh +++ b/install/Adempiere/RUN_silentsetup.sh @@ -35,7 +35,7 @@ find . -name '*.sh' -exec chmod a+x '{}' \; cd utils . ./RUN_SignDatabaseBuild.sh -. ./RUN_UnixEnv.sh +. utils/RUN_UnixEnv.sh echo . echo For problems, check log file in base directory diff --git a/install/build.xml b/install/build.xml index f8187a9afa..ac3bce1a17 100644 --- a/install/build.xml +++ b/install/build.xml @@ -209,7 +209,7 @@ - + diff --git a/install/src/org/compiere/install/KeyStoreMgt.java b/install/src/org/compiere/install/KeyStoreMgt.java index ed1bf6f129..b7c2511235 100644 --- a/install/src/org/compiere/install/KeyStoreMgt.java +++ b/install/src/org/compiere/install/KeyStoreMgt.java @@ -453,13 +453,14 @@ public class KeyStoreMgt list.toArray(args); // System.out.println(" args #" + args.length); //vpj-cd add support java 6 - try - { - KeyTool.main(args); - } - catch (Exception e) - { - } + try + { + KeyTool.main(args); + } + catch (Exception e) + { + e.printStackTrace(); + } } // ketyool /** diff --git a/pipo/.classpath b/pipo/.classpath new file mode 100644 index 0000000000..ad32c83a78 --- /dev/null +++ b/pipo/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/pipo/.project b/pipo/.project new file mode 100644 index 0000000000..3c9fc47d88 --- /dev/null +++ b/pipo/.project @@ -0,0 +1,28 @@ + + + pipo + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/pipo/.settings/org.eclipse.jdt.core.prefs b/pipo/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..ceb61221f1 --- /dev/null +++ b/pipo/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Fri Mar 12 08:48:46 CET 2010 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/pipo/.settings/org.eclipse.pde.core.prefs b/pipo/.settings/org.eclipse.pde.core.prefs new file mode 100644 index 0000000000..173c0ad34c --- /dev/null +++ b/pipo/.settings/org.eclipse.pde.core.prefs @@ -0,0 +1,4 @@ +#Fri Mar 12 15:16:08 CET 2010 +eclipse.preferences.version=1 +pluginProject.extensions=true +resolve.requirebundle=false diff --git a/pipo/META-INF/MANIFEST.MF b/pipo/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..c182e44326 --- /dev/null +++ b/pipo/META-INF/MANIFEST.MF @@ -0,0 +1,12 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: PiPo +Bundle-SymbolicName: org.adempiere.pipo;singleton:=true +Bundle-Version: 1.0.0.qualifier +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Import-Package: org.osgi.framework +Export-Package: org.adempiere.pipo.srv, + org.adempiere.pipo2, + org.adempiere.pipo2.exception +Require-Bundle: org.adempiere.base;bundle-version="1.0.0", + org.adempiere.tools;bundle-version="1.0.0" diff --git a/pipo/build.properties b/pipo/build.properties new file mode 100644 index 0000000000..e9863e281e --- /dev/null +++ b/pipo/build.properties @@ -0,0 +1,5 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + plugin.xml diff --git a/pipo/build.xml b/pipo/build.xml new file mode 100644 index 0000000000..89c37495c1 --- /dev/null +++ b/pipo/build.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pipo/plugin.xml b/pipo/plugin.xml new file mode 100644 index 0000000000..f3d7a1ee49 --- /dev/null +++ b/pipo/plugin.xml @@ -0,0 +1,12 @@ + + + + + + + + + + diff --git a/pipo/schema/org.adempiere.pipo.Handlers.exsd b/pipo/schema/org.adempiere.pipo.Handlers.exsd new file mode 100644 index 0000000000..08af55b1a2 --- /dev/null +++ b/pipo/schema/org.adempiere.pipo.Handlers.exsd @@ -0,0 +1,109 @@ + + + + + + + + + [Enter description of this extension point.] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + element name like AD_Message, AD_Table, Code_Snippet, etc + + + + + + + + + + + + + + + + + + + + + + [Enter the first release in which this extension point appears.] + + + + + + + + + [Enter extension point usage example here.] + + + + + + + + + [Enter API information here.] + + + + + + + + + [Enter information about supplied implementation of this extension point.] + + + + + diff --git a/pipo/src/org/adempiere/pipo/srv/PipoDictionaryService.java b/pipo/src/org/adempiere/pipo/srv/PipoDictionaryService.java new file mode 100644 index 0000000000..6a9cd38541 --- /dev/null +++ b/pipo/src/org/adempiere/pipo/srv/PipoDictionaryService.java @@ -0,0 +1,81 @@ +package org.adempiere.pipo.srv; + +import java.io.File; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.adempiere.base.IDictionaryService; +import org.compiere.Adempiere; +import org.compiere.model.I_AD_Package_Imp_Proc; +import org.compiere.model.MPInstance; +import org.compiere.model.MPInstancePara; +import org.compiere.model.MProcess; +import org.compiere.model.X_AD_Package_Imp_Proc; +import org.compiere.process.ProcessInfo; +import org.compiere.util.Env; +import org.compiere.util.Trx; +import org.osgi.framework.BundleContext; + +public class PipoDictionaryService implements IDictionaryService { + + Logger logger = Logger.getLogger(PipoDictionaryService.class.getName()); + + /** official packin process id **/ + private final static int PACKIN_PROCESS_ID = 50008; + + @Override + public void merge(BundleContext context, File packageFile) throws Exception { + if (packageFile == null || !packageFile.exists()) { + logger.info("No PackIn Model found"); + return; + } + String trxName = Trx.createTrxName(); + try { + MProcess process = new MProcess(Env.getCtx(), PACKIN_PROCESS_ID, trxName); + X_AD_Package_Imp_Proc packageImp = new X_AD_Package_Imp_Proc(Env.getCtx(), 0, trxName); + packageImp.setAD_Override_Dict(false); + packageImp.setAD_Package_Dir(getPackageDir()); + packageImp.setAD_Package_Source(packageFile.getAbsolutePath()); + packageImp.setAD_Package_Source_Type(X_AD_Package_Imp_Proc.AD_PACKAGE_SOURCE_TYPE_File); + packageImp.saveEx(); + int Record_ID = packageImp.getAD_Package_Imp_Proc_ID(); + MPInstance pInstance = new MPInstance(process, Record_ID); + pInstance.saveEx(); + MPInstancePara para = new MPInstancePara(pInstance, 10); + para.setParameter("Name", context.getBundle().getSymbolicName()); + para.saveEx(); + para = new MPInstancePara(pInstance, 20); + para.setParameter("Version", (String) context.getBundle().getHeaders().get("Bundle-Version")); + para.saveEx(); + ProcessInfo pi = new ProcessInfo (process.getName(), process.getAD_Process_ID(), I_AD_Package_Imp_Proc.Table_ID, Record_ID); + pi.setAD_PInstance_ID(pInstance.getAD_PInstance_ID()); + process.processIt(pi, Trx.get(trxName, false)); + Trx.get(trxName, false).commit(); + logger.info("commit " + trxName); + } catch (Exception e) { + logger.log(Level.SEVERE, "importXML:", e); + throw e; + } finally { + Trx.get(trxName, false).close(); + } + + } + + private String getPackageDir() { + + // Create Target directory if required + String packageDirectory = Adempiere.getAdempiereHome(); + String result = packageDirectory + File.separator + + "packages"; + File docDir = new File( result+File.separator+"doc"); + + if (!docDir.exists()) { + boolean success = docDir.mkdirs(); + if (!success) { + logger.info("Target directory creation failed"); + } + } + return result; + } + +} diff --git a/pipo/src/org/adempiere/pipo2/AbstractElementHandler.java b/pipo/src/org/adempiere/pipo2/AbstractElementHandler.java new file mode 100644 index 0000000000..18b9a47cfd --- /dev/null +++ b/pipo/src/org/adempiere/pipo2/AbstractElementHandler.java @@ -0,0 +1,553 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com * + * Contributor(s): Low Heng Sin hengsin@avantz.com * + *****************************************************************************/ +package org.adempiere.pipo2; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import java.util.logging.Level; + +import javax.xml.transform.sax.TransformerHandler; + +import org.compiere.model.PO; +import org.compiere.model.POInfo; +import org.compiere.model.Query; +import org.compiere.model.X_AD_Package_Imp_Backup; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.util.CLogger; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +import java.sql.ResultSet; +import java.sql.PreparedStatement; + +import org.adempiere.pipo2.exception.DatabaseAccessException; + +/** + * + * @author hengsin + * + */ +public abstract class AbstractElementHandler implements ElementHandler { + + protected CLogger log = CLogger.getCLogger(getClass()); + + /** + * Get ID from Name for a table. + * + * @param tableName + * @param name + * + */ + public int findIdByName (Properties ctx, String tableName, String name) { + return IDFinder.findIdByName(tableName, name, getClientId(ctx), getTrxName(ctx)); + } + + /** + * Get ID from column value for a table. + * + * @param tableName + * @param columName + * @param name + */ + public int findIdByColumn (Properties ctx, String tableName, String columnName, Object value) { + int id = 0; + if ("AD_Table".equals(tableName) && "TableName".equals(columnName) && value != null) { + id = getPackInProcess(ctx).getTableId(value.toString()); + if (id <= 0) { + id = IDFinder.findIdByColumn(tableName, columnName, value, getClientId(ctx), getTrxName(ctx)); + if (id > 0) { + getPackInProcess(ctx).addTable(value.toString(), id); + } + } + } else { + id = IDFinder.findIdByColumn(tableName, columnName, value, getClientId(ctx), getTrxName(ctx)); + } + return id; + } + + /** + * @param ctx + * @param type + * @param tableName + * @param tableId + * @return X_AD_Package_Imp_Detail + */ + public X_AD_Package_Imp_Detail createImportDetail(Properties ctx, String type, String tableName, int tableId) { + X_AD_Package_Imp_Detail impDetail = new X_AD_Package_Imp_Detail(ctx, 0, getTrxName(ctx)); + impDetail.setAD_Package_Imp_ID(getPackageImpId(ctx)); + impDetail.setAD_Org_ID(Env.getAD_Org_ID(ctx) ); + impDetail.setType(type); + impDetail.setName(""); + impDetail.setAction(""); + impDetail.setAD_Original_ID(1); + impDetail.setTableName(tableName); + impDetail.setAD_Table_ID(tableId); + impDetail.saveEx(getTrxName(ctx)); + + return impDetail; + } + + /** + * Write results to log and records in history table + * + * @param ctx + * @param success + * @param detail + * @param objectName + * @param objectID + * @param action + * @throws SAXException + * + */ + public void logImportDetail (Properties ctx, X_AD_Package_Imp_Detail detail, int success, String objectName, int objectID, + String action) throws SAXException{ + StringBuffer recordLayout = new StringBuffer(); + TransformerHandler hd_document = getLogDocument(ctx); + AttributesImpl attsOut = new AttributesImpl(); + String result = success == 1 ? "Success" : "Failure"; + + //hd_documemt.startElement("","","Successful",attsOut); + recordLayout.append("Type:") + .append(detail.getType()) + .append(" - Name:") + .append(objectName) + .append(" - ID:") + .append(objectID) + .append(" - Action:") + .append(action) + .append(" - " + result); + + hd_document.startElement("","",result,attsOut); + hd_document.characters(recordLayout.toString().toCharArray(),0,recordLayout.length()); + hd_document.endElement("","",result); + + detail.setName(objectName); + detail.setAction(action); + detail.setSuccess(result); + detail.setAD_Original_ID(objectID); + detail.saveEx(getTrxName(ctx)); + } + + /** + * Get ID from Name for a table with a parent name reference. + * + * @param tableName + * @param name + * @param tableNameMaster + * @param nameMaster + */ + public int findIdByNameAndParentName (Properties ctx, String tableName, String name, String tableNameMaster, String nameMaster) { + return IDFinder.findIdByNameAndParentName(tableName, name, tableNameMaster, nameMaster, getTrxName(ctx)); + } + + /** + * Get ID from column value for a table with a parent id reference. + * + * @param tableName + * @param name + * @param tableNameMaster + * @param nameMaster + */ + + public int findIdByColumnAndParentId (Properties ctx, String tableName, String columnName, String name, String tableNameMaster, int masterID) { + return IDFinder.findIdByColumnAndParentId(tableName, columnName, name, tableNameMaster, masterID, + getTrxName(ctx)); + } + + /** + * Get ID from Name for a table with a parent reference ID. + * + * @param tableName + * @param name + * @param tableNameMaster + * @param masterID + */ + public int findIdByNameAndParentId (Properties ctx, String tableName, String name, String tableNameMaster, int masterID) { + return IDFinder.findIdByNameAndParentId(tableName, name, tableNameMaster, masterID, getTrxName(ctx)); + } + + /** + * Make backup copy of record. + * + * @param tablename + * + * + * + */ + + public void backupRecord(Properties ctx, int AD_Package_Imp_Detail_ID, String tableName,PO from){ + + // Create new record + int tableID = findIdByColumn(ctx, "AD_Table", "TableName", tableName); + POInfo poInfo = POInfo.getPOInfo(ctx, tableID, getTrxName(ctx)); + + PreparedStatement pstmtReferenceId = DB.prepareStatement("SELECT AD_Reference_ID FROM AD_COLUMN WHERE AD_Column_ID = ?", getTrxName(ctx)); + ResultSet rs=null; + + try{ + for (int i = 0; i < poInfo.getColumnCount(); i++){ + + int columnID =findIdByColumnAndParentId (ctx, "AD_Column", "ColumnName", poInfo.getColumnName(i), "AD_Table", tableID); + + int referenceID=0; + + pstmtReferenceId.setInt(1,columnID); + rs = pstmtReferenceId.executeQuery(); + + if (rs.next()) + referenceID = rs.getInt(1); + + X_AD_Package_Imp_Backup backup = new X_AD_Package_Imp_Backup(ctx, 0, getTrxName(ctx)); + backup.setAD_Org_ID(Env.getAD_Org_ID(ctx)); + backup.setAD_Package_Imp_ID(getPackageImpId(ctx)); + backup.setAD_Package_Imp_Detail_ID(AD_Package_Imp_Detail_ID); + backup.setAD_Table_ID(tableID); + + backup.setAD_Column_ID(columnID); + backup.setAD_Reference_ID(referenceID); + Object value = from.get_ValueOld(i); + backup.setColValue(value != null ? value.toString() : null); + + backup.saveEx(getTrxName(ctx)); + } + } + catch(Exception e) + { + throw new DatabaseAccessException(e); + } + finally + { + DB.close(rs, pstmtReferenceId); + } + } + + /** + * Open input file for processing + * + * @param String file with path + * + */ + public FileInputStream OpenInputfile (String filePath) { + + FileInputStream fileTarget = null; + + try { + fileTarget = new FileInputStream(filePath); + } + catch (FileNotFoundException e ) { + System.out.println("File not found: " + filePath); + + return null; + } + return fileTarget; + } + + /** + * Open output file for processing + * + * @param String file with path + * + */ + public OutputStream OpenOutputfile (String filePath) { + + OutputStream fileTarget = null; + + try { + fileTarget = new FileOutputStream(filePath); + } + catch (FileNotFoundException e ) { + System.out.println("File not found: " + filePath); + + return null; + } + return fileTarget; + } + + /** + * Copyfile + * + * @param String file with path + * + */ + public int copyFile (InputStream source,OutputStream target) { + + int byteCount = 0; + int success = 0; + try { + while (true) { + int data = source.read(); + if (data < 0) + break; + target.write(data); + byteCount++; + } + source.close(); + target.close(); + //System.out.println("Successfully copied " + byteCount + " bytes."); + } + catch (Exception e) { + log.log(Level.SEVERE, e.getLocalizedMessage(), e); + success = -1; + } + return success; + } + + /** + * Get client id + * @param ctx + * @return int + */ + protected int getClientId(Properties ctx) { + return Env.getContextAsInt(ctx, "AD_Client_ID"); + } + + /** + * Get AD_Package_Imp_ID + * @param ctx + * @return int + */ + protected int getPackageImpId(Properties ctx) { + return Env.getContextAsInt(ctx, "AD_Package_Imp_ID"); + } + + /** + * Get update system maintained dictionary flag + * @param ctx + * @return update mode + */ + protected String getUpdateMode(Properties ctx) { + return Env.getContext(ctx, "UpdateMode"); + } + + /** + * Get current transaction name + * @param ctx + * @return transaction name + */ + protected String getTrxName(Properties ctx) { + return Env.getContext(ctx, "TrxName"); + } + + /** + * Get share document + * @param ctx + * @return TransformerHandler + */ + protected TransformerHandler getLogDocument(Properties ctx) { + return (TransformerHandler)ctx.get("LogDocument"); + } + + /** + * @param ctx + * @return package directory + */ + protected String getPackageDirectory(Properties ctx) { + return Env.getContext(ctx, "PackageDirectory"); + } + + /** + * Process element by entity type and user setting. + * @param ctx + * @param entityType + * @return boolean + */ + protected boolean isProcessElement(Properties ctx, String entityType) { + if ("D".equals(entityType) || "C".equals(entityType)) { + return "true".equalsIgnoreCase(getUpdateMode(ctx)); + } else { + return true; + } + } + + /** + * return null for empty string (""). + * @param element + * @param qName + * @return string value + */ + protected String getStringValue(Element element, String qName) { + return getStringValue(element, qName, null); + } + + /** + * return null for empty string (""). + * @param element + * @param qName + * @return string value + */ + protected String getStringValue(Element element, String qName, List excludes) { + String name = qName; + String s = element.properties.get(qName).contents.toString(); + + if (s != null && s.trim().length() > 0 && excludes != null) { + excludes.add(name); + } + return ((s == null || s.trim().length() == 0) ? null : s.trim()); + } + + /** + * @param element + * @param qName + * @param defaultValue + * @return boolean + */ + protected boolean getBooleanValue(Element element, String qName, boolean defaultValue) { + String value = element.properties.get(qName).contents.toString(); + return value != null ? Boolean.valueOf(value).booleanValue() : defaultValue; + } + + /** + * @param element + * @param qName + * @return BigDecimal + */ + protected BigDecimal getBigDecimal(Element element, String qName) { + String value = element.properties.get(qName).contents.toString(); + return value != null ? new BigDecimal(value) : null; + } + + /** + * @param element + * @param qName + * @return int + */ + protected int getIntValue(Element element, String qName) { + Element pe = element.properties.get(qName); + String value = pe != null ? pe.contents.toString() : null; + return value != null ? Integer.parseInt(value) : 0; + } + + /** + * Returns option - Is export-import of AD translations is needed + * @param ctx + * @param entityType + * @return boolean + */ + protected boolean isHandleTranslations(Properties ctx) { + + return "true".equalsIgnoreCase(Env.getContext(ctx, "isHandleTranslations")); + } + + protected List defaultExcludeList(String tableName) { + List excludes = new ArrayList(); + excludes.add("ad_client_id"); + excludes.add("ad_org_id"); + excludes.add("created"); + excludes.add("createdby"); + excludes.add("updated"); + excludes.add("updatedby"); + excludes.add(tableName + "_ID"); + return excludes; + } + + protected PackIn getPackInProcess(Properties ctx) { + return (PackIn)ctx.get(PackInHandler.PACK_IN_PROCESS_CTX_KEY); + } + + protected PackOut getPackOutProcess(Properties ctx) { + return (PackOut) ctx.get(PackOut.PACK_OUT_PROCESS_CTX_KEY); + } + + protected int getParentId(Element element, String expectedName) { + if (element.parent != null && element.parent.getElementValue().equals(expectedName) && + element.parent.recordId > 0) + return element.parent.recordId; + else + return 0; + } + + protected boolean isParentDefer(Element element, String expectedName) { + if (element.parent != null + && (expectedName == null || element.parent.getElementValue().equals(expectedName)) + && element.parent.defer) + return true; + else + return false; + } + + protected boolean isParentSkip(Element element, String expectedName) { + if (element.parent != null + && (expectedName == null || element.parent.getElementValue().equals(expectedName)) + && element.parent.skip) + return true; + else + return false; + } + + protected boolean isOfficialId(Element element, String columnName) { + int value = getIntValue(element, columnName); + if (value > 0 && value <= PackOut.MAX_OFFICIAL_ID) + return true; + else + return false; + } + + protected void addTextProperty(TransformerHandler handler, String qName, String text) throws SAXException { + AttributesImpl atts = new AttributesImpl(); + atts.addAttribute("", "", qName, "reference", "property"); + handler.startElement("", "", qName, atts); + append(handler, text); + handler.endElement("", "", qName); + } + + protected void append(TransformerHandler document, String str) throws SAXException + { + char[] contents = str != null ? str.toCharArray() : new char[0]; + document.characters(contents,0,contents.length); + } + + /** + * Find po by uuid or id + * @param + * @param ctx + * @param element + * @return T + */ + protected T findPO(Properties ctx, Element element) { + T po = null; + String tableName = element.getElementValue(); + String uuidColumn = tableName + "_UU"; + String idColumn = tableName + "_ID"; + if (element.properties.containsKey(uuidColumn)) { + String uuid = element.properties.get(uuidColumn).contents.toString(); + if (uuid != null && uuid.trim().length() == 36) { + Query query = new Query(ctx, tableName, uuidColumn+"=?", getTrxName(ctx)); + po = query.setParameters(uuid.trim()).firstOnly(); + } + } else if (element.properties.containsKey(idColumn)) { + String id = element.properties.get(idColumn).contents.toString(); + if (id != null && id.trim().length() > 0) { + Query query = new Query(ctx, tableName, idColumn+"=?", getTrxName(ctx)); + po = query.setParameters(id.trim()).firstOnly(); + } + } + return po; + } + + protected void addTypeName(AttributesImpl atts, String typeName) { + atts.addAttribute("", "", "type", "CDATA", typeName); + } +} diff --git a/pipo/src/org/adempiere/pipo2/Element.java b/pipo/src/org/adempiere/pipo2/Element.java new file mode 100644 index 0000000000..98e9b3b802 --- /dev/null +++ b/pipo/src/org/adempiere/pipo2/Element.java @@ -0,0 +1,83 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.xml.sax.Attributes; + +/** + * XML element structure + * @author Low Heng Sin + * + */ +public class Element { + + public String uri; + public String localName; + public String qName; + //element attributes + public Attributes attributes; + //defer for later reprocessing + public boolean defer = false; + //parent element + public Element parent; + //resolved db recordid, store for reference by child element + public int recordId = 0; + //unresolved dependency + public String unresolved = ""; + //number of pass + public int pass = 1; + //skip this node + public boolean skip = false; + + public boolean deferEnd = false; + + public Map properties = new LinkedHashMap(); + + public List childrens = new ArrayList(); + + public StringBuffer contents = new StringBuffer(); + + /** + * @param uri + * @param localName + * @param qName + * @param attributes + */ + public Element(String uri, String localName, String qName, Attributes attributes) { + this.uri = uri; + this.localName = localName; + this.qName = qName; + this.attributes = attributes; + } + + /** + * @return elementValue + */ + public String getElementValue() { + String elementValue = null; + if ("".equals (uri)) + elementValue = qName; + else + elementValue = uri + localName; + return elementValue; + } +} diff --git a/pipo/src/org/adempiere/pipo2/ElementHandler.java b/pipo/src/org/adempiere/pipo2/ElementHandler.java new file mode 100644 index 0000000000..8994416ddf --- /dev/null +++ b/pipo/src/org/adempiere/pipo2/ElementHandler.java @@ -0,0 +1,57 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2; + +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.xml.sax.SAXException; + +/** + * Interface for handling import and export of table data using xml + * @author Low Heng Sin + * + */ +public interface ElementHandler { + + /** + * Handle start of xml element ( import ). + * @param ctx + * @param element + * @throws org.xml.sax.SAXException + */ + public void startElement (Properties ctx, Element element) + throws org.xml.sax.SAXException; + + /** + * Handle closing of xml element ( import ). + * @param ctx + * @param element + * @throws SAXException + */ + public void endElement (Properties ctx, Element element) throws SAXException; + + /** + * @param packout + * @param packoutHandler + * @param docHandler + * @param recordId + * @throws Exception + */ + public void packOut(PackOut packout, TransformerHandler packoutHandler, TransformerHandler docHandler,int recordId) throws Exception; +} diff --git a/pipo/src/org/adempiere/pipo2/IDFinder.java b/pipo/src/org/adempiere/pipo2/IDFinder.java new file mode 100644 index 0000000000..0e0c9820da --- /dev/null +++ b/pipo/src/org/adempiere/pipo2/IDFinder.java @@ -0,0 +1,353 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.HashMap; +import java.util.Map; + +import org.adempiere.pipo2.exception.DatabaseAccessException; +import org.compiere.util.CLogger; +import org.compiere.util.DB; +import org.compiere.util.Env; + +/** + * Utility class for the looking up of record id. + * @author Low Heng Sin + * + */ +public class IDFinder { + + private static CLogger log = CLogger.getCLogger(IDFinder.class); + + private static MapidCache = new HashMap(); + + /** + * Get ID from column value for a table. + * + * @param tableName + * @param columName + * @param value + * @param AD_Client_ID + * @param trxName + */ + public static int findIdByColumn (String tableName, String columnName, Object value, int AD_Client_ID, String trxName) { + int id = 0; + + if (value == null) + return id; + + //construct cache key + StringBuffer key = new StringBuffer(); + key.append(tableName) + .append(".") + .append(columnName) + .append("=") + .append(value.toString()) + .append(" AND AD_Client_ID=").append(AD_Client_ID); + + //check cache + if (idCache.containsKey(key.toString())) + return idCache.get(key.toString()); + + StringBuffer sqlB = new StringBuffer ("SELECT ") + .append(tableName) + .append("_ID FROM ") + .append(tableName) + .append(" WHERE ") + .append(columnName) + .append(" = ?") + .append(" AND AD_Client_ID IN (0, ?)") + .append(" Order By AD_Client_ID Desc, ") + .append(tableName) + .append("_ID"); + + PreparedStatement pstmt = null; + ResultSet rs = null; + try { + pstmt = DB.prepareStatement(sqlB.toString(), trxName); + if (value instanceof String) + pstmt.setString(1, (String)value); + else if (value instanceof Integer) + pstmt.setInt(1, ((Integer)value).intValue()); + else + pstmt.setObject(1, value); + pstmt.setInt(2, AD_Client_ID); + + rs = pstmt.executeQuery(); + if (rs.next()) + id = rs.getInt(1); + } + catch (Exception e) { + throw new DatabaseAccessException(e); + } finally { + DB.close(rs, pstmt); + } + + //update cache + if (id > 0) + idCache.put(key.toString(), id); + + return id; + } + + /** + * Get ID from Name for a table with a parent name reference. + * + * @param tableName + * @param name + * @param tableNameMaster + * @param nameMaster + * @param trxName + */ + public static int findIdByNameAndParentName (String tableName, String name, String tableNameMaster, String nameMaster, String trxName) { + int id = 0; + //construct cache key + StringBuffer key = new StringBuffer(); + key.append(tableName) + .append(".Name=") + .append(name) + .append(" and ") + .append(tableNameMaster) + .append(".Name=") + .append(nameMaster); + + //check cache + if (idCache.containsKey(key.toString())) + return idCache.get(key.toString()); + + StringBuffer parentSql = new StringBuffer("SELECT ") + .append(tableNameMaster) + .append("_ID FROM ") + .append(tableNameMaster) + .append(" WHERE Name = ? AND AD_Client_ID IN (0, ?) ") + .append("ORDER BY AD_Client_ID Desc"); + int parentId = DB.getSQLValue(trxName, parentSql.toString(), Env.getAD_Client_ID(Env.getCtx())); + + if (parentId > 0) { + StringBuffer sqlB = new StringBuffer ("SELECT ") + .append(tableName) + .append("_ID FROM ") + .append(tableName) + .append(" WHERE Name = ? AND ") + .append(tableNameMaster) + .append("_ID = ?"); + + PreparedStatement pstmt = null; + ResultSet rs = null; + try { + pstmt = DB.prepareStatement(sqlB.toString(), trxName); + pstmt.setString(1, name); + pstmt.setString(2, nameMaster); + pstmt.setInt(3, parentId); + rs = pstmt.executeQuery(); + if (rs.next()) + id = rs.getInt(1); + } catch (Exception e) { + throw new DatabaseAccessException(e); + } finally { + DB.close(rs, pstmt); + } + } + + //update cache + if (id > 0) + idCache.put(key.toString(), id); + + return id; + } + + /** + * Get ID from column value for a table with a parent id reference. + * + * @param tableName + * @param name + * @param tableNameMaster + * @param masterID + * @param trxName + */ + + public static int findIdByColumnAndParentId (String tableName, String columnName, String name, String tableNameMaster, int masterID, String trxName) { + int id = 0; + + //check cache + String key = tableName + "." + columnName + "=" + name + tableNameMaster + "=" + masterID; + + if (idCache.containsKey(key)) + return idCache.get(key); + + StringBuffer sqlB = new StringBuffer ("SELECT ") + .append(tableName) + .append("_ID FROM ") + .append(tableName) + .append(" WHERE ") + .append(columnName) + .append(" = ? and ") + .append(tableNameMaster+"_ID = ? AND AD_Client_ID IN (0, ?) ") + .append("ORDER BY AD_Client_ID Desc "); + + log.info(sqlB.toString()); + + PreparedStatement pstmt = null; + ResultSet rs = null; + try { + + pstmt = DB.prepareStatement(sqlB.toString(), trxName); + pstmt.setString(1, name); + pstmt.setInt(2, masterID); + pstmt.setInt(3, Env.getAD_Client_ID(Env.getCtx())); + rs = pstmt.executeQuery(); + if (rs.next()) + { + id = rs.getInt(1); + } + } + catch (Exception e) { + throw new DatabaseAccessException(e); + } finally { + DB.close(rs, pstmt); + } + + //update cache + if (id > 0) + idCache.put(key, id); + + return id; + } + + /** + * Get ID from Name for a table with a parent reference ID. + * + * @param tableName + * @param name + * @param tableNameMaster + * @param masterID + * @param trxName + */ + public static int findIdByNameAndParentId (String tableName, String name, String tableNameMaster, int masterID, String trxName) { + int id = 0; + + //construct cache key + StringBuffer key = new StringBuffer(); + key.append(tableName) + .append(".Name=") + .append(name) + .append(" AND ") + .append(tableNameMaster) + .append(".") + .append(tableNameMaster) + .append("_ID=") + .append(masterID); + + //check cache + if (idCache.containsKey(key.toString())) + return idCache.get(key.toString()); + + StringBuffer sqlB = new StringBuffer ("SELECT ") + .append(tableName) + .append("_ID FROM ") + .append(tableName) + .append(" WHERE Name=? AND ") + .append(tableNameMaster) + .append("_ID=? AND AD_Client_ID IN (0, ?) ") + .append("ORDER BY AD_Client_ID Desc"); + + PreparedStatement pstmt = null; + ResultSet rs = null; + try { + pstmt = DB.prepareStatement(sqlB.toString(), trxName); + pstmt.setString(1, name); + pstmt.setInt(2, masterID); + pstmt.setInt(3, Env.getAD_Client_ID(Env.getCtx())); + rs = pstmt.executeQuery(); + if (rs.next()) + id = rs.getInt(1); + } + catch (Exception e) { + throw new DatabaseAccessException(e); + } finally { + DB.close(rs, pstmt); + } + + //update cache + if (id > 0) + idCache.put(key.toString(), id); + + return id; + } + + /** + * Get ID from Name for a table. + * + * @param tableName + * @param name + * @param AD_Client_ID + * @param trxName + */ + public static int findIdByName (String tableName, String name, int AD_Client_ID, String trxName) { + int id = 0; + + //construct cache key + StringBuffer key = new StringBuffer(); + key.append(tableName) + .append(".Name=") + .append(name); + if (!tableName.startsWith("AD_")) + key.append(" AND AD_Client_ID=").append(AD_Client_ID); + + //check cache + if (idCache.containsKey(key.toString())) + return idCache.get(key.toString()); + + StringBuffer sql = new StringBuffer("SELECT ") + .append(tableName) + .append("_ID ") + .append("FROM ") + .append(tableName) + .append(" ") + .append("WHERE Name=? ") + .append(" AND AD_Client_ID IN (0, ?) ") + .append(" ORDER BY AD_Client_ID Desc"); + + PreparedStatement pstmt = null; + ResultSet rs = null; + try { + pstmt = DB.prepareStatement(sql.toString(), trxName); + pstmt.setString(1, name); + pstmt.setInt(2, AD_Client_ID); + rs = pstmt.executeQuery(); + if (rs.next()) + id = rs.getInt(1); + } + catch (Exception e) { + throw new DatabaseAccessException(e); + } finally { + DB.close(rs, pstmt); + } + + //update cache + if (id > 0) + idCache.put(key.toString(), id); + + return id; + } + + public static void clearIDCache() { + idCache.clear(); + } +} diff --git a/pipo/src/org/adempiere/pipo2/IHandlerRegistry.java b/pipo/src/org/adempiere/pipo2/IHandlerRegistry.java new file mode 100644 index 0000000000..fd519f395f --- /dev/null +++ b/pipo/src/org/adempiere/pipo2/IHandlerRegistry.java @@ -0,0 +1,24 @@ +package org.adempiere.pipo2; + +public interface IHandlerRegistry { + + public static final String ELEMENT_TYPE_TRANSLATION = "translation"; + public static final String ELEMENT_TYPE_TABLE = "table"; + public static final String ELEMENT_TYPE_TASK = "task"; + public static final String ELEMENT_TYPE_PROPERTIES = "properties"; + + public static final String TABLE_TRANSLATION_HANDLER = "table.translationHandler"; + public static final String TABLE_GENERIC_HANDLER = "table.genericHandler"; + + /** + * @param element + * @return ElementHandler + */ + public ElementHandler getHandler(Element element); + + /** + * @param name + * @return ElementHandler + */ + public ElementHandler getHandler(String name); +} diff --git a/pipo/src/org/adempiere/pipo2/OSGiHandlerRegistry.java b/pipo/src/org/adempiere/pipo2/OSGiHandlerRegistry.java new file mode 100644 index 0000000000..6268e8b04b --- /dev/null +++ b/pipo/src/org/adempiere/pipo2/OSGiHandlerRegistry.java @@ -0,0 +1,59 @@ +/** + * + */ +package org.adempiere.pipo2; + +import org.adempiere.base.Service; +import org.adempiere.base.ServiceQuery; + +/** + * @author hengsin + * + */ +public class OSGiHandlerRegistry implements IHandlerRegistry { + + private final static String SERVICE_ID = "org.adempiere.pipo.Handlers"; + /** + * + */ + public OSGiHandlerRegistry() { + // TODO Auto-generated constructor stub + } + + /* (non-Javadoc) + * @see org.adempiere.pipo2.IHandlerRegistry#getHandler(org.adempiere.pipo2.Element) + */ + @Override + public ElementHandler getHandler(Element element) { + String id = null; + ElementHandler handler = null; + String type = element.attributes.getValue("type"); + if (ELEMENT_TYPE_TRANSLATION.equals(type)) { + id = TABLE_TRANSLATION_HANDLER; + } else { + id = element.getElementValue(); + } + + ServiceQuery query = new ServiceQuery(); + query.put("id", id); + handler = Service.locate(ElementHandler.class, SERVICE_ID, query); + if (handler == null) { + id = TABLE_GENERIC_HANDLER; + query.put("id", id); + handler = Service.locate(ElementHandler.class, SERVICE_ID, query); + } + return handler; + } + + /* (non-Javadoc) + * @see org.adempiere.pipo2.IHandlerRegistry#getHandler(java.lang.String) + */ + @Override + public ElementHandler getHandler(String name) { + ElementHandler handler = null; + ServiceQuery query = new ServiceQuery(); + query.put("id", name); + handler = Service.locate(ElementHandler.class, SERVICE_ID, query); + return handler; + } +} diff --git a/pipo/src/org/adempiere/pipo2/PackIn.java b/pipo/src/org/adempiere/pipo2/PackIn.java new file mode 100644 index 0000000000..147c1aa6fe --- /dev/null +++ b/pipo/src/org/adempiere/pipo2/PackIn.java @@ -0,0 +1,396 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert KLEIN. robeklein@hotmail.com + * + *****************************************************************************/ + +package org.adempiere.pipo2; + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import java.util.logging.Level; + +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; + +import org.compiere.Adempiere; +import org.compiere.db.CConnection; +import org.compiere.model.X_AD_Package_Imp_Proc; +import org.compiere.process.ProcessInfoParameter; +import org.compiere.process.SvrProcess; +import org.compiere.util.CLogMgt; +import org.compiere.util.CLogger; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.compiere.util.Ini; +import org.compiere.util.Trx; + +/** + * IntPackIn Tool. + * + * @author: Robert KLEIN. robeklein@hotmail.com + */ +public class PackIn extends SvrProcess { + + /** Logger */ + private CLogger log = CLogger.getCLogger(getClass()); + //update system maintain dictionary, default to false + private boolean m_UpdateDictionary = false; + private String m_Database = "Oracle"; + private String m_Package_Dir = null; + public int p_PackIn_ID = 0; + + private Map tableCache = new HashMap(); + private Map columnCache = new HashMap(); + private String packageName = null; + private String packageVersion = null; + + public PackIn() { + super(); + if (DB.isOracle()) + m_Database = "Oracle"; + else if (DB.isPostgreSQL()) + m_Database = "PostgreSQL"; + } + + /** + * add to table id cache + * @param tableName + * @param tableId + */ + public void addTable(String tableName, int tableId) { + tableCache.put(tableName, tableId); + } + + /** + * Find table id from cache + * @param tableName + * @return tableId + */ + public int getTableId(String tableName) { + if (tableCache.containsKey(tableName)) + return tableCache.get(tableName).intValue(); + else + return 0; + } + + /** + * add to column id cache + * @param tableName + * @param columnName + * @param columnId + */ + public void addColumn(String tableName, String columnName, int columnId) { + columnCache.put(tableName+"."+columnName, columnId); + } + + /** + * find column id from cache + * @param tableName + * @param columnName + * @return column id + */ + public int getColumnId(String tableName, String columnName) { + String key = tableName+"."+columnName; + if (columnCache.containsKey(key)) + return columnCache.get(key).intValue(); + else + return 0; + } + + protected void prepare() { + + p_PackIn_ID = getRecord_ID(); + ProcessInfoParameter[] params = getParameter(); + if (params != null && params.length > 0) { + for(ProcessInfoParameter param : params) { + if ("Name".equals(param.getParameterName())) { + packageName = param.getParameter().toString(); + } else if ("Version".equals(param.getParameterName())) { + packageVersion = param.getParameter().toString(); + } + } + } + } // prepare + + /** + * Uses PackInHandler to update AD. + * + * @param fileName + * xml file to read + * @return status message + */ + public String importXML(String fileName, Properties ctx, String trxName) throws Exception { + log.info("importXML:" + fileName); + File in = new File(fileName); + if (!in.exists()) { + String msg = "File does not exist: " + fileName; + log.info("importXML:" + msg); + return msg; + } + try { + FileInputStream input = new FileInputStream(in); + return importXML(input, ctx, trxName); + } catch (Exception e) { + log.log(Level.SEVERE, "importXML:", e); + throw e; + } + } + + public String importXML(InputStream input, Properties ctx, String trxName) { + try { + log.info("starting"); + System.setProperty("javax.xml.parsers.SAXParserFactory", + "org.apache.xerces.jaxp.SAXParserFactoryImpl"); + PackInHandler handler = new PackInHandler(); + handler.set_TrxName(trxName); + handler.setCtx(ctx); + handler.setProcess(this); + SAXParserFactory factory = SAXParserFactory.newInstance(); + SAXParser parser = factory.newSAXParser(); + String msg = "Start Parser"; + log.info(msg); + parser.parse(input, handler); + msg = "End Parser"; + log.info(msg); + return "Processed="+handler.getElementsProcessed()+" Un-Resolved="+handler.getUnresolvedCount(); + } catch (Exception e) { + log.log(Level.SEVERE, "importXML:", e); + throw new RuntimeException(e.getLocalizedMessage(), e); + } + } + + /** + * Doit + * + * @return "" + * + */ + protected String doIt() throws Exception { + + X_AD_Package_Imp_Proc adPackageImp = new X_AD_Package_Imp_Proc(getCtx(), + p_PackIn_ID, null); + + // clear cache of previous runs + IDFinder.clearIDCache(); + + // Create Target directory if required + String packageDirectory = adPackageImp.getAD_Package_Dir(); + if (packageDirectory == null || packageDirectory.trim().length() == 0) { + packageDirectory = Adempiere.getAdempiereHome(); + } + + String targetDirName = packageDirectory + File.separator + "packages"; + File targetDir = new File(targetDirName); + + if (!targetDir.exists()) { + boolean success = targetDir.mkdirs(); + if (!success) { + log.warning("Failed to create target directory. " + targetDirName); + } + } + + // Unzip package + File zipFilepath = new File(adPackageImp.getAD_Package_Source()); + log.info("zipFilepath->" + zipFilepath); + String PackageName = Zipper.getParentDir(zipFilepath); + Zipper.unpackFile(zipFilepath, targetDir); + + String dict_file = packageDirectory + File.separator + + "packages" + File.separator + PackageName + File.separator + + "dict" + File.separator + "PackOut.xml"; + + log.info("dict file->" + dict_file); + + if (adPackageImp.isAD_Override_Dict() == true) + m_UpdateDictionary = true; + else + m_UpdateDictionary = false; + + m_Package_Dir = packageDirectory + File.separator + + "packages" + File.separator + PackageName + File.separator; + + // call XML Handler + String msg = importXML(dict_file, getCtx(), get_TrxName()); + + // Generate Model Classes + // globalqss - don't call Generate Model must be done manual + // String args[] = + // {IntPackIn.getAD_Package_Dir()+"/dbPort/src/org/compiere/model/", + // "org.compiere.model","'U'"}; + // org.compiere.util.GenerateModel.main(args) ; + + return msg; + } // doIt + + public String getPackageDirectory() { + return m_Package_Dir; + } + + public void setPackageDirectory(String packageDirectory) { + m_Package_Dir = packageDirectory; + } + + public String getDatabaseType() { + return m_Database; + } + + public boolean isUpdateDictionary() { + return m_UpdateDictionary; + } + + public void setUpdateDictionary(boolean updateDictionary) { + m_UpdateDictionary = updateDictionary; + } + + public byte[] readBlob(String fileName) throws IOException { + byte[] data = null; + File file = new File(m_Package_Dir+File.separator+"blobs"+File.separator, fileName); + FileInputStream fis = null; + + try { + fis = new FileInputStream(file); + BufferedInputStream bis = new BufferedInputStream(fis); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + while (true) { + int b = bis.read(); + if (b == -1) + break; + else + baos.write(b); + } + } finally { + if (fis != null) { + try { + fis.close(); + } catch (IOException e) {} + } + } + return data; + } + + /** + * @return package name + */ + public String getPackageName() { + return packageName; + } + + /** + * @return package Version + */ + public String getPackageVersion() { + return packageVersion; + } + + /*************************************************************************** + * + * @param args + * XMLfile host port db username password + */ + public static void main(String[] args) { + if (args.length < 1) { + System.out + .println("Please give the file name to read as first parameter."); + System.exit(1); + } + + String file = args[0]; + org.compiere.Adempiere.startup(true); + + // globalqss - added argument 8 to generate system sequences + if (args.length > 8 && args[8].equals(Ini.P_ADEMPIERESYS)) { + System.out.println("**** WARNING: Working with system sequences " + + Ini.P_ADEMPIERESYS + " ****"); + Ini.setProperty(Ini.P_ADEMPIERESYS, true); + } + + PackIn packIn = new PackIn(); + // org.compiere.Compiere.startupEnvironment(true); + // Force connection if there are enough parameters. Else we work with + // Compiere.properties + if (args.length >= 6) { + // CConnection cc = CConnection.get("PostgreSQL", args[1], + // Integer.valueOf(args[2]).intValue(), args[5], args[3], args[4]); + CConnection cc = CConnection.get(); + // System.out.println("DB Connect String1:"+cc.getDbName()); + packIn.m_Database = cc.getType(); + DB.setDBTarget(cc); + } + + // Level.OFF, Level.SEVERE, Level.WARNING, Level.INFO, + // Level.CONFIG, Level.FINE, Level.FINER, Level.FINEST, Level.ALL + + Level logLevel = Level.FINER; + + switch (Integer.parseInt(args[6])) { + case 1: + logLevel = Level.OFF; + break; + case 2: + logLevel = Level.SEVERE; + break; + case 3: + logLevel = Level.WARNING; + break; + case 4: + logLevel = Level.INFO; + break; + case 5: + logLevel = Level.CONFIG; + break; + case 6: + logLevel = Level.FINE; + break; + case 7: + logLevel = Level.FINER; + break; + case 8: + logLevel = Level.FINEST; + break; + case 9: + logLevel = Level.ALL; + break; + } + CLogMgt.setLevel(logLevel); + CLogMgt.setLoggerLevel(logLevel, null); + + if (args.length >= 8) + packIn.m_UpdateDictionary = Boolean.valueOf(args[7]); + + String trxName = Trx.createTrxName("PackIn"); + try { + packIn.importXML(file, Env.getCtx(), trxName); + Trx trx = Trx.get(trxName, false); + if (trx != null) + trx.commit(true); + } catch (Exception e) { + System.out.println("Import Failed: " + e.getLocalizedMessage()); + Trx trx = Trx.get(trxName, false); + if (trx != null) + trx.rollback(); + } + + System.exit(0); + } // main + + +} // PackIn diff --git a/pipo/src/org/adempiere/pipo2/PackInHandler.java b/pipo/src/org/adempiere/pipo2/PackInHandler.java new file mode 100644 index 0000000000..65afd12958 --- /dev/null +++ b/pipo/src/org/adempiere/pipo2/PackInHandler.java @@ -0,0 +1,469 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * * + * Copyright (C) 2004 Marco LOMBARDO. lombardo@mayking.com * + * Contributor: Robert KLEIN. robeklein@hotmail.com * + * Contributor: Tim Heath * + * Contributor: Low Heng Sin hengsin@avantz.com * + *****************************************************************************/ + +package org.adempiere.pipo2; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Properties; +import java.util.Stack; +import java.util.logging.Level; + +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.sax.SAXTransformerFactory; +import javax.xml.transform.sax.TransformerHandler; +import javax.xml.transform.stream.StreamResult; + +import org.adempiere.pipo2.exception.DatabaseAccessException; +import org.compiere.model.X_AD_Package_Imp; +import org.compiere.model.X_AD_Package_Imp_Inst; +import org.compiere.util.CLogger; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.compiere.util.Trx; +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; +import org.xml.sax.helpers.DefaultHandler; + +/** + * SAX Handler for parsing XML description of the GUI. + * + * @author Marco LOMBARDO, lombardo@mayking.com + * @author Robert KLEIN, robeklein@hotmailo + * + * Contributor: William G. Heath - Import of workflows and dynamic validations + */ +public class PackInHandler extends DefaultHandler { + + public static final String PACK_IN_PROCESS_CTX_KEY = "PackInProcess"; + + /** + * PackInHandler Handler + */ + public PackInHandler () { + setupHandlers(); + } // PackInHandler + + /** Set this if you want to update Dictionary */ + private boolean m_updateDictionary = false; + private String packageDirectory = null; + private int AD_Package_Imp_ID=0; + private int AD_Package_Imp_Inst_ID=0; + private CLogger log = CLogger.getCLogger(PackInHandler.class); + private OutputStream logOutputStream = null; + private TransformerHandler logDocument = null; + private StreamResult loStreamResult = null; + private SAXTransformerFactory transformerFactory = null; + private Transformer logTransformer = null; + private boolean isInit = false; + private String logDate = null; + private String packageStatus = "Installing"; + // transaction name + private String m_trxName = null; + private Properties m_ctx = null; + + private IHandlerRegistry handlerRegistry = null; + private List defer = new ArrayList(); + private Stack stack = new Stack(); + private PackIn packIn; + private int elementProcessed = 0; + + private void init() throws SAXException { + + packageDirectory = packIn.getPackageDirectory(); + m_updateDictionary = packIn.isUpdateDictionary(); + SimpleDateFormat formatter_file = new SimpleDateFormat("yyMMddHHmmssZ"); + SimpleDateFormat formatter_log = new SimpleDateFormat("MM/dd/yy HH:mm:ss"); + Date today = new Date(); + String fileDate = formatter_file.format(today); + logDate = formatter_log.format(today); + + String logFileName = packageDirectory+File.separator+"doc"+File.separator+"Importlog_"+fileDate+".xml"; + log.info("packin log file="+logFileName); + try { + logOutputStream = new FileOutputStream (logFileName, false); + } catch (FileNotFoundException e1) { + log.warning ("Failed to create log file. error="+e1+" file="+logFileName); + } + loStreamResult = new StreamResult(logOutputStream); + transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); + + try { + logDocument = transformerFactory.newTransformerHandler(); + } catch (TransformerConfigurationException e2) { + log.info ("startElement:"+e2); + } + logTransformer = logDocument.getTransformer(); + logTransformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1"); + logTransformer.setOutputProperty(OutputKeys.INDENT,"yes"); + logDocument.setResult(loStreamResult); + logDocument.startDocument(); + logDocument.processingInstruction("xml-stylesheet","type=\"text/css\" href=\"adempiereDocument.css\""); + Properties tmp = new Properties(); + if (m_ctx != null) + tmp.putAll(m_ctx); + else + tmp.putAll(Env.getCtx()); + m_ctx = tmp; + if (m_trxName == null) + m_trxName = Trx.createTrxName("PackIn"); + + isInit=true; + } + + private void setupHandlers() { + handlerRegistry = new OSGiHandlerRegistry(); + } + + /** + * Receive notification of the start of an element. + * + * @param uri namespace + * @param localName simple name + * @param qName qualified name + * @param atts attributes + * @throws org.xml.sax.SAXException + */ + public void startElement (String uri, String localName, String qName, Attributes atts) + throws org.xml.sax.SAXException { + + // Initialize the handler + if (isInit == false){ + init(); + } + + // adempiereAD. + if (qName.equals("adempiereAD")) + { + log.info("adempiereAD updateMode="+m_updateDictionary); + + createLogHeader(atts); + + // Update Summary Package History Table + + int PK_preInstalled=0; + + String packageName = packIn.getPackageName(); + if (packageName == null || packageName.trim().length() == 0) + { + packageName = atts.getValue("Name"); + } + String packageVersion = packIn.getPackageVersion(); + if (packageVersion == null || packageVersion.trim().length() == 0) + { + packageVersion = atts.getValue("Version"); + } + + PreparedStatement pstmt = null; + ResultSet rs = null; + try { + pstmt = DB.prepareStatement("SELECT AD_PACKAGE_IMP_INST_ID FROM AD_PACKAGE_IMP_INST WHERE NAME =? AND PK_VERSION =?", null); + pstmt.setString(1,packageName); + pstmt.setString(2,packageVersion); + rs = pstmt.executeQuery(); + + if (rs.next()) + { + PK_preInstalled = rs.getInt(1); + } + } catch (Exception e) { + throw new DatabaseAccessException(e); + } finally { + DB.close(rs, pstmt); + } + + X_AD_Package_Imp packageImp = new X_AD_Package_Imp(m_ctx, 0, null); + packageImp.setAD_Org_ID(Env.getAD_Org_ID(m_ctx)); + packageImp.setReleaseNo(atts.getValue("CompVer")); + packageImp.setPK_Version(packageVersion); + packageImp.setVersion(atts.getValue("DataBase")); + packageImp.setDescription(atts.getValue("Description").replaceAll("'","''")); + packageImp.setName(packageName); + packageImp.setCreator(atts.getValue("Creator")); + packageImp.setCreatorContact(atts.getValue("CreatorContact")); + packageImp.setPK_Status(packageStatus); + + packageImp.saveEx(); + AD_Package_Imp_ID = packageImp.getAD_Package_Imp_ID(); + + if ( PK_preInstalled <= 0){ + //Insert Package into package install log + + X_AD_Package_Imp_Inst packageInst = new X_AD_Package_Imp_Inst(m_ctx, 0, null); + packageInst.setAD_Org_ID(Env.getAD_Org_ID(m_ctx)); + packageInst.setReleaseNo(atts.getValue("CompVer")); + packageInst.setPK_Version(atts.getValue("Version")); + packageInst.setVersion(atts.getValue("DataBase")); + packageInst.setDescription(atts.getValue("Description").replaceAll("'","''")); + packageInst.setName(atts.getValue("Name")); + packageInst.setCreator(atts.getValue("Creator")); + packageInst.setCreatorContact(atts.getValue("CreatorContact")); + packageInst.setPK_Status(packageStatus); + packageInst.saveEx(); + AD_Package_Imp_Inst_ID = packageInst.get_ID(); + } else { + //Update package list with package status + AD_Package_Imp_Inst_ID = PK_preInstalled; + + X_AD_Package_Imp_Inst packageInst = new X_AD_Package_Imp_Inst(m_ctx, AD_Package_Imp_Inst_ID, null); + packageInst.setPK_Status(packageStatus); + packageInst.saveEx(); + } + + Env.setContext(m_ctx, "AD_Package_Imp_ID", AD_Package_Imp_ID); + Env.setContext(m_ctx, "UpdateMode", m_updateDictionary); + Env.setContext(m_ctx, "TrxName", m_trxName); + Env.setContext(m_ctx, "PackageDirectory", packageDirectory); + m_ctx.put("LogDocument", logDocument); + m_ctx.put(PACK_IN_PROCESS_CTX_KEY, packIn); + } else { + Element e = new Element(uri, localName, qName, new AttributesImpl(atts)); + if (stack.size() > 0) + { + e.parent = stack.peek(); + String reference = atts.getValue("type"); + if (!IHandlerRegistry.ELEMENT_TYPE_PROPERTIES.equals(reference)) + { + e.parent.childrens.add(e); + } + else + { + e.parent.properties.put(qName, e); + } + } + stack.push(e); + } + } // startElement + + private void processElement(Element element) throws SAXException + { + ElementHandler handler = handlerRegistry.getHandler(element); + if (handler != null) + handler.startElement(m_ctx, element); + if (element.defer) + { + defer.add(new DeferEntry(element, true)); + } + + for (Element childElement : element.childrens) + { + processElement(childElement); + if (element.defer) { + defer.add(new DeferEntry(element, false)); + } else { + if (handler != null) + handler.endElement(m_ctx, element); + if (element.defer || element.deferEnd) + defer.add(new DeferEntry(element, false)); + else if (!element.skip) { + if (log.isLoggable(Level.INFO)) + log.info("Processed: " + element.getElementValue() + " - " + element.attributes.getValue(0)); + elementProcessed++; + } + } + } + + } + + private void createLogHeader(Attributes atts) throws SAXException { + AttributesImpl attsOut = new AttributesImpl(); + logDocument.startElement("","","adempiereDocument",attsOut); + PackOut.addTextElement(logDocument, "header", atts.getValue("Name")+" Install Log", attsOut); + PackOut.addTextElement(logDocument, "H3", "Package Name:", attsOut); + PackOut.addTextElement(logDocument, "packagename4log", atts.getValue("Name"), attsOut); + PackOut.addTextElement(logDocument, "H3", "Version:", attsOut); + PackOut.addTextElement(logDocument, "Version", atts.getValue("Version"), attsOut); + PackOut.addTextElement(logDocument, "H3", "Package Install Date:", attsOut); + PackOut.addTextElement(logDocument, "installDate", logDate, attsOut); + PackOut.addTextElement(logDocument, "H3", "Min. Version:", attsOut); + PackOut.addTextElement(logDocument, "AdempiereVersion", atts.getValue("AdempiereVersion"), attsOut); + PackOut.addTextElement(logDocument, "H3", "Min. Database Date:", attsOut); + PackOut.addTextElement(logDocument, "Database", atts.getValue("Database"), attsOut); + } + + /** + * @see org.xml.sax.helpers.DefaultHandler#characters(char[], int, int) + */ + @Override + public void characters(char[] ch, int start, int length) + throws SAXException { + if (stack.size() > 0 && length > 0) + { + Element e = stack.peek(); + e.contents.append(ch, start, length); + } + } + + /** + * Receive notification of the end of an element. + * @param uri namespace + * @param localName simple name + * @param qName qualified name + * @throws SAXException + */ + public void endElement (String uri, String localName, String qName) throws SAXException { + // Check namespace. + + String elementValue = null; + if ("".equals (uri)) + elementValue = qName; + else + elementValue = uri + localName; + + if (elementValue.equals("adempiereAD")){ + processDeferElements(); + if (!packageStatus.equals("Completed with errors")) + packageStatus = "Completed successfully"; + + //Update package history log with package status + X_AD_Package_Imp packageImp = new X_AD_Package_Imp(m_ctx, AD_Package_Imp_ID, null); + packageImp.setPK_Status(packageStatus); + packageImp.saveEx(); + + //Update package list with package status + X_AD_Package_Imp_Inst packageInst = new X_AD_Package_Imp_Inst(m_ctx, AD_Package_Imp_Inst_ID, null); + packageInst.setPK_Status(packageStatus); + packageInst.saveEx(); + + logDocument.endElement("","","adempiereDocument"); + logDocument.endDocument(); + try { + logOutputStream.close(); + } + catch (Exception e) + {} + + //reset + setupHandlers(); + } else { + Element e = stack.pop(); + if (stack.isEmpty()) + { + processElement(e); + } + } + } // endElement + + private void processDeferElements() throws SAXException { + + if (defer.isEmpty()) return; + + do { + int startSize = defer.size(); + List tmp = new ArrayList(defer); + defer.clear(); + for (DeferEntry d : tmp) { + if (d.startElement) { + d.element.defer = false; + d.element.unresolved = ""; + d.element.pass++; + } else { + if (d.element.deferEnd) { + d.element.deferEnd = false; + d.element.unresolved = ""; + } + } + if (log.isLoggable(Level.INFO)) { + log.info("Processeing Element: " + d.element.getElementValue() + " - " + + d.element.attributes.getValue(0)); + } + ElementHandler handler = handlerRegistry.getHandler(d.element); + if (handler != null) { + if (d.startElement) + handler.startElement(m_ctx, d.element); + else + handler.endElement(m_ctx, d.element); + } + if (d.element.defer) + defer.add(d); + else if (!d.startElement) { + if (d.element.deferEnd) + defer.add(d); + else { + if (log.isLoggable(Level.INFO)) + log.info("Imported Defer Element: " + d.element.getElementValue() + " - " + + d.element.attributes.getValue(0)); + elementProcessed++; + } + } + } + int endSize = defer.size(); + if (startSize == endSize) break; + } while (defer.size() > 0); + } + + // globalqss - add support for trx in 3.1.2 + public void set_TrxName(String trxName) { + m_trxName = trxName; + } + + // globalqss - add support for trx in 3.1.2 + public void setCtx(Properties ctx) { + m_ctx = ctx; + } + + /** + * @param packIn + */ + public void setProcess(PackIn packIn) { + this.packIn = packIn; + } + + /** + * @return number of elements that processed successfully + */ + public int getElementsProcessed() { + return elementProcessed; + } + + /** + * @return number of unresolved elements + */ + public int getUnresolvedCount() { + int count = 0; + if (defer != null && !defer.isEmpty()) { + for(DeferEntry entry : defer) { + if (!entry.startElement) + count++; + } + } + return count; + } + + class DeferEntry { + Element element; + boolean startElement = false; + + DeferEntry(Element e, boolean b) { + element = e; + startElement = b; + } + } +} // PackInHandler diff --git a/pipo/src/org/adempiere/pipo2/PackOut.java b/pipo/src/org/adempiere/pipo2/PackOut.java new file mode 100644 index 0000000000..e340a061f5 --- /dev/null +++ b/pipo/src/org/adempiere/pipo2/PackOut.java @@ -0,0 +1,472 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * * + * Copyright (C) * + * 2004 Robert KLEIN. robeklein@hotmail.com * + * Contributor(s): Low Heng Sin hengsin@avantz.com * + * Teo Sarca teo.sarca@arhipac.ro, SC ARHIPAC SERVICE SRL * + *****************************************************************************/ +package org.adempiere.pipo2; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.UnsupportedEncodingException; +import java.util.List; +import java.util.Properties; +import java.util.logging.Level; + +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.sax.SAXTransformerFactory; +import javax.xml.transform.sax.TransformerHandler; +import javax.xml.transform.stream.StreamResult; + +import org.compiere.model.I_AD_Form; +import org.compiere.model.I_AD_ImpFormat; +import org.compiere.model.I_AD_Menu; +import org.compiere.model.I_AD_Message; +import org.compiere.model.I_AD_PrintFormat; +import org.compiere.model.I_AD_Process; +import org.compiere.model.I_AD_Reference; +import org.compiere.model.I_AD_ReportView; +import org.compiere.model.I_AD_Role; +import org.compiere.model.I_AD_Table; +import org.compiere.model.I_AD_Val_Rule; +import org.compiere.model.I_AD_Window; +import org.compiere.model.I_AD_Workflow; +import org.compiere.model.MClient; +import org.compiere.model.MPackageExp; +import org.compiere.model.MPackageExpDetail; +import org.compiere.model.MTable; +import org.compiere.model.Query; +import org.compiere.model.X_AD_Package_Exp_Detail; +import org.compiere.process.SvrProcess; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +import org.adempiere.exceptions.AdempiereException; + +/** + * Convert AD to XML + * + * @author Robert Klein + * @version $Id: PackOut.java,v 1.0 + * + * Contributor: William G. Heath - Export of workflows and dynamic validations + * + * @author Teo Sarca, SC ARHIPAC SERVICE SRL + *
  • BF [ 1819315 ] PackOut: fix xml indentation not working + *
  • BF [ 1819319 ] PackOut: use just active AD_Package_Exp_Detail lines + */ + +public class PackOut extends SvrProcess +{ + private static final String TRX_NAME_CTX_KEY = "TrxName"; + public static final String PACK_OUT_PROCESS_CTX_KEY = "PackOutProcess"; + /** Record ID */ + private int p_PackOut_ID = 0; + private String PackOutVer = "005"; + + private Properties localContext = null; + private MPackageExp packageExp; + private MPackageExpDetail packageExpDetail; + private String packOutDir; + private String packageDir; + private int blobCount = 0; + + private IHandlerRegistry handlerRegistry = null; + + public static final int MAX_OFFICIAL_ID = MTable.MAX_OFFICIAL_ID; + + /** + * Prepare - e.g., get Parameters. + */ + protected void prepare() + { + p_PackOut_ID = getRecord_ID(); + } // prepare + + public static void addTextElement(TransformerHandler handler, String qName, String text, AttributesImpl atts) throws SAXException { + handler.startElement("", "", qName, atts); + append(handler, text); + handler.endElement("", "", qName); + } + + private static void append(TransformerHandler handler, String str) throws SAXException + { + char[] contents = str != null ? str.toCharArray() : new char[0]; + handler.characters(contents,0,contents.length); + } + + /** + * Start the transformation to XML + * @return info + * @throws Exception + */ + + protected String doIt() throws java.lang.Exception + { + initContext(); + + handlerRegistry = new OSGiHandlerRegistry(); + + OutputStream packageDocStream = null; + OutputStream packOutDocStream = null; + log.info("doIt - AD_PACKAGE_EXP_ID=" + p_PackOut_ID); + + if (p_PackOut_ID == 0) + throw new IllegalArgumentException("No Record"); + + int processedCount = 0; + try { + + packageExp = new MPackageExp(getCtx(), p_PackOut_ID, get_TrxName()); + + if (packageExp.getAD_Package_Exp_ID() == p_PackOut_ID){ + //Create the package documentation + packOutDir = packageExp.getFile_Directory().trim(); + if (!packOutDir.endsWith("/") && !packOutDir.endsWith("\\")) + packOutDir+= File.separator; + packageDir = packOutDir+ packageExp.getName(); + File packageDocDirFile = new File(packageDir+File.separator+"doc"+File.separator); + if (!packageDocDirFile.exists()) { + boolean success = packageDocDirFile.mkdirs(); + if (!success) { + throw new AdempiereException("Failed to create directory for pack out. " + packageDir+File.separator+"doc"+File.separator); + } + } + String docFileName = packageDir+File.separator+"doc"+File.separator+packageExp.getName()+"Doc.xml"; + packageDocStream = new FileOutputStream (docFileName, false); + TransformerHandler packageDocument = createPackageDoc(packageExp, packageDocStream); + + String packOutFileName = packageDir+File.separator+ "dict"+File.separator+"PackOut.xml"; + packOutDocStream = new FileOutputStream (packOutFileName, false); + TransformerHandler packOutDocument = createPackOutDoc(packageExp, packOutDocStream); + + Query query = new Query(getCtx(), MTable.get(getCtx(), X_AD_Package_Exp_Detail.Table_ID), "AD_Package_Exp_ID = ?", get_TrxName()); + List packageExpDetails = query.setOnlyActiveRecords(true) + .setOrderBy("Line") + .setParameters(new Object[]{p_PackOut_ID}) + .list(); + for(MPackageExpDetail dtl : packageExpDetails){ + packageExpDetail = dtl; + String type = packageExpDetail.getType(); + log.info(Integer.toString(packageExpDetail.getLine())); + + ElementHandler handler = handlerRegistry.getHandler(getTypeName(type)); + if (handler != null) + handler.packOut(this,packOutDocument,packageDocument,dtl.getExpRecordId()); + else + throw new IllegalArgumentException("Packout handler not found for type " + type); + + processedCount++; + } + + packOutDocument.endElement("","","adempiereAD"); + packOutDocument.endDocument(); + packageDocument.endElement("","","adempiereDocument"); + packageDocument.endDocument(); + + } + } + catch (Exception e) + { + log.log(Level.SEVERE,e.getLocalizedMessage(), e); + throw e; + } + finally + { + // Close streams - teo_sarca [ 1704762 ] + if (packageDocStream != null) + try { + packageDocStream.close(); + } catch (Exception e) {} + if (packOutDocStream != null) + try { + packOutDocStream.close(); + } catch (Exception e) {} + } + + //create compressed packages + //set the files + File srcFolder = new File(packOutDir); + File destZipFile = new File(packageDir+".zip"); + + //delete the old packages if necessary + destZipFile.delete(); + + //create the compressed packages + String includesdir = packageExp.getName() + File.separator +"**"; + Zipper.zipFolder(srcFolder, destZipFile, includesdir); + + return "Exported="+processedCount + " File=" + destZipFile.getAbsolutePath(); + } // doIt + + private TransformerHandler createPackOutDoc(MPackageExp packageExp, + OutputStream packOutDocStream) throws UnsupportedEncodingException, TransformerConfigurationException, SAXException { + StreamResult packOutStreamResult = new StreamResult(new OutputStreamWriter(packOutDocStream,"utf-8")); + SAXTransformerFactory packOutFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); + packOutFactory.setAttribute("indent-number", new Integer(4)); + TransformerHandler packOutDocument = packOutFactory.newTransformerHandler(); + Transformer packOutTransformer = packOutDocument.getTransformer(); + packOutTransformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1"); + packOutTransformer.setOutputProperty(OutputKeys.INDENT,"yes"); + packOutDocument.setResult(packOutStreamResult); + packOutDocument.startDocument(); + AttributesImpl atts = new AttributesImpl(); + atts.addAttribute("","","Name","CDATA",packageExp.getName()); + atts.addAttribute("","","Version","CDATA",packageExp.getPK_Version()); + atts.addAttribute("","","AdempiereVersion","CDATA",packageExp.getReleaseNo()); + atts.addAttribute("","","DataBase","CDATA",packageExp.getVersion()); + atts.addAttribute("","","Description","CDATA",packageExp.getDescription()); + atts.addAttribute("","","Creator","CDATA",packageExp.getUserName()); + atts.addAttribute("","","CreatorContact","CDATA",packageExp.getEMail()); + atts.addAttribute("","","CreatedDate","CDATA",packageExp.getCreated().toString()); + atts.addAttribute("","","UpdatedDate","CDATA",packageExp.getUpdated().toString()); + atts.addAttribute("","","PackOutVersion","CDATA",PackOutVer); + + MClient client = MClient.get(localContext); + StringBuffer sb = new StringBuffer () + .append(client.get_ID()) + .append("-") + .append(client.getValue()) + .append("-") + .append(client.getName()); + atts.addAttribute("", "", "Client", "CDATA", sb.toString()); + + packOutDocument.startElement("","","adempiereAD",atts); + return packOutDocument; + } + + private TransformerHandler createPackageDoc(MPackageExp packageExp, OutputStream packageDocStream) throws UnsupportedEncodingException, TransformerConfigurationException, SAXException { + StreamResult docStreamResult = new StreamResult(new OutputStreamWriter(packageDocStream,"utf-8")); + SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); + transformerFactory.setAttribute("indent-number", new Integer(4)); + TransformerHandler packageDocument = transformerFactory.newTransformerHandler(); + Transformer transformer = packageDocument.getTransformer(); + transformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1"); + transformer.setOutputProperty(OutputKeys.INDENT,"yes"); + packageDocument.setResult(docStreamResult); + packageDocument.startDocument(); + packageDocument.processingInstruction("xml-stylesheet","type=\"text/css\" href=\"adempiereDocument.css\""); + AttributesImpl atts = new AttributesImpl(); + packageDocument.startElement("","","adempiereDocument",atts); + addTextElement(packageDocument, "header", packageExp.getName()+" Package Description", atts); + addTextElement(packageDocument, "H1", "Package Name:", atts); + addTextElement(packageDocument, "packagename", packageExp.getName(), atts); + addTextElement(packageDocument, "H1", "Author:", atts); + addTextElement(packageDocument, "creator", packageExp.getUserName(), atts); + addTextElement(packageDocument, "H1", "Email Address:", atts); + addTextElement(packageDocument, "creatorcontact", packageExp.getEMail(), atts); + addTextElement(packageDocument, "H1", "Created:", atts); + addTextElement(packageDocument, "createddate", packageExp.getCreated().toString(), atts); + addTextElement(packageDocument, "H1", "Updated:", atts); + addTextElement(packageDocument, "updateddate", packageExp.getUpdated().toString(), atts); + addTextElement(packageDocument, "H1", "Description:", atts); + addTextElement(packageDocument, "description", packageExp.getDescription(), atts); + addTextElement(packageDocument, "H1", "Instructions:", atts); + addTextElement(packageDocument, "instructions", packageExp.getInstructions(), atts); + addTextElement(packageDocument, "H1", "Files in Package:", atts); + addTextElement(packageDocument, "file", "File: PackOut.xml", atts); + addTextElement(packageDocument, "filedirectory", "Directory: \\dict\\", atts); + addTextElement(packageDocument, "filenotes", "Notes: Contains all application/object settings for package", atts); + + MClient client = MClient.get(localContext); + StringBuffer sb = new StringBuffer () + .append(client.get_ID()) + .append("-") + .append(client.getValue()) + .append("-") + .append(client.getName()); + addTextElement(packageDocument, "H1", "Client:", atts); + addTextElement(packageDocument, "Client", sb.toString(), atts); + + File packageDictDirFile = new File(packageDir+File.separator+ "dict"+File.separator); + if (!packageDictDirFile.exists()) { + boolean success = packageDictDirFile.mkdirs(); + if (!success) + throw new AdempiereException("Failed to create directory. " + packageDir+File.separator+ "dict"+File.separator); + } + return packageDocument; + } + + private String getTypeName(String type) { + if (X_AD_Package_Exp_Detail.TYPE_ApplicationOrModule.equals(type)) + return I_AD_Menu.Table_Name; + else if (X_AD_Package_Exp_Detail.TYPE_CodeSnipit.equals(type)) + return "Code_Snipit"; + else if (X_AD_Package_Exp_Detail.TYPE_Data.equals(type)) + return IHandlerRegistry.TABLE_GENERIC_HANDLER; + else if (X_AD_Package_Exp_Detail.TYPE_DynamicValidationRule.equals(type)) + return I_AD_Val_Rule.Table_Name; + else if (X_AD_Package_Exp_Detail.TYPE_File_CodeOrOther.equals(type)) + return "Dist_File"; + else if (X_AD_Package_Exp_Detail.TYPE_Form.equals(type)) + return I_AD_Form.Table_Name; + else if (X_AD_Package_Exp_Detail.TYPE_ImportFormat.equals(type)) + return I_AD_ImpFormat.Table_Name; + else if (X_AD_Package_Exp_Detail.TYPE_Message.equals(type)) + return I_AD_Message.Table_Name; + else if (X_AD_Package_Exp_Detail.TYPE_PrintFormat.equals(type)) + return I_AD_PrintFormat.Table_Name; + else if (X_AD_Package_Exp_Detail.TYPE_ProcessReport.equals(type)) + return I_AD_Process.Table_Name; + else if (X_AD_Package_Exp_Detail.TYPE_Reference.equals(type)) + return I_AD_Reference.Table_Name; + else if (X_AD_Package_Exp_Detail.TYPE_ReportView.equals(type)) + return I_AD_ReportView.Table_Name; + else if (X_AD_Package_Exp_Detail.TYPE_Role.equals(type)) + return I_AD_Role.Table_Name; + else if (X_AD_Package_Exp_Detail.TYPE_SQLStatement.equals(type)) + return "SQL_Statement"; + else if (X_AD_Package_Exp_Detail.TYPE_Table.equals(type)) + return I_AD_Table.Table_Name; + else if (X_AD_Package_Exp_Detail.TYPE_Window.equals(type)) + return I_AD_Window.Table_Name; + else if (X_AD_Package_Exp_Detail.TYPE_Workflow.equals(type)) + return I_AD_Workflow.Table_Name; + + return type; + } + + private void initContext() { + Properties tmp = new Properties(); + if (getCtx() != null) + tmp.putAll(getCtx()); + tmp.put(TRX_NAME_CTX_KEY, get_TrxName()); + tmp.put(PACK_OUT_PROCESS_CTX_KEY, this); + localContext = tmp; + } + + /** + * @param sourceName + * @param destName + */ + public void copyFile (String sourceName, String destName ) { + InputStream source = null; // Stream for reading from the source file. + OutputStream copy= null; // Stream for writing the copy. + boolean force; // This is set to true if the "-f" option + // is specified on the command line. + int byteCount; // Number of bytes copied from the source file. + + force = true; + try { + source = new FileInputStream(sourceName); + } catch (FileNotFoundException e) { + System.out.println("Can't find file \"" + sourceName + "\"."); + return; + } + + try { + File file = new File(destName); + if (file.exists() && force == false) { + System.out.println("Output file exists. Use the -f option to replace it."); + return; + } + try { + copy = new FileOutputStream(destName, false); + } catch (IOException e) { + System.out.println("Can't open output file \"" + + destName + "\"."); + return; + } + byteCount = 0; + try { + while (true) { + int data = source.read(); + if (data < 0) + break; + copy.write(data); + byteCount++; + } + source.close(); + copy.close(); + System.out.println("Successfully copied " + byteCount + " bytes."); + } catch (Exception e) { + System.out.println("Error occurred while copying. "+ byteCount + " bytes copied."); + System.out.println(e.toString()); + } + } finally { + if (source != null) { + try { + source.close(); + } catch (IOException e) {} + } + if (copy != null) { + try { + copy.close(); + } catch (IOException e) {} + } + } + } + + @Override + public Properties getCtx() { + return localContext != null ? localContext : super.getCtx(); + } + + /** + * @param data + * @return + * @throws IOException + */ + public String writeBlob(byte[] data) throws IOException { + blobCount++; + String fileName = blobCount + ".dat"; + File path = new File(packageDir+File.separator+"blobs"+File.separator); + path.mkdirs(); + File file = new File(path, fileName); + FileOutputStream os = null; + try { + os = new FileOutputStream(file); + os.write(data); + os.flush(); + } finally { + if (os != null) { + try { + os.close(); + } catch (IOException e) {} + } + } + return fileName; + } + + /** + * @return MPackageExp + */ + public MPackageExp getPackageExp() { + return packageExp; + } + + /** + * @return MPackageExpDetail + */ + public MPackageExpDetail getPackageExpDetail() { + return packageExpDetail; + } + + /** + * @param name + * @return ElementHandler + */ + public ElementHandler getHandler(String name) { + return handlerRegistry.getHandler(name); + } +} // PackOut diff --git a/pipo/src/org/adempiere/pipo2/PackRoll.java b/pipo/src/org/adempiere/pipo2/PackRoll.java new file mode 100644 index 0000000000..5ad6cebbb1 --- /dev/null +++ b/pipo/src/org/adempiere/pipo2/PackRoll.java @@ -0,0 +1,423 @@ + +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Carlos Ruiz - globalqss + *****************************************************************************/ +package org.adempiere.pipo2; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.List; +import java.util.logging.Level; + +import org.compiere.model.MTable; +import org.compiere.model.Query; +import org.compiere.model.X_AD_Package_Imp_Backup; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.process.ProcessInfoParameter; +import org.compiere.process.SvrProcess; +import org.compiere.util.DB; +import org.compiere.util.Env; + +/** + * Reverse Package Install. + * + * @author Robert Klein + * + */ +public class PackRoll extends SvrProcess { + /** Package from Record */ + private int m_AD_Package_Imp_ID = 0; + private String m_Processing = null; + StringBuffer sql = null; + StringBuffer sqlB = null; + String columnIDName = null; + StringBuffer sqlC = null; + StringBuffer sqlD = null; + + /** + * Prepare - e.g., get Parameters. + */ + protected void prepare() { + ProcessInfoParameter[] para = getParameter(); + for (int i = 0; i < para.length; i++) { + String name = para[i].getParameterName(); + if (para[i].getParameter() == null) + ; + else if (name.equals("Processing")) + m_Processing = (String) para[i].getParameter(); + else + log.log(Level.SEVERE, "prepare - Unknown Parameter: " + name); + } + m_AD_Package_Imp_ID = getRecord_ID(); + } // prepare + + /** + * Perform process. + * + * @return Message (translated text) + * @throws Exception + * if not successful + */ + protected String doIt() throws Exception + { + + DB.executeUpdateEx("UPDATE AD_Package_Imp SET PK_Status = 'Uninstalling' WHERE AD_Package_Imp_ID = ?", new Object[]{m_AD_Package_Imp_ID}, get_TrxName()); + + log.info("Starting Package Reversal"); + // select all records that are new or have been updated by package + // install + try { + Query query = new Query(getCtx(), X_AD_Package_Imp_Detail.Table_Name, "AD_Package_Imp_ID=?", get_TrxName()); + List packageImpDetails = query.setParameters(new Object[]{m_AD_Package_Imp_ID}).list(); + for (X_AD_Package_Imp_Detail packageImpDetail : packageImpDetails) { + + if (packageImpDetail.getType().equals("file")) { + + Query query2 = new Query(getCtx(), X_AD_Package_Imp_Backup.Table_Name, "AD_Package_Imp_Detail_ID=? AND AD_Package_Imp_ID=?", get_TrxName()); + List backups = query2.setParameters(new Object[]{packageImpDetail.getAD_Package_Imp_Detail_ID(), packageImpDetail.getAD_Package_Imp_ID()}).list(); + + for (X_AD_Package_Imp_Backup backup : backups) { + if (backup.getAD_Package_Imp_Bck_Dir() != null + && backup.getAD_Package_Imp_Org_Dir() != null) { + copyFile(backup.getAD_Package_Imp_Bck_Dir(),backup.getAD_Package_Imp_Org_Dir()); + } + + // Update uninstall field for column + backup.setUninstall(true); + backup.saveEx(); + + // Update uninstall field for record + packageImpDetail.setUninstall(true); + packageImpDetail.saveEx(); + } + + } else { + + String tableName = packageImpDetail.getTableName(); + + int recordID = packageImpDetail.getAD_Original_ID(); + + // determine if record is an update to the original + // if record is an update then update record with backup + // settings + // else inactivate record + if (packageImpDetail.getAction().equalsIgnoreCase("update")) { + // select all backed up columns for the record + + try { + Query query2 = new Query(getCtx(), X_AD_Package_Imp_Backup.Table_Name, "AD_Package_Imp_Detail_ID=? AND AD_Package_Imp_ID=?", get_TrxName()); + List backups = query2.setParameters(new Object[]{packageImpDetail.getAD_Package_Imp_Detail_ID(), packageImpDetail.getAD_Package_Imp_ID()}).list(); + + String IsKey = null; + String columnName = null; + + for (X_AD_Package_Imp_Backup backup : backups) { + + PreparedStatement pstmt =null; + ResultSet rs=null; + try { + pstmt = DB.prepareStatement("SELECT IsKey,ColumnName FROM AD_Column WHERE AD_Column_ID = ?",get_TrxName()); + pstmt.setInt(1,backup.getAD_Column_ID()); + rs = pstmt.executeQuery(); + if(rs.next()) + { + IsKey = rs.getString(1); + columnName = rs.getString(2); + } + } finally { + DB.close(rs, pstmt); + } + // Get Table value + tableName = MTable.getTableName(getCtx(), backup.getAD_Table_ID()); + + // Get Column Name + // Adjust for Column reference table + if (tableName.equals("AD_Ref_Table")) + { + columnIDName = "AD_Reference_ID"; + } + else if (tableName.equals("AD_TreeNodeMM")) + { + columnIDName = "Node_ID"; + } + else + { + columnIDName = tableName + "_ID"; + } + + // Update columns for record + // TODO make process more efficient! + + if (IsKey.equals("Y") + || columnName.startsWith("Created")) + ; // ignore is a Key Column or if it + // references a Created(By) Column + // Update "Updated" field with current date + else if (columnName.equals("Updated")) + { + // Format Date + sqlC = new StringBuffer("UPDATE " + + tableName + " SET " + columnName + + " = SYSDATE WHERE " + + columnIDName + " = " + recordID); + + DB.executeUpdateEx(sqlC.toString(), get_TrxName()); + // Update uninstall field + backup.setUninstall(true); + backup.saveEx(); + } + // Update "UpdatedBy" field with current user + else if (columnName.equals("UpdatedBy")) { + + sqlC = new StringBuffer("UPDATE " + + tableName + " SET " + columnName + + " = '" + + Env.getAD_User_ID(Env.getCtx()) + + "' WHERE " + columnIDName + " = " + + recordID); + DB.executeUpdateEx(sqlC.toString(), get_TrxName()); + backup.setUninstall(true); + backup.saveEx(); + } + // Update all other fields with backup + // information + else { + Object[] parameters = null; + int v_AD_Reference_ID = backup.getAD_Reference_ID(); + // Update columns that are Strings adjusting + // for single quotes + if (v_AD_Reference_ID == 10 + || v_AD_Reference_ID == 14 + || v_AD_Reference_ID == 34 + || v_AD_Reference_ID == 17 + // Carlos Ruiz globalqss, special + // treatment for EntityType + // it's a Table reference but must + // be treated as String + || (v_AD_Reference_ID == 18 && columnName + .equalsIgnoreCase("EntityType"))) { + if (backup.getColValue().toString().equals("null")) { + ;// Ignore null values + } else { + sqlC = new StringBuffer("UPDATE " + + tableName + + " SET " + + columnName + + " = ?" + + " WHERE " + columnIDName + + " = " + recordID); + parameters = new Object[]{backup.getColValue()}; + } + // Update true/false columns + } else if (v_AD_Reference_ID == 20 + || v_AD_Reference_ID == 28) { + + sqlC = new StringBuffer("UPDATE " + + tableName + + " SET " + + columnName + + " = ? " + + " WHERE " + + columnIDName + " = " + + recordID); + parameters = new Object[]{backup.getColValue().equals("true") ? "Y" : "N"}; + } + // Update columns that are Strings adjusting + // for single quotes + else if (v_AD_Reference_ID == 13 + || v_AD_Reference_ID == 18 + || v_AD_Reference_ID == 19 + || v_AD_Reference_ID == 21 + || v_AD_Reference_ID == 25 + || v_AD_Reference_ID == 27 + || v_AD_Reference_ID == 30 + || v_AD_Reference_ID == 31 + || v_AD_Reference_ID == 35) + { + + sqlC = new StringBuffer("UPDATE " + + tableName + + " SET " + + columnName + + " = ?" + + " WHERE " + columnIDName + + " = " + recordID); + parameters = new Object[]{backup.getColValue()}; + } + // Update columns that are numbers + else if (v_AD_Reference_ID == 11 + || v_AD_Reference_ID == 12 + || v_AD_Reference_ID == 22 + || v_AD_Reference_ID == 29) + { + sqlC = new StringBuffer("UPDATE " + + tableName + + " SET " + + columnName + + " = ?" + + " WHERE " + columnIDName + + " = " + recordID); + parameters = new Object[]{backup.getColValue()}; + } + // Update columns that are dates + else if (v_AD_Reference_ID == 15 + || v_AD_Reference_ID == 16) + // TODO Develop portable code to update + // date columns + ;// ignore + else + // 23-Binary, 24-Radio, 26-RowID, + // 32-Image not supported + ;// ignore + // execute update + + if(sqlC!=null) + { + DB.executeUpdateEx(sqlC.toString(), parameters, get_TrxName()); + } + + // Update uninstall field for column + backup.setUninstall(true); + backup.saveEx(); + + // Update uninstall field for record + packageImpDetail.setUninstall(true); + packageImpDetail.saveEx(); + } + } + + } catch (Exception e) { + log.log(Level.SEVERE, "doIt", e); + //System.exit(0); + } + } // ********* Update Loop + // Inactivate new records + else if (packageImpDetail.getAction().equalsIgnoreCase("new")) { + if (tableName.equals("AD_Ref_Table")) + columnIDName = "AD_Reference_ID"; + else if (tableName.equals("AD_TreeNodeMM")) + columnIDName = "Node_ID"; + else + columnIDName = tableName + "_ID"; + sqlC=new StringBuffer(" UPDATE ") + .append(tableName) + .append(" SET IsActive = 'N' WHERE ") + .append(columnIDName) + .append(" = ? "); + DB.executeUpdateEx(sqlC.toString(), new Object[]{recordID}, get_TrxName()); + + // Update uninstall field for record + packageImpDetail.setUninstall(true); + packageImpDetail.saveEx(); + } + } + + } + } catch (Exception e) { + log.log(Level.SEVERE, "doIt", e); + } + + // Update uninstall field for package + DB.executeUpdateEx("UPDATE AD_Package_Imp SET Uninstall = 'Y', PK_Status = 'Uninstalled' WHERE AD_Package_Imp_ID = ?", new Object[]{m_AD_Package_Imp_ID}, get_TrxName()); + + log.info("Package Reversal Completed"); + return ""; + } // doIt + + /** + * Open input file for processing + * + * @param String + * file with path + * + */ + public FileInputStream OpenInputfile(String filePath) { + + FileInputStream fileTarget = null; + + try { + fileTarget = new FileInputStream(filePath); + } catch (FileNotFoundException e) { + System.out.println("Can't find file "); + + return null; + } + return fileTarget; + } + + /** + * Open output file for processing + * + * @param String + * file with path + * + */ + public OutputStream OpenOutputfile(String filePath) { + + OutputStream fileTarget = null; + + try { + fileTarget = new FileOutputStream(filePath); + } catch (FileNotFoundException e) { + System.out.println("Can't find file "); + + return null; + } + return fileTarget; + } + + /** + * Copyfile + * + * @param String + * file with path + * + */ + public int copyFile(String sourceFile, String targetFile) { + + OutputStream target = OpenOutputfile(targetFile); + InputStream source = OpenInputfile(sourceFile); + + int byteCount = 0; + int success = 0; + try { + while (true) { + int data = source.read(); + if (data < 0) + break; + target.write(data); + byteCount++; + } + source.close(); + target.close(); + + System.out.println("Successfully copied " + byteCount + " bytes."); + } catch (Exception e) { + System.out.println("Error occurred while copying. " + byteCount + + " bytes copied."); + System.out.println(e.toString()); + + success = -1; + } + return success; + } + +} // PackRoll diff --git a/pipo/src/org/adempiere/pipo2/PoExporter.java b/pipo/src/org/adempiere/pipo2/PoExporter.java new file mode 100644 index 0000000000..2af7887451 --- /dev/null +++ b/pipo/src/org/adempiere/pipo2/PoExporter.java @@ -0,0 +1,321 @@ +package org.adempiere.pipo2; + +import java.math.BigDecimal; +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.exceptions.AdempiereException; +import org.compiere.model.I_AD_Client; +import org.compiere.model.I_AD_Org; +import org.compiere.model.MTable; +import org.compiere.model.PO; +import org.compiere.model.POInfo; +import org.compiere.util.CLogger; +import org.compiere.util.DisplayType; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class PoExporter { + + private PO po = null; + + @SuppressWarnings("unused") + private CLogger log = CLogger.getCLogger(getClass()); + private Properties ctx; + + private TransformerHandler transformerHandler; + + private void addTextElement(String qName, String text, AttributesImpl atts) { + try { + transformerHandler.startElement("", "", qName, atts); + append(text); + transformerHandler.endElement("", "", qName); + } catch (SAXException e) { + throw new RuntimeException(e); + } + } + + private void append(String str) throws SAXException + { + char[] contents = str != null ? str.toCharArray() : new char[0]; + transformerHandler.characters(contents,0,contents.length); + } + + /** + * @param ctx + * @param po + */ + public PoExporter(Properties ctx, TransformerHandler handler, PO po){ + this.ctx = ctx; + this.po = po; + transformerHandler = handler; + } + + /** + * + * @param name + * @param value + */ + public void addUnchecked(String name, String value, AttributesImpl atts){ + addTextElement(name, value, atts); + } + + /** + * + * @param name + * @param stringValue + * @param atts + */ + public void addString(String name, String stringValue, AttributesImpl atts){ + addString(name, stringValue, "", atts); + } + + /** + * + * @param name + * @param defaultValue + * @param stringValue + */ + public void addString(String name, String stringValue, String defaultValue, AttributesImpl atts){ + addTextElement(name, stringValue != null ? stringValue : defaultValue, atts); + } + + /** + * + * @param name + * @param boolValue + */ + public void addBoolean(String name, boolean boolValue, AttributesImpl atts){ + addTextElement(name, boolValue == true ? "true" : "false", atts); + } + + + /** + * + * @param name + * @param columnName + */ + public void add(String columnName, AttributesImpl atts) { + add(columnName, "", atts); + } + + /** + * + * @param name + * @param columnName + * @param defaultValue + */ + public void add(String columnName, String defaultValue, AttributesImpl atts) { + Object value = po.get_Value(columnName); + + if(value == null){ + addTextElement(columnName, defaultValue, atts); + return; + } + + if(value instanceof String){ + addTextElement(columnName, (String)value, atts); + } else if(value instanceof Boolean) { + addTextElement(columnName, (Boolean)value == true ? "true" : "false", atts); + } else if(value instanceof Integer) { + addTextElement(columnName, value.toString(), atts); + } else if(value instanceof BigDecimal) { + addTextElement(columnName, value.toString(), atts); + } else{ + addTextElement(columnName, value.toString(), atts); + } + } + + /** + * @param columnName + * @param defaultValue + */ + public void add(String columnName, boolean defaultValue, AttributesImpl atts) { + Object oo = po.get_Value(columnName); + boolean value = defaultValue; + if (oo != null) + { + if (oo instanceof Boolean) + value = ((Boolean)oo).booleanValue(); + else + value = "Y".equals(oo); + } + addBoolean(columnName, value, atts); + } + + /** + * + * + */ + public void addIsActive(AttributesImpl atts){ + addTextElement("IsActive", (Boolean)po.isActive() == true ? "true" : "false", atts); + } + + public void addTableReference(String tableName, String searchColumn, AttributesImpl atts) { + String columnName = tableName + "_ID"; + addTableReference(columnName, tableName, searchColumn, atts); + } + + public void addTableReference(String columnName, String tableName, String searchColumn, AttributesImpl atts) { + int id = po.get_Value(columnName) != null ? (Integer)po.get_Value(columnName) : 0; + addTableReference(columnName, tableName, searchColumn, id, atts); + } + + public void addTableReference(String columnName, String tableName, String searchColumn, int id, AttributesImpl atts) { + String value = ReferenceUtils.getTableReference(tableName, searchColumn, id, atts); + addString(columnName, value, atts); + } + + public void export(List excludes) { + export(excludes, false); + } + + public void export(List excludes, boolean preservedOrg) { + POInfo info = POInfo.getPOInfo(po.getCtx(), po.get_Table_ID()); + int count = info.getColumnCount(); + //special treatment for ad_org_id + int AD_Client_ID = po.getAD_Client_ID(); + if (AD_Client_ID == 0) + { + addString("AD_Org_ID", "0", new AttributesImpl()); + } + else + { + int AD_Org_ID = po.getAD_Org_ID(); + if (AD_Org_ID == 0) + { + addString("AD_Org_ID", "0", new AttributesImpl()); + } + else + { + if (!preservedOrg) + addString("AD_Org_ID", "@AD_Org_ID@", new AttributesImpl()); + else { + addTableReference(I_AD_Client.Table_Name, I_AD_Client.COLUMNNAME_Value, new AttributesImpl()); + addTableReference(I_AD_Org.Table_Name, I_AD_Org.COLUMNNAME_Value, new AttributesImpl()); + } + } + } + + for(int i = 0; i < count; i++) { + String columnName = info.getColumnName(i); + if (excludes != null) { + boolean exclude = false; + for(String ex : excludes) + { + if (ex.equalsIgnoreCase(columnName)) + { + exclude = true; + break; + } + } + if (exclude) + continue; + } + + int displayType = info.getColumnDisplayType(i); + if (DisplayType.YesNo == displayType) { + add(columnName, false, new AttributesImpl()); + } else if (DisplayType.TableDir == displayType || DisplayType.ID == displayType) { + String tableName = null; + String searchColumn = null; + if ("Record_ID".equalsIgnoreCase(columnName) && po.get_ColumnIndex("AD_Table_ID") >= 0) { + int AD_Table_ID = po.get_Value(po.get_ColumnIndex("AD_Table_ID")) != null + ? (Integer)po.get_Value(po.get_ColumnIndex("AD_Table_ID")) : 0; + tableName = MTable.getTableName(ctx, AD_Table_ID); + searchColumn = tableName + "_ID"; + } else { + //remove _ID + searchColumn = columnName; + tableName = columnName.substring(0, columnName.length() - 3); + if (tableName.equalsIgnoreCase("ad_table")) { + searchColumn = "TableName"; + } else if (tableName.equalsIgnoreCase("ad_column")) { + searchColumn = "ColumnName"; + } + } + if (searchColumn.endsWith("_ID")) { + int AD_Table_ID = MTable.getTable_ID(tableName); + POInfo pInfo = POInfo.getPOInfo(po.getCtx(), AD_Table_ID); + if (pInfo.getColumnIndex("Value") >= 0) { + searchColumn = "Value"; + } else if (pInfo.getColumnIndex("Name") >= 0) { + searchColumn = "Name"; + } else if (pInfo.getColumnIndex("DocumentNo") >= 0) { + searchColumn = "DocumentNo"; + } + } + addTableReference(columnName, tableName, searchColumn, new AttributesImpl()); + } else if (DisplayType.List == displayType) { + add(columnName, "", new AttributesImpl()); + } else if (DisplayType.isLookup(displayType)) { + String searchColumn = null; + String tableName = null; + if ("Record_ID".equalsIgnoreCase(columnName) && po.get_ColumnIndex("AD_Table_ID") >= 0) { + int AD_Table_ID = po.get_Value(po.get_ColumnIndex("AD_Table_ID")) != null + ? (Integer)po.get_Value(po.get_ColumnIndex("AD_Table_ID")) : 0; + tableName = MTable.getTableName(ctx, AD_Table_ID); + searchColumn = tableName + "_ID"; + } else if (info.getColumnLookup(i) != null){ + searchColumn = info.getColumnLookup(i).getColumnName(); + tableName = searchColumn.substring(0, searchColumn.indexOf(".")); + searchColumn = searchColumn.substring(searchColumn.indexOf(".")+1); + } else { + searchColumn = columnName; + } + if (searchColumn.endsWith("_ID")) { + if (tableName.equalsIgnoreCase("ad_table")) { + searchColumn = "TableName"; + } else if (tableName.equalsIgnoreCase("ad_column")){ + searchColumn = "ColumnName"; + } else { + int AD_Table_ID = MTable.getTable_ID(tableName); + POInfo pInfo = POInfo.getPOInfo(po.getCtx(), AD_Table_ID); + if (pInfo.getColumnIndex("Value") >= 0) { + searchColumn = "Value"; + } else if (pInfo.getColumnIndex("Name") >= 0) { + searchColumn = "Name"; + } else if (pInfo.getColumnIndex("DocumentNo") >= 0) { + searchColumn = "DocumentNo"; + } + } + } + addTableReference(columnName, tableName, searchColumn, new AttributesImpl()); + } else if (DisplayType.isLOB(displayType)) { + addBlob(columnName); + } else { + add(columnName, "", new AttributesImpl()); + } + } + } + + public void addBlob(String columnName) { + Object value = po.get_Value(columnName); + if (value == null) { + addString(columnName, "", new AttributesImpl()); + return; + } + + PackOut packOut = (PackOut) ctx.get(PackOut.PACK_OUT_PROCESS_CTX_KEY); + byte[] data = null; + String dataType = null; + String fileName = null; + try { + if (value instanceof String) { + data = ((String)value).getBytes("UTF-8"); + dataType = "string"; + } else { + data = (byte[]) value; + dataType = "byte[]"; + } + + fileName = packOut.writeBlob(data); + } catch (Exception e) { + throw new AdempiereException(e.getLocalizedMessage(), e); + } + + addString(columnName, fileName + "|" + dataType, new AttributesImpl()); + } +} diff --git a/pipo/src/org/adempiere/pipo2/PoFiller.java b/pipo/src/org/adempiere/pipo2/PoFiller.java new file mode 100644 index 0000000000..4f3851739a --- /dev/null +++ b/pipo/src/org/adempiere/pipo2/PoFiller.java @@ -0,0 +1,251 @@ +package org.adempiere.pipo2; + +import java.io.IOException; +import java.math.BigDecimal; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import org.adempiere.exceptions.AdempiereException; +import org.compiere.model.PO; +import org.compiere.model.POInfo; +import org.compiere.util.DisplayType; +import org.compiere.util.Env; + +public class PoFiller{ + + PO po = null; + private AbstractElementHandler handler; + private Properties ctx; + private Element element; + + /** + * + * @param po + * @param atts + * @param handler + */ + public PoFiller(Properties ctx, PO po, Element element, AbstractElementHandler handler){ + + this.ctx = ctx; + this.po = po; + this.element = element; + this.handler = handler; + } + + /** + * + * @param columnName + */ + public void setString(String columnName){ + + Element e = element.properties.get(columnName); + String value = e != null ? e.contents.toString() : null; + + value = "".equals(value) ? null : value; + + po.set_ValueOfColumn(columnName, value); + } + + /** + * + * @param columnName + */ + public void setBoolean(String columnName){ + + Element e = element.properties.get(columnName); + String value = e != null ? e.contents.toString() : null; + + boolean bool = "true".equals(value) ? true : false; + + po.set_ValueOfColumn(columnName, bool); + } + + /** + * + * @param qName + */ + public void setTimestamp(String qName) { + Element e = element.properties.get(qName); + String value = e != null ? e.contents.toString() : null; + + if (value.trim().length() == 0) + value = null; + Timestamp ts = value != null ? Timestamp.valueOf(value) : null; + + po.set_ValueOfColumn(qName, ts); + } + + /** + * + * @param qName + */ + public void setInteger(String qName) { + Element e = element.properties.get(qName); + String value = e != null ? e.contents.toString() : null; + + if (value.trim().length() == 0) + value = null; + Integer i = value != null ? new Integer(value) : null; + + po.set_ValueOfColumn(qName, i); + } + + /** + * + * @param qName + */ + public void setBigDecimal(String qName) { + Element e = element.properties.get(qName); + String value = e != null ? e.contents.toString() : null; + + if (value.trim().length() == 0) + value = null; + BigDecimal bd = value != null ? new BigDecimal(value) : null; + + po.set_ValueOfColumn(qName, bd); + } + + public static int findTableReference(Properties ctx, AbstractElementHandler handler, Element element, String qName) { + Element propertyElement = element.properties.get(qName); + if (propertyElement == null) + return 0; + + int id = 0; + String value = propertyElement.contents.toString(); + if (value != null && value.trim().length() > 0) + { + String[] names = qName.split("[.]"); + if (names.length < 2) + return 0; + String columnName = names[0]; + if (names.length != 3) + columnName = columnName + "_ID"; + String tableName = names.length == 3 ? names[1] : names[0]; + String searchColumn = names.length == 3 ? names[2] : names[1]; + + id = handler.findIdByColumn(ctx, tableName, searchColumn, value.trim()); + } + return id; + } + + /** + * + * @param qName + */ + public int setTableReference(String qName) { + Element e = element.properties.get(qName); + if (e == null) + return 0; + + String value = e.contents.toString(); + String columnName = qName; + if (value != null && value.trim().length() > 0) { + int id = ReferenceUtils.resolveReference(ctx, e); + if (columnName.equals("AD_Client_ID") && id > 0) { + if (id != Env.getAD_Client_ID(ctx)) { + return -1; + } + } + if (po.get_ColumnIndex(columnName) >= 0) { + if (id > 0) { + po.set_ValueOfColumn(columnName, id); + return id; + } + return -1; + } else { + return 0; + } + } else { + return 0; + } + } + + /** + * process all attributes + * @param excludes list of attribute to exclude + */ + public List autoFill(List excludes) { + POInfo info = POInfo.getPOInfo(po.getCtx(), po.get_Table_ID()); + ListnotFounds = new ArrayList(); + + //special treatment for ad_org_id + Element orgElement = element.properties.get("AD_Org_ID"); + String sAD_Org_ID = orgElement != null ? orgElement.contents.toString() : null; + if (sAD_Org_ID != null && sAD_Org_ID.equals("0")) + po.setAD_Org_ID(0); + else if (sAD_Org_ID != null && sAD_Org_ID.equals("@AD_Org_ID@")) + po.setAD_Org_ID(Env.getAD_Org_ID(ctx)); + else { + if (setTableReference("AD_Client_ID") >= 0) + setTableReference("AD_Org_ID"); + } + + for(String qName : element.properties.keySet()) { + if (excludes != null ){ + boolean exclude = false; + for(String ex : excludes) + { + if (ex.equalsIgnoreCase(qName)) + { + exclude = true; + break; + } + } + if (exclude) + continue; + } + Element e = element.properties.get(qName); + if ("table".equalsIgnoreCase(e.attributes.getValue("reference"))) { + int id = setTableReference(qName); + if (id < 0) { + notFounds.add(qName); + } + } else { + int index = info.getColumnIndex(qName); + if (index < 0) + continue; + if (info.getColumnClass(index) == Boolean.class) { + setBoolean(qName); + } else if (info.getColumnClass(index) == BigDecimal.class){ + setBigDecimal(qName); + } else if (info.getColumnClass(index) == Integer.class) { + setInteger(qName); + } else if (info.getColumnClass(index) == Timestamp.class) { + setTimestamp(qName); + } else if (DisplayType.isLOB(info.getColumnDisplayType(index))) { + setBlob(qName); + } else { + setString(qName); + } + } + } + return notFounds; + } + + private void setBlob(String qName) { + Element pe = element.properties.get(qName); + String value = pe != null ? pe.contents.toString() : null; + Object data = null; + if (value != null && value.trim().length() > 0) { + String[] component = value.split("[|]"); + if (component.length == 2) { + String fileName = component[0]; + String dataType = component[1]; + PackIn packIn = handler.getPackInProcess(ctx); + try { + byte[] bytes = packIn.readBlob(fileName); + if ("byte[]".equals(dataType)) { + data = bytes; + } else { + data = new String(bytes, "UTF-8"); + } + } catch (IOException e) { + throw new AdempiereException(e.getLocalizedMessage(), e); + } + } + } + po.set_ValueOfColumn(qName, data); + } +} diff --git a/pipo/src/org/adempiere/pipo2/ReferenceUtils.java b/pipo/src/org/adempiere/pipo2/ReferenceUtils.java new file mode 100644 index 0000000000..cfa9c1ed04 --- /dev/null +++ b/pipo/src/org/adempiere/pipo2/ReferenceUtils.java @@ -0,0 +1,113 @@ +package org.adempiere.pipo2; + +import java.util.Properties; + +import org.compiere.model.MTable; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.xml.sax.helpers.AttributesImpl; + +public class ReferenceUtils { + + public static int resolveReference(Properties ctx, Element e) + { + String value = e.contents.toString(); + String referenceKey = e.attributes.getValue("reference-key"); + if (value != null && value.trim().length() > 0) + { + if (isTableLookup(e)) + { + String[] names = referenceKey.split("[.]"); + if (names.length < 2) + return 0; + String tableName = names[0]; + String searchColumn = names[1]; + + return IDFinder.findIdByColumn(tableName, searchColumn, value.trim(), Env.getAD_Client_ID(ctx), null); + } + else if (isIDLookup(e)) + { + int id = Integer.parseInt(value); + return id; + } + else if (isUUIDLookup(e)) + { + return IDFinder.findIdByColumn(referenceKey, referenceKey + "_UU", value.trim(), Env.getAD_Client_ID(ctx), null); + } + else + { + throw new IllegalArgumentException("Unknown table reference type="+e.attributes.getValue("reference")); + } + } + else + { + return 0; + } + } + + public static boolean isLookup(Element element) + { + if (isIDLookup(element) || isUUIDLookup(element) || isTableLookup(element)) + return true; + else + return false; + } + + public static boolean isIDLookup(Element element) + { + return "id".equals(element.properties.get("reference")); + } + + public static boolean isUUIDLookup(Element element) + { + return "uuid".equals(element.properties.get("reference")); + } + + public static boolean isTableLookup(Element element) + { + return "table".equals(element.properties.get("reference")); + } + + public static String getTableReference(String tableName, String searchColumn, int id, AttributesImpl atts) + { + String keyColumn = tableName + "_ID"; + String sql = "SELECT " + searchColumn + " FROM " + + tableName + " WHERE " + keyColumn + " = ?"; + if (id > 0 && id <= PackOut.MAX_OFFICIAL_ID) + { + atts.addAttribute("", "", "reference", "CDATA", "id"); + String value = Integer.toString(id); + return value; + } + else if (id == 0) + { + atts.addAttribute("", "", "reference", "CDATA", "id"); + return ""; + } + else + { + MTable table = MTable.get(Env.getCtx(), tableName); + if (table.get_ColumnIndex(tableName + "_UU") >= 0 ) + { + sql = "SELECT " + tableName + "_UU" + " FROM " + + tableName + " WHERE " + keyColumn + " = ?"; + String value = DB.getSQLValueString(null, sql, id); + if (value != null && value.trim().length() > 0) + { + atts.addAttribute("", "", "reference", "CDATA", "uuid"); + atts.addAttribute("", "", "reference-key", "CDATA", tableName); + return value.trim(); + } + } + + String value = DB.getSQLValueString(null, sql, id); + StringBuffer buffer = new StringBuffer(); + buffer.append(tableName).append(".").append(searchColumn); + atts.addAttribute("", "", "reference", "CDATA", "table"); + atts.addAttribute("", "", "reference-key", "CDATA", buffer.toString()); + return value; + } + } +} + + diff --git a/pipo/src/org/adempiere/pipo2/Zipper.java b/pipo/src/org/adempiere/pipo2/Zipper.java new file mode 100644 index 0000000000..be9ca8b5f8 --- /dev/null +++ b/pipo/src/org/adempiere/pipo2/Zipper.java @@ -0,0 +1,120 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * _____________________________________________ + *****************************************************************************/ +package org.adempiere.pipo2; + + +import java.io.File; +import java.io.IOException; +import java.util.Enumeration; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +import org.apache.tools.ant.Project; +import org.apache.tools.ant.Target; +import org.apache.tools.ant.taskdefs.Expand; +import org.apache.tools.ant.taskdefs.GZip; +import org.apache.tools.ant.taskdefs.Tar; +import org.apache.tools.ant.taskdefs.Zip; +/** + * Compress package + * + * @author Rob Klein + * @version $Id: ImportFAJournal2.java,v 1.0 $ + * + */ +public class Zipper { + + + /** + * Zip the srcFolder into the destFileZipFile. All the folder subtree of the src folder is added to the destZipFile + * archive. + * + * + * @param srcFolder File, the path of the srcFolder + * @param destZipFile File, the path of the destination zipFile. This file will be created or erased. + */ + static public void zipFolder(File srcFolder, File destZipFile, String includesdir) + { + Zip zipper = new Zip(); + zipper.setDestFile(destZipFile); + zipper.setBasedir(srcFolder); + zipper.setIncludes(includesdir.replace(" ", "*")); + zipper.setUpdate(true); + zipper.setCompress(true); + zipper.setCaseSensitive(false); + zipper.setFilesonly(false); + zipper.setTaskName("zip"); + zipper.setTaskType("zip"); + zipper.setProject(new Project()); + zipper.setOwningTarget(new Target()); + zipper.execute(); + System.out.println(destZipFile); + } + static public void tarFolder(File srcFolder, File destTarFile, String includesdir) + { + Tar tarer = new Tar(); + tarer.setDestFile(destTarFile); + tarer.setBasedir(srcFolder); + tarer.setIncludes(includesdir); + tarer.setCaseSensitive(false); + tarer.setTaskName("tar"); + tarer.setTaskType("tar"); + tarer.setProject(new Project()); + tarer.setOwningTarget(new Target()); + tarer.execute(); + } + static public void gzipFile(File srcFile, File destFile) + { + GZip GZiper = new GZip(); + GZiper.setDestfile(destFile); + GZiper.setSrc(srcFile); + GZiper.setTaskName("gzip"); + GZiper.setTaskType("gzip"); + GZiper.setProject(new Project()); + GZiper.setOwningTarget(new Target()); + GZiper.execute(); + } + static public void unpackFile(File zipFilepath, File destinationDir) + { + Expand Unzipper = new Expand(); + Unzipper.setDest(destinationDir); + Unzipper.setSrc(zipFilepath); + Unzipper.setTaskType ("unzip"); + Unzipper.setTaskName ("unzip"); + Unzipper.setProject(new Project()); + Unzipper.setOwningTarget(new Target()); + Unzipper.execute(); + } + static public String getParentDir(File zipFilepath) + { + try { + ZipFile zipFile = new ZipFile(zipFilepath); + Enumeration entries = zipFile.entries(); + ZipEntry entry = entries.nextElement(); + File tempfile = new File(entry.getName()); + while (tempfile.getParent()!=null) + tempfile = tempfile.getParentFile(); + return tempfile.getName(); + } catch (IOException ioe) { + System.err.println("Unhandled exception:"); + ioe.printStackTrace(); + return ""; + } + } + }// CreateZipFile + + diff --git a/pipo/src/org/adempiere/pipo2/exception/DatabaseAccessException.java b/pipo/src/org/adempiere/pipo2/exception/DatabaseAccessException.java new file mode 100644 index 0000000000..07269f5c4e --- /dev/null +++ b/pipo/src/org/adempiere/pipo2/exception/DatabaseAccessException.java @@ -0,0 +1,26 @@ +package org.adempiere.pipo2.exception; + +public class DatabaseAccessException extends RuntimeException { + + /** + * + */ + private static final long serialVersionUID = -8834711100842625706L; + + public DatabaseAccessException() { + super(); + } + + public DatabaseAccessException(String message, Throwable cause) { + super(message, cause); + } + + public DatabaseAccessException(String message) { + super(message); + } + + public DatabaseAccessException(Throwable cause) { + super(cause); + } + +} diff --git a/pipo/src/org/adempiere/pipo2/exception/POSaveFailedException.java b/pipo/src/org/adempiere/pipo2/exception/POSaveFailedException.java new file mode 100644 index 0000000000..ea5699c852 --- /dev/null +++ b/pipo/src/org/adempiere/pipo2/exception/POSaveFailedException.java @@ -0,0 +1,25 @@ +package org.adempiere.pipo2.exception; + +public class POSaveFailedException extends RuntimeException { + + /** + * + */ + private static final long serialVersionUID = 8325708851137221459L; + + public POSaveFailedException() { + super(); + } + + public POSaveFailedException(String message, Throwable cause) { + super(message, cause); + } + + public POSaveFailedException(String message) { + super(message); + } + + public POSaveFailedException(Throwable cause) { + super(cause); + } +} diff --git a/pipoHandlers/.classpath b/pipoHandlers/.classpath new file mode 100644 index 0000000000..ad32c83a78 --- /dev/null +++ b/pipoHandlers/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/pipoHandlers/.project b/pipoHandlers/.project new file mode 100644 index 0000000000..77a4556959 --- /dev/null +++ b/pipoHandlers/.project @@ -0,0 +1,28 @@ + + + pipoHandlers + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/pipoHandlers/.settings/org.eclipse.jdt.core.prefs b/pipoHandlers/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..bb618cfae4 --- /dev/null +++ b/pipoHandlers/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Fri Aug 06 19:56:31 MYT 2010 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/pipoHandlers/.settings/org.eclipse.pde.core.prefs b/pipoHandlers/.settings/org.eclipse.pde.core.prefs new file mode 100644 index 0000000000..0ec87bdbfe --- /dev/null +++ b/pipoHandlers/.settings/org.eclipse.pde.core.prefs @@ -0,0 +1,4 @@ +#Fri Aug 06 19:58:58 MYT 2010 +eclipse.preferences.version=1 +pluginProject.extensions=true +resolve.requirebundle=false diff --git a/pipoHandlers/META-INF/MANIFEST.MF b/pipoHandlers/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..59e0b718be --- /dev/null +++ b/pipoHandlers/META-INF/MANIFEST.MF @@ -0,0 +1,8 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: PipoHandlers +Bundle-SymbolicName: org.adempiere.pipo.defaultHandlers;singleton:=true +Bundle-Version: 1.0.0.qualifier +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Require-Bundle: org.adempiere.pipo;bundle-version="1.0.0", + org.adempiere.base;bundle-version="1.0.0" diff --git a/pipoHandlers/build.properties b/pipoHandlers/build.properties new file mode 100644 index 0000000000..e9863e281e --- /dev/null +++ b/pipoHandlers/build.properties @@ -0,0 +1,5 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + plugin.xml diff --git a/pipoHandlers/build.xml b/pipoHandlers/build.xml new file mode 100644 index 0000000000..a2f3db9389 --- /dev/null +++ b/pipoHandlers/build.xml @@ -0,0 +1,36 @@ + + + + + + + + + + This buildfile is used to build the client subproject within + the Adempiere project. + + + + + + + + + + + + + + + + + + + + + diff --git a/pipoHandlers/plugin.xml b/pipoHandlers/plugin.xml new file mode 100644 index 0000000000..f163e56f08 --- /dev/null +++ b/pipoHandlers/plugin.xml @@ -0,0 +1,177 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/AdElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/AdElementHandler.java new file mode 100644 index 0000000000..612ae824a0 --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/AdElementHandler.java @@ -0,0 +1,159 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + + +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.exception.POSaveFailedException; +import org.compiere.model.M_Element; +import org.compiere.model.X_AD_Element; +import org.compiere.model.X_AD_Package_Imp_Detail; + +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class AdElementHandler extends AbstractElementHandler { + + private List processedElements = new ArrayList(); + + private final String AD_ELEMENT = "AD_Element"; + + + public void startElement(Properties ctx, Element element) + throws SAXException { + String action = null; + + String entitytype = getStringValue(element, "EntityType"); + String ColumnName = getStringValue(element, "ColumnName"); + + if (isProcessElement(ctx, entitytype)) { + + M_Element mElement = findPO(ctx, element); + if (mElement == null) { + int id = findIdByColumn(ctx, X_AD_Element.Table_Name, X_AD_Element.COLUMNNAME_ColumnName, ColumnName); + mElement = new M_Element(ctx, id, getTrxName(ctx)); + } + List excludes = defaultExcludeList(X_AD_Element.Table_Name); + if (mElement.getAD_Element_ID() == 0 && isOfficialId(element, "AD_Element_ID")) + mElement.setAD_Element_ID(getIntValue(element, "AD_Element_ID")); + + if (processedElements.contains(mElement.getAD_Element_ID())) { + element.skip = true; + return; + } + + PoFiller pf = new PoFiller(ctx, mElement, element, this); + List notfounds = pf.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + + if (mElement.is_new() || mElement.is_Changed()) { + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_Element.Table_Name, X_AD_Element.Table_ID); + if (!mElement.is_new()) { + backupRecord(ctx, impDetail.getAD_Package_Imp_Detail_ID(), AD_ELEMENT, mElement); + action = "Update"; + } else { + action = "New"; + } + + if (mElement.save(getTrxName(ctx)) == true) { + logImportDetail(ctx, impDetail, 1, mElement.getName(), + mElement.get_ID(), action); + + element.recordId = mElement.getAD_Element_ID(); + + processedElements.add(mElement.getAD_Element_ID()); + + } else { + logImportDetail(ctx, impDetail, 0, mElement.getName(), + mElement.get_ID(), action); + throw new POSaveFailedException("Reference"); + } + } + } else { + element.skip = true; + } + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + protected void create(Properties ctx, TransformerHandler document) + throws SAXException { + + + int adElement_id = Env.getContextAsInt(ctx, + X_AD_Element.COLUMNNAME_AD_Element_ID); + + if (processedElements.contains(adElement_id)) + return; + + processedElements.add(adElement_id); + + X_AD_Element m_AdElement = new X_AD_Element(ctx, adElement_id, null); + + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "table"); + document.startElement("", "", "AD_Element", atts); + createAdElementBinding(ctx, document, m_AdElement); + + PackOut packOut = (PackOut)ctx.get("PackOutProcess"); + + + try{ + new CommonTranslationHandler().packOut(packOut,document,null,m_AdElement.get_ID()); + } + catch(Exception e) + { + log.info(e.toString()); + } + + document.endElement("", "", "AD_Element"); + } + + + private void createAdElementBinding(Properties ctx, TransformerHandler document, + X_AD_Element m_AdElement) { + + PoExporter filler = new PoExporter(ctx, document, m_AdElement); + if (m_AdElement.getAD_Element_ID() <= PackOut.MAX_OFFICIAL_ID) + filler.add(X_AD_Element.COLUMNNAME_AD_Element_ID, new AttributesImpl()); + + List excludes = defaultExcludeList(X_AD_Element.Table_Name); + filler.export(excludes); + } + + public void packOut(PackOut packout, TransformerHandler packoutHandler, TransformerHandler docHandler,int recordId) throws Exception + { + Env.setContext(packout.getCtx(), X_AD_Element.COLUMNNAME_AD_Element_ID, recordId); + this.create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(X_AD_Element.COLUMNNAME_AD_Element_ID); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/CodeSnippetElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/CodeSnippetElementHandler.java new file mode 100644 index 0000000000..ee26684a09 --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/CodeSnippetElementHandler.java @@ -0,0 +1,247 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + + +import org.compiere.Adempiere; +import org.compiere.model.MPackageExpDetail; +import org.compiere.model.X_AD_Package_Exp_Detail; +import org.compiere.model.X_AD_Package_Imp_Backup; +import org.compiere.model.X_AD_Package_Imp_Detail; + +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; + +public class CodeSnippetElementHandler extends AbstractElementHandler { + + public void startElement(Properties ctx, Element element) throws SAXException { + String action = null; + action = "Update"; + String releaseNumber = getStringValue(element, "ReleaseNo"); + //Check Release Number + if(Adempiere.MAIN_VERSION.equals(releaseNumber)||releaseNumber.equals("all")){ + String sourceName = getStringValue(element, "filename"); + String targetDirectory = getStringValue(element, "filedir"); + String oldCode = getStringValue(element, "oldcode"); + String newCode = getStringValue(element, "newcode"); + + InputStream source; // Stream for reading from the source file. + OutputStream copy; // Stream for writing the copy. + + String packagePath=null; + String sourcePath=null; + + //get adempiere-all directory + try { + packagePath = getPackageDirectory(ctx); + File parentDirectory = new File(packagePath); + while (!parentDirectory.getName().equals("packages")){ + parentDirectory = parentDirectory.getParentFile(); + } + parentDirectory = parentDirectory.getParentFile(); + sourcePath = parentDirectory.getCanonicalPath(); + } catch (IOException e1) { + System.out.println("Can't find adempiere-all directory."); + } + + // Create backup directory if required + File backupDir = new File(packagePath+File.separator+"backup"+File.separator); + if (!backupDir.exists()){ + boolean success = (new File(packagePath+File.separator+"backup"+File.separator)).mkdirs(); + if (!success) { + log.info("Backup directory creation failed"); + } + } + + //Correct target directory for proper file seperator + String fullDirectory = sourcePath+targetDirectory; + String targetDirectoryModified=null; + String fileDate = null; + char slash1 = '\\'; + char slash2 = '/'; + if (File.separator.equals("/")) + targetDirectoryModified = fullDirectory.replace(slash1,slash2); + else + targetDirectoryModified = fullDirectory.replace(slash2,slash1); + + File file = new File(targetDirectoryModified+sourceName); + log.info(targetDirectoryModified+sourceName); + //TODO: derived force from user parameter + boolean force = true; + // check to see if overwrites are allowed + if (file.exists()) { + if (!force) { + System.out.println("Output file exists. Use the -f option to replace it."); + return; + } + //backup file to package directory + else { + action = "Update"; + log.info("Target Backup:"+targetDirectoryModified+sourceName); + source = OpenInputfile(targetDirectoryModified+sourceName); + SimpleDateFormat formatter_file = new SimpleDateFormat("yyMMddHHmmssSSSSZ"); + Date today = new Date(); + fileDate = formatter_file.format(today); + copy = OpenOutputfile(packagePath+File.separator+"backup"+File.separator+fileDate+"_"+sourceName); + log.info("Source Backup:"+packagePath+File.separator+"backup"+File.separator+fileDate+"_"+sourceName); + copyFile (source,copy); + log.info("Backup Complete"); + } + } + + int success = readReplace(targetDirectoryModified+sourceName, oldCode, newCode); + + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, "codesnipit", sourceName, 0); + // Record in log + if (success != -1){ + try { + logImportDetail (ctx, impDetail, 1, sourceName, 0, action); + } catch (SAXException e) { + log.info ("setfile:"+e); + } + } + else{ + try { + logImportDetail (ctx, impDetail, 0, sourceName, 0, action); + } catch (SAXException e) { + log.info ("setfile:"+e); + } + } + + //Record in transaction file + X_AD_Package_Imp_Backup backup = new X_AD_Package_Imp_Backup(ctx, 0, getTrxName(ctx)); + backup.setAD_Org_ID(Env.getAD_Org_ID(ctx)); + backup.setAD_Package_Imp_ID(getPackageImpId(ctx)); + backup.setAD_Package_Imp_Org_Dir(targetDirectoryModified+sourceName ); + backup.setAD_Package_Imp_Bck_Dir(packagePath+File.separator+"backup"+File.separator+fileDate+"_"+sourceName); + backup.saveEx(); + + } + } + + + /** + * Find and replace code + * + * @param file name + * @param old string + * @param new string + * + */ + public static int readReplace(String fname, String oldPattern, String replPattern){ + String line; + StringBuffer sb = new StringBuffer(); + + try { + + FileInputStream fis = new FileInputStream(fname); + BufferedReader reader=new BufferedReader ( new InputStreamReader(fis)); + while((line = reader.readLine()) != null) { + line = line.replaceAll(oldPattern, replPattern); + System.err.println(line); + sb.append(line+"\n"); + } + reader.close(); + BufferedWriter out=new BufferedWriter ( new FileWriter(fname)); + out.write(sb.toString()); + out.close(); + } + catch (Throwable e) { + System.err.println("error replacing codesnipit "+e); + return -1; + } + return 0; + } + + + public void endElement(Properties ctx, Element element) + throws SAXException { + } + + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + String FileDir = Env.getContext(ctx, X_AD_Package_Exp_Detail.COLUMNNAME_File_Directory); + String FileName = Env.getContext(ctx, X_AD_Package_Exp_Detail.COLUMNNAME_FileName); + String OldCode = Env.getContext(ctx, X_AD_Package_Exp_Detail.COLUMNNAME_AD_Package_Code_Old); + String NewCode = Env.getContext(ctx, X_AD_Package_Exp_Detail.COLUMNNAME_AD_Package_Code_New); + String ReleaseNo = Env.getContext(ctx, X_AD_Package_Exp_Detail.COLUMNNAME_ReleaseNo); + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "custom"); + createSnipitBinding(atts, FileDir, FileName, OldCode, NewCode, ReleaseNo); + document.startElement("","","Code_Snipit",atts); + document.endElement("","","Code_Snipit"); + } + + private AttributesImpl createSnipitBinding( AttributesImpl atts, String FileDir, String FileName, String OldCode, String NewCode, String ReleaseNo) + { + atts.clear(); + atts.addAttribute("","","filedir","CDATA",FileDir); + atts.addAttribute("","","filename","CDATA",FileName); + String preOldCode = OldCode.toString(); + String preNewCode = NewCode.toString(); + String modOldCode = preOldCode.replaceAll("\\$","\\\\\\$").replaceAll("\\.","\\\\.") + .replaceAll("\\^","\\\\^").replaceAll("\\(","\\\\(").replaceAll("\\)","\\\\)") + .replaceAll("\\[","\\\\[").replaceAll("\\/","\\\\/").replaceAll("\\+","\\\\+") + .replaceAll("\\*","\\\\*").replaceAll("\\|","\\\\|"); + String modNewCode = preNewCode.replaceAll("\\$","\\\\\\$").replaceAll("\\.","\\\\.") + .replaceAll("\\^","\\\\^").replaceAll("\\(","\\\\(").replaceAll("\\)","\\\\)") + .replaceAll("\\[","\\\\[").replaceAll("\\/","\\\\/").replaceAll("\\+","\\\\+") + .replaceAll("\\*","\\\\*").replaceAll("\\|","\\\\|"); + atts.addAttribute("","","oldcode","CDATA",modOldCode); + atts.addAttribute("","","newcode","CDATA",modNewCode); + atts.addAttribute("","","ReleaseNo","CDATA",ReleaseNo); + return atts; + } + + public void packOut(PackOut packout, TransformerHandler packoutHandler, TransformerHandler docHandler,int recordId) throws Exception + { + MPackageExpDetail detail = packout.getPackageExpDetail(); + Env.setContext(packout.getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_Destination_Directory, detail.getDestination_Directory()); + Env.setContext(packout.getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_FileName, detail.getDestination_FileName()); + Env.setContext(packout.getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_Package_Code_Old, detail.getAD_Package_Code_Old()); + Env.setContext(packout.getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_Package_Code_New, detail.getAD_Package_Code_New()); + Env.setContext(packout.getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_ReleaseNo,detail.getReleaseNo()); + this.create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_File_Directory); + packout.getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_FileName); + packout.getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Package_Code_Old); + packout.getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Package_Code_New); + packout.getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_ReleaseNo); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/ColumnElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/ColumnElementHandler.java new file mode 100644 index 0000000000..13c54b90b5 --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/ColumnElementHandler.java @@ -0,0 +1,344 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; +import java.util.Properties; +import java.util.logging.Level; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.exception.DatabaseAccessException; +import org.adempiere.pipo2.exception.POSaveFailedException; +import org.compiere.model.I_AD_Column; +import org.compiere.model.I_AD_Table; +import org.compiere.model.MColumn; +import org.compiere.model.MTable; +import org.compiere.model.X_AD_Column; +import org.compiere.model.X_AD_Element; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.util.DB; +import org.compiere.util.DisplayType; +import org.compiere.util.Env; +import org.compiere.util.Trx; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class ColumnElementHandler extends AbstractElementHandler { + + public void startElement(Properties ctx, Element element) + throws SAXException { + int success = 0; + String entitytype = getStringValue(element, "EntityType"); + if (isProcessElement(ctx, entitytype)) { + if (isParentDefer(element, I_AD_Table.Table_Name)) { + element.defer = true; + return; + } + + List excludes = defaultExcludeList(X_AD_Column.Table_Name); + String columnName = getStringValue(element, "ColumnName", excludes); + + MColumn mColumn = findPO(ctx, element); + if (mColumn == null) { + int tableid = 0; + if (getParentId(element, I_AD_Table.Table_Name) > 0) { + tableid = getParentId(element, "table"); + } else { + mColumn = new MColumn(ctx, 0, getTrxName(ctx)); + PoFiller filler = new PoFiller(ctx, mColumn, element, this); + filler.setTableReference("AD_Table_ID"); + tableid = mColumn.getAD_Table_ID(); + } + int AD_Column_ID = findIdByColumnAndParentId(ctx, "AD_Column", "ColumnName", columnName, "AD_Table", tableid); + mColumn = new MColumn(ctx, AD_Column_ID > 0 ? AD_Column_ID : 0, getTrxName(ctx)); + if (mColumn.getAD_Column_ID() == 0 && isOfficialId(element, "AD_Column_ID")) { + mColumn.setAD_Column_ID(getIntValue(element, "AD_Column_ID")); + } + } + + mColumn.setColumnName(columnName); + mColumn.setIsSyncDatabase(getStringValue(element, "IsSyncDatabase", excludes)); + + PoFiller filler = new PoFiller(ctx, mColumn, element, this); + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + + if (!mColumn.is_new() && !mColumn.is_Changed()) + return; + + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_Column.Table_Name, X_AD_Column.Table_ID); + String action = null; + if (!mColumn.is_new()) { + backupRecord(ctx, impDetail.getAD_Package_Imp_Detail_ID(), "AD_Column", mColumn); + action = "Update"; + } else { + action = "New"; + } + + // Setup Element. + if (mColumn.getAD_Element_ID() == 0) { + X_AD_Element adElement = new X_AD_Element(ctx, 0, getTrxName(ctx)); + adElement.setColumnName(mColumn.getColumnName()); + adElement.setEntityType(mColumn.getEntityType()); + adElement.setPrintName(mColumn.getColumnName()); + adElement.setName(mColumn.getColumnName()); + adElement.saveEx(); + X_AD_Package_Imp_Detail eleDetail = createImportDetail(ctx, "Element", X_AD_Element.Table_Name, + X_AD_Element.Table_ID); + logImportDetail(ctx, eleDetail, 1, mColumn.getColumnName(), adElement + .getAD_Element_ID(), "New"); + mColumn.setAD_Element_ID(adElement.getAD_Element_ID()); + } + + boolean recreateColumn = (mColumn.is_new() + || mColumn.is_ValueChanged("AD_Reference_ID") + || mColumn.is_ValueChanged("FieldLength") + || mColumn.is_ValueChanged("ColumnName") || mColumn + .is_ValueChanged("IsMandatory")); + + //ignore fieldlength change for clob and lob + if (!mColumn.is_ValueChanged("AD_Reference_ID") && mColumn.is_ValueChanged("FieldLength")) { + if (DisplayType.isLOB(mColumn.getAD_Reference_ID())) { + recreateColumn = false; + } + } + + // changed default ?? + // m_Column.is_ValueChanged("DefaultValue") doesn't work well with + // nulls + if (!recreateColumn) { + String oldDefault = (String) mColumn + .get_ValueOld("DefaultValue"); + String newDefault = mColumn.getDefaultValue(); + if (oldDefault != null && oldDefault.length() == 0) + oldDefault = null; + if (newDefault != null && newDefault.length() == 0) + newDefault = null; + if ((oldDefault == null && newDefault != null) + || (oldDefault != null && newDefault == null)) { + recreateColumn = true; + } else if (oldDefault != null && newDefault != null) { + if (!oldDefault.equals(newDefault)) + recreateColumn = true; + } + } + + // Don't create database column for virtual columns + boolean syncDatabase = "Y".equalsIgnoreCase(getStringValue(element, "IsSyncDatabase")); + if (recreateColumn) { + if (mColumn.isVirtualColumn() || !syncDatabase) + recreateColumn = false; + } + + if (mColumn.save(getTrxName(ctx)) == true) { + logImportDetail(ctx, impDetail, 1, mColumn.getName(), mColumn + .get_ID(), action); + element.recordId = mColumn.getAD_Column_ID(); + } else { + logImportDetail(ctx, impDetail, 0, mColumn.getName(), mColumn + .get_ID(), action); + throw new POSaveFailedException("Failed to import column."); + } + + if (recreateColumn || syncDatabase) { + MTable table = new MTable(ctx, mColumn.getAD_Table_ID(), getTrxName(ctx)); + if (!table.isView() && !mColumn.isVirtualColumn()) { + success = createColumn(ctx, table, mColumn, recreateColumn); + + X_AD_Package_Imp_Detail dbDetail = createImportDetail(ctx, "dbColumn", X_AD_Column.Table_Name, X_AD_Column.Table_ID); + if (success == 1) { + logImportDetail(ctx, dbDetail, 1, mColumn.getColumnName(), + mColumn.get_ID(), action); + } else { + logImportDetail(ctx, dbDetail, 0, mColumn.getColumnName(), + mColumn.get_ID(), action); + throw new DatabaseAccessException("Failed to create column or related constraint for " + mColumn.getColumnName()); + } + } + } + } else { + element.skip = true; + } + } + + /** + * Check if column exists in database and modify. If not create column. + * + * @param tablename + * @param columnname + * @param v_AD_Reference_ID + * @param v_FieldLength + * @param v_DefaultValue + * @param v_IsMandatory + * + */ + private int createColumn(Properties ctx, MTable table, MColumn column, boolean doAlter) { + + int no = 0; + + String sql = null; + ResultSet rst = null; + ResultSet rsc = null; + Connection conn = null; + Trx trx = Trx.get(getTrxName(ctx), true); + if (!trx.commit()) + return 0; + + try { + // Find Column in Database + conn = trx.getConnection(); + DatabaseMetaData md = conn.getMetaData(); + String catalog = DB.getDatabase().getCatalog(); + String schema = DB.getDatabase().getSchema(); + String tableName = table.getTableName(); + String columnName = column.getColumnName(); + if (DB.isOracle()) { + tableName = tableName.toUpperCase(); + columnName = columnName.toUpperCase(); + } else if (DB.isPostgreSQL()) { + tableName = tableName.toLowerCase(); + columnName = columnName.toLowerCase(); + } + + rst = md.getTables(catalog, schema, tableName, + new String[] { "TABLE" }); + if (!rst.next()) { + // table doesn't exist + sql = table.getSQLCreate(); + } else { + // + rsc = md.getColumns(catalog, schema, tableName, columnName); + if (rsc.next()) { + if (doAlter) { + // update existing column + boolean notNull = DatabaseMetaData.columnNoNulls == rsc + .getInt("NULLABLE"); + sql = column.getSQLModify(table, + column.isMandatory() != notNull); + } + } else { + // No existing column + sql = column.getSQLAdd(table); + } + rsc.close(); + rsc = null; + } + + rst.close(); + rst = null; + //execute modify or add if needed + if (sql != null && sql.trim().length() > 0) { + log.info(sql); + + if (sql.indexOf(DB.SQLSTATEMENT_SEPARATOR) == -1) { + no = DB.executeUpdate(sql, false, trx.getTrxName()); + if (no == -1) + return 0; + } else { + String statements[] = sql.split(DB.SQLSTATEMENT_SEPARATOR); + for (int i = 0; i < statements.length; i++) { + int count = DB.executeUpdate(statements[i], false, + trx.getTrxName()); + if (count == -1) { + return 0; + } + no += count; + } + } + } + trx.commit(true); + } catch (SQLException e) { + log.log(Level.SEVERE, e.getLocalizedMessage(), e); + if (rsc != null) { + try { + rsc.close(); + } catch (SQLException e1) { + } + rsc = null; + } + if (rst != null) { + try { + rst.close(); + } catch (SQLException e1) { + } + rst = null; + } + trx.rollback(); + return 0; + } + + return 1; + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int AD_Column_ID = Env.getContextAsInt(ctx, + X_AD_Column.COLUMNNAME_AD_Column_ID); + AttributesImpl atts = new AttributesImpl(); + X_AD_Column m_Column = new X_AD_Column(ctx, AD_Column_ID, + getTrxName(ctx)); + addTypeName(atts, "table"); + document.startElement("", "", I_AD_Column.Table_Name, atts); + createColumnBinding(ctx, document, m_Column); + document.endElement("", "", I_AD_Column.Table_Name); + } + + private void createColumnBinding(Properties ctx, TransformerHandler document, + X_AD_Column m_Column) { + + PoExporter filler = new PoExporter(ctx, document, m_Column); + Listexcludes = defaultExcludeList(X_AD_Column.Table_Name); + + if (m_Column.getAD_Column_ID() <= PackOut.MAX_OFFICIAL_ID) + filler.add("AD_Column_ID", new AttributesImpl()); + + filler.addString("IsSyncDatabase", "Y", new AttributesImpl()); + filler.addTableReference("AD_Table", "TableName", new AttributesImpl()); + filler.addTableReference("AD_Reference_Value_ID", "AD_Reference", "Name", new AttributesImpl()); + + excludes.add("IsSyncDatabase"); + excludes.add("AD_Table_ID"); + excludes.add("AD_Reference_Value_ID"); + + filler.export(excludes); + } + + @Override + public void packOut(PackOut packout, TransformerHandler packoutHandler, + TransformerHandler docHandler, + int recordId) throws Exception { + Env.setContext(packout.getCtx(), I_AD_Column.COLUMNNAME_AD_Column_ID, recordId); + create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(I_AD_Column.COLUMNNAME_AD_Column_ID); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/CommonTranslationHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/CommonTranslationHandler.java new file mode 100644 index 0000000000..427b883ced --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/CommonTranslationHandler.java @@ -0,0 +1,301 @@ +package org.adempiere.pipo2.handler; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.exceptions.DBException; +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.ElementHandler; +import org.adempiere.pipo2.PackOut; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +import org.compiere.model.X_AD_Element; + +public class CommonTranslationHandler extends AbstractElementHandler implements ElementHandler { + + public static final String CONTEXT_KEY_PARENT_TABLE = "currentParentTableForTranslation"; + public static final String CONTEXT_KEY_PARENT_RECORD_ID = "currentParentTableRecordID_ForTranslation"; + + private HashMap> cacheColumns = new HashMap>();//Key: table name. Value: set of PIPO columns + + + public void startElement(Properties ctx, Element element) throws SAXException { + + if(! isHandleTranslations(ctx)){ + return;//translation import option is disabled + } + + if(isParentSkip(element, null)){ + return; + } + + if(isParentDefer(element, null)){ + element.defer = true; + return; + } + + String elementValue = element.getElementValue(); + int parentID = element.parent.recordId; + + if(parentID ==0) + throw new SAXException(); + + String language = getStringValue(element, "AD_Language"); + + log.info(elementValue+" "+getStringValue(element, "Name")); + + if(isRecordExists(elementValue, parentID, language, ctx)){ + updateTranslation(elementValue, parentID, ctx, element); + }else{ + insertTranslation(elementValue, parentID, ctx, element); + } + } + + + private boolean isRecordExists(String tableName, int parentID, + String language, Properties ctx) { + + String sql = + "SELECT AD_Client_ID FROM " + tableName +" WHERE " + + tableName.substring(0, tableName.length()-4) + "_ID = ? AND AD_Language = ?"; + + if(DB.getSQLValue(getTrxName(ctx), sql, parentID, language) == -1){ + return false; + }else{ + return true; + } + } + + + private void insertTranslation(String tableName, int parentID, + Properties ctx, Element element) throws SAXException{ + + String parentTable = tableName.substring(0, tableName.length()-4); + ArrayList columns = getTranslatedColumns(parentTable); + StringBuffer sql = new StringBuffer(); + sql.append("INSERT INTO ") + .append(tableName) + .append(" (") + .append(parentTable) + .append("_ID, ") + .append(" AD_Client_ID, AD_Org_ID, CreatedBy, UpdatedBy, ") + .append(cast(columns)) + .append(") values ( ?, ?, ?, ?, ? "); + + for (int i = 0; i columns = getTranslatedColumns(parentTable); + StringBuffer buffer = new StringBuffer("UPDATE "+tableName+" SET "); + for (String columnName : columns) { + buffer.append(columnName).append("=?,"); + } + + String sql = buffer.substring(0, buffer.length()-1); + sql += " WHERE AD_Language = '"+getStringValue(element, "AD_Language")+ + "' AND "+parentTable+"_ID="+parentID; + + PreparedStatement pstm = null; + try { + pstm = DB.prepareStatement(sql,getTrxName(ctx)); + int i=0; + for (String columnName : columns) { + String value = getStringValue(element, columnName); + i++; + + if(columnName.equalsIgnoreCase("IsActive") || + columnName.equalsIgnoreCase("IsTranslated")){ + + value = "true".equals(value) ? "Y" : "N"; + } + + pstm.setString(i, value); + } + + if(pstm.executeUpdate()<0){ + throw new SAXException(); + } + } catch (Exception e) { + throw new DBException(e); + } finally { + DB.close(pstm); + } + } + + + public void endElement(Properties ctx, Element element) throws SAXException { + + } + + + public void create(Properties ctx, TransformerHandler document) throws SAXException { + + String parenTableName = Env.getContext(ctx, CONTEXT_KEY_PARENT_TABLE); + + int parentRecordID = Env.getContextAsInt(ctx, CONTEXT_KEY_PARENT_RECORD_ID); + + createTranslationTags(ctx, parenTableName, parentRecordID, document); + } + + + private void createTranslationTags(Properties ctx, String parentTable, + int parentRecordID, TransformerHandler document) throws SAXException { + + ArrayList translatedColumns = getTranslatedColumns(parentTable); + + String sql = + "select "+cast(translatedColumns)+" from "+parentTable+"_trl where "+ + parentTable+"_ID="+parentRecordID; + + PreparedStatement pstm = null; + ResultSet rs = null; + try { + + pstm = DB.prepareStatement(sql, null); + rs = pstm.executeQuery(); + + String elementName = parentTable + "_Trl"; + while(rs.next()){ + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "translation"); + document.startElement("", "", elementName, atts); + exportRow(ctx, document, translatedColumns, rs); + document.endElement("", "", elementName); + } + + } catch (Exception e) { + e.printStackTrace(); + throw new SAXException(); + } finally { + DB.close(rs, pstm); + } + } + + private void exportRow(Properties ctx, TransformerHandler document, ArrayList columns, + ResultSet rs) throws Exception { + + PoExporter af = new PoExporter(ctx, document, null); + + for (String columnName : columns) { + if(columnName.equalsIgnoreCase("IsActive")|| + columnName.equalsIgnoreCase("IsTranslated")) { + af.addBoolean(columnName, rs.getString(columnName).equalsIgnoreCase("Y"), new AttributesImpl()); + } else{ + af.addString(columnName, rs.getString(columnName), new AttributesImpl()); + } + } + } + + /** + * + * @param parentTable + * @return + * @throws SAXException + */ + private ArrayList getTranslatedColumns(String parentTable) throws SAXException { + + + ArrayList pipolColumns = cacheColumns.get(parentTable); + if(pipolColumns != null){ + return pipolColumns; + } + + ArrayList columns = new ArrayList(); + String sql = "select * from ad_column where ad_table_id = " + + "(select ad_table_id from ad_table where tableName = ?)" + + "and isTranslated='Y'"; + + PreparedStatement pstm = null; + ResultSet rs = null; + try { + pstm = DB.prepareStatement(sql, null); + pstm.setString(1, parentTable); + + rs = pstm.executeQuery(); + while(rs.next()){ + columns.add(rs.getString("columnName")); + } + } catch (SQLException e) { + e.printStackTrace(); + throw new SAXException(); + } finally { + DB.close(rs, pstm); + } + + columns.add("AD_Language"); + columns.add("IsActive"); + columns.add("IsTranslated"); + + //Putting in cache + cacheColumns.put(parentTable, columns); + + return columns; + } + + private String cast(ArrayList arg){ + String str = arg.toString(); + return str.substring(1, str.length()-1); + } + + public void packOut(PackOut packout, TransformerHandler packoutHandler, TransformerHandler docHandler,int recordId) throws Exception + { + if("true".equals(packout.getCtx().getProperty("isHandleTranslations"))){ + Env.setContext(packout.getCtx(), CommonTranslationHandler.CONTEXT_KEY_PARENT_TABLE,X_AD_Element.Table_Name); + Env.setContext(packout.getCtx(), CommonTranslationHandler.CONTEXT_KEY_PARENT_RECORD_ID,recordId); + this.create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(CommonTranslationHandler.CONTEXT_KEY_PARENT_TABLE); + packout.getCtx().remove(CommonTranslationHandler.CONTEXT_KEY_PARENT_RECORD_ID); + + } + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/DistFileElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/DistFileElementHandler.java new file mode 100644 index 0000000000..f61387ef80 --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/DistFileElementHandler.java @@ -0,0 +1,218 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.compiere.Adempiere; +import org.compiere.model.MPackageExp; +import org.compiere.model.MPackageExpDetail; +import org.compiere.model.X_AD_Package_Exp_Detail; +import org.compiere.model.X_AD_Package_Imp_Backup; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class DistFileElementHandler extends AbstractElementHandler { + + String fileDest; + + public DistFileElementHandler() + { + + } + + public DistFileElementHandler(String fileDest) + { + this.fileDest=fileDest; + } + + public void startElement(Properties ctx, Element element) throws SAXException { + String action = null; + + String releaseNumber = getStringValue(element,"ReleaseNo"); + //Check Release Number + if(releaseNumber==null||Adempiere.MAIN_VERSION.equals(releaseNumber)||releaseNumber.equals("all")){ + String fileName = getStringValue(element, "filename"); + String sourceDirectory = getStringValue(element, "sourceDirectory"); + String targetDirectory = getStringValue(element, "targetDirectory"); + + action = "New"; + InputStream inputStream; // Stream for reading from the source file. + OutputStream outputStream; // Stream for writing the copy. + + String packagePath=null; + String adempiereSourcePath=null; + + //get adempiere-all directory + try { + packagePath = getPackageDirectory(ctx); + File parentDirectory = new File(packagePath); + while (!parentDirectory.getName().equals("packages")){ + parentDirectory = parentDirectory.getParentFile(); + } + parentDirectory = parentDirectory.getParentFile(); + adempiereSourcePath = parentDirectory.getCanonicalPath(); + } catch (IOException e1) { + System.out.println("Can't find adempiere-all directory."); + } + + + // Create backup directory if required + File backupDir = new File(packagePath+File.separator+"backup"+File.separator); + if (!backupDir.exists()){ + boolean success = (new File(packagePath+File.separator+"backup"+File.separator)).mkdirs(); + if (!success) { + log.info("Backup directory creation failed"); + } + } + + //Correct target directory for proper file seperator + String fullTargetPath = adempiereSourcePath+targetDirectory; + char slash1 = '\\'; + char slash2 = '/'; + if (File.separator.equals("/")) + fullTargetPath = fullTargetPath.replace(slash1,slash2); + else + fullTargetPath = fullTargetPath.replace(slash2,slash1); + + File file = new File(fullTargetPath+fileName); + //TODO: derive force from user parameter + boolean force = true; + String fileDate = null; + //check to see if overwrites are allowed + if (file.exists()) + { + if (!force) { + System.out.println( + "Output file exists. Use the -f option to replace it."); + return; + } + //backup file to package directory + else { + action = "Update"; + log.info("Target Backup:"+fullTargetPath+fileName); + inputStream = OpenInputfile(fullTargetPath+fileName); + SimpleDateFormat formatter_file = new SimpleDateFormat("yyMMddHHmmssSSSSZ"); + Date today = new Date(); + fileDate = formatter_file.format(today); + outputStream = OpenOutputfile(packagePath+File.separator+"backup"+File.separator+fileDate+"_"+fileName); + log.info("Source Backup:"+packagePath+File.separator+"backup"+File.separator+fileDate+"_"+fileName); + copyFile (inputStream, outputStream); + log.info("Backup Complete"); + } + } + +// Correct dist directory for proper file seperator + String fullSourcePath=null; + if (File.separator.equals("/")) + fullSourcePath = sourceDirectory.replace(slash1,slash2); + else + fullSourcePath = sourceDirectory.replace(slash2,slash1); + inputStream = OpenInputfile(packagePath+fullSourcePath+fileName); + +// Create Target directory if required + File targetDir = new File(fullTargetPath); + if (!targetDir.exists()){ + boolean success = (new File(fullTargetPath)).mkdirs(); + if (!success) { + log.info("Target directory creation failed"); + } + } + outputStream = OpenOutputfile(fullTargetPath+fileName); + //Copy File + int success = copyFile (inputStream,outputStream); + //Record in log + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, "file", fileName, 0); + if (success != -1){ + try { + logImportDetail (ctx, impDetail, 1, fileName, 0, action); + } catch (SAXException e) { + log.info ("setfile:"+e); + } + } + else{ + try { + logImportDetail (ctx, impDetail, 0, fileName, 0, action); + } catch (SAXException e) { + log.info ("setfile:"+e); + } + } + //Record in transaction file + X_AD_Package_Imp_Backup backup = new X_AD_Package_Imp_Backup(ctx, 0, getTrxName(ctx)); + backup.setAD_Org_ID(Env.getAD_Org_ID(ctx)); + backup.setAD_Package_Imp_Org_Dir(fullTargetPath+fileName); + backup.setAD_Package_Imp_Bck_Dir(packagePath+File.separator+"backup"+File.separator+fileDate+"_"+fileName); + backup.setAD_Package_Imp_ID(getPackageImpId(ctx)); + backup.saveEx(); + + } + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + String FileName = Env.getContext(ctx, X_AD_Package_Exp_Detail.COLUMNNAME_FileName); + String Source_Directory = Env.getContext(ctx, "Source_Directory"); + String Target_Directory = Env.getContext(ctx, X_AD_Package_Exp_Detail.COLUMNNAME_Target_Directory); + String ReleaseNo = Env.getContext(ctx, X_AD_Package_Exp_Detail.COLUMNNAME_ReleaseNo); + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "custom"); + document.startElement("","","Dist_File",atts); + addTextProperty(document,"filename",FileName); + addTextProperty(document,"sourceDirectory",Source_Directory); + addTextProperty(document,"targetDirectory",Target_Directory); + addTextProperty(document,"ReleaseNo",ReleaseNo); + atts.addAttribute("","","ReleaseNo","CDATA",ReleaseNo); + document.endElement("","","Dist_File"); + } + + public void doPackout(PackOut packout, MPackageExp header, MPackageExpDetail detail,TransformerHandler packOutDocument,TransformerHandler packageDocument,AttributesImpl atts,int recordId) throws Exception + { + Env.setContext(packout.getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_FileName, detail.getFileName()); + Env.setContext(packout.getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_ReleaseNo, detail.getReleaseNo()); + Env.setContext(packout.getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_Target_Directory, detail.getTarget_Directory()); + Env.setContext(packout.getCtx(), "Source_Directory", fileDest); + this.create(packout.getCtx(), packOutDocument); + packout.getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_FileName); + packout.getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_ReleaseNo); + packout.getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_Target_Directory); + packout.getCtx().remove("Source_Directory"); + } + + @Override + public void packOut(PackOut packout, TransformerHandler packoutHandler, + TransformerHandler docHandler, + int recordId) throws Exception { + // TODO Auto-generated method stub + + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/DynValRuleElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/DynValRuleElementHandler.java new file mode 100644 index 0000000000..1e640e73a6 --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/DynValRuleElementHandler.java @@ -0,0 +1,130 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.exception.POSaveFailedException; +import org.compiere.model.I_AD_Val_Rule; +import org.compiere.model.X_AD_Package_Exp_Detail; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.model.X_AD_Val_Rule; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class DynValRuleElementHandler extends AbstractElementHandler { + + private List rules = new ArrayList(); + + public void startElement(Properties ctx, Element element) throws SAXException { + String entitytype = getStringValue(element, "EntityType"); + if (isProcessElement(ctx, entitytype)) { + String name = getStringValue(element, "Name"); + + X_AD_Val_Rule mValRule = findPO(ctx, element); + if (mValRule == null) + { + int id = findIdByColumn(ctx, "AD_Val_Rule", "Name", name); + mValRule = new X_AD_Val_Rule(ctx, id > 0 ? id : 0, getTrxName(ctx)); + } + if (mValRule.getAD_Val_Rule_ID() == 0 && isOfficialId(element, "AD_Val_Rule_ID")) + mValRule.setAD_Val_Rule_ID(getIntValue(element, "AD_Val_Rule_ID")); + + List excludes = defaultExcludeList(X_AD_Val_Rule.Table_Name); + + PoFiller filler = new PoFiller(ctx, mValRule, element, this); + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + + if (mValRule.is_new() || mValRule.is_Changed()) { + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_Val_Rule.Table_Name, + X_AD_Val_Rule.Table_ID); + String action = null; + if (!mValRule.is_new()){ + backupRecord(ctx, impDetail.getAD_Package_Imp_Detail_ID(), X_AD_Val_Rule.Table_Name, mValRule); + action = "Update"; + } + else{ + action = "New"; + } + + if (mValRule.save(getTrxName(ctx)) == true){ + logImportDetail (ctx, impDetail, 1, mValRule.getName(), mValRule.get_ID(),action); + } + else{ + logImportDetail (ctx, impDetail, 0, mValRule.getName(), mValRule.get_ID(),action); + throw new POSaveFailedException("Failed to save dynamic validation rule."); + } + } + } else { + element.skip = true; + } + + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + protected void create(Properties ctx, TransformerHandler document) + throws SAXException { + int AD_Val_Rule_ID = Env.getContextAsInt(ctx, X_AD_Package_Exp_Detail.COLUMNNAME_AD_Val_Rule_ID); + if (rules.contains(AD_Val_Rule_ID)) + return; + rules.add(AD_Val_Rule_ID); + X_AD_Val_Rule m_ValRule = new X_AD_Val_Rule (ctx, AD_Val_Rule_ID, null); + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "table"); + document.startElement("","",I_AD_Val_Rule.Table_Name, atts); + createDynamicValidationRuleBinding(ctx,document,m_ValRule); + document.endElement("","",I_AD_Val_Rule.Table_Name); + + } + + private void createDynamicValidationRuleBinding(Properties ctx, TransformerHandler document, X_AD_Val_Rule m_ValRule) + { + PoExporter filler = new PoExporter(ctx, document, m_ValRule); + Listexcludes = defaultExcludeList(X_AD_Val_Rule.Table_Name); + + if (m_ValRule.getAD_Val_Rule_ID() <= PackOut.MAX_OFFICIAL_ID) + filler.add("AD_Val_Rule_ID", new AttributesImpl()); + + filler.export(excludes); + } + + + public void packOut(PackOut packout, TransformerHandler packoutHandler, TransformerHandler docHandler,int recordId) throws Exception + { + + Env.setContext(packout.getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_Val_Rule_ID, recordId); + + this.create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Val_Rule_ID); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/FieldElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/FieldElementHandler.java new file mode 100644 index 0000000000..e6f4087916 --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/FieldElementHandler.java @@ -0,0 +1,197 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.ElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.ReferenceUtils; +import org.adempiere.pipo2.exception.POSaveFailedException; +import org.compiere.model.I_AD_Field; +import org.compiere.model.I_AD_Tab; +import org.compiere.model.MField; +import org.compiere.model.X_AD_Field; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class FieldElementHandler extends AbstractElementHandler { + + public void startElement(Properties ctx, Element element) + throws SAXException { + String entitytype = getStringValue(element, "EntityType"); + if (isProcessElement(ctx, entitytype)) { + if (isParentDefer(element, I_AD_Tab.Table_Name)) { + element.defer = true; + return; + } + + Listexcludes = defaultExcludeList(X_AD_Field.Table_Name); + + int tabid = getParentId(element, I_AD_Tab.Table_Name) ; + if (tabid <= 0) { + element.defer = true; + return; + } + + MField mField = findPO(ctx, element); + if (mField == null) + { + int AD_Table_ID = ReferenceUtils.resolveReference(ctx, element.parent.properties.get("AD_Table_ID")); + Element columnElement = element.parent.properties.get("AD_Column_ID"); + int AD_Column_ID = 0; + if (ReferenceUtils.isIDLookup(columnElement) || ReferenceUtils.isUUIDLookup(columnElement)) + { + AD_Column_ID = ReferenceUtils.resolveReference(ctx, columnElement); + } + else + { + String colname = getStringValue(element, "AD_Column_ID", excludes); + AD_Column_ID = findIdByColumnAndParentId(ctx, "AD_Column", "ColumnName", colname, "AD_Table", AD_Table_ID); + } + + + StringBuffer sqlB = new StringBuffer( + "select AD_Field_ID from AD_Field where AD_Column_ID = ") + .append(AD_Column_ID) + .append(" and AD_Tab_ID = ?"); + int id = DB.getSQLValue(getTrxName(ctx), sqlB.toString(), tabid); + mField = new MField(ctx, id > 0 ? id : 0, getTrxName(ctx)); + if (mField.is_new()) { + mField.setAD_Column_ID(AD_Column_ID); + mField.setAD_Tab_ID(tabid); + } + } + PoFiller filler = new PoFiller(ctx, mField, element, this); + if (mField.getAD_Field_ID() == 0 && isOfficialId(element, "AD_Field_ID")) + { + filler.setInteger("AD_Field_ID"); + } + + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + + if (mField.is_new() || mField.is_Changed()) { + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_Field.Table_Name, + X_AD_Field.Table_ID); + String action = null; + if (!mField.is_new()){ + backupRecord(ctx, impDetail.getAD_Package_Imp_Detail_ID(), I_AD_Field.Table_Name, mField); + action = "Update"; + } + else{ + action = "New"; + } + + if (mField.save(getTrxName(ctx)) == true) { + logImportDetail(ctx, impDetail, 1, mField.getName(), mField + .get_ID(), action); + element.recordId = mField.getAD_Field_ID(); + } else { + logImportDetail(ctx, impDetail, 0, mField.getName(), mField + .get_ID(), action); + throw new POSaveFailedException("Failed to save field definition."); + } + } + } else { + element.skip = true; + } + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int AD_Field_ID = Env.getContextAsInt(ctx, + X_AD_Field.COLUMNNAME_AD_Field_ID); + X_AD_Field m_Field = new X_AD_Field(ctx, AD_Field_ID, null); + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "table"); + document.startElement("", "", I_AD_Field.Table_Name, atts); + createFieldBinding(ctx, document, m_Field); + + PackOut packOut = (PackOut)ctx.get("PackOutProcess"); + + try + { + if(m_Field.getAD_FieldGroup_ID() > 0) + { + ElementHandler handler = packOut.getHandler("FG"); + handler.packOut(packOut,document,null,m_Field.getAD_FieldGroup_ID()); + } + + if (m_Field.getAD_Reference_ID()>0) + { + ElementHandler handler = packOut.getHandler("REF"); + handler.packOut(packOut,document,null,m_Field.getAD_Reference_ID()); + } + + if (m_Field.getAD_Reference_Value_ID()>0) + { + ElementHandler handler = packOut.getHandler("REF"); + handler.packOut(packOut,document,null,m_Field.getAD_Reference_Value_ID()); + } + + if (m_Field.getAD_Val_Rule_ID()>0) + { + ElementHandler handler = packOut.getHandler("V"); + handler.packOut(packOut,document,null,m_Field.getAD_Val_Rule_ID()); + } + } + catch(Exception e) + { + log.info(e.toString()); + } + + document.endElement("", "", I_AD_Field.Table_Name); + } + + private void createFieldBinding(Properties ctx, TransformerHandler document, + X_AD_Field m_Field) { + + List excludes = defaultExcludeList(X_AD_Field.Table_Name); + PoExporter filler = new PoExporter(ctx, document, m_Field); + if (m_Field.getAD_Field_ID() <= PackOut.MAX_OFFICIAL_ID) { + filler.add("AD_Field_ID", new AttributesImpl()); + } + + filler.export(excludes); + } + + @Override + public void packOut(PackOut packout, TransformerHandler packoutHandler, + TransformerHandler docHandler, + int recordId) throws Exception { + Env.setContext(packout.getCtx(), I_AD_Field.COLUMNNAME_AD_Field_ID, recordId); + create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(I_AD_Field.COLUMNNAME_AD_Field_ID); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/FieldGroupElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/FieldGroupElementHandler.java new file mode 100644 index 0000000000..b4080fb3a1 --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/FieldGroupElementHandler.java @@ -0,0 +1,165 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Igor G. - progerpro@gmail.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + + +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.exception.POSaveFailedException; +import org.compiere.model.I_AD_FieldGroup; +import org.compiere.model.X_AD_FieldGroup; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class FieldGroupElementHandler extends AbstractElementHandler { + + + private List processedFieldGroups = new ArrayList(); + + + public void startElement(Properties ctx, Element element) + throws SAXException { + String elementValue = element.getElementValue(); + String action = null; + + log.info(elementValue + " " + getStringValue(element, "Name")); + + String entitytype = getStringValue(element, "EntityType"); + String name = getStringValue(element, "Name"); + + if (isProcessElement(ctx, entitytype)) { + + X_AD_FieldGroup fieldGroup = findPO(ctx, element); + if (fieldGroup == null) + { + int id = findIdByColumn(ctx, X_AD_FieldGroup.Table_Name, X_AD_FieldGroup.COLUMNNAME_Name, name); + fieldGroup = new X_AD_FieldGroup(ctx, id > 0 ? id : 0, getTrxName(ctx)); + } + PoFiller pf = new PoFiller(ctx, fieldGroup, element, this); + List excludes = defaultExcludeList(X_AD_FieldGroup.Table_Name); + if (fieldGroup.getAD_FieldGroup_ID() == 0 && isOfficialId(element, "AD_FieldGroup_ID")) + { + pf.setInteger("AD_FieldGroup_ID"); + } + + if (processedFieldGroups.contains(fieldGroup.getAD_FieldGroup_ID())) { + element.skip = true; + return; + } + + List notfounds = pf.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + + if (fieldGroup.is_new() || fieldGroup.is_Changed()) { + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_FieldGroup.Table_Name, + X_AD_FieldGroup.Table_ID); + if (!fieldGroup.is_new()) { + backupRecord(ctx, impDetail.getAD_Package_Imp_Detail_ID(), X_AD_FieldGroup.Table_Name, fieldGroup); + action = "Update"; + } else { + action = "New"; + } + + if (fieldGroup.save(getTrxName(ctx)) == true) { + logImportDetail(ctx, impDetail, 1, fieldGroup.getName(), + fieldGroup.get_ID(), action); + + element.recordId = fieldGroup.getAD_FieldGroup_ID(); + + processedFieldGroups.add(fieldGroup.getAD_FieldGroup_ID()); + + } else { + logImportDetail(ctx, impDetail, 0, fieldGroup.getName(), + fieldGroup.get_ID(), action); + throw new POSaveFailedException("Reference"); + } + } + } else { + element.skip = true; + } + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + protected void create(Properties ctx, TransformerHandler document) + throws SAXException { + + + int fieldGroup_id = Env.getContextAsInt(ctx, + X_AD_FieldGroup.COLUMNNAME_AD_FieldGroup_ID); + + if (processedFieldGroups.contains(fieldGroup_id)) + return; + + processedFieldGroups.add(fieldGroup_id); + + X_AD_FieldGroup fieldGroup = new X_AD_FieldGroup(ctx, fieldGroup_id, null); + + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "table"); + document.startElement("", "", I_AD_FieldGroup.Table_Name, atts); + + createAdElementBinding(ctx, document, fieldGroup); + + PackOut packOut = (PackOut)ctx.get("PackOutProcess"); + + try{ + new CommonTranslationHandler().packOut(packOut,document,null,fieldGroup.get_ID()); + } + catch(Exception e) + { + log.info(e.toString()); + } + document.endElement("", "", I_AD_FieldGroup.Table_Name); + } + + + private void createAdElementBinding(Properties ctx, TransformerHandler document, + X_AD_FieldGroup fieldGroup) { + + PoExporter filler = new PoExporter(ctx, document, fieldGroup); + List excludes = defaultExcludeList(X_AD_FieldGroup.Table_Name); + if (fieldGroup.getAD_FieldGroup_ID() <= PackOut.MAX_OFFICIAL_ID) { + filler.add(X_AD_FieldGroup.COLUMNNAME_AD_FieldGroup_ID, new AttributesImpl()); + } + + filler.export(excludes); + } + + public void packOut(PackOut packout, TransformerHandler packoutHandler, TransformerHandler docHandler,int recordId) throws Exception + { + Env.setContext(packout.getCtx(), X_AD_FieldGroup.COLUMNNAME_AD_FieldGroup_ID, recordId); + + this.create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(X_AD_FieldGroup.COLUMNNAME_AD_FieldGroup_ID); + } +} \ No newline at end of file diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/FileElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/FileElementHandler.java new file mode 100644 index 0000000000..176b1ae8fd --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/FileElementHandler.java @@ -0,0 +1,97 @@ +package org.adempiere.pipo2.handler; + +import java.io.File; +import java.util.Properties; +import java.util.logging.Level; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.exceptions.AdempiereException; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.ElementHandler; +import org.adempiere.pipo2.PackOut; +import org.compiere.model.MPackageExp; +import org.compiere.model.MPackageExpDetail; +import org.compiere.util.CLogger; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class FileElementHandler implements ElementHandler { + + private CLogger log = CLogger.getCLogger(FileElementHandler.class); + + public void packOut(PackOut packout, TransformerHandler packoutHandler, + TransformerHandler docHandler, int recordId) throws Exception { + MPackageExp header = packout.getPackageExp(); + MPackageExpDetail detail = packout.getPackageExpDetail(); + log.log(Level.INFO, + "In PackOut.java handling Code or Other 2pack module creation"); + String fileDirectory = header.getFile_Directory() + header.getName() + + detail.getTarget_Directory(); + log.log(Level.INFO, "targetDirectory" + fileDirectory); + String targetDirectory = null; + char fileseperator1 = '/'; + char fileseperator2 = '\\'; + // Correct package for proper file seperator + if (File.separator.equals("/")) { + targetDirectory = fileDirectory.replace(fileseperator2, + fileseperator1); + } else + targetDirectory = fileDirectory.replace(fileseperator1, + fileseperator2); + + String sourceDirectory = null; + fileDirectory = detail.getFile_Directory(); + // Correct package for proper file seperator + if (File.separator.equals("/")) { + sourceDirectory = fileDirectory.replace(fileseperator2, + fileseperator1); + } else + sourceDirectory = fileDirectory.replace(fileseperator2, + fileseperator1); + + packout.copyFile(sourceDirectory + detail.getFileName(), + targetDirectory + detail.getFileName()); + + AttributesImpl atts = new AttributesImpl(); + + if (detail.getDestination_Directory() != null) { + + fileDirectory = detail.getDestination_Directory(); + String destinationDirectory = null; + + // Correct package for proper file seperator + if (File.separator.equals("/")) { + destinationDirectory = fileDirectory.replace(fileseperator2, + fileseperator1); + } else + destinationDirectory = fileDirectory.replace(fileseperator2, + fileseperator1); + + try { + new DistFileElementHandler(destinationDirectory).doPackout( + packout, null, detail, packoutHandler, null, null, 0); + } catch (Exception e) { + throw new AdempiereException(e.getLocalizedMessage(), e); + } + } + + if (detail.getFileName() != null) { + PackOut.addTextElement(docHandler, "file", + "File: " + detail.getFileName(), atts); + } + PackOut.addTextElement(docHandler, "filedirectory", "Directory: " + + detail.getTarget_Directory(), atts); + PackOut.addTextElement(docHandler, "filenotes", + "Notes: " + detail.getDescription(), atts); + } + + @Override + public void startElement(Properties ctx, Element element) + throws SAXException { + } + + @Override + public void endElement(Properties ctx, Element element) throws SAXException { + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/FormAccessElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/FormAccessElementHandler.java new file mode 100644 index 0000000000..de5cb266ea --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/FormAccessElementHandler.java @@ -0,0 +1,125 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.ReferenceUtils; +import org.compiere.model.I_AD_Form_Access; +import org.compiere.model.I_AD_Role; +import org.compiere.model.MFormAccess; +import org.compiere.model.Query; +import org.compiere.model.X_AD_Form; +import org.compiere.model.X_AD_Form_Access; +import org.compiere.model.X_AD_Role; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class FormAccessElementHandler extends AbstractElementHandler { + + public void startElement(Properties ctx, Element element) throws SAXException { + List excludes = defaultExcludeList(X_AD_Form_Access.Table_Name); + + MFormAccess po = findPO(ctx, element); + if (po == null) { + int AD_Role_ID = 0; + if (getParentId(element, I_AD_Role.Table_Name) > 0) { + AD_Role_ID = getParentId(element, I_AD_Role.Table_Name); + } else { + AD_Role_ID = ReferenceUtils.resolveReference(ctx, element.properties.get("AD_Role_ID")); + } + if (AD_Role_ID <= 0) + { + element.defer = true; + return; + } + + int AD_Form_ID = ReferenceUtils.resolveReference(ctx, element.properties.get("AD_Form_ID")); + if (AD_Form_ID <= 0) + { + element.defer = true; + return; + } + + Query query = new Query(ctx, "AD_Form_Access", "AD_Form_ID = ? AND AD_Role_ID = ?", getTrxName(ctx)); + po = query.setParameters(new Object[]{AD_Form_ID, AD_Role_ID}) + .setClient_ID() + .first(); + if (po == null) + { + po = new MFormAccess(ctx, 0, null); + po.setAD_Form_ID(AD_Form_ID); + po.setAD_Role_ID(AD_Role_ID); + } + + excludes.add("AD_Form_ID"); + excludes.add("AD_Role_ID"); + } + + PoFiller filler = new PoFiller(ctx, po, element, this); + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + po.saveEx(); + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int AD_Form_ID = Env.getContextAsInt(ctx, X_AD_Form.COLUMNNAME_AD_Form_ID); + int AD_Role_ID = Env.getContextAsInt(ctx, X_AD_Role.COLUMNNAME_AD_Role_ID); + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "table"); + document.startElement("", "", I_AD_Form_Access.Table_Name, atts); + createFormAccessBinding(ctx, document, AD_Form_ID, AD_Role_ID); + document.endElement("", "", I_AD_Form_Access.Table_Name); + } + + private void createFormAccessBinding(Properties ctx, TransformerHandler document, + int formId, int roleId) { + MFormAccess po = null; + Query query = new Query(ctx, "AD_Form_Access", "AD_Form_ID = ? AND AD_Role_ID = ?", getTrxName(ctx)); + po = query.setParameters(new Object[]{formId, roleId}).first(); + if (po != null) { + PoExporter filler = new PoExporter(ctx, document, po); + List excludes = defaultExcludeList(X_AD_Form_Access.Table_Name); + filler.export(excludes); + } + } + + @Override + public void packOut(PackOut packout, TransformerHandler packoutHandler, + TransformerHandler docHandler, + int recordId) throws Exception { + // TODO Auto-generated method stub + + } + +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/FormElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/FormElementHandler.java new file mode 100644 index 0000000000..f838389294 --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/FormElementHandler.java @@ -0,0 +1,128 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + + +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.exception.POSaveFailedException; +import org.compiere.model.I_AD_Form; +import org.compiere.model.MForm; +import org.compiere.model.X_AD_Form; +import org.compiere.model.X_AD_Package_Exp_Detail; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class FormElementHandler extends AbstractElementHandler { + + private List forms = new ArrayList(); + + public void startElement(Properties ctx, Element element) throws SAXException { + List excludes = defaultExcludeList(X_AD_Form.Table_Name); + + String entitytype = getStringValue(element, "EntityType"); + if (isProcessElement(ctx, entitytype)) { + MForm mForm = findPO(ctx, element); + if (mForm == null) { + String name = getStringValue(element, "Name"); + int id = findIdByName(ctx, "AD_Form", name); + mForm = new MForm(ctx, id > 0 ? id : 0, getTrxName(ctx)); + } + PoFiller filler = new PoFiller(ctx, mForm, element, this); + + if (mForm.getAD_Form_ID() == 0 && isOfficialId(element, "AD_Form_ID")) + { + filler.setInteger("AD_Form_ID"); + } + + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + + if (mForm.is_new() || mForm.is_Changed()) { + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_Form.Table_Name, + X_AD_Form.Table_ID); + String action = null; + if (!mForm.is_new()){ + backupRecord(ctx, impDetail.getAD_Package_Imp_Detail_ID(), X_AD_Form.Table_Name, mForm); + action = "Update"; + } + else{ + action = "New"; + } + + if (mForm.save(getTrxName(ctx)) == true){ + logImportDetail (ctx, impDetail, 1, mForm.getName(), mForm.get_ID(), action); + } + else{ + logImportDetail (ctx, impDetail, 0, mForm.getName(), mForm.get_ID(), action); + throw new POSaveFailedException("Failed to save form definition"); + } + } + } else { + element.skip = true; + } + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + protected void create(Properties ctx, TransformerHandler document) + throws SAXException { + int AD_Form_ID = Env.getContextAsInt(ctx, "AD_Form_ID"); + if (forms.contains(AD_Form_ID)) return; + + forms.add(AD_Form_ID); + X_AD_Form m_Form = new X_AD_Form (ctx, AD_Form_ID, null); + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "table"); + document.startElement("","",I_AD_Form.Table_Name,atts); + createFormBinding(ctx, document, m_Form); + document.endElement("","",I_AD_Form.Table_Name); + } + + private void createFormBinding(Properties ctx, TransformerHandler document, X_AD_Form m_Form) + { + PoExporter filler = new PoExporter(ctx, document, m_Form); + List excludes = defaultExcludeList(X_AD_Form.Table_Name); + if (m_Form.getAD_Form_ID() <= PackOut.MAX_OFFICIAL_ID) { + filler.add("AD_Form_ID", new AttributesImpl()); + } + filler.export(excludes); + } + + + public void packOut(PackOut packout, TransformerHandler packoutHandler, TransformerHandler docHandler,int recordId) throws Exception + { + Env.setContext(packout.getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_Form_ID, recordId); + this.create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Form_ID); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/GenericPOElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/GenericPOElementHandler.java new file mode 100644 index 0000000000..91ee290fba --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/GenericPOElementHandler.java @@ -0,0 +1,219 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com * + * Contributor(s): Low Heng Sin hengsin@avantz.com * + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.exceptions.AdempiereException; +import org.adempiere.model.GenericPO; +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.compiere.model.MColumn; +import org.compiere.model.MPackageExpDetail; +import org.compiere.model.MRole; +import org.compiere.model.MTable; +import org.compiere.model.PO; +import org.compiere.model.POInfo; +import org.compiere.model.Query; +import org.compiere.model.X_AD_Package_Exp_Detail; +import org.compiere.util.DB; +import org.compiere.util.DisplayType; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +/** + * + * @author Robert Klein. + * @author Low Heng Sin + * + */ +public class GenericPOElementHandler extends AbstractElementHandler { + + public GenericPOElementHandler() { + } + + public void startElement(Properties ctx, Element element) throws SAXException { + String tableName = element.getElementValue(); + + PO po = findPO(ctx, element); + if (po == null) { + MTable table = MTable.get(ctx, tableName); + POInfo info = POInfo.getPOInfo(ctx, table.getAD_Table_ID()); + MColumn columns[] = table.getColumns(false); + StringBuffer whereClause = new StringBuffer(); + List parameters = new ArrayList(); + for(int i = 0; i < columns.length; i++) { + MColumn column = columns[i]; + if (column.isIdentifier()) { + if (whereClause.length() > 0) + whereClause.append(" AND "); + whereClause.append(column.getColumnName()).append(" = ? "); + parameters.add(getStringValue(element, column.getColumnName())); + } else if (column.isParent()) { + int parentId = 0; + String parentTableName = null; + if (column.getAD_Reference_ID() == DisplayType.TableDir) { + parentTableName = column.getColumnName().substring(0, column.getColumnName().length() - 3); + } else { + String searchColumn = info.getColumnLookup(i).getColumnName(); + parentTableName = searchColumn.substring(0, searchColumn.indexOf(".")); + } + + Element parent = element.parent; + while (parent != null) { + if (parent.getElementValue().equalsIgnoreCase(parentTableName)) { + parentId = parent.recordId; + break; + } + parent = parent.parent; + } + if (parentId > 0) { + if (whereClause.length() > 0) + whereClause.append(" AND "); + whereClause.append(column.getColumnName()).append(" = ?"); + parameters.add(parentId); + } + } + } + Query query = new Query(ctx, table, whereClause.toString(), getTrxName(ctx)); + po = query.setParameters(parameters).first(); + if (po == null) { + po = new GenericPO(tableName, ctx, 0); + } + } + PoFiller filler = new PoFiller(ctx, po, element, this); + List excludes = defaultExcludeList(tableName); + if (po.get_ID() == 0) { + Element idElement = element.properties.get(tableName + "_ID"); + if (idElement != null && idElement.contents != null && idElement.contents.length() > 0) { + int id = 0; + try { + id = Integer.parseInt(idElement.contents.toString()); + if (id > 0 && id <= PackOut.MAX_OFFICIAL_ID) { + po.set_ValueOfColumn(tableName + "_ID", id); + } + } catch (Exception e) {} + } + } + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + po.saveEx(); + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + AttributesImpl atts = new AttributesImpl(); + + String sql = Env.getContext(ctx, X_AD_Package_Exp_Detail.COLUMNNAME_SQLStatement); + String components[] = null; + if (sql.indexOf(";") > 0) { + components = sql.split("[;]"); + sql = components[0]; + } else { + components = new String[]{sql}; + } + int tableId = Env.getContextAsInt(ctx, X_AD_Package_Exp_Detail.COLUMNNAME_AD_Table_ID); + String tableName = MTable.getTableName(ctx, tableId); + List excludes = defaultExcludeList(tableName); + Statement stmt = null; + ResultSet rs = null; + try { + sql = MRole.getDefault().addAccessSQL(sql, tableName, true, true); + stmt = DB.createStatement(); + rs = stmt.executeQuery(sql); + while (rs.next()) { + GenericPO po = new GenericPO(tableName, ctx, rs); + int AD_Client_ID = po.getAD_Client_ID(); + if (AD_Client_ID != Env.getAD_Client_ID(ctx)) + continue; + addTypeName(atts, "table"); + document.startElement("","", tableName, atts); + PoExporter filler = new PoExporter(ctx, document, po); + filler.export(excludes); + + for (int i = 1; i < components.length; i++) { + String tables[] = components[i].split("[>]"); + exportDetail(ctx, document, po, 0, tables); + } + document.endElement("","",tableName); + } + } catch (Exception e) { + throw new AdempiereException(e); + } finally { + DB.close(rs, stmt); + } + } + + private void exportDetail(Properties ctx, TransformerHandler document, GenericPO parent, int index, String[] tables) { + AttributesImpl atts = new AttributesImpl(); + String sql = "SELECT * FROM " + tables[index] + " WHERE " + parent.get_TableName() + "_ID = ?"; + PreparedStatement pstmt = null; + ResultSet rs = null; + try { + sql = MRole.getDefault().addAccessSQL(sql, tables[index], true, true); + pstmt = DB.prepareStatement(sql, null); + pstmt.setInt(1, parent.get_ID()); + rs = pstmt.executeQuery(); + while (rs.next()) { + GenericPO po = new GenericPO(tables[index], ctx, rs); + int AD_Client_ID = po.getAD_Client_ID(); + if (AD_Client_ID != Env.getAD_Client_ID(ctx)) + continue; + List excludes = defaultExcludeList(tables[index]); + document.startElement("", "", tables[index], atts); + PoExporter filler = new PoExporter(ctx, document, po); + filler.export(excludes); + if (index + 1 < tables.length) { + exportDetail(ctx, document, po, index+1, tables); + } + document.endElement("","",tables[index]); + } + } catch (Exception e) { + throw new AdempiereException(e); + } finally { + DB.close(rs, pstmt); + } + + } + + public void packOut(PackOut packout, TransformerHandler packoutHandler, TransformerHandler docHandler,int recordId) throws Exception + { + MPackageExpDetail detail = packout.getPackageExpDetail(); + Env.setContext(packout.getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_Table_ID, detail.getAD_Table_ID()); + Env.setContext(packout.getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_SQLStatement, detail.getSQLStatement()); + this.create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Table_ID); + packout.getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_SQLStatement); + } +} \ No newline at end of file diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/ImpFormatElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/ImpFormatElementHandler.java new file mode 100644 index 0000000000..50a5bd205f --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/ImpFormatElementHandler.java @@ -0,0 +1,163 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import java.util.logging.Level; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.exception.DatabaseAccessException; +import org.adempiere.pipo2.exception.POSaveFailedException; +import org.compiere.model.I_AD_ImpFormat; +import org.compiere.model.X_AD_ImpFormat; +import org.compiere.model.X_AD_ImpFormat_Row; +import org.compiere.model.X_AD_Package_Exp_Detail; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class ImpFormatElementHandler extends AbstractElementHandler { + + private ImpFormatRowElementHandler rowHandler = new ImpFormatRowElementHandler(); + + private List formats = new ArrayList(); + + public void startElement(Properties ctx, Element element) + throws SAXException { + + List excludes = defaultExcludeList(X_AD_ImpFormat.Table_Name); + String name = getStringValue(element, "Name"); + + X_AD_ImpFormat mImpFormat = findPO(ctx, element); + if (mImpFormat == null) { + int id = findIdByName(ctx, "AD_ImpFormat", name); + mImpFormat = new X_AD_ImpFormat(ctx, id > 0 ? id : 0, + getTrxName(ctx)); + } + PoFiller filler = new PoFiller(ctx, mImpFormat, element, this); + + if (mImpFormat.getAD_ImpFormat_ID() == 0 && isOfficialId(element, "AD_ImpFormat_ID")) + { + filler.setInteger("AD_ImpFormat_ID"); + } + + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + + if (mImpFormat.is_new() || mImpFormat.is_Changed()) { + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_ImpFormat.Table_Name, + X_AD_ImpFormat.Table_ID); + String action = null; + if (!mImpFormat.is_new()) { + backupRecord(ctx, impDetail.getAD_Package_Imp_Detail_ID(), X_AD_ImpFormat.Table_Name, mImpFormat); + action = "Update"; + } else { + action = "New"; + } + if (mImpFormat.save(getTrxName(ctx)) == true) { + logImportDetail(ctx, impDetail, 1, mImpFormat.getName(), mImpFormat + .get_ID(), action); + } else { + logImportDetail(ctx, impDetail, 0, mImpFormat.getName(), mImpFormat + .get_ID(), action); + throw new POSaveFailedException("Failed to save Import Format."); + } + } + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + protected void create(Properties ctx, TransformerHandler document) + throws SAXException { + int import_id = Env.getContextAsInt(ctx, + X_AD_Package_Exp_Detail.COLUMNNAME_AD_ImpFormat_ID); + + if (formats.contains(import_id)) + return; + formats.add(import_id); + AttributesImpl atts = new AttributesImpl(); + X_AD_ImpFormat m_ImpFormat = new X_AD_ImpFormat(ctx, import_id, null); + addTypeName(atts, "table"); + document.startElement("", "", I_AD_ImpFormat.Table_Name, atts); + createImpFormatBinding(ctx, document, m_ImpFormat); + + String sql = "SELECT * FROM AD_ImpFormat_Row WHERE AD_ImpFormat_ID= " + + import_id; + + PreparedStatement pstmt = null; + ResultSet rs = null; + + try { + pstmt = DB.prepareStatement(sql, getTrxName(ctx)); + rs = pstmt.executeQuery(); + while (rs.next()) { + createImpFormatRow(ctx, document, rs + .getInt("AD_ImpFormat_Row_ID")); + } + } catch (Exception e) { + log.log(Level.SEVERE, "ImpFormat", e); + throw new DatabaseAccessException("Failed to export Import Format.", e); + } finally { + DB.close(rs, pstmt); + } + document.endElement("", "", I_AD_ImpFormat.Table_Name); + + } + + private void createImpFormatRow(Properties ctx, + TransformerHandler document, int AD_ImpFormat_Row_ID) + throws SAXException { + Env.setContext(ctx, X_AD_ImpFormat_Row.COLUMNNAME_AD_ImpFormat_Row_ID, + AD_ImpFormat_Row_ID); + rowHandler.create(ctx, document); + ctx.remove(X_AD_ImpFormat_Row.COLUMNNAME_AD_ImpFormat_Row_ID); + } + + private void createImpFormatBinding(Properties ctx, TransformerHandler document, + X_AD_ImpFormat m_ImpFormat) { + PoExporter filler = new PoExporter(ctx, document, m_ImpFormat); + List excludes = defaultExcludeList(X_AD_ImpFormat.Table_Name); + if (m_ImpFormat.getAD_ImpFormat_ID() <= PackOut.MAX_OFFICIAL_ID) + { + filler.add("AD_ImpFormat_ID", new AttributesImpl()); + } + filler.export(excludes); + } + + public void packOut(PackOut packout, TransformerHandler packoutHandler, TransformerHandler docHandler,int recordId) throws Exception + { + Env.setContext(packout.getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_ImpFormat_ID, recordId); + this.create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_ImpFormat_ID); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/ImpFormatRowElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/ImpFormatRowElementHandler.java new file mode 100644 index 0000000000..5355949df5 --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/ImpFormatRowElementHandler.java @@ -0,0 +1,181 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.ReferenceUtils; +import org.adempiere.pipo2.exception.POSaveFailedException; +import org.compiere.model.I_AD_ImpFormat; +import org.compiere.model.I_AD_ImpFormat_Row; +import org.compiere.model.X_AD_ImpFormat_Row; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class ImpFormatRowElementHandler extends AbstractElementHandler { + + public void startElement(Properties ctx, Element element) throws SAXException { + + String action = null; + List excludes = defaultExcludeList(X_AD_ImpFormat_Row.Table_Name); + + if (isParentDefer(element, I_AD_ImpFormat.Table_Name)) { + element.defer = true; + return; + } + + X_AD_ImpFormat_Row mImpFormatRow = findPO(ctx, element); + if (mImpFormatRow == null) { + int impFormatId = 0; + if (getParentId(element, I_AD_ImpFormat.Table_Name) > 0) { + impFormatId = getParentId(element, I_AD_ImpFormat.Table_Name); + } else { + Element e = element.properties.get(I_AD_ImpFormat_Row.COLUMNNAME_AD_ImpFormat_ID); + if (ReferenceUtils.isIDLookup(e) || ReferenceUtils.isUUIDLookup(e)) + impFormatId = ReferenceUtils.resolveReference(ctx, e); + else + impFormatId = findIdByName(ctx, "AD_ImpFormat", e.contents.toString()); + } + + if (impFormatId <= 0) { + element.defer = true; + return; + } + + Element tableElement = element.properties.get(I_AD_ImpFormat.COLUMNNAME_AD_Table_ID); + int tableId = 0; + if (ReferenceUtils.isIDLookup(tableElement) || ReferenceUtils.isUUIDLookup(tableElement)) { + tableId = ReferenceUtils.resolveReference(ctx, tableElement); + } else { + String tableName = getStringValue(element, I_AD_ImpFormat.COLUMNNAME_AD_Table_ID, excludes); + + if (tableName != null && tableName.trim().length() > 0) { + tableId = findIdByColumn(ctx, "AD_Table", "TableName", tableName); + } + if (tableId <= 0) { + element.defer = true; + return; + } + } + + Element columnElement = element.properties.get(I_AD_ImpFormat_Row.COLUMNNAME_AD_Column_ID); + int columnId = 0; + if (ReferenceUtils.isIDLookup(columnElement) || ReferenceUtils.isUUIDLookup(columnElement)) { + columnId = ReferenceUtils.resolveReference(ctx, columnElement); + } else { + String columnName = getStringValue(element, I_AD_ImpFormat_Row.COLUMNNAME_AD_Column_ID, excludes); + + if (columnName != null && columnName.trim().length() > 0) { + columnId = findIdByColumnAndParentId (ctx, "AD_Column","ColumnName", columnName, "AD_Table", tableId); + } + if (columnId <= 0) { + element.defer = true; + return; + } + } + + StringBuffer sqlB = new StringBuffer ("SELECT AD_ImpFormat_Row_ID FROM AD_ImpFormat_Row WHERE AD_Column_ID=? AND AD_ImpFormat_ID=?"); + int id = DB.getSQLValue(getTrxName(ctx),sqlB.toString(),columnId,impFormatId); + mImpFormatRow = new X_AD_ImpFormat_Row(ctx, id > 0 ? id : 0, getTrxName(ctx)); + + mImpFormatRow.setAD_Column_ID(columnId); + mImpFormatRow.setAD_ImpFormat_ID(impFormatId); + } + PoFiller filler = new PoFiller(ctx, mImpFormatRow, element, this); + if (mImpFormatRow.getAD_ImpFormat_Row_ID() == 0 && isOfficialId(element, "AD_ImpFormat_Row_ID")) + { + filler.setInteger("AD_ImpFormat_Row_ID"); + } + + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + + if (mImpFormatRow.is_new() || mImpFormatRow.is_Changed()) { + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_ImpFormat_Row.Table_Name, + X_AD_ImpFormat_Row.Table_ID); + if (!mImpFormatRow.is_new()){ + backupRecord(ctx, impDetail.getAD_Package_Imp_Detail_ID(), X_AD_ImpFormat_Row.Table_Name, mImpFormatRow); + action = "Update"; + } + else{ + action = "New"; + } + if (mImpFormatRow.save(getTrxName(ctx)) == true){ + logImportDetail (ctx, impDetail, 1, mImpFormatRow.getName(), mImpFormatRow.get_ID(),action); + } + else{ + logImportDetail (ctx, impDetail, 0, mImpFormatRow.getName(), mImpFormatRow.get_ID(),action); + throw new POSaveFailedException("Failed to import Import Format Row."); + } + } + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int AD_ImpFormat_Row_ID = Env.getContextAsInt(ctx, X_AD_ImpFormat_Row.COLUMNNAME_AD_ImpFormat_Row_ID); + X_AD_ImpFormat_Row m_ImpFormat_Row = new X_AD_ImpFormat_Row (ctx, AD_ImpFormat_Row_ID, getTrxName(ctx)); + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "table"); + document.startElement("","",I_AD_ImpFormat_Row.Table_Name,atts); + createImpFormatRowBinding(ctx,document,m_ImpFormat_Row); + document.endElement("","",I_AD_ImpFormat_Row.Table_Name); + } + + private void createImpFormatRowBinding(Properties ctx, TransformerHandler document, X_AD_ImpFormat_Row m_ImpFormat_Row) + { + PoExporter filler = new PoExporter(ctx, document, m_ImpFormat_Row); + List excludes = defaultExcludeList(X_AD_ImpFormat_Row.Table_Name); + + String sql = null; + + int tableId = DB.getSQLValue(null, sql,m_ImpFormat_Row.getAD_Column_ID()); + filler.addTableReference("AD_Table_ID", "AD_Table", "TableName", tableId, new AttributesImpl()); + + if (m_ImpFormat_Row.getAD_ImpFormat_Row_ID() <= PackOut.MAX_OFFICIAL_ID) + { + filler.add("AD_ImpFormat_Row_ID", new AttributesImpl()); + } + + filler.export(excludes); + } + + @Override + public void packOut(PackOut packout, TransformerHandler packoutHandler, + TransformerHandler docHandler, + int recordId) throws Exception { + Env.setContext(packout.getCtx(), I_AD_ImpFormat_Row.COLUMNNAME_AD_ImpFormat_Row_ID, recordId); + create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(I_AD_ImpFormat_Row.COLUMNNAME_AD_ImpFormat_Row_ID); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/MenuElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/MenuElementHandler.java new file mode 100644 index 0000000000..d6b4502171 --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/MenuElementHandler.java @@ -0,0 +1,367 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.util.List; +import java.util.Properties; +import java.util.logging.Level; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.exceptions.DBException; +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.ElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.ReferenceUtils; +import org.compiere.model.I_AD_Menu; +import org.compiere.model.X_AD_Menu; +import org.compiere.model.X_AD_Package_Exp_Detail; +import org.compiere.model.X_AD_Package_Imp_Backup; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.model.X_AD_Task; +import org.compiere.model.X_AD_TreeNodeMM; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class MenuElementHandler extends AbstractElementHandler { + + public void startElement(Properties ctx, Element element) + throws SAXException { + + List excludes = defaultExcludeList(X_AD_Menu.Table_Name); + + X_AD_Menu mMenu = findPO(ctx, element); + if (mMenu == null) { + String menuName = getStringValue(element, "Name"); + int menuId = findIdByColumn(ctx, "AD_Menu", "Name", menuName); + mMenu = new X_AD_Menu(ctx, menuId > 0 ? menuId : 0, getTrxName(ctx)); + } + PoFiller filler = new PoFiller(ctx, mMenu, element, this); + + if (mMenu.getAD_Menu_ID() == 0 && isOfficialId(element, "AD_Menu_ID")) + { + filler.setInteger("AD_Menu_ID"); + } + + List notFounds = filler.autoFill(excludes); + if (notFounds.size() > 0) { + element.defer = true; + return; + } + + if (!mMenu.is_new() && !mMenu.is_Changed()) + return; + + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_Menu.Table_Name, + X_AD_Menu.Table_ID); + String action = null; + if (!mMenu.is_new()) { + backupRecord(ctx, impDetail.getAD_Package_Imp_Detail_ID(), X_AD_Menu.Table_Name, mMenu); + action = "Update"; + } else { + action = "New"; + } + if (mMenu.save(getTrxName(ctx)) == true) { + try { + logImportDetail(ctx, impDetail, 1, mMenu.getName(), mMenu + .get_ID(), action); + } catch (SAXException e) { + log.info("setmenu:" + e); + } + } else { + try { + logImportDetail(ctx, impDetail, 0, mMenu.getName(), mMenu + .get_ID(), action); + } catch (SAXException e) { + log.info("setmenu:" + e); + } + } + + Element parentElement = element.properties.get("Parent_ID"); + int parentId = 0; + if (ReferenceUtils.isIDLookup(parentElement) || ReferenceUtils.isUUIDLookup(parentElement)) { + parentId = ReferenceUtils.resolveReference(ctx, parentElement); + } else { + String parent = getStringValue(element, "Parent_ID"); + parentId = findIdByName(ctx, "AD_Menu", parent); + } + + StringBuffer updateSQL = null; + String sql = "SELECT count(Parent_ID) FROM AD_TREENODEMM WHERE AD_Tree_ID = 10" + + " AND Node_ID = " + mMenu.getAD_Menu_ID(); + int countRecords = DB.getSQLValue(getTrxName(ctx), sql); + if (countRecords > 0) { + sql = "select * from AD_TREENODEMM where AD_Tree_ID = 10 and " + + " Node_ID =?"; + PreparedStatement pstmt = null; + ResultSet rs = null; + try { + pstmt = DB.prepareStatement(sql, + getTrxName(ctx)); + pstmt.setInt(1, mMenu.getAD_Menu_ID()); + rs = pstmt.executeQuery(); + if (rs.next()) { + + String colValue = null; + ResultSetMetaData meta = rs.getMetaData(); + int columns = meta.getColumnCount(); + int tableID = X_AD_TreeNodeMM.Table_ID; + + for (int q = 1; q <= columns; q++) { + + String colName = meta.getColumnName(q).toUpperCase(); + sql = "SELECT AD_Column_ID FROM AD_column WHERE Upper(ColumnName) = ? AND AD_Table_ID = ?"; + int columnID = DB.getSQLValue(getTrxName(ctx), sql, colName, tableID); + sql = "SELECT AD_Reference_ID FROM AD_COLUMN WHERE AD_Column_ID = ?"; + int referenceID = DB.getSQLValue(getTrxName(ctx), sql, columnID); + if (referenceID == 20 || referenceID == 28) + if (rs.getObject(q).equals("Y")) + colValue = "true"; + else + colValue = "false"; + else + colValue = rs.getObject(q).toString(); + + X_AD_Package_Imp_Backup backup = new X_AD_Package_Imp_Backup(ctx, 0, getTrxName(ctx)); + backup.setAD_Package_Imp_Detail_ID(impDetail.getAD_Package_Imp_Detail_ID()); + backup.setAD_Package_Imp_ID(getPackageImpId(ctx)); + backup.setAD_Table_ID(tableID); + backup.setAD_Column_ID(columnID); + backup.setAD_Reference_ID(referenceID); + backup.setColValue(colValue); + backup.saveEx(); + } + + } + + } catch (Exception e) { + throw new DBException(e); + } finally { + DB.close(rs, pstmt); + } + + updateSQL = new StringBuffer("UPDATE AD_TREENODEMM ").append( + "SET Parent_ID = " + parentId).append( + " , SeqNo = " + getStringValue(element, "SeqNo")).append( + " WHERE AD_Tree_ID = 10").append( + " AND Node_ID = " + mMenu.getAD_Menu_ID()); + } else { + updateSQL = new StringBuffer("Insert INTO AD_TREENODEMM").append( + "(AD_Client_ID, AD_Org_ID, CreatedBy, UpdatedBy, ").append( + "Parent_ID, SeqNo, AD_Tree_ID, Node_ID)").append( + "VALUES(0, 0, 0, 0, ").append( + parentId + "," + getStringValue(element, "SeqNo") + ", 10, " + + mMenu.getAD_Menu_ID() + ")"); + } + DB.executeUpdateEx(updateSQL.toString(), getTrxName(ctx)); + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int AD_Menu_ID = Env.getContextAsInt(ctx, "AD_Menu_ID"); + X_AD_Menu m_Menu = new X_AD_Menu(ctx, AD_Menu_ID, null); + if (m_Menu.isSummary() == false) { + createApplication(ctx, document, AD_Menu_ID); + } else { + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "table"); + document.startElement("", "", I_AD_Menu.Table_Name, atts); + createMenuBinding(ctx, document, m_Menu); + createModule(ctx, document, AD_Menu_ID); + document.endElement("", "", I_AD_Menu.Table_Name); + } + } + + private void createMenuBinding(Properties ctx, TransformerHandler document, + X_AD_Menu m_Menu) { + + PoExporter filler = new PoExporter(ctx, document, m_Menu); + List excludes = defaultExcludeList(X_AD_Menu.Table_Name); + String sql = "SELECT Parent_ID FROM AD_TreeNoDemm WHERE AD_Tree_ID = 10 and Node_ID=?"; + int id = DB.getSQLValue(null, sql, m_Menu.getAD_Menu_ID()); + if (id > 0) { + filler.addTableReference("Parent_ID", "AD_Menu", "Name", id, new AttributesImpl()); + } + sql = "SELECT SeqNo FROM AD_TreeNoDemm WHERE AD_Tree_ID = 10 and Node_ID=?"; + int seqNo = DB.getSQLValue(null, sql, m_Menu.getAD_Menu_ID()); + filler.addString("SeqNo", Integer.toString(seqNo), new AttributesImpl()); + if (m_Menu.getAD_Menu_ID() <= PackOut.MAX_OFFICIAL_ID) + filler.addString("AD_Menu_ID", Integer.toString(m_Menu.getAD_Menu_ID()), new AttributesImpl()); + + filler.export(excludes); + } + + private void createApplication(Properties ctx, TransformerHandler document, + int AD_Menu_ID) throws SAXException { + PackOut packOut = (PackOut)ctx.get("PackOutProcess"); + String sql = null; + // int x = 0; + sql = "SELECT A.Node_ID, B.AD_Menu_ID, B.Name, B.AD_WINDOW_ID, B.AD_WORKFLOW_ID, B.AD_TASK_ID, " + + "B.AD_PROCESS_ID, B.AD_FORM_ID, B.AD_WORKBENCH_ID " + + "FROM AD_TreeNoDemm A, AD_Menu B " + + "WHERE A.Node_ID = " + + AD_Menu_ID + " AND A.Node_ID = B.AD_Menu_ID"; + + AttributesImpl atts = new AttributesImpl(); + PreparedStatement pstmt = null; + ResultSet rs = null; + try { + pstmt = DB.prepareStatement(sql, getTrxName(ctx)); + rs = pstmt.executeQuery(); + while (rs.next()) { + + X_AD_Menu m_Menu = new X_AD_Menu(ctx, rs.getInt("AD_Menu_ID"), + null); + document.startElement("", "", I_AD_Menu.Table_Name, atts); + createMenuBinding(ctx, document, m_Menu); + if (rs.getInt("AD_WINDOW_ID") > 0 + || rs.getInt("AD_WORKFLOW_ID") > 0 + || rs.getInt("AD_TASK_ID") > 0 + || rs.getInt("AD_PROCESS_ID") > 0 + || rs.getInt("AD_FORM_ID") > 0) { + // Call CreateWindow. + if (rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Window_ID)>0) + { + ElementHandler handler = packOut.getHandler("W"); + handler.packOut(packOut,document,null,rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Window_ID)); + } + else if (rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Process_ID)>0) + { + ElementHandler handler = packOut.getHandler("P"); + handler.packOut(packOut,document,null,rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Process_ID)); + } else if (rs.getInt(X_AD_Task.COLUMNNAME_AD_Task_ID)>0) + { + ElementHandler handler = packOut.getHandler("ad.task"); + handler.packOut(packOut,document,null,rs.getInt(X_AD_Task.COLUMNNAME_AD_Task_ID)); + } + else if (rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Form_ID) > 0) + { + ElementHandler handler = packOut.getHandler("X"); + handler.packOut(packOut,document,null,rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Form_ID)); + } + else if (rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Workflow_ID) > 0) + { + ElementHandler handler = packOut.getHandler("F"); + handler.packOut(packOut,document,null,rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Workflow_ID)); + } + // Call CreateModule because entry is a summary menu + } else { + createModule(ctx, document, rs.getInt("Node_ID")); + } + document.endElement("", "", I_AD_Menu.Table_Name); + } + } catch (Exception e) { + log.log(Level.SEVERE, "getWindows", e); + throw new DBException(e); + } finally { + DB.close(rs, pstmt); + } + } + + public void createModule(Properties ctx, TransformerHandler document, + int menu_id) throws SAXException { + PackOut packOut = (PackOut)ctx.get("PackOutProcess"); + String sql = null; + sql = "SELECT A.Node_ID, B.AD_Menu_ID, B.Name, B.AD_WINDOW_ID, B.AD_WORKFLOW_ID, B.AD_TASK_ID, " + + "B.AD_PROCESS_ID, B.AD_FORM_ID, B.AD_WORKBENCH_ID " + + "FROM AD_TreeNoDemm A, AD_Menu B " + + "WHERE A.Parent_ID = " + + menu_id + " AND A.Node_ID = B.AD_Menu_ID"; + + AttributesImpl atts = new AttributesImpl(); + PreparedStatement pstmt = null; + ResultSet rs = null; + try { + pstmt = DB.prepareStatement(sql, getTrxName(ctx)); + rs = pstmt.executeQuery(); + while (rs.next()) { + // Menu tag Start. + X_AD_Menu m_Menu = new X_AD_Menu(ctx, rs.getInt("AD_Menu_ID"), + null); + document.startElement("", "", I_AD_Menu.Table_Name, atts); + createMenuBinding(ctx, document, m_Menu); + if (rs.getInt("AD_WINDOW_ID") > 0 + || rs.getInt("AD_WORKFLOW_ID") > 0 + || rs.getInt("AD_TASK_ID") > 0 + || rs.getInt("AD_PROCESS_ID") > 0 + || rs.getInt("AD_FORM_ID") > 0) { + // Call CreateWindow. + if (rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Window_ID)>0) + { + ElementHandler handler = packOut.getHandler("W"); + handler.packOut(packOut,document,null,rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Window_ID)); + } + else if (rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Process_ID)>0) + { + ElementHandler handler = packOut.getHandler("P"); + handler.packOut(packOut,document,null,rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Process_ID)); + } + else if (rs.getInt(X_AD_Task.COLUMNNAME_AD_Task_ID)>0) + { + ElementHandler handler = packOut.getHandler("K"); + handler.packOut(packOut,document,null,rs.getInt(X_AD_Task.COLUMNNAME_AD_Task_ID)); + } + else if (rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Form_ID) > 0) + { + ElementHandler handler = packOut.getHandler("X"); + handler.packOut(packOut,document,null,rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Form_ID)); + } + else if (rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Workflow_ID) > 0) + { + ElementHandler handler = packOut.getHandler("F"); + handler.packOut(packOut,document,null,rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Workflow_ID)); + } + // Call CreateModule because entry is a summary menu + } else { + createModule(ctx, document, rs.getInt("Node_ID")); + } + document.endElement("", "", I_AD_Menu.Table_Name); + } + } catch (Exception e) { + log.log(Level.SEVERE, "getWindows", e); + throw new DBException(e); + } finally { + DB.close(rs, pstmt); + } + } + + public void packOut(PackOut packout, TransformerHandler packoutHandler, TransformerHandler docHandler, int recordId) throws Exception + { + Env.setContext(packout.getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_Menu_ID, recordId); + this.create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Menu_ID); + } +} + + + + + + + + diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/MessageElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/MessageElementHandler.java new file mode 100644 index 0000000000..d59fa87a7e --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/MessageElementHandler.java @@ -0,0 +1,124 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.exception.POSaveFailedException; +import org.compiere.model.I_AD_Message; +import org.compiere.model.MMessage; +import org.compiere.model.X_AD_Message; +import org.compiere.model.X_AD_Package_Exp_Detail; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class MessageElementHandler extends AbstractElementHandler { + + private List messages = new ArrayList(); + + public void startElement(Properties ctx, Element element) throws SAXException { + String entitytype = getStringValue(element, "EntityType"); + if (isProcessElement(ctx, entitytype)) { + MMessage mMessage = findPO(ctx, element); + if (mMessage == null) { + String value = getStringValue(element, "Value"); + int id = findIdByColumn(ctx, "AD_Message", "value", value); + + mMessage = new MMessage(ctx, id > 0 ? id : 0, getTrxName(ctx)); + } + PoFiller filler = new PoFiller(ctx, mMessage, element, this); + List excludes = defaultExcludeList(X_AD_Message.Table_Name); + + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + + if (mMessage.is_new() || mMessage.is_Changed()) { + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_Message.Table_Name, + X_AD_Message.Table_ID); + String action = null; + if (mMessage.getAD_Message_ID() == 0 && isOfficialId(element, "AD_Message_ID")) + filler.setInteger("AD_Message_ID"); + + if (!mMessage.is_new()){ + backupRecord(ctx, impDetail.getAD_Package_Imp_Detail_ID(), X_AD_Message.Table_Name, mMessage); + action = "Update"; + } + else{ + action = "New"; + } + if (mMessage.save(getTrxName(ctx)) == true){ + logImportDetail (ctx, impDetail, 1, mMessage.getValue(), mMessage.get_ID(),action); + } + else{ + logImportDetail (ctx, impDetail, 0, mMessage.getValue(), mMessage.get_ID(),action); + throw new POSaveFailedException("Failed to save message."); + } + } + } else { + element.skip = true; + } + + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int AD_Message_ID = Env.getContextAsInt(ctx, X_AD_Package_Exp_Detail.COLUMNNAME_AD_Message_ID); + if (messages.contains(AD_Message_ID)) + return; + messages.add(AD_Message_ID); + AttributesImpl atts = new AttributesImpl(); + X_AD_Message m_Message = new X_AD_Message (ctx, AD_Message_ID, null); + addTypeName(atts, "table"); + document.startElement("","",I_AD_Message.Table_Name,atts); + createMessageBinding(ctx,document,m_Message); + document.endElement("","",I_AD_Message.Table_Name); + } + + private void createMessageBinding(Properties ctx, TransformerHandler document, X_AD_Message m_Message) + { + PoExporter filler = new PoExporter(ctx, document, m_Message); + if (m_Message.getAD_Message_ID() <= PackOut.MAX_OFFICIAL_ID) + filler.add("AD_Message_ID", new AttributesImpl()); + + List excludes = defaultExcludeList(X_AD_Message.Table_Name); + filler.export(excludes); + } + + public void packOut(PackOut packout, TransformerHandler packoutHandler, TransformerHandler docHandler,int recordId) throws Exception + { + Env.setContext(packout.getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_Message_ID, recordId); + this.create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Message_ID); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/OrgRoleElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/OrgRoleElementHandler.java new file mode 100644 index 0000000000..7d54500977 --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/OrgRoleElementHandler.java @@ -0,0 +1,120 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.ReferenceUtils; +import org.compiere.model.I_AD_Role; +import org.compiere.model.I_AD_Role_OrgAccess; +import org.compiere.model.Query; +import org.compiere.model.X_AD_Role; +import org.compiere.model.X_AD_Role_OrgAccess; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class OrgRoleElementHandler extends AbstractElementHandler { + + public void startElement(Properties ctx, Element element) throws SAXException { + List excludes = defaultExcludeList(X_AD_Role_OrgAccess.Table_Name); + + X_AD_Role_OrgAccess po = findPO(ctx, element); + if (po == null) { + int roleId = 0; + if (getParentId(element, I_AD_Role.Table_Name) > 0) { + roleId = getParentId(element, I_AD_Role.Table_Name); + } else { + Element roleElement = element.properties.get("AD_Role_ID"); + roleId = ReferenceUtils.resolveReference(ctx, roleElement); + } + + Element orgElement = element.properties.get("AD_Org_ID"); + int orgId = ReferenceUtils.resolveReference(ctx, orgElement); + + Query query = new Query(ctx, "AD_Role_OrgAccess", "AD_Role_ID=? and AD_Org_ID=?", getTrxName(ctx)); + po = query.setParameters(new Object[]{roleId, orgId}) + .setClient_ID() + .first(); + + if (po == null) { + po = new X_AD_Role_OrgAccess(ctx, 0, getTrxName(ctx)); + po.setAD_Org_ID(orgId); + po.setAD_Role_ID(roleId); + } + excludes.add("AD_Org_ID"); + excludes.add("AD_Role_ID"); + } + PoFiller filler = new PoFiller(ctx, po, element, this); + + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + po.saveEx(); + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int AD_Org_ID = Env.getContextAsInt(ctx, "AD_Org_ID"); + int AD_Role_ID = Env.getContextAsInt(ctx, X_AD_Role.COLUMNNAME_AD_Role_ID); + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "table"); + document.startElement("", "", I_AD_Role_OrgAccess.Table_Name, atts); + createOrgAccessBinding(ctx, document, AD_Org_ID, AD_Role_ID); + document.endElement("", "", I_AD_Role_OrgAccess.Table_Name); + + } + + private void createOrgAccessBinding(Properties ctx, TransformerHandler document, + int orgId, int roleId) { + Query query = new Query(ctx, "AD_Role_OrgAccess", "AD_Role_ID=? and AD_Org_ID=?", getTrxName(ctx)); + X_AD_Role_OrgAccess po = query.setParameters(new Object[]{roleId, orgId}).first(); + PoExporter filler = new PoExporter(ctx, document, po); + AttributesImpl orgRefAtts = new AttributesImpl(); + String orgReference = ReferenceUtils.getTableReference("AD_Org", "Name", orgId, orgRefAtts); + filler.addString("AD_Org_ID", orgReference, orgRefAtts); + + AttributesImpl roleRefAtts = new AttributesImpl(); + String roleReference = ReferenceUtils.getTableReference("AD_Role", "Name", roleId, roleRefAtts); + filler.addString("AD_Role_ID", roleReference, roleRefAtts); + + List excludes = defaultExcludeList(X_AD_Role_OrgAccess.Table_Name); + excludes.add("AD_Org_ID"); + excludes.add("AD_Role_ID"); + filler.export(excludes); + } + + @Override + public void packOut(PackOut packout, TransformerHandler packoutHandler, + TransformerHandler docHandler, + int recordId) throws Exception { + create(packout.getCtx(), packoutHandler); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/PreferenceElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/PreferenceElementHandler.java new file mode 100644 index 0000000000..341156315d --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/PreferenceElementHandler.java @@ -0,0 +1,138 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.exception.POSaveFailedException; +import org.compiere.model.I_AD_Preference; +import org.compiere.model.MPreference; +import org.compiere.model.Query; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.model.X_AD_Preference; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class PreferenceElementHandler extends AbstractElementHandler { + + public void startElement(Properties ctx, Element element) + throws SAXException { + + List excludes = defaultExcludeList(X_AD_Preference.Table_Name); + MPreference mPreference = findPO(ctx, element); + if (mPreference == null) { + mPreference = new MPreference(ctx, 0, getTrxName(ctx)); + PoFiller filler = new PoFiller(ctx, mPreference, element, this); + List notFounds = filler.autoFill(excludes); + if (notFounds.size() > 0) { + element.defer = true; + return; + } + + Query query = new Query(ctx, "AD_Preference", "Attribute = ? AND coalesce(AD_User_ID,0) = ? AND coalesce(AD_Window_ID,0) = ?", getTrxName(ctx)); + MPreference tmp = query + .setParameters(new Object[]{mPreference.getAttribute(), mPreference.getAD_User_ID(), mPreference.getAD_Window_ID()}) + .first(); + if (tmp != null) { + filler = new PoFiller(ctx, tmp, element, this); + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + mPreference = tmp; + } + } else { + PoFiller filler = new PoFiller(ctx, mPreference, element, this); + List notFounds = filler.autoFill(excludes); + if (notFounds.size() > 0) { + element.defer = true; + return; + } + } + + if (mPreference.get_ID() == 0 && isOfficialId(element, "AD_Preference_ID")) + mPreference.setAD_Preference_ID(Integer.parseInt(getStringValue(element, "AD_Preference_ID"))); + + if (mPreference.is_new() || mPreference.is_Changed()) { + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_Preference.Table_Name, + X_AD_Preference.Table_ID); + String action = null; + if (!mPreference.is_new()) { + backupRecord(ctx, impDetail.getAD_Package_Imp_Detail_ID(), X_AD_Preference.Table_Name, mPreference); + action = "Update"; + } else { + action = "New"; + } + + if (mPreference.save(getTrxName(ctx)) == true) { + logImportDetail(ctx, impDetail, 1, mPreference.getAttribute(), + mPreference.get_ID(), action); + } else { + logImportDetail(ctx, impDetail, 0, mPreference.getAttribute(), + mPreference.get_ID(), action); + throw new POSaveFailedException("Failed to save Preference"); + } + } + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int AD_Preference_ID = Env.getContextAsInt(ctx, + X_AD_Preference.COLUMNNAME_AD_Preference_ID); + X_AD_Preference m_Preference = new X_AD_Preference(ctx, + AD_Preference_ID, getTrxName(ctx)); + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "table"); + document.startElement("", "", I_AD_Preference.Table_Name, atts); + createPreferenceBinding(ctx, document, m_Preference); + document.endElement("", "", I_AD_Preference.Table_Name); + } + + private void createPreferenceBinding(Properties ctx, TransformerHandler document, + X_AD_Preference m_Preference) { + PoExporter filler = new PoExporter(ctx, document, m_Preference); + List excludes = defaultExcludeList(X_AD_Preference.Table_Name); + + if (m_Preference.getAD_Preference_ID() <= PackOut.MAX_OFFICIAL_ID) + filler.addString("AD_Preference_ID", Integer.toString(m_Preference.getAD_Preference_ID()), new AttributesImpl()); + + filler.export(excludes); + } + + @Override + public void packOut(PackOut packout, TransformerHandler packoutHandler, + TransformerHandler docHandler, + int recordId) throws Exception { + Env.setContext(packout.getCtx(), I_AD_Preference.COLUMNNAME_AD_Preference_ID, recordId); + create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(I_AD_Preference.COLUMNNAME_AD_Preference_ID); + + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/PrintFormatElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/PrintFormatElementHandler.java new file mode 100644 index 0000000000..bda5170d14 --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/PrintFormatElementHandler.java @@ -0,0 +1,164 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + * Teo Sarca, SC ARHIPAC SERVICE SRL + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.exceptions.DBException; +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.exception.POSaveFailedException; +import org.compiere.model.I_AD_PrintFormat; +import org.compiere.model.X_AD_Package_Exp_Detail; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.model.X_AD_PrintFormat; +import org.compiere.model.X_AD_PrintFormatItem; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class PrintFormatElementHandler extends AbstractElementHandler { + + private List formats = new ArrayList(); + + public void startElement(Properties ctx, Element element) + throws SAXException { + + X_AD_PrintFormat mPrintFormat = findPO(ctx, element); + if (mPrintFormat == null) { + String name = getStringValue(element, "Name"); + int id = findIdByColumn(ctx, "AD_PrintFormat", "Name", name); + mPrintFormat = new X_AD_PrintFormat(ctx, id > 0 ? id : 0, getTrxName(ctx)); + } + PoFiller filler = new PoFiller(ctx, mPrintFormat, element, this); + List excludes = defaultExcludeList(X_AD_PrintFormat.Table_Name); + if (mPrintFormat.getAD_PrintFormat_ID() == 0 && isOfficialId(element, "AD_PrintFormat_ID")) + mPrintFormat.setAD_PrintFormat_ID(getIntValue(element, "AD_PrintFormat_ID")); + + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + + if (mPrintFormat.is_new() || mPrintFormat.is_Changed()) { + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_PrintFormat.Table_Name, + X_AD_PrintFormat.Table_ID); + String action = null; + if (!mPrintFormat.is_new()) { + backupRecord(ctx, impDetail.getAD_Package_Imp_Detail_ID(), X_AD_PrintFormat.Table_Name, mPrintFormat); + action = "Update"; + } else { + action = "New"; + } + if (mPrintFormat.save(getTrxName(ctx)) == true) { + logImportDetail(ctx, impDetail, 1, mPrintFormat.getName(), + mPrintFormat.get_ID(), action); + element.recordId = mPrintFormat.getAD_PrintFormat_ID(); + } else { + logImportDetail(ctx, impDetail, 0, mPrintFormat.getName(), + mPrintFormat.get_ID(), action); + throw new POSaveFailedException("Failed to save Print Format"); + } + } + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int AD_PrintFormat_ID = Env.getContextAsInt(ctx, + X_AD_Package_Exp_Detail.COLUMNNAME_AD_PrintFormat_ID); + + if (formats.contains(AD_PrintFormat_ID)) + return; + formats.add(AD_PrintFormat_ID); + AttributesImpl atts = new AttributesImpl(); + + X_AD_PrintFormat m_Printformat = new X_AD_PrintFormat(ctx, AD_PrintFormat_ID, null); + if (m_Printformat.getAD_PrintPaper_ID() > 0) { + try { + getPackOutProcess(ctx).getHandler("PP").packOut(getPackOutProcess(ctx), document, getLogDocument(ctx), m_Printformat.getAD_PrintPaper_ID()); + } catch (Exception e) { + throw new SAXException(e); + } + } + addTypeName(atts, "table"); + document.startElement("", "", I_AD_PrintFormat.Table_Name, atts); + createPrintFormatBinding(ctx, document, m_Printformat); + + String sql = "SELECT AD_PrintFormatItem_ID FROM AD_PrintFormatItem WHERE AD_PrintFormat_ID= " + + m_Printformat.getAD_PrintFormat_ID() + + " ORDER BY "+X_AD_PrintFormatItem.COLUMNNAME_SeqNo; + PreparedStatement pstmt = null; + ResultSet rs = null; + try { + pstmt = DB.prepareStatement(sql, getTrxName(ctx)); + rs = pstmt.executeQuery(); + while (rs.next()) { + createItem(ctx, document, rs.getInt("AD_PrintFormatItem_ID")); + } + } catch (Exception e) { + throw new DBException(e); + } finally { + DB.close(rs, pstmt); + } + document.endElement("", "", I_AD_PrintFormat.Table_Name); + + } + + private void createItem(Properties ctx, TransformerHandler document, + int AD_PrintFormatItem_ID) throws SAXException { + try { + getPackOutProcess(ctx).getHandler("ad.printformat.item").packOut(getPackOutProcess(ctx), document, getLogDocument(ctx), AD_PrintFormatItem_ID); + } catch (Exception e) { + throw new SAXException(e); + } + } + + private void createPrintFormatBinding(Properties ctx, TransformerHandler document, + X_AD_PrintFormat m_Printformat) { + + PoExporter filler = new PoExporter(ctx, document, m_Printformat); + List excludes = defaultExcludeList(X_AD_PrintFormat.Table_Name); + if (m_Printformat.getAD_PrintFormat_ID() <= PackOut.MAX_OFFICIAL_ID) { + filler.add("AD_PrintFormat_ID", new AttributesImpl()); + } + + filler.export(excludes); + } + + public void packOut(PackOut packout, TransformerHandler packoutHandler, TransformerHandler docHandler,int recordId) throws Exception + { + Env.setContext(packout.getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_PrintFormat_ID, recordId); + this.create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_PrintFormat_ID); + } +} + diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/PrintFormatItemElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/PrintFormatItemElementHandler.java new file mode 100644 index 0000000000..8d8780056e --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/PrintFormatItemElementHandler.java @@ -0,0 +1,177 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + * Teo Sarca, SC ARHIPAC SERVICE SRL + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.ReferenceUtils; +import org.adempiere.pipo2.exception.POSaveFailedException; +import org.compiere.model.I_AD_PrintFormatItem; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.model.X_AD_PrintFormatItem; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class PrintFormatItemElementHandler extends AbstractElementHandler { + + public void startElement(Properties ctx, Element element) + throws SAXException { + + List excludes = defaultExcludeList(X_AD_PrintFormatItem.Table_Name); + + if (isParentDefer(element, I_AD_PrintFormatItem.Table_Name)) { + element.defer = true; + return; + } + + X_AD_PrintFormatItem mPrintFormatItem = findPO(ctx, element); + if (mPrintFormatItem == null) { + int parentId = 0; + if (getParentId(element, I_AD_PrintFormatItem.Table_Name) > 0) { + parentId = getParentId(element, I_AD_PrintFormatItem.Table_Name); + } else { + Element pfElement = element.properties.get(I_AD_PrintFormatItem.COLUMNNAME_AD_PrintFormat_ID); + parentId = ReferenceUtils.resolveReference(ctx, pfElement); + } + if (parentId <= 0) { + element.defer = true; + return; + } + + String name = getStringValue(element, "Name"); + int id = findIdByNameAndParentId(ctx, "AD_PrintFormatItem", name, "AD_PrintFormat", parentId); + mPrintFormatItem = new X_AD_PrintFormatItem(ctx, id > 0 ? id : 0, getTrxName(ctx)); + mPrintFormatItem.setAD_PrintFormat_ID(parentId); + excludes.add(I_AD_PrintFormatItem.COLUMNNAME_AD_PrintFormat_ID); + } + PoFiller filler = new PoFiller(ctx, mPrintFormatItem, element, this); + + if (mPrintFormatItem.getAD_PrintFormatItem_ID() == 0 && isOfficialId(element, "AD_PrintFormatItem_ID")) + filler.setInteger("AD_PrintFormatItem_ID"); + + excludes.add("AD_Table_ID"); + excludes.add("AD_Column_ID"); + int columnId = 0; + Element columnElement = element.properties.get("AD_Column_ID"); + if (ReferenceUtils.isIDLookup(columnElement) || ReferenceUtils.isUUIDLookup(columnElement)) { + columnId = ReferenceUtils.resolveReference(ctx, columnElement); + } else { + Element tableElement = element.properties.get("AD_Table_ID"); + int tableId = ReferenceUtils.resolveReference(ctx, tableElement); + String columnName = getStringValue(element, "AD_Column_ID"); + columnId = findIdByColumnAndParentId(ctx, "AD_Column", "ColumnName", columnName, + "AD_Table", tableId); + } + if (columnId > 0) + mPrintFormatItem.setAD_Column_ID(columnId); + + excludes.add("AD_PrintFormatChild_ID"); + Element pfchildElement = element.properties.get(I_AD_PrintFormatItem.COLUMNNAME_AD_PrintFormatChild_ID); + int AD_PrintFormatChild_ID = ReferenceUtils.resolveReference(ctx, pfchildElement); + if (AD_PrintFormatChild_ID > 0) { + mPrintFormatItem.setAD_PrintFormatChild_ID(AD_PrintFormatChild_ID); + } else if (pfchildElement.contents != null && pfchildElement.contents.length() > 0) { + element.defer = true; + element.unresolved = "AD_PrintFormat: " + pfchildElement.contents; + return; + + } + + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + + if (mPrintFormatItem.is_new() || mPrintFormatItem.is_Changed()) { + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_PrintFormatItem.Table_Name, + X_AD_PrintFormatItem.Table_ID); + String action = null; + if (!mPrintFormatItem.is_new()) { + backupRecord(ctx, impDetail.getAD_Package_Imp_Detail_ID(), X_AD_PrintFormatItem.Table_Name, mPrintFormatItem); + action = "Update"; + } else { + action = "New"; + } + if (mPrintFormatItem.save(getTrxName(ctx)) == true) { + logImportDetail(ctx, impDetail, 1, mPrintFormatItem.getName(), + mPrintFormatItem.get_ID(), action); + } else { + logImportDetail(ctx, impDetail, 0, mPrintFormatItem.getName(), + mPrintFormatItem.get_ID(), action); + throw new POSaveFailedException("PrintFormatItem"); + } + } + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int AD_PrintFormatItem_ID = Env.getContextAsInt(ctx, + X_AD_PrintFormatItem.COLUMNNAME_AD_PrintFormatItem_ID); + X_AD_PrintFormatItem m_PrintFormatItem = new X_AD_PrintFormatItem(ctx, + AD_PrintFormatItem_ID, null); + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "table"); + document.startElement("", "", I_AD_PrintFormatItem.Table_Name, atts); + createPrintFormatItemBinding(ctx, document, m_PrintFormatItem); + document.endElement("", "", I_AD_PrintFormatItem.Table_Name); + } + + private void createPrintFormatItemBinding(Properties ctx, TransformerHandler document, + X_AD_PrintFormatItem mPrintformatItem) { + + PoExporter filler = new PoExporter(ctx, document, mPrintformatItem); + List excludes = defaultExcludeList(X_AD_PrintFormatItem.Table_Name); + + if (mPrintformatItem.getAD_PrintFormatItem_ID() <= PackOut.MAX_OFFICIAL_ID) + filler.add("AD_PrintFormatItem_ID", new AttributesImpl()); + + if (mPrintformatItem.getAD_Column_ID() > 0) { + String sql = "SELECT AD_Table_ID FROM AD_Column WHERE AD_Column_ID=?"; + int tableID = DB.getSQLValue(null, sql, mPrintformatItem.getAD_Column_ID()); + AttributesImpl referenceAtts = new AttributesImpl(); + String value = ReferenceUtils.getTableReference("AD_Table", "TableName", tableID, referenceAtts); + filler.addString("AD_Table.TableName", value, referenceAtts); + } + + filler.export(excludes); + } + + public void packOut(PackOut packout, TransformerHandler packoutHandler, + TransformerHandler docHandler, + int recordId) throws Exception { + + Env.setContext(packout.getCtx(), X_AD_PrintFormatItem.COLUMNNAME_AD_PrintFormatItem_ID, recordId); + + this.create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(X_AD_PrintFormatItem.COLUMNNAME_AD_PrintFormatItem_ID); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/PrintPaperElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/PrintPaperElementHandler.java new file mode 100644 index 0000000000..c6ac7876b3 --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/PrintPaperElementHandler.java @@ -0,0 +1,120 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + * Teo Sarca, SC ARHIPAC SERVICE SRL + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.exception.POSaveFailedException; +import org.compiere.model.I_AD_PrintPaper; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.model.X_AD_PrintPaper; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class PrintPaperElementHandler extends AbstractElementHandler { + + public void startElement(Properties ctx, Element element) + throws SAXException { + + List excludes = defaultExcludeList(X_AD_PrintPaper.Table_Name); + + X_AD_PrintPaper printPaper = findPO(ctx, element); + + if (printPaper == null) { + String printPaperName = getStringValue(element, "Name", excludes); + int id = findIdByName(ctx, "AD_PrintPaper", printPaperName); + + printPaper = new X_AD_PrintPaper(ctx, id > 0 ? id : 0, getTrxName(ctx)); + } + PoFiller filler = new PoFiller(ctx, printPaper, element, this); + + if (printPaper.getAD_PrintPaper_ID() == 0 && isOfficialId(element, "AD_PrintPaper_ID")) + filler.setInteger("AD_PrintPaper_ID"); + + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + + if (printPaper.is_new() || printPaper.is_Changed()) { + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_PrintPaper.Table_Name, X_AD_PrintPaper.Table_ID); + String action = null; + if (!printPaper.is_new()) { + backupRecord(ctx, impDetail.getAD_Package_Imp_Detail_ID(), "AD_PrintPaper", printPaper); + action = "Update"; + } else { + action = "New"; + } + if (printPaper.save(getTrxName(ctx)) == true) { + logImportDetail(ctx, impDetail, 1, printPaper.getName(), + printPaper.get_ID(), action); + } else { + logImportDetail(ctx, impDetail, 0, printPaper.getName(), + printPaper.get_ID(), action); + throw new POSaveFailedException("PrintPaper"); + } + } + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int AD_PrintPaper_ID = Env.getContextAsInt(ctx, + X_AD_PrintPaper.COLUMNNAME_AD_PrintPaper_ID); + X_AD_PrintPaper printPaper = new X_AD_PrintPaper(ctx, + AD_PrintPaper_ID, null); + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "table"); + document.startElement("", "", I_AD_PrintPaper.Table_Name, atts); + createPrintPaperBinding(ctx, document, printPaper); + document.endElement("", "", I_AD_PrintPaper.Table_Name); + } + + private void createPrintPaperBinding(Properties ctx, TransformerHandler document, + X_AD_PrintPaper printPaper) { + + PoExporter filler = new PoExporter(ctx, document, printPaper); + List excludes = defaultExcludeList(X_AD_PrintPaper.Table_Name); + + if (printPaper.getAD_PrintPaper_ID() <= PackOut.MAX_OFFICIAL_ID) + filler.add("AD_PrintPaper_ID", new AttributesImpl()); + + filler.export(excludes); + } + + public void packOut(PackOut packout, TransformerHandler packoutHandler, + TransformerHandler docHandler, + int recordId) throws Exception { + Env.setContext(packout.getCtx(), X_AD_PrintPaper.COLUMNNAME_AD_PrintPaper_ID, recordId); + + this.create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(X_AD_PrintPaper.COLUMNNAME_AD_PrintPaper_ID); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/ProcessAccessElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/ProcessAccessElementHandler.java new file mode 100644 index 0000000000..5b1329485c --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/ProcessAccessElementHandler.java @@ -0,0 +1,113 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.ReferenceUtils; +import org.compiere.model.I_AD_Process_Access; +import org.compiere.model.I_AD_Role; +import org.compiere.model.Query; +import org.compiere.model.X_AD_Process; +import org.compiere.model.X_AD_Process_Access; +import org.compiere.model.X_AD_Role; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class ProcessAccessElementHandler extends AbstractElementHandler { + + public void startElement(Properties ctx, Element element) throws SAXException { + int roleid =0; + int processid =0; + List excludes = defaultExcludeList(X_AD_Process_Access.Table_Name); + + X_AD_Process_Access po = findPO(ctx, element); + if (po == null) { + if (getParentId(element, I_AD_Role.Table_Name) > 0) { + roleid = getParentId(element, I_AD_Role.Table_Name); + } else { + Element roleElement = element.properties.get(I_AD_Process_Access.COLUMNNAME_AD_Role_ID); + roleid = ReferenceUtils.resolveReference(ctx, roleElement); + } + + Element processElement = element.properties.get(I_AD_Process_Access.COLUMNNAME_AD_Process_ID); + processid = ReferenceUtils.resolveReference(ctx, processElement); + + Query query = new Query(ctx, "AD_Process_Access", "AD_Role_ID=? and AD_Process_ID=?", getTrxName(ctx)); + po = query.setParameters(new Object[]{roleid, processid}).first(); + if (po == null) + { + po = new X_AD_Process_Access(ctx, 0, getTrxName(ctx)); + po.setAD_Process_ID(processid); + po.setAD_Role_ID(roleid); + } + excludes.add(I_AD_Process_Access.COLUMNNAME_AD_Role_ID); + excludes.add(I_AD_Process_Access.COLUMNNAME_AD_Process_ID); + } + PoFiller filler = new PoFiller(ctx, po, element, this); + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + po.saveEx(); + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int AD_Process_ID = Env.getContextAsInt(ctx, X_AD_Process.COLUMNNAME_AD_Process_ID); + int AD_Role_ID = Env.getContextAsInt(ctx, X_AD_Role.COLUMNNAME_AD_Role_ID); + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "table"); + document.startElement("", "", I_AD_Process_Access.Table_Name, atts); + createProcessAccessBinding(ctx, document, AD_Process_ID, AD_Role_ID); + document.endElement("", "", I_AD_Process_Access.Table_Name); + } + + private void createProcessAccessBinding(Properties ctx, TransformerHandler document, + int process_id, int role_id) { + + X_AD_Process_Access po = null; + Query query = new Query(ctx, "AD_Process_Access", "AD_Role_ID=? and AD_Process_ID=?", getTrxName(ctx)); + po = query.setParameters(new Object[]{role_id, process_id}).first(); + if (po != null) + { + PoExporter filler = new PoExporter(ctx, document, po); + List excludes = defaultExcludeList(X_AD_Process_Access.Table_Name); + filler.export(excludes); + } + } + + @Override + public void packOut(PackOut packout, TransformerHandler packoutHandler, + TransformerHandler docHandler, + int recordId) throws Exception { + create(packout.getCtx(), packoutHandler); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/ProcessElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/ProcessElementHandler.java new file mode 100644 index 0000000000..f854742a83 --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/ProcessElementHandler.java @@ -0,0 +1,190 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com * + * Contributor(s): Low Heng Sin hengsin@avantz.com * + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.exceptions.AdempiereException; +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.ElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.exception.POSaveFailedException; +import org.compiere.model.I_AD_Process; +import org.compiere.model.Query; +import org.compiere.model.X_AD_Package_Exp_Detail; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.model.X_AD_Process; +import org.compiere.model.X_AD_Process_Para; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class ProcessElementHandler extends AbstractElementHandler { + + private ProcessParaElementHandler paraHandler = new ProcessParaElementHandler(); + + private List processes = new ArrayList(); + + public void startElement(Properties ctx, Element element) + throws SAXException { + String entitytype = getStringValue(element, "EntityType"); + if (isProcessElement(ctx, entitytype)) { + X_AD_Process mProcess = findPO(ctx, element); + if (mProcess == null) { + String value = getStringValue(element, "Value"); + + // Get New process. + int id = findIdByColumn(ctx, "AD_Process", "Value", value); + mProcess = new X_AD_Process(ctx, id > 0 ? id : 0, getTrxName(ctx)); + } + + if (mProcess.getAD_Process_ID() == 0 && isOfficialId(element, "AD_Process_ID")) + mProcess.setAD_Process_ID(Integer.parseInt(getStringValue(element, "AD_Process_ID"))); + + PoFiller filler = new PoFiller(ctx, mProcess, element, this); + List excludes = defaultExcludeList(X_AD_Process.Table_Name); + + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + + if (mProcess.is_new() || mProcess.is_Changed()) { + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_Process.Table_Name, + X_AD_Process.Table_ID); + String action = null; + if (!mProcess.is_new()) { + backupRecord(ctx, impDetail.getAD_Package_Imp_Detail_ID(), X_AD_Process.Table_Name, mProcess); + action = "Update"; + } else { + action = "New"; + } + + if (mProcess.save(getTrxName(ctx)) == true) { + logImportDetail(ctx, impDetail, 1, mProcess.getName(), mProcess + .get_ID(), action); + element.recordId = mProcess.getAD_Process_ID(); + } else { + logImportDetail(ctx, impDetail, 0, mProcess.getName(), mProcess + .get_ID(), action); + throw new POSaveFailedException("Process"); + } + } + } else { + element.skip = true; + } + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int AD_Process_ID = Env.getContextAsInt(ctx, "AD_Process_ID"); + if (processes.contains(AD_Process_ID)) + return; + processes.add(AD_Process_ID); + PackOut packOut = getPackOutProcess(ctx); + + X_AD_Process m_Process = new X_AD_Process(ctx, AD_Process_ID, getTrxName(ctx)); + + AttributesImpl atts = new AttributesImpl(); + + try { + if (m_Process.isReport() && m_Process.getAD_ReportView_ID() > 0) + { + ElementHandler handler = packOut.getHandler("R"); + handler.packOut(packOut,document,null,m_Process.getAD_ReportView_ID()); + } + if (m_Process.isReport() && m_Process.getAD_PrintFormat_ID() > 0) + { + ElementHandler handler = packOut.getHandler("PFT"); + handler.packOut(packOut,document,null,m_Process.getAD_PrintFormat_ID()); + } + if (m_Process.getAD_Workflow_ID() > 0) { + ElementHandler handler = packOut.getHandler("F"); + handler.packOut(packOut,document,null,m_Process.getAD_Workflow_ID()); + } + addTypeName(atts, "table"); + document.startElement("", "", I_AD_Process.Table_Name, atts); + createProcessBinding(ctx, document, m_Process); + + Query query = new Query(ctx, "AD_Process_PARA", "AD_Process_ID = ?", getTrxName(ctx)); + List paralist = query.setParameters(new Object[]{AD_Process_ID}).list(); + for (X_AD_Process_Para para : paralist) { + if (para.getAD_Reference_ID()>0) + { + ElementHandler handler = packOut.getHandler("REF"); + handler.packOut(packOut,document,null,para.getAD_Reference_ID()); + } + + if (para.getAD_Reference_Value_ID()>0) + { + ElementHandler handler = packOut.getHandler("REF"); + handler.packOut(packOut,document,null,para.getAD_Reference_Value_ID()); + } + + if (para.getAD_Val_Rule_ID() > 0) + { + ElementHandler handler = packOut.getHandler("V"); + handler.packOut(packOut,document,null,para.getAD_Val_Rule_ID()); + } + + createProcessPara(ctx, document, para.getAD_Process_Para_ID()); + } + + document.endElement("", "", I_AD_Process.Table_Name); + } catch (Exception e) { + throw new AdempiereException(e); + } + + } + + private void createProcessPara(Properties ctx, TransformerHandler document, + int AD_Process_Para_ID) throws SAXException { + Env.setContext(ctx, X_AD_Process_Para.COLUMNNAME_AD_Process_Para_ID, + AD_Process_Para_ID); + paraHandler.create(ctx, document); + ctx.remove(X_AD_Process_Para.COLUMNNAME_AD_Process_Para_ID); + } + + private void createProcessBinding(Properties ctx, TransformerHandler document, + X_AD_Process m_Process) { + PoExporter filler = new PoExporter(ctx, document, m_Process); + List excludes = defaultExcludeList(X_AD_Process.Table_Name); + + if (m_Process.getAD_Process_ID() <= PackOut.MAX_OFFICIAL_ID) + filler.add("AD_Process_ID", new AttributesImpl()); + + filler.export(excludes); + } + + public void packOut(PackOut packout, TransformerHandler packoutHandler, TransformerHandler docHandler,int recordId) throws Exception + { + Env.setContext(packout.getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_Process_ID, recordId); + this.create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Process_ID); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/ProcessParaElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/ProcessParaElementHandler.java new file mode 100644 index 0000000000..5f331abe74 --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/ProcessParaElementHandler.java @@ -0,0 +1,159 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.exceptions.AdempiereException; +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.ElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.ReferenceUtils; +import org.adempiere.pipo2.exception.POSaveFailedException; +import org.compiere.model.I_AD_Process; +import org.compiere.model.I_AD_Process_Para; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.model.X_AD_Process_Para; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class ProcessParaElementHandler extends AbstractElementHandler { + + public void startElement(Properties ctx, Element element) + throws SAXException { + List excludes = defaultExcludeList(X_AD_Process_Para.Table_Name); + + String entitytype = getStringValue(element, "EntityType"); + if (isProcessElement(ctx, entitytype)) { + if (isParentDefer(element, I_AD_Process.Table_Name)) { + element.defer = true; + return; + } + + X_AD_Process_Para mProcessPara = findPO(ctx, element); + if (mProcessPara == null) { + String name = getStringValue(element, "Name"); + + int id = 0; + int masterId = 0; + if (getParentId(element, I_AD_Process.Table_Name) > 0) { + masterId = getParentId(element, "process"); + } else { + Element processElement = element.properties.get(I_AD_Process_Para.COLUMNNAME_AD_Process_ID); + masterId = ReferenceUtils.resolveReference(ctx, processElement); + } + if (masterId <= 0) { + element.defer = true; + element.unresolved = "AD_Process: " + getStringValue(element, I_AD_Process_Para.COLUMNNAME_AD_Process_ID); + return; + } + + id = findIdByColumnAndParentId(ctx, "AD_Process_Para", "Name", name, "AD_Process", masterId); + mProcessPara = new X_AD_Process_Para(ctx, id > 0 ? id : 0, getTrxName(ctx)); + mProcessPara.setAD_Process_ID(masterId); + excludes.add(I_AD_Process_Para.COLUMNNAME_AD_Process_ID); + } + + if (mProcessPara.getAD_Process_Para_ID() == 0 && isOfficialId(element, "AD_Process_Para_ID")) + mProcessPara.setAD_Process_Para_ID(Integer.parseInt(getStringValue(element, "AD_Process_Para_ID"))); + + PoFiller filler = new PoFiller(ctx, mProcessPara, element, this); + + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + + if (mProcessPara.is_new() || mProcessPara.is_Changed()) { + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_Process_Para.Table_Name, + X_AD_Process_Para.Table_ID); + String action = null; + if (!mProcessPara.is_new()) { + backupRecord(ctx, impDetail.getAD_Package_Imp_Detail_ID(), X_AD_Process_Para.Table_Name, + mProcessPara); + action = "Update"; + } else { + action = "New"; + } + if (mProcessPara.save(getTrxName(ctx)) == true) { + logImportDetail(ctx, impDetail, 1, mProcessPara.getName(), + mProcessPara.get_ID(), action); + } else { + logImportDetail(ctx, impDetail, 0, mProcessPara.getName(), + mProcessPara.get_ID(), action); + throw new POSaveFailedException("ProcessPara"); + } + } + } else { + element.skip = true; + } + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int AD_Process_Para_ID = Env.getContextAsInt(ctx, + X_AD_Process_Para.COLUMNNAME_AD_Process_Para_ID); + X_AD_Process_Para m_Processpara = new X_AD_Process_Para(ctx, + AD_Process_Para_ID, getTrxName(ctx)); + + if (m_Processpara.getAD_Element_ID() > 0) { + PackOut packOut = getPackOutProcess(ctx); + ElementHandler handler = packOut.getHandler("ELE"); + try { + handler.packOut(packOut,document,null,m_Processpara.getAD_Element_ID()); + } catch (Exception e) { + throw new AdempiereException(e); + } + } + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "table"); + document.startElement("", "", I_AD_Process_Para.Table_Name, atts); + createProcessParaBinding(ctx, document, m_Processpara); + document.endElement("", "", I_AD_Process_Para.Table_Name); + } + + private void createProcessParaBinding(Properties ctx, TransformerHandler document, + X_AD_Process_Para m_Processpara) { + + PoExporter filler = new PoExporter(ctx, document, m_Processpara); + List excludes = defaultExcludeList(X_AD_Process_Para.Table_Name); + + if (m_Processpara.getAD_Process_Para_ID() <= PackOut.MAX_OFFICIAL_ID) + filler.add("AD_Process_Para_ID", new AttributesImpl()); + filler.export(excludes); + } + + @Override + public void packOut(PackOut packout, TransformerHandler packoutHandler, + TransformerHandler docHandler, + int recordId) throws Exception { + Env.setContext(packout.getCtx(), I_AD_Process_Para.COLUMNNAME_AD_Process_Para_ID, recordId); + create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(I_AD_Process_Para.COLUMNNAME_AD_Process_Para_ID); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/ReferenceElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/ReferenceElementHandler.java new file mode 100644 index 0000000000..82011f0f43 --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/ReferenceElementHandler.java @@ -0,0 +1,195 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import java.util.logging.Level; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.exception.DatabaseAccessException; +import org.adempiere.pipo2.exception.POSaveFailedException; +import org.compiere.model.I_AD_Reference; +import org.compiere.model.X_AD_Package_Exp_Detail; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.model.X_AD_Ref_List; +import org.compiere.model.X_AD_Ref_Table; +import org.compiere.model.X_AD_Reference; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class ReferenceElementHandler extends AbstractElementHandler { + + private ReferenceListElementHandler listHandler = new ReferenceListElementHandler(); + private ReferenceTableElementHandler tableHandler = new ReferenceTableElementHandler(); + + private List references = new ArrayList(); + + public void startElement(Properties ctx, Element element) + throws SAXException { + String entitytype = getStringValue(element, "EntityType"); + String name = getStringValue(element, "Name"); + + if (isProcessElement(ctx, entitytype)) { + + X_AD_Reference mReference = findPO(ctx, element); + if (mReference == null) { + int id = findIdByName(ctx, "AD_Reference", name); + mReference = new X_AD_Reference(ctx, id > 0 ? id : 0, getTrxName(ctx)); + } + List excludes = defaultExcludeList(X_AD_Reference.Table_Name); + if (mReference.getAD_Reference_ID() == 0 && isOfficialId(element, "AD_Reference_ID")) + mReference.setAD_Reference_ID(getIntValue(element, "AD_Reference_ID")); + + PoFiller filler = new PoFiller(ctx, mReference, element, this); + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + + if (mReference.is_new() || mReference.is_Changed()) { + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_Reference.Table_Name, + X_AD_Reference.Table_ID); + String action = null; + if (!mReference.is_new()) { + if (references.contains(mReference.getAD_Reference_ID())) { + element.skip = true; + return; + } + backupRecord(ctx, impDetail.getAD_Package_Imp_ID(), X_AD_Reference.Table_Name, mReference); + action = "Update"; + } else { + action = "New"; + } + if (mReference.save(getTrxName(ctx)) == true) { + logImportDetail(ctx, impDetail, 1, mReference.getName(), + mReference.get_ID(), action); + references.add(mReference.getAD_Reference_ID()); + element.recordId = mReference.getAD_Reference_ID(); + } else { + logImportDetail(ctx, impDetail, 0, mReference.getName(), + mReference.get_ID(), action); + throw new POSaveFailedException("Reference"); + } + } + } else { + element.skip = true; + } + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int Reference_id = Env.getContextAsInt(ctx, + X_AD_Reference.COLUMNNAME_AD_Reference_ID); + + if (references.contains(Reference_id)) + return; + + references.add(Reference_id); + AttributesImpl atts = new AttributesImpl(); + + X_AD_Reference m_Reference = new X_AD_Reference(ctx, Reference_id, getTrxName(ctx)); + + addTypeName(atts, "table"); + document.startElement("", "", I_AD_Reference.Table_Name, atts); + createReferenceBinding(ctx, document, m_Reference); + + if (m_Reference.getValidationType().compareTo("L") == 0) { + String sql1 = "SELECT AD_REF_LIST_ID FROM AD_Ref_List WHERE AD_Reference_ID= " + + Reference_id; + + PreparedStatement pstmt = null; + ResultSet rs = null; + + try { + pstmt = DB.prepareStatement(sql1, getTrxName(ctx)); + rs = pstmt.executeQuery(); + + while (rs.next()) { + createReferenceList(ctx, document, rs.getInt("AD_REF_LIST_ID")); + } + } + catch (Exception e) { + log.log(Level.SEVERE, e.getLocalizedMessage(), e); + if (e instanceof SAXException) + throw (SAXException) e; + else if (e instanceof SQLException) + throw new DatabaseAccessException("Failed to export Reference.", e); + else if (e instanceof RuntimeException) + throw (RuntimeException) e; + else + throw new RuntimeException("Failed to export Reference.", e); + } finally { + DB.close(rs, pstmt); + } + + } else if (m_Reference.getValidationType().compareTo("T") == 0) { + createReferenceTable(ctx, document, Reference_id); + } + document.endElement("", "", I_AD_Reference.Table_Name); + + } + + private void createReferenceTable(Properties ctx, TransformerHandler document, + int reference_id) throws SAXException { + Env.setContext(ctx, X_AD_Ref_Table.COLUMNNAME_AD_Reference_ID, reference_id); + tableHandler.create(ctx, document); + ctx.remove(X_AD_Ref_Table.COLUMNNAME_AD_Reference_ID); + } + + private void createReferenceList(Properties ctx, + TransformerHandler document, int AD_Ref_List_ID) + throws SAXException { + Env.setContext(ctx, X_AD_Ref_List.COLUMNNAME_AD_Ref_List_ID, + AD_Ref_List_ID); + listHandler.create(ctx, document); + ctx.remove(X_AD_Ref_List.COLUMNNAME_AD_Ref_List_ID); + } + + private void createReferenceBinding(Properties ctx, TransformerHandler document, + X_AD_Reference m_Reference) { + List excludes = defaultExcludeList(X_AD_Reference.Table_Name); + PoExporter filler = new PoExporter(ctx, document, m_Reference); + if (m_Reference.getAD_Reference_ID() <= PackOut.MAX_OFFICIAL_ID) + filler.add("AD_Reference_ID", new AttributesImpl()); + + filler.export(excludes); + } + + public void packOut(PackOut packout, TransformerHandler packoutHandler, TransformerHandler docHandler,int recordId) throws Exception + { + Env.setContext(packout.getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_Reference_ID, recordId); + this.create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Reference_ID); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/ReferenceListElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/ReferenceListElementHandler.java new file mode 100644 index 0000000000..795577be9e --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/ReferenceListElementHandler.java @@ -0,0 +1,135 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.ReferenceUtils; +import org.adempiere.pipo2.exception.POSaveFailedException; +import org.compiere.model.I_AD_Ref_List; +import org.compiere.model.I_AD_Reference; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.model.X_AD_Ref_List; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class ReferenceListElementHandler extends AbstractElementHandler { + + public void startElement(Properties ctx, Element element) + throws SAXException { + + String entitytype = getStringValue(element, "EntityType"); + if (isProcessElement(ctx, entitytype)) { + if (isParentSkip(element, null)) { + element.skip = true; + return; + } + + X_AD_Ref_List mRefList = findPO(ctx, element); + if (mRefList == null) { + String value = getStringValue(element, "Value"); + int AD_Reference_ID = 0; + if (getParentId(element, I_AD_Reference.Table_Name) > 0) { + AD_Reference_ID = getParentId(element, I_AD_Reference.Table_Name); + } else { + Element referenceElement = element.properties.get(I_AD_Ref_List.COLUMNNAME_AD_Reference_ID); + AD_Reference_ID = ReferenceUtils.resolveReference(ctx, referenceElement); + } + + int AD_Ref_List_ID = findIdByColumnAndParentId(ctx, "AD_Ref_List", "Value", value, "AD_Reference", AD_Reference_ID); + mRefList = new X_AD_Ref_List(ctx, AD_Ref_List_ID, getTrxName(ctx)); + } + + if (mRefList.getAD_Ref_List_ID() == 0 && isOfficialId(element, "AD_Ref_List_ID")) + mRefList.setAD_Ref_List_ID(getIntValue(element, "AD_Ref_List_ID")); + + PoFiller filler = new PoFiller(ctx, mRefList, element, this); + List excludes = defaultExcludeList(X_AD_Ref_List.Table_Name); + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + + if (mRefList.is_new() || mRefList.is_Changed()) { + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_Ref_List.Table_Name, + X_AD_Ref_List.Table_ID); + String action = null; + if (!mRefList.is_new()) { + backupRecord(ctx, impDetail.getAD_Package_Imp_Detail_ID(), X_AD_Ref_List.Table_Name, mRefList); + action = "Update"; + } else { + action = "New"; + } + if (mRefList.save(getTrxName(ctx)) == true) { + logImportDetail(ctx, impDetail, 1, mRefList.getName(), + mRefList.get_ID(), action); + } else { + logImportDetail(ctx, impDetail, 0, mRefList.getName(), + mRefList.get_ID(), action); + throw new POSaveFailedException("ReferenceList"); + } + } + } else { + element.skip = true; + } + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int AD_Ref_List_ID = Env.getContextAsInt(ctx, + X_AD_Ref_List.COLUMNNAME_AD_Ref_List_ID); + X_AD_Ref_List m_Ref_List = new X_AD_Ref_List(ctx, AD_Ref_List_ID, + getTrxName(ctx)); + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "table"); + document.startElement("", "", I_AD_Ref_List.Table_Name, atts); + createRefListBinding(ctx, document, m_Ref_List); + document.endElement("", "", I_AD_Ref_List.Table_Name); + } + + private void createRefListBinding(Properties ctx, TransformerHandler document, + X_AD_Ref_List m_Ref_List) { + List excludes = defaultExcludeList(X_AD_Ref_List.Table_Name); + PoExporter filler = new PoExporter(ctx, document, m_Ref_List); + if (m_Ref_List.getAD_Ref_List_ID() <= PackOut.MAX_OFFICIAL_ID) + filler.add("AD_Ref_List_ID", new AttributesImpl()); + + filler.export(excludes); + } + + @Override + public void packOut(PackOut packout, TransformerHandler packoutHandler, + TransformerHandler docHandler, + int recordId) throws Exception { + Env.setContext(packout.getCtx(), I_AD_Ref_List.COLUMNNAME_AD_Ref_List_ID, recordId); + create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(I_AD_Ref_List.COLUMNNAME_AD_Ref_List_ID); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/ReferenceTableElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/ReferenceTableElementHandler.java new file mode 100644 index 0000000000..c6afb14b7a --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/ReferenceTableElementHandler.java @@ -0,0 +1,183 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.List; +import java.util.Properties; +import java.util.logging.Level; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.ReferenceUtils; +import org.adempiere.pipo2.exception.DatabaseAccessException; +import org.compiere.model.I_AD_Ref_Table; +import org.compiere.model.I_AD_Reference; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.model.X_AD_Ref_Table; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class ReferenceTableElementHandler extends AbstractElementHandler { + + public void startElement(Properties ctx, Element element) + throws SAXException { + + List excludes = defaultExcludeList(X_AD_Ref_Table.Table_Name); + + String entitytype = getStringValue(element, "EntityType"); + if (isProcessElement(ctx, entitytype)) { + if (isParentSkip(element, null)) { + element.skip = true; + return; + } + + X_AD_Ref_Table refTable = findPO(ctx, element); + if (refTable == null) { + int AD_Reference_ID = 0; + if (getParentId(element, I_AD_Reference.Table_Name) > 0) { + AD_Reference_ID = getParentId(element, I_AD_Reference.Table_Name); + } else { + Element referenceElement = element.properties.get(I_AD_Ref_Table.COLUMNNAME_AD_Reference_ID); + AD_Reference_ID = ReferenceUtils.resolveReference(ctx, referenceElement); + } + if (AD_Reference_ID <= 0 && isOfficialId(element, "AD_Reference_ID")) + AD_Reference_ID = getIntValue(element, "AD_Reference_ID"); + + String sql = "SELECT * FROM AD_Ref_Table WHERE AD_Reference_ID = ?"; + PreparedStatement pstmt = null; + ResultSet rs = null; + try { + pstmt = DB.prepareStatement(sql, getTrxName(ctx)); + pstmt.setInt(1, AD_Reference_ID); + rs = pstmt.executeQuery(); + if (rs.next()) { + refTable = new X_AD_Ref_Table(ctx, rs, getTrxName(ctx)); + } else { + refTable = new X_AD_Ref_Table(ctx, 0, getTrxName(ctx)); + } + } catch (Exception e) { + throw new DatabaseAccessException(e.getLocalizedMessage(), e); + } finally { + DB.close(rs, pstmt); + } + } + String action = refTable.is_new() ? "New" : "Update"; + PoFiller filler = new PoFiller(ctx, refTable, element, this); + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + int tableId = refTable.getAD_Table_ID(); + Element displayElement = element.properties.get("AD_Display"); + int displayColumnId = 0; + if (ReferenceUtils.isIDLookup(displayElement) || ReferenceUtils.isUUIDLookup(displayElement)) { + displayColumnId = ReferenceUtils.resolveReference(ctx, displayElement); + } else { + displayColumnId = findIdByColumnAndParentId(ctx, "AD_Column", "ColumnName", displayElement.contents.toString(), "AD_Table", tableId); + } + refTable.setAD_Display(displayColumnId); + + + Element keyElement = element.properties.get("AD_Key"); + int keyColumnId = 0; + if (ReferenceUtils.isIDLookup(keyElement) || ReferenceUtils.isUUIDLookup(keyElement)) { + keyColumnId = ReferenceUtils.resolveReference(ctx, keyElement); + } else { + keyColumnId = findIdByColumnAndParentId(ctx, "AD_Column", "ColumnName", keyElement.contents.toString(), "AD_Table", tableId); + } + refTable.setAD_Key(keyColumnId); + + if (refTable.is_new() || refTable.is_Changed()) { + refTable.saveEx(); + + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_Ref_Table.Table_Name, + X_AD_Ref_Table.Table_ID); + + logImportDetail(ctx, impDetail, 1, refTable.getAD_Reference().getName(), refTable.getAD_Reference_ID(), action); + } + } else { + element.skip = true; + } + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int Reference_id = Env.getContextAsInt(ctx, + X_AD_Ref_Table.COLUMNNAME_AD_Reference_ID); + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "table"); + document.startElement("", "", I_AD_Ref_Table.Table_Name, atts); + createReferenceTableBinding(ctx, document, Reference_id); + document.endElement("", "", I_AD_Ref_Table.Table_Name); + } + + private void createReferenceTableBinding(Properties ctx, + TransformerHandler document, int reference_ID) { + + if (reference_ID <= PackOut.MAX_OFFICIAL_ID) + { + PoExporter filler = new PoExporter(ctx,document,null); + filler.addString("AD_Reference_ID", Integer.toString(reference_ID), new AttributesImpl()); + } + String sql = "SELECT * FROM AD_Ref_Table WHERE AD_Reference_ID= " + + reference_ID; + + PreparedStatement pstmt = null; + ResultSet rs = null; + try { + pstmt = DB.prepareStatement(sql, getTrxName(ctx)); + rs = pstmt.executeQuery(); + if (rs.next()) { + X_AD_Ref_Table refTable = new X_AD_Ref_Table(ctx, rs, getTrxName(ctx)); + PoExporter filler = new PoExporter(ctx,document,refTable); + List excludes = defaultExcludeList(X_AD_Ref_Table.Table_Name); + excludes.add("ad_display"); + excludes.add("ad_key"); + filler.export(excludes); + filler.addTableReference("AD_Display", "AD_Column", "ColumnName", new AttributesImpl()); + filler.addTableReference("AD_Key", "AD_Column", "ColumnName", new AttributesImpl()); + } + } catch (Exception e) { + log.log(Level.SEVERE, e.getLocalizedMessage(), e); + throw new DatabaseAccessException("Failed to export Reference Table", e); + } finally { + DB.close(rs, pstmt); + } + } + + @Override + public void packOut(PackOut packout, TransformerHandler packoutHandler, + TransformerHandler docHandler, + int recordId) throws Exception { + Env.setContext(packout.getCtx(), I_AD_Ref_Table.COLUMNNAME_AD_Reference_ID, recordId); + create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(I_AD_Ref_Table.COLUMNNAME_AD_Reference_ID); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/ReportViewColElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/ReportViewColElementHandler.java new file mode 100644 index 0000000000..62827f3dfc --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/ReportViewColElementHandler.java @@ -0,0 +1,179 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.ReferenceUtils; +import org.adempiere.pipo2.exception.POSaveFailedException; +import org.compiere.model.I_AD_ReportView; +import org.compiere.model.I_AD_ReportView_Col; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.model.X_AD_ReportView_Col; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class ReportViewColElementHandler extends AbstractElementHandler { + + public void startElement(Properties ctx, Element element) + throws SAXException { + List excludes = defaultExcludeList(X_AD_ReportView_Col.Table_Name); + + String entitytype = getStringValue(element,"EntityType"); + if (isProcessElement(ctx, entitytype)) { + excludes.add("AD_Table_ID"); + X_AD_ReportView_Col mReportviewCol = findPO(ctx, element); + if (mReportviewCol == null) { + int AD_ReportView_ID = 0; + if (getParentId(element, I_AD_ReportView.Table_Name) > 0) { + AD_ReportView_ID = getParentId(element, I_AD_ReportView.Table_Name); + } else { + Element rvElement = element.properties.get(I_AD_ReportView_Col.COLUMNNAME_AD_ReportView_ID); + AD_ReportView_ID = ReferenceUtils.resolveReference(ctx, rvElement); + } + if (AD_ReportView_ID <= 0) { + element.defer = true; + return; + } + + int AD_Column_ID = 0; + Element columnElement = element.properties.get(I_AD_ReportView_Col.COLUMNNAME_AD_Column_ID); + if (ReferenceUtils.isIDLookup(columnElement) || ReferenceUtils.isUUIDLookup(columnElement)) { + AD_Column_ID = ReferenceUtils.resolveReference(ctx, columnElement); + } else { + if (columnElement.contents != null && columnElement.contents.length() > 0) { + Element tableElement = element.properties.get("AD_Table_ID"); + int AD_Table_ID = ReferenceUtils.resolveReference(ctx, tableElement); + AD_Column_ID = findIdByColumnAndParentId(ctx, "AD_Column", "ColumnName", columnElement.contents.toString(), + "AD_Table", AD_Table_ID); + if (AD_Column_ID <= 0) { + element.defer = true; + return; + } + } + } + + String functionColumn = getStringValue(element, "FunctionColumn"); + StringBuffer sql = new StringBuffer("SELECT AD_Reportview_Col_ID FROM AD_Reportview_Col ") + .append(" WHERE AD_Column_ID "); + if (AD_Column_ID > 0) + sql.append(" = " + AD_Column_ID); + else + sql.append(" IS NULL "); + sql.append(" AND FunctionColumn = ?"); + sql.append(" AND AD_ReportView_ID = ?"); + + int id = DB.getSQLValue(getTrxName(ctx), sql.toString(), functionColumn, AD_ReportView_ID); + mReportviewCol = new X_AD_ReportView_Col(ctx, id > 0 ? id : 0, getTrxName(ctx)); + mReportviewCol.setAD_ReportView_ID(AD_ReportView_ID); + if (AD_Column_ID > 0) { + mReportviewCol.setAD_Column_ID(id); + } + mReportviewCol.setFunctionColumn(functionColumn); + excludes.add("FunctionColumn"); + excludes.add("AD_ReportView_ID"); + excludes.add("AD_Column_ID"); + } + + if (mReportviewCol.getAD_ReportView_Col_ID() == 0 && isOfficialId(element, "AD_ReportView_Col_ID")) + mReportviewCol.setAD_ReportView_Col_ID(getIntValue(element, "AD_ReportView_Col_ID")); + + PoFiller filler = new PoFiller(ctx, mReportviewCol, element, this); + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + + if (mReportviewCol.is_new() || mReportviewCol.is_Changed()) { + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_ReportView_Col.Table_Name, + X_AD_ReportView_Col.Table_ID); + String action = null; + if (!mReportviewCol.is_new()) { + backupRecord(ctx, impDetail.getAD_Package_Imp_Detail_ID(), X_AD_ReportView_Col.Table_Name, + mReportviewCol); + action = "Update"; + } else { + action = "New"; + } + if (mReportviewCol.save(getTrxName(ctx)) == true) { + logImportDetail(ctx, impDetail, 1, "" + mReportviewCol.getAD_ReportView_ID(), + mReportviewCol.get_ID(), action); + } else { + logImportDetail(ctx, impDetail, 0, "" + mReportviewCol.getAD_ReportView_ID(), + mReportviewCol.get_ID(),action); + throw new POSaveFailedException("ReportViewCol"); + } + } + } else { + element.skip = true; + } + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int AD_ReportView_Col_ID = Env.getContextAsInt(ctx, + X_AD_ReportView_Col.COLUMNNAME_AD_ReportView_Col_ID); + X_AD_ReportView_Col m_Reportview_Col = new X_AD_ReportView_Col(ctx, + AD_ReportView_Col_ID, getTrxName(ctx)); + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "table"); + document.startElement("", "", I_AD_ReportView_Col.Table_Name, atts); + createReportViewColBinding(ctx, document, m_Reportview_Col); + document.endElement("", "", I_AD_ReportView_Col.Table_Name); + } + + private void createReportViewColBinding(Properties ctx, TransformerHandler document, + X_AD_ReportView_Col m_Reportview_Col) { + + PoExporter filler = new PoExporter(ctx, document, m_Reportview_Col); + List excludes = defaultExcludeList(X_AD_ReportView_Col.Table_Name); + if (m_Reportview_Col.getAD_ReportView_Col_ID() <= PackOut.MAX_OFFICIAL_ID) + filler.add("AD_ReportView_Col_ID", new AttributesImpl()); + + if (m_Reportview_Col.getAD_Column_ID() > 0) { + int AD_Table_ID = m_Reportview_Col.getAD_Column().getAD_Table_ID(); + AttributesImpl tableAtts = new AttributesImpl(); + String value = ReferenceUtils.getTableReference("AD_Table", "TableName", AD_Table_ID, tableAtts); + filler.addString("AD_Table_ID", value, tableAtts); + } + + filler.export(excludes); + } + + @Override + public void packOut(PackOut packout, TransformerHandler packoutHandler, + TransformerHandler docHandler, + int recordId) throws Exception { + Env.setContext(packout.getCtx(), I_AD_ReportView_Col.COLUMNNAME_AD_ReportView_Col_ID, recordId); + create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(I_AD_ReportView_Col.COLUMNNAME_AD_ReportView_Col_ID); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/ReportViewElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/ReportViewElementHandler.java new file mode 100644 index 0000000000..5056e5fda3 --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/ReportViewElementHandler.java @@ -0,0 +1,182 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.exceptions.AdempiereException; +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.ElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.exception.POSaveFailedException; +import org.compiere.model.I_AD_ReportView; +import org.compiere.model.X_AD_Package_Exp_Detail; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.model.X_AD_ReportView; +import org.compiere.model.X_AD_ReportView_Col; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class ReportViewElementHandler extends AbstractElementHandler { + + private ReportViewColElementHandler columnHandler = new ReportViewColElementHandler(); + + private List views = new ArrayList(); + + public void startElement(Properties ctx, Element element) + throws SAXException { + + List excludes = defaultExcludeList(X_AD_ReportView.Table_Name); + + X_AD_ReportView mReportview = findPO(ctx, element); + if (mReportview == null) { + String name = getStringValue(element, "Name"); + int id = findIdByName(ctx, "AD_ReportView", name); + mReportview = new X_AD_ReportView(ctx, id, getTrxName(ctx)); + } + PoFiller filler = new PoFiller(ctx, mReportview, element, this); + if (mReportview.getAD_ReportView_ID() == 0 && isOfficialId(element, "AD_ReportView_ID")) + mReportview.setAD_ReportView_ID(getIntValue(element, "AD_ReportView_ID")); + + List notfound = filler.autoFill(excludes); + if (notfound.size() > 0) { + element.defer = true; + return; + } + + if (mReportview.is_new() || mReportview.is_Changed()) { + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_ReportView.Table_Name, + X_AD_ReportView.Table_ID); + String action = null; + if (!mReportview.is_new()) { + backupRecord(ctx, impDetail.getAD_Package_Imp_Detail_ID(), X_AD_ReportView.Table_Name, mReportview); + action = "Update"; + } else { + action = "New"; + } + if (mReportview.save(getTrxName(ctx)) == true) { + logImportDetail(ctx, impDetail, 1, mReportview.getName(), + mReportview.get_ID(), action); + element.recordId = mReportview.getAD_ReportView_ID(); + } else { + logImportDetail(ctx, impDetail, 0, mReportview.getName(), + mReportview.get_ID(), action); + throw new POSaveFailedException("ReportView"); + } + } + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + PackOut packOut = getPackOutProcess(ctx); + int AD_ReportView_ID = Env.getContextAsInt(ctx, "AD_ReportView_ID"); + if (views.contains(AD_ReportView_ID)) + return; + + views.add(AD_ReportView_ID); + AttributesImpl atts = new AttributesImpl(); + X_AD_ReportView m_Reportview = new X_AD_ReportView(ctx, AD_ReportView_ID, getTrxName(ctx)); + + // Export Table if neccessary + ElementHandler tableHandler = packOut.getHandler("T"); + try { + tableHandler.packOut(packOut, document, null, m_Reportview.getAD_Table_ID()); + } catch (Exception e) { + throw new AdempiereException(e); + } + + addTypeName(atts, "table"); + document.startElement("", "", I_AD_ReportView.Table_Name, atts); + createReportViewBinding(ctx, document, m_Reportview); + document.endElement("", "", I_AD_ReportView.Table_Name); + + String sql = "SELECT AD_PrintFormat_ID FROM AD_PrintFormat WHERE AD_ReportView_ID= " + + AD_ReportView_ID; + PreparedStatement pstmt = null; + ResultSet rs = null; + try { + pstmt = DB.prepareStatement(sql, getTrxName(ctx)); + rs = pstmt.executeQuery(); + while (rs.next()) { + ElementHandler pftHandler = packOut.getHandler("PFT"); + pftHandler.packOut(packOut, document, null, rs.getInt(1)); + + } + } catch (Exception e) { + throw new AdempiereException(e); + } finally { + DB.close(rs, pstmt); + } + + sql = "SELECT AD_ReportView_Col_ID FROM AD_ReportView_Col WHERE AD_Reportview_ID= " + + AD_ReportView_ID; + pstmt = null; + rs = null; + try { + pstmt = DB.prepareStatement(sql, getTrxName(ctx)); + rs = pstmt.executeQuery(); + while (rs.next()) { + createReportViewCol(ctx, document, rs.getInt("AD_ReportView_Col_ID")); + } + } catch (Exception e) { + throw new AdempiereException(e); + } finally { + DB.close(rs, pstmt); + } + } + + private void createReportViewCol(Properties ctx, + TransformerHandler document, int AD_ReportView_Col_ID) + throws SAXException { + Env.setContext(ctx, + X_AD_ReportView_Col.COLUMNNAME_AD_ReportView_Col_ID, + AD_ReportView_Col_ID); + columnHandler.create(ctx, document); + ctx.remove(X_AD_ReportView_Col.COLUMNNAME_AD_ReportView_Col_ID); + } + + private void createReportViewBinding(Properties ctx, TransformerHandler document, + X_AD_ReportView m_Reportview) { + + PoExporter filler = new PoExporter(ctx, document, m_Reportview); + List excludes = defaultExcludeList(X_AD_ReportView.Table_Name); + if (m_Reportview.getAD_ReportView_ID() <= PackOut.MAX_OFFICIAL_ID) + filler.add("AD_ReportView_ID", new AttributesImpl()); + filler.export(excludes); + } + + public void packOut(PackOut packout, TransformerHandler packoutHandler, TransformerHandler docHandler,int recordId) throws Exception + { + Env.setContext(packout.getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_ReportView_ID, recordId); + this.create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_ReportView_ID); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/RoleElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/RoleElementHandler.java new file mode 100644 index 0000000000..a9e3ba397d --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/RoleElementHandler.java @@ -0,0 +1,336 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import java.util.logging.Level; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.ReferenceUtils; +import org.adempiere.pipo2.exception.DatabaseAccessException; +import org.adempiere.pipo2.exception.POSaveFailedException; +import org.compiere.model.I_AD_Role; +import org.compiere.model.MRole; +import org.compiere.model.X_AD_Form; +import org.compiere.model.X_AD_Package_Exp_Detail; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.model.X_AD_Process; +import org.compiere.model.X_AD_Role; +import org.compiere.model.X_AD_Task; +import org.compiere.model.X_AD_User; +import org.compiere.model.X_AD_Window; +import org.compiere.model.X_AD_Workflow; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class RoleElementHandler extends AbstractElementHandler { + + private List roles = new ArrayList(); + + private OrgRoleElementHandler orgHandler = new OrgRoleElementHandler(); + private ProcessAccessElementHandler processHandler = new ProcessAccessElementHandler(); + private UserRoleElementHandler userHandler = new UserRoleElementHandler(); + private WindowAccessElementHandler windowHandler = new WindowAccessElementHandler(); + private FormAccessElementHandler formHandler = new FormAccessElementHandler(); + private TaskAccessElementHandler taskHandler = new TaskAccessElementHandler(); + private WorkflowAccessElementHandler workflowHandler = new WorkflowAccessElementHandler(); + + public void startElement(Properties ctx, Element element) + throws SAXException { + + List excludes = defaultExcludeList(X_AD_Role.Table_Name); + + MRole mRole = findPO(ctx, element); + if (mRole == null) { + String name = getStringValue(element, "Name", excludes); + int id = findIdByName(ctx, "AD_Role", name); + mRole = new MRole(ctx, id > 0 ? id : 0, getTrxName(ctx)); + mRole.setName(name); + } + + if (mRole.getAD_Role_ID() == 0 && isOfficialId(element, "AD_Role_ID")) + mRole.setAD_Role_ID(getIntValue(element, "AD_Role_ID")); + + PoFiller filler = new PoFiller(ctx, mRole, element, this); + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + + if (mRole.is_new() || mRole.is_Changed()) { + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_Role.Table_Name, + X_AD_Role.Table_ID); + String action = null; + if (!mRole.is_new()) { + action = "Update"; + } else { + action = "New"; + } + if (mRole.save(getTrxName(ctx)) == true) { + element.recordId = mRole.getAD_Role_ID(); + logImportDetail(ctx, impDetail, 1, mRole.getName(), mRole.get_ID(), + action); + } else { + + logImportDetail(ctx, impDetail, 0, mRole.getName(), mRole.get_ID(), + action); + throw new POSaveFailedException("Role"); + } + } + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int Role_id = Env.getContextAsInt(ctx, + X_AD_Package_Exp_Detail.COLUMNNAME_AD_Role_ID); + if (roles.contains(Role_id)) + return; + roles.add(Role_id); + X_AD_Role m_Role = new X_AD_Role(ctx, Role_id, null); + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "table"); + document.startElement("", "", I_AD_Role.Table_Name, atts); + createRoleBinding(ctx, document, m_Role); + + // Process org access + String sql = "SELECT AD_Org_ID, AD_Role_ID FROM AD_Role_OrgAccess WHERE AD_Role_ID= " + + Role_id; + PreparedStatement pstmt = null; + ResultSet rs = null; + try { + pstmt = DB.prepareStatement(sql, getTrxName(ctx)); + rs = pstmt.executeQuery(); + while (rs.next()) { + createOrgAccess(ctx, document, rs.getInt("AD_Org_ID"), rs.getInt("AD_Role_ID")); + } + } catch (Exception e) { + log.log(Level.SEVERE, "AD_Role_OrgAccess", e); + throw new DatabaseAccessException("Failed to export organization role access."); + } finally { + DB.close(rs, pstmt); + } + + // Process user assignment access + sql = "SELECT AD_User_ID, AD_Role_ID, AD_Org_ID FROM AD_User_Roles WHERE AD_Role_ID= " + Role_id; + pstmt = null; + rs = null; + try { + pstmt = DB.prepareStatement(sql, getTrxName(ctx)); + rs = pstmt.executeQuery(); + while (rs.next()) { + createUserRole(ctx, document, rs.getInt("AD_User_ID"), rs.getInt("AD_Role_ID"), rs.getInt("AD_Org_ID")); + } + } catch (Exception e) { + log.log(Level.SEVERE, "AD_User_Roles", e); + throw new DatabaseAccessException("Failed to export user role assignment."); + } finally { + DB.close(rs, pstmt); + } + + // Process AD_Window_Access Values + sql = "SELECT AD_Window_ID, AD_Role_ID FROM AD_Window_Access WHERE AD_Role_ID= " + Role_id; + pstmt = null; + rs = null; + try { + pstmt = DB.prepareStatement(sql, getTrxName(ctx)); + rs = pstmt.executeQuery(); + while (rs.next()) { + createWindowAccess(ctx, document, rs.getInt("AD_Window_ID"), rs.getInt("AD_Role_ID")); + } + } catch (Exception e) { + log.log(Level.SEVERE, "AD_Window_Access", e); + throw new DatabaseAccessException("Failed to export window access."); + } finally { + DB.close(rs, pstmt); + } + + // Process AD_Process_Access Values + sql = "SELECT AD_Process_ID, AD_Role_ID FROM AD_Process_Access WHERE AD_Role_ID= " + Role_id; + pstmt = null; + rs = null; + try { + pstmt = DB.prepareStatement(sql, getTrxName(ctx)); + rs = pstmt.executeQuery(); + while (rs.next()) { + createProcessAccess(ctx, document, rs.getInt("AD_Process_ID"), rs.getInt("AD_Role_ID")); + } + } catch (Exception e) { + log.log(Level.SEVERE, "AD_Process_Access", e); + throw new DatabaseAccessException("Failed to export process access."); + } finally { + DB.close(rs, pstmt); + } + + // Process AD_Form_Access Values + sql = "SELECT AD_Form_ID, AD_Role_ID FROM AD_Form_Access WHERE AD_Role_ID= " + Role_id; + pstmt = null; + rs = null; + try { + pstmt = DB.prepareStatement(sql, getTrxName(ctx)); + rs = pstmt.executeQuery(); + while (rs.next()) { + createFormAccess(ctx, document, rs.getInt("AD_Form_ID"), rs.getInt("AD_Role_ID")); + } + } catch (Exception e) { + log.log(Level.SEVERE, "AD_Form_Access", e); + throw new DatabaseAccessException("Failed to export form access."); + } finally { + DB.close(rs, pstmt); + } + + // Process AD_Workflow_Access Values + sql = "SELECT AD_Workflow_ID, AD_Role_ID FROM AD_Workflow_Access WHERE AD_Role_ID= " + Role_id; + pstmt = null; + rs = null; + try { + pstmt = DB.prepareStatement(sql, getTrxName(ctx)); + rs = pstmt.executeQuery(); + while (rs.next()) { + createWorkflowAccess(ctx, document, rs.getInt("AD_Workflow_ID"), rs.getInt("AD_Role_ID")); + } + } catch (Exception e) { + log.log(Level.SEVERE, "AD_Workflow_Access", e); + throw new DatabaseAccessException("Failed to export workflow access."); + } finally { + DB.close(rs, pstmt); + } + + // Process AD_Task_Access Values + sql = "SELECT AD_Task_ID, AD_Role_ID FROM AD_Task_Access WHERE AD_Role_ID= " + Role_id; + pstmt = null; + rs = null; + try { + pstmt = DB.prepareStatement(sql, getTrxName(ctx)); + rs = pstmt.executeQuery(); + while (rs.next()) { + createTaskAccess(ctx, document, rs.getInt("AD_Task_ID"), rs.getInt("AD_Role_ID")); + } + } catch (Exception e) { + log.log(Level.SEVERE, "AD_Task_Access", e); + throw new DatabaseAccessException("Failed to export task access."); + } finally { + DB.close(rs, pstmt); + } + document.endElement("", "", I_AD_Role.Table_Name); + } + + private void createTaskAccess(Properties ctx, TransformerHandler document, + int AD_Task_ID, int AD_Role_ID) throws SAXException { + Env.setContext(ctx, X_AD_Task.COLUMNNAME_AD_Task_ID, AD_Task_ID); + Env.setContext(ctx, X_AD_Role.COLUMNNAME_AD_Role_ID, AD_Role_ID); + taskHandler.create(ctx, document); + ctx.remove(X_AD_Task.COLUMNNAME_AD_Task_ID); + ctx.remove(X_AD_Role.COLUMNNAME_AD_Role_ID); + } + + private void createWorkflowAccess(Properties ctx, + TransformerHandler document, int AD_Workflow_ID, int AD_Role_ID) throws SAXException { + Env.setContext(ctx, X_AD_Workflow.COLUMNNAME_AD_Workflow_ID, AD_Workflow_ID); + Env.setContext(ctx, X_AD_Role.COLUMNNAME_AD_Role_ID, AD_Role_ID); + workflowHandler.create(ctx, document); + ctx.remove(X_AD_Workflow.COLUMNNAME_AD_Workflow_ID); + ctx.remove(X_AD_Role.COLUMNNAME_AD_Role_ID); + } + + private void createFormAccess(Properties ctx, TransformerHandler document, + int AD_Form_ID, int AD_Role_ID) throws SAXException { + Env.setContext(ctx, X_AD_Form.COLUMNNAME_AD_Form_ID, AD_Form_ID); + Env.setContext(ctx, X_AD_Role.COLUMNNAME_AD_Role_ID, AD_Role_ID); + formHandler.create(ctx, document); + ctx.remove(X_AD_Form.COLUMNNAME_AD_Form_ID); + ctx.remove(X_AD_Role.COLUMNNAME_AD_Role_ID); + } + + private void createProcessAccess(Properties ctx, + TransformerHandler document, int AD_Process_ID, int AD_Role_ID) throws SAXException { + Env.setContext(ctx, X_AD_Process.COLUMNNAME_AD_Process_ID, AD_Process_ID); + Env.setContext(ctx, X_AD_Role.COLUMNNAME_AD_Role_ID, AD_Role_ID); + processHandler.create(ctx, document); + ctx.remove(X_AD_Process.COLUMNNAME_AD_Process_ID); + ctx.remove(X_AD_Role.COLUMNNAME_AD_Role_ID); + } + + private void createWindowAccess(Properties ctx, + TransformerHandler document, int AD_Window_ID, int AD_Role_ID) throws SAXException { + Env.setContext(ctx, X_AD_Window.COLUMNNAME_AD_Window_ID, AD_Window_ID); + Env.setContext(ctx, X_AD_Role.COLUMNNAME_AD_Role_ID, AD_Role_ID); + windowHandler.create(ctx, document); + ctx.remove(X_AD_Window.COLUMNNAME_AD_Window_ID); + ctx.remove(X_AD_Role.COLUMNNAME_AD_Role_ID); + } + + private void createUserRole(Properties ctx, TransformerHandler document, + int AD_User_ID, int AD_Role_ID, int AD_Org_ID) throws SAXException { + Env.setContext(ctx, X_AD_User.COLUMNNAME_AD_User_ID, AD_User_ID); + Env.setContext(ctx, X_AD_Role.COLUMNNAME_AD_Role_ID, AD_Role_ID); + Env.setContext(ctx, "AD_Org_ID", AD_Org_ID); + userHandler.create(ctx, document); + ctx.remove(X_AD_User.COLUMNNAME_AD_User_ID); + ctx.remove(X_AD_Role.COLUMNNAME_AD_Role_ID); + ctx.remove("AD_Org_ID"); + } + + private void createOrgAccess(Properties ctx, TransformerHandler document, + int AD_Org_ID, int AD_Role_ID) throws SAXException { + Env.setContext(ctx, "AD_Org_ID", AD_Org_ID); + Env.setContext(ctx, X_AD_Role.COLUMNNAME_AD_Role_ID, AD_Role_ID); + orgHandler.create(ctx, document); + ctx.remove("AD_Org_ID"); + ctx.remove(X_AD_Role.COLUMNNAME_AD_Role_ID); + } + + private void createRoleBinding(Properties ctx, TransformerHandler document, + X_AD_Role m_Role) { + PoExporter filler = new PoExporter(ctx, document, m_Role); + List excludes = defaultExcludeList(X_AD_Role.Table_Name); + if (m_Role.getAD_Role_ID() <= PackOut.MAX_OFFICIAL_ID) + filler.add("AD_Role_ID", new AttributesImpl()); + + if (m_Role.getC_Currency_ID() > 0) { + AttributesImpl currencyAtts = new AttributesImpl(); + String value = ReferenceUtils.getTableReference("C_Currency", "ISO_Code", m_Role.getC_Currency_ID(), currencyAtts); + filler.addString("C_Currency_ID", value, currencyAtts); + } else + filler.addString("C_Currency_ID", "", new AttributesImpl()); + + excludes.add(X_AD_Role.COLUMNNAME_C_Currency_ID); + filler.export(excludes); + } + + public void packOut(PackOut packout, TransformerHandler packoutHandler, TransformerHandler docHandler,int recordId) throws Exception + { + Env.setContext(packout.getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_Role_ID, recordId); + this.create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Role_ID); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/SQLStatementElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/SQLStatementElementHandler.java new file mode 100644 index 0000000000..1a43ddd5b4 --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/SQLStatementElementHandler.java @@ -0,0 +1,125 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.Statement; +import java.util.Properties; +import java.util.logging.Level; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.compiere.model.MPackageExpDetail; +import org.compiere.model.X_AD_Package_Exp_Detail; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class SQLStatementElementHandler extends AbstractElementHandler { + + public void startElement(Properties ctx, Element element) throws SAXException { + String elementValue = element.getElementValue(); + + log.info(elementValue); + String DBType = getStringValue(element, "DBType"); + String sql = getStringValue(element, "statement"); + if (sql.endsWith(";")) + sql = sql.substring(0, sql.length() - 1); + PreparedStatement pstmt = null; + try { + pstmt = DB.prepareStatement(sql, getTrxName(ctx)); + if(DBType.equals("ALL")) { + int n = pstmt.executeUpdate(); + log.info("Executed SQL Statement: "+ getStringValue(element, "statement") + " ReturnValue="+n); + } + else if(DB.isOracle() == true && DBType.equals("Oracle")) { + pstmt.executeUpdate(); + log.info("Executed SQL Statement for Oracle: "+ getStringValue(element, "statement")); + } + else if ( DB.isPostgreSQL() + && ( DBType.equals("Postgres") + || DBType.equals("PostgreSQL") // backward compatibility with old packages developed by hand + ) + ) { + // Avoid convert layer - command specific for postgresql + // + // pstmt = DB.prepareStatement(sql, null); + // pstmt.executeUpdate(); + // + Connection m_con = DB.getConnectionRW(true); + try { + Statement stmt = m_con.createStatement(); + int n = stmt.executeUpdate (sql); + log.info("Executed SQL Statement for PostgreSQL: "+ getStringValue(element,"statement") + " ReturnValue="+n); + // Postgres needs to commit DDL statements + if (m_con != null && !m_con.getAutoCommit()) + m_con.commit(); + stmt.close(); + } finally { + m_con.close(); + } + } + } catch (Exception e) { + log.log(Level.SEVERE,"SQLSatement", e); + } finally { + DB.close(pstmt); + } + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + String SQLStatement = Env.getContext(ctx, X_AD_Package_Exp_Detail.COLUMNNAME_SQLStatement); + String DBType = Env.getContext(ctx, X_AD_Package_Exp_Detail.COLUMNNAME_DBType); + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "custom"); + document.startElement("","","SQLStatement",atts); + createSQLStatmentBinding(document, SQLStatement, DBType); + document.endElement("","","SQLStatement"); + } + + private void createSQLStatmentBinding( TransformerHandler document, String sqlStatement, String DBType) throws SAXException + { + document.startElement("","","DBType", new AttributesImpl()); + char[] contents = DBType.toCharArray(); + document.characters(contents,0,contents.length); + document.endElement("","","DBType"); + + document.startElement("","","statement", new AttributesImpl()); + contents = sqlStatement.toCharArray(); + document.characters(contents,0,contents.length); + document.endElement("","","statement"); + + } + + public void packOut(PackOut packout, TransformerHandler packoutHandler, TransformerHandler docHandler,int field) throws Exception + { + MPackageExpDetail detail = packout.getPackageExpDetail(); + Env.setContext(packout.getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_SQLStatement, detail.getSQLStatement()); + Env.setContext(packout.getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_DBType, detail.getDBType()); + this.create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_SQLStatement); + packout.getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_DBType); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/TabElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/TabElementHandler.java new file mode 100644 index 0000000000..baba9bd72f --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/TabElementHandler.java @@ -0,0 +1,238 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.List; +import java.util.Properties; +import java.util.logging.Level; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.exceptions.AdempiereException; +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.ElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.ReferenceUtils; +import org.adempiere.pipo2.exception.DatabaseAccessException; +import org.adempiere.pipo2.exception.POSaveFailedException; +import org.compiere.model.I_AD_Tab; +import org.compiere.model.I_AD_Window; +import org.compiere.model.MTab; +import org.compiere.model.X_AD_Field; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.model.X_AD_Tab; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class TabElementHandler extends AbstractElementHandler { + + private FieldElementHandler fieldHandler = new FieldElementHandler(); + + public void startElement(Properties ctx, Element element) throws SAXException { + List excludes = defaultExcludeList(X_AD_Tab.Table_Name); + + String entitytype = getStringValue(element, "EntityType"); + if (isProcessElement(ctx, entitytype)) { + if (isParentDefer(element, I_AD_Window.Table_Name)) { + element.defer = true; + return; + } + + MTab mTab = findPO(ctx, element); + if (mTab == null) { + String name = getStringValue(element, "Name", excludes); + + int windowId = 0; + if (getParentId(element, I_AD_Window.Table_Name) > 0) { + windowId = getParentId(element, I_AD_Window.Table_Name); + } else { + Element windowElement = element.properties.get(I_AD_Tab.COLUMNNAME_AD_Window_ID); + windowId = ReferenceUtils.resolveReference(ctx, windowElement); + } + if (windowId <= 0) { + element.defer = true; + return; + } + + Element tableElement = element.properties.get(I_AD_Tab.COLUMNNAME_AD_Table_ID); + int tableId = ReferenceUtils.resolveReference(ctx, tableElement); + if (tableId <= 0) { + element.defer = true; + return; + } + + String sql = "SELECT AD_Tab_ID FROM AD_Tab where AD_Window_ID = ? " + + " AND Name = ?" + + " AND AD_Table_ID = ?"; + + int id = DB.getSQLValue(getTrxName(ctx), sql, windowId, name, tableId); + mTab = new MTab(ctx, id > 0 ? id : 0, getTrxName(ctx)); + mTab.setAD_Table_ID(tableId); + mTab.setName(name); + mTab.setAD_Window_ID(windowId); + } + + PoFiller filler = new PoFiller(ctx, mTab, element, this); + if (mTab.getAD_Tab_ID() == 0 && isOfficialId(element, "AD_Tab_ID")) + mTab.setAD_Tab_ID(getIntValue(element, "AD_Tab_ID")); + + Element columnElement = element.properties.get(I_AD_Tab.COLUMNNAME_AD_Column_ID); + int AD_Column_ID = 0; + if (ReferenceUtils.isIDLookup(columnElement) || ReferenceUtils.isUUIDLookup(columnElement)) { + AD_Column_ID = ReferenceUtils.resolveReference(ctx, columnElement); + } else if (columnElement.contents != null && columnElement.contents.length() > 0){ + AD_Column_ID = findIdByColumnAndParentId (ctx, "AD_Column","ColumnName", columnElement.contents.toString(), + "AD_Table", mTab.getAD_Table_ID()); + } + mTab.setAD_Column_ID(AD_Column_ID); + + columnElement = element.properties.get(I_AD_Tab.COLUMNNAME_AD_ColumnSortOrder_ID); + AD_Column_ID = 0; + if (ReferenceUtils.isIDLookup(columnElement) || ReferenceUtils.isUUIDLookup(columnElement)) { + AD_Column_ID = ReferenceUtils.resolveReference(ctx, columnElement); + } else if (columnElement.contents != null && columnElement.contents.length() > 0){ + AD_Column_ID = findIdByColumnAndParentId (ctx, "AD_Column","ColumnName", columnElement.contents.toString(), + "AD_Table", mTab.getAD_Table_ID()); + } + mTab.setAD_ColumnSortOrder_ID(AD_Column_ID); + + columnElement = element.properties.get(I_AD_Tab.COLUMNNAME_AD_ColumnSortYesNo_ID); + AD_Column_ID = 0; + if (ReferenceUtils.isIDLookup(columnElement) || ReferenceUtils.isUUIDLookup(columnElement)) { + AD_Column_ID = ReferenceUtils.resolveReference(ctx, columnElement); + } else if (columnElement.contents != null && columnElement.contents.length() > 0){ + AD_Column_ID = findIdByColumnAndParentId (ctx, "AD_Column","ColumnName", columnElement.contents.toString(), + "AD_Table", mTab.getAD_Table_ID()); + } + mTab.setAD_ColumnSortYesNo_ID(AD_Column_ID); + + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + + if (mTab.is_new() || mTab.is_Changed()) { + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_Tab.Table_Name, + X_AD_Tab.Table_ID); + String action = null; + if (!mTab.is_new()){ + backupRecord(ctx, impDetail.getAD_Package_Imp_Detail_ID(), X_AD_Tab.Table_Name,mTab); + action = "Update"; + } + else{ + action = "New"; + } + if (mTab.save(getTrxName(ctx)) == true){ + logImportDetail (ctx, impDetail, 1, mTab.getName(), mTab.get_ID(),action); + element.recordId = mTab.getAD_Tab_ID(); + } else { + logImportDetail (ctx, impDetail, 0, mTab.getName(), mTab.get_ID(),action); + throw new POSaveFailedException("Tab"); + } + } + } else { + element.skip = true; + } + + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + PackOut packOut = getPackOutProcess(ctx); + int AD_Tab_ID = Env.getContextAsInt(ctx, X_AD_Tab.COLUMNNAME_AD_Tab_ID); + X_AD_Tab m_Tab = new X_AD_Tab (ctx, AD_Tab_ID, getTrxName(ctx)); + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "table"); + document.startElement("","",I_AD_Tab.Table_Name,atts); + createTabBinding(ctx,document,m_Tab); + //Fields tags. + String sql = "SELECT AD_Field_ID FROM AD_FIELD WHERE AD_TAB_ID = " + AD_Tab_ID + + "ORDER BY SEQNO asc"; + PreparedStatement pstmt = null; + ResultSet rs = null; + try { + pstmt = DB.prepareStatement (sql, getTrxName(ctx)); + rs = pstmt.executeQuery(); + while (rs.next()) + { + createField(ctx, document, rs.getInt("AD_Field_ID")); + } + } + catch (Exception e) + { + log.log(Level.SEVERE,e.getLocalizedMessage(), e); + throw new DatabaseAccessException("Failed to export window tab", e); + } + finally + { + DB.close(rs, pstmt); + } + document.endElement("","",I_AD_Tab.Table_Name); + + if(m_Tab.getAD_Process_ID() > 0 ) + { + try + { + ElementHandler handler = packOut.getHandler("P"); + handler.packOut(packOut,document,null,m_Tab.getAD_Process_ID()); + } + catch(Exception e) + { + throw new AdempiereException(e); + } + } + + } + + private void createField(Properties ctx, TransformerHandler document, + int AD_Field_ID) throws SAXException { + Env.setContext(ctx, X_AD_Field.COLUMNNAME_AD_Field_ID, AD_Field_ID); + fieldHandler.create(ctx, document); + ctx.remove(X_AD_Field.COLUMNNAME_AD_Field_ID); + } + + private void createTabBinding(Properties ctx, TransformerHandler document, X_AD_Tab m_Tab) + { + PoExporter filler = new PoExporter(ctx, document, m_Tab); + List excludes = defaultExcludeList(X_AD_Tab.Table_Name); + + if (m_Tab.getAD_Tab_ID() <= PackOut.MAX_OFFICIAL_ID) + filler.add("AD_Tab_ID", new AttributesImpl()); + + filler.export(excludes); + } + + @Override + public void packOut(PackOut packout, TransformerHandler packoutHandler, + TransformerHandler docHandler, + int recordId) throws Exception { + Env.setContext(packout.getCtx(), I_AD_Tab.COLUMNNAME_AD_Tab_ID, recordId); + create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(I_AD_Tab.COLUMNNAME_AD_Tab_ID); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/TableElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/TableElementHandler.java new file mode 100644 index 0000000000..808352ec7b --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/TableElementHandler.java @@ -0,0 +1,217 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.exceptions.AdempiereException; +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.ElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackIn; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.exception.POSaveFailedException; +import org.compiere.model.I_AD_Table; +import org.compiere.model.MTable; +import org.compiere.model.X_AD_Column; +import org.compiere.model.X_AD_Package_Exp_Detail; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.model.X_AD_Table; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class TableElementHandler extends AbstractElementHandler { + private ColumnElementHandler columnHandler = new ColumnElementHandler(); + + private Listtables = new ArrayList(); + + public void startElement(Properties ctx, Element element) throws SAXException { + PackIn packIn = getPackInProcess(ctx); + List excludes = defaultExcludeList(X_AD_Table.Table_Name); + + String entitytype = getStringValue(element, "EntityType"); + if (isProcessElement(ctx, entitytype)) { + + MTable mTable = findPO(ctx, element); + if (mTable == null) { + String tableName = getStringValue(element, "TableName", excludes); + + int id = packIn.getTableId(tableName); + if (id <= 0) { + id = findIdByColumn(ctx, "AD_Table", "TableName", tableName); + if (id > 0) + packIn.addTable(tableName, id); + } + if (id > 0 && isTableProcess(ctx, id)) { + return; + } + + mTable = new MTable(ctx, id > 0 ? id : 0, getTrxName(ctx)); + mTable.setTableName(tableName); + } + + if (mTable.getAD_Table_ID() == 0 && isOfficialId(element, "AD_Table_ID")) + { + mTable.setAD_Table_ID(getIntValue(element, "AD_Table_ID")); + } + + PoFiller filler = new PoFiller(ctx, mTable, element, this); + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + + if (mTable.is_new() || mTable.is_Changed()) { + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_Table.Table_Name, + X_AD_Table.Table_ID); + String action = null; + if (!mTable.is_new()){ + backupRecord(ctx, impDetail.getAD_Package_Imp_Detail_ID(),X_AD_Table.Table_Name,mTable); + action = "Update"; + } + else{ + action = "New"; + } + if (mTable.save(getTrxName(ctx)) == true){ + logImportDetail (ctx, impDetail, 1, mTable.getName(),mTable.get_ID(),action); + tables.add(mTable.getAD_Table_ID()); + packIn.addTable(mTable.getTableName(), mTable.getAD_Table_ID()); + element.recordId = mTable.getAD_Table_ID(); + } + else{ + logImportDetail (ctx, impDetail, 0, mTable.getName(), mTable.get_ID(),action); + throw new POSaveFailedException("Table"); + } + } + } else { + element.skip = true; + } + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + + int AD_Table_ID = Env.getContextAsInt(ctx, X_AD_Package_Exp_Detail.COLUMNNAME_AD_Table_ID); + PackOut packOut = getPackOutProcess(ctx); + boolean exported = isTableProcess(ctx, AD_Table_ID); + AttributesImpl atts = new AttributesImpl(); + //Export table if not already done so + if (!exported){ + X_AD_Table m_Table = new X_AD_Table (ctx, AD_Table_ID, null); + addTypeName(atts, "table"); + document.startElement("","",I_AD_Table.Table_Name,atts); + createTableBinding(ctx,document,m_Table); + + String sql = "SELECT * FROM AD_Column WHERE AD_Table_ID = ? " + + " ORDER BY IsKey DESC, AD_Column_ID"; // Export key column as the first one + + PreparedStatement pstmt = null; + ResultSet rs = null; + + try { + pstmt = DB.prepareStatement (sql, getTrxName(ctx)); + pstmt.setInt(1, AD_Table_ID); + rs = pstmt.executeQuery(); + + while (rs.next()){ + ElementHandler handler = packOut.getHandler("ELE"); + handler.packOut(packOut,document,null,rs.getInt(X_AD_Column.COLUMNNAME_AD_Element_ID)); + + if (rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Reference_ID)>0) + { + handler = packOut.getHandler("REF"); + handler.packOut(packOut,document,null,rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Reference_ID)); + } + + if (rs.getInt("AD_Reference_Value_ID")>0) + { + handler = packOut.getHandler("REF"); + handler.packOut(packOut,document,null,rs.getInt("AD_Reference_Value_ID")); + } + + if (rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Process_ID)>0) + { + handler = packOut.getHandler("P"); + handler.packOut(packOut,document,null,rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Process_ID)); + } + + if (rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Val_Rule_ID)>0) + { + handler = packOut.getHandler("V"); + handler.packOut(packOut,document,null,rs.getInt(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Val_Rule_ID)); + } + + createColumn(ctx, document, rs.getInt("AD_Column_ID")); + } + } catch (Exception e) { + throw new AdempiereException(e); + } finally { + DB.close(rs, pstmt); + } + document.endElement("","",I_AD_Table.Table_Name); + } + + } + + private void createColumn(Properties ctx, TransformerHandler document, int AD_Column_ID) throws SAXException { + Env.setContext(ctx, X_AD_Column.COLUMNNAME_AD_Column_ID, AD_Column_ID); + columnHandler.create(ctx, document); + ctx.remove(X_AD_Column.COLUMNNAME_AD_Column_ID); + } + + private boolean isTableProcess(Properties ctx, int AD_Table_ID) { + if (tables.contains(AD_Table_ID)) + return true; + else { + tables.add(AD_Table_ID); + return false; + } + } + + private void createTableBinding(Properties ctx, TransformerHandler document, X_AD_Table m_Table) + { + PoExporter filler = new PoExporter(ctx, document, m_Table); + if (m_Table.getAD_Table_ID() <= PackOut.MAX_OFFICIAL_ID) + { + filler.add("AD_Table_ID", new AttributesImpl()); + } + + List excludes = defaultExcludeList(X_AD_Table.Table_Name); + filler.export(excludes); + } + + public void packOut(PackOut packout, TransformerHandler packoutHandler, TransformerHandler docHandler,int recordId) throws Exception + { + Env.setContext(packout.getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_Table_ID, recordId); + this.create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Table_ID); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/TaskAccessElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/TaskAccessElementHandler.java new file mode 100644 index 0000000000..6f23d61101 --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/TaskAccessElementHandler.java @@ -0,0 +1,109 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.ReferenceUtils; +import org.compiere.model.I_AD_Role; +import org.compiere.model.I_AD_Task_Access; +import org.compiere.model.Query; +import org.compiere.model.X_AD_Role; +import org.compiere.model.X_AD_Task; +import org.compiere.model.X_AD_Task_Access; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class TaskAccessElementHandler extends AbstractElementHandler { + + public void startElement(Properties ctx, Element element) throws SAXException { + int roleid =0; + int taskid =0; + List excludes = defaultExcludeList(X_AD_Task_Access.Table_Name); + + X_AD_Task_Access po = findPO(ctx, element); + if (po == null) { + if (getParentId(element, I_AD_Role.Table_Name) > 0) { + roleid = getParentId(element, I_AD_Role.Table_Name); + } else { + Element roleElement = element.properties.get(I_AD_Task_Access.COLUMNNAME_AD_Role_ID); + roleid = ReferenceUtils.resolveReference(ctx, roleElement); + } + + Element taskElement = element.properties.get(I_AD_Task_Access.COLUMNNAME_AD_Task_ID); + taskid = ReferenceUtils.resolveReference(ctx, taskElement); + + Query query = new Query(ctx, "AD_Task_Access", "AD_Role_ID=? and AD_Task_ID=?", getTrxName(ctx)); + po = query.setParameters(new Object[]{roleid, taskid}).first(); + if (po == null){ + po = new X_AD_Task_Access(ctx, 0, getTrxName(ctx)); + po.setAD_Role_ID(roleid); + po.setAD_Task_ID(taskid); + } + excludes.add(I_AD_Task_Access.COLUMNNAME_AD_Role_ID); + excludes.add(I_AD_Task_Access.COLUMNNAME_AD_Task_ID); + } + PoFiller filler = new PoFiller(ctx, po, element, this); + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + po.saveEx(); + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int AD_Task_ID = Env.getContextAsInt(ctx, X_AD_Task.COLUMNNAME_AD_Task_ID); + int AD_Role_ID = Env.getContextAsInt(ctx, X_AD_Role.COLUMNNAME_AD_Role_ID); + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "table"); + document.startElement("", "", I_AD_Task_Access.Table_Name, atts); + createTaskAccessBinding(ctx, document, AD_Task_ID, AD_Role_ID); + document.endElement("", "", I_AD_Task_Access.Table_Name); + } + + private void createTaskAccessBinding(Properties ctx, TransformerHandler document, + int taskid, int roleid) { + Query query = new Query(ctx, "AD_Task_Access", "AD_Role_ID=? and AD_Task_ID=?", getTrxName(ctx)); + X_AD_Task_Access po = query.setParameters(new Object[]{roleid, taskid}).first(); + if (po != null) { + PoExporter filler = new PoExporter(ctx, document, po); + List excludes = defaultExcludeList(X_AD_Task_Access.Table_Name); + filler.export(excludes); + } + } + + @Override + public void packOut(PackOut packout, TransformerHandler packoutHandler, + TransformerHandler docHandler, + int recordId) throws Exception { + create(packout.getCtx(), packoutHandler); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/TaskElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/TaskElementHandler.java new file mode 100644 index 0000000000..9037a06148 --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/TaskElementHandler.java @@ -0,0 +1,126 @@ +/****************************************************************************** +. * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + + +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.exception.POSaveFailedException; +import org.compiere.model.I_AD_Task; +import org.compiere.model.MTask; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.model.X_AD_Task; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class TaskElementHandler extends AbstractElementHandler { + + private List tasks = new ArrayList(); + + public void startElement(Properties ctx, Element element) + throws SAXException { + List excludes = defaultExcludeList(X_AD_Task.Table_Name); + + String entitytype = getStringValue(element, "EntityType"); + if (isProcessElement(ctx, entitytype)) { + + MTask mTask = findPO(ctx, element); + if (mTask == null) { + String name = getStringValue(element, "Name"); + int id = findIdByName(ctx, "AD_Task", name); + mTask = new MTask(ctx, id > 0 ? id : 0, getTrxName(ctx)); + } + + if (mTask.getAD_Task_ID() == 0 && isOfficialId(element, "AD_Task_ID")) + mTask.setAD_Task_ID(getIntValue(element, "AD_Task_ID")); + + PoFiller filler = new PoFiller(ctx, mTask, element, this); + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + + if (mTask.is_new() || mTask.is_Changed()) { + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_Task.Table_Name, + X_AD_Task.Table_ID); + String action = null; + if (!mTask.is_new()) { + backupRecord(ctx, impDetail.getAD_Package_Imp_Detail_ID(), X_AD_Task.Table_Name, mTask); + action = "Update"; + } else { + action = "New"; + } + if (mTask.save(getTrxName(ctx)) == true) { + logImportDetail(ctx, impDetail, 1, mTask.getName(), mTask.get_ID(), + action); + } else { + logImportDetail(ctx, impDetail, 0, mTask.getName(), mTask.get_ID(), + action); + throw new POSaveFailedException("Task"); + } + } + } else { + element.skip = true; + } + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int AD_Task_ID = Env.getContextAsInt(ctx, "AD_Task_ID"); + if (tasks.contains(AD_Task_ID)) + return; + tasks.add(AD_Task_ID); + X_AD_Task m_Task = new X_AD_Task(ctx, AD_Task_ID, null); + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "table"); + document.startElement("", "", I_AD_Task.Table_Name, atts); + createTaskBinding(ctx, document, m_Task); + document.endElement("", "", I_AD_Task.Table_Name); + + } + + private void createTaskBinding(Properties ctx, TransformerHandler document, + X_AD_Task m_Task) { + PoExporter filler = new PoExporter(ctx, document, m_Task); + List excludes = defaultExcludeList(X_AD_Task.Table_Name); + if (m_Task.getAD_Task_ID() <= PackOut.MAX_OFFICIAL_ID) + filler.add("AD_Task_ID", new AttributesImpl()); + filler.export(excludes); + } + + public void packOut(PackOut packout, TransformerHandler packoutHandler, TransformerHandler docHandler,int recordId) throws Exception + { + Env.setContext(packout.getCtx(), X_AD_Task.COLUMNNAME_AD_Task_ID, recordId); + + this.create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(X_AD_Task.COLUMNNAME_AD_Task_ID); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/UserRoleElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/UserRoleElementHandler.java new file mode 100644 index 0000000000..a836ee9b04 --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/UserRoleElementHandler.java @@ -0,0 +1,116 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.ReferenceUtils; +import org.compiere.model.I_AD_User_Roles; +import org.compiere.model.Query; +import org.compiere.model.X_AD_Role; +import org.compiere.model.X_AD_User; +import org.compiere.model.X_AD_User_Roles; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class UserRoleElementHandler extends AbstractElementHandler { + + public void startElement(Properties ctx, Element element) throws SAXException { + int roleid =0; + int userid =0; + int orgid =0; + + List excludes = defaultExcludeList(X_AD_User_Roles.Table_Name); + + X_AD_User_Roles po = findPO(ctx, element); + if (po == null) { + Element userElement = element.properties.get(I_AD_User_Roles.COLUMNNAME_AD_User_ID); + userid = ReferenceUtils.resolveReference(ctx, userElement); + + if (getParentId(element, "role") > 0) { + roleid = getParentId(element, "role"); + } else { + Element roleElement = element.properties.get(I_AD_User_Roles.COLUMNNAME_AD_Role_ID); + roleid = ReferenceUtils.resolveReference(ctx, roleElement); + } + + Element orgElement = element.properties.get(I_AD_User_Roles.COLUMNNAME_AD_Org_ID); + orgid = ReferenceUtils.resolveReference(ctx, orgElement); + + Query query = new Query(ctx, "AD_User_Roles", "AD_User_ID = ? AND AD_Role_ID = ? AND AD_Org_ID = ?", getTrxName(ctx)); + po = query.setParameters(new Object[]{userid, roleid, orgid}).first(); + if (po == null) { + po = new X_AD_User_Roles(ctx, 0, getTrxName(ctx)); + po.setAD_Org_ID(orgid); + po.setAD_Role_ID(roleid); + po.setAD_User_ID(userid); + } + excludes.add(I_AD_User_Roles.COLUMNNAME_AD_User_ID); + excludes.add(I_AD_User_Roles.COLUMNNAME_AD_Role_ID); + excludes.add(I_AD_User_Roles.COLUMNNAME_AD_Org_ID); + } + PoFiller filler = new PoFiller(ctx, po, element, this); + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + po.saveEx(); + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int AD_User_ID = Env.getContextAsInt(ctx, X_AD_User.COLUMNNAME_AD_User_ID); + int AD_Role_ID = Env.getContextAsInt(ctx, X_AD_Role.COLUMNNAME_AD_Role_ID); + int AD_Org_ID = Env.getContextAsInt(ctx, "AD_Org_ID"); + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "table"); + document.startElement("", "", I_AD_User_Roles.Table_Name, atts); + createUserAssignBinding(ctx, document, AD_User_ID,AD_Role_ID, AD_Org_ID); + document.endElement("", "", I_AD_User_Roles.Table_Name); + } + + private void createUserAssignBinding(Properties ctx, TransformerHandler document, + int user_id, int role_id, int org_id) { + + Query query = new Query(ctx, "AD_User_Roles", "AD_User_ID = ? AND AD_Role_ID = ? AND AD_Org_ID = ?", getTrxName(ctx)); + X_AD_User_Roles po = query.setParameters(new Object[]{user_id, role_id, org_id}).first(); + PoExporter filler = new PoExporter(ctx, document, po); + List excludes = defaultExcludeList(X_AD_User_Roles.Table_Name); + + filler.export(excludes); + } + + @Override + public void packOut(PackOut packout, TransformerHandler packoutHandler, + TransformerHandler docHandler, + int recordId) throws Exception { + create(packout.getCtx(), packoutHandler); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/WindowAccessElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/WindowAccessElementHandler.java new file mode 100644 index 0000000000..f28c828f6f --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/WindowAccessElementHandler.java @@ -0,0 +1,115 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.ReferenceUtils; +import org.compiere.model.I_AD_Role; +import org.compiere.model.I_AD_Window_Access; +import org.compiere.model.Query; +import org.compiere.model.X_AD_Role; +import org.compiere.model.X_AD_Window; +import org.compiere.model.X_AD_Window_Access; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class WindowAccessElementHandler extends AbstractElementHandler { + + public void startElement(Properties ctx, Element element) throws SAXException { + int roleid =0; + int windowid =0; + List excludes = defaultExcludeList(X_AD_Window_Access.Table_Name); + + X_AD_Window_Access po = findPO(ctx, element); + if (po == null) { + if (getParentId(element, I_AD_Role.Table_Name) > 0) { + roleid = getParentId(element, I_AD_Role.Table_Name); + } else { + Element roleElement = element.properties.get(I_AD_Window_Access.COLUMNNAME_AD_Role_ID); + roleid = ReferenceUtils.resolveReference(ctx, roleElement); + } + if (roleid <= 0) { + element.defer = true; + return; + } + + Element windowElement = element.properties.get(I_AD_Window_Access.COLUMNNAME_AD_Window_ID); + windowid = ReferenceUtils.resolveReference(ctx, windowElement); + if (windowid <= 0) { + element.defer = true; + return; + } + + Query query = new Query(ctx, "AD_Window_Access", "AD_Role_ID=? and AD_Window_ID=?", getTrxName(ctx)); + po = query.setParameters(new Object[]{roleid, windowid}).first(); + if (po == null) { + po = new X_AD_Window_Access(ctx, 0, getTrxName(ctx)); + po.setAD_Role_ID(roleid); + po.setAD_Window_ID(windowid); + } + } + PoFiller filler = new PoFiller(ctx, po, element, this); + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + po.saveEx(); + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int AD_Window_ID = Env.getContextAsInt(ctx, X_AD_Window.COLUMNNAME_AD_Window_ID); + int AD_Role_ID = Env.getContextAsInt(ctx, X_AD_Role.COLUMNNAME_AD_Role_ID); + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "table"); + document.startElement("", "", I_AD_Window_Access.Table_Name, atts); + createWindowAccessBinding(ctx, document, AD_Window_ID, AD_Role_ID); + document.endElement("", "", I_AD_Window_Access.Table_Name); + } + + private void createWindowAccessBinding(Properties ctx, TransformerHandler document, + int window_id, int role_id) { + + Query query = new Query(ctx, "AD_Window_Access", "AD_Role_ID=? and AD_Window_ID=?", getTrxName(ctx)); + X_AD_Window_Access po = query.setParameters(new Object[]{role_id, window_id}).first(); + PoExporter filler = new PoExporter(ctx, document, po); + List excludes = defaultExcludeList(X_AD_Window_Access.Table_Name); + + filler.export(excludes); + } + + @Override + public void packOut(PackOut packout, TransformerHandler packoutHandler, + TransformerHandler docHandler, + int recordId) throws Exception { + create(packout.getCtx(), packoutHandler); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/WindowElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/WindowElementHandler.java new file mode 100644 index 0000000000..ae6c175945 --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/WindowElementHandler.java @@ -0,0 +1,219 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import java.util.logging.Level; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.ElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.exception.DatabaseAccessException; +import org.adempiere.pipo2.exception.POSaveFailedException; +import org.compiere.model.I_AD_Window; +import org.compiere.model.MWindow; +import org.compiere.model.X_AD_Package_Exp_Detail; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.model.X_AD_Preference; +import org.compiere.model.X_AD_Tab; +import org.compiere.model.X_AD_Window; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class WindowElementHandler extends AbstractElementHandler { + + private TabElementHandler tabHandler = new TabElementHandler(); + private PreferenceElementHandler preferenceHandler = new PreferenceElementHandler(); + + private List windows = new ArrayList(); + + public void startElement(Properties ctx, Element element) + throws SAXException { + List excludes = defaultExcludeList(X_AD_Window.Table_Name); + + String entitytype = getStringValue(element, "EntityType"); + if (isProcessElement(ctx, entitytype)) { + MWindow mWindow = findPO(ctx, element); + if (mWindow == null) { + String name = getStringValue(element, "Name", excludes); + int id = findIdByName(ctx, "AD_Window", name); + if (id > 0 && windows.contains(id)) { + return; + } + + mWindow = new MWindow(ctx, id > 0 ? id : 0, getTrxName(ctx)); + mWindow.setName(name); + } else { + if (windows.contains(mWindow.getAD_Window_ID())) { + return; + } + } + + if (mWindow.getAD_Window_ID() == 0 && isOfficialId(element, "AD_Window_ID")) + mWindow.setAD_Window_ID(getIntValue(element, "AD_Window_ID")); + + PoFiller filler = new PoFiller(ctx, mWindow, element, this); + + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + + if (mWindow.is_new() || mWindow.is_Changed()) { + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_Window.Table_Name, + X_AD_Window.Table_ID); + String action = null; + if (!mWindow.is_new()) { + backupRecord(ctx, impDetail.getAD_Package_Imp_Detail_ID(), X_AD_Window.Table_Name, mWindow); + action = "Update"; + } else { + action = "New"; + } + if (mWindow.save(getTrxName(ctx)) == true) { + logImportDetail(ctx, impDetail, 1, mWindow.getName(), mWindow + .get_ID(), action); + element.recordId = mWindow.getAD_Window_ID(); + windows.add(mWindow.getAD_Window_ID()); + } else { + logImportDetail(ctx, impDetail, 0, mWindow.getName(), mWindow + .get_ID(), action); + throw new POSaveFailedException("Window"); + } + } + } else { + element.skip = true; + } + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int AD_Window_ID = Env.getContextAsInt(ctx, "AD_Window_ID"); + PackOut packOut = (PackOut) ctx.get("PackOutProcess"); + + X_AD_Window m_Window = new X_AD_Window(ctx, AD_Window_ID, null); + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "table"); + document.startElement("", "", I_AD_Window.Table_Name, atts); + createWindowBinding(ctx, document, m_Window); + // Tab Tag + String sql = "SELECT AD_Tab_ID, AD_Table_ID FROM AD_TAB WHERE AD_WINDOW_ID = " + + AD_Window_ID; + PreparedStatement pstmt = null; + ResultSet rs = null; + try { + pstmt = DB.prepareStatement(sql, getTrxName(ctx)); + rs = pstmt.executeQuery(); + while (rs.next()) { + ElementHandler handler = packOut.getHandler("T"); + handler.packOut(packOut,document,null,rs.getInt("AD_Table_ID")); + + createTab(ctx, document, rs.getInt("AD_Tab_ID")); + } + } catch (Exception e) { + log.log(Level.SEVERE, e.getLocalizedMessage(), e); + if (e instanceof SAXException) + throw (SAXException) e; + else if (e instanceof SQLException) + throw new DatabaseAccessException("Failed to export window.", e); + else if (e instanceof RuntimeException) + throw (RuntimeException) e; + else + throw new RuntimeException("Failed to export window.", e); + } finally { + DB.close(rs, pstmt); + } + + //TODO: export of ad_image and ad_color use + + // Loop tags. + document.endElement("", "", I_AD_Window.Table_Name); + + // Preference Tag + sql = "SELECT AD_Preference_ID FROM AD_PREFERENCE WHERE AD_WINDOW_ID = ?"; + pstmt = null; + rs = null; + try { + pstmt = DB.prepareStatement(sql, getTrxName(ctx)); + pstmt.setInt(1, AD_Window_ID); + rs = pstmt.executeQuery(); + while (rs.next()) { + createPreference(ctx, document, rs.getInt("AD_Preference_ID")); + } + } catch (Exception e) { + log.log(Level.SEVERE, e.getLocalizedMessage(), e); + if (e instanceof SAXException) + throw (SAXException) e; + else if (e instanceof SQLException) + throw new DatabaseAccessException("Failed to export window preference.", e); + else if (e instanceof RuntimeException) + throw (RuntimeException) e; + else + throw new RuntimeException("Failed to export window preference.", e); + } finally { + DB.close(rs, pstmt); + } + } + + private void createPreference(Properties ctx, TransformerHandler document, + int AD_Preference_ID) throws SAXException { + Env.setContext(ctx, X_AD_Preference.COLUMNNAME_AD_Preference_ID, + AD_Preference_ID); + preferenceHandler.create(ctx, document); + ctx.remove(X_AD_Preference.COLUMNNAME_AD_Preference_ID); + } + + private void createTab(Properties ctx, TransformerHandler document, + int AD_Tab_ID) throws SAXException { + Env.setContext(ctx, X_AD_Tab.COLUMNNAME_AD_Tab_ID, AD_Tab_ID); + tabHandler.create(ctx, document); + ctx.remove(X_AD_Tab.COLUMNNAME_AD_Tab_ID); + } + + private void createWindowBinding(Properties ctx, TransformerHandler document, + X_AD_Window m_Window) { + PoExporter filler = new PoExporter(ctx, document, m_Window); + List excludes = defaultExcludeList(X_AD_Window.Table_Name); + + if (m_Window.getAD_Window_ID() <= PackOut.MAX_OFFICIAL_ID) + filler.add("AD_Window_ID", new AttributesImpl()); + + filler.export(excludes); + } + + public void packOut(PackOut packout, TransformerHandler packoutHandler, TransformerHandler docHandler,int recordId) throws Exception + { + Env.setContext(packout.getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_Window_ID, recordId); + this.create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Window_ID); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/WorkflowAccessElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/WorkflowAccessElementHandler.java new file mode 100644 index 0000000000..549ab98ada --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/WorkflowAccessElementHandler.java @@ -0,0 +1,111 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.ReferenceUtils; +import org.compiere.model.I_AD_Role; +import org.compiere.model.I_AD_Workflow_Access; +import org.compiere.model.Query; +import org.compiere.model.X_AD_Role; +import org.compiere.model.X_AD_Workflow; +import org.compiere.model.X_AD_Workflow_Access; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class WorkflowAccessElementHandler extends AbstractElementHandler { + + public void startElement(Properties ctx, Element element) throws SAXException { + int roleid =0; + int workflowid =0; + List excludes = defaultExcludeList(X_AD_Workflow_Access.Table_Name); + + X_AD_Workflow_Access po = findPO(ctx, element); + if (po == null) { + if (getParentId(element, I_AD_Role.Table_Name) > 0) { + roleid = getParentId(element, I_AD_Role.Table_Name); + } else { + Element roleElement = element.properties.get(I_AD_Workflow_Access.COLUMNNAME_AD_Role_ID); + roleid = ReferenceUtils.resolveReference(ctx, roleElement); + } + + Element wfElement = element.properties.get(I_AD_Workflow_Access.COLUMNNAME_AD_Workflow_ID); + workflowid = ReferenceUtils.resolveReference(ctx, wfElement); + + Query query = new Query(ctx, "AD_Workflow_Access", "AD_Role_ID=? and AD_Workflow_ID=?", getTrxName(ctx)); + po = query.setParameters(new Object[]{roleid, workflowid}).first(); + if (po == null) { + po = new X_AD_Workflow_Access(ctx, 0, getTrxName(ctx)); + po.setAD_Role_ID(roleid); + po.setAD_Workflow_ID(workflowid); + } + excludes.add(I_AD_Workflow_Access.COLUMNNAME_AD_Role_ID); + excludes.add(I_AD_Workflow_Access.COLUMNNAME_AD_Workflow_ID); + } + + PoFiller filler = new PoFiller(ctx, po, element, this); + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + po.saveEx(); + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int AD_Workflow_ID = Env.getContextAsInt(ctx, X_AD_Workflow.COLUMNNAME_AD_Workflow_ID); + int AD_Role_ID = Env.getContextAsInt(ctx, X_AD_Role.COLUMNNAME_AD_Role_ID); + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "table"); + document.startElement("", "", I_AD_Workflow_Access.Table_Name, atts); + createWorkflowAccessBinding(ctx, document, AD_Workflow_ID, AD_Role_ID); + document.endElement("", "", I_AD_Workflow_Access.Table_Name); + } + + private void createWorkflowAccessBinding(Properties ctx, TransformerHandler document, + int workflow_id, int role_id) { + + X_AD_Workflow_Access po = null; + Query query = new Query(ctx, "AD_Workflow_Access", "AD_Role_ID=? and AD_Workflow_ID=?", getTrxName(ctx)); + po = query.setParameters(new Object[]{role_id, workflow_id}).first(); + PoExporter filler = new PoExporter(ctx, document, po); + List excludes = defaultExcludeList(X_AD_Workflow_Access.Table_Name); + + filler.export(excludes); + } + + @Override + public void packOut(PackOut packout, TransformerHandler packoutHandler, + TransformerHandler docHandler, + int recordId) throws Exception { + create(packout.getCtx(), packoutHandler); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/WorkflowElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/WorkflowElementHandler.java new file mode 100644 index 0000000000..22824fba3e --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/WorkflowElementHandler.java @@ -0,0 +1,251 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.exceptions.DBException; +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.exception.POSaveFailedException; +import org.compiere.model.I_AD_Workflow; +import org.compiere.model.X_AD_Package_Exp_Detail; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.model.X_AD_WF_NextCondition; +import org.compiere.model.X_AD_WF_Node; +import org.compiere.model.X_AD_WF_NodeNext; +import org.compiere.model.X_AD_Workflow; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.compiere.wf.MWorkflow; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class WorkflowElementHandler extends AbstractElementHandler { + + private WorkflowNodeElementHandler nodeHandler = new WorkflowNodeElementHandler(); + private WorkflowNodeNextElementHandler nodeNextHandler = new WorkflowNodeNextElementHandler(); + private WorkflowNodeNextConditionElementHandler nextConditionHandler = new WorkflowNodeNextConditionElementHandler(); + + private List workflows = new ArrayList(); + + public void startElement(Properties ctx, Element element) + throws SAXException { + List excludes = defaultExcludeList(X_AD_Workflow.Table_Name); + + String entitytype = getStringValue(element, "EntityType"); + if (isProcessElement(ctx, entitytype)) { + + MWorkflow mWorkflow = findPO(ctx, element); + if (mWorkflow == null) { + String workflowValue = getStringValue(element, "Value", excludes); + int id = findIdByColumn(ctx, "AD_Workflow", "Value", workflowValue); + if (id > 0 && workflows.contains(id)) { + element.skip = true; + return; + } + + mWorkflow = new MWorkflow(ctx, id > 0 ? id : 0, getTrxName(ctx)); + mWorkflow.setValue(workflowValue); + } + + PoFiller filler = new PoFiller(ctx, mWorkflow, element, this); + if (mWorkflow.getAD_Workflow_ID() == 0 && isOfficialId(element, "AD_Workflow_ID")) + filler.setInteger("AD_Workflow_ID"); + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + + if (mWorkflow.is_new() || mWorkflow.is_Changed()) { + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_Workflow.Table_Name, + X_AD_Workflow.Table_ID); + String action = null; + + if (!mWorkflow.is_new()) { + backupRecord(ctx, impDetail.getAD_Package_Imp_Detail_ID(), X_AD_Workflow.Table_Name, mWorkflow); + action = "Update"; + } else { + action = "New"; + } + if (mWorkflow.save(getTrxName(ctx)) == true) { + log.info("m_Workflow save success"); + logImportDetail(ctx,impDetail, 1, mWorkflow.getName(), mWorkflow + .get_ID(), action); + workflows.add(mWorkflow.getAD_Workflow_ID()); + element.recordId = mWorkflow.getAD_Workflow_ID(); + } else { + log.info("m_Workflow save failure"); + logImportDetail(ctx, impDetail, 0, mWorkflow.getName(), mWorkflow + .get_ID(), action); + throw new POSaveFailedException("MWorkflow"); + } + } + } else { + element.skip = true; + } + } + + /** + * @param ctx + * @param element + */ + public void endElement(Properties ctx, Element element) throws SAXException { + if (!element.defer && !element.skip && element.recordId > 0) { + //set start node + String value = getStringValue(element, "AD_WF_Node.Value"); + if (value != null && value.trim().length() > 0) { + MWorkflow m_Workflow = new MWorkflow(ctx, element.recordId, getTrxName(ctx)); + int id = findIdByColumnAndParentId(ctx, "AD_WF_Node", "Value", value, "AD_Workflow", m_Workflow.getAD_Workflow_ID()); + if (id <= 0) { + log.warning("Failed to resolve start node reference for workflow element. Workflow=" + + m_Workflow.getName() + " StartNode=" + value); + return; + } + m_Workflow.setAD_WF_Node_ID(id); + + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_Workflow.Table_Name, + X_AD_Workflow.Table_ID); + + if (m_Workflow.save(getTrxName(ctx)) == true) { + log.info("m_Workflow update success"); + logImportDetail(ctx, impDetail, 1, m_Workflow.getName(), m_Workflow + .get_ID(), "Update"); + workflows.add(m_Workflow.getAD_Workflow_ID()); + element.recordId = m_Workflow.getAD_Workflow_ID(); + } else { + log.info("m_Workflow update fail"); + logImportDetail(ctx, impDetail, 0, m_Workflow.getName(), m_Workflow + .get_ID(), "Update"); + throw new POSaveFailedException("MWorkflow"); + } + } + } + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int AD_Workflow_ID = Env.getContextAsInt(ctx, + X_AD_Package_Exp_Detail.COLUMNNAME_AD_Workflow_ID); + if (workflows.contains(AD_Workflow_ID)) + return; + + workflows.add(AD_Workflow_ID); + int ad_wf_nodenext_id = 0; + int ad_wf_nodenextcondition_id = 0; + AttributesImpl atts = new AttributesImpl(); + + X_AD_Workflow m_Workflow = new X_AD_Workflow(ctx, + AD_Workflow_ID, null); + + atts.addAttribute("", "", "type", "CDATA", "object"); + atts.addAttribute("", "", "type-name", "CDATA", "ad.workflow"); + document.startElement("", "", I_AD_Workflow.Table_Name, atts); + createWorkflowBinding(ctx, document, m_Workflow); + String sql = "SELECT AD_WF_Node_ID FROM AD_WF_Node WHERE AD_Workflow_ID = " + + AD_Workflow_ID; + + PreparedStatement pstmt = null; + ResultSet rs = null; + try { + pstmt = DB.prepareStatement(sql, getTrxName(ctx)); + // Generated workflowNodeNext(s) and + // workflowNodeNextCondition(s) + rs = pstmt.executeQuery(); + while (rs.next()) { + int nodeId = rs.getInt("AD_WF_Node_ID"); + createNode(ctx, document, nodeId); + + ad_wf_nodenext_id = 0; + + sql = "SELECT ad_wf_nodenext_id from ad_wf_nodenext WHERE ad_wf_node_id = ?"; + ad_wf_nodenext_id = DB.getSQLValue(null, sql, nodeId); + if (ad_wf_nodenext_id > 0) { + createNodeNext(ctx, document, ad_wf_nodenext_id); + + ad_wf_nodenextcondition_id = 0; + sql = "SELECT ad_wf_nextcondition_id from ad_wf_nextcondition WHERE ad_wf_nodenext_id = ?"; + ad_wf_nodenextcondition_id = DB.getSQLValue(null, sql, nodeId); + log.info("ad_wf_nodenextcondition_id: " + + String.valueOf(ad_wf_nodenextcondition_id)); + if (ad_wf_nodenextcondition_id > 0) { + createNodeNextCondition(ctx, document, ad_wf_nodenextcondition_id); + } + } + } + } catch (Exception e) { + throw new DBException(e); + } finally { + DB.close(rs, pstmt); + document.endElement("", "", I_AD_Workflow.Table_Name); + } + } + + private void createNodeNextCondition(Properties ctx, + TransformerHandler document, int ad_wf_nodenextcondition_id) + throws SAXException { + Env.setContext(ctx, + X_AD_WF_NextCondition.COLUMNNAME_AD_WF_NextCondition_ID, + ad_wf_nodenextcondition_id); + nextConditionHandler.create(ctx, document); + ctx.remove(X_AD_WF_NextCondition.COLUMNNAME_AD_WF_NextCondition_ID); + } + + private void createNodeNext(Properties ctx, TransformerHandler document, + int ad_wf_nodenext_id) throws SAXException { + Env.setContext(ctx, X_AD_WF_NodeNext.COLUMNNAME_AD_WF_NodeNext_ID, + ad_wf_nodenext_id); + nodeNextHandler.create(ctx, document); + ctx.remove(X_AD_WF_NodeNext.COLUMNNAME_AD_WF_NodeNext_ID); + } + + private void createNode(Properties ctx, TransformerHandler document, + int AD_WF_Node_ID) throws SAXException { + Env.setContext(ctx, X_AD_WF_Node.COLUMNNAME_AD_WF_Node_ID, + AD_WF_Node_ID); + nodeHandler.create(ctx, document); + ctx.remove(X_AD_WF_Node.COLUMNNAME_AD_WF_Node_ID); + } + + private void createWorkflowBinding(Properties ctx, TransformerHandler document, X_AD_Workflow m_Workflow) { + + PoExporter filler = new PoExporter(ctx, document, m_Workflow); + List excludes = defaultExcludeList(X_AD_Workflow.Table_Name); + if (m_Workflow.getAD_Workflow_ID() <= PackOut.MAX_OFFICIAL_ID) + filler.add("AD_Workflow_ID", new AttributesImpl()); + + filler.export(excludes); + } + + + public void packOut(PackOut packout, TransformerHandler packoutHandler, TransformerHandler docHandler,int recordId) throws Exception + { + Env.setContext(packout.getCtx(), X_AD_Package_Exp_Detail.COLUMNNAME_AD_Workflow_ID, recordId); + this.create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(X_AD_Package_Exp_Detail.COLUMNNAME_AD_Workflow_ID); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/WorkflowNodeElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/WorkflowNodeElementHandler.java new file mode 100644 index 0000000000..9d5c345c7b --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/WorkflowNodeElementHandler.java @@ -0,0 +1,157 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + * Contributor(s): Victor Perez. victor.perez@e-evolution.com [Bugs-1789058 ] + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.ReferenceUtils; +import org.adempiere.pipo2.exception.POSaveFailedException; +import org.compiere.model.I_AD_WF_Node; +import org.compiere.model.I_AD_Workflow; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.model.X_AD_WF_Node; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class WorkflowNodeElementHandler extends AbstractElementHandler { + + public void startElement(Properties ctx, Element element) + throws SAXException { + List excludes = defaultExcludeList(X_AD_WF_Node.Table_Name); + + String entitytype = getStringValue(element, "EntityType"); + if (isProcessElement(ctx, entitytype)) { + if (isParentSkip(element, null)) { + element.skip = true; + return; + } + if (isParentDefer(element, I_AD_Workflow.Table_Name)) { + element.unresolved = "Parent element mark as defer: " + getStringValue(element, "AD_Workflow.Value"); + element.defer = true; + return; + } + + X_AD_WF_Node mWFNode = findPO(ctx, element); + if (mWFNode == null) { + int workflowId = 0; + Element wfElement = element.properties.get(I_AD_WF_Node.COLUMNNAME_AD_Workflow_ID); + if (getParentId(element, I_AD_Workflow.Table_Name) > 0) { + workflowId = getParentId(element, I_AD_Workflow.Table_Name); + } else { + workflowId = ReferenceUtils.resolveReference(ctx, wfElement); + } + if (workflowId <= 0) { + element.defer = true; + element.unresolved = "AD_Workflow: " + wfElement.contents; + return; + } + + String workflowNodeValue = getStringValue(element, "Value", excludes); + StringBuffer sqlB = new StringBuffer( + "SELECT AD_WF_Node_ID FROM AD_WF_Node WHERE AD_Workflow_ID=? and Value =?"); + + int id = DB.getSQLValue(getTrxName(ctx), sqlB.toString(), workflowId, workflowNodeValue); + mWFNode = new X_AD_WF_Node(ctx, id > 0 ? id : 0, getTrxName(ctx)); + mWFNode.setValue(workflowNodeValue); + mWFNode.setAD_Workflow_ID(workflowId); + excludes.add(I_AD_WF_Node.COLUMNNAME_AD_Workflow_ID); + excludes.add("Value"); + } + + PoFiller filler = new PoFiller(ctx, mWFNode, element, this); + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + + if (mWFNode.is_new() || mWFNode.is_Changed()) { + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_WF_Node.Table_Name, + X_AD_WF_Node.Table_ID); + String action = null; + if (mWFNode.getAD_WF_Node_ID() == 0 && isOfficialId(element, "AD_WF_Node_ID")) + mWFNode.setAD_WF_Node_ID(getIntValue(element, "AD_WF_Node_ID")); + if (!mWFNode.is_new()) { + backupRecord(ctx, impDetail.getAD_Package_Imp_Detail_ID(), X_AD_WF_Node.Table_Name, mWFNode); + action = "Update"; + } else { + action = "New"; + } + if (mWFNode.save(getTrxName(ctx)) == true) { + log.info("m_WFNode save success"); + logImportDetail(ctx, impDetail, 1, mWFNode.getName(), mWFNode + .get_ID(), action); + } else { + log.info("m_WFNode save failure"); + logImportDetail(ctx, impDetail, 0, mWFNode.getName(), mWFNode + .get_ID(), action); + throw new POSaveFailedException("WorkflowNode"); + } + } + } else { + element.skip = true; + } + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int AD_WF_Node_ID = Env.getContextAsInt(ctx, + X_AD_WF_Node.COLUMNNAME_AD_WF_Node_ID); + AttributesImpl atts = new AttributesImpl(); + X_AD_WF_Node m_WF_Node = new X_AD_WF_Node(ctx, AD_WF_Node_ID, + getTrxName(ctx)); + + addTypeName(atts, "table"); + document.startElement("", "", I_AD_WF_Node.Table_Name, atts); + createWorkflowNodeBinding(ctx, document, m_WF_Node); + document.endElement("", "", I_AD_WF_Node.Table_Name); + } + + private void createWorkflowNodeBinding(Properties ctx, TransformerHandler document, + X_AD_WF_Node m_WF_Node) { + + PoExporter filler = new PoExporter(ctx, document, m_WF_Node); + List excludes = defaultExcludeList(X_AD_WF_Node.Table_Name); + if (m_WF_Node.getAD_WF_Node_ID() <= PackOut.MAX_OFFICIAL_ID) + filler.add("AD_WF_Node_ID", new AttributesImpl()); + + filler.export(excludes); + } + + @Override + public void packOut(PackOut packout, TransformerHandler packoutHandler, + TransformerHandler docHandler, + int recordId) throws Exception { + Env.setContext(packout.getCtx(), I_AD_WF_Node.COLUMNNAME_AD_WF_Node_ID, recordId); + create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(I_AD_WF_Node.COLUMNNAME_AD_WF_Node_ID); + } +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/WorkflowNodeNextConditionElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/WorkflowNodeNextConditionElementHandler.java new file mode 100644 index 0000000000..2254a61210 --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/WorkflowNodeNextConditionElementHandler.java @@ -0,0 +1,217 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.ReferenceUtils; +import org.adempiere.pipo2.exception.POSaveFailedException; +import org.compiere.model.I_AD_WF_NextCondition; +import org.compiere.model.I_AD_Workflow; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.model.X_AD_WF_NextCondition; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.compiere.wf.MWFNextCondition; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class WorkflowNodeNextConditionElementHandler extends + AbstractElementHandler { + + public void startElement(Properties ctx, Element element) + throws SAXException { + List excludes = defaultExcludeList(X_AD_WF_NextCondition.Table_Name); + + String entitytype = getStringValue(element, "EntityType"); + if (isProcessElement(ctx, entitytype)) { + if (isParentSkip(element, null)) { + element.skip = true; + return; + } + + MWFNextCondition mWFNodeNextCondition = findPO(ctx, element); + if (mWFNodeNextCondition == null) { + int workflowId = 0; + Element wfElement = element.properties.get("AD_Workflow_ID"); + if (getParentId(element, I_AD_Workflow.Table_Name) > 0) { + workflowId = getParentId(element, I_AD_Workflow.Table_Name); + } else { + workflowId = ReferenceUtils.resolveReference(ctx, wfElement); + } + if (workflowId <= 0) { + element.defer = true; + element.unresolved = "AD_Workflow: " + wfElement.contents; + return; + } + + int AD_WF_NodeNext_ID = 0; + Element nodeNextElement = element.properties.get(I_AD_WF_NextCondition.COLUMNNAME_AD_WF_NodeNext_ID); + if (ReferenceUtils.isIDLookup(nodeNextElement) || ReferenceUtils.isUUIDLookup(nodeNextElement)) { + AD_WF_NodeNext_ID = ReferenceUtils.resolveReference(ctx, nodeNextElement); + } else { + Element wfnElement = element.properties.get("AD_WF_Node_ID"); + int wfNodeId = ReferenceUtils.resolveReference(ctx, wfnElement); + if (wfNodeId <= 0) { + element.unresolved = "AD_WF_Node=" + wfnElement.contents; + element.defer = true; + return; + } + + Element nextElement = element.properties.get("AD_WF_Next_ID"); + int wfNodeNextId = ReferenceUtils.resolveReference(ctx, nextElement); + if (wfNodeNextId <= 0) { + element.unresolved = "AD_WF_Node=" + nextElement.contents; + element.defer = true; + return; + } + + String sql = "SELECT AD_WF_NodeNext_ID FROM AD_WF_NodeNext WHERE AD_WF_Node_ID =? and AD_WF_Next_ID =?"; + AD_WF_NodeNext_ID = DB.getSQLValue(getTrxName(ctx), sql, wfNodeId, wfNodeNextId); + } + + String sql = "SELECT AD_WF_NextCondition_ID FROM AD_WF_NextCondition WHERE AD_WF_NodeNext_ID =?"; + int id = DB.getSQLValue(getTrxName(ctx), sql, AD_WF_NodeNext_ID); + + mWFNodeNextCondition = new MWFNextCondition(ctx, id > 0 ? id : 0, getTrxName(ctx)); + mWFNodeNextCondition.setAD_WF_NodeNext_ID(AD_WF_NodeNext_ID); + } + + PoFiller filler = new PoFiller(ctx, mWFNodeNextCondition, element, this); + if (mWFNodeNextCondition.get_ID() == 0 && isOfficialId(element, "AD_WF_NextCondition_ID")) + filler.setInteger("AD_WF_NextCondition_ID"); + + Element tableElement = element.properties.get("AD_Table_ID"); + Element columnElement = element.properties.get("AD_Column_ID"); + int columnId = 0; + if (ReferenceUtils.isIDLookup(columnElement) || ReferenceUtils.isUUIDLookup(columnElement)) { + columnId = ReferenceUtils.resolveReference(ctx, columnElement); + } else { + int AD_Table_ID = ReferenceUtils.resolveReference(ctx, tableElement); + columnId = findIdByColumnAndParentId(ctx, "AD_Column", "ColumnName", columnElement.contents.toString(), "AD_Table", AD_Table_ID); + } + mWFNodeNextCondition.setAD_Column_ID(columnId); + + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + + if (mWFNodeNextCondition.is_new() || mWFNodeNextCondition.is_Changed()) { + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_WF_NextCondition.Table_Name, + X_AD_WF_NextCondition.Table_ID); + String action = null; + if (!mWFNodeNextCondition.is_new()) { + backupRecord(ctx, impDetail.getAD_Package_Imp_Detail_ID(), X_AD_WF_NextCondition.Table_Name, + mWFNodeNextCondition); + action = "Update"; + } else { + action = "New"; + } + if (mWFNodeNextCondition.save(getTrxName(ctx)) == true) { + log.info("m_WFNodeNextCondition save success"); + logImportDetail( + ctx, + impDetail, + 1, + String.valueOf(mWFNodeNextCondition.get_ID()), + mWFNodeNextCondition.get_ID(), + action); + } else { + log.info("m_WFNodeNextCondition save failure"); + logImportDetail( + ctx, + impDetail, + 0, + String.valueOf(mWFNodeNextCondition.get_ID()), + mWFNodeNextCondition.get_ID(), + action); + throw new POSaveFailedException("WorkflowNodeNextCondition"); + } + } + } else { + element.skip = true; + } + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int ad_wf_nodenextcondition_id = Env.getContextAsInt(ctx, + X_AD_WF_NextCondition.COLUMNNAME_AD_WF_NextCondition_ID); + X_AD_WF_NextCondition m_WF_NodeNextCondition = new X_AD_WF_NextCondition( + ctx, ad_wf_nodenextcondition_id, null); + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "table"); + document.startElement("", "", I_AD_WF_NextCondition.Table_Name, atts); + createWorkflowNodeNextConditionBinding(ctx, document, m_WF_NodeNextCondition); + document.endElement("", "", I_AD_WF_NextCondition.Table_Name); + } + + private void createWorkflowNodeNextConditionBinding(Properties ctx, TransformerHandler document, X_AD_WF_NextCondition mWFNodeNextCondition) { + PoExporter filler = new PoExporter(ctx, document, mWFNodeNextCondition); + List excludes = defaultExcludeList(X_AD_WF_NextCondition.Table_Name); + + if (mWFNodeNextCondition.getAD_WF_NextCondition_ID() <= PackOut.MAX_OFFICIAL_ID) + filler.add("AD_WF_NextCondition_ID", new AttributesImpl()); + + int AD_workflow_ID = mWFNodeNextCondition.getAD_WF_NodeNext().getAD_WF_Node().getAD_Workflow_ID(); + AttributesImpl wfAttributes = new AttributesImpl(); + String value = ReferenceUtils.getTableReference("AD_Workflow", "Value", AD_workflow_ID, wfAttributes); + filler.addString("AD_Workflow_ID", value, wfAttributes); + + int AD_WF_Node_ID = mWFNodeNextCondition.getAD_WF_NodeNext().getAD_WF_Node_ID(); + AttributesImpl wfnAttributes = new AttributesImpl(); + value = ReferenceUtils.getTableReference("AD_WF_Node", "Value", AD_WF_Node_ID, wfnAttributes); + filler.addString("AD_WF_Node_ID", value, wfnAttributes); + + int AD_WF_Next_ID = mWFNodeNextCondition.getAD_WF_NodeNext().getAD_WF_Next_ID(); + AttributesImpl nextAttributes = new AttributesImpl(); + value = ReferenceUtils.getTableReference("AD_WF_Node", "Value", AD_WF_Next_ID, nextAttributes); + filler.addString("AD_WF_Next_ID", value, nextAttributes); + + if (mWFNodeNextCondition.getAD_Column_ID() > 0) { + int AD_Table_ID = mWFNodeNextCondition.getAD_Column().getAD_Table_ID(); + AttributesImpl tableAttributes = new AttributesImpl(); + value = ReferenceUtils.getTableReference("AD_Table", "TableName", AD_Table_ID, tableAttributes); + filler.addString("AD_Table_ID", value, tableAttributes); + } + + filler.export(excludes); + } + + @Override + public void packOut(PackOut packout, TransformerHandler packoutHandler, + TransformerHandler docHandler, + int recordId) throws Exception { + Env.setContext(packout.getCtx(), I_AD_WF_NextCondition.COLUMNNAME_AD_WF_NextCondition_ID, recordId); + create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(I_AD_WF_NextCondition.COLUMNNAME_AD_WF_NextCondition_ID); + } + +} diff --git a/pipoHandlers/src/org/adempiere/pipo2/handler/WorkflowNodeNextElementHandler.java b/pipoHandlers/src/org/adempiere/pipo2/handler/WorkflowNodeNextElementHandler.java new file mode 100644 index 0000000000..c01b70ac9b --- /dev/null +++ b/pipoHandlers/src/org/adempiere/pipo2/handler/WorkflowNodeNextElementHandler.java @@ -0,0 +1,175 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * + * Copyright (C) 2005 Robert Klein. robeklein@hotmail.com + * Contributor(s): Low Heng Sin hengsin@avantz.com + *****************************************************************************/ +package org.adempiere.pipo2.handler; + +import java.util.List; +import java.util.Properties; + +import javax.xml.transform.sax.TransformerHandler; + +import org.adempiere.pipo2.AbstractElementHandler; +import org.adempiere.pipo2.PoExporter; +import org.adempiere.pipo2.Element; +import org.adempiere.pipo2.PackOut; +import org.adempiere.pipo2.PoFiller; +import org.adempiere.pipo2.ReferenceUtils; +import org.adempiere.pipo2.exception.POSaveFailedException; +import org.compiere.model.I_AD_WF_Node; +import org.compiere.model.I_AD_WF_NodeNext; +import org.compiere.model.I_AD_Workflow; +import org.compiere.model.X_AD_Package_Imp_Detail; +import org.compiere.model.X_AD_WF_NodeNext; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.compiere.wf.MWFNodeNext; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +public class WorkflowNodeNextElementHandler extends AbstractElementHandler { + + public void startElement(Properties ctx, Element element) throws SAXException { + List excludes = defaultExcludeList(X_AD_WF_NodeNext.Table_Name); + + String entitytype = getStringValue(element, "EntityType"); + if (isProcessElement(ctx, entitytype)) { + if (isParentSkip(element, null)) { + element.skip = true; + return; + } + + MWFNodeNext mWFNodeNext = findPO(ctx, element); + if (mWFNodeNext == null) { + int workflowId = 0; + Element wfElement = element.properties.get(I_AD_WF_Node.COLUMNNAME_AD_Workflow_ID); + if (getParentId(element, I_AD_Workflow.Table_Name) > 0) { + workflowId = getParentId(element, I_AD_Workflow.Table_Name); + } else { + workflowId = ReferenceUtils.resolveReference(ctx, wfElement); + } + if (workflowId <= 0) { + element.defer = true; + element.unresolved = "AD_Workflow: " + wfElement.contents; + return; + } + + int wfNodeId = 0; + Element wfnElement = element.properties.get(I_AD_WF_NodeNext.COLUMNNAME_AD_WF_Node_ID); + if (ReferenceUtils.isIDLookup(wfnElement) || ReferenceUtils.isUUIDLookup(wfnElement)) { + wfNodeId = ReferenceUtils.resolveReference(ctx, wfnElement); + } else { + wfNodeId = DB.getSQLValue(getTrxName(ctx), "SELECT AD_WF_Node_Id FROM AD_WF_Node WHERE AD_Workflow_ID=? AND Value=? AND AD_Client_ID=?", + workflowId, wfnElement.contents.toString(), Env.getAD_Client_ID(ctx)); + } + if (wfNodeId <= 0) { + element.defer = true; + element.unresolved = "AD_WF_Node: " + wfnElement.contents; + return; + } + + int AD_WF_Next_ID = 0; + Element nextElement = element.properties.get(I_AD_WF_NodeNext.COLUMNNAME_AD_WF_Next_ID); + if (ReferenceUtils.isIDLookup(nextElement) || ReferenceUtils.isUUIDLookup(nextElement)) { + AD_WF_Next_ID = ReferenceUtils.resolveReference(ctx, nextElement); + } else { + AD_WF_Next_ID = DB.getSQLValue(getTrxName(ctx), "SELECT AD_WF_Node_Id FROM AD_WF_Node WHERE AD_Workflow_ID=? AND Value=? AND AD_Client_ID=?", + workflowId, nextElement.contents.toString(), Env.getAD_Client_ID(ctx)); + } + if (AD_WF_Next_ID <= 0) { + element.defer = true; + element.unresolved = "AD_WF_Node: " + nextElement.contents; + return; + } + + int AD_WF_NodeNext_ID = DB.getSQLValue(getTrxName(ctx), "SELECT AD_WF_NodeNext_ID FROM AD_WF_NodeNext WHERE AD_WF_Node_ID=? and AD_WF_NEXT_ID =?", wfNodeId, AD_WF_Next_ID); + + mWFNodeNext = new MWFNodeNext(ctx, AD_WF_NodeNext_ID, getTrxName(ctx)); + mWFNodeNext.setAD_WF_Node_ID(wfNodeId); + mWFNodeNext.setAD_WF_Next_ID(AD_WF_Next_ID); + } + + PoFiller filler = new PoFiller(ctx, mWFNodeNext, element, this); + if (mWFNodeNext.getAD_WF_NodeNext_ID() == 0 && isOfficialId(element, "AD_WF_NodeNext_ID")) + mWFNodeNext.setAD_WF_NodeNext_ID(getIntValue(element, "AD_WF_NodeNext_ID")); + + List notfounds = filler.autoFill(excludes); + if (notfounds.size() > 0) { + element.defer = true; + return; + } + + if (mWFNodeNext.is_new() || mWFNodeNext.is_Changed()) { + X_AD_Package_Imp_Detail impDetail = createImportDetail(ctx, element.qName, X_AD_WF_NodeNext.Table_Name, + X_AD_WF_NodeNext.Table_ID); + String action = null; + if (!mWFNodeNext.is_new()){ + backupRecord(ctx, impDetail.getAD_Package_Imp_Detail_ID(), X_AD_WF_NodeNext.Table_Name,mWFNodeNext); + action = "Update"; + } else{ + action = "New"; + } + if (mWFNodeNext.save(getTrxName(ctx)) == true){ + log.info("m_WFNodeNext save success"); + logImportDetail (ctx, impDetail, 1, String.valueOf(mWFNodeNext.get_ID()),mWFNodeNext.get_ID(), action); + } else{ + log.info("m_WFNodeNext save failure"); + logImportDetail (ctx, impDetail, 0, String.valueOf(mWFNodeNext.get_ID()), mWFNodeNext.get_ID(), action); + throw new POSaveFailedException("WorkflowNodeNext"); + } + } + } else { + element.skip = true; + } + } + + public void endElement(Properties ctx, Element element) throws SAXException { + } + + public void create(Properties ctx, TransformerHandler document) + throws SAXException { + int ad_wf_nodenext_id = Env.getContextAsInt(ctx, X_AD_WF_NodeNext.COLUMNNAME_AD_WF_NodeNext_ID); + X_AD_WF_NodeNext m_WF_NodeNext = new X_AD_WF_NodeNext( + ctx, ad_wf_nodenext_id, null); + AttributesImpl atts = new AttributesImpl(); + addTypeName(atts, "table"); + document.startElement("", "", I_AD_WF_NodeNext.Table_Name, atts); + createWorkflowNodeNextBinding(ctx, document, m_WF_NodeNext); + document.endElement("", "", I_AD_WF_NodeNext.Table_Name); + + } + + private void createWorkflowNodeNextBinding(Properties ctx, TransformerHandler document, + X_AD_WF_NodeNext m_WF_NodeNext) + { + + PoExporter filler = new PoExporter(ctx, document, m_WF_NodeNext); + List excludes = defaultExcludeList(X_AD_WF_NodeNext.Table_Name); + + if (m_WF_NodeNext.getAD_WF_NodeNext_ID() <= PackOut.MAX_OFFICIAL_ID) + filler.add("AD_WF_NodeNext_ID", new AttributesImpl()); + + filler.export(excludes); + } + + @Override + public void packOut(PackOut packout, TransformerHandler packoutHandler, + TransformerHandler docHandler, + int recordId) throws Exception { + Env.setContext(packout.getCtx(), I_AD_WF_NodeNext.COLUMNNAME_AD_WF_NodeNext_ID, recordId); + create(packout.getCtx(), packoutHandler); + packout.getCtx().remove(I_AD_WF_NodeNext.COLUMNNAME_AD_WF_NodeNext_ID); + } +} diff --git a/plugins/pluginList/plugin.xml b/plugins/pluginList/plugin.xml index 802aa740db..1393adbd45 100644 --- a/plugins/pluginList/plugin.xml +++ b/plugins/pluginList/plugin.xml @@ -2,10 +2,10 @@ - +
    - +
    -
    diff --git a/plugins/pluginUtils/src/org/adempiere/plugin/utils/AdempiereActivator.java b/plugins/pluginUtils/src/org/adempiere/plugin/utils/AdempiereActivator.java index 9396d622df..cb67399104 100644 --- a/plugins/pluginUtils/src/org/adempiere/plugin/utils/AdempiereActivator.java +++ b/plugins/pluginUtils/src/org/adempiere/plugin/utils/AdempiereActivator.java @@ -1,6 +1,7 @@ package org.adempiere.plugin.utils; -import java.io.InputStream; +import java.io.File; +import java.net.URL; import java.util.logging.Level; import java.util.logging.Logger; @@ -59,23 +60,16 @@ public class AdempiereActivator implements BundleActivator { } protected void packIn(String trxName) { - InputStream packout = this.getClass().getResourceAsStream( - "/META-INF/PackOut.xml"); + URL packout = this.getClass().getResource( + "/META-INF/2Pack.zip"); if (packout != null) { IDictionaryService service = Service.locate(IDictionaryService.class); try { - service.merge(packout); + service.merge(context, new File(packout.getFile())); } catch (Exception e) { logger.log(Level.WARNING, "Error on Dictionary service", e); } } - X_AD_Package_Imp pkg = new X_AD_Package_Imp(Env.getCtx(), - 0, trxName); - pkg.setName(getName()); - pkg.setPK_Version(getVersion()); - pkg.setPK_Status("Installed."); - pkg.setDescription(getDescription()); - pkg.save(trxName); } protected BundleContext getContext() { @@ -98,5 +92,4 @@ public class AdempiereActivator implements BundleActivator { protected void stop() { }; - } diff --git a/serverApps/META-INF/MANIFEST.MF b/serverApps/META-INF/MANIFEST.MF index ca2fff43d2..aad144f4e2 100644 --- a/serverApps/META-INF/MANIFEST.MF +++ b/serverApps/META-INF/MANIFEST.MF @@ -16,7 +16,6 @@ Eclipse-RegisterBuddy: org.adempiere.tools Require-Bundle: org.apache.xerces;bundle-version="2.9.0", org.apache.xml.serializer;bundle-version="2.7.1", com.springsource.javax.servlet;bundle-version="2.5.0", - org.adempiere.client;bundle-version="1.0.0", org.adempiere.base;bundle-version="1.0.0", org.adempiere.tools;bundle-version="1.0.0", com.springsource.javax.servlet.jsp;bundle-version="2.1.0" diff --git a/serverApps/build.xml b/serverApps/build.xml index 563bc66cc9..8dbee2d07a 100644 --- a/serverApps/build.xml +++ b/serverApps/build.xml @@ -24,7 +24,7 @@ - + diff --git a/serverRoot/build.properties b/serverRoot/build.properties index 7434588529..714fa2790d 100644 --- a/serverRoot/build.properties +++ b/serverRoot/build.properties @@ -1,7 +1,31 @@ bin.includes = META-INF/,\ WEB-INF/lib/jardiff.jar,\ WEB-INF/lib/jnlp-servlet.jar,\ - . + .,\ + WEB-INF/web.xml,\ + AdemPiere150x50.gif,\ + Adempiere120x60.gif,\ + Background.gif,\ + C32.gif,\ + Logo.gif,\ + adempiere.html,\ + adempiere.jnlp,\ + adempiere_logo.gif,\ + adempiere_logo.png,\ + adempiere_logo2.gif,\ + adempiere_logo3.png,\ + applet.html,\ + favicon.ico,\ + footer_bar.gif,\ + header_banner.jpg,\ + header_banner.png,\ + header_bar.jpg,\ + index.html,\ + robots.txt,\ + standard.css,\ + webstart.jpg,\ + webstart_s.jpg,\ + zip.gif bin.excludes = src/**,\ .settings/**,\ .classpath,\ diff --git a/serverRoot/build.xml b/serverRoot/build.xml index cf8ebd3cf5..02666d0d48 100644 --- a/serverRoot/build.xml +++ b/serverRoot/build.xml @@ -16,7 +16,7 @@ - + diff --git a/tools/build.xml b/tools/build.xml index a541ccf19b..297af62fc7 100644 --- a/tools/build.xml +++ b/tools/build.xml @@ -33,7 +33,7 @@ - + diff --git a/uibase/.classpath b/uibase/.classpath new file mode 100644 index 0000000000..aed1b056e6 --- /dev/null +++ b/uibase/.classpath @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/uibase/.project b/uibase/.project new file mode 100644 index 0000000000..97a1edc033 --- /dev/null +++ b/uibase/.project @@ -0,0 +1,28 @@ + + + uibase + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/uibase/.settings/org.eclipse.jdt.core.prefs b/uibase/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..d43f98f30f --- /dev/null +++ b/uibase/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Mon Aug 09 17:35:10 MYT 2010 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/uibase/.settings/org.eclipse.pde.core.prefs b/uibase/.settings/org.eclipse.pde.core.prefs new file mode 100644 index 0000000000..2cbb9a1de4 --- /dev/null +++ b/uibase/.settings/org.eclipse.pde.core.prefs @@ -0,0 +1,4 @@ +#Mon Aug 09 17:35:10 MYT 2010 +eclipse.preferences.version=1 +pluginProject.extensions=false +resolve.requirebundle=false diff --git a/uibase/META-INF/MANIFEST.MF b/uibase/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..2bd6fc9ca9 --- /dev/null +++ b/uibase/META-INF/MANIFEST.MF @@ -0,0 +1,27 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: UI base +Bundle-SymbolicName: org.adempiere.ui.base +Bundle-Version: 1.0.0.qualifier +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Require-Bundle: org.adempiere.base;bundle-version="1.0.0" +Export-Package: org.compiere.apps, + org.compiere.apps.form, + org.compiere.apps.wf, + org.compiere.grid, + org.compiere.grid.ed, + org.compiere.install, + org.compiere.minigrid, + org.compiere.print, + org.netbeans.api.visual.action, + org.netbeans.api.visual.anchor, + org.netbeans.api.visual.border, + org.netbeans.api.visual.graph, + org.netbeans.api.visual.graph.layout, + org.netbeans.api.visual.layout, + org.netbeans.api.visual.model, + org.netbeans.api.visual.router, + org.netbeans.api.visual.widget +Bundle-ClassPath: org-netbeans-api-visual.jar, + org-openide-util.jar, + . diff --git a/uibase/build.properties b/uibase/build.properties new file mode 100644 index 0000000000..d2f304d4af --- /dev/null +++ b/uibase/build.properties @@ -0,0 +1,6 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + org-netbeans-api-visual.jar,\ + org-openide-util.jar diff --git a/uibase/build.xml b/uibase/build.xml new file mode 100644 index 0000000000..fe0e2471d4 --- /dev/null +++ b/uibase/build.xml @@ -0,0 +1,36 @@ + + + + + + + + + + This buildfile is used to build the client subproject within + the Adempiere project. + + + + + + + + + + + + + + + + + + + + + diff --git a/client/src/org/compiere/apps/ALoginRes.java b/uibase/src/org/compiere/apps/ALoginRes.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes.java rename to uibase/src/org/compiere/apps/ALoginRes.java diff --git a/client/src/org/compiere/apps/ALoginRes_ar.java b/uibase/src/org/compiere/apps/ALoginRes_ar.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes_ar.java rename to uibase/src/org/compiere/apps/ALoginRes_ar.java diff --git a/client/src/org/compiere/apps/ALoginRes_bg.java b/uibase/src/org/compiere/apps/ALoginRes_bg.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes_bg.java rename to uibase/src/org/compiere/apps/ALoginRes_bg.java diff --git a/client/src/org/compiere/apps/ALoginRes_ca.java b/uibase/src/org/compiere/apps/ALoginRes_ca.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes_ca.java rename to uibase/src/org/compiere/apps/ALoginRes_ca.java diff --git a/client/src/org/compiere/apps/ALoginRes_da.java b/uibase/src/org/compiere/apps/ALoginRes_da.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes_da.java rename to uibase/src/org/compiere/apps/ALoginRes_da.java diff --git a/client/src/org/compiere/apps/ALoginRes_de.java b/uibase/src/org/compiere/apps/ALoginRes_de.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes_de.java rename to uibase/src/org/compiere/apps/ALoginRes_de.java diff --git a/client/src/org/compiere/apps/ALoginRes_el.java b/uibase/src/org/compiere/apps/ALoginRes_el.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes_el.java rename to uibase/src/org/compiere/apps/ALoginRes_el.java diff --git a/client/src/org/compiere/apps/ALoginRes_es.java b/uibase/src/org/compiere/apps/ALoginRes_es.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes_es.java rename to uibase/src/org/compiere/apps/ALoginRes_es.java diff --git a/client/src/org/compiere/apps/ALoginRes_fa.java b/uibase/src/org/compiere/apps/ALoginRes_fa.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes_fa.java rename to uibase/src/org/compiere/apps/ALoginRes_fa.java diff --git a/client/src/org/compiere/apps/ALoginRes_fr.java b/uibase/src/org/compiere/apps/ALoginRes_fr.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes_fr.java rename to uibase/src/org/compiere/apps/ALoginRes_fr.java diff --git a/client/src/org/compiere/apps/ALoginRes_hr.java b/uibase/src/org/compiere/apps/ALoginRes_hr.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes_hr.java rename to uibase/src/org/compiere/apps/ALoginRes_hr.java diff --git a/client/src/org/compiere/apps/ALoginRes_hu.java b/uibase/src/org/compiere/apps/ALoginRes_hu.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes_hu.java rename to uibase/src/org/compiere/apps/ALoginRes_hu.java diff --git a/client/src/org/compiere/apps/ALoginRes_in.java b/uibase/src/org/compiere/apps/ALoginRes_in.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes_in.java rename to uibase/src/org/compiere/apps/ALoginRes_in.java diff --git a/client/src/org/compiere/apps/ALoginRes_it.java b/uibase/src/org/compiere/apps/ALoginRes_it.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes_it.java rename to uibase/src/org/compiere/apps/ALoginRes_it.java diff --git a/client/src/org/compiere/apps/ALoginRes_ja.java b/uibase/src/org/compiere/apps/ALoginRes_ja.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes_ja.java rename to uibase/src/org/compiere/apps/ALoginRes_ja.java diff --git a/client/src/org/compiere/apps/ALoginRes_ml.java b/uibase/src/org/compiere/apps/ALoginRes_ml.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes_ml.java rename to uibase/src/org/compiere/apps/ALoginRes_ml.java diff --git a/client/src/org/compiere/apps/ALoginRes_ms.java b/uibase/src/org/compiere/apps/ALoginRes_ms.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes_ms.java rename to uibase/src/org/compiere/apps/ALoginRes_ms.java diff --git a/client/src/org/compiere/apps/ALoginRes_nl.java b/uibase/src/org/compiere/apps/ALoginRes_nl.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes_nl.java rename to uibase/src/org/compiere/apps/ALoginRes_nl.java diff --git a/client/src/org/compiere/apps/ALoginRes_no.java b/uibase/src/org/compiere/apps/ALoginRes_no.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes_no.java rename to uibase/src/org/compiere/apps/ALoginRes_no.java diff --git a/client/src/org/compiere/apps/ALoginRes_pl.java b/uibase/src/org/compiere/apps/ALoginRes_pl.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes_pl.java rename to uibase/src/org/compiere/apps/ALoginRes_pl.java diff --git a/client/src/org/compiere/apps/ALoginRes_pt.java b/uibase/src/org/compiere/apps/ALoginRes_pt.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes_pt.java rename to uibase/src/org/compiere/apps/ALoginRes_pt.java diff --git a/client/src/org/compiere/apps/ALoginRes_ro.java b/uibase/src/org/compiere/apps/ALoginRes_ro.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes_ro.java rename to uibase/src/org/compiere/apps/ALoginRes_ro.java diff --git a/client/src/org/compiere/apps/ALoginRes_ru.java b/uibase/src/org/compiere/apps/ALoginRes_ru.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes_ru.java rename to uibase/src/org/compiere/apps/ALoginRes_ru.java diff --git a/client/src/org/compiere/apps/ALoginRes_sl.java b/uibase/src/org/compiere/apps/ALoginRes_sl.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes_sl.java rename to uibase/src/org/compiere/apps/ALoginRes_sl.java diff --git a/client/src/org/compiere/apps/ALoginRes_sr.java b/uibase/src/org/compiere/apps/ALoginRes_sr.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes_sr.java rename to uibase/src/org/compiere/apps/ALoginRes_sr.java diff --git a/client/src/org/compiere/apps/ALoginRes_sv.java b/uibase/src/org/compiere/apps/ALoginRes_sv.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes_sv.java rename to uibase/src/org/compiere/apps/ALoginRes_sv.java diff --git a/client/src/org/compiere/apps/ALoginRes_th.java b/uibase/src/org/compiere/apps/ALoginRes_th.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes_th.java rename to uibase/src/org/compiere/apps/ALoginRes_th.java diff --git a/client/src/org/compiere/apps/ALoginRes_vi.java b/uibase/src/org/compiere/apps/ALoginRes_vi.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes_vi.java rename to uibase/src/org/compiere/apps/ALoginRes_vi.java diff --git a/client/src/org/compiere/apps/ALoginRes_zh.java b/uibase/src/org/compiere/apps/ALoginRes_zh.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes_zh.java rename to uibase/src/org/compiere/apps/ALoginRes_zh.java diff --git a/client/src/org/compiere/apps/ALoginRes_zh_CN.java b/uibase/src/org/compiere/apps/ALoginRes_zh_CN.java similarity index 100% rename from client/src/org/compiere/apps/ALoginRes_zh_CN.java rename to uibase/src/org/compiere/apps/ALoginRes_zh_CN.java diff --git a/uibase/src/org/compiere/apps/AbstractProcessCtl.java b/uibase/src/org/compiere/apps/AbstractProcessCtl.java new file mode 100644 index 0000000000..8abc542051 --- /dev/null +++ b/uibase/src/org/compiere/apps/AbstractProcessCtl.java @@ -0,0 +1,516 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.apps; + +import java.io.InvalidClassException; +import java.lang.reflect.UndeclaredThrowableException; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.logging.Level; + +import org.adempiere.util.ProcessUtil; +import org.compiere.db.CConnection; +import org.compiere.interfaces.Server; +import org.compiere.model.MRule; +import org.compiere.print.ReportCtl; +import org.compiere.process.ClientProcess; +import org.compiere.process.ProcessInfo; +import org.compiere.process.ProcessInfoUtil; +import org.compiere.util.ASyncProcess; +import org.compiere.util.CLogger; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.compiere.util.Ini; +import org.compiere.util.Msg; +import org.compiere.util.Trx; +import org.compiere.wf.MWFProcess; + +/** + * Process Interface Controller. + * + * @author Jorg Janke + * @version $Id: ProcessCtl.java,v 1.2 2006/07/30 00:51:27 jjanke Exp $ + * @author Low Heng Sin + * - Added support for having description and parameter in one dialog + * - Added support to run db process remotely on server + * + * @author Teo Sarca, SC ARHIPAC SERVICE SRL + *
  • BF [ 1757523 ] Server Processes are using Server's context + *
  • FR [ 1807922 ] Pocess threads should have a better name + *
  • BF [ 1960523 ] Server Process functionality not working + */ +public abstract class AbstractProcessCtl implements Runnable +{ + /************************************************************************** + * Constructor + * @param parent Container & ASyncProcess + * @param pi Process info + * @param trx Transaction + * Created in process(), VInvoiceGen.generateInvoices + */ + public AbstractProcessCtl (ASyncProcess parent, int WindowNo, ProcessInfo pi, Trx trx) + { + windowno = WindowNo; + m_parent = parent; + m_pi = pi; + m_trx = trx; // handeled correctly + } // ProcessCtl + + /** Windowno */ + private int windowno; + /** Parenr */ + private ASyncProcess m_parent; + /** Process Info */ + private ProcessInfo m_pi; + private Trx m_trx; + private boolean m_IsServerProcess = false; + + /** Static Logger */ + private static CLogger log = CLogger.getCLogger (AbstractProcessCtl.class); + + /** + * Run this process in a new thread + */ + public void start() + { + Thread thread = new Thread(this); + // Set thread name - teo_sarca FR [ 1807922 ] + if (m_pi != null) + thread.setName(m_pi.getTitle()+"-"+m_pi.getAD_PInstance_ID()); + thread.start(); + } + + /** + * Execute Process Instance and Lock UI. + * Calls lockUI and unlockUI if parent is a ASyncProcess + *
    +	 *		- Get Process Information
    +	 *      - Call Class
    +	 *		- Submit SQL Procedure
    +	 *		- Run SQL Procedure
    +	 *	
    + */ + public void run () + { + log.fine("AD_PInstance_ID=" + m_pi.getAD_PInstance_ID() + + ", Record_ID=" + m_pi.getRecord_ID()); + + // Lock + lock(); + // try {System.out.println(">> sleeping ..");sleep(20000);System.out.println(".. sleeping <<");} catch (Exception e) {} + + // Get Process Information: Name, Procedure Name, ClassName, IsReport, IsDirectPrint + String ProcedureName = ""; + String JasperReport = ""; + int AD_ReportView_ID = 0; + int AD_Workflow_ID = 0; + boolean IsReport = false; + boolean IsDirectPrint = false; + boolean isPrintPreview = m_pi.isPrintPreview(); + + // + String sql = "SELECT p.Name, p.ProcedureName,p.ClassName, p.AD_Process_ID," // 1..4 + + " p.isReport,p.IsDirectPrint,p.AD_ReportView_ID,p.AD_Workflow_ID," // 5..8 + + " CASE WHEN COALESCE(p.Statistic_Count,0)=0 THEN 0 ELSE p.Statistic_Seconds/p.Statistic_Count END CASE," + + " p.IsServerProcess, p.JasperReport " + + "FROM AD_Process p" + + " INNER JOIN AD_PInstance i ON (p.AD_Process_ID=i.AD_Process_ID) " + + "WHERE p.IsActive='Y'" + + " AND i.AD_PInstance_ID=?"; + if (!Env.isBaseLanguage(Env.getCtx(), "AD_Process")) + sql = "SELECT t.Name, p.ProcedureName,p.ClassName, p.AD_Process_ID," // 1..4 + + " p.isReport, p.IsDirectPrint,p.AD_ReportView_ID,p.AD_Workflow_ID," // 5..8 + + " CASE WHEN COALESCE(p.Statistic_Count,0)=0 THEN 0 ELSE p.Statistic_Seconds/p.Statistic_Count END CASE," + + " p.IsServerProcess, p.JasperReport " + + "FROM AD_Process p" + + " INNER JOIN AD_PInstance i ON (p.AD_Process_ID=i.AD_Process_ID) " + + " INNER JOIN AD_Process_Trl t ON (p.AD_Process_ID=t.AD_Process_ID" + + " AND t.AD_Language='" + Env.getAD_Language(Env.getCtx()) + "') " + + "WHERE p.IsActive='Y'" + + " AND i.AD_PInstance_ID=?"; + // + PreparedStatement pstmt = null; + ResultSet rs = null; + try + { + pstmt = DB.prepareStatement(sql, + ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, null); + pstmt.setInt(1, m_pi.getAD_PInstance_ID()); + rs = pstmt.executeQuery(); + if (rs.next()) + { + m_pi.setTitle (rs.getString(1)); + updateProgressWindowTitle(m_pi.getTitle()); + ProcedureName = rs.getString(2); + m_pi.setClassName (rs.getString(3)); + m_pi.setAD_Process_ID (rs.getInt(4)); + // Report + if ("Y".equals(rs.getString(5))) + { + IsReport = true; + if ("Y".equals(rs.getString(6)) && !Ini.isPropertyBool(Ini.P_PRINTPREVIEW) + && !isPrintPreview ) + IsDirectPrint = true; + } + AD_ReportView_ID = rs.getInt(7); + AD_Workflow_ID = rs.getInt(8); + // + int estimate = rs.getInt(9); + if (estimate != 0) + { + m_pi.setEstSeconds (estimate + 1); // admin overhead + updateProgressWindowTimerEstimate(m_pi.getEstSeconds()); + } + m_IsServerProcess = "Y".equals(rs.getString(10)); + JasperReport = rs.getString(11); + } + else + log.log(Level.SEVERE, "No AD_PInstance_ID=" + m_pi.getAD_PInstance_ID()); + } + catch (Throwable e) + { + m_pi.setSummary (Msg.getMsg(Env.getCtx(), "ProcessNoProcedure") + " " + e.getLocalizedMessage(), true); + unlock(); + log.log(Level.SEVERE, "run", e); + return; + } + finally + { + DB.close(rs, pstmt); + rs = null; pstmt = null; + } + + // No PL/SQL Procedure + if (ProcedureName == null) + ProcedureName = ""; + + + /********************************************************************** + * Workflow + */ + if (AD_Workflow_ID > 0) + { + startWorkflow (AD_Workflow_ID); + unlock(); + return; + } + + // Clear Jasper Report class if default - to be executed later + boolean isJasper = false; + if (JasperReport != null && JasperReport.trim().length() > 0) { + isJasper = true; + if (ProcessUtil.JASPER_STARTER_CLASS.equals(m_pi.getClassName())) { + m_pi.setClassName(null); + } + } + + /********************************************************************** + * Start Optional Class + */ + if (m_pi.getClassName() != null) + { + if (isJasper) + { + m_pi.setReportingProcess(true); + } + + // Run Class + if (!startProcess()) + { + unlock(); + return; + } + + // No Optional SQL procedure ... done + if (!IsReport && ProcedureName.length() == 0) + { + unlock (); + return; + } + // No Optional Report ... done + if (IsReport && AD_ReportView_ID == 0 && ! isJasper) + { + unlock (); + return; + } + } + + /********************************************************************** + * Report submission + */ + // Optional Pre-Report Process + if (IsReport && ProcedureName.length() > 0) + { + m_pi.setReportingProcess(true); + if (!startDBProcess(ProcedureName)) + { + unlock(); + return; + } + } // Pre-Report + + if (isJasper) + { + m_pi.setReportingProcess(true); + m_pi.setClassName(ProcessUtil.JASPER_STARTER_CLASS); + startProcess(); + unlock(); + return; + } + + if (IsReport) + { + m_pi.setReportingProcess(true); + // Start Report ----------------------------------------------- + boolean ok = ReportCtl.start(m_parent, windowno, m_pi, IsDirectPrint); + m_pi.setSummary("Report", !ok); + unlock (); + } + /********************************************************************** + * Process submission + */ + else + { + if (!startDBProcess (ProcedureName)) + { + unlock(); + return; + } + // Success - getResult + ProcessInfoUtil.setSummaryFromDB(m_pi); + unlock(); + } // *** Process submission *** + // log.fine(Log.l3_Util, "ProcessCtl.run - done"); + } // run + + protected abstract void updateProgressWindowTimerEstimate(int estSeconds); + + protected abstract void updateProgressWindowTitle(String title); + + /** + * Lock UI & show Waiting + */ + protected abstract void lock (); + + /** + * Unlock UI & dispose Waiting. + * Called from run() + */ + protected abstract void unlock (); + + protected int getWindowNo() + { + return windowno; + } + + protected ProcessInfo getProcessInfo() + { + return m_pi; + } + + protected ASyncProcess getParent() + { + return m_parent; + } + + protected boolean isServerProcess() + { + return m_IsServerProcess; + } + + /************************************************************************** + * Start Workflow. + * + * @param AD_Workflow_ID workflow + * @return true if started + */ + private boolean startWorkflow (int AD_Workflow_ID) + { + log.fine(AD_Workflow_ID + " - " + m_pi); + boolean started = false; + if (m_IsServerProcess) + { + Server server = CConnection.get().getServer(); + try + { + if (server != null) + { // See ServerBean + m_pi = server.workflow (Env.getRemoteCallCtx(Env.getCtx()), m_pi, AD_Workflow_ID); + log.finest("server => " + m_pi); + started = true; + } + } + catch (Exception ex) + { + log.log(Level.SEVERE, "AppsServer error", ex); + started = false; + } + } + // Run locally + if (!started && !m_IsServerProcess) + { + if (m_trx != null) + m_pi.setTransactionName(m_trx.getTrxName()); + MWFProcess wfProcess = ProcessUtil.startWorkFlow(Env.getCtx(), m_pi, AD_Workflow_ID); + started = wfProcess != null; + } + return started; + } // startWorkflow + + /************************************************************************** + * Start Java Process Class. + * instanciate the class implementing the interface ProcessCall. + * The class can be a Server/Client class (when in Package + * org adempiere.process or org.compiere.model) or a client only class + * (e.g. in org.compiere.report) + * + * @return true if success + */ + private boolean startProcess () + { + log.fine(m_pi.toString()); + boolean started = false; + + //hengsin, bug [ 1633995 ] + boolean clientOnly = false; + if (! m_pi.getClassName().toLowerCase().startsWith(MRule.SCRIPT_PREFIX)) { + try { + Class processClass = Class.forName(m_pi.getClassName()); + if (ClientProcess.class.isAssignableFrom(processClass)) + clientOnly = true; + } catch (Exception e) {} + } + + if (m_IsServerProcess && !clientOnly) + { + Server server = CConnection.get().getServer(); + try + { + if (server != null) + { + // See ServerBean + m_pi = server.process (Env.getRemoteCallCtx(Env.getCtx()), m_pi); + log.finest("server => " + m_pi); + started = true; + } + } + catch (UndeclaredThrowableException ex) + { + Throwable cause = ex.getCause(); + if (cause != null) + { + if (cause instanceof InvalidClassException) + log.log(Level.SEVERE, "Version Server <> Client: " + + cause.toString() + " - " + m_pi, ex); + else + log.log(Level.SEVERE, "AppsServer error(1b): " + + cause.toString() + " - " + m_pi, ex); + } + else + log.log(Level.SEVERE, " AppsServer error(1) - " + + m_pi, ex); + started = false; + } + catch (Exception ex) + { + Throwable cause = ex.getCause(); + if (cause == null) + cause = ex; + log.log(Level.SEVERE, "AppsServer error - " + m_pi, cause); + started = false; + } + } + // Run locally + if (!started && (!m_IsServerProcess || clientOnly )) + { + if (m_pi.getClassName().toLowerCase().startsWith(MRule.SCRIPT_PREFIX)) { + return ProcessUtil.startScriptProcess(Env.getCtx(), m_pi, m_trx); + } else { + return ProcessUtil.startJavaProcess(Env.getCtx(), m_pi, m_trx); + } + } + return !m_pi.isError(); + } // startProcess + + + /************************************************************************** + * Start Database Process + * @param ProcedureName PL/SQL procedure name + * @return true if success + */ + private boolean startDBProcess (String ProcedureName) + { + // execute on this thread/connection + log.fine(ProcedureName + "(" + m_pi.getAD_PInstance_ID() + ")"); + boolean started = false; + if (m_IsServerProcess) + { + Server server = CConnection.get().getServer(); + try + { + if (server != null) + { // See ServerBean + m_pi = server.dbProcess(m_pi, ProcedureName); + log.finest("server => " + m_pi); + started = true; + } + } + catch (UndeclaredThrowableException ex) + { + Throwable cause = ex.getCause(); + if (cause != null) + { + if (cause instanceof InvalidClassException) + log.log(Level.SEVERE, "Version Server <> Client: " + + cause.toString() + " - " + m_pi, ex); + else + log.log(Level.SEVERE, "AppsServer error(1b): " + + cause.toString() + " - " + m_pi, ex); + } + else + { + log.log(Level.SEVERE, " AppsServer error(1) - " + + m_pi, ex); + cause = ex; + } + m_pi.setSummary (Msg.getMsg(Env.getCtx(), "ProcessRunError") + " " + cause.getLocalizedMessage()); + m_pi.setError (true); + return false; + } + catch (Exception ex) + { + Throwable cause = ex.getCause(); + if (cause == null) + cause = ex; + log.log(Level.SEVERE, "AppsServer error - " + m_pi, cause); + m_pi.setSummary (Msg.getMsg(Env.getCtx(), "ProcessRunError") + " " + cause.getLocalizedMessage()); + m_pi.setError (true); + return false; + } + } + + //try locally + if (!started) + { + return ProcessUtil.startDatabaseProcedure(m_pi, ProcedureName, m_trx); + } + // log.fine(Log.l4_Data, "ProcessCtl.startProcess - done"); + return true; + } // startDBProcess + + +} // ProcessCtl diff --git a/client/src/org/compiere/apps/IProcessParameter.java b/uibase/src/org/compiere/apps/IProcessParameter.java similarity index 100% rename from client/src/org/compiere/apps/IProcessParameter.java rename to uibase/src/org/compiere/apps/IProcessParameter.java diff --git a/client/src/org/compiere/apps/IStatusBar.java b/uibase/src/org/compiere/apps/IStatusBar.java similarity index 100% rename from client/src/org/compiere/apps/IStatusBar.java rename to uibase/src/org/compiere/apps/IStatusBar.java diff --git a/client/src/org/compiere/apps/form/Allocation.java b/uibase/src/org/compiere/apps/form/Allocation.java similarity index 100% rename from client/src/org/compiere/apps/form/Allocation.java rename to uibase/src/org/compiere/apps/form/Allocation.java diff --git a/client/src/org/compiere/apps/form/Archive.java b/uibase/src/org/compiere/apps/form/Archive.java similarity index 100% rename from client/src/org/compiere/apps/form/Archive.java rename to uibase/src/org/compiere/apps/form/Archive.java diff --git a/client/src/org/compiere/apps/form/Charge.java b/uibase/src/org/compiere/apps/form/Charge.java similarity index 100% rename from client/src/org/compiere/apps/form/Charge.java rename to uibase/src/org/compiere/apps/form/Charge.java diff --git a/client/src/org/compiere/apps/form/GenForm.java b/uibase/src/org/compiere/apps/form/GenForm.java similarity index 100% rename from client/src/org/compiere/apps/form/GenForm.java rename to uibase/src/org/compiere/apps/form/GenForm.java diff --git a/client/src/org/compiere/apps/form/InOutGen.java b/uibase/src/org/compiere/apps/form/InOutGen.java similarity index 100% rename from client/src/org/compiere/apps/form/InOutGen.java rename to uibase/src/org/compiere/apps/form/InOutGen.java diff --git a/client/src/org/compiere/apps/form/InvoiceGen.java b/uibase/src/org/compiere/apps/form/InvoiceGen.java similarity index 100% rename from client/src/org/compiere/apps/form/InvoiceGen.java rename to uibase/src/org/compiere/apps/form/InvoiceGen.java diff --git a/client/src/org/compiere/apps/form/Match.java b/uibase/src/org/compiere/apps/form/Match.java similarity index 100% rename from client/src/org/compiere/apps/form/Match.java rename to uibase/src/org/compiere/apps/form/Match.java diff --git a/client/src/org/compiere/apps/form/Merge.java b/uibase/src/org/compiere/apps/form/Merge.java similarity index 100% rename from client/src/org/compiere/apps/form/Merge.java rename to uibase/src/org/compiere/apps/form/Merge.java diff --git a/client/src/org/compiere/apps/form/PayPrint.java b/uibase/src/org/compiere/apps/form/PayPrint.java similarity index 100% rename from client/src/org/compiere/apps/form/PayPrint.java rename to uibase/src/org/compiere/apps/form/PayPrint.java diff --git a/client/src/org/compiere/apps/form/PaySelect.java b/uibase/src/org/compiere/apps/form/PaySelect.java similarity index 100% rename from client/src/org/compiere/apps/form/PaySelect.java rename to uibase/src/org/compiere/apps/form/PaySelect.java diff --git a/client/src/org/compiere/apps/form/TreeMaintenance.java b/uibase/src/org/compiere/apps/form/TreeMaintenance.java similarity index 100% rename from client/src/org/compiere/apps/form/TreeMaintenance.java rename to uibase/src/org/compiere/apps/form/TreeMaintenance.java diff --git a/client/src/org/compiere/apps/form/TrxMaterial.java b/uibase/src/org/compiere/apps/form/TrxMaterial.java similarity index 95% rename from client/src/org/compiere/apps/form/TrxMaterial.java rename to uibase/src/org/compiere/apps/form/TrxMaterial.java index f0b57bbb3c..d700d93f4f 100644 --- a/client/src/org/compiere/apps/form/TrxMaterial.java +++ b/uibase/src/org/compiere/apps/form/TrxMaterial.java @@ -19,7 +19,6 @@ import java.sql.SQLException; import java.sql.Timestamp; import java.util.logging.Level; -import org.compiere.apps.AEnv; import org.compiere.apps.IStatusBar; import org.compiere.model.GridTab; import org.compiere.model.GridWindow; @@ -52,7 +51,7 @@ public class TrxMaterial { m_staticQuery = new MQuery(); m_staticQuery.addRestriction("AD_Client_ID", MQuery.EQUAL, Env.getAD_Client_ID(Env.getCtx())); int AD_Window_ID = 223; // Hardcoded - GridWindowVO wVO = AEnv.getMWindowVO (m_WindowNo, AD_Window_ID, 0); + GridWindowVO wVO = Env.getMWindowVO (m_WindowNo, AD_Window_ID, 0); if (wVO == null) return; m_mWindow = new GridWindow (wVO); diff --git a/uibase/src/org/compiere/apps/wf/MultilineLabelWidget.java b/uibase/src/org/compiere/apps/wf/MultilineLabelWidget.java new file mode 100644 index 0000000000..d5c933e4b6 --- /dev/null +++ b/uibase/src/org/compiere/apps/wf/MultilineLabelWidget.java @@ -0,0 +1,76 @@ +package org.compiere.apps.wf; + +import java.awt.Graphics2D; +import java.awt.Insets; +import java.awt.Rectangle; +import java.awt.font.LineBreakMeasurer; +import java.awt.font.TextAttribute; +import java.awt.font.TextLayout; +import java.text.AttributedCharacterIterator; +import java.text.AttributedString; + +import org.netbeans.api.visual.widget.LabelWidget; +import org.netbeans.api.visual.widget.Scene; + +public class MultilineLabelWidget extends LabelWidget { + private boolean justify; + + public MultilineLabelWidget(Scene scene, String label) { + super(scene); + this.setLabel(label); + this.setJustified(true); + } + + @Override + protected void paintWidget() { + paintOrGetSize(this.getGraphics()); + } + + private void paintOrGetSize(Graphics2D gr) { + float width = (float) (this.getBounds() != null ? this.getBounds() + .getWidth() : this.getPreferredSize().getWidth()); + Insets insets = this.getBorder().getInsets(); + float rwidth = width - (insets.left + insets.right);// + margin.left + + // margin.right; + Rectangle rec = this.calculateClientArea(); + gr.setFont(getFont()); + + float x = 0.0F;// + margin.left; + float y = (float) rec.getY();// + margin.top; + + if (rwidth > 0 && this.getLabel() != null + && this.getLabel().length() > 0) { + AttributedString as = new AttributedString(this.getLabel()); + as.addAttribute(TextAttribute.FONT, getFont()); + AttributedCharacterIterator aci = as.getIterator(); + LineBreakMeasurer lbm = new LineBreakMeasurer(aci, gr + .getFontRenderContext()); + + while (lbm.getPosition() < aci.getEndIndex()) { + TextLayout textLayout = lbm.nextLayout(rwidth); + if (gr != null && isJustified() + && textLayout.getVisibleAdvance() > 0.80 * rwidth) { + textLayout = textLayout.getJustifiedLayout(rwidth); + } + if (gr != null) { + textLayout.draw(gr, x, y + textLayout.getAscent()); + } + y += textLayout.getDescent() + textLayout.getLeading() + + textLayout.getAscent(); + + } + } + } + + public boolean isJustified() { + return justify; + } + + public void setJustified(boolean justify) { + boolean old = this.justify; + this.justify = justify; + if (old != this.justify) { + repaint(); + } + } +} \ No newline at end of file diff --git a/uibase/src/org/compiere/apps/wf/WFGraphLayout.java b/uibase/src/org/compiere/apps/wf/WFGraphLayout.java new file mode 100644 index 0000000000..59b3c639f8 --- /dev/null +++ b/uibase/src/org/compiere/apps/wf/WFGraphLayout.java @@ -0,0 +1,43 @@ +/** + * + */ +package org.compiere.apps.wf; + +import java.awt.Point; +import java.util.Collection; + +import org.compiere.wf.MWFNodeNext; +import org.netbeans.api.visual.graph.layout.GraphLayout; +import org.netbeans.api.visual.graph.layout.UniversalGraph; + +/** + * @author hengsin + * + */ +public class WFGraphLayout extends GraphLayout { + + public final static int COLUMN_WIDTH = 250; + public final static int ROW_HEIGHT = 150; + + @Override + protected void performGraphLayout(UniversalGraph graph) { + Collection nodes = graph.getNodes(); + performNodesLayout(graph, nodes); + } + + @Override + protected void performNodesLayout(UniversalGraph graph, + Collection nodes) { + + for(Integer node : nodes) { + WFNodeWidget widget = (WFNodeWidget) graph.getScene().findWidget(node); + int x = (widget.getColumn() - 1) * COLUMN_WIDTH; + int y = (widget.getRow() - 1) * ROW_HEIGHT; + Point point = new Point(x, y); + setResolvedNodeLocation(graph, node, point); + widget.setPreferredLocation(point); + } + } + +} + diff --git a/uibase/src/org/compiere/apps/wf/WFNodeWidget.java b/uibase/src/org/compiere/apps/wf/WFNodeWidget.java new file mode 100644 index 0000000000..f6647f9d1f --- /dev/null +++ b/uibase/src/org/compiere/apps/wf/WFNodeWidget.java @@ -0,0 +1,174 @@ +/** + * + */ +package org.compiere.apps.wf; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Image; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.net.URL; + +import javax.imageio.ImageIO; +import javax.swing.ImageIcon; + +import org.compiere.model.MImage; +import org.compiere.model.MTreeNode; +import org.compiere.util.Env; +import org.compiere.wf.MWFNode; +import org.netbeans.api.visual.border.Border; +import org.netbeans.api.visual.border.BorderFactory; +import org.netbeans.api.visual.layout.LayoutFactory; +import org.netbeans.api.visual.widget.ImageWidget; +import org.netbeans.api.visual.widget.LabelWidget; +import org.netbeans.api.visual.widget.Scene; +import org.netbeans.api.visual.widget.SeparatorWidget; +import org.netbeans.api.visual.widget.Widget; + +/** + * @author hengsin + * + */ +public class WFNodeWidget extends Widget { + + public final static int NODE_WIDTH = 150; + public final static int NODE_HEIGHT = 100; + + private static final Border EMPTY_BORDER = BorderFactory.createEmptyBorder (4); + + private int row = 0; + private int column = 0; + + private MWFNode model; + + /** + * @param scene + */ + public WFNodeWidget(Scene scene, MWFNode node) { + super(scene); + + setLayout (LayoutFactory.createVerticalFlowLayout ()); + setOpaque (true); + setCheckClipping (true); + + setPreferredSize(new Dimension(NODE_WIDTH, NODE_HEIGHT)); + + ImageWidget imageWidget = null; + int imageId = node.getAD_Image_ID(); + if (imageId > 0) { + MImage mImage = MImage.get(Env.getCtx(), imageId); + Image image = null; + byte[] imageData = mImage.getBinaryData(); + if (imageData != null && imageData.length > 0) { + try { + image = ImageIO.read(new ByteArrayInputStream(imageData)); + } catch (IOException e) { + } + } else { + String url = mImage.getImageURL(); + if (url != null && url.trim().length() > 0) { + try { + image = ImageIO.read(new URL(url)); + } catch (IOException e) { + } + } + } + if (image != null) { + imageWidget = new ImageWidget(scene, image); + imageWidget.setToolTipText(node.getName()); + addChild(imageWidget); + } + } + else { + setBorder (BorderFactory.createLineBorder ()); + Widget titleWidget = new Widget (scene); + titleWidget.setLayout (LayoutFactory.createHorizontalFlowLayout ()); + titleWidget.setBorder (EMPTY_BORDER); + + ImageWidget titleIcon = new ImageWidget (scene); + String action = node.getAction(); + int index = MTreeNode.getImageIndex(action); + ImageIcon icon = (ImageIcon) MTreeNode.getIcon(index); + if (icon != null) + { + titleIcon.setImage (icon.getImage()); + titleIcon.setToolTipText(getActionType(node)); + titleWidget.addChild (titleIcon); + } + + String titleText = node.getName(); + if (titleText.length() > 20) + titleText = titleText.substring(0, 20) + "..."; + LabelWidget titleTextWidget = new LabelWidget (scene, titleText); + titleTextWidget.setFont (scene.getDefaultFont ().deriveFont (Font.BOLD)); + if (titleText.length() > 20) + titleTextWidget.setToolTipText(node.getName()); + titleWidget.addChild (titleTextWidget); + addChild (titleWidget); + + addChild (new SeparatorWidget (scene, SeparatorWidget.Orientation.HORIZONTAL)); + + String description = node.getDescription(true); + if (description != null && description.length() > 0) + { + MultilineLabelWidget label = new MultilineLabelWidget(scene, description); + label.setPreferredSize(new Dimension(NODE_WIDTH - 20, NODE_HEIGHT - 20)); + addChild(label); + } + } + + model = node; + } + + /** + * Get Action Info + * @return info + */ + public String getActionType(MWFNode node) + { + String action = node.getAction(); + if (MWFNode.ACTION_AppsProcess.equals(action)) + return "Process"; + else if (MWFNode.ACTION_DocumentAction.equals(action)) + return "Document Action: " + node.getDocAction(); + else if (MWFNode.ACTION_AppsReport.equals(action)) + return "Report"; + else if (MWFNode.ACTION_AppsTask.equals(action)) + return "Task"; + else if (MWFNode.ACTION_SetVariable.equals(action)) + return "Set Variable"; + else if (MWFNode.ACTION_SubWorkflow.equals(action)) + return "Workflow"; + else if (MWFNode.ACTION_UserChoice.equals(action)) + return "User Choice"; + else if (MWFNode.ACTION_UserForm.equals(action)) + return "Form"; + else if (MWFNode.ACTION_UserWindow.equals(action)) + return "Window"; + else if (MWFNode.ACTION_WaitSleep.equals(action)) + return "Sleep:WaitTime=" + node.getWaitTime(); + return ""; + } // getActionInfo + + public int getColumn() { + return column; + } + + public void setColumn(int column) { + this.column = column; + } + + public int getRow() { + return row; + } + + public void setRow(int row) { + this.row = row; + } + + public MWFNode getModel() { + return model; + } +} diff --git a/uibase/src/org/compiere/apps/wf/WorkflowGraphScene.java b/uibase/src/org/compiere/apps/wf/WorkflowGraphScene.java new file mode 100644 index 0000000000..072733824a --- /dev/null +++ b/uibase/src/org/compiere/apps/wf/WorkflowGraphScene.java @@ -0,0 +1,81 @@ +/** + * + */ +package org.compiere.apps.wf; + + +import org.compiere.util.Env; +import org.compiere.wf.MWFNode; +import org.compiere.wf.MWFNodeNext; +import org.netbeans.api.visual.action.WidgetAction; +import org.netbeans.api.visual.anchor.AnchorFactory; +import org.netbeans.api.visual.anchor.AnchorShape; +import org.netbeans.api.visual.graph.GraphScene; +import org.netbeans.api.visual.layout.LayoutFactory.ConnectionWidgetLayoutAlignment; +import org.netbeans.api.visual.router.RouterFactory; +import org.netbeans.api.visual.widget.ConnectionWidget; +import org.netbeans.api.visual.widget.LabelWidget; +import org.netbeans.api.visual.widget.LayerWidget; +import org.netbeans.api.visual.widget.Widget; + +/** + * @author hengsin + * + */ +public class WorkflowGraphScene extends GraphScene { + + private LayerWidget mainLayer; + private LayerWidget connectionLayer; + + private WidgetAction selectAction = createSelectAction(); + + public WorkflowGraphScene() { + mainLayer = new LayerWidget (this); + connectionLayer = new LayerWidget (this); + addChild (mainLayer); + addChild (connectionLayer); + } + + @Override + protected void attachEdgeSourceAnchor(MWFNodeNext edge, Integer oldsource, + Integer sourceNode) { + ((ConnectionWidget) findWidget (edge)).setSourceAnchor (AnchorFactory.createRectangularAnchor (findWidget (sourceNode))); + } + + @Override + protected void attachEdgeTargetAnchor(MWFNodeNext edge, Integer oldtarget, + Integer targetNode) { + ((ConnectionWidget) findWidget (edge)).setTargetAnchor (AnchorFactory.createRectangularAnchor (findWidget (targetNode))); + } + + @Override + protected Widget attachEdgeWidget(MWFNodeNext edge) { + ConnectionWidget connection = new ConnectionWidget (this); + connection.setTargetAnchorShape (AnchorShape.TRIANGLE_FILLED); + connection.setRouter (RouterFactory.createOrthogonalSearchRouter (mainLayer, connectionLayer)); + connection.setRoutingPolicy (ConnectionWidget.RoutingPolicy.ALWAYS_ROUTE); + + String description = edge.getDescription(); + if (description != null && description.length() > 0) { + description = "{" + String.valueOf(edge.getSeqNo()) + + ": " + description + "}"; + LabelWidget label = new LabelWidget(this, description); + connection.addChild(label); + connection.setConstraint (label, ConnectionWidgetLayoutAlignment.TOP_CENTER, 0.5f); + } + + connectionLayer.addChild (connection); + return connection; + } + + @Override + protected Widget attachNodeWidget(Integer node) { + WFNodeWidget widget = (WFNodeWidget) findWidget(node); + if (widget == null) { + widget = new WFNodeWidget(this, MWFNode.get(Env.getCtx(), node)); + widget.getActions ().addAction (selectAction); + mainLayer.addChild (widget); + } + return widget; + } +} diff --git a/client/src/org/compiere/grid/CreateFrom.java b/uibase/src/org/compiere/grid/CreateFrom.java similarity index 100% rename from client/src/org/compiere/grid/CreateFrom.java rename to uibase/src/org/compiere/grid/CreateFrom.java diff --git a/client/src/org/compiere/grid/CreateFromInvoice.java b/uibase/src/org/compiere/grid/CreateFromInvoice.java similarity index 100% rename from client/src/org/compiere/grid/CreateFromInvoice.java rename to uibase/src/org/compiere/grid/CreateFromInvoice.java diff --git a/client/src/org/compiere/grid/CreateFromRMA.java b/uibase/src/org/compiere/grid/CreateFromRMA.java similarity index 100% rename from client/src/org/compiere/grid/CreateFromRMA.java rename to uibase/src/org/compiere/grid/CreateFromRMA.java diff --git a/client/src/org/compiere/grid/CreateFromShipment.java b/uibase/src/org/compiere/grid/CreateFromShipment.java similarity index 100% rename from client/src/org/compiere/grid/CreateFromShipment.java rename to uibase/src/org/compiere/grid/CreateFromShipment.java diff --git a/client/src/org/compiere/grid/CreateFromStatement.java b/uibase/src/org/compiere/grid/CreateFromStatement.java similarity index 100% rename from client/src/org/compiere/grid/CreateFromStatement.java rename to uibase/src/org/compiere/grid/CreateFromStatement.java diff --git a/client/src/org/compiere/grid/ICreateFrom.java b/uibase/src/org/compiere/grid/ICreateFrom.java similarity index 100% rename from client/src/org/compiere/grid/ICreateFrom.java rename to uibase/src/org/compiere/grid/ICreateFrom.java diff --git a/client/src/org/compiere/grid/ed/CityVO.java b/uibase/src/org/compiere/grid/ed/CityVO.java similarity index 100% rename from client/src/org/compiere/grid/ed/CityVO.java rename to uibase/src/org/compiere/grid/ed/CityVO.java diff --git a/client/src/org/compiere/install/Translation.java b/uibase/src/org/compiere/install/Translation.java similarity index 100% rename from client/src/org/compiere/install/Translation.java rename to uibase/src/org/compiere/install/Translation.java diff --git a/client/src/org/compiere/install/TranslationController.java b/uibase/src/org/compiere/install/TranslationController.java similarity index 100% rename from client/src/org/compiere/install/TranslationController.java rename to uibase/src/org/compiere/install/TranslationController.java diff --git a/client/src/org/compiere/install/TranslationHandler.java b/uibase/src/org/compiere/install/TranslationHandler.java similarity index 100% rename from client/src/org/compiere/install/TranslationHandler.java rename to uibase/src/org/compiere/install/TranslationHandler.java diff --git a/client/src/org/compiere/minigrid/ColumnInfo.java b/uibase/src/org/compiere/minigrid/ColumnInfo.java similarity index 100% rename from client/src/org/compiere/minigrid/ColumnInfo.java rename to uibase/src/org/compiere/minigrid/ColumnInfo.java diff --git a/client/src/org/compiere/minigrid/IDColumn.java b/uibase/src/org/compiere/minigrid/IDColumn.java similarity index 100% rename from client/src/org/compiere/minigrid/IDColumn.java rename to uibase/src/org/compiere/minigrid/IDColumn.java diff --git a/client/src/org/compiere/minigrid/IMiniTable.java b/uibase/src/org/compiere/minigrid/IMiniTable.java similarity index 100% rename from client/src/org/compiere/minigrid/IMiniTable.java rename to uibase/src/org/compiere/minigrid/IMiniTable.java diff --git a/client/src/org/compiere/print/ReportCtl.java b/uibase/src/org/compiere/print/ReportCtl.java similarity index 90% rename from client/src/org/compiere/print/ReportCtl.java rename to uibase/src/org/compiere/print/ReportCtl.java index e293003db3..3cb68cd7dd 100644 --- a/client/src/org/compiere/print/ReportCtl.java +++ b/uibase/src/org/compiere/print/ReportCtl.java @@ -16,26 +16,19 @@ *****************************************************************************/ package org.compiere.print; -import java.lang.reflect.Method; import java.util.Properties; -import java.util.Vector; import java.util.logging.Level; import org.adempiere.exceptions.AdempiereException; -import org.compiere.apps.ADialog; -import org.compiere.apps.ProcessCtl; import org.compiere.model.MPaySelectionCheck; import org.compiere.model.MProcess; import org.compiere.model.MQuery; import org.compiere.model.MTable; import org.compiere.model.PrintInfo; import org.compiere.process.ProcessInfo; -import org.compiere.process.ProcessInfoParameter; import org.compiere.util.ASyncProcess; import org.compiere.util.CLogger; import org.compiere.util.Env; -import org.compiere.util.Ini; -import org.compiere.util.Trx; /** * Report Controller. @@ -72,7 +65,7 @@ public class ReportCtl /** Static Logger */ private static CLogger s_log = CLogger.getCLogger (ReportCtl.class); - private static ReportViewerProvider viewerProvider = new SwingViewerProvider(); + private static ReportViewerProvider viewerProvider = null; /** * Create Report. @@ -304,26 +297,7 @@ public class ReportCtl ReportEngine re = ReportEngine.get (Env.getCtx(), type, Record_ID); if (re == null) { - if (Ini.isClient()) - { - ADialog.error(0, null, "NoDocPrintFormat"); - } - else - { - try - { - ClassLoader loader = Thread.currentThread().getContextClassLoader(); - if (loader == null) - loader = ReportCtl.class.getClassLoader(); - Class clazz = loader.loadClass("org.adempiere.webui.window.FDialog"); - Method m = clazz.getMethod("error", Integer.TYPE, String.class); - m.invoke(null, 0, "NoDocPrintFormat"); - } catch (Exception e) - { - throw new AdempiereException(e); - } - } - return false; + throw new AdempiereException("NoDocPrintFormat"); } if (customPrintFormat!=null) { // Use custom print format if available @@ -387,10 +361,10 @@ public class ReportCtl if (printPreview) preview(re); else { - if (printerName!=null) { - re.getPrintInfo().setPrinterName(printerName); - } - re.print(); + if (printerName!=null) { + re.getPrintInfo().setPrinterName(printerName); + } + re.print(); } } diff --git a/client/src/org/compiere/print/ReportViewerProvider.java b/uibase/src/org/compiere/print/ReportViewerProvider.java similarity index 100% rename from client/src/org/compiere/print/ReportViewerProvider.java rename to uibase/src/org/compiere/print/ReportViewerProvider.java diff --git a/utils_dev/build.xml b/utils_dev/build.xml index 6b1e2b66a4..4e9e3cb14b 100644 --- a/utils_dev/build.xml +++ b/utils_dev/build.xml @@ -15,25 +15,30 @@ - + + + + + + @@ -44,6 +49,10 @@ + + + + @@ -51,6 +60,8 @@ + + diff --git a/webStore/META-INF/MANIFEST.MF b/webStore/META-INF/MANIFEST.MF index 1701c60ec3..db587cef90 100644 --- a/webStore/META-INF/MANIFEST.MF +++ b/webStore/META-INF/MANIFEST.MF @@ -5,7 +5,6 @@ Bundle-SymbolicName: org.adempiere.wstore;singleton:=true Bundle-Version: 1.0.0.qualifier Require-Bundle: com.springsource.javax.servlet;bundle-version="2.5.0", org.adempiere.JasperReports;bundle-version="1.0.0", - org.adempiere.client;bundle-version="1.0.0", org.adempiere.base;bundle-version="1.0.0", org.adempiere.tools;bundle-version="1.0.0", org.adempiere.JasperReportsTools;bundle-version="1.0.0", diff --git a/webStore/build.xml b/webStore/build.xml index 811ad07d72..621fc772a4 100644 --- a/webStore/build.xml +++ b/webStore/build.xml @@ -31,7 +31,7 @@ - + diff --git a/zkwebui/META-INF/MANIFEST.MF b/zkwebui/META-INF/MANIFEST.MF index 527b32fba9..c6137fd253 100644 --- a/zkwebui/META-INF/MANIFEST.MF +++ b/zkwebui/META-INF/MANIFEST.MF @@ -369,9 +369,9 @@ Require-Bundle: org.apache.xerces;bundle-version="2.9.0", org.apache.xml.serializer;bundle-version="2.7.1", com.springsource.javax.servlet;bundle-version="2.5.0", org.adempiere.JasperReports;bundle-version="1.0.0", - org.adempiere.client;bundle-version="1.0.0", org.adempiere.base;bundle-version="1.0.0", org.adempiere.tools;bundle-version="1.0.0", - org.adempiere.JasperReportsTools;bundle-version="1.0.0" + org.adempiere.JasperReportsTools;bundle-version="1.0.0", + org.adempiere.ui.base;bundle-version="1.0.0" Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Eclipse-ExtensibleAPI: true diff --git a/zkwebui/WEB-INF/src/org/adempiere/webui/Extensions.java b/zkwebui/WEB-INF/src/org/adempiere/webui/Extensions.java new file mode 100644 index 0000000000..23fd3c3517 --- /dev/null +++ b/zkwebui/WEB-INF/src/org/adempiere/webui/Extensions.java @@ -0,0 +1,18 @@ +package org.adempiere.webui; + +import org.adempiere.base.Core; +import org.adempiere.base.Service; +import org.adempiere.base.ServiceQuery; + +public class Extensions { + + public static Object getForm(String id) { + if (Core.isExtension(id)) { + id = id.substring(Core.OSGI_PREFIX.length()); + } + + ServiceQuery query = new ServiceQuery(); + query.put("id", id); + return Service.locate(Object.class, "org.adempiere.webui.Form", query); + } +} diff --git a/zkwebui/WEB-INF/src/org/adempiere/webui/apps/ProcessDialog.java b/zkwebui/WEB-INF/src/org/adempiere/webui/apps/ProcessDialog.java index dcf9663c7c..7337ec6184 100644 --- a/zkwebui/WEB-INF/src/org/adempiere/webui/apps/ProcessDialog.java +++ b/zkwebui/WEB-INF/src/org/adempiere/webui/apps/ProcessDialog.java @@ -19,7 +19,6 @@ import org.adempiere.webui.process.WProcessInfo; import org.adempiere.webui.session.SessionManager; import org.adempiere.webui.window.FDialog; import org.adempiere.webui.window.SimplePDFViewer; -import org.compiere.apps.ProcessCtl; import org.compiere.print.ReportEngine; import org.compiere.process.ProcessInfo; import org.compiere.process.ProcessInfoUtil; @@ -309,7 +308,7 @@ public class ProcessDialog extends Window implements EventListener//, ASyncProce public void runProcess() { try { - ProcessCtl.process(null, m_WindowNo, parameterPanel, m_pi, null); + WProcessCtl.process(null, m_WindowNo, parameterPanel, m_pi, null); } finally { unlockUI(m_pi); } diff --git a/zkwebui/WEB-INF/src/org/adempiere/webui/apps/ProcessModalDialog.java b/zkwebui/WEB-INF/src/org/adempiere/webui/apps/ProcessModalDialog.java index aab90af9c1..3ddabef27b 100644 --- a/zkwebui/WEB-INF/src/org/adempiere/webui/apps/ProcessModalDialog.java +++ b/zkwebui/WEB-INF/src/org/adempiere/webui/apps/ProcessModalDialog.java @@ -27,7 +27,6 @@ import org.adempiere.webui.component.Button; import org.adempiere.webui.component.Panel; import org.adempiere.webui.component.VerticalBox; import org.adempiere.webui.component.Window; -import org.compiere.apps.ProcessCtl; import org.compiere.process.ProcessInfo; import org.compiere.util.ASyncProcess; import org.compiere.util.CLogger; @@ -325,7 +324,7 @@ public class ProcessModalDialog extends Window implements EventListener */ public void runProcess() { try { - ProcessCtl.process(null, m_WindowNo, parameterPanel, m_pi, null); + WProcessCtl.process(null, m_WindowNo, parameterPanel, m_pi, null); } finally { dispose(); if (m_ASyncProcess != null) { diff --git a/zkwebui/WEB-INF/src/org/adempiere/webui/apps/WProcessCtl.java b/zkwebui/WEB-INF/src/org/adempiere/webui/apps/WProcessCtl.java index 0eb17b3e16..f0ac76dedc 100644 --- a/zkwebui/WEB-INF/src/org/adempiere/webui/apps/WProcessCtl.java +++ b/zkwebui/WEB-INF/src/org/adempiere/webui/apps/WProcessCtl.java @@ -17,8 +17,8 @@ package org.adempiere.webui.apps; import org.adempiere.webui.component.Window; +import org.compiere.apps.AbstractProcessCtl; import org.compiere.apps.IProcessParameter; -import org.compiere.apps.ProcessCtl; import org.compiere.model.MPInstance; import org.compiere.process.ProcessInfo; import org.compiere.util.ASyncProcess; @@ -32,7 +32,7 @@ import org.compiere.util.Trx; * @author hengsin * */ -public class WProcessCtl { +public class WProcessCtl extends AbstractProcessCtl { /** Logger */ private static CLogger log = CLogger.getCLogger(WProcessCtl.class); @@ -113,6 +113,80 @@ public class WProcessCtl { */ public static void process(ASyncProcess parent, int WindowNo, IProcessParameter parameter, ProcessInfo pi, Trx trx) { - ProcessCtl.process(parent, WindowNo, parameter, pi, trx); + log.fine("WindowNo=" + WindowNo + " - " + pi); + + MPInstance instance = null; + try + { + instance = new MPInstance(Env.getCtx(), pi.getAD_Process_ID(), pi.getRecord_ID()); + } + catch (Exception e) + { + pi.setSummary (e.getLocalizedMessage()); + pi.setError (true); + log.warning(pi.toString()); + return; + } + catch (Error e) + { + pi.setSummary (e.getLocalizedMessage()); + pi.setError (true); + log.warning(pi.toString()); + return; + } + if (!instance.save()) + { + pi.setSummary (Msg.getMsg(Env.getCtx(), "ProcessNoInstance")); + pi.setError (true); + return; + } + pi.setAD_PInstance_ID (instance.getAD_PInstance_ID()); + + // Get Parameters + if (parameter != null) { + if (!parameter.saveParameters()) + { + pi.setSummary (Msg.getMsg(Env.getCtx(), "ProcessCancelled")); + pi.setError (true); + return; + } + } + + // execute + WProcessCtl worker = new WProcessCtl(parent, WindowNo, pi, trx); + worker.run(); + } + + /** + * @param parent + * @param WindowNo + * @param pi + * @param trx + */ + public WProcessCtl(ASyncProcess parent, int WindowNo, ProcessInfo pi, + Trx trx) { + super(parent, WindowNo, pi, trx); + } + + @Override + protected void updateProgressWindowTimerEstimate(int estSeconds) { + } + + @Override + protected void updateProgressWindowTitle(String title) { + } + + @Override + protected void lock() { + if (getParent() != null) { + getParent().lockUI(getProcessInfo()); + } + } + + @Override + protected void unlock() { + if (getParent() != null) { + getParent().unlockUI(getProcessInfo()); + } } } diff --git a/zkwebui/WEB-INF/src/org/adempiere/webui/apps/form/WGenForm.java b/zkwebui/WEB-INF/src/org/adempiere/webui/apps/form/WGenForm.java index 2592b5bdb5..39c3995bff 100644 --- a/zkwebui/WEB-INF/src/org/adempiere/webui/apps/form/WGenForm.java +++ b/zkwebui/WEB-INF/src/org/adempiere/webui/apps/form/WGenForm.java @@ -22,6 +22,7 @@ import java.util.logging.Level; import org.adempiere.webui.LayoutUtils; import org.adempiere.webui.apps.AEnv; import org.adempiere.webui.apps.BusyDialog; +import org.adempiere.webui.apps.WProcessCtl; import org.adempiere.webui.component.ConfirmPanel; import org.adempiere.webui.component.DesktopTabpanel; import org.adempiere.webui.component.Grid; @@ -40,7 +41,6 @@ import org.adempiere.webui.panel.StatusBarPanel; import org.adempiere.webui.session.SessionManager; import org.adempiere.webui.window.FDialog; import org.adempiere.webui.window.SimplePDFViewer; -import org.compiere.apps.ProcessCtl; import org.compiere.apps.form.GenForm; import org.compiere.minigrid.IDColumn; import org.compiere.model.MQuery; @@ -291,7 +291,7 @@ public class WGenForm extends ADForm implements EventListener, WTableModelListen */ public void runProcess() { - final ProcessCtl worker = new ProcessCtl(null, getWindowNo(), genForm.getProcessInfo(), genForm.getTrx()); + final WProcessCtl worker = new WProcessCtl(null, getWindowNo(), genForm.getProcessInfo(), genForm.getTrx()); try { worker.run(); // complete tasks in unlockUI / generateShipments_complete } finally{ diff --git a/zkwebui/WEB-INF/src/org/adempiere/webui/apps/form/WSQLProcess.java b/zkwebui/WEB-INF/src/org/adempiere/webui/apps/form/WSQLProcess.java index 6de7c97a4c..39ddd9ee33 100644 --- a/zkwebui/WEB-INF/src/org/adempiere/webui/apps/form/WSQLProcess.java +++ b/zkwebui/WEB-INF/src/org/adempiere/webui/apps/form/WSQLProcess.java @@ -21,6 +21,12 @@ package org.adempiere.webui.apps.form; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.StringTokenizer; +import java.util.logging.Level; + import org.adempiere.webui.component.Button; import org.adempiere.webui.component.Grid; import org.adempiere.webui.component.Label; @@ -28,8 +34,8 @@ import org.adempiere.webui.component.Row; import org.adempiere.webui.component.Rows; import org.adempiere.webui.component.Textbox; import org.adempiere.webui.panel.ADForm; -import org.compiere.apps.form.VSQLProcess; import org.compiere.util.CLogger; +import org.compiere.util.DB; import org.compiere.util.Env; import org.compiere.util.Msg; import org.zkoss.zk.ui.event.Event; @@ -51,10 +57,15 @@ public class WSQLProcess extends ADForm implements EventListener * */ private static final long serialVersionUID = -2038792517003449189L; - + /** Log. */ - private static CLogger log = CLogger.getCLogger(VSQLProcess.class); + private static CLogger log = CLogger.getCLogger(WSQLProcess.class); + /** DML Statement */ + private static final String[] DML_KEYWORDS = new String[]{ + "SELECT", "UPDATE", "DELETE", "TRUNCATE" + }; + /** Grid used to layout components. */ private Grid m_grdMain = new Grid(); /** SQL label. */ @@ -144,7 +155,18 @@ public class WSQLProcess extends ADForm implements EventListener */ public static String processStatements (String sqlStatements, boolean allowDML) { - return VSQLProcess.processStatements(sqlStatements, allowDML); + if (sqlStatements == null || sqlStatements.length() == 0) + return ""; + StringBuffer result = new StringBuffer(); + // + StringTokenizer st = new StringTokenizer(sqlStatements, ";", false); + while (st.hasMoreTokens()) + { + result.append(processStatement(st.nextToken(), allowDML)); + result.append(Env.NL); + } + // + return result.toString(); } /** @@ -156,7 +178,88 @@ public class WSQLProcess extends ADForm implements EventListener */ public static String processStatement (String sqlStatement, boolean allowDML) { - return VSQLProcess.processStatement(sqlStatement, allowDML); + if (sqlStatement == null) + return ""; + StringBuffer sb = new StringBuffer(); + char[] chars = sqlStatement.toCharArray(); + for (int i = 0; i < chars.length; i++) + { + char c = chars[i]; + if (Character.isWhitespace(c)) + sb.append(' '); + else + sb.append(c); + } + String sql = sb.toString().trim(); + if (sql.length() == 0) + return ""; + // + StringBuffer result = new StringBuffer("SQL> ") + .append(sql) + .append(Env.NL); + if (!allowDML) + { + boolean error = false; + String SQL = sql.toUpperCase(); + for (int i = 0; i < DML_KEYWORDS.length; i++) + { + if (SQL.startsWith(DML_KEYWORDS[i] + " ") + || SQL.indexOf(" " + DML_KEYWORDS[i] + " ") != -1 + || SQL.indexOf("(" + DML_KEYWORDS[i] + " ") != -1) + { + result.append("===> ERROR: Not Allowed Keyword ") + .append(DML_KEYWORDS[i]) + .append(Env.NL); + error = true; + } + } + if (error) + return result.toString(); + } // !allowDML + + // Process + Connection conn = DB.createConnection(true, Connection.TRANSACTION_READ_COMMITTED); + Statement stmt = null; + try + { + stmt = conn.createStatement(); + boolean OK = stmt.execute(sql); + int count = stmt.getUpdateCount(); + if (count == -1) + { + result.append("---> ResultSet"); + } + else + result.append("---> Result=").append(count); + } + catch (SQLException e) + { + log.log(Level.SEVERE, "process statement: " + sql + " - " + e.toString()); + result.append("===> ").append(e.toString()); + } + + // Clean up + try + { + stmt.close(); + } + catch (SQLException e1) + { + log.log(Level.SEVERE, "processStatement - close statement", e1); + } + stmt = null; + try + { + conn.close(); + } + catch (SQLException e2) + { + log.log(Level.SEVERE, "processStatement - close connection", e2); + } + conn = null; + // + result.append(Env.NL); + return result.toString(); } diff --git a/zkwebui/WEB-INF/src/org/adempiere/webui/apps/wf/WFEditor.java b/zkwebui/WEB-INF/src/org/adempiere/webui/apps/wf/WFEditor.java index 83e3fd9c7c..5838b04f0d 100644 --- a/zkwebui/WEB-INF/src/org/adempiere/webui/apps/wf/WFEditor.java +++ b/zkwebui/WEB-INF/src/org/adempiere/webui/apps/wf/WFEditor.java @@ -13,48 +13,75 @@ package org.adempiere.webui.apps.wf; import java.awt.Dimension; +import java.awt.Graphics2D; import java.awt.image.BufferedImage; -import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.List; import java.util.logging.Level; -import javax.imageio.ImageIO; - +import org.adempiere.exceptions.AdempiereException; +import org.adempiere.webui.apps.AEnv; import org.adempiere.webui.component.ConfirmPanel; import org.adempiere.webui.component.ListItem; import org.adempiere.webui.component.Listbox; import org.adempiere.webui.component.ListboxFactory; +import org.adempiere.webui.component.Textbox; +import org.adempiere.webui.component.ToolBar; import org.adempiere.webui.panel.ADForm; -import org.compiere.apps.wf.WFLine; +import org.compiere.apps.wf.WFGraphLayout; +import org.compiere.apps.wf.WFNodeWidget; +import org.compiere.model.MQuery; import org.compiere.model.MRole; +import org.compiere.model.MTable; import org.compiere.util.DB; import org.compiere.util.Env; import org.compiere.util.KeyNamePair; +import org.compiere.util.Msg; +import org.compiere.util.Util; import org.compiere.wf.MWFNode; import org.compiere.wf.MWFNodeNext; import org.compiere.wf.MWorkflow; -import org.zkoss.image.AImage; -import org.zkoss.image.Image; +import org.zkoss.zhtml.Table; +import org.zkoss.zhtml.Td; +import org.zkoss.zhtml.Tr; +import org.zkoss.zk.ui.Component; +import org.zkoss.zk.ui.SuspendNotAllowedException; +import org.zkoss.zk.ui.event.DropEvent; import org.zkoss.zk.ui.event.Event; +import org.zkoss.zk.ui.event.EventListener; import org.zkoss.zk.ui.event.Events; import org.zkoss.zkex.zul.Borderlayout; import org.zkoss.zkex.zul.Center; import org.zkoss.zkex.zul.North; import org.zkoss.zkex.zul.South; -import org.zkoss.zul.Imagemap; +import org.zkoss.zul.Div; +import org.zkoss.zul.Hbox; +import org.zkoss.zul.Label; +import org.zkoss.zul.Menupopup; +import org.zkoss.zul.Separator; +import org.zkoss.zul.Space; +import org.zkoss.zul.Toolbarbutton; +import org.zkoss.zul.Vbox; +import org.zkoss.zul.Window; /** - * - * TODO: implement support for edit + * * @author Low Heng Sin * */ public class WFEditor extends ADForm { /** - * + * */ private static final long serialVersionUID = 6874950519612113345L; private Listbox workflowList; - private Imagemap imageMap; + private int m_workflowId = 0; + private Toolbarbutton zoomButton; + private Toolbarbutton newButton; + private Table table; + private Center center; + private MWorkflow m_wf; + private WFNodeContainer nodeContainer; @Override protected void initForm() { @@ -62,31 +89,40 @@ public class WFEditor extends ADForm { Borderlayout layout = new Borderlayout(); layout.setStyle("width: 100%; height: 100%; position: absolute;"); appendChild(layout); - + String sql = MRole.getDefault().addAccessSQL( "SELECT AD_Workflow_ID, Name FROM AD_Workflow ORDER BY 2", "AD_Workflow", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO); // all KeyNamePair[] pp = DB.getKeyNamePairs(sql, true); - + workflowList = ListboxFactory.newDropdownListbox(); for (KeyNamePair knp : pp) { workflowList.addItem(knp); } workflowList.addEventListener(Events.ON_SELECT, this); - + North north = new North(); layout.appendChild(north); - north.appendChild(workflowList); - workflowList.setStyle("margin-left: 10px; margin-top: 5px;"); + ToolBar toolbar = new ToolBar(); + north.appendChild(toolbar); + toolbar.appendChild(workflowList); + workflowList.setStyle("margin-left: 10px; margin-top: 5px; margin-right:5px;"); + zoomButton = new Toolbarbutton(); + zoomButton.setImage("/images/Zoom16.png"); + toolbar.appendChild(zoomButton); + zoomButton.addEventListener(Events.ON_CLICK, this); + newButton = new Toolbarbutton(); + newButton.setImage("/images/New16.png"); + toolbar.appendChild(newButton); + newButton.addEventListener(Events.ON_CLICK, this); north.setHeight("30px"); - - imageMap = new Imagemap(); - Center center = new Center(); + + createTable(); + center = new Center(); layout.appendChild(center); center.setAutoscroll(true); -// center.setFlex(true); - center.appendChild(imageMap); - + center.appendChild(table); + ConfirmPanel confirmPanel = new ConfirmPanel(true); confirmPanel.addActionListener(this); South south = new South(); @@ -95,6 +131,14 @@ public class WFEditor extends ADForm { south.setHeight("36px"); } + private void createTable() { + table = new Table(); + table.setDynamicProperty("cellpadding", "0"); + table.setDynamicProperty("cellspacing", "0"); + table.setDynamicProperty("border", "none"); + table.setStyle("margin:0;padding:0"); + } + @Override public void onEvent(Event event) throws Exception { if (event.getTarget().getId().equals(ConfirmPanel.A_CANCEL)) @@ -102,51 +146,297 @@ public class WFEditor extends ADForm { else if (event.getTarget().getId().equals(ConfirmPanel.A_OK)) this.detach(); else if (event.getTarget() == workflowList) { + center.removeChild(table); + createTable(); + center.appendChild(table); ListItem item = workflowList.getSelectedItem(); KeyNamePair knp = item != null ? item.toKeyNamePair() : null; if (knp != null && knp.getKey() > 0) { load(knp.getKey()); - } else { - Image dummy = null; - imageMap.setContent(dummy); + } + } + else if (event.getTarget() == zoomButton) { + zoom(); + } + else if (event.getTarget() == newButton) { + createNewNode(); + } + else if (event.getTarget() instanceof WFPopupItem) { + WFPopupItem item = (WFPopupItem) event.getTarget(); + item.execute(this); + } + else if (event.getName().equals(Events.ON_DROP)) { + DropEvent dropEvent = (DropEvent) event; + Integer AD_WF_Node_ID = (Integer) dropEvent.getDragged().getAttribute("AD_WF_Node_ID"); + Integer xPosition = (Integer) event.getTarget().getAttribute("Node.XPosition"); + Integer yPosition = (Integer) event.getTarget().getAttribute("Node.YPosition"); + if (AD_WF_Node_ID != null) { + WFNodeWidget widget = (WFNodeWidget) nodeContainer.getGraphScene().findWidget(AD_WF_Node_ID); + if (widget != null) { + widget.getModel().setXPosition(xPosition); + widget.getModel().setYPosition(yPosition); + widget.getModel().saveEx(); + reload(m_workflowId); + } } } } + private void createNewNode() { + String nameLabel = Util.cleanAmp(Msg.getMsg(Env.getCtx(), "Name")); + String title = Msg.getMsg(Env.getCtx(), "CreateNewNode"); + final Window w = new Window(); + w.setTitle(title); + Vbox vbox = new Vbox(); + w.appendChild(vbox); + vbox.appendChild(new Separator()); + Hbox hbox = new Hbox(); + hbox.appendChild(new Label(nameLabel)); + hbox.appendChild(new Space()); + final Textbox text = new Textbox(); + hbox.appendChild(text); + vbox.appendChild(hbox); + vbox.appendChild(new Separator()); + final ConfirmPanel panel = new ConfirmPanel(true, false, false, false, false, false, false); + vbox.appendChild(panel); + panel.addActionListener(Events.ON_CLICK, new EventListener() { + + public void onEvent(Event event) throws Exception { + if (event.getTarget() == panel.getButton(ConfirmPanel.A_CANCEL)) { + text.setText(""); + } + w.onClose(); + } + }); + try { + w.setWidth("250px"); + w.setBorder("normal"); + w.setPage(this.getPage()); + w.doModal(); + } catch (SuspendNotAllowedException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + String name = text.getText(); + if (name != null && name.length() > 0) + { + int AD_Client_ID = Env.getAD_Client_ID(Env.getCtx()); + MWFNode node = new MWFNode(m_wf, name, name); + node.setClientOrg(AD_Client_ID, 0); + node.saveEx(); + reload(m_wf.getAD_Workflow_ID()); + } + } + + void reload(int workflowId) { + center.removeChild(table); + createTable(); + center.appendChild(table); + load(workflowId); + } + private void load(int workflowId) { // Get Workflow - MWorkflow wf = new MWorkflow (Env.getCtx(), workflowId, null); - WFNodeContainer nodeContainer = new WFNodeContainer(); - nodeContainer.setWorkflow(wf); - + m_wf = new MWorkflow (Env.getCtx(), workflowId, null); + m_workflowId = workflowId; + nodeContainer = new WFNodeContainer(); + nodeContainer.setWorkflow(m_wf); + // Add Nodes for Paint - MWFNode[] nodes = wf.getNodes(true, Env.getAD_Client_ID(Env.getCtx())); + MWFNode[] nodes = m_wf.getNodes(true, Env.getAD_Client_ID(Env.getCtx())); + List added = new ArrayList(); + for (int i = 0; i < nodes.length; i++) + { + if (!added.contains(nodes[i].getAD_WF_Node_ID())) + nodeContainer.addNode(nodes[i]); + } + + // Add lines for (int i = 0; i < nodes.length; i++) { - WFNode wfn = new WFNode (nodes[i]); - nodeContainer.add (wfn); - // Add Lines MWFNodeNext[] nexts = nodes[i].getTransitions(Env.getAD_Client_ID(Env.getCtx())); for (int j = 0; j < nexts.length; j++) - nodeContainer.add (new WFLine (nexts[j])); + { + nodeContainer.addEdge(nexts[j]); + } } + Dimension dimension = nodeContainer.getDimension(); - BufferedImage bi = new BufferedImage (dimension.width + 2, dimension.height + 2, BufferedImage.TYPE_INT_ARGB); - nodeContainer.paint(bi.createGraphics()); - ByteArrayOutputStream os = new ByteArrayOutputStream(); + BufferedImage bi = new BufferedImage (dimension.width, dimension.height, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = bi.createGraphics(); + nodeContainer.validate(graphics); + nodeContainer.paint(graphics); + try { - ImageIO.write(bi, "png", os); - AImage imageContent = new AImage("workflow.png", os.toByteArray()); - imageMap.setWidth(dimension.width + "px"); - imageMap.setHeight(dimension.height + "px"); - imageMap.setContent(imageContent); - + int row = nodeContainer.getRowCount(); + for(int i = 0; i < row+1; i++) { + Tr tr = new Tr(); + table.appendChild(tr); + for(int c = 0; c < 4; c++) { + BufferedImage t = new BufferedImage(WFGraphLayout.COLUMN_WIDTH, WFGraphLayout.ROW_HEIGHT, BufferedImage.TYPE_INT_ARGB); + Graphics2D tg = t.createGraphics(); + Td td = new Td(); + td.setStyle("border: 1px dotted lightgray"); + tr.appendChild(td); + + if (i < row) + { + int x = c * WFGraphLayout.COLUMN_WIDTH; + int y = i * WFGraphLayout.ROW_HEIGHT; + + tg.drawImage(bi.getSubimage(x, y, WFGraphLayout.COLUMN_WIDTH, WFGraphLayout.ROW_HEIGHT), 0, 0, null); + org.zkoss.zul.Image image = new org.zkoss.zul.Image(); + image.setContent(t); + td.appendChild(image); + String imgStyle = "border:none;margin:0;padding:0"; + + WFNodeWidget widget = nodeContainer.findWidget(i+1, c+1); + if (widget != null) + { + MWFNode node = widget.getModel(); + if (node.getHelp(true) != null) { + image.setTooltiptext(node.getHelp(true)); + } + image.setAttribute("AD_WF_Node_ID", node.getAD_WF_Node_ID()); + if (node.getAD_Client_ID() == Env.getAD_Client_ID(Env.getCtx())) { + image.addEventListener(Events.ON_CLICK, new EventListener() { + + public void onEvent(Event event) throws Exception { + showNodeMenu(event.getTarget()); + } + }); + image.setDraggable("WFNode"); + imgStyle = imgStyle + ";cursor:pointer"; + } + } + else + { + image.setDroppable("WFNode"); + image.addEventListener(Events.ON_DROP, this); + image.setAttribute("Node.XPosition", c+1); + image.setAttribute("Node.YPosition", i+1); + } + image.setStyle(imgStyle); + } + else + { + Div div = new Div(); + div.setWidth((WFGraphLayout.COLUMN_WIDTH) + "px"); + div.setHeight((WFGraphLayout.ROW_HEIGHT) + "px"); + div.setAttribute("Node.XPosition", c+1); + div.setAttribute("Node.YPosition", i+1); + div.setDroppable("WFNode"); + div.addEventListener(Events.ON_DROP, this); + td.appendChild(div); + } + + tg.dispose(); + } + } + } catch (Exception e) { logger.log(Level.SEVERE, e.getLocalizedMessage(), e); } - - } - - + } + + protected void showNodeMenu(Component target) { + Integer AD_WF_Node_ID = (Integer) target.getAttribute("AD_WF_Node_ID"); + if (AD_WF_Node_ID != null) { + WFNodeWidget widget = (WFNodeWidget) nodeContainer.getGraphScene().findWidget(AD_WF_Node_ID); + if (widget != null) { + MWFNode node = widget.getModel(); + Menupopup popupMenu = new Menupopup(); + if (node.getAD_Client_ID() == Env.getAD_Client_ID(Env.getCtx())) + { + String title = Msg.getMsg(Env.getCtx(), "DeleteNode") + + ": " + node.getName(); + addMenuItem(popupMenu, title, node, -1); + } + MWFNode[] nodes = m_wf.getNodes(true, Env.getAD_Client_ID(Env.getCtx())); + MWFNodeNext[] lines = node.getTransitions(Env.getAD_Client_ID(Env.getCtx())); + // Add New Line + for (int n = 0; n < nodes.length; n++) + { + MWFNode nn = nodes[n]; + if (nn.getAD_WF_Node_ID() == node.getAD_WF_Node_ID()) + continue; // same + boolean found = false; + for (int i = 0; i < lines.length; i++) + { + MWFNodeNext line = lines[i]; + if (nn.getAD_WF_Node_ID() == line.getAD_WF_Next_ID()) + { + found = true; + break; + } + } + if (!found) + { + String title = Msg.getMsg(Env.getCtx(), "AddLine") + + ": " + node.getName() + " -> " + nn.getName(); + addMenuItem(popupMenu, title, node, nn.getAD_WF_Node_ID()); + } + } + // Delete Lines + for (int i = 0; i < lines.length; i++) + { + MWFNodeNext line = lines[i]; + if (line.getAD_Client_ID() != Env.getAD_Client_ID(Env.getCtx())) + continue; + MWFNode next = MWFNode.get(Env.getCtx(), line.getAD_WF_Next_ID()); + String title = Msg.getMsg(Env.getCtx(), "DeleteLine") + + ": " + node.getName() + " -> " + next.getName(); + addMenuItem(popupMenu, title, line); + } + popupMenu.setPage(target.getPage()); + popupMenu.open(target); + } + + } + } + + /** + * Zoom to WorkFlow + */ + private void zoom() + { + if (m_workflowId > 0) { + int AD_Window_ID = MTable.get(Env.getCtx(), MWorkflow.Table_ID).getAD_Window_ID(); + + if (AD_Window_ID <= 0) { + throw new AdempiereException("@NotFound@ @AD_Window_ID@"); + } + + MQuery query = null; + query = MQuery.getEqualQuery("AD_Workflow_ID", m_workflowId); + AEnv.zoom(AD_Window_ID, query); + } + } // zoom + + /** + * Add Menu Item to - add new line to node + * @param menu base menu + * @param title title + */ + private void addMenuItem (Menupopup menu, String title, MWFNode node, int AD_WF_NodeTo_ID) + { + WFPopupItem item = new WFPopupItem (title, node, AD_WF_NodeTo_ID); + menu.appendChild(item); + item.addEventListener(Events.ON_CLICK, this); + } // addMenuItem + + /** + * Add Menu Item to - delete line + * @param menu base menu + * @param title title + */ + private void addMenuItem (Menupopup menu, String title, MWFNodeNext line) + { + WFPopupItem item = new WFPopupItem (title, line); + menu.appendChild(item); + item.addEventListener(Events.ON_CLICK, this); + } // addMenuItem } diff --git a/zkwebui/WEB-INF/src/org/adempiere/webui/apps/wf/WFNode.java b/zkwebui/WEB-INF/src/org/adempiere/webui/apps/wf/WFNode.java deleted file mode 100644 index 8c81b3d3e9..0000000000 --- a/zkwebui/WEB-INF/src/org/adempiere/webui/apps/wf/WFNode.java +++ /dev/null @@ -1,107 +0,0 @@ -/****************************************************************************** - * Copyright (C) 2008 Low Heng Sin * - * This program is free software; you can redistribute it and/or modify it * - * under the terms version 2 of the GNU General Public License as published * - * by the Free Software Foundation. This program is distributed in the hope * - * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * - * See the GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License along * - * with this program; if not, write to the Free Software Foundation, Inc., * - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * - *****************************************************************************/ -package org.adempiere.webui.apps.wf; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.font.LineBreakMeasurer; -import java.awt.font.TextAttribute; -import java.awt.font.TextLayout; -import java.text.AttributedCharacterIterator; -import java.text.AttributedString; - -import org.compiere.apps.wf.WFIcon; -import org.compiere.wf.MWFNode; - -/** - * - * @author Low Heng Sin - * - */ -public class WFNode { - - /** Size of the Node */ - private static Dimension s_size = new Dimension (120, 50); - private MWFNode m_node; - private WFIcon m_icon; - private Rectangle m_bounds; - - /** - * Create WF Node - * @param node model - */ - public WFNode (MWFNode node) { - m_node = node; - m_icon = new WFIcon(node.getAction()); - m_bounds = new Rectangle(m_node.getXPosition(), m_node.getYPosition(), s_size.width, - s_size.height); - } - - public void paint(Graphics2D g2D) { - m_icon.paintIcon(null, g2D, 0, 0); - // Paint Text - g2D.setPaint(Color.BLACK); - Font base = new Font(null); - Font font = new Font(base.getName(), Font.ITALIC | Font.BOLD, base.getSize()); - // - AttributedString aString = new AttributedString(m_node.getName(true)); - aString.addAttribute(TextAttribute.FONT, font); - aString.addAttribute(TextAttribute.FOREGROUND, Color.BLACK); - AttributedCharacterIterator iter = aString.getIterator(); - // - LineBreakMeasurer measurer = new LineBreakMeasurer(iter, g2D.getFontRenderContext()); - float width = s_size.width - m_icon.getIconWidth() - 2; - TextLayout layout = measurer.nextLayout(width); - float xPos = m_icon.getIconWidth(); - float yPos = layout.getAscent() + 2; - // - layout.draw(g2D, xPos, yPos); - width = s_size.width - 4; // 2 pt - while (measurer.getPosition() < iter.getEndIndex()) - { - layout = measurer.nextLayout(width); - yPos += layout.getAscent() + layout.getDescent() + layout.getLeading(); - layout.draw(g2D, 2, yPos); - } - } - - /** - * - * @return AD_WF_Node_ID - */ - public int getAD_WF_Node_ID() { - return m_node.getAD_WF_Node_ID(); - } - - public Rectangle getBounds() { - return m_bounds; - } - - public MWFNode getNode() { - return m_node; - } - - /** - * - * @param x - * @param y - * @param width - * @param height - */ - public void setBounds(int x, int y, int width, int height) { - m_bounds = new Rectangle(x, y, width, height); - } -} diff --git a/zkwebui/WEB-INF/src/org/adempiere/webui/apps/wf/WFNodeContainer.java b/zkwebui/WEB-INF/src/org/adempiere/webui/apps/wf/WFNodeContainer.java index 9433afd2c6..153dc7cb44 100644 --- a/zkwebui/WEB-INF/src/org/adempiere/webui/apps/wf/WFNodeContainer.java +++ b/zkwebui/WEB-INF/src/org/adempiere/webui/apps/wf/WFNodeContainer.java @@ -12,40 +12,57 @@ *****************************************************************************/ package org.adempiere.webui.apps.wf; -import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics2D; +import java.awt.Point; import java.awt.Rectangle; -import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; -import org.compiere.apps.wf.WFLine; +import org.compiere.apps.wf.WFGraphLayout; +import org.compiere.apps.wf.WFNodeWidget; +import org.compiere.apps.wf.WorkflowGraphScene; +import org.compiere.model.X_AD_Workflow; import org.compiere.util.CLogger; +import org.compiere.wf.MWFNode; +import org.compiere.wf.MWFNodeNext; import org.compiere.wf.MWorkflow; +import org.netbeans.api.visual.graph.GraphScene; +import org.netbeans.api.visual.graph.layout.GraphLayout; +import org.netbeans.api.visual.layout.LayoutFactory; +import org.netbeans.api.visual.layout.SceneLayout; /** - * + * * @author Low Heng Sin * */ -public class WFNodeContainer +public class WFNodeContainer { + /** Logger */ + @SuppressWarnings("unused") + private static CLogger log = CLogger.getCLogger(WFNodeContainer.class); + + /** The Workflow */ + private MWorkflow m_wf = null; + + private int currentRow = 1; + private int currentColumn = 0; + private int noOfColumns = 4; + private int rowCount = 0; + + private WorkflowGraphScene graphScene = new WorkflowGraphScene(); + + private Map matrix = null; + /** * WFContentPanel */ public WFNodeContainer () { + matrix = new HashMap(); } // WFContentPanel - - /** Logger */ - private static CLogger log = CLogger.getCLogger(WFNodeContainer.class); - /** Node List */ - private ArrayList m_nodes = new ArrayList(); - /** Line List */ - private ArrayList m_lines = new ArrayList(); - - /** The Workflow */ - private MWorkflow m_wf = null; - + /** * Set Workflow * @param wf workflow @@ -54,162 +71,163 @@ public class WFNodeContainer { m_wf = wf; } // setWorkflow - - + + /** * Remove All and their listeners */ public void removeAll () { - m_nodes.clear(); - m_lines.clear(); + graphScene = new WorkflowGraphScene(); + currentColumn = 0; + currentRow = 1; + matrix = new HashMap(); } // removeAll - - - /** - * Add Component and add Mouse Listener - * @param comp component - * @return component - */ - public void add (WFNode node) - { - m_nodes.add(node); - } // add - - /** - * - * @param line - */ - public void add(WFLine line) - { - m_lines.add(line); + + + public void addNode(MWFNode node) { + int oldRow = currentRow; + int oldColumn = currentColumn; + if (node.getXPosition() > 0 && node.getYPosition() > 0) { + currentColumn = node.getXPosition(); + currentRow = node.getYPosition(); + if (currentColumn > noOfColumns) { + currentColumn = 1; + currentRow ++; + } + } else if (currentColumn == noOfColumns) { + currentColumn = 1; + if (m_wf.getWorkflowType().equals(X_AD_Workflow.WORKFLOWTYPE_General)) { + currentRow++; + } else { + currentRow = currentRow + 2; + } + } else { + if (m_wf.getWorkflowType().equals(X_AD_Workflow.WORKFLOWTYPE_General) || currentColumn == 0) { + currentColumn++; + } else { + currentColumn = currentColumn + 2; + if (currentColumn > noOfColumns) { + currentColumn = 1; + currentRow = currentRow + 2; + } + } + } + + if (currentRow > rowCount) { + rowCount = currentRow; + } + + Integer[] nodes = matrix.get(currentRow); + if (nodes == null) { + nodes = new Integer[noOfColumns]; + matrix.put(currentRow, nodes); + } else { + //detect collision + while (nodes[currentColumn - 1] != null) { + if (nodes[currentColumn - 1] == node.getAD_WF_Node_ID()) { + break; + } else if (currentColumn == noOfColumns) { + currentColumn = 1; + currentRow ++; + nodes = matrix.get(currentRow); + if (nodes == null) { + nodes = new Integer[noOfColumns]; + matrix.put(currentRow, nodes); + } + } else { + currentColumn ++; + } + } + } + + WFNodeWidget w = (WFNodeWidget) graphScene.addNode(node.getAD_WF_Node_ID()); + w.setColumn(currentColumn); + w.setRow(currentRow); + + nodes[currentColumn - 1] = node.getAD_WF_Node_ID(); + + if (currentRow < oldRow) { + currentRow = oldRow; + currentColumn = oldColumn; + } else if ( currentRow == oldRow && currentColumn < oldColumn) { + currentColumn = oldColumn; + } + } + + public void addEdge(MWFNodeNext edge) { + graphScene.addEdge(edge); + graphScene.setEdgeSource(edge, edge.getAD_WF_Node_ID()); + graphScene.setEdgeTarget(edge, edge.getAD_WF_Next_ID()); } /** - * Create Lines. - * Called by WF Layout Manager + * + * @param row row #, starting from 1 + * @param column column #, starting from 1 + * @return WFNodeWidget */ - protected void createLines() - { - log.fine("Lines #" + m_lines.size()); - for (int i = 0; i < m_lines.size(); i++) - { - WFLine line = (WFLine)m_lines.get(i); - Rectangle from = findBounds (line.getAD_WF_Node_ID()); - Rectangle to = findBounds (line.getAD_WF_Next_ID()); - line.setFromTo(from, to); - // same bounds as parent - // line.setBounds(0,0, width, height); - } // for all lines + public WFNodeWidget findWidget(int row, int column) { + WFNodeWidget widget = null; + Integer[] nodeRow = matrix.get(row); + if (nodeRow != null && column <= nodeRow.length) { + widget = (WFNodeWidget) graphScene.findWidget(nodeRow[column - 1]); + } + return widget; } - + /** * Get Bounds of WF Node Icon * @param AD_WF_Node_ID node id * @return bounds of node with ID or null */ - private Rectangle findBounds (int AD_WF_Node_ID) + public Rectangle findBounds (int AD_WF_Node_ID) { - for (int i = 0; i < m_nodes.size(); i++) - { - WFNode node = (WFNode)m_nodes.get(i); - if (node.getAD_WF_Node_ID() == AD_WF_Node_ID) - return node.getBounds(); - } - return null; + WFNodeWidget widget = (WFNodeWidget) graphScene.findWidget(AD_WF_Node_ID); + if (widget == null) + return null; + + Point p = widget.getPreferredLocation(); + return new Rectangle(p.x, p.y, WFNodeWidget.NODE_WIDTH, WFNodeWidget.NODE_HEIGHT); } // findBounds - public Dimension getDimension() + public Dimension getDimension() { - if (needLayout()) - updateLayout(); - - int width = 0; - int height = 0; - // Go through all node - for (int i = 0; i < m_nodes.size(); i++) - { - WFNode node = m_nodes.get(i); - Rectangle rect = node.getBounds(); - if (rect.x + rect.width > width) - width = rect.x + rect.width; - if (rect.y + rect.height > height) - height = rect.y + rect.height; - } // for all components - - return new Dimension(width, height); + return new Dimension(noOfColumns * WFGraphLayout.COLUMN_WIDTH, currentRow * WFGraphLayout.ROW_HEIGHT); } - - /************************************************************************** - * Paint Component. - * Paint Lines directly as not added. - * @param g graphics - */ - public void paint(Graphics2D g) + + public void validate(Graphics2D graphics) { - - for (int i = 0; i < m_nodes.size(); i++) - { - WFNode node = m_nodes.get(i); - Rectangle rect = node.getBounds(); - g.setColor(Color.BLACK); - g.drawRect(rect.x, rect.y, rect.width, rect.height); - Graphics2D t = (Graphics2D) g.create(rect.x, rect.y, rect.width, rect.height); - node.paint(t); - t.dispose(); - } // for all components - - createLines(); - - // Paint Lines - for (int i = 0; i < m_lines.size(); i++) - { - WFLine line = (WFLine)m_lines.get(i); - line.paint(g); - } - } // paint + GraphLayout graphLayout = new WFGraphLayout(); + graphLayout.setAnimated(false); + SceneLayout sceneGraphLayout = LayoutFactory.createSceneGraphLayout (graphScene, graphLayout); + sceneGraphLayout.invokeLayoutImmediately(); + + graphScene.validate(graphics); + } - private void updateLayout() { - int x = 5; - int y = 5;for (int i = 0; i < m_nodes.size(); i++) - { - WFNode node = m_nodes.get(i); - Rectangle rect = node.getBounds(); - node.setBounds(x, y, rect.width, rect.height); - // next pos - if (x == 5) - x = 230; - else - { - x = 5; - y += 100; - } - } + public void paint(Graphics2D graphics) { + graphScene.paint(graphics); } - - /** - * Need Layout - * @param parent parent - * @return true if we need to layout - */ - private boolean needLayout () - { - // Go through all components - for (int i = 0; i < m_nodes.size(); i++) - { - WFNode node = m_nodes.get(i); - Rectangle rect = node.getBounds(); - if (rect.x == 0 && rect.y == 0) - { - return true; - } - } - return false; - } // needLayout - public ArrayList getNodes() { - return m_nodes; + public int getRowCount() { + return rowCount; + } + + public int getCurrentRow() { + return currentRow; + } + + public int getCurrentColumn() { + return currentColumn; + } + + public int getColumnCount() { + return noOfColumns; + } + + public GraphScene getGraphScene() { + return graphScene; } - } // WFContentPanel diff --git a/zkwebui/WEB-INF/src/org/adempiere/webui/apps/wf/WFPanel.java b/zkwebui/WEB-INF/src/org/adempiere/webui/apps/wf/WFPanel.java index da4d8c5c30..3443d49e0e 100644 --- a/zkwebui/WEB-INF/src/org/adempiere/webui/apps/wf/WFPanel.java +++ b/zkwebui/WEB-INF/src/org/adempiere/webui/apps/wf/WFPanel.java @@ -13,34 +13,31 @@ package org.adempiere.webui.apps.wf; import java.awt.Dimension; -import java.awt.Rectangle; +import java.awt.Graphics2D; import java.awt.image.BufferedImage; -import java.io.ByteArrayOutputStream; -import java.util.Properties; +import java.util.ArrayList; +import java.util.List; import java.util.logging.Level; -import javax.imageio.ImageIO; - -import org.adempiere.webui.exception.ApplicationException; import org.adempiere.webui.session.SessionManager; -import org.compiere.apps.wf.WFLine; +import org.compiere.apps.wf.WFGraphLayout; +import org.compiere.apps.wf.WFNodeWidget; import org.compiere.util.CLogger; import org.compiere.util.Env; import org.compiere.wf.MWFNode; import org.compiere.wf.MWFNodeNext; import org.compiere.wf.MWorkflow; -import org.zkoss.image.AImage; +import org.zkoss.zhtml.Table; +import org.zkoss.zhtml.Td; +import org.zkoss.zhtml.Tr; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.EventListener; import org.zkoss.zk.ui.event.Events; -import org.zkoss.zk.ui.event.MouseEvent; import org.zkoss.zkex.zul.Borderlayout; import org.zkoss.zkex.zul.Center; import org.zkoss.zkex.zul.South; -import org.zkoss.zul.Area; import org.zkoss.zul.Div; import org.zkoss.zul.Html; -import org.zkoss.zul.Imagemap; /** * WorkFlow Panel @@ -72,13 +69,12 @@ public class WFPanel extends Borderlayout implements EventListener } // WFPanel /** Window No */ + @SuppressWarnings("unused") private int m_WindowNo = 0; /** Workflow Model */ private MWorkflow m_wf = null; - /** Context */ - private Properties m_ctx = Env.getCtx(); /** Logger */ private static CLogger log = CLogger.getCLogger(WFPanel.class); @@ -89,6 +85,7 @@ public class WFPanel extends Borderlayout implements EventListener private Html infoTextPane = new Html(); private Div contentPanel = new Div(); // + private Table table; /** @@ -107,7 +104,8 @@ public class WFPanel extends Borderlayout implements EventListener this.setStyle("height: 100%; width: 100%; position: absolute"); Center center = new Center(); this.appendChild(center); - center.appendChild(contentPanel); + createTable(); + center.appendChild(table); contentPanel.setStyle("width: 100%; heigh: 100%;"); center.setAutoscroll(true); center.setFlex(true); @@ -122,6 +120,14 @@ public class WFPanel extends Borderlayout implements EventListener south.setFlex(true); } // jbInit + private void createTable() { + table = new Table(); + table.setDynamicProperty("cellpadding", "0"); + table.setDynamicProperty("cellspacing", "0"); + table.setDynamicProperty("border", "none"); + table.setStyle("margin:0;padding:0"); + } + /** * Dispose * @see org.compiere.apps.form.FormPanel#dispose() @@ -141,56 +147,77 @@ public class WFPanel extends Borderlayout implements EventListener log.fine("AD_Workflow_ID=" + AD_Workflow_ID); if (AD_Workflow_ID == 0) return; - int AD_Client_ID = Env.getAD_Client_ID(Env.getCtx()); // Get Workflow m_wf = new MWorkflow (Env.getCtx(), AD_Workflow_ID, null); nodeContainer.removeAll(); nodeContainer.setWorkflow(m_wf); // Add Nodes for Paint - MWFNode[] nodes = m_wf.getNodes(true, AD_Client_ID); + MWFNode[] nodes = m_wf.getNodes(true, Env.getAD_Client_ID(Env.getCtx())); + List added = new ArrayList(); for (int i = 0; i < nodes.length; i++) { - WFNode wfn = new WFNode (nodes[i]); - nodeContainer.add (wfn); - // Add Lines - MWFNodeNext[] nexts = nodes[i].getTransitions(AD_Client_ID); - for (int j = 0; j < nexts.length; j++) - nodeContainer.add (new WFLine (nexts[j])); + if (!added.contains(nodes[i].getAD_WF_Node_ID())) + nodeContainer.addNode(nodes[i]); } - Dimension dimension = nodeContainer.getDimension(); - BufferedImage bi = new BufferedImage (dimension.width + 2, dimension.height + 2, BufferedImage.TYPE_INT_ARGB); - nodeContainer.paint(bi.createGraphics()); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - try { - ImageIO.write(bi, "png", os); - AImage imageContent = new AImage("workflow.png", os.toByteArray()); - Imagemap image = new Imagemap(); - image.setWidth(dimension.width + "px"); - image.setHeight(dimension.height + "px"); - image.setContent(imageContent); - contentPanel.appendChild(image); - - image.addEventListener(Events.ON_CLICK, this); - for(WFNode node : nodeContainer.getNodes()) { - Area area = new Area(); - Rectangle rect = node.getBounds(); - area.setCoords(rect.x + "," + rect.y + "," + (rect.x+rect.width) + "," - + (rect.y+rect.height)); - image.appendChild(area); - area.setId("WFN_"+node.getAD_WF_Node_ID()); - StringBuffer tooltip = new StringBuffer(); - String s = node.getNode().getDescription(true); - if (s != null && s.trim().length() > 0) - tooltip.append(s); - String h = node.getNode().getHelp(true); - if (h != null && h.trim().length() > 0) { - if (tooltip.length() > 0) - tooltip.append(". "); - tooltip.append(h); - } - area.setTooltiptext(tooltip.toString()); + + // Add lines + for (int i = 0; i < nodes.length; i++) + { + MWFNodeNext[] nexts = nodes[i].getTransitions(Env.getAD_Client_ID(Env.getCtx())); + for (int j = 0; j < nexts.length; j++) + { + nodeContainer.addEdge(nexts[j]); } + } + + + Dimension dimension = nodeContainer.getDimension(); + BufferedImage bi = new BufferedImage (dimension.width, dimension.height, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = bi.createGraphics(); + nodeContainer.validate(graphics); + nodeContainer.paint(graphics); + + try { + int row = nodeContainer.getRowCount(); + for(int i = 0; i < row; i++) { + Tr tr = new Tr(); + table.appendChild(tr); + for(int c = 0; c < 4; c++) { + BufferedImage t = new BufferedImage(WFGraphLayout.COLUMN_WIDTH, WFGraphLayout.ROW_HEIGHT, BufferedImage.TYPE_INT_ARGB); + Graphics2D tg = t.createGraphics(); + Td td = new Td(); +// td.setStyle("border: 1px dotted lightgray"); + tr.appendChild(td); + + int x = c * WFGraphLayout.COLUMN_WIDTH; + int y = i * WFGraphLayout.ROW_HEIGHT; + + tg.drawImage(bi.getSubimage(x, y, WFGraphLayout.COLUMN_WIDTH, WFGraphLayout.ROW_HEIGHT), 0, 0, null); + org.zkoss.zul.Image image = new org.zkoss.zul.Image(); + image.setContent(t); + td.appendChild(image); + + WFNodeWidget widget = nodeContainer.findWidget(i+1, c+1); + if (widget != null) + { + MWFNode node = widget.getModel(); + if (node.getHelp(true) != null) { + image.setTooltiptext(node.getHelp(true)); + } + image.setAttribute("AD_WF_Node_ID", node.getAD_WF_Node_ID()); + image.addEventListener(Events.ON_CLICK, this); + image.setStyle("cursor:pointer;border:none;margin:0;padding:0;"); + } + else + { + image.setStyle("border:none;margin:0;padding:0;"); + } + + tg.dispose(); + } + } + } catch (Exception e) { log.log(Level.SEVERE, e.getLocalizedMessage(), e); } @@ -227,12 +254,11 @@ public class WFPanel extends Borderlayout implements EventListener } public void onEvent(Event event) throws Exception { - if (Events.ON_CLICK.equals(event.getName()) && event instanceof MouseEvent) { - MouseEvent me = (MouseEvent) event; - String areaId = me.getArea(); - if (areaId != null && areaId.startsWith("WFN_")) { - int id = Integer.valueOf(areaId.substring(4)); - for(WFNode node : nodeContainer.getNodes()) { + if (Events.ON_CLICK.equals(event.getName())) { + Integer id = (Integer) event.getTarget().getAttribute("AD_WF_Node_ID"); + if (id != null) { + MWFNode[] nodes = m_wf.getNodes(true, Env.getAD_Client_ID(Env.getCtx())); + for(MWFNode node : nodes) { if (node.getAD_WF_Node_ID() == id) { start(node); break; @@ -242,8 +268,7 @@ public class WFPanel extends Borderlayout implements EventListener } } - private void start(WFNode node) { - MWFNode wfn = node.getNode(); + private void start(MWFNode wfn) { if (wfn.getAD_Window_ID() > 0) { SessionManager.getAppDesktop().openWindow(wfn.getAD_Window_ID()); } else if (wfn.getAD_Form_ID() > 0) { @@ -254,9 +279,7 @@ public class WFPanel extends Borderlayout implements EventListener SessionManager.getAppDesktop().openTask(wfn.getAD_Task_ID()); } else if (wfn.getWorkflow_ID() > 0) { SessionManager.getAppDesktop().openWorkflow(wfn.getWorkflow_ID()); - } else { - throw new ApplicationException("Action not yet implemented: " + wfn.getAction()); - } + } } } // WFPanel diff --git a/zkwebui/WEB-INF/src/org/adempiere/webui/apps/wf/WFPopupItem.java b/zkwebui/WEB-INF/src/org/adempiere/webui/apps/wf/WFPopupItem.java new file mode 100644 index 0000000000..4b0c46f51f --- /dev/null +++ b/zkwebui/WEB-INF/src/org/adempiere/webui/apps/wf/WFPopupItem.java @@ -0,0 +1,83 @@ +package org.adempiere.webui.apps.wf; + +import org.compiere.util.CLogger; +import org.compiere.util.Env; +import org.compiere.wf.MWFNode; +import org.compiere.wf.MWFNodeNext; +import org.zkoss.zul.Menuitem; + +public class WFPopupItem extends Menuitem { + + /** + * + */ + private static final long serialVersionUID = 4634863991042969718L; + private int m_AD_Workflow_ID; + + private static final CLogger log = CLogger.getCLogger(WFPopupItem.class); + + /** + * Add Line Item + * @param title title + * @param node node + * @param AD_WF_NodeTo_ID line to + */ + public WFPopupItem (String title, MWFNode node, int AD_WF_NodeTo_ID) + { + super (title); + m_node = node; + m_AD_WF_NodeTo_ID = AD_WF_NodeTo_ID; + m_AD_Workflow_ID = node.getAD_Workflow_ID(); + } // WFPopupItem + + /** + * Delete Line Item + * @param title title + * @param line line to be deleted + */ + public WFPopupItem (String title, MWFNodeNext line) + { + super (title); + m_line = line; + } // WFPopupItem + + /** The Node */ + private MWFNode m_node; + /** The Line */ + private MWFNodeNext m_line; + /** The Next Node ID */ + private int m_AD_WF_NodeTo_ID; + + /** + * Execute + */ + public void execute(final WFEditor wfp) + { + // Add Line + if (m_node != null && m_AD_WF_NodeTo_ID > 0) + { + int AD_Client_ID = Env.getAD_Client_ID(Env.getCtx()); + MWFNodeNext newLine = new MWFNodeNext(m_node, m_AD_WF_NodeTo_ID); + newLine.setClientOrg(AD_Client_ID, 0); + newLine.save(); + log.info("Add Line to " + m_node + " -> " + newLine); + wfp.reload(m_AD_Workflow_ID); + } + // Delete Node + else if (m_node != null && m_AD_WF_NodeTo_ID == -1) + { + log.info("Delete Node: " + m_node); + m_node.delete(false); + wfp.reload(m_AD_Workflow_ID); + } + // Delete Line + else if (m_line != null) + { + log.info("Delete Line: " + m_line); + m_line.delete(false); + wfp.reload(m_AD_Workflow_ID); + } + else + log.warning("No Action??"); + } // execute +} diff --git a/zkwebui/WEB-INF/src/org/adempiere/webui/component/WListbox.java b/zkwebui/WEB-INF/src/org/adempiere/webui/component/WListbox.java index 4da9bf46ef..01a7647086 100644 --- a/zkwebui/WEB-INF/src/org/adempiere/webui/component/WListbox.java +++ b/zkwebui/WEB-INF/src/org/adempiere/webui/component/WListbox.java @@ -33,7 +33,6 @@ import org.adempiere.webui.exception.ApplicationException; import org.compiere.minigrid.ColumnInfo; import org.compiere.minigrid.IDColumn; import org.compiere.minigrid.IMiniTable; -import org.compiere.minigrid.MiniTable; import org.compiere.model.MRole; import org.compiere.model.PO; import org.compiere.util.CLogger; @@ -63,7 +62,7 @@ public class WListbox extends Listbox implements IMiniTable, TableValueChangeLis private static final long serialVersionUID = 8717707799347994189L; /** Logger. */ - private static CLogger logger = CLogger.getCLogger(MiniTable.class); + private static CLogger logger = CLogger.getCLogger(WListbox.class); /** Model Index of Key Column. */ protected int m_keyColumnIndex = -1; diff --git a/zkwebui/WEB-INF/src/org/adempiere/webui/panel/ADForm.java b/zkwebui/WEB-INF/src/org/adempiere/webui/panel/ADForm.java index f51a251754..1764343ba5 100755 --- a/zkwebui/WEB-INF/src/org/adempiere/webui/panel/ADForm.java +++ b/zkwebui/WEB-INF/src/org/adempiere/webui/panel/ADForm.java @@ -19,6 +19,8 @@ package org.adempiere.webui.panel; import java.util.logging.Level; +import org.adempiere.base.Core; +import org.adempiere.webui.Extensions; import org.adempiere.webui.component.Window; import org.adempiere.webui.exception.ApplicationException; import org.adempiere.webui.session.SessionManager; @@ -286,7 +288,7 @@ public abstract class ADForm extends Window implements EventListener */ public static ADForm openForm (int adFormID) { - Object obj; + Object obj = null; ADForm form; String webClassName = ""; MForm mform = new MForm(Env.getCtx(), adFormID, null); @@ -299,33 +301,40 @@ public abstract class ADForm extends Window implements EventListener } else { - logger.info("AD_Form_ID=" + adFormID + " - Class=" + richClassName); - //static lookup - webClassName = ADClassNameMap.get(richClassName); - //fallback to dynamic translation - if (webClassName == null || webClassName.trim().length() == 0) + if (Core.isExtension(richClassName)) { - webClassName = translateFormClassName(richClassName); + obj = Extensions.getForm(richClassName); } - if (webClassName == null) + if (obj == null) { - throw new ApplicationException("Web UI form not implemented for the swing form " + - richClassName); - } - - try - { - // Create instance w/o parameters - obj = ADForm.class.getClassLoader().loadClass(webClassName).newInstance(); - } - catch (Exception e) - { - throw new ApplicationException("The selected web user interface custom form '" + - webClassName + - "' is not accessible.", e); + //static lookup + webClassName = ADClassNameMap.get(richClassName); + //fallback to dynamic translation + if (webClassName == null || webClassName.trim().length() == 0) + { + webClassName = translateFormClassName(richClassName); + } + + if (webClassName == null) + { + throw new ApplicationException("Web UI form not implemented for the swing form " + + richClassName); + } + + try + { + // Create instance w/o parameters + obj = ADForm.class.getClassLoader().loadClass(webClassName).newInstance(); + } + catch (Exception e) + { + throw new ApplicationException("The selected web user interface custom form '" + + webClassName + + "' is not accessible.", e); + } } try diff --git a/zkwebui/WEB-INF/src/org/adempiere/webui/panel/InfoPAttributeInstancePanel.java b/zkwebui/WEB-INF/src/org/adempiere/webui/panel/InfoPAttributeInstancePanel.java index 61c9092b9e..5693c320e6 100644 --- a/zkwebui/WEB-INF/src/org/adempiere/webui/panel/InfoPAttributeInstancePanel.java +++ b/zkwebui/WEB-INF/src/org/adempiere/webui/panel/InfoPAttributeInstancePanel.java @@ -24,7 +24,6 @@ import org.adempiere.webui.component.WListbox; import org.adempiere.webui.component.Window; import org.adempiere.webui.event.WTableModelEvent; import org.adempiere.webui.event.WTableModelListener; -import org.compiere.apps.search.PAttributeInstance; import org.compiere.minigrid.ColumnInfo; import org.compiere.minigrid.IDColumn; import org.compiere.util.CLogger; @@ -111,7 +110,7 @@ public class InfoPAttributeInstancePanel extends Window implements EventListener private String m_M_AttributeSetInstanceName = null; private String m_sql; /** Logger */ - private static CLogger log = CLogger.getCLogger(PAttributeInstance.class); + private static CLogger log = CLogger.getCLogger(InfoPAttributeInstancePanel.class); /** * Static Init diff --git a/zkwebui/WEB-INF/src/org/adempiere/webui/panel/InfoPAttributePanel.java b/zkwebui/WEB-INF/src/org/adempiere/webui/panel/InfoPAttributePanel.java index 341b3841f3..4e17950667 100644 --- a/zkwebui/WEB-INF/src/org/adempiere/webui/panel/InfoPAttributePanel.java +++ b/zkwebui/WEB-INF/src/org/adempiere/webui/panel/InfoPAttributePanel.java @@ -32,7 +32,6 @@ import org.adempiere.webui.component.Rows; import org.adempiere.webui.component.Window; import org.adempiere.webui.editor.WNumberEditor; import org.adempiere.webui.editor.WStringEditor; -import org.compiere.apps.search.InfoPAttribute; import org.compiere.model.MAttribute; import org.compiere.model.MAttributeSet; import org.compiere.model.MRole; @@ -103,7 +102,7 @@ public class InfoPAttributePanel extends Window implements EventListener private ArrayList m_instanceEditors = new ArrayList(); private ArrayList m_instanceEditorsTo = new ArrayList(); /** Logger */ - private static CLogger log = CLogger.getCLogger(InfoPAttribute.class); + private static CLogger log = CLogger.getCLogger(InfoPAttributePanel.class); private Rows rows = null; private ConfirmPanel confirmPanel = new ConfirmPanel(true); diff --git a/zkwebui/WEB-INF/src/org/adempiere/webui/panel/WOnlyCurrentDays.java b/zkwebui/WEB-INF/src/org/adempiere/webui/panel/WOnlyCurrentDays.java index 2daa0bc57c..68faa56ad3 100644 --- a/zkwebui/WEB-INF/src/org/adempiere/webui/panel/WOnlyCurrentDays.java +++ b/zkwebui/WEB-INF/src/org/adempiere/webui/panel/WOnlyCurrentDays.java @@ -22,7 +22,6 @@ import java.util.logging.Level; import org.adempiere.webui.apps.AEnv; import org.adempiere.webui.component.Button; import org.adempiere.webui.component.Window; -import org.compiere.grid.VOnlyCurrentDays; import org.compiere.util.CLogger; import org.compiere.util.Env; import org.compiere.util.Msg; @@ -81,7 +80,7 @@ public class WOnlyCurrentDays extends Window implements EventListener private int m_days = 0; /** Logger */ - private static CLogger log = CLogger.getCLogger(VOnlyCurrentDays.class); + private static CLogger log = CLogger.getCLogger(WOnlyCurrentDays.class); /** * Static Initializer diff --git a/zkwebui/WEB-INF/src/org/adempiere/webui/window/ZkReportViewer.java b/zkwebui/WEB-INF/src/org/adempiere/webui/window/ZkReportViewer.java index 1f6ad0ad85..68b60d9503 100644 --- a/zkwebui/WEB-INF/src/org/adempiere/webui/window/ZkReportViewer.java +++ b/zkwebui/WEB-INF/src/org/adempiere/webui/window/ZkReportViewer.java @@ -45,8 +45,8 @@ import org.compiere.model.MClient; import org.compiere.model.MQuery; import org.compiere.model.MRole; import org.compiere.model.MSysConfig; +import org.compiere.model.MTable; import org.compiere.model.MUser; -import org.compiere.print.AReport; import org.compiere.print.ArchiveEngine; import org.compiere.print.MPrintFormat; import org.compiere.print.ReportEngine; @@ -579,7 +579,7 @@ public class ZkReportViewer extends Window implements EventListener { */ private void executeDrill (MQuery query, Component component) { - int AD_Table_ID = AReport.getAD_Table_ID(query.getTableName()); + int AD_Table_ID = MTable.getTable_ID(query.getTableName()); if (!MRole.getDefault().isCanReport(AD_Table_ID)) { FDialog.error(m_WindowNo, this, "AccessCannotReport", query.getTableName()); diff --git a/zkwebui/build.properties b/zkwebui/build.properties index 35ebda241c..883a916bfb 100644 --- a/zkwebui/build.properties +++ b/zkwebui/build.properties @@ -11,7 +11,8 @@ bin.includes = META-INF/,\ theme.zs,\ zul/,\ WEB-INF/classes/,\ - timeout.zul + timeout.zul,\ + plugin.xml bin.excludes = WEB-INF/src/,\ WEB-INF/web-2.5.xml src.includes = WEB-INF/classes/,\ diff --git a/zkwebui/build.xml b/zkwebui/build.xml index ae9cbadd78..ee69e57232 100644 --- a/zkwebui/build.xml +++ b/zkwebui/build.xml @@ -13,7 +13,7 @@ - + diff --git a/zkwebui/plugin.xml b/zkwebui/plugin.xml new file mode 100644 index 0000000000..d4f09ef2fd --- /dev/null +++ b/zkwebui/plugin.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/zkwebui/schema/org.adempiere.webui.Form.exsd b/zkwebui/schema/org.adempiere.webui.Form.exsd new file mode 100644 index 0000000000..e83da0ea8c --- /dev/null +++ b/zkwebui/schema/org.adempiere.webui.Form.exsd @@ -0,0 +1,102 @@ + + + + + + + + + [Enter description of this extension point.] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + [Enter the first release in which this extension point appears.] + + + + + + + + + [Enter extension point usage example here.] + + + + + + + + + [Enter API information here.] + + + + + + + + + [Enter information about supplied implementation of this extension point.] + + + + +