commit fede81f8401c95b1dd713b7a06391ea5f3ebbc13 Author: lijh Date: Tue Mar 10 15:34:45 2026 +0800 first commit diff --git a/cn.net.connor.std.aifrcp/.classpath b/cn.net.connor.std.aifrcp/.classpath new file mode 100644 index 0000000..d888998 --- /dev/null +++ b/cn.net.connor.std.aifrcp/.classpath @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/cn.net.connor.std.aifrcp/.gitignore b/cn.net.connor.std.aifrcp/.gitignore new file mode 100644 index 0000000..ae3c172 --- /dev/null +++ b/cn.net.connor.std.aifrcp/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/cn.net.connor.std.aifrcp/.project b/cn.net.connor.std.aifrcp/.project new file mode 100644 index 0000000..dc8864c --- /dev/null +++ b/cn.net.connor.std.aifrcp/.project @@ -0,0 +1,28 @@ + + + cn.net.connor.std.aifrcp + + + + + + 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/cn.net.connor.std.aifrcp/.settings/org.eclipse.jdt.core.prefs b/cn.net.connor.std.aifrcp/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..9f6ece8 --- /dev/null +++ b/cn.net.connor.std.aifrcp/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.release=disabled +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/cn.net.connor.std.aifrcp/META-INF/MANIFEST.MF b/cn.net.connor.std.aifrcp/META-INF/MANIFEST.MF new file mode 100644 index 0000000..5f21f7b --- /dev/null +++ b/cn.net.connor.std.aifrcp/META-INF/MANIFEST.MF @@ -0,0 +1,33 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Aifrcp +Bundle-SymbolicName: cn.net.connor.std.aifrcp;singleton:=true +Bundle-Version: 13000.1.0 +Bundle-Activator: cn.net.connor.std.aifrcp.Activator +Eclipse-BuddyPolicy: registered +Require-Bundle: org.eclipse.ui, + org.eclipse.core.runtime, + com.teamcenter.rac.aifrcp;visibility:=reexport, + com.teamcenter.rac.external;visibility:=reexport, + com.teamcenter.rac.kernel;visibility:=reexport, + com.teamcenter.rac.ui.commands;visibility:=reexport, + com.teamcenter.rac.util, + com.teamcenter.rac.common;visibility:=reexport, + org.apache.poi.39, + TcSoaStructureManagementRac, + TcSoaCoreRac, + TcSoaCoreTypes, + TcSoaProjectManagementRac, + TcSoaCommon, + TcSoaClient, + com.teamcenter.rac.schedule +Bundle-RequiredExecutionEnvironment: JavaSE-1.8 +Automatic-Module-Name: cn.net.connor.std.aifrcp +Bundle-ActivationPolicy: lazy +Export-Package: cn.net.connor.std.aifrcp, + cn.net.connor.std.aifrcp.util, + cn.net.connor.std.aifrcp.xml +Bundle-ClassPath: lib/ojdbc7.jar, + lib/sqljdbc4-2.0.jar, + . +Import-Package: com.teamcenter.rac.cme.time.common diff --git a/cn.net.connor.std.aifrcp/README.MD b/cn.net.connor.std.aifrcp/README.MD new file mode 100644 index 0000000..afc1698 --- /dev/null +++ b/cn.net.connor.std.aifrcp/README.MD @@ -0,0 +1,100 @@ +# cn.net.connor.std.aifrcp + +`集成框架` `工具包` + +#### 使用说明 + +1. 集成框架 + + 简化插件开发框架,包含类:`KHandler` `KAction` `KCommand` `KDialog` `KDialogController` `KOperation` `KFrame` `KFormRendering` + +2. 工具包 + + 工具包列表: + + - KLocalizer + + 在当前包下生成或更新properties注册文件,支持中文和英文 + + 调用方法 + + ```java + new KLocalizer(this.getClass()).showDialog(); + ``` + + 自动复制以下内容到剪切板 + + ```java + REG.getString("[注册文件中填写的key]") + ``` + + - KSqlUtil + + 数据库工具类,支持oracle和sqlserver + + 连接数据库首选项为多值,需要配置5行值: + + ```text + oracle或sqlserver + 数据库ip + 数据库id + 登录用户id + 登录用户密码 + ``` + + - KUtil + + - POIUtil + + - ScheduleUtil + + + +## 属性路径 + +> 从目标对象出发,通过一系列关系和类型过滤找到需要提取属性的对象,然后提取对象或其属性 + +格式: + +```text +1. 提取关系下的对象:配置关系属性名称,多层关系之间用点号“.”分隔,如“关系1.关系2.关系3” +2. 提取属性:如果提取当前对象,直接配置属性名称即可;如果需要通过关系查找,在上面点关系配置后面添加属性名称,也用点号分隔,如“属性名称”或“关系1.关系2.关系3.属性名称”;属性名称前加“#”则提取显示值,如“关系1.#属性名称” +3. 日期属性可以配置日期格式:在属性名称后添加“@日期格式”,如“日期属性名称@yyyy年MM月” +4. 提取关系和属性时都支持用“+”进行拼接 +``` + +过滤类型: + +```text +在需要过滤类型的层级关系名称后添加“@类型名称”,多个类型之间用英文逗号分隔,注意下面的特殊关系名称不全部支持类型过滤 + +如果指定不能包含的类型,在需要过滤类型的层级关系名称后添加“@!类型名称1,类型名称2”,多个类型之间用英文逗号分隔 +注意:感叹号只需要添加一次,影响分析无效 +``` + +属性值替换: + +```text +将属性值替换为另一个值 +在需要替换的属性名称后添加“@属性值1=替换值1,属性值2=替换值2”,多个配置之间用英文逗号分隔 + +替换所有非空值:“@*=替换值” +替换所有空值:“@=替换值” +``` + +一些特殊关系名称: + +```text +latest_item_revision:查找对象的最新版本,要求上一级是Item类型 +bom:查询bom子行,要求上一级是BomLine类型,支持类型过滤,配置版本类型名称 +parent:查询bom父行,要求上一级是BomLine类型 +meactivity:(仅提取关系下的子对象支持)获取工步文件夹,要求上一级是BomLine类型,支持类型过滤,获取到的是工步行,如果需要工步文件夹需要进一步获取al_object关系子对象,支持类型过滤,配置文件夹类型名称 +workflow: (仅提取关系下的子对象支持)根据流程模板名称和任务名称查询工作流程的任务,格式“workflow@流程模板名称,任务名称” +关系名称前加#:通过影响分析查询父对象,支持类型过滤,但不支持不包含类型 +``` + +特殊属性名称: + +```text +index: 填写序号,按表格行的主对象进行编号,格式固定为“对象标记名称:index”,不允许存在关系路径 +``` \ No newline at end of file diff --git a/cn.net.connor.std.aifrcp/build.properties b/cn.net.connor.std.aifrcp/build.properties new file mode 100644 index 0000000..c54964b --- /dev/null +++ b/cn.net.connor.std.aifrcp/build.properties @@ -0,0 +1,6 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + lib/ojdbc7.jar,\ + lib/sqljdbc4-2.0.jar diff --git a/cn.net.connor.std.aifrcp/lib/ojdbc7.jar b/cn.net.connor.std.aifrcp/lib/ojdbc7.jar new file mode 100644 index 0000000..2077ea3 Binary files /dev/null and b/cn.net.connor.std.aifrcp/lib/ojdbc7.jar differ diff --git a/cn.net.connor.std.aifrcp/lib/sqljdbc4-2.0.jar b/cn.net.connor.std.aifrcp/lib/sqljdbc4-2.0.jar new file mode 100644 index 0000000..240872c Binary files /dev/null and b/cn.net.connor.std.aifrcp/lib/sqljdbc4-2.0.jar differ diff --git a/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/Activator.java b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/Activator.java new file mode 100644 index 0000000..c37a825 --- /dev/null +++ b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/Activator.java @@ -0,0 +1,44 @@ +package cn.net.connor.std.aifrcp; + +import org.eclipse.ui.plugin.AbstractUIPlugin; +import org.osgi.framework.BundleContext; + +/** + * The activator class controls the plug-in life cycle + */ +public class Activator extends AbstractUIPlugin { + + // The plug-in ID + public static final String PLUGIN_ID = "cn.net.connor.std.aifrcp"; //$NON-NLS-1$ + + // The shared instance + private static Activator plugin; + + /** + * The constructor + */ + public Activator() { + } + + @Override + public void start(BundleContext context) throws Exception { + super.start(context); + plugin = this; + } + + @Override + public void stop(BundleContext context) throws Exception { + plugin = null; + super.stop(context); + } + + /** + * Returns the shared instance + * + * @return the shared instance + */ + public static Activator getDefault() { + return plugin; + } + +} diff --git a/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/KAction.java b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/KAction.java new file mode 100644 index 0000000..8af5ab9 --- /dev/null +++ b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/KAction.java @@ -0,0 +1,32 @@ +package cn.net.connor.std.aifrcp; + +import com.teamcenter.rac.aif.AbstractAIFUIApplication; +import com.teamcenter.rac.aif.common.actions.AbstractAIFAction; +import com.teamcenter.rac.util.Instancer; +import com.teamcenter.rac.util.MessageBox; + +public class KAction extends AbstractAIFAction { + + KAction(AbstractAIFUIApplication app, String string) { + super(app, string); + } + + @Override + public void run() { + try { + System.out.println("Command: [" + actionName + "]"); + int ind = actionName.indexOf('#'); + String action = actionName; + String actionData = ""; + if (ind > 0) { + action = actionName.substring(0, ind); + actionData = actionName.substring(ind + 1); + } + KCommand command = (KCommand) Instancer.newInstanceEx2(action, new Object[] { this.application, action, actionData }); + command.executeModal(); + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(e); + } + } +} diff --git a/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/KCommand.java b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/KCommand.java new file mode 100644 index 0000000..d8f965c --- /dev/null +++ b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/KCommand.java @@ -0,0 +1,16 @@ +package cn.net.connor.std.aifrcp; + +import com.teamcenter.rac.aif.AbstractAIFApplication; +import com.teamcenter.rac.aif.AbstractAIFCommand; + +public abstract class KCommand extends AbstractAIFCommand { + + protected AbstractAIFApplication app; + protected String actionInfo; + + public KCommand(AbstractAIFApplication app, String commandId, String actionInfo) { + this.app = app; + this.actionInfo = actionInfo; + } + +} diff --git a/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/KDialog.java b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/KDialog.java new file mode 100644 index 0000000..909f34e --- /dev/null +++ b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/KDialog.java @@ -0,0 +1,83 @@ +package cn.net.connor.std.aifrcp; + +import java.awt.GridBagConstraints; +import java.awt.Insets; + +import com.teamcenter.rac.aif.AbstractAIFDialog; +import com.teamcenter.rac.util.Instancer; +import com.teamcenter.rac.util.MessageBox; + +@SuppressWarnings("serial") +public abstract class KDialog extends AbstractAIFDialog { + + protected KDialogController aifController; + + protected GridBagConstraints getGridBagConstraints(double weightx, double weighty, Insets inset) { + return new GridBagConstraints(0, 0, 1, 1, weightx, weighty, GridBagConstraints.CENTER, GridBagConstraints.BOTH, inset, 0, 0); + } + + public KDialog() { + this(null); + } + + public KDialog(KDialogController aifController) { + super(false); + this.aifController = aifController; + if (this.aifController == null) { + try { + this.aifController = (KDialogController) Instancer.newInstanceEx2(this.getClass().getName() + "Controller", new Object[0]); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + public KDialog(AbstractAIFDialog parent, boolean model) { + this(parent, model, null); + } + + public KDialog(AbstractAIFDialog parent, boolean model, KDialogController aifController) { + super(parent, model); + this.aifController = aifController; + if (this.aifController == null) { + try { + this.aifController = (KDialogController) Instancer.newInstanceEx2(this.getClass().getName() + "Controller", new Object[0]); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + public boolean initDialog() { + try { + if (this.aifController == null) { + System.out.println("Dialog controller is null"); + return false; + } + this.aifController.setDialog(this); + if (!aifController.init()) { + return false; + } + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(this, e); + return false; + } + initUI(); + addListeners(); + return true; + } + + @Override + public void run() { + if (initDialog()) { + showDialog(); + } + + } + + protected abstract void addListeners(); + + protected abstract void initUI(); + +} diff --git a/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/KDialogController.java b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/KDialogController.java new file mode 100644 index 0000000..5486881 --- /dev/null +++ b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/KDialogController.java @@ -0,0 +1,23 @@ +package cn.net.connor.std.aifrcp; + +import com.teamcenter.rac.aif.AbstractAIFApplication; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCSession; + +public abstract class KDialogController { + + protected AbstractAIFApplication app; + protected TCSession session; + protected KDialog aifDialog; + + public KDialogController() { + this.app = AIFUtility.getCurrentApplication(); + this.session = (TCSession) app.getSession(); + } + + protected void setDialog(KDialog dialog) { + this.aifDialog = dialog; + } + + public abstract boolean init() throws Exception; +} diff --git a/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/KFormRendering.java b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/KFormRendering.java new file mode 100644 index 0000000..5e0964e --- /dev/null +++ b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/KFormRendering.java @@ -0,0 +1,77 @@ +package cn.net.connor.std.aifrcp; + +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCException; +import com.teamcenter.rac.stylesheet.AbstractRendering; +import com.teamcenter.rac.util.MessageBox; + +public abstract class KFormRendering extends AbstractRendering{ + + private static final long serialVersionUID = 3564943386348236428L; + + public KFormRendering(TCComponent arg0) throws Exception { + super(arg0); + loadRendering(); + } + + public abstract void loadUI() throws Exception; + + @Override + public void loadRendering() throws TCException { + try { + loadUI(); + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(e); + } + } + + public abstract void saveData() throws Exception; + + @Override + public void saveRendering() { + try { + saveData(); + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(e); + } + } + + public abstract boolean isModified(); + + @Override + public boolean isRenderingModified() { + return isModified(); + } + + /** + * Update form value, from window to viewer + */ + public abstract void updateData(); + + @Override + public void updateRendering() { + super.updateRendering(); + updateData(); + } + + public abstract void setReadOnly(); + + @Override + public void setRenderingReadOnly() { + super.setRenderingReadOnly(); + setReadOnly(); + } + + public abstract void setReadWrite(); + + @Override + public void setRenderingReadWrite() { + super.setRenderingReadWrite(); + setReadWrite(); + } + + + +} diff --git a/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/KFrame.java b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/KFrame.java new file mode 100644 index 0000000..6b689ae --- /dev/null +++ b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/KFrame.java @@ -0,0 +1,33 @@ +package cn.net.connor.std.aifrcp; + +import javax.swing.JFrame; + +import com.teamcenter.rac.util.MessageBox; +import com.teamcenter.rac.util.UIUtilities; + +@SuppressWarnings("serial") +public abstract class KFrame extends JFrame { + protected KDialogController controller; + + public KFrame(KDialogController controller) { + this.controller = controller; + try { + if (!this.controller.init()) { + return; + } + initUI(); + showFrame(); + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(this, e); + } + } + + public void showFrame() { + this.pack(); + UIUtilities.centerToScreen(this); + setVisible(true); + } + + protected abstract void initUI() throws Exception; +} diff --git a/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/KHandler.java b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/KHandler.java new file mode 100644 index 0000000..4fc5f39 --- /dev/null +++ b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/KHandler.java @@ -0,0 +1,24 @@ +package cn.net.connor.std.aifrcp; + +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.core.commands.ExecutionEvent; + +import com.teamcenter.rac.aif.AbstractAIFUIApplication; +import com.teamcenter.rac.aifrcp.AIFUtility; + +/** + * Add following config to MANIFEST.MF + * Eclipse-RegisterBuddy: cn.net.connor.std.aifrcp + * @author ycq + * + */ +public class KHandler extends AbstractHandler { + + @Override + public Object execute(ExecutionEvent arg0) { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + new Thread(new KAction(app,arg0.getCommand().getId())).start(); + return null; + } + +} diff --git a/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/KLocalizer.java b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/KLocalizer.java new file mode 100644 index 0000000..89d376e --- /dev/null +++ b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/KLocalizer.java @@ -0,0 +1,196 @@ +package cn.net.connor.std.aifrcp; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.Toolkit; +import java.awt.datatransfer.Clipboard; +import java.awt.datatransfer.StringSelection; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowEvent; +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.util.Properties; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; + +@SuppressWarnings("serial") +public class KLocalizer extends JFrame{ + + private JTextField tf_key; + private JTextField tf_en; + private JTextField tf_cn; + private JButton b_add; + private JLabel l_info; + private JButton b_close; + private Class c; + + public KLocalizer(Class c) { + this.c = c; + } + + public static void main(String[] args) { + new KLocalizer(KLocalizer.class).showDialog(); + } + + public void showDialog() { + this.setTitle(c.getPackage().getName()); + this.setMinimumSize(new Dimension(400,270)); + this.setPreferredSize(new Dimension(400,270)); + this.setLayout(new BorderLayout()); + this.add(BorderLayout.CENTER,initCenterPanel()); + this.add(BorderLayout.SOUTH,initBtnPanel()); + addListeners(); + pack(); + this.setLocationRelativeTo(null); + this.setAlwaysOnTop(true); + setVisible(true); + } + + private void addListeners() { + b_add.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + try { + addLocaleInfo(); + } catch (Exception e1) { + e1.printStackTrace(); + } + } + }); + this.b_close.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + dispose(); + } + }); + } + + protected void addLocaleInfo() throws Exception{ + this.l_info.setText(""); + String key = this.tf_key.getText(); + String en = this.tf_en.getText(); + String cn = this.tf_cn.getText(); + Package p = c.getPackage(); + String path = "src/"+p.getName().replace('.', '/'); + System.out.println("PATH: "+path); + int index = path.lastIndexOf('/'); + if(index<=0) { + this.l_info.setText("Class Path Error"); + return; + } + String title = path.substring(index+1); + String enFile = path+"/"+title+"_locale.properties"; + String cnFile = path+"/"+title+"_locale_zh_CN.properties"; + System.out.println("TITLE: "+title); + if(title.length()>0) { + String code = "REG.getString(\""+key+"\")"; + System.out.println("PASTE: "+code); + StringSelection selection = new StringSelection(code); + Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); + clipboard.setContents(selection, selection); + } + File file = new File(enFile); + if(!file.exists()) { + file.createNewFile(); + } + file = new File(cnFile); + if(!file.exists()) { + file.createNewFile(); + } + //System.out.println("EN Path:"+enFile); + //System.out.println("CN Path"+cnFile); + Properties enProps = new Properties(); + enProps.load(new FileReader(enFile)); + Properties cnProps = new Properties(); + cnProps.load(new FileReader(cnFile)); + if(enProps.containsKey(key)||cnProps.containsKey(key)) { + this.l_info.setText("Key "+key+" already existed."); + System.out.println("REG.getString(\""+key+"\")"); + return; + } + if(isEmpty(key)||isEmpty(en)||isEmpty(cn)) { + this.l_info.setText("Missing input."); + return; + } + System.out.println("EN: "+key+"="+en); + System.out.println("CN: "+key+"="+cn); + enProps.setProperty(key, en); + cnProps.setProperty(key, cn); + FileOutputStream enos; + enProps.store(enos = new FileOutputStream(enFile), ""); + FileOutputStream cnos; + cnProps.store(cnos = new FileOutputStream(cnFile), ""); + enos.flush(); + enos.close(); + cnos.flush(); + cnos.close(); + this.l_info.setText("Write success."); + tf_key.setText(""); + tf_en.setText(""); + tf_cn.setText(""); + } + + private JPanel initBtnPanel() { + JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER,15,5)); + panel.add(this.b_add = new JButton(" Write ")); + panel.add(this.b_close = new JButton(" Close ")); + return panel; + } + + private JPanel initCenterPanel() { + JPanel panel = new JPanel(new GridBagLayout()); + panel.setBorder(BorderFactory.createEmptyBorder(0,30,0,25)); + GridBagConstraints s = new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(4, 0, 4, 5), 0, 0); + newRow(panel, new JLabel("Key: "), s, 1); + addCol(panel, this.tf_key = new JTextField(), s, 1, 1); + newRow(panel, new JLabel("EN: "), s, 1); + addCol(panel, this.tf_en = new JTextField(), s, 1, 1); + newRow(panel, new JLabel("CN: "), s, 1); + addCol(panel, this.tf_cn = new JTextField(), s, 1, 1); + this.l_info = new JLabel(); + this.l_info.setForeground(Color.RED); + this.l_info.setPreferredSize(new Dimension(100,50)); + newRow(panel, l_info, s, 2); + return panel; + } + + public static boolean isEmpty(String str) { + return str==null||"".equals(str.trim()); + } + + @Override + protected void processWindowEvent(WindowEvent e) { + if(e.getID()==WindowEvent.WINDOW_CLOSING) { + dispose(); + } + super.processWindowEvent(e); + } + + public static void newRow(JPanel panel, Component comp, GridBagConstraints s, int width) { + s.weightx = 0; + s.gridwidth = width; + s.gridx = 0; + s.gridy++; + panel.add(comp, s); + } + + public static void addCol(JPanel panel, Component comp, GridBagConstraints s, int width, double weightx) { + s.gridx++; + s.gridwidth = width; + s.weightx = weightx; + panel.add(comp, s); + } +} diff --git a/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/KOperation.java b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/KOperation.java new file mode 100644 index 0000000..c3318bd --- /dev/null +++ b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/KOperation.java @@ -0,0 +1,45 @@ +package cn.net.connor.std.aifrcp; + +import com.teamcenter.rac.aif.AbstractAIFApplication; +import com.teamcenter.rac.aif.AbstractAIFOperation; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +public abstract class KOperation extends AbstractAIFOperation{ + + protected AbstractAIFApplication app; + protected TCSession session; + + public KOperation(AbstractAIFApplication app,String opName) { + super(opName,true); + this.app = app; + this.session = (TCSession)app.getSession(); + setSession(session); + } + + public abstract boolean init() throws Exception; + + public abstract void execute() throws Exception; + + public abstract void clearCache() throws Exception; + + @Override + public void executeOperation() { + try { + if(!init()) { + return; + } + execute(); + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(e); + } finally { + try { + clearCache(); + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(e); + } + } + } +} diff --git a/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/KCheckBoxTableHeaderRenderer.java b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/KCheckBoxTableHeaderRenderer.java new file mode 100644 index 0000000..25a4149 --- /dev/null +++ b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/KCheckBoxTableHeaderRenderer.java @@ -0,0 +1,64 @@ +package cn.net.connor.std.aifrcp.util; + + +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +import javax.swing.BorderFactory; +import javax.swing.JCheckBox; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JTable; +import javax.swing.SwingConstants; +import javax.swing.table.JTableHeader; +import javax.swing.table.TableCellRenderer; + +public class KCheckBoxTableHeaderRenderer implements TableCellRenderer{ + + private JTableHeader tableHeader; + private JCheckBox selectBox; + private int indBoolean; + + public KCheckBoxTableHeaderRenderer(final JTable table, int indBoolean,boolean selected) { + this.tableHeader = table.getTableHeader(); + this.indBoolean=indBoolean; + selectBox = new JCheckBox(""); + selectBox.setSelected(selected); + tableHeader.addMouseListener(new MouseAdapter() { + public void mouseClicked(MouseEvent e) { + if (e.getClickCount() > 0) { + int selectColumn = tableHeader.columnAtPoint(e.getPoint()); + if (selectColumn == indBoolean) { + boolean value = !selectBox.isSelected(); + selectBox.setSelected(value); + for(int index = 0; index < table.getRowCount(); index ++){ + table.setValueAt(value, index, indBoolean); + } + tableHeader.repaint(); + } + } + } + }); + } + + @Override + public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { + String valueStr = (String) value; + JLabel label = new JLabel(valueStr); + label.setHorizontalAlignment(SwingConstants.CENTER); + selectBox.setHorizontalAlignment(SwingConstants.CENTER); + selectBox.setBorderPainted(true); + JComponent component = (column == indBoolean) ? selectBox : label; + component.setOpaque(true); + component.setForeground(tableHeader.getForeground()); + component.setBackground(tableHeader.getBackground()); + component.setFont(tableHeader.getFont()); + component.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, Color.WHITE)); + component.setPreferredSize(new Dimension(component.getPreferredSize().width,25)); + return component; + } + +} \ No newline at end of file diff --git a/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/KChineseSplitter.java b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/KChineseSplitter.java new file mode 100644 index 0000000..b65e94a --- /dev/null +++ b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/KChineseSplitter.java @@ -0,0 +1,141 @@ +package cn.net.connor.std.aifrcp.util; + +import java.util.ArrayList; +import java.util.List; + +public class KChineseSplitter { + + public static List getDivideVals(String propVal, int maxLen) { + return getDivideVals(propVal, maxLen, "\n"); + // List res = new ArrayList<>(); + // if(KUtil.isEmpty(propVal)||maxLen<=0) { + // res.add(propVal); + // return res; + // } + // String[] texts = propVal.split("\n"); + // for (int j = 0; j < texts.length; j++) { + // String text = texts[j]; + // if (maxLen > 0) { + // List splitRes = splitStrFullCharacter(text, maxLen); + // res.addAll(splitRes); + // } else { + // res.add(text); + // } + // } + // return res; + } + + public static List getDivideVals(String propVal, int maxLen, String splitFlag) { + List res = new ArrayList<>(); + if (KUtil.isEmpty(propVal) || maxLen <= 0) { + if (splitFlag != null && !"".equals(splitFlag) && !KUtil.isEmpty(propVal)) { + String[] texts = propVal.split(splitFlag); + for (int j = 0; j < texts.length; j++) { + res.add(texts[j]); + } + } else { + res.add(propVal); + } + return res; + } + String[] texts; + if (splitFlag == null || "".equals(splitFlag)) { + texts = new String[] { propVal }; + } else { + texts = propVal.split(splitFlag); + } + for (int j = 0; j < texts.length; j++) { + String text = texts[j]; + if (maxLen > 0) { + List splitRes = splitStrFullCharacter(text, maxLen); + res.addAll(splitRes); + } else { + res.add(text); + } + } + return res; + } + + public static List splitStrFullCharacter(String str, int charNum) { + List res = new ArrayList<>(); + int index = getSplitIndex(str, charNum); + while (index > 0) { + res.add(str.substring(0, index)); + str = str.substring(index); + index = getSplitIndex(str, charNum); + } + // if (!"".equals(str)) { + res.add(str); + // } + return res; + } + + // public static double getFullCharacterLength(String str) { + // char[] chars = str.toCharArray(); + // double counter = 0; + // for (int i = 0; i < chars.length; i++) { + // if (isFullCharacter(chars[i])) { + // counter += 1; + // } else { + // counter += 0.5; + // } + // } + // return counter; + // } + + public static double getFullCharacterCount(String str) { + char[] chars = str.toCharArray(); + double counter = 0; + for (int i = 0; i < chars.length; i++) { + if (isFullCharacter(chars[i])) { + counter += 1; + } else { + counter += 0.5; + } + } + return counter; + + } + + public static int getSplitIndex(String str, double charNum) { + char[] chars = str.toCharArray(); + double counter = 0; + for (int i = 0; i < chars.length; i++) { + if (isFullCharacter(chars[i])) { + counter += 1; + } else { + counter += 0.5; + } + if (counter == charNum) { + return i + 1; + } else if (counter > charNum) { + return i; + } + } + return -1; + } + + // 根据Unicode编码完美的判断中文汉字和符号 + public static boolean isChinese(char c) { + Character.UnicodeBlock ub = Character.UnicodeBlock.of(c); + if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A + || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION + || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) { + return true; + } + return false; + } + + public static boolean isFullCharacter(char c) { + if (isChinese(c)) { + return true; + } + String temp = String.valueOf(c); + if (temp.matches("[\u4e00-\u9fa5]")) { + return true; + } + int charValue = (int) c; + // System.out.println(charValue); + return (charValue >= 65281 && charValue <= 65374) || (charValue >= 12288 && charValue <= 12290 || charValue == 9474); + } +} \ No newline at end of file diff --git a/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/KEmptyDialog.java b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/KEmptyDialog.java new file mode 100644 index 0000000..793fb0b --- /dev/null +++ b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/KEmptyDialog.java @@ -0,0 +1,11 @@ +package cn.net.connor.std.aifrcp.util; + +import com.teamcenter.rac.aif.AbstractAIFDialog; + +@SuppressWarnings("serial") +public class KEmptyDialog extends AbstractAIFDialog { + + public KEmptyDialog() { + super(false); + } +} diff --git a/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/KSWTProgressDialog.java b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/KSWTProgressDialog.java new file mode 100644 index 0000000..40ab0f1 --- /dev/null +++ b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/KSWTProgressDialog.java @@ -0,0 +1,121 @@ +package cn.net.connor.std.aifrcp.util; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.window.Window; +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.ProgressBar; +import org.eclipse.swt.widgets.Shell; + +public class KSWTProgressDialog extends Dialog { + private String m_title = ""; + + private String m_message = ""; + + private ProgressBar m_progressBar; + + private boolean indeterminate; + + private Label label; + + private Label subLabel; + + private boolean showSubMessage; + + public KSWTProgressDialog(Shell paramShell, String title, String message, int shellStyle, boolean indeterminate, boolean showSubMessage) { + super(paramShell); + this.m_title = title; + this.m_message = message; + this.indeterminate = indeterminate; + this.showSubMessage = showSubMessage; + if (shellStyle <= 0) { + setShellStyle(0x8830 | Window.getDefaultOrientation()); + } else { + setShellStyle(shellStyle); + } + } + + public KSWTProgressDialog(Shell paramShell, String title, String message, int shellStyle, boolean indeterminate) { + this(paramShell, title, message, 0, indeterminate, false); + } + + public KSWTProgressDialog(Shell paramShell, String title, String message) { + this(paramShell, title, message, 0, false, false); + } + + protected void configureShell(Shell paramShell) { + super.configureShell(paramShell); + paramShell.setText(this.m_title); + } + + protected void createButtonsForButtonBar(Composite paramComposite) { + } + + protected Control createContents(Composite paramComposite) { + super.createContents(paramComposite); + getShell().setText(this.m_title); + Composite composite = (Composite) getDialogArea(); + this.label = new Label(composite, SWT.NONE); + label.setText(this.m_message); + this.m_progressBar = new ProgressBar(composite, indeterminate ? SWT.INDETERMINATE : SWT.NONE);// NULL SMOOTH INDETERMINATE + GridData gridData = new GridData(GridData.FILL_HORIZONTAL); + label.setLayoutData(gridData); + gridData = new GridData(GridData.FILL_HORIZONTAL); + this.m_progressBar.setLayoutData(gridData); + if (showSubMessage) { + this.subLabel = new Label(composite, SWT.NONE); + gridData = new GridData(GridData.FILL_HORIZONTAL); + this.subLabel.setLayoutData(gridData); + } + return composite; + } + + public void updateProgress(int value, int count) { + updateProgress(null, value, count); + } + + public void updateMessage(String message) { + updateProgress(message, -1, -1); + } + + public void updateSubMessage(String suMessage) { + updateSubProgress(suMessage, -1, -1); + } + + public void updateProgress(String message, int value, int count) { + Display.getDefault().asyncExec(() -> { + if (message != null) { + label.setText(message); + } + if (count > 0) { + m_progressBar.setMaximum(count); + m_progressBar.setSelection(value); + } + }); + } + + public void updateSubProgress(String subMessage, int value, int count) { + Display.getDefault().asyncExec(() -> { + if (subMessage != null && subLabel != null) { + subLabel.setText(subMessage); + } + if (count > 0) { + m_progressBar.setMaximum(count); + m_progressBar.setSelection(value); + } + }); + } + + public void openDialog() { + Display.getDefault().asyncExec(() -> open()); + } + + public void closeDialog() { + Display.getDefault().asyncExec(() -> close()); + } + +} diff --git a/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/KSqlUtil.java b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/KSqlUtil.java new file mode 100644 index 0000000..26eba95 --- /dev/null +++ b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/KSqlUtil.java @@ -0,0 +1,251 @@ +package cn.net.connor.std.aifrcp.util; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import com.teamcenter.rac.kernel.TCException; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.Registry; + +public class KSqlUtil { + + private static final String ORACLE = "ORACLE"; + private static final String SQLSERVER = "SQLSERVER"; + private static final Registry REG = Registry.getRegistry(KSqlUtil.class); + + public static Date getDate(java.sql.Date date) { + if (date == null) { + return null; + } + return new Date(date.getTime()); + } + + public static Connection getConnection(TCSession session, String prefName) throws Exception{ + String[] prefVals = KUtil.getPrefVals(session, prefName); + int len = KUtil.getLen(prefVals); + if(len!=5) { + throw new TCException(String.format(REG.getString("preferror.ERROR1"), prefName)); + } + String dbType = prefVals[0].toUpperCase(); + String ip = prefVals[1].trim(); + String sid = prefVals[2].trim(); + String user = prefVals[3].trim(); + String password = prefVals[4].trim(); + switch (dbType) { + case ORACLE: + return getOracleConnection(ip, sid, user, password); + case SQLSERVER: + return getSqlServerConnection(ip, sid, user, password); + default: + throw new TCException("Unknown database type: "+dbType); + } + } + + public static Connection getOracleConnection(TCSession session, String prefName) throws Exception { + String[] prefVals = KUtil.getPrefVals(session, prefName); + if (KUtil.getLen(prefVals) != 4) { + throw new TCException(String.format(REG.getString("preferror.ERROR1"), prefName)); + } + String ip = prefVals[0]; + String sid = prefVals[1]; + String user = prefVals[2]; + String password = prefVals[3]; + return getOracleConnection(ip, sid, user, password); + } + + public static Connection getOracleConnection(String ip, String sid, String user, String password) throws Exception { + String driver = "oracle.jdbc.driver.OracleDriver"; + String url = String.format("jdbc:oracle:thin:@%s:1521:%s", ip, sid); + Connection connection = null; + try { + Class.forName(driver); + connection = DriverManager.getConnection(url, user, password); + connection.setAutoCommit(false); + } catch (Exception e) { + e.printStackTrace(); + } + if (connection == null) { + throw new TCException(REG.getString("dbconn.ERROR")); + } + return connection; + } + + public static Connection getSqlServerConnection(TCSession session, String prefName) throws Exception { + String[] prefVals = KUtil.getPrefVals(session, prefName); + if (KUtil.getLen(prefVals) != 4) { + throw new TCException(String.format(REG.getString("preferror.ERROR1"), prefName)); + } + String ip = prefVals[0]; + String sid = prefVals[1]; + String user = prefVals[2]; + String password = prefVals[3]; + return getSqlServerConnection(ip, sid, user, password); + } + + public static Connection getSqlServerConnection(String ip, String sid, String user, String password) throws Exception { + String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; + String url = String.format("jdbc:sqlserver://%s;DatabaseName=%s", ip, sid); + Connection connection = null; + try { + Class.forName(driver); + connection = DriverManager.getConnection(url, user, password); + connection.setAutoCommit(false); + } catch (Exception e) { + e.printStackTrace(); + } + if (connection == null) { + throw new TCException(REG.getString("dbconn.ERROR")); + } + return connection; + } + + public static final PreparedStatement getPs(Connection conn, String sql) throws Exception { + return getPs(conn, sql, null); + } + + public static final PreparedStatement getPs(Connection conn, String sql, Object[] argments) throws Exception { + PreparedStatement ps = conn.prepareStatement(sql); + if (argments != null) { + for (int i = 0; i < argments.length; i++) { + ps.setObject(i + 1, argments[i]); + } + } + return ps; + } + + public static final int update(Connection conn, String sql) { + return update(conn, sql, null); + } + + public static final int update(Connection conn, String sql, Object[] argments) { + int i = -1; + PreparedStatement ps = null; + try { + ps = KSqlUtil.getPs(conn, sql, argments); + i = ps.executeUpdate(); + conn.commit(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + free(ps); + } + return i; + } + + public static final int updateNoCommit(Connection conn, String sql, Object[] argments) { + int i = -1; + PreparedStatement ps = null; + try { + ps = KSqlUtil.getPs(conn, sql, argments); + i = ps.executeUpdate(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + free(ps); + } + return i; + } + + public static final ResultSet read(PreparedStatement ps) throws Exception { + ResultSet rs = ps.executeQuery(); + return rs; + } + + public static final String queryString(Connection conn, String sql, Object[] params) throws Exception { + ResultSet rs = null; + PreparedStatement ps = null; + String res = null; + try { + ps = KSqlUtil.getPs(conn, sql, params); + rs = KSqlUtil.read(ps); + while (rs.next()) { + res = rs.getString(1); + } + } finally { + KSqlUtil.free(rs, ps, null); + } + return res; + } + + public static final List queryStringArray(Connection conn, String sql, Object[] params) throws Exception { + ResultSet rs = null; + PreparedStatement ps = null; + List res = new ArrayList(); + try { + ps = KSqlUtil.getPs(conn, sql, params); + rs = KSqlUtil.read(ps); + while (rs.next()) { + res.add(rs.getString(1)); + } + } finally { + KSqlUtil.free(rs, ps, null); + } + return res; + } + + public static final List queryStringArray(Connection conn, String sql, Object[] params, int colCnt) throws Exception { + if (colCnt == 0) { + return null; + } + ResultSet rs = null; + PreparedStatement ps = null; + List res = new ArrayList(); + try { + ps = KSqlUtil.getPs(conn, sql, params); + rs = KSqlUtil.read(ps); + while (rs.next()) { + String[] rowdata = new String[colCnt]; + for (int i = 0; i < colCnt; i++) { + rowdata[i] = rs.getString(i + 1); + } + res.add(rowdata); + } + } finally { + KSqlUtil.free(rs, ps, null); + } + return res; + } + + public static final void free(ResultSet resultSet) { + free(resultSet, null, null); + } + + public static final void free(Statement statement) { + free(null, statement, null); + } + + public static final void free(Connection connection) { + free(null, null, connection); + } + + public static final void free(ResultSet resultSet, Statement statement, Connection connection) { + if (statement != null) { + try { + statement.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + if (connection != null) { + try { + connection.close(); + connection = null; + } catch (Exception e) { + e.printStackTrace(); + } + } + if (resultSet != null) { + try { + resultSet.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } +} \ No newline at end of file diff --git a/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/KTableRowTableLoader.java b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/KTableRowTableLoader.java new file mode 100644 index 0000000..64e26e0 --- /dev/null +++ b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/KTableRowTableLoader.java @@ -0,0 +1,289 @@ +package cn.net.connor.std.aifrcp.util; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.swing.JComponent; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.table.DefaultTableModel; +import javax.swing.table.TableColumnModel; + +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCException; +import com.teamcenter.rac.kernel.TCProperty; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.services.rac.core.DataManagementService; + +public class KTableRowTableLoader { + + private TCComponent parent; + private String prefName; + private DefaultTableModel tableModel; + private JTable table; + private TCSession session; + private String[] tableHeaders; + private int[] tableHeaderWidth; + private String[] tableProps; + private String tableRowType; + private String tableRowRelation; + private List tableRows = new ArrayList<>(); + private boolean editable; + + private KTableRowTableLoader(TCSession session, TCComponent parent, String prefName, boolean editable) { + this.session = session; + this.parent = parent; + this.prefName = prefName; + this.editable = editable; + } + + public static KTableRowTableLoader parse(TCSession session, TCComponent parent, String prefName, boolean editable) throws Exception { + KTableRowTableLoader loader = new KTableRowTableLoader(session, parent, prefName, editable); + loader.initColConfigs(); + if (KUtil.getLen(loader.tableHeaders) < 1) { + return null; + } + TCProperty prop = parent.getTCProperty(loader.tableRowRelation); + if (prop == null) { + System.out.println(parent + " -> " + parent.getType()); + System.out.println("Property not defined: " + loader.tableRowRelation); + return null; + } + return loader; + } + + public void loadTCData() throws Exception { + tableRows.clear(); + tableModel.getDataVector().clear(); + TCComponent[] cc = parent.getRelatedComponents(tableRowRelation); + int len = KUtil.getLen(cc); + for (int i = 0; i < len; i++) { + addRow(cc[i]); + } + } + + public void addRow(TCComponent comp) throws Exception { + KTableRow row = new KTableRow(comp, tableProps); + this.tableRows.add(row); + tableModel.addRow(row.getRowData()); + } + + public DefaultTableModel getTableModel() { + return tableModel; + } + + public void setTableModel(DefaultTableModel tableModel) { + this.tableModel = tableModel; + } + + public JTable getTable() { + return table; + } + + public void setTable(JTable table) { + this.table = table; + } + + public void removeRow() throws Exception { + int[] selectRows = table.getSelectedRows(); + Arrays.sort(selectRows); + System.out.println("Remove Rows: " + Arrays.toString(selectRows)); + int len = selectRows.length; + if (len > 0) { + for (int i = len - 1; i >= 0; i--) { + int index = selectRows[i]; + tableModel.removeRow(index); + this.tableRows.remove(index); + } + } else { + int rowCnt = table.getRowCount(); + if (rowCnt > 0) { + tableModel.removeRow(rowCnt - 1); + this.tableRows.remove(rowCnt - 1); + } + } + + } + + @SuppressWarnings("deprecation") + public void saveTCData() throws Exception { + if (table.getCellEditor() != null) { + table.getCellEditor().stopCellEditing(); + } + int rowCnt = tableRows.size(); + if (rowCnt != table.getRowCount()) { + System.out.println("Not match: " + rowCnt + " - " + table.getRowCount()); + throw new Exception("Table Row Count Error"); + } + System.out.println("Save TableRow: " + parent); + DataManagementService dmService = DataManagementService.getService(session); + List rowComponents = new ArrayList<>(); + int colCnt = KUtil.getLen(tableProps); + for (int i = 0; i < rowCnt; i++) { + String[] tableRowValue = new String[colCnt]; + for (int j = 0; j < colCnt; j++) { + tableRowValue[j] = (String) table.getValueAt(i, j); + } + KTableRow tableRow = this.tableRows.get(i); + TCComponent comp = tableRow.getRowComponent(dmService, tableRowType, tableRowValue); + rowComponents.add(comp); + } + parent.lock(); + try { + TCProperty prop = parent.getTCProperty(tableRowRelation); + if (prop == null) { + throw new Exception("Property not defined: " + tableRowRelation); + } + prop.setReferenceValueArray(rowComponents.toArray(new TCComponent[] {})); + parent.save(); + } finally { + parent.unlock(); + } + } + + public boolean isModified() throws Exception { + int rowCnt = tableRows.size(); + if (rowCnt != table.getRowCount()) { + System.out.println("Not match: " + rowCnt + " - " + table.getRowCount()); + throw new Exception("Table Row Count Error"); + } + int colCnt = KUtil.getLen(tableProps); + for (int i = 0; i < rowCnt; i++) { + String[] tableRowValue = new String[colCnt]; + for (int j = 0; j < colCnt; j++) { + tableRowValue[j] = (String) table.getValueAt(i, j); + } + KTableRow tableRow = this.tableRows.get(i); + if (tableRow.isModified(tableRowValue)) { + return true; + } + } + return false; + } + + @SuppressWarnings("serial") + public JComponent getTablePanel() throws Exception { + this.tableModel = new DefaultTableModel(); + this.table = new JTable(this.tableModel) { + public boolean isCellEditable(int row, int column) { + return editable; + } + }; + tableModel.setDataVector(null, tableHeaders); + table.getTableHeader().setReorderingAllowed(false); + int colCnt = KUtil.getLen(tableHeaders); + TableColumnModel colModel = this.table.getColumnModel(); + for (int i = 0; i < colCnt; i++) { + colModel.getColumn(i).setPreferredWidth(tableHeaderWidth[i]); + } + this.table.setRowHeight(23); + // this.table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); + JScrollPane scroll = new JScrollPane(table); + return scroll; + } + + private void initColConfigs() throws Exception { + String[] tableConfigs = KUtil.getPrefVals(session, prefName); + int len = KUtil.getLen(tableConfigs); + if (len < 3) { + return; + } + this.tableRowType = tableConfigs[0].trim(); + this.tableRowRelation = tableConfigs[1].trim(); + int colCnt = len - 2; + tableHeaders = new String[colCnt]; + tableHeaderWidth = new int[colCnt]; + tableProps = new String[colCnt]; + for (int i = 0; i < colCnt; i++) { + String config = tableConfigs[i + 2]; + int ind = config.lastIndexOf('='); + if (ind > 0) { + tableHeaders[i] = config.substring(0, ind); + tableProps[i] = config.substring(ind + 1); + } else { + tableHeaders[i] = config; + tableProps[i] = config; + } + int width = 0; + while (tableHeaders[i].length() > 0 && Character.isDigit(tableHeaders[i].charAt(0))) { + width = width * 10 + (tableHeaders[i].charAt(0) - '0'); + tableHeaders[i] = tableHeaders[i].substring(1); + } + if (width < 1) { + width = 120; + } + tableHeaderWidth[i] = width; + } + + } + + public static class KTableRow { + + private TCComponent row; + private String[] propNames; + private String[] rowData; + + public KTableRow(TCComponent row, String[] propNames) throws Exception { + this.row = row; + this.propNames = propNames; + initRowData(); + } + + public String[] getRowData() { + return rowData; + } + + private void initRowData() throws Exception { + int colCnt = KUtil.getLen(propNames); + rowData = new String[colCnt]; + if (row != null) { + for (int i = 0; i < colCnt; i++) { + rowData[i] = row.getProperty(propNames[i]); + } + } + } + + public boolean isModified(String[] newValues) throws Exception { + if (row == null) { + return true; + } + int colCnt = KUtil.getLen(propNames); + if (colCnt != KUtil.getLen(newValues)) { + return true; + } + for (int i = 0; i < colCnt; i++) { + String oldValue = rowData[i] == null ? "" : rowData[i]; + String newValue = newValues[i] == null ? "" : newValues[i]; + if (!oldValue.equals(newValue)) { + return true; + } + } + return false; + } + + public TCComponent getRowComponent(DataManagementService dmService, String tableRowType, String[] newValues) throws Exception { + if (!isModified(newValues)) { + return row; + } + + Map rowStringProps = new HashMap(); + int colCnt = KUtil.getLen(propNames); + for (int i = 0; i < colCnt; i++) { + rowStringProps.put(propNames[i], newValues[i]); + } + if (this.row == null) { + this.row = KUtil.newTableRow(dmService, tableRowType, rowStringProps, null); + if (this.row == null) { + throw new TCException("Create TableRow \"" + tableRowType + "\" Failed"); + } + } else { + KUtil.setProperties(row, rowStringProps); + } + return row; + } + + } +} diff --git a/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/KUtil.java b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/KUtil.java new file mode 100644 index 0000000..1b9aafb --- /dev/null +++ b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/KUtil.java @@ -0,0 +1,2142 @@ +package cn.net.connor.std.aifrcp.util; + +import java.awt.Component; +import java.awt.Desktop; +import java.awt.Dimension; +import java.awt.GridBagConstraints; +import java.awt.Window; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.net.URI; +import java.nio.charset.Charset; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JFileChooser; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.filechooser.FileNameExtensionFilter; +import javax.swing.filechooser.FileSystemView; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Shell; + +import com.teamcenter.rac.aif.AbstractAIFUIApplication; +import com.teamcenter.rac.aif.kernel.AIFComponentContext; +import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.cme.time.common.ActivityUtils; +import com.teamcenter.rac.commands.open.OpenCommand; +import com.teamcenter.rac.kernel.ListOfValuesInfo; +import com.teamcenter.rac.kernel.SoaUtil; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentBOMLine; +import com.teamcenter.rac.kernel.TCComponentBOMWindow; +import com.teamcenter.rac.kernel.TCComponentCfgActivityLine; +import com.teamcenter.rac.kernel.TCComponentContextList; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentDatasetType; +import com.teamcenter.rac.kernel.TCComponentFolder; +import com.teamcenter.rac.kernel.TCComponentForm; +import com.teamcenter.rac.kernel.TCComponentGroup; +import com.teamcenter.rac.kernel.TCComponentGroupMember; +import com.teamcenter.rac.kernel.TCComponentItem; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCComponentItemRevisionType; +import com.teamcenter.rac.kernel.TCComponentItemType; +import com.teamcenter.rac.kernel.TCComponentListOfValues; +import com.teamcenter.rac.kernel.TCComponentListOfValuesType; +import com.teamcenter.rac.kernel.TCComponentManager; +import com.teamcenter.rac.kernel.TCComponentQuery; +import com.teamcenter.rac.kernel.TCComponentQueryType; +import com.teamcenter.rac.kernel.TCComponentSchedule; +import com.teamcenter.rac.kernel.TCComponentScheduleDeliverable; +import com.teamcenter.rac.kernel.TCComponentTaskDeliverable; +import com.teamcenter.rac.kernel.TCComponentType; +import com.teamcenter.rac.kernel.TCComponentUser; +import com.teamcenter.rac.kernel.TCException; +import com.teamcenter.rac.kernel.TCPreferenceService; +import com.teamcenter.rac.kernel.TCProperty; +import com.teamcenter.rac.kernel.TCPropertyDescriptor; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.kernel.TCUserService; +import com.teamcenter.rac.schedule.ScheduleViewApplication; +import com.teamcenter.rac.schedule.ScheduleViewApplicationPanel; +import com.teamcenter.rac.util.MessageBox; +import com.teamcenter.rac.util.Registry; +import com.teamcenter.rac.util.UIUtilities; +import com.teamcenter.services.internal.rac.structuremanagement.StructureService; +import com.teamcenter.services.internal.rac.structuremanagement._2008_06.Structure.CopyRecursivelyResponse; +import com.teamcenter.services.rac.core.DataManagementService; +import com.teamcenter.services.rac.core.SessionService; +import com.teamcenter.services.rac.core._2006_03.DataManagement.Relationship; +import com.teamcenter.services.rac.core._2007_01.DataManagement.WhereReferencedInfo; +import com.teamcenter.services.rac.core._2007_01.DataManagement.WhereReferencedOutput; +import com.teamcenter.services.rac.core._2007_01.DataManagement.WhereReferencedResponse; +import com.teamcenter.services.rac.core._2007_12.Session.StateNameValue; +import com.teamcenter.services.rac.core._2008_06.DataManagement.CreateIn; +import com.teamcenter.services.rac.core._2008_06.DataManagement.CreateInput; +import com.teamcenter.services.rac.core._2008_06.DataManagement.CreateOut; +import com.teamcenter.services.rac.core._2008_06.DataManagement.CreateResponse; +import com.teamcenter.soa.client.model.LovValue; +import com.teamcenter.soa.client.model.Property; +import com.teamcenter.soa.client.model.ServiceData; + +@SuppressWarnings("deprecation") +public class KUtil { + + public static final Registry REG = Registry.getRegistry(KUtil.class); + public static final ZoneId zoneId = ZoneId.systemDefault(); + + public static TCComponentItemRevision copyBOM(TCSession session, TCComponentBOMWindow bomWindow, String prefKey) throws Exception { + if (bomWindow == null) { + return null; + } + TCComponentBOMLine topLine = bomWindow.getTopBOMLine(); + if (topLine == null) { + return null; + } + TCComponentItemRevision newRev = null; + System.out.println("Copy Bom: " + topLine); + if (KUtil.isEmpty(prefKey)) { + prefKey = "Product.Template.Cloning"; // this is a preference name, "Product.Template" + } + System.out.println("PrefKey: " + prefKey); + StructureService ss = StructureService.getService(session); + TCComponentItem topItem = topLine.getItem(); + TCComponentItemRevision topRev = topLine.getItemRevision(); + TCComponentBOMWindow newWindow = bomWindow.getTypeComponent().create(bomWindow.getRevisionRule()); + TCComponentItemType pt = topItem.getTypeComponent(); + String id = pt.getNewID(); + String revId = pt.getNewRev(null); + String name = topItem.getStringProperty("object_name"); + String desc = topItem.getStringProperty("object_desc"); + CopyRecursivelyResponse resp = ss.copyRecursively(topRev, prefKey, bomWindow, newWindow, name, desc, id, revId, false); + SoaUtil.checkPartialErrors(resp.serviceData); + if (resp.serviceData.sizeOfCreatedObjects() != 0) { + newRev = (TCComponentItemRevision) resp.serviceData.getCreatedObject(0); + System.out.println(">> Copy Result: " + newRev); + } + newWindow.setClearCacheOnClose(true); + newWindow.close(); + return newRev; + } + + public static TCComponentSchedule getCurrentSchedule() { + AbstractAIFUIApplication aifApp = AIFUtility.getCurrentApplication(); + if (aifApp == null) { + return null; + } + if (aifApp instanceof ScheduleViewApplication) { + ScheduleViewApplication app = (ScheduleViewApplication) aifApp; + ScheduleViewApplicationPanel panel = (ScheduleViewApplicationPanel) app.getApplicationPanel(); + if (panel == null) { + return null; + } + return panel.getCurrentProject(); + } + InterfaceAIFComponent target = aifApp.getTargetComponent(); + if (target != null && (target instanceof TCComponentSchedule)) { + return (TCComponentSchedule) target; + } + return null; + } + + public static TCComponent[] objectsInProject(TCSession session, String type, String projId) throws Exception { + if (KUtil.isEmpty(type) || KUtil.isEmpty(projId)) { + return null; + } + String queryName = "Objects in Projects"; + String[] keys = new String[] { KUtil.getText(session, "Type"), KUtil.getText(session, "ProjectID") }; + String[] vals = new String[] { type, projId }; + return KUtil.query(session, queryName, keys, vals); + } + + public static TCComponent[] objectsInProject(TCSession session, String type, String projId, String name) throws Exception { + if (KUtil.isEmpty(type) || KUtil.isEmpty(projId) || KUtil.isEmpty(name)) { + return null; + } + String queryName = "Objects in Projects"; + String[] keys = new String[] { KUtil.getText(session, "Name"), KUtil.getText(session, "Type"), KUtil.getText(session, "ProjectID") }; + String[] vals = new String[] { name, type, projId }; + return KUtil.query(session, queryName, keys, vals); + } + + public static TCComponentItem createItem(TCComponentItemType itemType, String itemName) throws Exception { + if (itemType == null) { + return null; + } + String id = itemType.getNewID(); + String rev = itemType.getNewRev(null); + return itemType.create(id, rev, itemType.getName(), itemName, "", null); + } + + public static void setByPass(TCSession session, boolean b) throws Exception { + SessionService sessionService = SessionService.getService(session); + StateNameValue[] propPairs = new StateNameValue[1]; + propPairs[0] = new StateNameValue(); + propPairs[0].name = new String("bypassFlag"); + propPairs[0].value = new String(Property.toBooleanString(true)); + com.teamcenter.soa.client.model.ServiceData data = sessionService.setUserSessionState(propPairs); + SoaUtil.checkPartialErrors(data); + } + + public static void setByPassItk(TCSession session, boolean val) { + try { + TCUserService userservice = session.getUserService(); + userservice.call(val ? "CONNOR_open_bypass" : "CONNOR_close_bypass", new Object[] { "" }); + System.out.println(val ? "Open Bypass" : "Close Bypass"); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static TCComponentItem createItemBySOA(TCSession session, String itemTypeName, String revTypeName, String revMasterTypeName, String itemId, String revId, String name, + Map stringProps, Map dateProps, Map stringArrayProps) throws Exception { + if (KUtil.isEmpty(itemTypeName) || KUtil.isEmpty(revTypeName) || KUtil.isEmpty(revMasterTypeName)) { + return null; + } + CreateInput revMasterInput = new CreateInput(); + revMasterInput.boName = revMasterTypeName; + if (stringProps != null) { + revMasterInput.stringProps = stringProps; + } + if (dateProps != null) { + revMasterInput.dateProps = dateProps; + } + if (stringArrayProps != null) { + revMasterInput.stringArrayProps = stringArrayProps; + } + CreateInput revInput = new CreateInput(); + revInput.boName = revTypeName; + Map revPropMap = new HashMap<>(); + if (!KUtil.isEmpty(revId)) { + revPropMap.put("item_revision_id", revId); + } + revInput.stringProps = revPropMap; + Map revMasterInfoMap = new HashMap<>(); + revMasterInfoMap.put("IMAN_master_form_rev", new CreateInput[] { revMasterInput }); + revInput.compoundCreateInput = revMasterInfoMap; + // create rev + CreateInput itemInput = new CreateInput(); + itemInput.boName = itemTypeName; + Map itemPropMap = new HashMap<>(); + if (!KUtil.isEmpty(itemId)) { + itemPropMap.put("item_id", itemId); + } + if (!KUtil.isEmpty(name)) { + itemPropMap.put("object_name", name); + } + itemInput.stringProps = itemPropMap; + Map revInfoMap = new HashMap<>(); + revInfoMap.put("revision", new CreateInput[] { revInput }); + itemInput.compoundCreateInput = revInfoMap; + // create info + CreateIn cI = new CreateIn(); + cI.clientId = "CreateItem"; + cI.data = itemInput; + // service + DataManagementService service = DataManagementService.getService(session); + // create + CreateResponse resp = service.createObjects(new CreateIn[] { cI }); + SoaUtil.checkPartialErrors(resp.serviceData); + CreateOut[] cOs = resp.output; + if (cOs.length > 0) { + for (TCComponent s : cOs[0].objects) { + if (s instanceof TCComponentItem) { + return (TCComponentItem) s; + } + } + } + return null; + } + + public static TCComponentItemRevision getLatestReleaseRevison(TCComponentItem targetComp) throws Exception { + // System.out.println("Get Latest Released Revision: " + targetComp); + if (targetComp == null) { + return null; + } + List releaseRevisionList = new ArrayList<>(); + TCComponent[] comps = targetComp.getReferenceListProperty("revision_list"); + // System.out.println(">> Revisions: " + Arrays.toString(comps)); + for (TCComponent comp : comps) { + if (KUtil.isReleased(comp)) { + releaseRevisionList.add((TCComponentItemRevision) comp); + } + } + // System.out.println(">> Released Revisions: " + releaseRevisionList); + TCComponentItemRevision res = getLatestReleaseRevision(releaseRevisionList); + // System.out.println(">> Latest Released Revision: " + res); + return res; + } + + public static TCComponentItemRevision getLatestReleaseRevision(List releaseRevisionList) throws Exception { + if (releaseRevisionList.size() == 0) { + return null; + } + TCComponentItemRevision latestRev = null; + latestRev = releaseRevisionList.get(0); + String maxRevId = latestRev.getStringProperty("item_revision_id"); + String tempRevId; + for (TCComponentItemRevision rev : releaseRevisionList) { + tempRevId = rev.getStringProperty("item_revision_id"); + if (maxRevId.compareTo(tempRevId) < 0) { + maxRevId = tempRevId; + latestRev = rev; + } else if (maxRevId.compareTo(tempRevId) == 0) { + int maxSequenceId = latestRev.getIntProperty("sequence_id"); + int tempSequenceId = rev.getIntProperty("sequence_id"); + if (maxSequenceId < tempSequenceId) { + latestRev = rev; + } + } + } + return latestRev; + } + + public static TCComponentItem createItemBySOA(TCSession session, String itemTypeName, String revTypeName, String revMasterTypeName, String itemId, String revId, String name, + Map stringProps, Map dateProps) throws Exception { + return createItemBySOA(session, itemTypeName, revTypeName, revMasterTypeName, itemId, revId, name, stringProps, dateProps, null); + } + + public static TCComponentFolder createFolderBySOA(TCSession session, String folderTypeName, Map folderProperties) throws Exception { + if (KUtil.isEmpty(folderTypeName)) { + return null; + } + CreateInput itemInput = new CreateInput(); + itemInput.boName = folderTypeName; + if (folderProperties != null) { + itemInput.stringProps = folderProperties; + } + // create info + CreateIn cI = new CreateIn(); + cI.clientId = "CreateFolder"; + cI.data = itemInput; + // service + DataManagementService service = DataManagementService.getService(session); + // create + CreateResponse resp = service.createObjects(new CreateIn[] { cI }); + SoaUtil.checkPartialErrors(resp.serviceData); + CreateOut[] cOs = resp.output; + if (cOs.length > 0) { + for (TCComponent s : cOs[0].objects) { + if (s instanceof TCComponentFolder) { + return (TCComponentFolder) s; + } + } + } + return null; + } + + public static TCComponentFolder createFolderBySOA(TCSession session, String folderTypeName, String folderName) throws Exception { + if (KUtil.isEmpty(folderTypeName)) { + return null; + } + CreateInput itemInput = new CreateInput(); + itemInput.boName = folderTypeName; + Map itemPropMap = new HashMap<>(); + itemPropMap.put("object_name", folderName); + itemInput.stringProps = itemPropMap; + // create info + CreateIn cI = new CreateIn(); + cI.clientId = "CreateFolder"; + cI.data = itemInput; + // service + DataManagementService service = DataManagementService.getService(session); + // create + CreateResponse resp = service.createObjects(new CreateIn[] { cI }); + SoaUtil.checkPartialErrors(resp.serviceData); + CreateOut[] cOs = resp.output; + if (cOs.length > 0) { + for (TCComponent s : cOs[0].objects) { + if (s instanceof TCComponentFolder) { + return (TCComponentFolder) s; + } + } + } + return null; + } + + public static Date localDateToDate(LocalDate localDate) { + if (localDate == null) { + return null; + } + ZonedDateTime zdt = localDate.atStartOfDay(zoneId); + Date date = Date.from(zdt.toInstant()); + return date; + } + + public static LocalDate dateToLocalDate(Date date) { + if (date == null) { + return null; + } + Instant instant = date.toInstant(); + LocalDate localDate = instant.atZone(zoneId).toLocalDate(); + return localDate; + } + + public static TCComponent stringToComponent(TCSession session, String uid) throws Exception { + if (KUtil.isEmpty(uid)) { + return null; + } + return session.stringToComponent(uid); + } + + public static String getText(TCSession session, String str) throws Exception { + if (KUtil.isEmpty(str)) { + return str; + } + String res = session.getTextService().getTextValue(str); + if (!KUtil.isEmpty(res)) { + return res; + } + return str; + } + + public static void sendTo(TCComponent comp, String perspectiveId) { + if (comp == null) { + return; + } + if (KUtil.isEmpty(perspectiveId)) { + perspectiveId = "com.teamcenter.rac.ui.perspectives.navigatorPerspective"; + } + com.teamcenter.rac.common.Activator.getDefault().openPerspective(perspectiveId); + com.teamcenter.rac.common.Activator.getDefault().openComponents(perspectiveId, new TCComponent[] { comp }); + } + + public static void open(TCComponent comp) { + if (comp == null) { + return; + } + if (comp instanceof TCComponentScheduleDeliverable) { + System.out.println(">> Open Schedule Deliverable: " + comp); + try { + comp = comp.getReferenceProperty("deliverable_inst"); + System.out.println(">> Open Schedule Deliverable Inst: " + comp); + if (comp == null) { + return; + } + } catch (Exception e) { + e.printStackTrace(); + } + } else if (comp instanceof TCComponentTaskDeliverable) { + System.out.println(">> Open Task Deliverable: " + comp); + try { + comp = comp.getReferenceProperty("fnd0DeliverableInstance"); + System.out.println(">> Open Task Deliverable Inst: " + comp); + if (comp == null) { + return; + } + } catch (Exception e) { + e.printStackTrace(); + } + } + try { + Registry localRegistry = Registry.getRegistry("com.teamcenter.rac.commands.open.open"); + OpenCommand localOpenCommand = (OpenCommand) localRegistry.newInstanceForEx("openCommand", new Object[] { AIFUtility.getActiveDesktop(), comp }); + localOpenCommand.executeModeless(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static JButton getImageBtn(Class c, String iconPath) { + ImageIcon icon = new ImageIcon(c.getResource(iconPath)); + JButton btn = new JButton(icon); + btn.setPreferredSize(new Dimension(26, 26)); + btn.setContentAreaFilled(true); + btn.setFocusPainted(false); + btn.setBorderPainted(true); + return btn; + } + + public static void showScrollDialog(Window dialog, String text, String title) { + if (dialog == null) { + dialog = UIUtilities.getCurrentModalDialog(); + } + JTextArea textArea = new JTextArea(text); + textArea.setEditable(false); + JScrollPane scrollPane = new JScrollPane(textArea); + textArea.setLineWrap(true); + textArea.setWrapStyleWord(true); + scrollPane.setPreferredSize(new Dimension(500, 300)); + JOptionPane.showMessageDialog(dialog, scrollPane, title, JOptionPane.INFORMATION_MESSAGE); + } + + public static void showScrollDialogWithExport(Window dialog, String text, String title, String exportFileName) { + if (dialog == null) { + dialog = UIUtilities.getCurrentModalDialog(); + } + JTextArea textArea = new JTextArea(text); + textArea.setEditable(false); + JScrollPane scrollPane = new JScrollPane(textArea); + textArea.setLineWrap(true); + textArea.setWrapStyleWord(true); + scrollPane.setPreferredSize(new Dimension(500, 300)); + String yesOption = REG.getString("ok"); + String exportOption = REG.getString("export"); + int op = JOptionPane.showOptionDialog(dialog, scrollPane, title, JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new String[] { yesOption, exportOption }, yesOption); + if (op == 1) { + System.out.println("Export"); + File saveFile = KUtil.chooseSaveFile(dialog, exportFileName, "txt"); + if (saveFile != null) { + try { + BufferedWriter writer = new BufferedWriter(new FileWriter(saveFile, false)); + writer.write(text); + writer.flush(); + writer.close(); + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(dialog, e); + } + } + } + } + + public static void errorSWT(Shell shell, String message, String title) { + showDialog(shell, message, title, SWT.ICON_ERROR); + } + + public static void showDialog(Shell shell, String message, String title, int type) { + org.eclipse.swt.widgets.MessageBox dialog = new org.eclipse.swt.widgets.MessageBox(shell, SWT.OK | type); + dialog.setText(title); + dialog.setMessage(message); + dialog.open(); + } + + public static String[] getPrefVals(TCSession session, String prefName) throws Exception { + if (KUtil.isEmpty(prefName)) { + return null; + } + TCPreferenceService prefService = session.getPreferenceService(); + // prefService.refresh(); + return prefService.getStringValues(prefName); + } + + public static String getPrefVal(TCSession session, String prefName) throws Exception { + if (KUtil.isEmpty(prefName)) { + return null; + } + TCPreferenceService prefService = session.getPreferenceService(); + // prefService.refresh(); + return prefService.getStringValue(prefName); + } + + public static void newRow(JPanel panel, Component comp, GridBagConstraints s, int width) { + newRow(panel, comp, s, width, 0); + } + + public static void newRow(JPanel panel, Component comp, GridBagConstraints s, int width, double weightx) { + s.weightx = weightx; + s.gridwidth = width; + s.gridx = 0; + s.gridy++; + panel.add(comp, s); + } + + public static void newRow(JDialog panel, Component comp, GridBagConstraints s, int width) { + s.weightx = 0; + s.gridwidth = width; + s.gridx = 0; + s.gridy++; + panel.add(comp, s); + } + + public static void addCol(JPanel panel, Component comp, GridBagConstraints s, int width, double weightx) { + s.gridx++; + s.gridwidth = width; + s.weightx = weightx; + panel.add(comp, s); + } + + public static TCComponent getChildByTypeAndName(TCComponent parent, String cType, String cName, String relation) throws Exception { + if (parent == null || KUtil.isEmpty(cType) || KUtil.isEmpty(cName)) { + return null; + } + parent.refresh(); + TCComponent[] kids = parent.getRelatedComponents(relation); + if (kids == null) { + return null; + } + for (TCComponent c : kids) { + if (c.getType().equals(cType) && cName.equals((c.getStringProperty("object_name")))) { + return c; + } + } + return null; + } + + public static List getChildrenByType(TCComponent parent, String cType, String relation) throws Exception { + if (parent == null || KUtil.isEmpty(cType)) { + return null; + } + parent.refresh(); + List res = new ArrayList(); + TCComponent[] kids = parent.getRelatedComponents(relation); + if (kids == null) { + return null; + } + for (TCComponent c : kids) { + if (c.getType().equals(cType)) { + res.add(c); + } + } + return res; + } + + public static TCComponentFolder getChildFolder(TCComponentFolder folder, String cFolderName) throws Exception { + if (folder == null || cFolderName == null) { + return null; + } + AIFComponentContext[] cc = folder.getChildren(); + int len = KUtil.getLen(cc); + for (int i = 0; i < len; i++) { + InterfaceAIFComponent c = cc[i].getComponent(); + if ((c instanceof TCComponentFolder) && cFolderName.equals(c.getProperty("object_name"))) { + return (TCComponentFolder) c; + } + } + return null; + } + + public static TCComponentDataset uploadFile(TCSession session, TCComponent rev, File newFile, String dsName, String dsTypeName, String refName, String rel) throws Exception { + TCComponentDataset ds = (TCComponentDataset) getChildByTypeAndName(rev, dsTypeName, dsName, rel); + if (ds == null) { + TCComponentDatasetType dsType = (TCComponentDatasetType) session.getTypeComponent(dsTypeName); + ds = dsType.create(dsName, "", dsTypeName); + if (rev != null) { + rev.add(rel, ds); + rev.refresh(); + } + } + setDsFile(ds, refName, newFile); + return ds; + } + + public static void setDsFile(TCComponentDataset ds, String refName, File newFile) throws Exception { + String[] refs = new String[] { refName }; + String[] files = new String[] { newFile.getAbsolutePath() }; + ds.setFiles(files, refs); + // ds.save(); + ds.refresh(); + } + + public static boolean isEmpty(String str) { + return str == null || "".equals(str.trim()); + } + + public static int inArray(int target, int[] arr) { + int len = arr == null ? 0 : arr.length; + for (int i = 0; i < len; i++) { + if (target == arr[i]) { + return i; + } + } + return -1; + } + + public static int inArray(String target, String[] arr) { + if (target == null) { + return -1; + } + int len = arr == null ? 0 : arr.length; + for (int i = 0; i < len; i++) { + if (target.equals(arr[i])) { + return i; + } + } + return -1; + } + + public static File getFileFromDataset(TCSession session, String dsType, String uid, String prefName) throws Exception { + TCComponent comp = null; + try { + comp = session.stringToComponent(uid); + } catch (Exception e) { + e.printStackTrace(); + } + if (comp == null) { + throw new TCException(String.format(REG.getString("dsuidinpref.ERROR1"), prefName)); + } + String type = comp.getType(); + System.out.println("Dataset: " + comp + "|Type: " + type); + if (!dsType.equals(type)) { + throw new TCException(String.format(REG.getString("dsuidinpref.ERROR1"), prefName)); + } + TCComponentDataset tDataset = (TCComponentDataset) comp; + return getDatasetFile(tDataset); + } + + public static File getDatasetFile(TCComponentDataset dataset) throws Exception { + File[] files = dataset.getFiles("", System.getenv("TEMP")); + if (files == null || files.length == 0) { + throw new TCException(String.format(REG.getString("norefindataset.ERROR1"), dataset.toString())); + } + System.out.println(">> Download file (" + files.length + "): " + files[0].getAbsolutePath()); + return files[0]; + } + + public static File getDatasetFile(File dir, TCComponentDataset dataset) throws Exception { + if (dir == null || !dir.isDirectory()) { + throw new TCException("Directory not found."); + } + File[] files = dataset.getFiles("", dir.getAbsolutePath()); + if (files == null || files.length == 0) { + throw new TCException(String.format(REG.getString("norefindataset.ERROR1"), dataset.toString())); + } + System.out.println(">> Download file (" + files.length + "): " + files[0].getAbsolutePath()); + return files[0]; + } + + public static File getDatasetFile(File dir, TCComponentDataset dataset, String refName) throws Exception { + if (dir == null || !dir.isDirectory()) { + throw new TCException("Directory not found."); + } + String[] fileNames = dataset.getFileNames(refName); + if (fileNames.length == 0) { + return null; + } + File file = dataset.getFile(refName, fileNames[0], dir.getAbsolutePath()); + return file; + } + + public static String[] getStringArrayProp(TCComponentForm form, String propName) throws Exception { + if (form == null) { + return null; + } + TCProperty prop = form.getFormTCProperty(propName); + if (prop == null) { + throw new java.lang.Exception(String.format(REG.getString("nopropintype.ERROR2"), form.getDisplayType(), propName)); + } + return prop.getStringArrayValue(); + } + + public static File chooseDirectory(Component parent) { + FileSystemView fsv = FileSystemView.getFileSystemView(); + String deskPath = fsv.getHomeDirectory().getPath(); + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setCurrentDirectory(new File(deskPath)); + fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + int state = fileChooser.showOpenDialog(parent); + if (state == 1) { + return null; + } + return fileChooser.getSelectedFile(); + } + + public static boolean addReleaseStatus(TCSession session, String uid, String status) throws Exception { + TCUserService userservice = session.getUserService(); + Object[] obj = new Object[2]; + obj[0] = uid; + obj[1] = status; + Object res = userservice.call("K_add_release_status", obj); + if (res != null && res.toString().equalsIgnoreCase("true")) { + return true; + } + return false; + } + + public static boolean addReleaseStatusStd(TCSession session, String uid, String status) throws Exception { + TCUserService userservice = session.getUserService(); + Object[] obj = new Object[2]; + obj[0] = uid; + obj[1] = status; + Object res = userservice.call("connor_std_addreleasestatus", obj); + if (res != null && res.toString().equalsIgnoreCase("true")) { + return true; + } + return false; + } + + public static File chooseFile(Component parent) { + FileSystemView fsv = FileSystemView.getFileSystemView(); + String deskPath = fsv.getHomeDirectory().getPath(); + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setCurrentDirectory(new File(deskPath)); + fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); + FileNameExtensionFilter filter = new FileNameExtensionFilter("*.xlsx", "xlsx"); + fileChooser.setFileFilter(filter); + int state = fileChooser.showOpenDialog(parent); + if (state == 1) { + return null; + } + return fileChooser.getSelectedFile(); + } + + public static File chooseSaveFile(Component parent, String defaultFile, String ext) { + FileSystemView fsv = FileSystemView.getFileSystemView(); + String deskPath = fsv.getHomeDirectory().getPath(); + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setCurrentDirectory(new File(deskPath)); + fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); + if (!KUtil.isEmpty(ext)) { + FileNameExtensionFilter filter = new FileNameExtensionFilter("*." + ext, ext); + fileChooser.setFileFilter(filter); + } + fileChooser.setSelectedFile(new File(defaultFile)); + int state = fileChooser.showSaveDialog(parent); + if (state == 1) { + return null; + } + return fileChooser.getSelectedFile(); + } + + public static File getNewFile(File folder, String fileName, String ext) { + File file = new File(folder.getAbsolutePath() + "\\" + fileName + "." + ext); + int index = 1; + while (file.exists()) { + file = new File(folder.getAbsolutePath() + "\\" + fileName + "(" + (index++) + ")." + ext); + } + return file; + } + + public static String getDateStr(Date date, String format) { + String res = ""; + try { + SimpleDateFormat sdf = new SimpleDateFormat(format); + res = sdf.format(date); + } catch (Exception e) { + e.printStackTrace(); + } + return res; + } + + public static TCComponent[] query(TCSession session, String queryName, String[] keys, String[] vals) throws Exception { +// System.out.println("Query: " + queryName); +// System.out.println("keys = " + Arrays.toString(keys)); +// System.out.println("vals = " + Arrays.toString(vals)); + TCComponentQueryType queryType = (TCComponentQueryType) session.getTypeComponent("ImanQuery"); + TCComponentQuery query = (TCComponentQuery) queryType.find(queryName); + if (query == null) { + throw new TCException(String.format(REG.getString("querynotexist.ERROR1"), queryName)); + } + query.clearCache(); + query.refresh(); + return query.execute(keys, vals); + } + + public static TCComponentContextList combineContext(TCSession session, TCComponentQuery query, TCComponentContextList... contexts) throws Exception { + Class c = TCComponentContextList.class; + Field f1 = c.getDeclaredField("m_compUids"); + f1.setAccessible(true); + List compUids = new ArrayList<>(); + for (TCComponentContextList cc : contexts) { + String[] u1 = (String[]) f1.get(cc); + System.out.println(Arrays.toString(u1)); + compUids.addAll(Arrays.asList(u1)); + } + Constructor constructor = c.getDeclaredConstructor(TCComponentManager.class, TCComponent.class, String[].class, String[].class, String.class); + constructor.setAccessible(true); + TCComponentContextList res = (TCComponentContextList) constructor.newInstance(new TCComponentManager(session), query, compUids.toArray(new String[] {}), null, ""); + return res; + } + + public static int getLen(Object[] arr) { + return arr == null ? 0 : arr.length; + } + + public static String getValueInArray(String[] arr, int index) { + int len = arr == null ? 0 : arr.length; + if (index >= len) { + return ""; + } + return arr[index]; + } + + public static String getValueInArray(String arrStr, int index, String splitter) { + if (KUtil.isEmpty(arrStr)) { + return ""; + } + String[] split = arrStr.split(splitter, -1); + int len = getLen(split); + if (len > index && index >= 0) { + return split[index]; + } + return ""; + } + + public static String getTypeNames(TCSession session, Object[] types) { + int len = types == null ? 0 : types.length; + if (len == 0) { + return ""; + } + String[] names = new String[len]; + for (int i = 0; i < len; i++) { + try { + if ("TC_Project".equals(types[i].toString())) { + names[i] = REG.getString("project"); + } else { + names[i] = session.getTypeComponent(types[i].toString()).getDisplayTypeName(); + } + } catch (Exception e) { + e.printStackTrace(); + } + if (names[i] == null) { + names[i] = types[i].toString(); + } + } + return Arrays.toString(names); + } + + public static String getTypeName(TCSession session, String type) { + if (KUtil.isEmpty(type)) { + return ""; + } + try { + if ("TC_Project".equals(type)) { + return REG.getString("project"); + } else { + return session.getTypeComponent(type).getDisplayTypeName(); + } + } catch (Exception e) { + e.printStackTrace(); + } + return type; + } + + public static boolean isReleased(TCComponent comp) throws Exception { + TCComponent[] status = comp.getReferenceListProperty("release_status_list"); + if (status == null || status.length == 0) { + return false; + } + return true; + } + + public static TCComponentGroup getGroupByName(TCSession session, String str) throws Exception { + System.out.println("Search Group: " + str); + if (KUtil.isEmpty(str)) { + return null; + } + String queryName = "GroupByName"; + String[] keys = new String[] { KUtil.getText(session, "name") }; + String[] vals = new String[] { str }; + TCComponent[] res = KUtil.query(session, queryName, keys, vals); + int len = KUtil.getLen(res); + if (len == 0) { + return null; + } + if (len > 1) { + throw new TCException(String.format("Find Multipy Group By Name [%s]", str)); + } + return (TCComponentGroup) res[0]; + } + + public static TCComponentUser getUserFromStr(TCSession session, String str) throws Exception { + System.out.println("Search User: " + str); + if (KUtil.isEmpty(str)) { + return null; + } + int ind1 = str.lastIndexOf('('); + int ind2 = str.lastIndexOf(')'); + TCComponentUser user = null; + if (ind1 > 0 && ind2 > ind1) { + String userId = str.substring(ind1 + 1, ind2); + if (KUtil.isEmpty(userId)) { + System.out.println("No Id between '(' and ')'"); + user = null; + } else { + user = queryUserById(session, userId); + } + } else { + user = queryUserById(session, str); + if (user == null) { + user = queryUserByName(session, str); + } + } + return user; + } + + public static TCComponentUser queryUserById(TCSession session, String userId) throws Exception { + System.out.println("Search User By Id: " + userId); + if (KUtil.isEmpty(userId)) { + return null; + } + String queryName = "Admin - Employee Information"; + String[] keys = new String[] { KUtil.getText(session, "UserId") }; + String[] vals = new String[] { userId }; + TCComponent[] res = KUtil.query(session, queryName, keys, vals); + int len = KUtil.getLen(res); + if (len == 0) { + return null; + } + if (len > 1) { + throw new TCException(String.format(REG.getString("multiuserbyid.ERROR1"), userId)); + } + return (TCComponentUser) res[0]; + } + + public static TCComponentUser queryUserByName(TCSession session, String userName) throws Exception { + System.out.println("Search User By Name: " + userName); + if (KUtil.isEmpty(userName)) { + return null; + } + String queryName = "Admin - Employee Information"; + String[] keys = new String[] { KUtil.getText(session, "PersonName") }; + String[] vals = new String[] { userName }; + TCComponent[] res = KUtil.query(session, queryName, keys, vals); + int len = KUtil.getLen(res); + if (len == 0) { + return null; + } + if (len > 1) { + throw new TCException(String.format(REG.getString("multiuserbyname.ERROR1"), userName)); + } + return (TCComponentUser) res[0]; + } + + public static TCComponent[] getGroupMember(List privMembers) throws Exception { + if (privMembers == null) { + return null; + } + List res = new ArrayList<>(); + for (TCComponentUser user : privMembers) { + TCComponentGroupMember[] gms = user.getGroupMembers(); + int len = KUtil.getLen(gms); + for (int i = 0; i < len; i++) { + TCComponentGroupMember gm = gms[i]; + if (KUtil.isEmpty(gm.toString())) { + continue; + } + /* + * if(!gm.isActive()) { System.out.println("锟斤拷锟皆憋拷腔疃拷锟�"+gm); continue; } + */ + if (!res.contains(gm)) { + System.out.println("Add Group Member: " + gm); + res.add(gm); + } else { + System.out.println("Added: " + gm); + } + } + } + return res.toArray(new TCComponent[] {}); + } + + public static int compareWBS(String wbsCode, String wbsCode2) { + if (KUtil.isEmpty(wbsCode) && KUtil.isEmpty(wbsCode2)) { + return 0; + } + if (KUtil.isEmpty(wbsCode)) { + return -1; + } + if (KUtil.isEmpty(wbsCode2)) { + return 1; + } + String[] a = wbsCode.split("\\."); + String[] b = wbsCode2.split("\\."); + int lenA = a.length; + int lenB = b.length; + for (int i = 0; i < lenA && i < lenB; i++) { + String aa = a[i]; + String bb = b[i]; + int ai = 0; + int bi = 0; + try { + ai = Integer.parseInt(aa); + bi = Integer.parseInt(bb); + } catch (Exception e) { + e.printStackTrace(); + } + if (ai != bi) { + return ai - bi; + } + } + return lenA - lenB; + } + + public static TCComponentListOfValues getLov(TCSession session, String lovName) { + TCComponentListOfValuesType lovType; + try { + lovType = (TCComponentListOfValuesType) session.getTypeComponent("ListOfValues"); + TCComponentListOfValues[] lov = lovType.find(lovName); + if (lov.length > 0) + return lov[0]; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static String getLovValue(TCSession session, TCComponentListOfValues lov, String str) throws Exception { + return getLovValue(session, lov, str, true); + } + + public static String getLovValue(TCSession session, TCComponentListOfValues lov, String str, boolean translate) throws Exception { + if (lov == null || KUtil.isEmpty(str)) { + return str; + } + if (translate) { + String prefName = "LOV_TRANS_" + lov.getStringProperty(TCComponentListOfValues.PROP_LOV_NAME); + String[] prefVals = KUtil.getPrefVals(session, prefName); + int len = KUtil.getLen(prefVals); + for (int i = 0; i < len; i++) { + String pref = prefVals[i]; + int ind = pref.indexOf('='); + if (ind > 0) { + String realVal = pref.substring(0, ind); + String disVal = pref.substring(ind + 1); + if (str.equals(realVal) || str.equals(disVal)) { + return realVal; + } + } + } + } + ListOfValuesInfo info = lov.getListOfValues(); + if (info == null) { + return str; + } + List v = info.getValues(); + int size = v == null ? 0 : v.size(); + for (int i = 0; i < size; i++) { + LovValue vv = v.get(i); + String realValue = vv.getValue() == null ? "" : vv.getValue().toString(); + if (str.equals(realValue)) { + return str; + } + String disValue = vv.getDisplayValue(); + if (str.equals(disValue)) { + return realValue; + } + } + throw new TCException(String.format(REG.getString("valuenotinlov.ERROR2"), lov.toString(), str)); + } + + public static String getLovDisplayableValue(TCComponentListOfValues lov, String str) throws Exception { + if (lov == null || KUtil.isEmpty(str)) { + return str; + } + ListOfValuesInfo info = lov.getListOfValues(); + if (info == null) { + return str; + } + List v = info.getValues(); + int size = v == null ? 0 : v.size(); + for (int i = 0; i < size; i++) { + LovValue vv = v.get(i); + String realValue = vv.getValue() == null ? "" : vv.getValue().toString(); + if (str.equals(realValue)) { + return vv.getDisplayValue(); + } + String disValue = vv.getDisplayValue(); + if (str.equals(disValue)) { + return str; + } + } + throw new TCException(String.format(REG.getString("valuenotinlov.ERROR2"), lov.toString(), str)); + } + + public static void openFile(File file) { + try { + if (file != null && file.exists()) { + Runtime.getRuntime().exec("cmd /c start /b call \"" + file.getAbsolutePath() + "\""); + } + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(e); + } + } + + public static int runCommand(String command) throws Exception { + if (KUtil.isEmpty(command)) { + return -1; + } + Process p = Runtime.getRuntime().exec(command); + BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream(), Charset.forName("GBK"))); + String line; + while ((line = in.readLine()) != null) { + System.out.println(line); + } + return p.waitFor(); + } + + public static void writeToFile(File file, String encoding, String txt) throws Exception { + if (file == null || KUtil.isEmpty(encoding)) { + return; + } + Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), encoding)); + try { + out.write(txt); + out.flush(); + } finally { + out.close(); + } + } + + public static void importDataset(TCSession session, TCComponent parent, String rel, File f, String dsType, String refName) throws Exception { + if (f == null || !f.exists() || KUtil.isEmpty(dsType) || KUtil.isEmpty(refName)) { + return; + } + TCComponentDatasetType datasetType = (TCComponentDatasetType) session.getTypeComponent(dsType); + TCComponentDataset dataset = datasetType.create(f.getName(), "", dsType); + String paths[] = { f.getAbsolutePath() }; + String refs[] = { refName }; + dataset.setFiles(paths, refs); + if (parent != null && !KUtil.isEmpty(rel)) { + parent.add(rel, dataset); + } + } + + public static TCComponentItem createItemBySOA(TCSession session, TCComponentItemType itemType, Map itemPropMap, Map itemMasterPropMap, + Map revPropMap, Map revMasterPropMap) throws Exception { + String type = itemType.getName(); + TCComponentItemRevisionType revType = itemType.getItemRevisionType(); + String revTypeName = revType.getName(); + String itemMasterTypeName = type + " Master"; + String revMasterTypeName = revTypeName + " Master"; + if (session.getTypeComponent(itemMasterTypeName) == null) { + itemMasterTypeName = type + "Master"; + } + if (session.getTypeComponent(revMasterTypeName) == null) { + revMasterTypeName = revTypeName + "Master"; + } + CreateInput revMasterInput = new CreateInput(); + revMasterInput.boName = revMasterTypeName; + revMasterInput.stringProps = revMasterPropMap; + CreateInput itemMasterInput = new CreateInput(); + itemMasterInput.boName = itemMasterTypeName; + itemMasterInput.stringProps = itemMasterPropMap; + CreateInput revInput = new CreateInput(); + revInput.boName = revTypeName; + revInput.stringProps = revPropMap; + Map revMasterInfoMap = new HashMap<>(); + revMasterInfoMap.put("IMAN_master_form_rev", new CreateInput[] { revMasterInput }); + revInput.compoundCreateInput = revMasterInfoMap; + // create rev + CreateInput itemInput = new CreateInput(); + itemInput.boName = type; + itemInput.stringProps = itemPropMap; + Map revInfoMap = new HashMap<>(); + revInfoMap.put("revision", new CreateInput[] { revInput }); + revInfoMap.put("IMAN_master_form", new CreateInput[] { itemMasterInput }); + itemInput.compoundCreateInput = revInfoMap; + // create info + CreateIn cI = new CreateIn(); + cI.clientId = "CreateItem"; + cI.data = itemInput; + // service + DataManagementService service = DataManagementService.getService(session); + // create + CreateResponse resp = service.createObjects(new CreateIn[] { cI }); + SoaUtil.checkPartialErrors(resp.serviceData); + CreateOut[] cOs = resp.output; + TCComponentItem newItem = null; + if (cOs.length > 0) { + for (TCComponent s : cOs[0].objects) { + if (s instanceof TCComponentItem) { + newItem = (TCComponentItem) s; + } + } + } + return newItem; + } + + public static void initPropMap(String propConfig, String value, Map itemPropMap, Map itemMasterPropMap, Map revPropMap, + Map revMasterPropMap) throws Exception { + initPropMap(propConfig, value, itemPropMap, itemMasterPropMap, revPropMap, revMasterPropMap, null); + } + + public static void initPropMap(String propConfig, String value, Map itemPropMap, Map itemMasterPropMap, Map revPropMap, + Map revMasterPropMap, Map bomlinePropMap) throws Exception { + if (KUtil.isEmpty(propConfig)) { + return; + } + String propFrom = null, propName = null; + String[] split = propConfig.split("\\."); + if (KUtil.getLen(split) == 2) { + propFrom = split[0].trim().toUpperCase(); + propName = split[1].trim(); + } + if (KUtil.isEmpty(propFrom) || KUtil.isEmpty(propName)) { + return; + } + Map target; + if ("ITEM".equals(propFrom)) { + target = itemPropMap; + // System.out.println(">> ITEM PROP: " + propName + " = " + value); + } else if ("REV".equals(propFrom)) { + // System.out.println(">> REV PROP: " + propName + " = " + value); + target = revPropMap; + } else if ("ITEMMASTER".equals(propFrom)) { + // System.out.println(">> ITEMMASTER PROP: " + propName + " = " + value); + target = itemMasterPropMap; + } else if ("REVMASTER".equals(propFrom)) { + // System.out.println(">> REVMASTER PROP: " + propName + " = " + value); + target = revMasterPropMap; + } else if ("BOMLINE".equals(propFrom)) { + // System.out.println(">> BOMLINE PROP: " + propName + " = " + value); + target = bomlinePropMap; + } else { + throw new TCException(String.format(REG.getString("proplocationnotdefined.ERROR1"), propFrom)); + } + if (target == null) { + return; + } + target.put(propName, value); + } + + public static String getMarkedPropValue(String config, Map markedComponents) throws Exception { + if (markedComponents == null || KUtil.isEmpty(config)) { + return ""; + } + StringBuilder res = new StringBuilder(); + String[] propConfigSplit = config.split("\\+"); + int len = KUtil.getLen(propConfigSplit); + for (int i = 0; i < len; i++) { + String propConfig = propConfigSplit[i]; + Map replaceMap = null; // rev.object_desc:被替换值1=替换值1;被替换值2=替换值2 + { + int ind = propConfig.lastIndexOf(':'); + if (ind > 0) { + replaceMap = new HashMap(); + String replaceConfig = propConfig.substring(ind + 1); + propConfig = propConfig.substring(0, ind); + String[] split = replaceConfig.split(";"); + for (String string : split) { + ind = string.indexOf('='); + if (ind > 0) { + replaceMap.put(string.substring(0, ind), string.substring(ind + 1)); + } + } + } + } + String propFrom = null, propName = null; + String defaultValue = "";// rev.object_desc.默认值 + String childTypes = ""; // rev.IMAN_specification.childTypes.childPropName-splitter + // childTypes配置*或不配置取所有类型 + String childPropName = ""; + String childPropSpliter = ";"; + String[] split = propConfig.split("\\.", -1); + if (KUtil.getLen(split) >= 2) { + propFrom = split[0].trim().toUpperCase(); + propName = split[1].trim(); + } + if (KUtil.getLen(split) >= 3) { + defaultValue = split[2].trim(); + childTypes = defaultValue; + } + if (KUtil.getLen(split) >= 4) { + childPropName = split[3].trim(); + int ind = childPropName.lastIndexOf('-'); + if (ind > 0) { + childPropSpliter = childPropName.substring(ind + 1); + childPropName = childPropName.substring(0, ind); + } + } + if (KUtil.isEmpty(propFrom) || KUtil.isEmpty(propName)) { + if (propConfig.contains("\\n")) { + propConfig = propConfig.replace("\\n", "\n"); + } + res.append(propConfig); + continue; + } + if (!markedComponents.containsKey(propFrom)) { + if (propFrom.startsWith("T")) { + return ""; + } + // loadSpecialLocations(propFrom, propName, res, markedComponents, + // relatedComponents); + continue; + } + TCComponent comp = markedComponents.get(propFrom); + // 检查表格属性 属性位置.表格属性名称-表格行属性名称[-连接符] + int ind = propName.indexOf('-'); + if (ind > 0) { + String tableProp = propName.substring(0, ind).trim(); + String tableRowProp = propName.substring(ind + 1).trim(); + if (!KUtil.isEmpty(tableProp) && !KUtil.isEmpty(tableRowProp)) { + TCProperty prop = comp.getTCProperty(tableProp.trim()); + if (prop == null) { + throw new TCException(String.format(REG.getString("propnotdefinedintype.ERROR2"), comp.getType(), propName)); + } + String rowSplitter = "#ROW#"; + ind = tableRowProp.indexOf('-'); + if (ind > 0) { + rowSplitter = tableRowProp.substring(ind + 1); + tableRowProp = tableRowProp.substring(0, ind); + } + TCComponent[] tableRows = prop.getReferenceValueArray(); + int rowCnt = KUtil.getLen(tableRows); + String[] value = new String[rowCnt]; + for (int j = 0; j < rowCnt; j++) { + value[j] = tableRows[j].getPropertyDisplayableValue(tableRowProp); + } + res.append(String.join(rowSplitter, value)); + } + continue; + } + TCProperty prop = comp.getTCProperty(propName.trim()); + if (prop == null) { + throw new TCException(String.format(REG.getString("propnotdefinedintype.ERROR2"), comp.getType(), propName)); + } + if (prop.isReferenceType() && !KUtil.isEmpty(childPropName)) { + TCComponent[] arr = prop.getReferenceValueArray(); + int childCnt = KUtil.getLen(arr); + boolean addSplitter = false; + for (int j = 0; j < childCnt; j++) { + TCComponent child = arr[j]; + String[] childTypeArr = childTypes.split(";"); + if (childTypes.length() < 2 || KUtil.inArray(child.getType(), childTypeArr) >= 0) { + if (addSplitter) { + res.append(childPropSpliter); + } + String propValue = child.getPropertyDisplayableValue(childPropName); + if (propValue != null && replaceMap != null && replaceMap.containsKey(propValue)) { + propValue = replaceMap.get(propValue); + } + res.append(propValue); + addSplitter = true; + } + } + } else { + String value = prop.getDisplayableValue(); + if ("NAME".equalsIgnoreCase(defaultValue)) { + value = prop.getPropertyDisplayName(); + } else if (value == null || "".equals(value)) { + value = defaultValue; + } + if (value != null && replaceMap != null && replaceMap.containsKey(value)) { + value = replaceMap.get(value); + } + res.append(value); + } + } + return res.toString(); + } + + public static TCComponent getLatestComponent(List comps) { + int size = comps == null ? 0 : comps.size(); + if (size == 0) { + return null; + } + if (size == 1) { + return comps.get(0); + } + TCComponent res = comps.get(0); + try { + Date maxDate = res.getDateProperty("creation_date"); + for (int i = 1; i < size; i++) { + TCComponent temp = comps.get(i); + Date tempDate = temp.getDateProperty("creation_date"); + if (tempDate.after(maxDate)) { + maxDate = tempDate; + res = temp; + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return res; + } + + public static TCComponentType[] getComponentTypes(TCSession session, String itemTypeName) throws Exception { + TCComponentItemType itemType = null; + try { + itemType = (TCComponentItemType) session.getTypeComponent(itemTypeName); + } catch (Exception e) { + e.printStackTrace(); + } + if (itemType == null) { + throw new TCException(String.format(REG.getString("typenotfound.ERROR1"), itemTypeName)); + } + TCComponentItemRevisionType revType = itemType.getItemRevisionType(); + if (revType == null) { + throw new TCException(String.format(REG.getString("typenotfound.ERROR1"), itemTypeName + "Revision")); + } + TCComponentType itemMasterType = null; + try { + itemMasterType = session.getTypeComponent(itemTypeName + "Master"); + } catch (Exception e) { + e.printStackTrace(); + } + if (itemMasterType == null) { + try { + itemMasterType = session.getTypeComponent(itemTypeName + " Master"); + } catch (Exception e) { + e.printStackTrace(); + } + } + if (itemMasterType == null) { + throw new TCException(String.format(REG.getString("typenotfound.ERROR1"), itemTypeName + "Master")); + } + TCComponentType revMasterType = null; + try { + revMasterType = session.getTypeComponent(revType.getTypeName() + "Master"); + } catch (Exception e) { + e.printStackTrace(); + } + if (revMasterType == null) { + try { + revMasterType = session.getTypeComponent(revType.getTypeName() + " Master"); + } catch (Exception e) { + e.printStackTrace(); + } + } + if (revMasterType == null) { + throw new TCException(String.format(REG.getString("typenotfound.ERROR1"), revType.getTypeName() + "Master")); + } + return new TCComponentType[] { itemType, revType, itemMasterType, revMasterType }; + } + + public static String getPropertyDisplayName(TCComponentType type, String propName) throws Exception { + if (type == null || KUtil.isEmpty(propName)) { + return propName; + } + TCPropertyDescriptor desc = type.getPropDesc(propName); + if (desc == null) { + throw new TCException(String.format(REG.getString("propnotdefinedintype.ERROR2"), type.getDisplayTypeName(), propName)); + } + return desc.getDisplayName(); + } + + public static String getConfigPropValue(TCComponentItemRevision rev, String propConfigStr) throws Exception { + if (rev == null || KUtil.isEmpty(propConfigStr)) { + return ""; + } + StringBuilder res = new StringBuilder(); + String[] propConfigSplit = propConfigStr.split("\\+"); + int len = KUtil.getLen(propConfigSplit); + for (int i = 0; i < len; i++) { + String propConfig = propConfigSplit[i]; + String propFrom = null, propName = null; + String[] split = propConfig.split("\\."); + if (KUtil.getLen(split) == 2) { + propFrom = split[0].trim().toUpperCase(); + propName = split[1].trim(); + } + if (KUtil.isEmpty(propFrom) || KUtil.isEmpty(propName)) { + res.append(propConfig); + continue; + } + TCComponent target; + if ("ITEM".equals(propFrom)) { + target = rev.getItem(); + } else if ("REV".equals(propFrom)) { + target = rev; + } else if ("ITEMMASTER".equals(propFrom)) { + target = rev.getItem().getRelatedComponent("IMAN_master_form"); + } else if ("REVMASTER".equals(propFrom)) { + target = rev.getRelatedComponent("IMAN_master_form_rev"); + } else { + throw new TCException(String.format(REG.getString("proplocationnotdefined.ERROR1"), propFrom)); + } + TCProperty prop = target.getTCProperty(propName.trim()); + if (prop == null) { + throw new TCException(String.format(REG.getString("propnotdefinedintype.ERROR2"), target.getType(), propName)); + } + res.append(prop.getStringValue()); + } + return res.toString(); + } + + public static String getConfigPropDisplayableValue(TCComponentItemRevision rev, String propConfigStr) throws Exception { + if (rev == null || KUtil.isEmpty(propConfigStr)) { + return ""; + } + StringBuilder res = new StringBuilder(); + String[] propConfigSplit = propConfigStr.split("\\+"); + int len = KUtil.getLen(propConfigSplit); + for (int i = 0; i < len; i++) { + String propConfig = propConfigSplit[i]; + String propFrom = null, propName = null; + String[] split = propConfig.split("\\."); + if (KUtil.getLen(split) == 2) { + propFrom = split[0].trim().toUpperCase(); + propName = split[1].trim(); + } + if (KUtil.isEmpty(propFrom) || KUtil.isEmpty(propName)) { + res.append(propConfig); + continue; + } + TCComponent target; + if ("ITEM".equals(propFrom)) { + target = rev.getItem(); + } else if ("REV".equals(propFrom)) { + target = rev; + } else if ("ITEMMASTER".equals(propFrom)) { + target = rev.getItem().getRelatedComponent("IMAN_master_form"); + } else if ("REVMASTER".equals(propFrom)) { + target = rev.getRelatedComponent("IMAN_master_form_rev"); + } else { + throw new TCException(String.format(REG.getString("proplocationnotdefined.ERROR1"), propFrom)); + } + TCProperty prop = target.getTCProperty(propName.trim()); + if (prop == null) { + throw new TCException(String.format(REG.getString("propnotdefinedintype.ERROR2"), target.getType(), propName)); + } + res.append(prop.getDisplayableValue()); + } + return res.toString(); + } + + public static void removeAllParents(DataManagementService dm, TCComponent comp) throws Exception { + comp.refresh(); + System.out.println("Remove from parent: " + comp); + WhereReferencedResponse refResp = dm.whereReferenced(new TCComponent[] { comp }, 1); + SoaUtil.checkPartialErrors(refResp.serviceData); + int len = KUtil.getLen(refResp.output); + List datas = new ArrayList(); + for (int i = 0; i < len; i++) { + WhereReferencedOutput ref = refResp.output[i]; + int cnt = KUtil.getLen(ref.info); + for (int j = 0; j < cnt; j++) { + WhereReferencedInfo info = ref.info[j]; + Relationship data = new Relationship(); + data.primaryObject = info.referencer; + data.secondaryObject = comp; + data.relationType = info.relation; + System.out.println(">> " + info.relation + " | " + info.referencer); + datas.add(data); + } + } + ServiceData resp = dm.deleteRelations(datas.toArray(new Relationship[] {})); + SoaUtil.checkPartialErrors(resp); + } + + public static TCComponent newTableRow(DataManagementService dmService, String type, Map rowStringProps, Map rowDateProps) throws Exception { + CreateIn rowIn = new CreateIn(); + CreateInput rowInput = new CreateInput(); + rowInput.boName = type; + if (rowStringProps != null) { + rowInput.stringProps = rowStringProps; + } + if (rowDateProps != null) { + rowInput.dateProps = rowDateProps; + } + rowIn.data = rowInput; + CreateResponse res = dmService.createObjects(new CreateIn[] { rowIn }); + SoaUtil.checkPartialErrors(res.serviceData); + if (res.serviceData.sizeOfCreatedObjects() > 0) { + return res.serviceData.getCreatedObject(0); + } + return null; + } + + public static void openUrl(String url) throws Exception { + System.out.println("Open Url: " + url); + if (KUtil.isEmpty(url)) { + return; + } + if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) { + Desktop.getDesktop().browse(new URI(url)); + } + } + + public static Date addDay(Date day, int cnt) { + if (day == null) { + return null; + } + Calendar c = Calendar.getInstance(); + c.setTime(day); + c.add(Calendar.DATE, cnt); + return c.getTime(); + } + + public static TCComponentListOfValues getLovFromProp(TCComponentType type, String propName) throws Exception { + if (type == null || KUtil.isEmpty(propName)) { + return null; + } + TCPropertyDescriptor propDesc = type.getPropDesc(propName); + if (propDesc == null) { + throw new TCException(String.format(REG.getString("propnotdefinedintype.ERROR2"), type.getType(), propName)); + } + return propDesc.getLOV(); + } + + public static SimpleDateFormat PROP_DATE_FORMAT = new SimpleDateFormat("yyyy/MM/dd HH:mm"); + + public static String getSinglePropValueByPath(TCComponent comp, String propPath, String splitter) throws Exception { + return getSinglePropValueByPath(comp, propPath, splitter, null); + } + + public static String getSinglePropValueByPath(TCComponent comp, String propPath, String splitter, SimpleDateFormat dateFormat) throws Exception { + if (comp == null || propPath == null) { + return ""; + } + if (dateFormat == null) { + dateFormat = PROP_DATE_FORMAT; + } + // uid + if (propPath.equalsIgnoreCase("uid")) { + return comp.getUid(); + } + // current time + if (propPath.startsWith("#NOW#")) { + return new SimpleDateFormat(propPath.substring(6)).format(new Date()); + } + if (propPath.trim().equals(".")) { + return propPath; + } + String propName = propPath; + String subPropName = null; + int ind = propPath.indexOf('.'); + if (ind > 0) { + propName = propPath.substring(0, ind); + subPropName = propPath.substring(ind + 1); + } + int filterTypeInd = propName.indexOf('@'); + String[] filterTypes = null; + boolean isExcludeType = false; + String propDateFormat = null; + if (filterTypeInd > 0) { + propDateFormat = propName.substring(filterTypeInd + 1); + String filterTypeStr = propName.substring(filterTypeInd + 1); + propName = propName.substring(0, filterTypeInd); + isExcludeType = filterTypeStr.startsWith("!"); + if (isExcludeType) { + filterTypeStr = filterTypeStr.substring(1); + } + filterTypes = filterTypeStr.split(","); + if (KUtil.getLen(filterTypes) == 0) { + filterTypes = null; + } + } + // where referenced + if (!KUtil.isEmpty(subPropName) && propName.startsWith("#")) { + propName = propName.substring(1); + AIFComponentContext[] parents = comp.whereReferencedByTypeRelation(filterTypes, new String[] { propName }); + int len = KUtil.getLen(parents); + boolean addSplitter = false; + String res = ""; + for (int i = 0; i < len; i++) { + TCComponent parent = (TCComponent) parents[i].getComponent(); + if (addSplitter) { + res += splitter; + } + addSplitter = true; + res += getSinglePropValueByPath(parent, subPropName, splitter, dateFormat); + } + return res; + } + // display value + if (propName.startsWith("#")) { + propName = propName.substring(1); + TCProperty prop = comp.getTCProperty(propName); + if (prop == null) { + return propPath; + } + return prop.getDisplayableValue(); + } + // latest revision + if (propName.equalsIgnoreCase("latest_item_revision") && (comp instanceof TCComponentItemRevision)) { + TCComponentItemRevision child = ((TCComponentItem) comp).getLatestItemRevision(); + if (KUtil.isEmpty(subPropName)) { + return child.toString(); + } else { + return getSinglePropValueByPath(child, subPropName, splitter, dateFormat); + } + } + // bom + if (propName.equalsIgnoreCase("bom") && (comp instanceof TCComponentBOMLine)) { + AIFComponentContext[] cc = comp.getChildren(); + int childCnt = KUtil.getLen(cc); + boolean addSplitter = false; + String res = ""; + for (int i = 0; i < childCnt; i++) { + TCComponentBOMLine cLine = (TCComponentBOMLine) cc[i].getComponent(); + if (filterTypes != null && !isValidType(cLine.getStringProperty("bl_rev_object_type"), isExcludeType, filterTypes)) { + continue; + } + if (addSplitter) { + res += splitter; + } + addSplitter = true; + res += getSinglePropValueByPath(cLine, subPropName, splitter, dateFormat); + } + return res; + } + // bom parent + if (propName.equalsIgnoreCase("parent") && (comp instanceof TCComponentBOMLine)) { + TCComponentBOMLine parentLine = ((TCComponentBOMLine) comp).parent(); + return getSinglePropValueByPath(parentLine, subPropName, splitter, dateFormat); + } + // normal + TCProperty prop = comp.getTCProperty(propName); + if (prop == null) { + return propPath; + } + String propValue = getTCPropertyValue(prop, subPropName, filterTypes, isExcludeType, splitter, propDateFormat, dateFormat); + if (propValue == null) { + propValue = ""; + } + // replace config + Map replaceMap = arrayToMap(filterTypes, "="); + if (replaceMap != null && replaceMap.size() > 0) { + if (replaceMap.containsKey(propValue)) { + String newValue = replaceMap.get(propValue); + System.out.println(String.format("Replace Value “%s” [%s] -> [%s]", comp.toString(), propValue, newValue)); + propValue = newValue; + } else if (replaceMap.containsKey("*") && !KUtil.isEmpty(propValue)) { + String newValue = replaceMap.get("*"); + System.out.println(String.format("Replace NonEmpty Value “%s” [%s] -> [%s]", comp.toString(), propValue, newValue)); + propValue = newValue; + } else if (replaceMap.containsKey("") && KUtil.isEmpty(propValue)) { + String newValue = replaceMap.get(""); + System.out.println(String.format("Replace Empty Value “%s” [%s] -> [%s]", comp.toString(), propValue, newValue)); + propValue = newValue; + } + } + return propValue; + } + + public static Map arrayToMap(String[] arr, String splitter) throws Exception { + int len = KUtil.getLen(arr); + if (len == 0 || splitter == null || splitter.length() == 0) { + return null; + } + Map res = new LinkedHashMap<>(); + for (int i = 0; i < len; i++) { + String str = arr[i]; + if (str == null) { + continue; + } + int ind = str.indexOf(splitter); + if (ind < 0) { + continue; + } + res.put(str.substring(0, ind), str.substring(ind + splitter.length())); + } + return res; + } + + public static final String getTCPropertyValue(TCProperty prop, String subPropName, String[] filterTypes, boolean isExcludeType, String splitter, String propDateFormat, SimpleDateFormat dateFormat) + throws Exception { + if (prop.isReferenceType()) { + if (prop.isNotArray()) { + TCComponent child = prop.getReferenceValue(); + if (child == null) { + return ""; + } + if (filterTypes != null && !isValidType(child.getType(), isExcludeType, filterTypes)) { + return ""; + } + if (KUtil.isEmpty(subPropName)) { + return child.toString(); + } else { + return getSinglePropValueByPath(child, subPropName, splitter, dateFormat); + } + } else { + TCComponent[] children = prop.getReferenceValueArray(); + int len = KUtil.getLen(children); + if (len == 0) { + return ""; + } + if (KUtil.isEmpty(subPropName)) { + subPropName = "object_string"; + } + String res = ""; + boolean addSplitter = false; + for (int i = 0; i < len; i++) { + if (filterTypes != null && !isValidType(children[i].getType(), isExcludeType, filterTypes)) { + continue; + } + if (addSplitter) { + res += splitter; + } + addSplitter = true; + res += getSinglePropValueByPath(children[i], subPropName, splitter, dateFormat); + } + return res; + } + } else { + if (prop.isNotArray()) { + switch (prop.getPropertyType()) { + case TCProperty.PROP_string: + case TCProperty.PROP_long_string: + return prop.getStringValue(); + case TCProperty.PROP_date: + Date date = prop.getDateValue(); + if (date == null) { + return ""; + } + if (!KUtil.isEmpty(propDateFormat)) { + return getDateStr(date, propDateFormat); + } + return dateFormat.format(date); + default: + return prop.getDisplayableValue(); + } + } else { + switch (prop.getPropertyType()) { + case TCProperty.PROP_string: + case TCProperty.PROP_long_string: + return String.join(splitter, prop.getStringValueArray()); + default: + return String.join(splitter, prop.getDisplayableValues()); + } + } + } + } + + /** + * + * @param comp + * @param propPath + * child_relation[@type1,type2].#parent_relation[@type3,type4] + * @param filterProps + * propPath=propValue|*|null|regex + * @param res + * @throws Exception + */ + public static void getSingleChildrenByPath(TCComponent comp, String propPath, Map filterProps, List res) throws Exception { + if (comp == null) { + return; + } + if (KUtil.isEmpty(propPath)) { + if (filterProps != null) { + for (String propName : filterProps.keySet()) { + String filterValue = filterProps.get(propName); + String propValue = KUtil.getPropValueByPath(comp, propName, ";"); + if ("*".equals(filterValue)) { + if (KUtil.isEmpty(propValue)) { + return; + } + } else if ("null".equalsIgnoreCase(filterValue)) { + if (!KUtil.isEmpty(propValue)) { + return; + } + } else if (!propValue.matches(filterValue)) { + return; + } + } + } + res.add(comp); + return; + } + if (propPath.trim().equals(".")) { + return; + } + String propName = propPath; + String subPropName = null; + int ind = propPath.indexOf('.'); + if (ind > 0) { + propName = propPath.substring(0, ind); + subPropName = propPath.substring(ind + 1); + } + // normal + int filterTypeInd = propName.indexOf('@'); + String[] filterTypes = null; + boolean isExcludeType = false; + if (filterTypeInd > 0) { + String filterTypeStr = propName.substring(filterTypeInd + 1); + propName = propName.substring(0, filterTypeInd); + isExcludeType = filterTypeStr.startsWith("!"); + if (isExcludeType) { + filterTypeStr = filterTypeStr.substring(1); + } + filterTypes = filterTypeStr.split(","); + if (KUtil.getLen(filterTypes) == 0) { + filterTypes = null; + } + } + // latest revision + if (propName.equalsIgnoreCase("latest_item_revision") && (comp instanceof TCComponentItem)) { + TCComponentItemRevision child = ((TCComponentItem) comp).getLatestItemRevision(); + getSingleChildrenByPath(child, subPropName, filterProps, res); + return; + } + // bom + if (propName.equalsIgnoreCase("bom") && (comp instanceof TCComponentBOMLine)) { + AIFComponentContext[] cc = comp.getChildren(); + int childCnt = KUtil.getLen(cc); + for (int i = 0; i < childCnt; i++) { + TCComponentBOMLine cLine = (TCComponentBOMLine) cc[i].getComponent(); + if (filterTypes != null && !isValidType(cLine.getStringProperty("bl_rev_object_type"), isExcludeType, filterTypes)) { + continue; + } + getSingleChildrenByPath(cLine, subPropName, filterProps, res); + } + return; + } + // bom parent + if (propName.equalsIgnoreCase("parent") && (comp instanceof TCComponentBOMLine)) { + TCComponentBOMLine parentLine = ((TCComponentBOMLine) comp).parent(); + getSingleChildrenByPath(parentLine, subPropName, filterProps, res); + return; + } + // meactivity + if (propName.equalsIgnoreCase("meactivity") && (comp instanceof TCComponentBOMLine)) { + TCComponentCfgActivityLine actLine = (TCComponentCfgActivityLine) comp.getReferenceProperty("bl_me_activity_lines"); + if (actLine != null) { + TCComponent[] cc = ActivityUtils.getSortedActivityChildren(actLine); + int childCnt = KUtil.getLen(cc); + for (int i = 0; i < childCnt; i++) { + if (filterTypes != null && !isValidType(cc[i].getStringProperty("me_cl_object_type"), isExcludeType, filterTypes)) { + continue; + } + getSingleChildrenByPath(cc[i], subPropName, filterProps, res); // al_object + } + } + return; + } + // workflow task + if (propName.equalsIgnoreCase("workflow") && KUtil.getLen(filterTypes) == 2) { + List tasks = getWorkflowTaskByName(comp, filterTypes[0], filterTypes[1]); + int len = tasks == null ? 0 : tasks.size(); + for (int i = 0; i < len; i++) { + TCComponent task = tasks.get(i); + getSingleChildrenByPath(task, subPropName, filterProps, res); + } + return; + } + // where referenced + if (propName.startsWith("#")) { + propName = propName.substring(1); + AIFComponentContext[] parents = comp.whereReferencedByTypeRelation(filterTypes, new String[] { propName }); + int len = KUtil.getLen(parents); + for (int i = 0; i < len; i++) { + TCComponent parent = (TCComponent) parents[i].getComponent(); + getSingleChildrenByPath(parent, subPropName, filterProps, res); + } + return; + } + TCProperty prop = comp.getTCProperty(propName); + if (prop == null) { + return; + } + if (prop.isReferenceType()) { + if (prop.isNotArray()) { + TCComponent child = prop.getReferenceValue(); + if (child == null) { + return; + } + if (filterTypes != null && !isValidType(child.getType(), isExcludeType, filterTypes)) { + return; + } + getSingleChildrenByPath(child, subPropName, filterProps, res); + return; + } else { + TCComponent[] children = prop.getReferenceValueArray(); + int len = KUtil.getLen(children); + if (len == 0) { + return; + } + for (int i = 0; i < len; i++) { + if (filterTypes != null && !isValidType(children[i].getType(), isExcludeType, filterTypes)) { + continue; + } + getSingleChildrenByPath(children[i], subPropName, filterProps, res); + } + return; + } + } + } + + private static boolean isValidType(String typeName, boolean isExcludeType, String[] filterTypes) { + if (isExcludeType) { + if (KUtil.inArray(typeName, filterTypes) >= 0) { + return false; + } + } else { + if (KUtil.inArray(typeName, filterTypes) < 0) { + return false; + } + } + return true; + } + + public static void getChildrenByPath(TCComponent comp, String propPath, Map filterProps, List res) throws Exception { + if (comp == null || propPath == null) { + return; + } + String[] propPathSplit = propPath.split("\\+"); + int len = KUtil.getLen(propPathSplit); + for (int i = 0; i < len; i++) { + String singlePropPath = propPathSplit[i]; + getSingleChildrenByPath(comp, singlePropPath, filterProps, res); + } + } + + public static String getPropValueByPath(TCComponent comp, String propPath, String splitter) throws Exception { + return getPropValueByPath(comp, propPath, splitter, null); + } + + public static String getPropValueByPath(TCComponent comp, String propPath, String splitter, SimpleDateFormat dateFormat) throws Exception { + if (comp == null || propPath == null) { + return ""; + } + StringBuilder res = new StringBuilder(); + String[] propPathSplit = propPath.split("\\+"); + int len = KUtil.getLen(propPathSplit); + for (int i = 0; i < len; i++) { + String singlePropPath = propPathSplit[i]; + res.append(getSinglePropValueByPath(comp, singlePropPath, splitter, dateFormat)); + } + return res.toString(); + } + + public static List getWorkflowTaskByName(TCComponent comp, String workflowName, String nodeName) throws Exception { + if (comp == null || KUtil.isEmpty(workflowName) || KUtil.isEmpty(nodeName)) { + return null; + } + List tasks = new ArrayList<>(); + System.out.println("Read workflow [" + comp + "] -> " + workflowName + "." + nodeName); + TCComponent[] workflows = comp.getReferenceListProperty("fnd0AllWorkflows"); + System.out.println(">> workflows: " + Arrays.toString(workflows)); + int len = KUtil.getLen(workflows); + for (int i = 0; i < len; i++) { + TCComponent workflow = workflows[i]; + if (!workflowName.equals(workflow.getStringProperty("object_name"))) { + continue; + } + TCComponent[] cc = workflow.getReferenceListProperty("child_tasks"); + System.out.println(" >> " + workflow + " -> " + Arrays.toString(cc)); + int childCnt = KUtil.getLen(cc); + for (int j = 0; j < childCnt; j++) { + TCComponent childTask = cc[j]; + if (!nodeName.equals(childTask.getStringProperty("object_name"))) { + continue; + } + tasks.add(childTask); + } + } + return tasks; + } + + public static File createTempDir() throws Exception { + File tempDir = new File(System.getenv("TEMP") + File.separator + UUID.randomUUID()); + if (!tempDir.isDirectory()) { + if (!tempDir.mkdirs()) { + throw new Exception("Create temp directory failed: \n" + tempDir.getAbsolutePath()); + } + } + return tempDir; + } + + public static void setProperties(TCComponent comp, Map props) throws Exception { + if (comp == null || props == null || props.size() == 0) { + return; + } + comp.lock(); + try { + comp.setProperties(props); + comp.save(); + } finally { + comp.unlock(); + } + } + +} diff --git a/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/KXmlUtil.java b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/KXmlUtil.java new file mode 100644 index 0000000..9199f1c --- /dev/null +++ b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/KXmlUtil.java @@ -0,0 +1,88 @@ +package cn.net.connor.std.aifrcp.util; + +import java.io.File; +import java.io.FileInputStream; +import java.util.ArrayList; +import java.util.List; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.w3c.dom.ls.DOMImplementationLS; +import org.w3c.dom.ls.LSSerializer; + +public class KXmlUtil { + + public static Document getDoc(File file) throws Exception { + if (file == null) { + return null; + } + DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = dbFactory.newDocumentBuilder(); + FileInputStream in = new FileInputStream(file); + Document doc = builder.parse(in); + in.close(); + return doc; + } + + public static Element getRoot(Document doc) throws Exception { + if(doc==null) { + return null; + } + return doc.getDocumentElement(); + } + + public static Element getChildNode(Element node, String nodeName) throws Exception { + if(node==null||KUtil.isEmpty(nodeName)) { + return null; + } + NodeList cc = node.getElementsByTagName(nodeName); + int cnt = cc == null ? 0 : cc.getLength(); + for (int i = 0; i < cnt; i++) { + Node child = cc.item(i); + if (child.getNodeType() == Node.ELEMENT_NODE) { + return (Element) child; + } + } + return null; + } + + public static List getChildNodes(Element node, String nodeName) throws Exception { + List res = new ArrayList<>(); + if(node==null||KUtil.isEmpty(nodeName)) { + return res; + } + NodeList cc = node.getElementsByTagName(nodeName); + int cnt = cc == null ? 0 : cc.getLength(); + for (int i = 0; i < cnt; i++) { + Node child = cc.item(i); + if (child.getNodeType() == Node.ELEMENT_NODE) { + res.add((Element) child); + } + } + return res; + } + + public static String getAttribute(Element node, String attrName) throws Exception{ + return node.getAttribute(attrName); + } + + public static String getNodeText(Element node) throws Exception{ + return node.getTextContent(); + } + + public static String nodeToString(Element node) throws Exception{ + if(node==null) { + return null; + } + Document document = node.getOwnerDocument(); + DOMImplementationLS domImplLS = (DOMImplementationLS) document + .getImplementation(); + LSSerializer serializer = domImplLS.createLSSerializer(); + return serializer.writeToString(node); + } +} diff --git a/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/POIUtil.java b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/POIUtil.java new file mode 100644 index 0000000..731c6a7 --- /dev/null +++ b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/POIUtil.java @@ -0,0 +1,900 @@ +package cn.net.connor.std.aifrcp.util; + +import java.awt.Color; +import java.awt.Point; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.text.DecimalFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.apache.poi.POIXMLDocumentPart; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.ClientAnchor; +import org.apache.poi.ss.usermodel.DateUtil; +import org.apache.poi.ss.usermodel.HorizontalAlignment; +import org.apache.poi.ss.usermodel.IndexedColors; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.VerticalAlignment; +import org.apache.poi.ss.util.AreaReference; +import org.apache.poi.ss.util.CellRangeAddress; +import org.apache.poi.ss.util.CellReference; +import org.apache.poi.xssf.usermodel.XSSFCell; +import org.apache.poi.xssf.usermodel.XSSFCellStyle; +import org.apache.poi.xssf.usermodel.XSSFColor; +import org.apache.poi.xssf.usermodel.XSSFDrawing; +import org.apache.poi.xssf.usermodel.XSSFFont; +import org.apache.poi.xssf.usermodel.XSSFName; +import org.apache.poi.xssf.usermodel.XSSFPicture; +import org.apache.poi.xssf.usermodel.XSSFRow; +import org.apache.poi.xssf.usermodel.XSSFShape; +import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder.BorderSide; + +public class POIUtil { + + public static XSSFColor GRAY = new XSSFColor(new Color(217, 217, 217)); + public static XSSFColor YELLOW = new XSSFColor(new Color(255, 255, 204)); + public static XSSFColor BLUE = new XSSFColor(new Color(0, 0, 255)); + public static XSSFColor GREEN = new XSSFColor(new Color(158, 234, 106)); + + public static void setValue(XSSFSheet sheet, int rowId, int col, String val) { + setValue(sheet, rowId, col, val, null); + } + + public static int getTitleRow(XSSFSheet sheet, int startRow, String[] titleData) { + if (sheet == null || KUtil.getLen(titleData) == 0) { + return -1; + } + int lastRow = sheet.getLastRowNum(); + for (int i = startRow; i <= lastRow; i++) { + LinkedHashMap data = POIUtil.readRow(null, sheet, i, false); + if (data == null) { + continue; + } + boolean match = true; + for (String title : titleData) { + if (!data.containsValue(title)) { + match = false; + break; + } + } + if (match) { + return i; + } + } + return -1; + } + + public static XSSFCellStyle getMergeCellStyle(XSSFWorkbook wb, XSSFColor bgColor, XSSFColor fontColor, String fontFamily, short fontSize, boolean bold, boolean top, boolean right, boolean bottom, + boolean left, HorizontalAlignment ha) { + XSSFCellStyle style = wb.createCellStyle(); + style.setBorderBottom(bottom ? CellStyle.BORDER_MEDIUM : CellStyle.BORDER_THIN); + style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); + style.setBorderLeft(left ? CellStyle.BORDER_MEDIUM : CellStyle.BORDER_THIN); + style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); + style.setBorderRight(right ? CellStyle.BORDER_MEDIUM : CellStyle.BORDER_THIN); + style.setRightBorderColor(IndexedColors.BLACK.getIndex()); + style.setBorderTop(top ? CellStyle.BORDER_MEDIUM : CellStyle.BORDER_THIN); + style.setTopBorderColor(IndexedColors.BLACK.getIndex()); + style.setAlignment(ha); + style.setVerticalAlignment(VerticalAlignment.CENTER); + if (bgColor != null) { + style.setFillForegroundColor(bgColor); + style.setFillPattern(CellStyle.SOLID_FOREGROUND); + } + XSSFFont font = wb.createFont(); + if (fontColor != null) { + font.setColor(fontColor); + } + if (!KUtil.isEmpty(fontFamily)) { + font.setFontName(fontFamily);// (FontFamily.valueOf(fontFamily)); + } + if (fontSize > 0) { + font.setFontHeightInPoints(fontSize); + } + font.setBold(bold); + style.setFont(font); + + return style; + } + + public static CellRangeAddress CellRangeAddress(XSSFWorkbook wb, XSSFSheet sheet, int a, int b, int c, int d, XSSFColor bgColor, XSSFColor fontColor, String fontFamily, short fontSize, + boolean bold, boolean top, boolean right, boolean bottom, boolean left, HorizontalAlignment ha) { + CellRangeAddress res = new CellRangeAddress(a, b, c, d); + XSSFCellStyle style = getMergeCellStyle(wb, bgColor, fontColor, fontFamily, fontSize, bold, top, right, bottom, left, ha); + for (int rowId = a; rowId <= b; rowId++) { + XSSFRow row = sheet.getRow(rowId); + if (row == null) { + continue; + } + for (int colId = c; colId <= d; colId++) { + XSSFCell cell = row.getCell(colId); + if (cell == null) { + cell = row.createCell(colId); + } + cell.setCellStyle(style); + } + } + return res; + } + + public static CellRangeAddress CellRangeAddress(XSSFWorkbook wb, XSSFSheet sheet, int a, int b, int c, int d, XSSFCellStyle style) { + CellRangeAddress res = new CellRangeAddress(a, b, c, d); + for (int rowId = a; rowId <= b; rowId++) { + XSSFRow row = sheet.getRow(rowId); + if (row == null) { + continue; + } + for (int colId = c; colId <= d; colId++) { + XSSFCell cell = row.getCell(colId); + if (cell == null) { + cell = row.createCell(colId); + } + cell.setCellStyle(style); + } + } + return res; + } + + public static CellRangeAddress CellRangeAddress(XSSFWorkbook wb, XSSFSheet sheet, int a, int b, int c, int d, XSSFColor bgColor, XSSFColor fontColor, String fontFamily, short fontSize, + boolean bold, boolean top, boolean right, boolean bottom, boolean left) { + return CellRangeAddress(wb, sheet, a, b, c, d, bgColor, fontColor, fontFamily, fontSize, bold, top, right, bottom, left, HorizontalAlignment.CENTER); + } + + public static CellRangeAddress CellRangeAddress(XSSFWorkbook wb, XSSFSheet sheet, int a, int b, int c, int d) { + return CellRangeAddress(wb, sheet, a, b, c, d, null, null, "SimSun", (short) 11, false, false, false, false, false, HorizontalAlignment.CENTER); + } + + public static CellRangeAddress CellRangeAddress(XSSFWorkbook wb, XSSFSheet sheet, int a, int b, int c, int d, HorizontalAlignment ha) { + return CellRangeAddress(wb, sheet, a, b, c, d, null, null, "SimSun", (short) 11, false, false, false, false, false, ha); + } + + public static void setValue(XSSFSheet sheet, int rowId, int col, String val, XSSFCellStyle style) { + XSSFRow row = sheet.getRow(rowId); + if (row == null) { + row = sheet.createRow(rowId); + } + XSSFCell cell = row.getCell(col); + if (cell == null) { + cell = row.createCell(col); + } + cell.setCellValue(val); + if (style != null) { + cell.setCellStyle(style); + } + } + + public static void setValue(XSSFRow row, int col, String val, XSSFCellStyle style) { + XSSFCell cell = row.getCell(col); + if (cell == null) { + cell = row.createCell(col); + } + cell.setCellValue(val); + if (style != null) { + cell.setCellStyle(style); + } + } + + public static XSSFCellStyle getCellStyle(XSSFWorkbook wb, XSSFColor color, boolean isRight) { + XSSFCellStyle style = wb.createCellStyle(); + style.setBorderBottom(CellStyle.BORDER_THIN); + style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); + style.setBorderLeft(CellStyle.BORDER_THIN); + style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); + style.setBorderRight(isRight ? CellStyle.BORDER_MEDIUM : CellStyle.BORDER_THIN); + style.setRightBorderColor(IndexedColors.BLACK.getIndex()); + style.setBorderTop(CellStyle.BORDER_THIN); + style.setTopBorderColor(IndexedColors.BLACK.getIndex()); + if (color != null) { + style.setFillForegroundColor(color); + style.setFillPattern(CellStyle.SOLID_FOREGROUND); + } + return style; + } + + public static XSSFCellStyle getCellStyle(XSSFWorkbook wb, XSSFColor color, boolean isRight, String fontFamily, short fontSize) { + XSSFCellStyle style = wb.createCellStyle(); + style.setBorderBottom(CellStyle.BORDER_THIN); + style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); + style.setBorderLeft(CellStyle.BORDER_THIN); + style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); + style.setBorderRight(isRight ? CellStyle.BORDER_MEDIUM : CellStyle.BORDER_THIN); + style.setRightBorderColor(IndexedColors.BLACK.getIndex()); + style.setBorderTop(CellStyle.BORDER_THIN); + style.setTopBorderColor(IndexedColors.BLACK.getIndex()); + if (color != null) { + style.setFillForegroundColor(color); + style.setFillPattern(CellStyle.SOLID_FOREGROUND); + } + XSSFFont font = wb.createFont(); + if (!KUtil.isEmpty(fontFamily)) { + font.setFontName(fontFamily);// (FontFamily.valueOf(fontFamily)); + } + if (fontSize > 0) { + font.setFontHeightInPoints(fontSize); + } + style.setFont(font); + return style; + } + + public static XSSFCellStyle getCellStyleNoBorder(XSSFWorkbook wb, XSSFColor color, String fontFamily, short fontSize) { + XSSFCellStyle style = wb.createCellStyle(); + if (color != null) { + style.setFillForegroundColor(color); + style.setFillPattern(CellStyle.SOLID_FOREGROUND); + } + XSSFFont font = wb.createFont(); + if (!KUtil.isEmpty(fontFamily)) { + font.setFontName(fontFamily);// (FontFamily.valueOf(fontFamily)); + } + if (fontSize > 0) { + font.setFontHeightInPoints(fontSize); + } + style.setFont(font); + return style; + } + + public static XSSFCellStyle getCellStyleCenter(XSSFWorkbook wb, XSSFColor color, boolean isRight, String fontFamily, short fontSize) { + XSSFCellStyle style = wb.createCellStyle(); + style.setBorderBottom(CellStyle.BORDER_THIN); + style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); + style.setBorderLeft(CellStyle.BORDER_THIN); + style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); + style.setBorderRight(isRight ? CellStyle.BORDER_MEDIUM : CellStyle.BORDER_THIN); + style.setRightBorderColor(IndexedColors.BLACK.getIndex()); + style.setBorderTop(CellStyle.BORDER_THIN); + style.setTopBorderColor(IndexedColors.BLACK.getIndex()); + if (color != null) { + style.setFillForegroundColor(color); + style.setFillPattern(CellStyle.SOLID_FOREGROUND); + } + XSSFFont font = wb.createFont(); + if (!KUtil.isEmpty(fontFamily)) { + font.setFontName(fontFamily);// (FontFamily.valueOf(fontFamily)); + } + if (fontSize > 0) { + font.setFontHeightInPoints(fontSize); + } + style.setFont(font); + style.setVerticalAlignment(VerticalAlignment.CENTER); + style.setAlignment(HorizontalAlignment.CENTER); + return style; + } + + public static void setValue(XSSFRow row, int col, String val) { + XSSFCell cell = row.getCell(col); + if (cell == null) { + cell = row.createCell(col); + // cell.setCellType(XSSFCell.CELL_TYPE_STRING); + } + cell.setCellValue(val); + } + + public static void setValue(XSSFRow row, int col, int val) { + XSSFCell cell = row.getCell(col); + if (cell == null) { + cell = row.createCell(col); + } + cell.setCellValue(val); + } + + public static void setValue(XSSFRow row, int col, double val) { + XSSFCell cell = row.getCell(col); + if (cell == null) { + cell = row.createCell(col); + } + cell.setCellValue(val); + } + + public static int[] parseLocation(String location) { + if (KUtil.isEmpty(location)) { + return null; + } + int ind = -1; + char[] arr = location.toCharArray(); + int len = arr == null ? 0 : arr.length; + for (int i = 0; i < len; i++) { + char c = arr[i]; + if (c >= '0' && c <= '9') { + ind = i; + break; + } + } + if (ind < 0) { + return null; + } + String col = location.substring(0, ind); + String row = location.substring(ind); + int colNum = parseExcelCol(col) - 1; + int rowNum = 0; + if (!KUtil.isEmpty(row)) { + try { + rowNum = Integer.parseInt(row) - 1; + } catch (Exception e) { + e.printStackTrace(); + } + } + return new int[] { colNum, rowNum }; + } + + public static int parseExcelCol(String s) { + int length = s.length(); + int col = 0; + for (int i = 0; i < length; i++) { + col = col * 26 + s.charAt(i) - 64; + } + return col; + } + + public static String formatExcelCol(int s) { + int n; + String res = ""; + while (s / 26 != 0) { + n = s % 26; + s = s / 26; + if (n == 0) { + n = 26; + s = s - 1; + } + res = (char) (n + 64) + res; + } + if (s != 0) { + res = (char) (s + 64) + res; + } + return res; + } + + public static void deleteCol(XSSFSheet sheet, int startRow, int EndRow, int columnToDelete) { + int maxColumn = 0; + for (int r = startRow; r <= EndRow; r++) { + Row row = sheet.getRow(r); + if (row == null) + continue; + int lastColumn = row.getLastCellNum(); + if (lastColumn > maxColumn) + maxColumn = lastColumn; + + if (lastColumn < columnToDelete) + continue; + for (int x = columnToDelete + 1; x < lastColumn + 1; x++) { + Cell oldCell = row.getCell(x - 1); + if (oldCell != null) + row.removeCell(oldCell); + + Cell nextCell = row.getCell(x); + if (nextCell != null) { + Cell newCell = row.createCell(x - 1, nextCell.getCellType()); + cloneCell(newCell, nextCell, true); + } + } + } + for (int c = 0; c < maxColumn; c++) { + sheet.setColumnWidth(c, sheet.getColumnWidth(c + 1)); + } + } + + public static void deleteColumn(Sheet sheet, int columnToDelete) { + int maxColumn = 0; + for (int r = 0; r < sheet.getLastRowNum() + 1; r++) { + Row row = sheet.getRow(r); + + // if no row exists here; then nothing to do; next! + if (row == null) + continue; + + // if the row doesn't have this many columns then we are good; next! + int lastColumn = row.getLastCellNum(); + if (lastColumn > maxColumn) + maxColumn = lastColumn; + + if (lastColumn < columnToDelete) + continue; + + for (int x = columnToDelete + 1; x < lastColumn + 1; x++) { + Cell oldCell = row.getCell(x - 1); + if (oldCell != null) + row.removeCell(oldCell); + + Cell nextCell = row.getCell(x); + if (nextCell != null) { + Cell newCell = row.createCell(x - 1, nextCell.getCellType()); + cloneCell(newCell, nextCell, true); + } + } + } + + // Adjust the column widths + for (int c = 0; c < maxColumn; c++) { + sheet.setColumnWidth(c, sheet.getColumnWidth(c + 1)); + } + } + + /* + * Takes an existing Cell and merges all the styles and forumla into the new one + */ + public static void cloneCell(Cell cNew, Cell cOld, boolean includeValue) { + cNew.setCellComment(cOld.getCellComment()); + cNew.setCellStyle(cOld.getCellStyle()); + if (!includeValue) { + return; + } + switch (cOld.getCellType()) { + case Cell.CELL_TYPE_BOOLEAN: { + cNew.setCellValue(cOld.getBooleanCellValue()); + break; + } + case Cell.CELL_TYPE_NUMERIC: { + cNew.setCellValue(cOld.getNumericCellValue()); + break; + } + case Cell.CELL_TYPE_STRING: { + cNew.setCellValue(cOld.getStringCellValue()); + break; + } + case Cell.CELL_TYPE_ERROR: { + cNew.setCellValue(cOld.getErrorCellValue()); + break; + } + case Cell.CELL_TYPE_FORMULA: { + cNew.setCellFormula(cOld.getCellFormula()); + break; + } + } + + } + + public static XSSFRow insertRow(XSSFSheet sheet, int row) { + int regionCnt = sheet.getNumMergedRegions(); + int sourceRowNum = row-1; + List copyRanges = new ArrayList(); + for (int n = 0; n < regionCnt; n++) { + CellRangeAddress region = sheet.getMergedRegion(n); + if ((region.getFirstRow() == sourceRowNum) && (region.getLastRow() == sourceRowNum)) { + copyRanges.add(region); + + } + } + XSSFRow sourceRow = sheet.getRow(sourceRowNum); + sheet.shiftRows(row, sheet.getLastRowNum(), 1, true, false); + XSSFRow targetRow = null; + XSSFCell sourceCell = null; + XSSFCell targetCell = null; + short m; + targetRow = sheet.createRow(row); + if (sourceRow != null) { + targetRow.setHeight(sourceRow.getHeight()); + for (m = sourceRow.getFirstCellNum(); m < sourceRow.getLastCellNum(); m++) { + sourceCell = sourceRow.getCell(m); + targetCell = targetRow.createCell(m); + targetCell.setCellStyle(sourceCell.getCellStyle()); + targetCell.setCellType(sourceCell.getCellType()); + } + } + for (org.apache.poi.ss.util.CellRangeAddress region : copyRanges) { + CellRangeAddress newRegion = new CellRangeAddress(row, row, region.getFirstColumn(), region.getLastColumn()); + sheet.addMergedRegion(newRegion); + } + return targetRow; + } + + public static void copyRows(XSSFWorkbook wb, XSSFSheet sheet, int startRow, int endRow, int margin, int endCol, int copyCount) { + int regionCnt = sheet.getNumMergedRegions(); + CellRangeAddress region; + for (int i = startRow; i <= endRow; i++) { + XSSFRow sourceRow = null; + XSSFRow targetRow = null; + XSSFCell sourceCell = null; + XSSFCell targetCell = null; + short m; + sourceRow = sheet.getRow(i); + for (int j = 1; j <= copyCount; j++) { + int space = (endRow - startRow + 1 + margin) * j; + targetRow = sheet.createRow(i + space); + targetRow.setHeight(sourceRow.getHeight()); + for (m = sourceRow.getFirstCellNum(); m <= endCol; m++) { + sourceCell = sourceRow.getCell(m); + targetCell = targetRow.createCell(m); + if (sourceCell != null) { + targetCell.setCellStyle(sourceCell.getCellStyle()); + int cType = sourceCell.getCellType(); + targetCell.setCellType(cType); + switch (cType) { + case XSSFCell.CELL_TYPE_STRING: + targetCell.setCellValue(sourceCell.getRichStringCellValue()); + break; + case XSSFCell.CELL_TYPE_NUMERIC: + targetCell.setCellValue(sourceCell.getNumericCellValue()); + break; + case XSSFCell.CELL_TYPE_FORMULA: + targetCell.setCellFormula(sourceCell.getCellFormula()); + break; + case XSSFCell.CELL_TYPE_BOOLEAN: + targetCell.setCellValue(sourceCell.getBooleanCellValue()); + break; + case XSSFCell.CELL_TYPE_ERROR: + targetCell.setCellValue(sourceCell.getErrorCellValue()); + break; + default: + targetCell.setCellValue(sourceCell.getRichStringCellValue()); + break; + } + } + } + + } + } + for (int j = 1; j <= copyCount; j++) { + int space = (endRow - startRow + 1 + margin) * j; + // ����ϲ���Ԫ�� + for (int n = 0; n < regionCnt; n++) { + region = sheet.getMergedRegion(n); + if ((region.getFirstColumn() >= startRow) && (region.getLastRow() <= endRow) && (region.getLastColumn() <= endCol)) { + CellRangeAddress newRegion = new CellRangeAddress(region.getFirstRow() + space, region.getLastRow() + space, region.getFirstColumn(), region.getLastColumn()); + sheet.addMergedRegion(newRegion); + } + } + } + } + + public static boolean writeToExcel(File tempFile, int[] cols, String[][] vals, int startRow, int endRow, Map otherData) { + FileInputStream input = null; + FileOutputStream output = null; + int rowCount = vals.length; + int colCount = cols.length; + XSSFRow row = null; + XSSFCell cell = null; + int index = 0; + try { + input = new FileInputStream(tempFile); + XSSFWorkbook wb = new XSSFWorkbook(input); + XSSFSheet sheet = wb.getSheetAt(index); + for (Point point : otherData.keySet()) { + row = sheet.getRow(point.x); + cell = row.getCell(point.y); + cell.setCellType(XSSFCell.CELL_TYPE_STRING); + cell.setCellValue(otherData.get(point)); + } + int sheetCount = vals.length % (endRow - startRow + 1) == 0 ? vals.length / (endRow - startRow + 1) : vals.length / (endRow - startRow + 1) + 1; + Map sheetMap = new HashMap<>(); + for (int i = 1; i < sheetCount; i++) { + XSSFSheet newSheet = wb.createSheet(); + copySheet2007(wb, sheet, newSheet); + sheetMap.put(i, newSheet); + } + for (int i = 0; i < rowCount; i++) { + if ((i + startRow - (endRow - startRow + 1) * index) > endRow) { + index++; + sheet = sheetMap.get(index); + row = sheet.getRow(i + startRow - (endRow - startRow + 1) * index); + } else { + row = sheet.getRow(i + startRow - (endRow - startRow + 1) * index); + } + for (int j = 0; j < colCount; j++) { + cell = row.getCell(cols[j]); + cell.setCellType(XSSFCell.CELL_TYPE_STRING); + cell.setCellValue(vals[i][j]); + } + } + output = new FileOutputStream(tempFile); + wb.write(output); + } catch (Exception e) { + e.printStackTrace(); + return false; + } finally { + if (output != null) { + try { + output.close(); + input.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + System.out.println("-------WRITE EXCEL OVER-------"); + return true; + } + + private static XSSFSheet copySheet2007(XSSFWorkbook workbook, XSSFSheet sheetFrom, XSSFSheet sheetTo) { + CellRangeAddress region = null; + XSSFRow rowFrom = null; + XSSFRow rowTo = null; + XSSFCell cellFrom = null; + XSSFCell cellTo = null; + for (int i = 0; i < sheetFrom.getNumMergedRegions(); i++) { + region = sheetFrom.getMergedRegion(i); + if ((region.getFirstColumn() >= sheetFrom.getFirstRowNum()) && (region.getLastRow() <= sheetFrom.getLastRowNum())) { + sheetTo.addMergedRegion(region); + } + } + for (int intRow = sheetFrom.getFirstRowNum(); intRow < sheetFrom.getLastRowNum(); intRow++) { + rowFrom = sheetFrom.getRow(intRow); + rowTo = sheetTo.createRow(intRow); + if (null == rowFrom) + continue; + rowTo.setHeight(rowFrom.getHeight()); + for (int intCol = 0; intCol < rowFrom.getLastCellNum(); intCol++) { + sheetTo.setDefaultColumnStyle(intCol, sheetFrom.getColumnStyle(intCol)); + sheetTo.setColumnWidth(intCol, sheetFrom.getColumnWidth(intCol)); + cellFrom = rowFrom.getCell(intCol); + cellTo = rowTo.createCell(intCol); + if (null == cellFrom) + continue; + cellTo.setCellStyle(cellFrom.getCellStyle()); + int cType = cellFrom.getCellType(); + cellTo.setCellType(cType); + switch (cType) { + case XSSFCell.CELL_TYPE_STRING: + cellTo.setCellValue(cellFrom.getRichStringCellValue()); + break; + case XSSFCell.CELL_TYPE_NUMERIC: + cellTo.setCellValue(cellFrom.getNumericCellValue()); + break; + case XSSFCell.CELL_TYPE_FORMULA: + cellTo.setCellFormula(cellFrom.getCellFormula()); + break; + case XSSFCell.CELL_TYPE_BOOLEAN: + cellTo.setCellValue(cellFrom.getBooleanCellValue()); + break; + case XSSFCell.CELL_TYPE_ERROR: + cellTo.setCellValue(cellFrom.getErrorCellValue()); + break; + default: + cellTo.setCellValue(cellFrom.getRichStringCellValue()); + break; + } + /* + * if (null != cellFrom.getStringCellValue() && + * !"".equals(cellFrom.getStringCellValue().trim())) + * cellTo.setCellValue(cellFrom.getStringCellValue()); + */ + } + } + XSSFDrawing patriarchTo = sheetTo.createDrawingPatriarch(); + for (POIXMLDocumentPart dr : sheetFrom.getRelations()) { + if (dr instanceof XSSFDrawing) { + XSSFDrawing drawing = (XSSFDrawing) dr; + List shapes = drawing.getShapes(); + for (XSSFShape shape : shapes) { + XSSFPicture pic = (XSSFPicture) shape; + patriarchTo.createPicture((ClientAnchor) pic.getAnchor(), workbook.addPicture(pic.getPictureData().getData(), XSSFWorkbook.PICTURE_TYPE_PNG)); + } + } + } + sheetTo.setDisplayGridlines(false); + sheetTo.setZoom(100, 100); + return sheetTo; + + } + + // public static String getValue(XSSFRow titleRow, int i) { + // XSSFCell cell = titleRow.getCell(i); + // if(cell==null) { + // return ""; + // } + // if(cell.getCellType()==XSSFCell.CELL_TYPE_NUMERIC) { + // return cell.getNumericCellValue()+""; + // }else { + // return cell.getStringCellValue(); + // } + // } + + public static DecimalFormat DF = new DecimalFormat("#.##########################################"); + + public static String getValue(XSSFRow titleRow, int i) { + XSSFCell cell = titleRow.getCell(i); + if (cell == null) { + return ""; + } + if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) { + return DF.format(cell.getNumericCellValue()); + } else if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING) { + return cell.getStringCellValue(); + } + return ""; + } + + public static String getValue(XSSFSheet sheet, int i, int j) { + XSSFRow row = sheet.getRow(i); + if (row == null) { + return null; + } + return getValue(row, j); + } + + public static XSSFRow getRow(XSSFSheet sheet, int i) { + XSSFRow row = sheet.getRow(i); + if (row == null) { + row = sheet.createRow(i); + } + return row; + } + + public static LinkedHashMap readRow(SimpleDateFormat dateFormat, XSSFSheet sheet, int rowNum, boolean readEmpty) { + if (sheet == null) { + return null; + } + XSSFRow row = sheet.getRow(rowNum); + if (row == null) { + return null; + } + LinkedHashMap data = new LinkedHashMap(); + int firstCol = row.getFirstCellNum(); + if (firstCol < 0) { + firstCol = 0; + } + int lastCol = row.getLastCellNum(); + for (int i = firstCol; i <= lastCol; i++) { + XSSFCell cell = row.getCell(i); + if (cell == null) { + continue; + } + String value; + switch (cell.getCellType()) { + case XSSFCell.CELL_TYPE_STRING: + value = cell.getStringCellValue(); + break; + case XSSFCell.CELL_TYPE_NUMERIC: + if (dateFormat != null && DateUtil.isCellDateFormatted(cell)) { + value = cell.getDateCellValue() == null ? "" : dateFormat.format(cell.getDateCellValue()); + } else { + value = DF.format(cell.getNumericCellValue()); + } + break; + case XSSFCell.CELL_TYPE_FORMULA: + value = cell.getCellFormula(); + break; + case XSSFCell.CELL_TYPE_ERROR: + value = cell.getErrorCellString(); + break; + case XSSFCell.CELL_TYPE_BOOLEAN: + value = cell.getBooleanCellValue() ? "true" : "false"; + break; + case XSSFCell.CELL_TYPE_BLANK: + value = ""; + break; + default: + value = ""; + break; + } + if (!readEmpty && (value == null || "".equals(value))) { + continue; + } + data.put(i, value); + } + return data; + } + + public static LinkedHashMap readRow(SimpleDateFormat dateFormat, XSSFSheet sheet, int rowNum, Integer[] cols) { + if (sheet == null || KUtil.getLen(cols) == 0) { + return null; + } + XSSFRow row = sheet.getRow(rowNum); + if (row == null) { + return null; + } + LinkedHashMap data = new LinkedHashMap(); + for (Integer i : cols) { + XSSFCell cell = row.getCell(i); + if (cell == null) { + data.put(i, ""); + continue; + } + String value; + switch (cell.getCellType()) { + case XSSFCell.CELL_TYPE_STRING: + value = cell.getStringCellValue(); + break; + case XSSFCell.CELL_TYPE_NUMERIC: + if (dateFormat != null && DateUtil.isCellDateFormatted(cell)) { + value = cell.getDateCellValue() == null ? "" : dateFormat.format(cell.getDateCellValue()); + } else { + value = DF.format(cell.getNumericCellValue()); + } + break; + case XSSFCell.CELL_TYPE_FORMULA: + value = cell.getCellFormula(); + break; + case XSSFCell.CELL_TYPE_ERROR: + value = cell.getErrorCellString(); + break; + case XSSFCell.CELL_TYPE_BOOLEAN: + value = cell.getBooleanCellValue() ? "true" : "false"; + break; + case XSSFCell.CELL_TYPE_BLANK: + value = ""; + break; + default: + value = ""; + break; + } + data.put(i, value); + } + return data; + } + + public static void writeToNamedCells(XSSFWorkbook wb, Map excelDataMap) throws Exception { + if (wb == null || excelDataMap == null || excelDataMap.size() == 0) { + return; + } + for (String cellName : excelDataMap.keySet()) { + String value = excelDataMap.get(cellName); + System.out.println("[" + cellName + "]=[" + value + "]"); + XSSFName name = wb.getName(cellName); + if (name == null) { + System.out.println(">> Named Cell Not Found"); + } else { + AreaReference aref = new AreaReference(name.getRefersToFormula()); + CellReference[] crefs = aref.getAllReferencedCells(); + for (int i = 0; i < crefs.length; i++) { + XSSFSheet s = wb.getSheet(crefs[i].getSheetName()); + int row = crefs[i].getRow(); + int col = crefs[i].getCol(); + System.out.println(">> " + crefs[i].formatAsString()); + POIUtil.setValue(s, row, col, value); + } + } + } + } + + public static XSSFCellStyle cloneCellStype(XSSFCellStyle fromStyle, XSSFWorkbook wb, Map fontMap) throws Exception{ + if(fromStyle==null||wb==null) { + return null; + } + XSSFCellStyle toStyle = wb.createCellStyle(); + toStyle.setAlignment(fromStyle.getAlignment()); + toStyle.setBorderColor(BorderSide.TOP, fromStyle.getBorderColor(BorderSide.TOP)); + toStyle.setBorderColor(BorderSide.LEFT, fromStyle.getBorderColor(BorderSide.LEFT)); + toStyle.setBorderColor(BorderSide.BOTTOM, fromStyle.getBorderColor(BorderSide.BOTTOM)); + toStyle.setBorderColor(BorderSide.RIGHT, fromStyle.getBorderColor(BorderSide.RIGHT)); + toStyle.setBorderTop(fromStyle.getBorderTop()); + toStyle.setBorderLeft(fromStyle.getBorderLeft()); + toStyle.setBorderBottom(fromStyle.getBorderBottom()); + toStyle.setBorderRight(fromStyle.getBorderRight()); + XSSFFont fromFont = fromStyle.getFont(); + if(fromFont!=null) { + XSSFFont toFont = wb.createFont(); + if(fontMap.containsKey(fromFont)) { + toFont = fontMap.get(fromFont); + }else { + toFont = wb.createFont(); + toFont.setBold(fromFont.getBold()); + toFont.setBoldweight(fromFont.getBoldweight()); + toFont.setCharSet(fromFont.getCharSet()); + toFont.setColor(fromFont.getColor()); + toFont.setColor(fromFont.getXSSFColor()); + toFont.setFamily(fromFont.getFamily()); + toFont.setFontHeight(fromFont.getFontHeight()); + toFont.setFontHeightInPoints(fromFont.getFontHeightInPoints()); + toFont.setFontName(fromFont.getFontName()); + toFont.setItalic(fromFont.getItalic()); + toFont.setScheme(fromFont.getScheme()); + toFont.setStrikeout(fromFont.getStrikeout()); + // toFont.setThemeColor(fromFont.getThemeColor()); + toFont.setTypeOffset(fromFont.getTypeOffset()); + toFont.setUnderline(fromFont.getUnderline()); + } + toStyle.setFont(toFont); + } + toStyle.setFillBackgroundColor(fromStyle.getFillBackgroundXSSFColor()); + toStyle.setFillForegroundColor(fromStyle.getFillForegroundXSSFColor()); + toStyle.setFillPattern(fromStyle.getFillPattern()); + toStyle.setHidden(fromStyle.getHidden()); + toStyle.setIndention(fromStyle.getIndention()); + toStyle.setLocked(fromStyle.getLocked()); + toStyle.setRotation(fromStyle.getRotation()); + toStyle.setVerticalAlignment(fromStyle.getVerticalAlignment()); + toStyle.setWrapText(fromStyle.getWrapText()); + return toStyle; + } + +} diff --git a/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/PropLocation.java b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/PropLocation.java new file mode 100644 index 0000000..c2ae9a6 --- /dev/null +++ b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/PropLocation.java @@ -0,0 +1,91 @@ +package cn.net.connor.std.aifrcp.util; + +import java.util.Map; + +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentBOMLine; +import com.teamcenter.rac.kernel.TCComponentItemRevision; + +public class PropLocation { + + public static final String ITEM = "ITEM"; + public static final String REV = "REV"; + public static final String ITEMMASTER = "ITEMMASTER"; + public static final String REVMASTER = "REVMASTER"; + public static final String BOMLINE = "BOMLINE"; + + public static final String CITEM = "CITEM"; + public static final String CREV = "CREV"; + public static final String CITEMMASTER = "CITEMMASTER"; + public static final String CREVMASTER = "CREVMASTER"; + public static final String CBOMLINE = "CBOMLINE"; + + public static final String PITEM = "PITEM"; + public static final String PREV = "PREV"; + public static final String PITEMMASTER = "PITEMMASTER"; + public static final String PREVMASTER = "PREVMASTER"; + public static final String PBOMLINE = "PBOMLINE"; + + public static final String METARGET_ITEM = "MITEM"; + public static final String METARGET_REV = "MREV"; + public static final String METARGET_ITEMMASTER = "MITEMMASTER"; + public static final String METARGET_REVMASTER = "MREVMASTER"; + + public static void initLocationMap(Map markedComponents, TCComponentItemRevision rev) throws Exception { + if (markedComponents == null || rev == null) { + return; + } + markedComponents.put(PropLocation.ITEM, rev.getItem()); + markedComponents.put(PropLocation.REV, rev); + markedComponents.put(PropLocation.ITEMMASTER, rev.getItem().getRelatedComponent("IMAN_master_form")); + markedComponents.put(PropLocation.REVMASTER, rev.getRelatedComponent("IMAN_master_form_rev")); + } + + public static void initMLocationMap(Map markedComponents, TCComponentItemRevision rev) throws Exception { + if (markedComponents == null || rev == null) { + return; + } + markedComponents.put(PropLocation.METARGET_ITEM, rev.getItem()); + markedComponents.put(PropLocation.METARGET_REV, rev); + markedComponents.put(PropLocation.METARGET_ITEMMASTER, rev.getItem().getRelatedComponent("IMAN_master_form")); + markedComponents.put(PropLocation.METARGET_REVMASTER, rev.getRelatedComponent("IMAN_master_form_rev")); + } + + public static void initLocationMap(Map markedComponents, TCComponentBOMLine targetLine) throws Exception { + if (markedComponents == null || targetLine == null) { + return; + } + markedComponents.put(PropLocation.BOMLINE, targetLine); + markedComponents.put(PropLocation.ITEM, targetLine.getItem()); + markedComponents.put(PropLocation.REV, targetLine.getItemRevision()); + markedComponents.put(PropLocation.ITEMMASTER, targetLine.getItem().getRelatedComponent("IMAN_master_form")); + markedComponents.put(PropLocation.REVMASTER, targetLine.getItemRevision().getRelatedComponent("IMAN_master_form_rev")); + } + + public static void initCLocationMap(Map markedComponents, TCComponentBOMLine targetLine) throws Exception { + if (markedComponents == null || targetLine == null) { + return; + } + markedComponents.put(PropLocation.CBOMLINE, targetLine); + markedComponents.put(PropLocation.CITEM, targetLine.getItem()); + markedComponents.put(PropLocation.CREV, targetLine.getItemRevision()); + markedComponents.put(PropLocation.CITEMMASTER, targetLine.getItem().getRelatedComponent("IMAN_master_form")); + markedComponents.put(PropLocation.CREVMASTER, targetLine.getItemRevision().getRelatedComponent("IMAN_master_form_rev")); + } + + public static void initPLocationMap(Map markedComponents, TCComponentBOMLine targetLine) throws Exception { + if (markedComponents == null || targetLine == null) { + return; + } + TCComponentBOMLine parentLine = targetLine.parent(); + if(parentLine==null) { + return; + } + markedComponents.put(PropLocation.PBOMLINE, parentLine); + markedComponents.put(PropLocation.PITEM, parentLine.getItem()); + markedComponents.put(PropLocation.PREV, parentLine.getItemRevision()); + markedComponents.put(PropLocation.PITEMMASTER, parentLine.getItem().getRelatedComponent("IMAN_master_form")); + markedComponents.put(PropLocation.PREVMASTER, parentLine.getItemRevision().getRelatedComponent("IMAN_master_form_rev")); + } + +} diff --git a/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/ScheduleUtil.java b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/ScheduleUtil.java new file mode 100644 index 0000000..a38eb8b --- /dev/null +++ b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/ScheduleUtil.java @@ -0,0 +1,267 @@ +package cn.net.connor.std.aifrcp.util; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import com.teamcenter.rac.aif.AbstractAIFUIApplication; +import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.SoaUtil; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentSchedule; +import com.teamcenter.rac.kernel.TCComponentScheduleTask; +import com.teamcenter.rac.kernel.TCComponentTCCalendar; +import com.teamcenter.rac.kernel.TCComponentTaskTemplate; +import com.teamcenter.rac.kernel.TCComponentTaskTemplateType; +import com.teamcenter.rac.kernel.TCComponentUser; +import com.teamcenter.rac.kernel.TCException; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.schedule.ScheduleViewApplication; +import com.teamcenter.rac.schedule.ScheduleViewApplicationPanel; +import com.teamcenter.rac.schedule.calendar.TCCalendar; +import com.teamcenter.rac.schedule.componentutils.CalendarHelper; +import com.teamcenter.rac.util.Registry; +import com.teamcenter.services.rac.projectmanagement.ScheduleManagementService; +import com.teamcenter.services.rac.projectmanagement._2007_06.ScheduleManagement.TaskDeliverableContainer; +import com.teamcenter.services.rac.projectmanagement._2008_06.ScheduleManagement.ScheduleDeliverableData; +import com.teamcenter.services.rac.projectmanagement._2012_02.ScheduleManagement.AssignmentCreateContainer; +import com.teamcenter.services.rac.projectmanagement._2012_02.ScheduleManagement.AttributeUpdateContainer; +import com.teamcenter.services.rac.projectmanagement._2012_02.ScheduleManagement.CreatedObjectsContainer; +import com.teamcenter.services.rac.projectmanagement._2012_02.ScheduleManagement.LaunchedWorkflowContainer; +import com.teamcenter.services.rac.projectmanagement._2012_02.ScheduleManagement.TaskCreateContainer; + +public class ScheduleUtil { + + private static Registry REG = Registry.getRegistry(ScheduleUtil.class); + public static final int DELIVERABLE_SUBMIT_TYPE_TARGET = 0; + public static final int DELIVERABLE_SUBMIT_TYPE_REFERENCE = 1; + + + public static TCComponentScheduleTask createScheduleTask(TCSession session, String taskName, TCComponentSchedule schedule, TCComponentScheduleTask parentTask, TCComponentUser user, String workflowName, + Date startDate, Date finishDate, boolean startWorkFlow, Map stringProps, int workEstimate) throws Exception { + return createScheduleTask(session, taskName, schedule, parentTask, user, workflowName, "0", null, startDate, finishDate, startWorkFlow, stringProps, workEstimate); + } + + @SuppressWarnings("deprecation") + public static TCComponentScheduleTask createScheduleTask(TCSession session, String taskName, TCComponentSchedule schedule, TCComponentScheduleTask parentTask, TCComponentUser user, String workflowName, + String workflowTrigger, String constraint, Date startDate, Date finishDate, boolean startWorkFlow, Map stringProps, int workEstimate) throws Exception { + ScheduleManagementService smService = ScheduleManagementService.getService(session); + TaskCreateContainer container = new TaskCreateContainer(); + container.name = taskName; + container.desc = ""; + container.objectType = "ScheduleTask"; + container.parent = parentTask; + Calendar start = Calendar.getInstance(); + start.setTime(startDate == null ? parentTask.getDateProperty("start_date") : startDate); + container.start = start; + if (workEstimate < 0) { + workEstimate = 8 * 60; + } + container.workEstimate = workEstimate; + + boolean addUser = user != null; + if (!KUtil.isEmpty(workflowName)) { + TCComponentTaskTemplateType taskTemplateType = (TCComponentTaskTemplateType) session.getTypeComponent(TCComponentTaskTemplateType.EPM_TASKTEMPLATE_TYPE); + if (taskTemplateType == null) { + throw new TCException("Task Template type not found."); + } + TCComponentTaskTemplate template = taskTemplateType.find(workflowName, TCComponentTaskTemplate.PROCESS_TEMPLATE_TYPE); + if (template == null) { + throw new TCException("Workflow template not found: " + workflowName); + } + List attrList = new ArrayList<>(); + AttributeUpdateContainer attr_triggerType = new com.teamcenter.services.rac.projectmanagement._2012_02.ScheduleManagement.AttributeUpdateContainer(); + attr_triggerType.attrName = "workflow_trigger_type"; + attr_triggerType.attrType = 4; + System.out.println("trigger type: " + workflowTrigger); + attr_triggerType.attrValue = workflowTrigger; + attrList.add(attr_triggerType); + + if (!KUtil.isEmpty(constraint)) { + AttributeUpdateContainer attr_constraint = new com.teamcenter.services.rac.projectmanagement._2012_02.ScheduleManagement.AttributeUpdateContainer(); + attr_constraint.attrName = "constraint"; + attr_constraint.attrType = 4; + System.out.println("constraint: " + constraint); + attr_constraint.attrValue = constraint; + attrList.add(attr_constraint); + } + + AttributeUpdateContainer attr_workflow = new com.teamcenter.services.rac.projectmanagement._2012_02.ScheduleManagement.AttributeUpdateContainer(); + attr_workflow.attrName = "workflow_template"; + attr_workflow.attrValue = template.getUid();// workflowUID; + attr_workflow.attrType = 8; // reference + attrList.add(attr_workflow); + + if (addUser) { + AttributeUpdateContainer attr_priuser = new com.teamcenter.services.rac.projectmanagement._2012_02.ScheduleManagement.AttributeUpdateContainer(); + attr_priuser.attrName = "privileged_user"; + attr_priuser.attrValue = user.getUid();// workflowUID; + attr_priuser.attrType = 8; // reference + attrList.add(attr_priuser); + + AttributeUpdateContainer attr_workflowowner = new com.teamcenter.services.rac.projectmanagement._2012_02.ScheduleManagement.AttributeUpdateContainer(); + attr_workflowowner.attrName = "fnd0workflow_owner"; + attr_workflowowner.attrValue = user.getUid();// workflowUID; + attr_workflowowner.attrType = 8; // reference + attrList.add(attr_workflowowner); + } + // int attrCnt = defaultAttrs.size(); + // for(int i=0;i 0) { + newTask = (TCComponentScheduleTask) resp.serviceData.getCreatedObject(0); + } else { + throw new TCException("Create schedule task failed: " + taskName); + } + // resouce assign + if (user != null) { + AssignmentCreateContainer assign = new AssignmentCreateContainer(); + assign.task = newTask; + assign.user = user; + assign.assignedPercent = 100; + CreatedObjectsContainer assignResp = smService.assignResources(schedule, new AssignmentCreateContainer[] { assign }); + SoaUtil.checkPartialErrors(assignResp.serviceData); + } + newTask.refresh(); + parentTask.refresh(); + if (finishDate != null) { + // Calendar end = Calendar.getInstance(); + // end.setTime(finishDate); + // container.finish = end; + // container.workEstimate = (int) + // Math.ceil(ChronoUnit.MINUTES.between(start.toInstant(), end.toInstant())); + // System.out.println(container.workEstimate); + newTask.setDateProperty("finish_date", finishDate); + newTask.refresh(); + } + if (stringProps != null) { + newTask.setProperties(stringProps); + newTask.refresh(); + } + if (startWorkFlow && !KUtil.isEmpty(workflowName)) { + LaunchedWorkflowContainer lResp = smService.launchScheduledWorkflow(new TCComponentScheduleTask[] { newTask }); + SoaUtil.checkPartialErrors(lResp.serviceData); + } + newTask.refresh(); + return newTask; + } + + public static TCComponentScheduleTask createScheduleTask(TCSession session, String taskName, TCComponentSchedule schedule, TCComponentScheduleTask parentTask, TCComponentUser user, String workflowName, + Date startDate, Date finishDate, boolean startWorkFlow, Map stringProps) throws Exception { + return createScheduleTask(session, taskName, schedule, parentTask, user, workflowName, startDate, finishDate, startWorkFlow, stringProps, 8 * 60); + } + + public static TCComponentTCCalendar getScheduleCalendar(TCSession session, TCComponentSchedule schedule) throws Exception { + if (schedule == null) { + return null; + } + return CalendarHelper.getScheduleCalendar(schedule, session); + } + + public static void createScheduleTaskDeliverable(TCSession session, TCComponentSchedule schedule, TCComponent deliverable, TCComponentScheduleTask task) throws Exception { + if (schedule == null || deliverable == null || task == null) { + return; + } + System.out.println("Create Task Deliverable: " + schedule + "|" + task + "|" + deliverable); + ScheduleDeliverableData[] data = new ScheduleDeliverableData[1]; + data[0] = new ScheduleDeliverableData(); + data[0].deliverableName = deliverable.toString(); + data[0].deliverableReference = deliverable; + data[0].deliverableType = deliverable.getType(); + data[0].schedule = schedule; + ScheduleManagementService smService = ScheduleManagementService.getService(session); + com.teamcenter.rac.kernel.ServiceData resp = smService.createScheduleDeliverableTemplates(data); + SoaUtil.checkPartialErrors(resp); + int size = resp.sizeOfCreatedObjects(); + if (size == 0) { + throw new TCException(String.format(REG.getString("createscheduledeliverable.ERROR2"), schedule.toString(), deliverable.toString())); + } + System.out.println(">> schedule deliverable: " + resp.getCreatedObject(0)); + TaskDeliverableContainer[] taskData = new TaskDeliverableContainer[1]; + taskData[0] = new TaskDeliverableContainer(); + taskData[0].scheduleDeliverable = resp.getCreatedObject(0); + taskData[0].submitType = DELIVERABLE_SUBMIT_TYPE_TARGET; + taskData[0].scheduleTask = task; + com.teamcenter.rac.kernel.ServiceData taskResp = smService.createTaskDeliverableTemplates(taskData); + SoaUtil.checkPartialErrors(taskResp); + } + + public static TCComponentSchedule getCurrentSchedule() { + AbstractAIFUIApplication aifApp = AIFUtility.getCurrentApplication(); + if (aifApp == null) { + return null; + } + if (aifApp instanceof ScheduleViewApplication) { + ScheduleViewApplication app = (ScheduleViewApplication) aifApp; + ScheduleViewApplicationPanel panel = (ScheduleViewApplicationPanel) app.getApplicationPanel(); + if (panel == null) { + return null; + } + return panel.getCurrentProject(); + } + InterfaceAIFComponent target = aifApp.getTargetComponent(); + if (target != null && (target instanceof TCComponentSchedule)) { + return (TCComponentSchedule) target; + } + return null; + } + + public static Date calTime(TCCalendar calendar, Date date, int minutes) { + if (calendar == null || date == null) { + return null; + } + int diff = minutes > 0 ? 1 : -1; + if (minutes < 0) { + minutes = -minutes; + } + Calendar c = Calendar.getInstance(); + c.setTime(date); + int counter = 0; + while (counter < minutes) { + counter += calendar.getMinutesOnDay(c); + c.add(Calendar.DATE, diff); + } + return c.getTime(); + } + + public static int getMinutesBetween(TCCalendar calendar, Date start, Date end) { + if (calendar == null || start == null || end == null) { + return 0; + } + Calendar c = Calendar.getInstance(); + c.setTime(start); + int res = 0; + while (c.getTime().before(end)) { + res += calendar.getMinutesOnDay(c); + // System.out.println(calendar.getMinutesOnDay(c)+" > "+c.getTime()); + c.add(Calendar.DATE, 1); + } + return res; + } + +} diff --git a/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/util_locale.properties b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/util_locale.properties new file mode 100644 index 0000000..6f0e2c6 --- /dev/null +++ b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/util_locale.properties @@ -0,0 +1,64 @@ +# +#Tue Apr 13 11:38:06 CST 2021 +createscheduledeliverable.ERROR2=\u4E3A [%s] \u521B\u5EFA\u65F6\u95F4\u8868\u4EA4\u4ED8\u7269 [%s] \u5931\u8D25 +project=Project +dsuidinpref.ERROR1=Error dataset uid set in preference\: %s +appendword=\u9644\u52A0\u6587\u4EF6 +valuenotinlov.ERROR2=LOV "%s" does not contain value\: %s +writedata=Write Data +querynotexist.ERROR1=Query not exist\: %s +dialoginit.ERROR=Init Error +preferror.ERROR1=Preference error\: %s +norefindataset.ERROR1=Download file from dataset "%s" failed. No ref file. +word.PAGECOUNT=\u5171 %s \u9875 +cancel=Cancel +exeop.STATUS=Execute... +initop.STATUS=Checking Data... +selectall=Select All +noflowkey.ERROR=Missing key for flow number. +wordfield_pagecount.NAME=\u9875\u6570 +nopropintype.ERROR2=Property is not defined in type "%s"\: %s. +getflowno.ERROR1=Error getting new flow number for key\: %s +formsave.ERRORTITLE=Error Saving Data +wordfield_pageno.NAME=\u9875\u7801 +wordfield_totalpagenominus1.NAME=\u603B\u9875\u7801\u51CF\u4E00 +wordfield_totalpagecount.NAME=\u603B\u9875\u6570 +exceltitlenorelateinfo.ERROR=Title row in sheet does not have any relation info. +selectProject=Select Project +proplocationnotdefined.ERROR1=\u672A\u77E5\u5C5E\u6027\u4F4D\u7F6E\u201C%s\u201D\uFF0C\u8BF7\u68C0\u67E5\u914D\u7F6E +excelnotitle.ERROR=Can't find title row in excel sheet. +loadCompFromUid.Error2=Error loading component "%s", UID \= "%s". +uploadfilewhencheckout.ERROR1=Dataset "%s" is checked out. Upload file failed. +wordfield_totalactualpagecountminus1.NAME=\u603B\u5B9E\u9645\u9875\u6570\u51CF\u4E00 +nodatainfile.ERROR1=No Data in File\: %s +noexportdata.ERROR=\u6CA1\u6709\u6570\u636E\u53EF\u4EE5\u5BFC\u51FA +notscheduleadmin.INFO=\u53EA\u6709\u534F\u8C03\u8005\u624D\u80FD\u64CD\u4F5C +word.PAGENUM=\u7B2C %s \u9875 +error=Error +mergefile=Merge File... +index=Index +ok=OK +forminit.ERRORTITLE=Error Loading Rendering +wordfield_totalactualpagecount.NAME=\u603B\u5B9E\u9645\u9875\u6570 +requireprop.INFO1=\u8BF7\u586B\u5199\u5C5E\u6027\uFF1A%s +clear=Clear +functionnotavailable.INFO=\u6B64\u5BF9\u8C61\u4E0D\u53EF\u4F7F\u7528\u6B64\u529F\u80FD +multiuserbyid.ERROR1=Find multiple users by id\: %s +preparedata=Prepare Data +dbconn.ERROR=Connect to database failed. +typenotfound.ERROR1=Type not found\: %s +filenotexist.ERROR1=File not exist\: %s +wordfield_totalpagecountminus1.NAME=\u603B\u9875\u6570\u51CF\u4E00 +readdata=Read Data +clearcache=Clear Cache +exportsuccess.INFO=Export Complete. +uploadfile=Upload File +propnotdefinedintype.ERROR2=\u5BF9\u8C61\u7C7B\u578B\u201C%s\u201D\u672A\u5B9A\u4E49\u5C5E\u6027\uFF1A%s +foldernotexist.ERROR1=Folder not exist\: %s +info=Info +search=Search +wordfield_totalpageno.NAME=\u603B\u9875\u7801 +multiuserbyname.ERROR1=Find multiple users by name\: %s +exportopenfile.INFO=Export complete. Open file? +prefnotconfiged.ERROR1=Prefernce not found\: %s +export=Export diff --git a/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/util_locale_zh_CN.properties b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/util_locale_zh_CN.properties new file mode 100644 index 0000000..c003844 --- /dev/null +++ b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/util/util_locale_zh_CN.properties @@ -0,0 +1,64 @@ +# +#Tue Apr 13 11:38:06 CST 2021 +createscheduledeliverable.ERROR2=\u4E3A [%s] \u521B\u5EFA\u65F6\u95F4\u8868\u4EA4\u4ED8\u7269 [%s] \u5931\u8D25 +project=\u9879\u76EE +dsuidinpref.ERROR1=\u8BF7\u68C0\u67E5\u9996\u9009\u9879<%s>\uFF0C\u901A\u8FC7\u914D\u7F6EUID\u672A\u627E\u5230\u6570\u636E\u96C6 +appendword=\u9644\u52A0\u6587\u4EF6 +valuenotinlov.ERROR2=LOV "%s" \u4E2D\u672A\u5B9A\u4E49\u6570\u503C\uFF1A%s +writedata=\u5199\u5165\u6570\u636E +querynotexist.ERROR1=\u67E5\u8BE2\u4E0D\u5B58\u5728\uFF1A%s +dialoginit.ERROR=\u521D\u59CB\u5316\u5F02\u5E38 +preferror.ERROR1=\u9996\u9009\u9879\u914D\u7F6E\u9519\u8BEF\uFF1A%s +norefindataset.ERROR1=\u4ECE\u6570\u636E\u96C6\u201C%s\u201D\u4E0B\u8F7D\u6587\u4EF6\u5931\u8D25\uFF0C\u6CA1\u6709\u627E\u5230\u5F15\u7528\u6587\u4EF6\u3002 +word.PAGECOUNT=\u5171 %s \u9875 +cancel=\u53D6\u6D88 +exeop.STATUS=\u6B63\u5728\u6267\u884C... +initop.STATUS=\u68C0\u67E5\u6570\u636E... +selectall=\u5168\u9009 +noflowkey.ERROR=\u6D41\u6C34\u7801\u952E\u503C\u4E0D\u53EF\u4E3A\u7A7A +wordfield_pagecount.NAME=\u9875\u6570 +nopropintype.ERROR2=\u5BF9\u8C61\u7C7B\u578B\u201C%s\u201D\u4E0D\u5B58\u5728\u5C5E\u6027\uFF1A%s +getflowno.ERROR1=\u83B7\u53D6\u6D41\u6C34\u7801\u5931\u8D25\uFF1A%s +formsave.ERRORTITLE=\u4FDD\u5B58\u6570\u636E\u51FA\u9519 +wordfield_pageno.NAME=\u9875\u7801 +wordfield_totalpagenominus1.NAME=\u603B\u9875\u7801\u51CF\u4E00 +wordfield_totalpagecount.NAME=\u603B\u9875\u6570 +exceltitlenorelateinfo.ERROR=\u6807\u9898\u884C\u6CA1\u6709\u89E3\u6790\u5230\u6620\u5C04\u5185\u5BB9 +selectProject=\u9009\u62E9\u9879\u76EE +proplocationnotdefined.ERROR1=\u672A\u77E5\u5C5E\u6027\u4F4D\u7F6E\u201C%s\u201D\uFF0C\u8BF7\u68C0\u67E5\u914D\u7F6E +excelnotitle.ERROR=\u672A\u627E\u5230\u5DE5\u4F5C\u8868\u4E2D\u7684\u6807\u9898\u884C +loadCompFromUid.Error2=\u52A0\u8F7D\u5BF9\u8C61\u201C%s\u201D\u5931\u8D25\uFF0CUID\=\u201C%s\u201D\u3002 +uploadfilewhencheckout.ERROR1=\u6570\u636E\u96C6\u201C%s\u201D\u5DF2\u7B7E\u51FA\uFF0C\u4E0A\u4F20\u6587\u4EF6\u5931\u8D25\u3002\u8BF7\u7B7E\u5165\u540E\u518D\u8FDB\u884C\u64CD\u4F5C\u3002 +wordfield_totalactualpagecountminus1.NAME=\u603B\u5B9E\u9645\u9875\u6570\u51CF\u4E00 +nodatainfile.ERROR1=\u6587\u4EF6\u4E2D\u6CA1\u6709\u6570\u636E\uFF1A%s +noexportdata.ERROR=\u6CA1\u6709\u6570\u636E\u53EF\u4EE5\u5BFC\u51FA +notscheduleadmin.INFO=\u53EA\u6709\u534F\u8C03\u8005\u624D\u80FD\u64CD\u4F5C +word.PAGENUM=\u7B2C %s \u9875 +error=\u9519\u8BEF +mergefile=\u5408\u5E76\u6587\u4EF6 +index=\u5E8F\u53F7 +ok=\u786E\u5B9A +forminit.ERRORTITLE=\u521D\u59CB\u5316\u754C\u9762\u5F02\u5E38 +wordfield_totalactualpagecount.NAME=\u603B\u5B9E\u9645\u9875\u6570 +requireprop.INFO1=\u8BF7\u586B\u5199\u5C5E\u6027\uFF1A%s +clear=\u6E05\u7A7A +functionnotavailable.INFO=\u6B64\u5BF9\u8C61\u4E0D\u53EF\u4F7F\u7528\u6B64\u529F\u80FD +multiuserbyid.ERROR1=\u901A\u8FC7id\u67E5\u8BE2\u5230\u591A\u4E2A\u7528\u6237\uFF1A%s +preparedata=\u51C6\u5907\u6570\u636E +dbconn.ERROR=\u8FDE\u63A5\u6570\u636E\u5E93\u5931\u8D25\u3002 +typenotfound.ERROR1=\u672A\u627E\u5230\u7C7B\u578B\uFF1A%s +filenotexist.ERROR1=\u6587\u4EF6\u4E0D\u5B58\u5728\uFF1A%s +wordfield_totalpagecountminus1.NAME=\u603B\u9875\u6570\u51CF\u4E00 +readdata=\u8BFB\u53D6\u6570\u636E +clearcache=\u6E05\u7406\u7F13\u5B58 +exportsuccess.INFO=\u5BFC\u51FA\u5B8C\u6210 +uploadfile=\u4E0A\u4F20\u6587\u4EF6 +propnotdefinedintype.ERROR2=\u5BF9\u8C61\u7C7B\u578B\u201C%s\u201D\u672A\u5B9A\u4E49\u5C5E\u6027\uFF1A%s +foldernotexist.ERROR1=\u6587\u4EF6\u5939\u4E0D\u5B58\u5728\uFF1A%s +info=\u63D0\u793A +search=\u67E5\u8BE2 +wordfield_totalpageno.NAME=\u603B\u9875\u7801 +multiuserbyname.ERROR1=\u901A\u8FC7\u59D3\u540D\u67E5\u8BE2\u5230\u591A\u4E2A\u7528\u6237\uFF1A%s +exportopenfile.INFO=\u5BFC\u51FA\u5B8C\u6210\uFF0C\u6253\u5F00\u6587\u4EF6\uFF1F +prefnotconfiged.ERROR1=\u672A\u914D\u7F6E\u9996\u9009\u9879\uFF1A%s +export=\u5BFC\u51FA diff --git a/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/xml/KXml.java b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/xml/KXml.java new file mode 100644 index 0000000..b5fbf09 --- /dev/null +++ b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/xml/KXml.java @@ -0,0 +1,116 @@ +package cn.net.connor.std.aifrcp.xml; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.OutputStreamWriter; +import java.io.StringWriter; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.InputSource; + +import com.teamcenter.rac.kernel.TCComponent; + +import cn.net.connor.std.aifrcp.util.KUtil; + +public class KXml { + + public static Document writeXml(KXmlConfigNode rootNode, TCComponent comp) throws Exception { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document doc = db.newDocument(); + Element newRootNode = rootNode.writeData(doc, comp); + doc.appendChild(newRootNode); + return doc; + } + + public static String writeToString(Document doc) throws Exception { + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); + StreamResult result = new StreamResult(new StringWriter()); + DOMSource source = new DOMSource(doc); + transformer.transform(source, result); + String xmlString = result.getWriter().toString(); + return xmlString; + } + + public static void writeToFile(Document doc, File outputFile, String fileEncoding) throws Exception { + if (outputFile == null || KUtil.isEmpty(fileEncoding) || doc == null) { + return; + } + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.setOutputProperty(OutputKeys.ENCODING, fileEncoding); + transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); + DOMSource source = new DOMSource(doc); + FileOutputStream os = new FileOutputStream(outputFile); + OutputStreamWriter writer = new OutputStreamWriter(os, fileEncoding); + StreamResult result = new StreamResult(writer); + transformer.transform(source, result); + os.flush(); + os.close(); + } + + public static KXmlConfigNode parseXmlTemplate(File xmlFile) throws Exception { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = null; + FileInputStream in = new FileInputStream(xmlFile); + try { + document = db.parse(in); + } catch (Exception e) { + e.printStackTrace(); + } + in.close(); + if (document == null) { + throw new Exception("Not valid xml format: " + xmlFile.getName()); + } + KXmlConfigNode rootNode = KXmlConfigNode.parse(document.getDocumentElement()); + if (rootNode == null) { + throw new Exception("Parse xml file failed: " + xmlFile.getName()); + } + return rootNode; + } + + public static KXmlNode parseXml(File xmlFile) throws Exception { + return parseXml(xmlFile, null); + } + + public static KXmlNode parseXml(File xmlFile, String encoding) throws Exception { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = null; + FileInputStream in = new FileInputStream(xmlFile); + try { + if(KUtil.isEmpty(encoding)) { + document = db.parse(in); + }else { + InputSource is = new InputSource(in); + is.setEncoding(encoding); + document = db.parse(is); + } + } catch (Exception e) { + e.printStackTrace(); + } + in.close(); + if (document == null) { + throw new Exception("Not valid xml format: " + xmlFile.getName()); + } + KXmlNode rootNode = KXmlNode.parse(document.getDocumentElement()); + if (rootNode == null) { + throw new Exception("Parse xml file failed: " + xmlFile.getName()); + } + return rootNode; + } + +} \ No newline at end of file diff --git a/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/xml/KXmlConfigNode.java b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/xml/KXmlConfigNode.java new file mode 100644 index 0000000..e98b18e --- /dev/null +++ b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/xml/KXmlConfigNode.java @@ -0,0 +1,145 @@ +package cn.net.connor.std.aifrcp.xml; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import com.teamcenter.rac.kernel.TCComponent; + +import cn.net.connor.std.aifrcp.util.KUtil; + +public class KXmlConfigNode { + public static final String ATTR_PATH = "path"; + public static final String ATTR_PROPERTY = "property"; + public static final String ATTR_REMOVEPARENTIFNOCHILD = "remove_parent_if_no_child"; + // 标签名称 + private String name; + // 标签值 + private String value; + // 属性 + private Map attrs; + // TC对象路径 bom bop rel & type + private String path; + // 属性配置 + private String property; + // 子节点 + private List children; + // 如果为空则删除父节点 + private boolean removeParentIfNoChild; + + private KXmlConfigNode(String name, String value, String path, String property, Map attrs, List children, boolean removeParentIfNoChild) { + super(); + this.name = name; + this.value = KUtil.isEmpty(value) ? "" : value; + this.path = KUtil.isEmpty(path) ? null : path; + this.property = KUtil.isEmpty(property) ? null : property; + this.children = children; + this.removeParentIfNoChild = removeParentIfNoChild; + this.attrs = attrs; + } + + public Element writeData(Document doc, TCComponent comp) throws Exception { + Element element = doc.createElement(name); + // 填写属性 + String propertyValue = value; + if (property != null) { + propertyValue = KUtil.getPropValueByPath(comp, property, ";"); + } + for (String attrName : attrs.keySet()) { + String attrValue = attrs.get(attrName); + element.setAttribute(attrName, attrValue); + } + element.setTextContent(propertyValue); + int childNodeCnt = children.size(); + int childCnt = 0; + for (int i = 0; i < childNodeCnt; i++) { + KXmlConfigNode childNode = children.get(i); + if (childNode.path != null) { + // 解析子节点路径,并进行分支 + List childComps = new ArrayList<>(); + KUtil.getChildrenByPath(comp, childNode.path, null, childComps); + int childCompCnt = childComps.size(); + childCnt += childCompCnt; + for (int j = 0; j < childCompCnt; j++) { + TCComponent childComp = childComps.get(j); + Element childElement = childNode.writeData(doc, childComp); + if (childElement != null) { + element.appendChild(childElement); + } + } + } else { + Element childElement = childNode.writeData(doc, comp); + if (childElement != null) { + element.appendChild(childElement); + } else if (childNode.removeParentIfNoChild) { + return null; + } + } + } + if (removeParentIfNoChild && childCnt == 0) { + return null; + } + return element; + } + + public void print(String space) { + System.out.print(String.format("\n%s<%s%s%s>%s", space, name, (path == null ? "" : (" " + ATTR_PATH + "=\"" + path + "\"")), + (property == null ? "" : (" " + ATTR_PROPERTY + "=\"" + property + "\"")), value)); + int childCnt = children.size(); + String childSpace = space + " "; + for (int i = 0; i < childCnt; i++) { + children.get(i).print(childSpace); + } + System.out.print(String.format("%s", childCnt == 0 ? "" : ("\n" + space), name)); + } + + public static KXmlConfigNode parse(Element node) throws Exception { + if (node == null) { + return null; + } + String name = node.getNodeName(); + String value = null; + Map attrs = new HashMap(); + NamedNodeMap nodeAttrMap = node.getAttributes(); + int attrCnt = nodeAttrMap.getLength(); + if (attrCnt > 0) { + for (int i = 0; i < attrCnt; i++) { + Node attr = nodeAttrMap.item(i); + String attrName = attr.getNodeName(); + String attrValue = attr.getNodeValue(); + attrs.put(attrName, attrValue); + attrs.put(attrName.toLowerCase(), attrValue); + } + } + String path = attrs.remove(ATTR_PATH); + String property = attrs.remove(ATTR_PROPERTY); + boolean removeParentIfNoChild = "true".equalsIgnoreCase(node.getAttribute(ATTR_REMOVEPARENTIFNOCHILD)); + List children = new ArrayList<>(); + NodeList cc = node.getChildNodes(); + int childCnt = cc == null ? 0 : cc.getLength(); + for (int i = 0; i < childCnt; i++) { + Node child = cc.item(i); + if (child.getNodeType() == Node.TEXT_NODE) { + value = child.getTextContent(); + continue; + } + if (child.getNodeType() != Node.ELEMENT_NODE) { + continue; + } + KXmlConfigNode childNode = KXmlConfigNode.parse((Element) child); + if (childNode == null) { + continue; + } + children.add(childNode); + } + return new KXmlConfigNode(name, value, path, property, attrs, children, removeParentIfNoChild); + } + +} \ No newline at end of file diff --git a/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/xml/KXmlNode.java b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/xml/KXmlNode.java new file mode 100644 index 0000000..0be74fa --- /dev/null +++ b/cn.net.connor.std.aifrcp/src/cn/net/connor/std/aifrcp/xml/KXmlNode.java @@ -0,0 +1,116 @@ +package cn.net.connor.std.aifrcp.xml; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import cn.net.connor.std.aifrcp.util.KUtil; + +public class KXmlNode { + // 标签名称 + private String name; + // 标签值 + private String value; + // 属性 + private Map attrs; + // 子节点 + private List children; + + public KXmlNode(String name, String value, Map attrs, List children) { + super(); + this.name = name; + this.value = value; + this.attrs = attrs; + this.children = children; + } + + public String getAttr(String attrName) { + if (attrs != null && attrs.containsKey(attrName)) { + return attrs.get(attrName); + } + return null; + } + + public String getName() { + return name; + } + + public String getValue() { + return value; + } + + public List getChildren(){ + return children; + } + + public KXmlNode findNode(String nodeName) { + if(KUtil.isEmpty(nodeName)) { + return null; + } + int childCnt = children==null?0:children.size(); + for(int i=0; i%s", space, name, (attrs == null ? "" : attrs.toString()), value)); + int childCnt = children.size(); + String childSpace = space + " "; + for (int i = 0; i < childCnt; i++) { + children.get(i).print(childSpace); + } + System.out.print(String.format("%s", childCnt == 0 ? "" : ("\n" + space), name)); + } + + public static KXmlNode parse(Element node) throws Exception { + if (node == null) { + return null; + } + String name = node.getNodeName(); + String value = null; + Map attrs = null; + NamedNodeMap nodeAttrMap = node.getAttributes(); + int attrCnt = nodeAttrMap.getLength(); + if (attrCnt > 0) { + attrs = new HashMap(); + for (int i = 0; i < attrCnt; i++) { + Node attr = nodeAttrMap.item(i); + String attrName = attr.getNodeName(); + String attrValue = attr.getNodeValue(); + attrs.put(attrName, attrValue); + attrs.put(attrName.toLowerCase(), attrValue); + } + } + List children = new ArrayList<>(); + NodeList cc = node.getChildNodes(); + int childCnt = cc == null ? 0 : cc.getLength(); + for (int i = 0; i < childCnt; i++) { + Node child = cc.item(i); + if (child.getNodeType() == Node.TEXT_NODE || child.getNodeType() == Node.CDATA_SECTION_NODE) { + value = child.getTextContent(); + continue; + } + if (child.getNodeType() != Node.ELEMENT_NODE) { + continue; + } + KXmlNode childNode = KXmlNode.parse((Element) child); + if (childNode == null) { + continue; + } + children.add(childNode); + } + return new KXmlNode(name, value, attrs, children); + } + +} \ No newline at end of file diff --git a/cn.net.connor.std.fx/.classpath b/cn.net.connor.std.fx/.classpath new file mode 100644 index 0000000..abf4437 --- /dev/null +++ b/cn.net.connor.std.fx/.classpath @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/cn.net.connor.std.fx/.gitignore b/cn.net.connor.std.fx/.gitignore new file mode 100644 index 0000000..ae3c172 --- /dev/null +++ b/cn.net.connor.std.fx/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/cn.net.connor.std.fx/.project b/cn.net.connor.std.fx/.project new file mode 100644 index 0000000..0c5e809 --- /dev/null +++ b/cn.net.connor.std.fx/.project @@ -0,0 +1,28 @@ + + + cn.net.connor.std.fx + + + + + + 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/cn.net.connor.std.fx/.settings/org.eclipse.jdt.core.prefs b/cn.net.connor.std.fx/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..9f6ece8 --- /dev/null +++ b/cn.net.connor.std.fx/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.release=disabled +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/cn.net.connor.std.fx/8u241/jfxrt.jar b/cn.net.connor.std.fx/8u241/jfxrt.jar new file mode 100644 index 0000000..275c31a Binary files /dev/null and b/cn.net.connor.std.fx/8u241/jfxrt.jar differ diff --git a/cn.net.connor.std.fx/8u241/jfxswt.jar b/cn.net.connor.std.fx/8u241/jfxswt.jar new file mode 100644 index 0000000..2c5c7f1 Binary files /dev/null and b/cn.net.connor.std.fx/8u241/jfxswt.jar differ diff --git a/cn.net.connor.std.fx/8u281/jfxrt.jar b/cn.net.connor.std.fx/8u281/jfxrt.jar new file mode 100644 index 0000000..b226d36 Binary files /dev/null and b/cn.net.connor.std.fx/8u281/jfxrt.jar differ diff --git a/cn.net.connor.std.fx/8u281/jfxswt.jar b/cn.net.connor.std.fx/8u281/jfxswt.jar new file mode 100644 index 0000000..84675b1 Binary files /dev/null and b/cn.net.connor.std.fx/8u281/jfxswt.jar differ diff --git a/cn.net.connor.std.fx/META-INF/MANIFEST.MF b/cn.net.connor.std.fx/META-INF/MANIFEST.MF new file mode 100644 index 0000000..650d51c --- /dev/null +++ b/cn.net.connor.std.fx/META-INF/MANIFEST.MF @@ -0,0 +1,195 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Fx +Bundle-SymbolicName: cn.net.connor.std.fx +Bundle-Version: 13000.1.0 +Bundle-Activator: cn.net.connor.std.fx.Activator +Eclipse-BuddyPolicy: registered +Require-Bundle: org.eclipse.ui, + org.eclipse.core.runtime, + com.teamcenter.rac.util, + com.teamcenter.rac.kernel, + com.teamcenter.rac.common +Bundle-RequiredExecutionEnvironment: JavaSE-1.8 +Automatic-Module-Name: cn.net.connor.std.fx +Bundle-ActivationPolicy: lazy +Bundle-ClassPath: lib/jfxrt.jar, + lib/jfxswt.jar, + . +Export-Package: cn.net.connor.std.fx, + com.sun.deploy.uitoolkit.impl.fx, + com.sun.deploy.uitoolkit.impl.fx.ui, + com.sun.deploy.uitoolkit.impl.fx.ui.resources, + com.sun.glass.events, + com.sun.glass.ui, + com.sun.glass.ui.delegate, + com.sun.glass.ui.win, + com.sun.glass.utils, + com.sun.javafx, + com.sun.javafx.animation, + com.sun.javafx.applet, + com.sun.javafx.application, + com.sun.javafx.beans, + com.sun.javafx.beans.event, + com.sun.javafx.binding, + com.sun.javafx.charts, + com.sun.javafx.collections, + com.sun.javafx.css, + com.sun.javafx.css.converters, + com.sun.javafx.css.parser, + com.sun.javafx.cursor, + com.sun.javafx.effect, + com.sun.javafx.embed, + com.sun.javafx.embed.swing, + com.sun.javafx.event, + com.sun.javafx.font, + com.sun.javafx.font.coretext, + com.sun.javafx.font.directwrite, + com.sun.javafx.font.freetype, + com.sun.javafx.fxml, + com.sun.javafx.fxml.builder, + com.sun.javafx.fxml.expression, + com.sun.javafx.geom, + com.sun.javafx.geom.transform, + com.sun.javafx.geometry, + com.sun.javafx.iio, + com.sun.javafx.iio.bmp, + com.sun.javafx.iio.common, + com.sun.javafx.iio.gif, + com.sun.javafx.iio.ios, + com.sun.javafx.iio.jpeg, + com.sun.javafx.iio.png, + com.sun.javafx.image, + com.sun.javafx.image.impl, + com.sun.javafx.jmx, + com.sun.javafx.logging, + com.sun.javafx.media, + com.sun.javafx.menu, + com.sun.javafx.perf, + com.sun.javafx.print, + com.sun.javafx.property, + com.sun.javafx.property.adapter, + com.sun.javafx.robot, + com.sun.javafx.robot.impl, + com.sun.javafx.runtime, + com.sun.javafx.runtime.async, + com.sun.javafx.runtime.eula, + com.sun.javafx.scene, + com.sun.javafx.scene.control, + com.sun.javafx.scene.control.behavior, + com.sun.javafx.scene.control.skin, + com.sun.javafx.scene.control.skin.resources, + com.sun.javafx.scene.input, + com.sun.javafx.scene.layout.region, + com.sun.javafx.scene.paint, + com.sun.javafx.scene.shape, + com.sun.javafx.scene.text, + com.sun.javafx.scene.transform, + com.sun.javafx.scene.traversal, + com.sun.javafx.scene.web, + com.sun.javafx.scene.web.behavior, + com.sun.javafx.scene.web.skin, + com.sun.javafx.sg.prism, + com.sun.javafx.sg.prism.web, + com.sun.javafx.stage, + com.sun.javafx.text, + com.sun.javafx.tk, + com.sun.javafx.tk.quantum, + com.sun.javafx.util, + com.sun.javafx.webkit, + com.sun.javafx.webkit.prism, + com.sun.javafx.webkit.prism.theme, + com.sun.javafx.webkit.theme, + com.sun.media.jfxmedia, + com.sun.media.jfxmedia.control, + com.sun.media.jfxmedia.effects, + com.sun.media.jfxmedia.events, + com.sun.media.jfxmedia.locator, + com.sun.media.jfxmedia.logging, + com.sun.media.jfxmedia.track, + com.sun.media.jfxmediaimpl, + com.sun.media.jfxmediaimpl.platform, + com.sun.media.jfxmediaimpl.platform.gstreamer, + com.sun.media.jfxmediaimpl.platform.ios, + com.sun.media.jfxmediaimpl.platform.java, + com.sun.media.jfxmediaimpl.platform.osx, + com.sun.openpisces, + com.sun.pisces, + com.sun.prism, + com.sun.prism.d3d, + com.sun.prism.image, + com.sun.prism.impl, + com.sun.prism.impl.packrect, + com.sun.prism.impl.paint, + com.sun.prism.impl.ps, + com.sun.prism.impl.shape, + com.sun.prism.j2d, + com.sun.prism.j2d.paint, + com.sun.prism.j2d.print, + com.sun.prism.paint, + com.sun.prism.ps, + com.sun.prism.shader, + com.sun.prism.shape, + com.sun.prism.sw, + com.sun.scenario, + com.sun.scenario.animation, + com.sun.scenario.animation.shared, + com.sun.scenario.effect, + com.sun.scenario.effect.impl, + com.sun.scenario.effect.impl.hw, + com.sun.scenario.effect.impl.hw.d3d, + com.sun.scenario.effect.impl.prism, + com.sun.scenario.effect.impl.prism.ps, + com.sun.scenario.effect.impl.prism.sw, + com.sun.scenario.effect.impl.state, + com.sun.scenario.effect.impl.sw, + com.sun.scenario.effect.impl.sw.java, + com.sun.scenario.effect.impl.sw.sse, + com.sun.scenario.effect.light, + com.sun.webkit, + com.sun.webkit.dom, + com.sun.webkit.event, + com.sun.webkit.graphics, + com.sun.webkit.network, + com.sun.webkit.network.about, + com.sun.webkit.network.data, + com.sun.webkit.perf, + com.sun.webkit.plugin, + com.sun.webkit.security, + com.sun.webkit.text, + javafx.animation, + javafx.application, + javafx.beans, + javafx.beans.binding, + javafx.beans.property, + javafx.beans.property.adapter, + javafx.beans.value, + javafx.collections, + javafx.collections.transformation, + javafx.concurrent, + javafx.css, + javafx.embed.swing, + javafx.embed.swt, + javafx.event, + javafx.fxml, + javafx.geometry, + javafx.print, + javafx.scene, + javafx.scene.canvas, + javafx.scene.chart, + javafx.scene.control, + javafx.scene.control.cell, + javafx.scene.effect, + javafx.scene.image, + javafx.scene.input, + javafx.scene.layout, + javafx.scene.media, + javafx.scene.paint, + javafx.scene.shape, + javafx.scene.text, + javafx.scene.transform, + javafx.scene.web, + javafx.stage, + javafx.util, + javafx.util.converter, + netscape.javascript diff --git a/cn.net.connor.std.fx/build.properties b/cn.net.connor.std.fx/build.properties new file mode 100644 index 0000000..afc7d90 --- /dev/null +++ b/cn.net.connor.std.fx/build.properties @@ -0,0 +1,6 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + lib/jfxrt.jar,\ + lib/jfxswt.jar diff --git a/cn.net.connor.std.fx/lib/jfxrt.jar b/cn.net.connor.std.fx/lib/jfxrt.jar new file mode 100644 index 0000000..275c31a Binary files /dev/null and b/cn.net.connor.std.fx/lib/jfxrt.jar differ diff --git a/cn.net.connor.std.fx/lib/jfxswt.jar b/cn.net.connor.std.fx/lib/jfxswt.jar new file mode 100644 index 0000000..2c5c7f1 Binary files /dev/null and b/cn.net.connor.std.fx/lib/jfxswt.jar differ diff --git a/cn.net.connor.std.fx/src/cn/net/connor/std/fx/Activator.java b/cn.net.connor.std.fx/src/cn/net/connor/std/fx/Activator.java new file mode 100644 index 0000000..52f139d --- /dev/null +++ b/cn.net.connor.std.fx/src/cn/net/connor/std/fx/Activator.java @@ -0,0 +1,44 @@ +package cn.net.connor.std.fx; + +import org.eclipse.ui.plugin.AbstractUIPlugin; +import org.osgi.framework.BundleContext; + +/** + * The activator class controls the plug-in life cycle + */ +public class Activator extends AbstractUIPlugin { + + // The plug-in ID + public static final String PLUGIN_ID = "cn.net.connor.std.fx"; //$NON-NLS-1$ + + // The shared instance + private static Activator plugin; + + /** + * The constructor + */ + public Activator() { + } + + @Override + public void start(BundleContext context) throws Exception { + super.start(context); + plugin = this; + } + + @Override + public void stop(BundleContext context) throws Exception { + plugin = null; + super.stop(context); + } + + /** + * Returns the shared instance + * + * @return the shared instance + */ + public static Activator getDefault() { + return plugin; + } + +} diff --git a/cn.net.connor.std.fx/src/cn/net/connor/std/fx/KFXEditableDateTableCell.java b/cn.net.connor.std.fx/src/cn/net/connor/std/fx/KFXEditableDateTableCell.java new file mode 100644 index 0000000..8eac637 --- /dev/null +++ b/cn.net.connor.std.fx/src/cn/net/connor/std/fx/KFXEditableDateTableCell.java @@ -0,0 +1,153 @@ +package cn.net.connor.std.fx; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.Date; + +import com.teamcenter.rac.treetable.SwingTextContextActivator; + +import javafx.beans.value.ChangeListener; +import javafx.beans.value.ObservableValue; +import javafx.event.Event; +import javafx.scene.control.DatePicker; +import javafx.scene.control.TableCell; +import javafx.scene.control.TableColumn; +import javafx.scene.control.TableColumn.CellEditEvent; +import javafx.scene.control.TablePosition; +import javafx.scene.control.TableView; +import javafx.scene.input.KeyCode; +public class KFXEditableDateTableCell extends TableCell { + protected DatePicker textField; + public static final ZoneId zoneId = ZoneId.systemDefault(); + public static Date localDateToDate(LocalDate localDate) { + if (localDate == null) { + return null; + } + ZonedDateTime zdt = localDate.atStartOfDay(zoneId); + Date date = Date.from(zdt.toInstant()); + return date; + } + + public static LocalDate dateToLocalDate(Date date) { + if (date == null) { + return null; + } + Instant instant = date.toInstant(); + LocalDate localDate = instant.atZone(zoneId).toLocalDate(); + return localDate; + } + + + protected ChangeListener changeListener = (obs,ov, nv) -> { + if (!nv) { + commitEdit(localDateToDate(textField.getValue())); + } + }; + + public KFXEditableDateTableCell () { + + } + + @Override + public void startEdit() { + if(editableProperty().get()){ + if (!isEmpty()) { + super.startEdit(); + createTextField(); + setText(null); + setGraphic(textField); + textField.requestFocus(); + } + } + } + + @Override + public void cancelEdit() { + super.cancelEdit(); + setText(getDateString()); + setGraphic(null); + } + + @Override + public void updateItem(Date item, boolean empty) { + super.updateItem(item, empty); + if (empty) { + setText(null); + setGraphic(null); + } else { + if (isEditing()) { + if (textField != null) { + System.out.println(">> "+getItem()); + textField.setValue(dateToLocalDate(getItem())); + //textField.selectAll(); + } + setText(null); + setGraphic(textField); + } else { + setText(getDateString()); + setGraphic(null); + } + } + } + + protected void createTextField() { + textField = new DatePicker(); + textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2); + textField.focusedProperty().addListener(changeListener); + textField.setOnAction(evt -> commitEdit(localDateToDate(textField.getValue()))); + textField.focusedProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue arg0, Boolean arg1, Boolean arg2) { + if(arg2) { + SwingTextContextActivator.instance().activateContext(); + }else { + SwingTextContextActivator.instance().deactivateContext(); + } + } + }); + textField.setOnKeyPressed((ke) -> { + if (ke.getCode().equals(KeyCode.ESCAPE)) { + textField.focusedProperty().removeListener(changeListener); + cancelEdit(); + } + if (ke.getCode().equals(KeyCode.TAB)) { + commitEdit(localDateToDate(textField.getValue())); + } + }); + } + + public static final DateFormat DF = new SimpleDateFormat("yyyy-MM-dd"); + + protected String getDateString() { + Date d = getItem(); + return d==null?"":DF.format(d); + } + + @Override + @SuppressWarnings({"unchecked", "rawtypes"}) + public void commitEdit(Date item) { + textField.focusedProperty().removeListener(changeListener); + if (isEditing()) { + super.commitEdit(item); + } else { + final TableView table = getTableView(); + if (table != null) { + TablePosition position = new TablePosition(getTableView(), + getTableRow().getIndex(), getTableColumn()); + CellEditEvent editEvent = new CellEditEvent(table, position, + TableColumn.editCommitEvent(), item); + Event.fireEvent(getTableColumn(), editEvent); + } + updateItem(item, false); + if (table != null) { + table.edit(-1, null); + } + // super.commitEdit(item); // 20201217 bug fix + } + } + +} diff --git a/cn.net.connor.std.fx/src/cn/net/connor/std/fx/KFXEditableStringAreaTableCell.java b/cn.net.connor.std.fx/src/cn/net/connor/std/fx/KFXEditableStringAreaTableCell.java new file mode 100644 index 0000000..6a3203f --- /dev/null +++ b/cn.net.connor.std.fx/src/cn/net/connor/std/fx/KFXEditableStringAreaTableCell.java @@ -0,0 +1,205 @@ +package cn.net.connor.std.fx; + +import com.teamcenter.rac.treetable.SwingTextContextActivator; + +import javafx.beans.value.ChangeListener; +import javafx.beans.value.ObservableValue; +import javafx.event.Event; +import javafx.scene.control.TableCell; +import javafx.scene.control.TableColumn; +import javafx.scene.control.TableColumn.CellEditEvent; +import javafx.scene.control.TablePosition; +import javafx.scene.control.TableView; +import javafx.scene.control.TextArea; +import javafx.scene.control.Tooltip; +import javafx.scene.input.KeyCode; +import javafx.scene.text.Text; + +/** + * select color: + * + * .table-row-cell .ktext { -fx-fill: black; } + * + * .table-row-cell:selected .ktext { -fx-fill: white; } + * + * .table-cell .ktext { -fx-fill: black; } + * + * .table-cell:selected .ktext { -fx-fill: white; } + * + * @author Administrator + * + * @param + * @param + */ + +public class KFXEditableStringAreaTableCell extends TableCell { + protected TextArea textArea; + protected boolean showToolTip = false; + protected ChangeListener changeListener = (obs, ov, nv) -> { + if (!nv) { + commitEdit(textArea.getText()); + } + }; + private Text text; + private KFXTextLocator textLocator; + + public KFXEditableStringAreaTableCell() { + super(); + } + + public KFXEditableStringAreaTableCell(KFXTextLocator textLocator) { + super(); + this.textLocator = textLocator; + } + + public KFXEditableStringAreaTableCell(boolean showToolTip) { + super(); + this.showToolTip = showToolTip; + } + + @Override + public void startEdit() { + if (editableProperty().get()) { + if (!isEmpty()) { + super.startEdit(); + createTextField(); + setText(null); + setGraphic(textArea); + textArea.requestFocus(); + } + } + } + + public void startEdit(int temp) { + if (isEditing()) { + System.out.println("=====>" + temp); + textArea.positionCaret(temp); + } + } + + @Override + public void cancelEdit() { + super.cancelEdit(); + // setText((String) getItem()); + // setGraphic(null); + setGraphic(text); + } + + @Override + public void updateItem(String item, boolean empty) { + super.updateItem(item, empty); + if (text == null) { + text = new Text(); + text.wrappingWidthProperty().bind(getTableColumn().widthProperty().subtract(20)); + text.textProperty().bind(itemProperty()); + text.getStyleClass().add("ktext"); + } + + // text.setStyle("-fx-fill:"+(getTableRow().isSelected()?"#FFF;":"#000;")); + if (empty) { + setText(null); + setGraphic(null); + } else { + if (isEditing()) { + if (textArea != null) { + textArea.setText(getString()); + // textArea.selectAll(); + } + setText(null); + setGraphic(textArea); + } else { + setGraphic(text); + // setText(getString()); + // setGraphic(null); + } + } + if (showToolTip) { + String str = getString(); + if (!"".equals(str)) { + Tooltip tt = new Tooltip(str); + tt.setWrapText(true); + tt.setMaxWidth(600); + setTooltip(tt); + } + } + } + + protected void createTextField() { + if (textArea == null) { + textArea = new TextArea(); + textArea.setWrapText(true); + textArea.setOnKeyPressed((ke) -> { + if (ke.getCode().equals(KeyCode.ESCAPE)) { + textArea.focusedProperty().removeListener(changeListener); + cancelEdit(); + } + if (ke.getCode().equals(KeyCode.TAB)) { + commitEdit(textArea.getText()); + } + }); + textArea.focusedProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue arg0, Boolean arg1, Boolean arg2) { + if(arg2) { + SwingTextContextActivator.instance().activateContext(); + }else { + SwingTextContextActivator.instance().deactivateContext(); + } + } + }); + if (textLocator != null) { + textArea.focusedProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, Boolean oldValue, Boolean newValue) { + if (newValue) { + System.out.println("focus get:" + getTableColumn().getText() + ":" + getTableRow().getIndex()); + textLocator.updateControl(KFXEditableStringAreaTableCell.this); + } else { + System.out.println("focus lost" + getTableColumn().getText() + ":" + getTableRow().getIndex()); + } + } + }); + textArea.caretPositionProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, Number oldValue, Number newValue) { + if (textArea.isFocused()) { + System.out.println("caret: " + oldValue + " -> " + newValue); + textLocator.currentCaret = newValue.intValue(); + } + } + }); + } + } + textArea.setText(getString()); + textArea.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2); + textArea.setPrefHeight(this.getHeight()); + textArea.focusedProperty().addListener(changeListener); + // textArea.setOnAction(evt -> commitEdit(textField.getText())); + } + + protected String getString() { + return getItem() == null ? "" : getItem().toString(); + } + + @Override + @SuppressWarnings({ "unchecked", "rawtypes" }) + public void commitEdit(String item) { + textArea.focusedProperty().removeListener(changeListener); + if (isEditing()) { + super.commitEdit(item); + } else { + final TableView table = getTableView(); + if (table != null) { + TablePosition position = new TablePosition(getTableView(), getTableRow().getIndex(), getTableColumn()); + CellEditEvent editEvent = new CellEditEvent(table, position, TableColumn.editCommitEvent(), item); + Event.fireEvent(getTableColumn(), editEvent); + } + updateItem(item, false); + if (table != null) { + table.edit(-1, null); + } + // super.commitEdit(item); // 20201217 bug fix + } + } + +} diff --git a/cn.net.connor.std.fx/src/cn/net/connor/std/fx/KFXEditableStringTableCell.java b/cn.net.connor.std.fx/src/cn/net/connor/std/fx/KFXEditableStringTableCell.java new file mode 100644 index 0000000..96ae99f --- /dev/null +++ b/cn.net.connor.std.fx/src/cn/net/connor/std/fx/KFXEditableStringTableCell.java @@ -0,0 +1,139 @@ +package cn.net.connor.std.fx; + +import com.teamcenter.rac.treetable.SwingTextContextActivator; + +import javafx.beans.value.ChangeListener; +import javafx.beans.value.ObservableValue; +import javafx.event.Event; +import javafx.scene.control.TableCell; +import javafx.scene.control.TableColumn; +import javafx.scene.control.TableColumn.CellEditEvent; +import javafx.scene.control.TablePosition; +import javafx.scene.control.TableView; +import javafx.scene.control.TextField; +import javafx.scene.control.Tooltip; +import javafx.scene.input.KeyCode; +public class KFXEditableStringTableCell extends TableCell { + protected TextField textField; + protected boolean showToolTip = false; + protected ChangeListener changeListener = (obs,ov, nv) -> { + if (!nv) { + commitEdit(textField.getText()); + } + }; + + public KFXEditableStringTableCell () { + + } + + public KFXEditableStringTableCell (boolean showToolTip) { + this.showToolTip=showToolTip; + } + + @Override + public void startEdit() { + if(editableProperty().get()){ + if (!isEmpty()) { + super.startEdit(); + createTextField(); + setText(null); + setGraphic(textField); + textField.requestFocus(); + } + } + } + + @Override + public void cancelEdit() { + super.cancelEdit(); + setText((String) getItem()); + setGraphic(null); + } + + @Override + public void updateItem(String item, boolean empty) { + super.updateItem(item, empty); + + if (empty) { + setText(null); + setGraphic(null); + } else { + if (isEditing()) { + if (textField != null) { + textField.setText(getString()); + textField.selectAll(); + } + setText(null); + setGraphic(textField); + } else { + setText(getString()); + setGraphic(null); + } + } + if(showToolTip) { + String str = getString(); + if(!"".equals(str)) { + Tooltip tt = new Tooltip(str); + tt.setWrapText(true); + tt.setMaxWidth(600); + setTooltip(tt); + } + } + } + + protected void createTextField() { + textField = new TextField(getString()); + textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2); + textField.focusedProperty().addListener(changeListener); + textField.setOnAction(evt -> commitEdit(textField.getText())); + textField.focusedProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue arg0, Boolean arg1, Boolean arg2) { + if(arg2) { + SwingTextContextActivator.instance().activateContext(); + }else { + SwingTextContextActivator.instance().deactivateContext(); + } + } + }); + textField.setOnKeyPressed((ke) -> { + if (ke.getCode().equals(KeyCode.ESCAPE)) { + textField.focusedProperty().removeListener(changeListener); + cancelEdit(); + } + if (ke.getCode().equals(KeyCode.TAB)) { + commitEdit(textField.getText()); + } + }); + } + + + + protected String getString() { + return getItem() == null ? "" : getItem().toString(); + } + + @Override + @SuppressWarnings({"unchecked", "rawtypes"}) + public void commitEdit(String item) { + textField.focusedProperty().removeListener(changeListener); + if (isEditing()) { + super.commitEdit(item); + } else { + final TableView table = getTableView(); + if (table != null) { + TablePosition position = new TablePosition(getTableView(), + getTableRow().getIndex(), getTableColumn()); + CellEditEvent editEvent = new CellEditEvent(table, position, + TableColumn.editCommitEvent(), item); + Event.fireEvent(getTableColumn(), editEvent); + } + updateItem(item, false); + if (table != null) { + table.edit(-1, null); + } + // super.commitEdit(item); // 20201217 bug fix + } + } + +} diff --git a/cn.net.connor.std.fx/src/cn/net/connor/std/fx/KFXPanel.java b/cn.net.connor.std.fx/src/cn/net/connor/std/fx/KFXPanel.java new file mode 100644 index 0000000..5ba0e9a --- /dev/null +++ b/cn.net.connor.std.fx/src/cn/net/connor/std/fx/KFXPanel.java @@ -0,0 +1,167 @@ +package cn.net.connor.std.fx; + +import java.awt.Window; + +import com.sun.javafx.util.Logging; +import com.teamcenter.rac.util.MessageBox; + +import javafx.application.Application; +import javafx.application.Platform; +import javafx.fxml.FXMLLoader; +import javafx.scene.Parent; +import javafx.scene.Scene; +import javafx.scene.control.Alert; +import javafx.scene.control.Alert.AlertType; +import javafx.stage.Stage; +import sun.util.logging.PlatformLogger.Level; + +public abstract class KFXPanel extends Application { + + static { + Platform.setImplicitExit(false); + Logging.getCSSLogger().setLevel(Level.OFF); + } + + //private static KFXPanel SINGLETON; + +// public static KFXPanel getSingleton(Class c, String css) { +// if (SINGLETON == null) { +// SINGLETON = new KFXPanel(c, css); +// } +// return SINGLETON; +// } +// +// public static KFXPanel getSingleton() { +// if (SINGLETON == null) { +// SINGLETON = new KFXPanel(); +// } +// return SINGLETON; +// } +// public static KFXPanel getSingleton(AbstractAIFDialog dialog, Class c, String css) { +// if (SINGLETON == null) { +// SINGLETON = new KFXPanel(dialog, c, css); +// } +// return SINGLETON; +// } +// +// public static KFXPanel getSingleton(AbstractAIFDialog dialog) { +// if (SINGLETON == null) { +// SINGLETON = new KFXPanel(dialog); +// } +// return SINGLETON; +// } + +// public KFXPanel() { +// initUI(); +// } +// +// public KFXPanel(Class c, String css) { +// this.cssForm = c.getResource(css).toExternalForm(); +// initUI(); +// } + + public KFXPanel(Window dialog) { + setParentDialog(dialog); + initUI(); + initData(); + } + + public KFXPanel(Window dialog, Class c, String css) { + setParentDialog(dialog); + this.cssForm = c.getResource(css).toExternalForm(); + initUI(); + initData(); + } + + protected Scene scene; + protected KFXPanelController aifController; + protected Parent root; + protected String cssForm; + protected Window parentDialog; + + public void setParentDialog(Window dialog) { + this.parentDialog = dialog; + } + + public Window getParentDialog() { + return this.parentDialog; + } + + public Parent getRoot() { + return root; + } + + public KFXPanelController getController() { + return aifController; + } + + + public Scene getScene() { + if(scene==null) { + scene = new Scene(root); + scene.setFill(null); + } + return scene; + } + + public void initData() { + try { + aifController.initData(this); + } catch (Exception e) { + e.printStackTrace(); + post(parentDialog,e.getMessage(),"",MessageBox.ERROR); + } + } + + protected void initUI() { + try { + FXMLLoader fxmlLoader = new FXMLLoader(); + String resource = this.getClass().getSimpleName() + ".fxml"; + //System.out.println("Load Resource: "+resource); + fxmlLoader.setLocation(this.getClass().getResource(resource)); + root = fxmlLoader.load(); + aifController = fxmlLoader.getController(); + // primaryStage.initStyle(StageStyle.TRANSPARENT); + if (cssForm != null) { + root.getStylesheets().add(cssForm); + } + } catch (Exception e) { + e.printStackTrace(); + post(parentDialog,e.getMessage(),"",MessageBox.ERROR); + } + } + + public static void post(Window dialog,String msg,String title,int msgType) { + if(dialog==null) { + Platform.runLater(new Runnable() { + @Override + public void run() { + Alert alert = new Alert(AlertType.INFORMATION); + alert.setTitle(title); + alert.setHeaderText(""); + alert.setContentText(msg); + alert.showAndWait(); + } + }); + }else { + MessageBox.post(dialog, msg,title,msgType); + } + } + + + @Override + public void start(Stage primaryStage) throws Exception { + initUI(); + initData(); + primaryStage.setScene(getScene()); + primaryStage.show(); + } + + /** + * Run as javafx application to test ui + * @param args + */ + public static void main(String[] args) { + launch(args); + } +} diff --git a/cn.net.connor.std.fx/src/cn/net/connor/std/fx/KFXPanelController.java b/cn.net.connor.std.fx/src/cn/net/connor/std/fx/KFXPanelController.java new file mode 100644 index 0000000..6963f9d --- /dev/null +++ b/cn.net.connor.std.fx/src/cn/net/connor/std/fx/KFXPanelController.java @@ -0,0 +1,29 @@ +package cn.net.connor.std.fx; + +import javafx.application.Platform; +import javafx.fxml.FXML; +import javafx.scene.layout.AnchorPane; + +public abstract class KFXPanelController { + + @FXML + protected AnchorPane coverPane; + + public abstract void initData(KFXPanel panel) throws Exception; + + public void setCoverVisible(boolean visible) { + if (coverPane != null) { + Platform.runLater(new Runnable() { + @Override + public void run() { + coverPane.setVisible(visible); + } + }); + try { + Thread.sleep(10); + } catch (Exception e) { + e.printStackTrace(); + } + } + } +} diff --git a/cn.net.connor.std.fx/src/cn/net/connor/std/fx/KFXTextLocator.java b/cn.net.connor.std.fx/src/cn/net/connor/std/fx/KFXTextLocator.java new file mode 100644 index 0000000..26a2d39 --- /dev/null +++ b/cn.net.connor.std.fx/src/cn/net/connor/std/fx/KFXTextLocator.java @@ -0,0 +1,32 @@ +package cn.net.connor.std.fx; + +import java.util.Date; + +import javafx.scene.control.Control; + +public abstract class KFXTextLocator { + + private Control currentControl; + + protected int currentCaret; + public long focuseTime; + + public void clearLocatorData() { + currentControl = null; + currentCaret = 0; + } + + public Control getCurrentControl() { + return currentControl; + } + + public void updateControl(Control currentControl) { + this.currentControl = currentControl; + this.currentCaret = 0; + this.focuseTime = new Date().getTime(); + } + + public abstract void insertText(String text); + + +} diff --git a/cn.net.connor.std.fx/src/cn/net/connor/std/fx/KFXUtil.java b/cn.net.connor.std.fx/src/cn/net/connor/std/fx/KFXUtil.java new file mode 100644 index 0000000..5381541 --- /dev/null +++ b/cn.net.connor.std.fx/src/cn/net/connor/std/fx/KFXUtil.java @@ -0,0 +1,173 @@ +package cn.net.connor.std.fx; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; + +import com.sun.javafx.scene.control.skin.TableViewSkin; + +import javafx.animation.KeyFrame; +import javafx.animation.Timeline; +import javafx.collections.FXCollections; +import javafx.collections.ObservableList; +import javafx.event.EventHandler; +import javafx.scene.control.ComboBox; +import javafx.scene.control.TableColumn; +import javafx.scene.control.TableView; +import javafx.scene.control.Tooltip; +import javafx.scene.input.KeyCode; +import javafx.scene.input.KeyEvent; +import javafx.util.Duration; + +public class KFXUtil { + private static Method columnToFitMethod; + + static { + try { + columnToFitMethod = TableViewSkin.class.getDeclaredMethod("resizeColumnToFitContent", TableColumn.class, int.class); + columnToFitMethod.setAccessible(true); + } catch (NoSuchMethodException e) { + e.printStackTrace(); + } + hackTooltipTiming(); + } + + public static void hackTooltipTiming() { + System.out.println("Hack Tooltip Timing"); + try { + Field fieldBehavior = Tooltip.class.getDeclaredField("BEHAVIOR"); + fieldBehavior.setAccessible(true); + Object objBehavior = fieldBehavior.get(Tooltip.class); + Field fieldTimer = objBehavior.getClass().getDeclaredField("activationTimer"); + fieldTimer.setAccessible(true); + Timeline objTimer = (Timeline) fieldTimer.get(objBehavior); + objTimer.getKeyFrames().clear(); + objTimer.getKeyFrames().add(new KeyFrame(new Duration(250))); + Field hideTimerField= objBehavior.getClass().getDeclaredField("hideTimer"); + hideTimerField.setAccessible(true); + Timeline hideTimer = (Timeline) hideTimerField.get(objBehavior); + hideTimer.getKeyFrames().clear(); + hideTimer.getKeyFrames().add(new KeyFrame(new Duration(100000))); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void autoResizeColumn(TableView tableView) { + if (tableView == null) { + return; + + } + for (TableColumn col : tableView.getColumns()) { + try { + columnToFitMethod.invoke(tableView.getSkin(), col, -1); + } catch (Exception e) { + // e.printStackTrace(); + } + } + } + + public static interface AutoCompleteComparator { + boolean matches(String typedText, T objectToCompare); + } + + public static void autoCompleteComboBoxPlus(ComboBox comboBox, AutoCompleteComparator comparatorMethod, boolean checkText) { + ObservableList data = comboBox.getItems(); + + comboBox.setEditable(true); + if(checkText) { + comboBox.getEditor().focusedProperty().addListener(observable -> { + if (comboBox.getSelectionModel().getSelectedIndex() < 0) { + comboBox.getEditor().setText(null); + } else { + T value = getComboBoxValue(comboBox); + comboBox.getEditor().setText(value == null ? null : value.toString()); + } + }); + } + comboBox.addEventHandler(KeyEvent.KEY_PRESSED, t -> comboBox.hide()); + comboBox.addEventHandler(KeyEvent.KEY_RELEASED, new EventHandler() { + + private boolean moveCaretToPos = false; + private int caretPos; + + @Override + public void handle(KeyEvent event) { + if (event.getCode() == KeyCode.UP) { + caretPos = -1; + if (comboBox.getEditor().getText() != null) { + moveCaret(comboBox.getEditor().getText().length()); + } + return; + } else if (event.getCode() == KeyCode.DOWN) { + if (!comboBox.isShowing()) { + comboBox.show(); + } + caretPos = -1; + if (comboBox.getEditor().getText() != null) { + moveCaret(comboBox.getEditor().getText().length()); + } + return; + } else if (event.getCode() == KeyCode.BACK_SPACE) { + if (comboBox.getEditor().getText() != null) { + moveCaretToPos = true; + caretPos = comboBox.getEditor().getCaretPosition(); + } + } else if (event.getCode() == KeyCode.DELETE) { + if (comboBox.getEditor().getText() != null) { + moveCaretToPos = true; + caretPos = comboBox.getEditor().getCaretPosition(); + } + } else if (event.getCode() == KeyCode.ENTER) { + return; + } + + if (event.getCode() == KeyCode.RIGHT || event.getCode() == KeyCode.LEFT || event.getCode().equals(KeyCode.SHIFT) || event.getCode().equals(KeyCode.CONTROL) || event.isControlDown() + || event.getCode() == KeyCode.HOME || event.getCode() == KeyCode.END || event.getCode() == KeyCode.TAB) { + return; + } + comboBox.hide(); + ObservableList list = FXCollections.observableArrayList(); + for (T aData : data) { + if (aData != null && comboBox.getEditor().getText() != null && comparatorMethod.matches(comboBox.getEditor().getText(), aData)) { + list.add(aData); + } + } + String t = ""; + if (comboBox.getEditor().getText() != null) { + t = comboBox.getEditor().getText(); + } + + comboBox.setItems(list); + comboBox.getEditor().setText(t); + if (!moveCaretToPos) { + caretPos = -1; + } + moveCaret(t.length()); + if (!list.isEmpty()) { + comboBox.show(); + } + } + + private void moveCaret(int textLength) { + if (caretPos == -1) { + comboBox.getEditor().positionCaret(textLength); + } else { + comboBox.getEditor().positionCaret(caretPos); + } + moveCaretToPos = false; + } + }); + } + public static void autoCompleteComboBoxPlus(ComboBox comboBox, AutoCompleteComparator comparatorMethod) { + autoCompleteComboBoxPlus(comboBox, comparatorMethod, true); + } + + public static T getComboBoxValue(ComboBox comboBox) { + if (comboBox.getSelectionModel().getSelectedIndex() < 0) { + return null; + } else { + return comboBox.getItems().get(comboBox.getSelectionModel().getSelectedIndex()); + } + } + +} diff --git a/cn.net.connor.std.fx/src/cn/net/connor/std/fx/KIndexCheckBox.java b/cn.net.connor.std.fx/src/cn/net/connor/std/fx/KIndexCheckBox.java new file mode 100644 index 0000000..981303d --- /dev/null +++ b/cn.net.connor.std.fx/src/cn/net/connor/std/fx/KIndexCheckBox.java @@ -0,0 +1,22 @@ +package cn.net.connor.std.fx; + +import javafx.scene.control.CheckBox; + +public class KIndexCheckBox extends CheckBox implements Comparable{ + + private int index; + + public KIndexCheckBox(int index){ + super(""+index); + this.index = index; + } + + @Override + public int compareTo(KIndexCheckBox var1) { + if(var1==null) { + return -1; + } + return index-var1.index; + } + +} diff --git a/cn.net.connor.std.fx/src/cn/net/connor/std/fx/KLOVComboBox.java b/cn.net.connor.std.fx/src/cn/net/connor/std/fx/KLOVComboBox.java new file mode 100644 index 0000000..ad9ce6e --- /dev/null +++ b/cn.net.connor.std.fx/src/cn/net/connor/std/fx/KLOVComboBox.java @@ -0,0 +1,58 @@ +package cn.net.connor.std.fx; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.teamcenter.rac.kernel.TCComponentListOfValues; +import com.teamcenter.soa.client.model.LovValue; + +import javafx.collections.FXCollections; +import javafx.collections.ObservableList; +import javafx.scene.control.ComboBox; +import javafx.util.StringConverter; + +public class KLOVComboBox extends ComboBox{ + + public KLOVComboBox(TCComponentListOfValues lov) throws Exception{ + super(); + if(lov==null) { + return; + } + ObservableList items = FXCollections.observableArrayList(); + Map real_dis = new HashMap(); + Map dis_real = new HashMap(); + List lovs = lov.getListOfValues().getValues(); + int size = lovs==null?0:lovs.size(); + for(int i=0;i converter = new StringConverter() { + + @Override + public String toString(String paramT) { + if(real_dis.containsKey(paramT)) { + return real_dis.get(paramT); + } + return paramT; + } + + @Override + public String fromString(String paramString) { + if(dis_real.containsKey(paramString)) { + return dis_real.get(paramString); + } + return paramString; + } + }; + setItems(items); + this.setConverter(converter ); + } + + +} diff --git a/cn.net.connor.std.fx/src/cn/net/connor/std/fx/style.css b/cn.net.connor.std.fx/src/cn/net/connor/std/fx/style.css new file mode 100644 index 0000000..62a76ef --- /dev/null +++ b/cn.net.connor.std.fx/src/cn/net/connor/std/fx/style.css @@ -0,0 +1,4 @@ +.table-view { + -fx-faint-focus-color: transparent; + -fx-focus-color: rgba(0,0,0,0.2); +} diff --git a/cn.net.connor.std.gdtex/.classpath b/cn.net.connor.std.gdtex/.classpath new file mode 100644 index 0000000..eca7bdb --- /dev/null +++ b/cn.net.connor.std.gdtex/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/cn.net.connor.std.gdtex/.gitignore b/cn.net.connor.std.gdtex/.gitignore new file mode 100644 index 0000000..ae3c172 --- /dev/null +++ b/cn.net.connor.std.gdtex/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/cn.net.connor.std.gdtex/.project b/cn.net.connor.std.gdtex/.project new file mode 100644 index 0000000..fc234d8 --- /dev/null +++ b/cn.net.connor.std.gdtex/.project @@ -0,0 +1,28 @@ + + + cn.net.connor.std.gdtex + + + + + + 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/cn.net.connor.std.gdtex/.settings/org.eclipse.jdt.core.prefs b/cn.net.connor.std.gdtex/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..0c68a61 --- /dev/null +++ b/cn.net.connor.std.gdtex/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,7 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/cn.net.connor.std.gdtex/META-INF/MANIFEST.MF b/cn.net.connor.std.gdtex/META-INF/MANIFEST.MF new file mode 100644 index 0000000..842eade --- /dev/null +++ b/cn.net.connor.std.gdtex/META-INF/MANIFEST.MF @@ -0,0 +1,17 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Gdtex +Bundle-SymbolicName: cn.net.connor.std.gdtex;singleton:=true +Bundle-Version: 13000.1.0 +Bundle-Activator: cn.net.connor.std.gdtex.Activator +Require-Bundle: org.eclipse.core.runtime, + com.teamcenter.rac.aifrcp, + com.teamcenter.rac.common, + com.teamcenter.rac.external, + com.teamcenter.rac.kernel, + com.teamcenter.rac.ui.commands, + com.teamcenter.rac.util +Bundle-RequiredExecutionEnvironment: JavaSE-1.8 +Automatic-Module-Name: cn.net.connor.std.gdtex +Bundle-ActivationPolicy: lazy +Export-Package: cn.net.connor.std.gdtex diff --git a/cn.net.connor.std.gdtex/README.MD b/cn.net.connor.std.gdtex/README.MD new file mode 100644 index 0000000..5327348 --- /dev/null +++ b/cn.net.connor.std.gdtex/README.MD @@ -0,0 +1,70 @@ +# GDT符号扩展 + +## 功能简介 + +扩展Teamcenter中GDT编辑器的符号 + +## 使用 + +1. 将`cn.net.connor.std.gdtex_1.0.0.jar`复制到TC的plugins目录 +2. 注册 + +## 配置 + +1. 首选项`connor_gdt_custom_symbols` + + 格式: + + ```text + 标识符号[=实际写入编辑器中的标识符号]=字符编码 + + 标识符号:保存在TC属性值中的内容,如“<#D5>” + 实际写入编辑器中的标识符号:选配,在点击符号进行插入时,可能需要插入额外的符号,在此处配置,如“<#D5><+>” + 字符编码:16进制的字符码,在创建字体时有相关内容,如“00D5”或“D5” + + 可以添加分组,在需要分组内容的前一行添加分组名称即可 + ``` + + 示例: + + ```text + 分组1 + <#K0>=D5 + 分组2 + <#K1>=<#K1><+>=D6 + <#K2>=<+><#K2><+>=D7 + ``` + +2. 首选项`connor_gdt_font` + + 单值,配置gdt字体文件路径,如果未配置或文件不存在,则使用jar包中的字体 + +3. 创建字体 + + - 修改`%TC_ROOT%/portal/fonts/gdtex.ttf`,使用工具添加需要的符号 + - 安装修改完成的字体文件 + - 用解压软件打开jar包,将字体文件放到jar包的根目录 + + +## 生成HTML配置 + +目的:原有的GDTEX字体在JavaFX内嵌浏览器中,部分字符的编码存在无法显示问题,如GDT13($7F)、GDT15($81)。需要创建相同符号的字符,通过配置首选项,将转换生成的HTML文件中有问题字符编码替换为新的字符编码 + +**首选项** `connor_gdt_custom_generate_html_replacement` + +格式:有问题字符编码=新字符编码 + +字符编码为html格式 + +示例: + +```text +=Ā +=ā +``` + + + + + + diff --git a/cn.net.connor.std.gdtex/build.properties b/cn.net.connor.std.gdtex/build.properties new file mode 100644 index 0000000..e9863e2 --- /dev/null +++ b/cn.net.connor.std.gdtex/build.properties @@ -0,0 +1,5 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + plugin.xml diff --git a/cn.net.connor.std.gdtex/plugin.xml b/cn.net.connor.std.gdtex/plugin.xml new file mode 100644 index 0000000..a31e6cf --- /dev/null +++ b/cn.net.connor.std.gdtex/plugin.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/cn.net.connor.std.gdtex/src/GDTEX.ttf b/cn.net.connor.std.gdtex/src/GDTEX.ttf new file mode 100644 index 0000000..31ad923 Binary files /dev/null and b/cn.net.connor.std.gdtex/src/GDTEX.ttf differ diff --git a/cn.net.connor.std.gdtex/src/cn/net/connor/std/gdtex/Activator.java b/cn.net.connor.std.gdtex/src/cn/net/connor/std/gdtex/Activator.java new file mode 100644 index 0000000..b56a2b2 --- /dev/null +++ b/cn.net.connor.std.gdtex/src/cn/net/connor/std/gdtex/Activator.java @@ -0,0 +1,22 @@ +package cn.net.connor.std.gdtex; + +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; + +public class Activator implements BundleActivator { + + private static BundleContext context; + + static BundleContext getContext() { + return context; + } + + public void start(BundleContext bundleContext) throws Exception { + Activator.context = bundleContext; + } + + public void stop(BundleContext bundleContext) throws Exception { + Activator.context = null; + } + +} diff --git a/cn.net.connor.std.gdtex/src/cn/net/connor/std/gdtex/KGdtEditor.java b/cn.net.connor.std.gdtex/src/cn/net/connor/std/gdtex/KGdtEditor.java new file mode 100644 index 0000000..1bc3121 --- /dev/null +++ b/cn.net.connor.std.gdtex/src/cn/net/connor/std/gdtex/KGdtEditor.java @@ -0,0 +1,131 @@ +package cn.net.connor.std.gdtex; + +import java.awt.BorderLayout; +import java.awt.Font; +import java.awt.Panel; +import java.io.File; +import java.io.InputStream; +import java.util.Arrays; + +import javax.swing.JPanel; +import javax.swing.JTabbedPane; +import javax.swing.JTextArea; + +import com.teamcenter.rac.aifrcp.AifrcpPlugin; +import com.teamcenter.rac.kernel.TCPreferenceService; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.stylesheet.gdt.CellGridLayout; +import com.teamcenter.rac.stylesheet.gdt.GdtDialog; +import com.teamcenter.rac.stylesheet.gdt.GdtEditor; +import com.teamcenter.rac.util.MessageBox; +import com.teamcenter.rac.util.Utilities; + +@SuppressWarnings("serial") +public class KGdtEditor extends GdtEditor { + + protected static Font GDT_FONT_EX; + + static { + try { + TCSession session = (TCSession) AifrcpPlugin.getSessionService().getActivePerspectiveSession(); + TCPreferenceService ps = session.getPreferenceService(); + String gdtFilePath = ps.getStringValue(KGenerateGDTHTML.PREF_GDT_FONT); + if(gdtFilePath!=null&&gdtFilePath.length()>0) { + File gdtFile = new File(gdtFilePath); + if(gdtFile.exists()) { + try { + System.out.println("GDT File Path: "+gdtFilePath); + GDT_FONT_EX = Font.createFont(0, gdtFile).deriveFont(20.0F); + } catch (Exception e) { + e.printStackTrace(); + } + }else { + System.out.println("GDT Font not Exist: "+gdtFilePath); + } + } + if(GDT_FONT_EX==null) { + System.out.println("Use GDT Font in Jar"); + InputStream inputStream = KGdtEditor.class.getClassLoader().getResourceAsStream("/GDTEX.ttf"); + GDT_FONT_EX = Font.createFont(0, inputStream).deriveFont(20.0F); + inputStream.close(); + } + } catch (Exception exception) { + exception.printStackTrace(); + throw new Error(exception); + } + } + + public KGdtEditor(JTextArea paramJTextArea) { + super(paramJTextArea); + System.out.println("KGdtEditor"); + try { + addCustomSymbols(); + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(e); + } + } + + protected void addCustomSymbols() throws Exception { + // read symbols + TCSession session = (TCSession) AifrcpPlugin.getSessionService().getActivePerspectiveSession(); + TCPreferenceService ps = session.getPreferenceService(); + String[] values = ps.getStringValues(KGenerateGDTHTML.PREF_GDT); + System.out.println(KGenerateGDTHTML.PREF_GDT + " -> " + Arrays.toString(values)); + int len = values == null ? 0 : values.length; + if (len == 0) { + return; + } + Panel panel = (Panel) this.getComponent(2); + JTabbedPane tabPane = (JTabbedPane) panel.getComponent(0); + JPanel tab = (JPanel) ((JPanel) tabPane.getComponent(1)).getComponent(1); + for (int i = 0; i < len; i++) { + String value = values[i]; + String symbol = null; + String symbolPlus = null; + String code = null; + int ind = value.lastIndexOf('='); + if (ind > 0) { + symbol = value.substring(0, ind).trim(); + code = value.substring(ind + 1).trim(); + } + if(symbol!=null) { + ind = symbol.indexOf('='); + if (ind > 0) { + symbolPlus = symbol.substring(ind + 1).trim(); + symbol = symbol.substring(0, ind).trim(); + } + } + if (symbol == null || code == null || symbol.length() == 0 || code.length() == 0) { // category + JPanel wrapper = new JPanel(new BorderLayout()); + tab = new JPanel(new CellGridLayout(4, 8)); + wrapper.add(BorderLayout.CENTER, tab); + tabPane.add(value, wrapper); + } else { // symbol + int cp = Integer.parseInt(code, 16); + char c[] = Character.toChars(cp); + System.out.println(code +" == "+ cp + " >> " + Arrays.toString(c)); + if(symbolPlus!=null&&symbolPlus.length()>0) { + tab.add(new SymbolButton(symbolPlus, KGenerateGDTHTML.generatePage(symbolPlus), GDT_FONT_EX));//new String(c) + }else { + tab.add(new SymbolButton(symbol, KGenerateGDTHTML.generatePage(symbol), GDT_FONT_EX)); + } + } + } + } + + @Override + public boolean updateDisplay() { + String str = this.marshText.getText(); + JTextArea textArea = (JTextArea) Utilities.getPrivateField(this, "textArea"); + textArea.setText(str); + String htmlString = KGenerateGDTHTML.generatePage(str); + Utilities.setPrivateField(this, "htmlString", htmlString); + GdtDialog gdtDialog = (GdtDialog) Utilities.getPrivateField(this, "gdtDialog"); + if (gdtDialog != null) { + gdtDialog.displayHTML(htmlString); + } + return true; + } + +} diff --git a/cn.net.connor.std.gdtex/src/cn/net/connor/std/gdtex/KGenerateGDTHTML.java b/cn.net.connor.std.gdtex/src/cn/net/connor/std/gdtex/KGenerateGDTHTML.java new file mode 100644 index 0000000..7ea5fee --- /dev/null +++ b/cn.net.connor.std.gdtex/src/cn/net/connor/std/gdtex/KGenerateGDTHTML.java @@ -0,0 +1,107 @@ +package cn.net.connor.std.gdtex; + +import java.lang.reflect.Field; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeMap; + +import com.teamcenter.rac.aifrcp.AifrcpPlugin; +import com.teamcenter.rac.kernel.TCPreferenceService; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.stylesheet.gdt.GenerateGDTHTML; + +public class KGenerateGDTHTML extends GenerateGDTHTML { + + public static final String PREF_GDT = "connor_gdt_custom_symbols"; // symbol[=symbolPlus]=code + public static final String PREF_GDT_HTML_REPLACE = "connor_gdt_custom_generate_html_replacement"; + public static final String PREF_GDT_FONT = "connor_gdt_font"; + public static Map replaceCharacters = new HashMap<>(); + + static { + try { + addCustomSymbols(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public KGenerateGDTHTML(String arg0) { + super(arg0); + } + + public static String generatePage(String paramString) { + String value = GenerateGDTHTML.generatePage(paramString); + if (replaceCharacters.size() > 0 && value != null) { + for (String oldValue : replaceCharacters.keySet()) { + String newValue = replaceCharacters.get(oldValue); + value = value.replace(oldValue, newValue); + } + } + return value; + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + protected static void addCustomSymbols() throws Exception { + Map symbolMap = new HashMap(); + // read symbols + TCSession session = (TCSession) AifrcpPlugin.getSessionService().getActivePerspectiveSession(); + TCPreferenceService ps = session.getPreferenceService(); + ps.refresh(); + // replacement + { + String[] replaceConfigs = ps.getStringValues(PREF_GDT_HTML_REPLACE); + System.out.println(PREF_GDT_HTML_REPLACE + " -> " + Arrays.toString(replaceConfigs)); + int replaceCnt = replaceConfigs == null ? 0 : replaceConfigs.length; + for (int i = 0; i < replaceCnt; i++) { + String[] split = replaceConfigs[i].split("="); + if (split.length == 2) { + replaceCharacters.put(split[0], split[1]); + } + } + System.out.println("Replace Character Map: " + replaceCharacters); + } + String[] values = ps.getStringValues(PREF_GDT); + System.out.println(PREF_GDT + " -> " + Arrays.toString(values)); + int len = values == null ? 0 : values.length; + if (len == 0) { + return; + } + for (int i = 0; i < len; i++) { + String value = values[i]; + String symbol = null; + String code = null; + int ind = value.lastIndexOf('='); + if (ind > 0) { + symbol = value.substring(0, ind).trim(); + code = value.substring(ind + 1).trim(); + } + if (symbol != null) { + ind = symbol.indexOf('='); + if (ind > 0) { + symbol = symbol.substring(0, ind).trim(); + } + } + if (symbol == null || code == null || symbol.length() == 0 || code.length() == 0) { // category + continue; + } + // symbol + symbolMap.put(symbol, code); + } + System.out.println(symbolMap); + if (symbolMap.size() == 0) { + return; + } + Class c = GenerateGDTHTML.class; + Field f = c.getDeclaredField("singleMap"); + f.setAccessible(true); + TreeMap singleMap = (TreeMap) f.get(GenerateGDTHTML.class);// (TreeMap) Utilities.getPrivateField(KGenerateGDTHTML.class, "singleMap"); + for (String symbol : symbolMap.keySet()) { + String code = symbolMap.get(symbol); + if (!singleMap.containsKey(code)) { + singleMap.put(symbol, "&#x" + code + ";"); + } + } + } + +} diff --git a/cn.net.connor.std.gdtex/src/cn/net/connor/std/gdtex/KPropertyGdtPanel.java b/cn.net.connor.std.gdtex/src/cn/net/connor/std/gdtex/KPropertyGdtPanel.java new file mode 100644 index 0000000..a62a289 --- /dev/null +++ b/cn.net.connor.std.gdtex/src/cn/net/connor/std/gdtex/KPropertyGdtPanel.java @@ -0,0 +1,16 @@ +package cn.net.connor.std.gdtex; + +import javax.swing.JTextArea; + +import com.teamcenter.rac.stylesheet.PropertyGdtPanel; +import com.teamcenter.rac.util.Utilities; + +@SuppressWarnings("serial") +public class KPropertyGdtPanel extends PropertyGdtPanel { + + public KPropertyGdtPanel() { + super(); + System.out.println("KPropertyGdtPanel" + (super.editor == null)); + Utilities.setPrivateField(this, "editor", new KGdtEditor((JTextArea) Utilities.getPrivateField(this, "textArea"))); + } +} diff --git a/cn.net.connor.std.gdtex/src/cn/net/connor/std/gdtex/KTitledPropertyGdtPanel.java b/cn.net.connor.std.gdtex/src/cn/net/connor/std/gdtex/KTitledPropertyGdtPanel.java new file mode 100644 index 0000000..5708264 --- /dev/null +++ b/cn.net.connor.std.gdtex/src/cn/net/connor/std/gdtex/KTitledPropertyGdtPanel.java @@ -0,0 +1,13 @@ +package cn.net.connor.std.gdtex; + +import com.teamcenter.rac.stylesheet.TitledPropertyGdtPanel; + +@SuppressWarnings("serial") +public class KTitledPropertyGdtPanel extends TitledPropertyGdtPanel{ + + public KTitledPropertyGdtPanel() { + super(); + System.out.println("KTitledPropertyGdtPanel"); + } + +} diff --git a/cn.net.connor.std.gdtex/src/com/teamcenter/rac/stylesheet/stylesheet_user.properties b/cn.net.connor.std.gdtex/src/com/teamcenter/rac/stylesheet/stylesheet_user.properties new file mode 100644 index 0000000..4e76827 --- /dev/null +++ b/cn.net.connor.std.gdtex/src/com/teamcenter/rac/stylesheet/stylesheet_user.properties @@ -0,0 +1,4 @@ +import=com.teamcenter.rac.common.common,com.teamcenter.rac.common.propertyrenderer.propertyrenderer,com.teamcenter.rac.pse.revisionrules.revisionrules,com.teamcenter.rac.pse.common.common + +gdtpanel.DEFINITION=cn.net.connor.std.gdtex.KPropertyGdtPanel +gdtpanel_titled.DEFINITION=cn.net.connor.std.gdtex.KTitledPropertyGdtPanel diff --git a/cn.net.connor.std.processedit/.classpath b/cn.net.connor.std.processedit/.classpath new file mode 100644 index 0000000..82d2abb --- /dev/null +++ b/cn.net.connor.std.processedit/.classpath @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/cn.net.connor.std.processedit/.gitignore b/cn.net.connor.std.processedit/.gitignore new file mode 100644 index 0000000..ae3c172 --- /dev/null +++ b/cn.net.connor.std.processedit/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/cn.net.connor.std.processedit/.project b/cn.net.connor.std.processedit/.project new file mode 100644 index 0000000..3725e71 --- /dev/null +++ b/cn.net.connor.std.processedit/.project @@ -0,0 +1,28 @@ + + + cn.net.connor.std.processedit + + + + + + 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/cn.net.connor.std.processedit/.settings/org.eclipse.core.resources.prefs b/cn.net.connor.std.processedit/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000..03e43bb --- /dev/null +++ b/cn.net.connor.std.processedit/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +encoding//src/cn/net/connor/std/processedit/util/PrefComponent.java=UTF-8 diff --git a/cn.net.connor.std.processedit/.settings/org.eclipse.jdt.core.prefs b/cn.net.connor.std.processedit/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..9f6ece8 --- /dev/null +++ b/cn.net.connor.std.processedit/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.release=disabled +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/cn.net.connor.std.processedit/META-INF/MANIFEST.MF b/cn.net.connor.std.processedit/META-INF/MANIFEST.MF new file mode 100644 index 0000000..82207d0 --- /dev/null +++ b/cn.net.connor.std.processedit/META-INF/MANIFEST.MF @@ -0,0 +1,57 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Processedit +Bundle-SymbolicName: cn.net.connor.std.processedit;singleton:=true +Bundle-Version: 13000.1.0 +Bundle-Activator: cn.net.connor.std.processedit.Activator +Eclipse-RegisterBuddy: cn.net.connor.std.aifrcp,cn.net.connor.std.fx +Require-Bundle: org.eclipse.ui, + org.eclipse.core.runtime, + com.teamcenter.rac.util;bundle-version="13000.1.0", + com.teamcenter.rac.tcapps;bundle-version="13000.1.0", + com.teamcenter.rac.ui.views;bundle-version="13000.1.0", + org.apache.poi.39, + TcSoaCommon, + TcSoaCoreRac, + TcSoaCoreTypes, + com.teamcenter.rac.cme.mpp;bundle-version="13000.1.0", + com.teamcenter.rac.cme.activity;bundle-version="13000.1.0", + com.teamcenter.rac.cme.time;bundle-version="13000.1.0", + com.teamcenter.rac.cme.legacy;bundle-version="13000.1.0", + com.teamcenter.rac.cme.bvr.connect;bundle-version="13000.1.0", + com.teamcenter.rac.cme.framework, + com.teamcenter.rac.classification.icm;bundle-version="13000.1.0", + com.teamcenter.rac.classification.icadmin;bundle-version="13000.1.0", + TcSoaStructureManagementRac;bundle-version="13000.1.0", + TcSoaStructureManagementLoose;bundle-version="13000.1.0", + TcSoaCoreLoose, + com.teamcenter.rac.aifrcp;bundle-version="13000.1.0", + com.teamcenter.rac.kernel;bundle-version="13000.1.0", + com.teamcenter.rac.common;bundle-version="13000.1.0", + cn.net.connor.std.aifrcp;bundle-version="13000.1.0", + cn.net.connor.std.gdtex;bundle-version="13000.1.0", + cn.net.connor.std.fx;bundle-version="13000.1.0", + com.teamcenter.rac.commonclient;bundle-version="13000.1.0" +Bundle-RequiredExecutionEnvironment: JavaSE-1.8 +Automatic-Module-Name: cn.net.connor.std.processedit +Bundle-ActivationPolicy: lazy +Export-Package: cn.net.connor.std.processedit, + cn.net.connor.std.processedit.choose, + cn.net.connor.std.processedit.choosefromsql, + cn.net.connor.std.processedit.commands, + cn.net.connor.std.processedit.meopviewfx, + cn.net.connor.std.processedit.meopviewfx.bean, + cn.net.connor.std.processedit.meopviewfx.reorder, + cn.net.connor.std.processedit.meopviewfx.ui, + cn.net.connor.std.processedit.modifymeopno, + cn.net.connor.std.processedit.newdatasetfromtemplate, + cn.net.connor.std.processedit.newmeop, + cn.net.connor.std.processedit.newmeprocess, + cn.net.connor.std.processedit.processview, + cn.net.connor.std.processedit.processview.safeicon, + cn.net.connor.std.processedit.searchbysql, + cn.net.connor.std.processedit.util, + cn.net.connor.std.processedit.word +Bundle-ClassPath: lib/jsqlparser-4.3.jar, + ., + lib/jacob.jar diff --git a/cn.net.connor.std.processedit/README.MD b/cn.net.connor.std.processedit/README.MD new file mode 100644 index 0000000..f150088 --- /dev/null +++ b/cn.net.connor.std.processedit/README.MD @@ -0,0 +1,384 @@ +# 工艺视图(首选项不完整) + +## 1. 工道编辑 + +相关首选项列表: + +1. Connor_AVIC_GXBZ_Bomline: 配置界面上方的表格 +2. Connor_AVIC_GXBZ_[对象类型]: 配置界面下方的表格,对象类型是选择bom行对应item的真实类型名称 +3. Connor_AVIC_GXBZ_Property_[对象类型]:配置界面中间属性表 +4. Connor_AVIC_GXBZ_Common_Folder: 配置通用文件夹或Excel的uid +5. Connor_AVIC_GXBZ_Personal_Folder:配置个人文件夹或Excel的uid + +### 1.1 表格首选项配置 + +涉及首选项: + +1. Connor_AVIC_GXBZ_Bomline + +2. Connor_AVIC_GXBZ_[对象类型] + +首选项格式说明: + +```text +第一行配置:指定的对象类型 +指定对象类型后,该表格只加载指定类型的子行,如存在新建功能,则使用该类型新建对象 +如不需要指定类型,首行需配置"bomline",此表格仅支持读取和修改bom行属性 + +第二行开始配置属性映射 +格式:[列宽][$每行最大字符数量][属性位置.][#]属性真实名称[=属性值(按该值进行过滤)] + +列宽:选配,直接在前面加数字 +每行最大字符数量:手动输入时,如果某行超过此数量则自动添加换行符 +属性位置:如不写即默认bomline属性(位置包含:bomline, item, rev, itemmaster, revmaster) +属性位置(工步):如不写默认为文件夹属性(位置包含:bomline,item) +#:属性名称前加#表示改列为手动序号列,用于重排序功能,支持多列 +##:属性名称前加##表示改列为自动序号列,不跟随上下移动,删除行时也会自动调整,支持多列 +属性真实名称:定义的属性名称,如要支持换行,请务必配置“bl_sequence_no”属性 +属性值:配置后,只显示属性匹配的行(如配置指定的事例类型) + +20210119更新: 下方表格支持GDT编辑器,属性名称配置到GDT_properties首选项即可 + +特殊配置: +sequence_step=工步号递增数值:配置工步号递增大小,不配置默认为10 +``` + +示例: + +```text +bomline +bl_indented_title +bl_occ_type=MEAssemble +200bl_item_object_name +``` + +```text +Item +bomline.##bl_sequence_no +bomline.bl_indented_title +rev.#object_desc +item.#object_desc +150item.object_name +sequence_step=2 +``` + +### 1.2 属性首选项配置 + +涉及首选项: + +1. Connor_AVIC_GXBZ_Property_[对象类型] + +格式: + +```text +多值,格式:[*]属性真实名称[=下拉值1;下拉值2;下拉值3] + +*:表示属性在版本上,不添加*表示属性在版本表单 +下拉值:配置后,若属性上未定义下拉值,则变更属性控件为下拉框,下拉内容为分号分隔后的配置内容;若定义下拉值,以bmide中定义的lov为准。 +``` + +示例: + +```text +object_name +*object_name=名称1;名称2;名称3 +object_type +creation_date +``` + +### 1.3 特殊文本树 + +涉及首选项: + +1. Connor_AVIC_GXBZ_Common_Folder: 配置通用文件夹或Excel的uid +2. Connor_AVIC_GXBZ_Personal_Folder:配置个人文件夹或Excel的uid + +Excel 格式说明 + +> 从左上角开始写入内容,单元格排列保持树形即可,注意不要在内容之间插入空列 + +真实值说明:真实值有多种配置方式 + +> 1. 在真实值单元格内容前加“#RV#” +> 2. 在配置的uid后添加“#RealValue#列号”,配置后,对应文件夹内所有excel或指定uid的excel的对应列作为真实值列 + +### 1.4 TC兼容性修改 + +> 由于工序编制界面基于javafx开发,TC的文本检测未进行兼容,所以在文本框中进行复制粘贴和剪切时存在问题。 +> +> 需要修改 com.teamcenter.rac.common.xxxx.jar 中的 plugin.xml + +```xml + + + + + + + + + + +``` + +修改为 + +```xml + + + + + + + + + + + + + + + +``` + +## 2. 工艺工序编辑 + +配置工艺视图中选择对应[对象真实类型]时,要在界面中显示的属性 + +```text +格式:“[*][#][$]显示名称=属性位置.属性名称[=附加lov的名称[=从工艺提取属性的属性位置.属性名称[=属性是否显示配置]]]”(属性位置包含 item, rev, itemmaster, revmaster) +注意:此处增加[$]符号的配置,表示控件是文本域,可多行输入。[*][#]同上,分别表示必填和只读 + +属性是否显示配置格式:“属性位置.属性名称:配置文本”。当属性真实值等于配置文本时,这条配置为有效配置,控件可见;否则忽略该行配置。 +示例:“版本描述=rev.object_desc=BillCodes==rev.object_desc:1” + +20210112: 附加lov名称配置可以替换为用英文分号分隔的下拉值列表 + +20201117 增加额外配置:某个下拉框(控制属性)选择指定的值时,隐藏指定的控件(隐藏属性) +格式:“HIDE_LISTENER:控制属性位置.控制属性名称=指定值:隐藏属性位置1.隐藏属性名称1;隐藏属性位置2.隐藏属性名称2” +示例:“HIDE_LISTENER:rev.object_desc=Civi:item.object_desc;item.object_name” +``` + +## 3. 选择原材料配置 + +**从Excel选择** + +Connor_AVIC_MEOPEXCEL_[属性真实名称] + +配置**创建工序**和**工艺编辑**视图界面中对应[属性真实名称]的选择按钮逻辑 + +```text +第一行:配置excel数据集的uid,可按照创建界面选择的类型区分。首先查找类型对应uid,未找到时查找默认uid。 +格式:“默认uid;真实类型名称1:类型1使用的uid;真实类型名称2:类型2使用的uid;...” +第二行开始:配置表格显示和属性映射信息 +格式:“[#]界面列名=excel列名[=属性位置.属性名称[=默认列宽]]” +#:表示添加该列的查询 +``` + +## 3. 修改工序号 + +1. 首选项:Connor_AVIC_SQGXH_GXLX,多值,配置工序对象类型真实名称 +2. 首选项:Connor_AVIC_SQGXH_SXBJ,多值,格式:"表头名称=属性位置.属性名称",属性位置包含:item,rev,itemmaster,revmaster,bomline + +## 4. 安全说明 + +首选项:connor_process_aqtb_zsjm,多值 + +格式: + +```text +第一行:安全图标文件夹UID +第二行:安全图标和选择版本的关系 +第三行:安全说明属性名称(版本属性) +第四行:图标数据集类型,多个类型用英文分号分隔 +第五行:需要添加安全图标的对象(Item)类型 +``` + +示例: + +```text +BkvJiCugJ5xHGD +IMAN_reference +object_desc +JPEG;Image +SF6_GMEP;Item +``` + +仅保留安全说明的配置方式 + +```text +第一行:安全说明属性名称(版本属性) +``` + +示例: + +```text +object_desc +``` + +## 5. DWG 略图 + +首选项 + +```text +Connor_AVIC_BZGXLT:配置标准工序略图 +Connor_AVIC_XLGXLT:配置下料工序略图 +``` + +格式: + +```text +select=选择的对象类型名称,多个用英文分号分隔 +relation=新数据集和选择对象的关系 +name=数据集名称和文件引用名称配置,支持拼接和属性路径,路径从bom行开始 +success=(选配)成功提示,不配置则不提示 +exist=(选配)根据名称、类型、关系检查数据集是否存在,已存在则不进行操作,不配置则不检查 +dataset=模板数据集uid +``` + +示例: + +```text +select=ItemRevision +relation=IMAN_reference +name=bl_sequence_no+_+bl_revision.IMAN_master_form_rev.object_desc+标准工序略图 +success=成功了 +exist=已经有了,不准上传 +dataset=R0kJyb3IJ5xHGD +``` + +# 6. 新建工艺 + +首选项:Connor_AVIC_[版本类型] + +配置创建工艺界面,对齐使用空格对齐(shift+space切换中英空格) + +```text +格式:“[*][#][@]标题名称=写入属性配置[=提取属性配置[+GY][=下拉内容1;下拉内容2;下拉内容3]]” +*:必填 +#:不可编辑 +@: 不可见 +属性配置格式:属性位置.属性名称(属性位置包含 item, rev, itemmaster, revmaster) +-------------------------------------------- +特殊写入属性配置: +object_type:必配,指定新建对象的类型,如有下拉值,配置“真实类型名称[-新对象版本(父)与用户选择版本(子)的关联关系名称[-用户选择版本(父)与新对象(子)的关联关系名称]]” +``` + +## 7. 更改说明 + +首选项:connor_process_ggjl + +配置工艺工序编辑界面中的更改记录,属性定义在版本表单 + +```text +第一行:表格行对象类型 +第二行:版本表单中表格属性名称 +第三号开始配置表格行属性,格式“[列宽]标题名称=属性名称”,仅字符串属性 + +首选项:connor_process_ggjl_editable + +单值,逻辑类型,配置更改记录是否可编辑,默认不可编辑,配置true为可编辑 +``` + +示例: + +```text +SF6_TableRow +sf6_tablerow +50第1列=sf6_col1 +第2列=sf6_col2 +第3列=sf6_col3 +第4列=sf6_col4 +第5列=sf6_col5 +第6列=sf6_col6 +``` + +## 8. 工作中心选择 + +首选项:Connor_AVIC_MEOP_WorkCenter_Class + +单值,配置工作中心分类ID + +# 更新记录 + +20220224 + +1. 工道编辑,序号特殊配置 + + 更新配置:序号属性名称前加# + + 属性位置(工步):如不写默认为文件夹属性(位置包含:bomline,item) + + ```text + [列宽][$每行最大字符数量][属性位置.][#]属性真实名称[=属性值(按该值进行过滤)] + ``` + + 示例 + + ```text + 首选项名称:Connor_AVIC_GXBZ_MEOP + 值: + SF6_CheckActivity + object_name + sf6_checkType + #sf6_checkTool + bomline.me_cl_display_string + object_desc + ``` + +2. 工艺工序编辑,选择原材料 + + **从数据库查询选择** + + `Connor_AVIC_MEOPSQL_[对象类型]_[属性真实名称]` + + 配置**工艺编辑**视图界面中对应[属性真实名称]的选择按钮逻辑 + + ```text + 配置sql查询语句,配置信息写到自定义表头中,注意表头需要加双引号 + 表头格式:“[#]界面列名[=属性位置.属性名称[=默认列宽]]” + #:表示添加该列的查询 + 注意存在查询条件时需要在末尾准备好where关键字 + + 添加单个对象到选择版本的关系下: + 1. 通过UID添加,格式“UID=关系名称=默认列宽”,需要查询出需要添加的对象的UID,列宽设置为零则不会在界面中显示 + 2. 通过ID添加,格式“ID=关系名称=默认列宽”,需要查询出需要添加的对象的ID,列宽设置为零则不会在界面中显示,添加对象的最新版本 + ``` + + 示例 + + ```text + 首选项名称:Connor_AVIC_MEOPSQL_SF6_GMEP_object_name + 值: + select + pobject_name "#名称=item.object_name=200", + puid "UID=NHL8_MaterialRlation=0" + from pworkspaceobject + where 1=1 + ``` + +3. 工步编辑从数据表选择 + + **从数据库查询选择** + + `Connor_AVIC_GXBZ_SelectSql_[当前视图选择的对象类型]` + + ```text + 配置sql查询语句,配置信息写到自定义表头中,注意表头需要加双引号 + 表头格式:“[#]界面列名[=反写属性名称[=默认列宽]]” + #:表示添加该列的查询 + 注意存在查询条件时需要在末尾准备好where关键字 + ``` + + 示例 + + ```text + 首选项名称:Connor_AVIC_GXBZ_SelectSql_MEOP + 值: + select + pobject_name "#名称=object_name=200", + puid "UID=object_desc" + from pworkspaceobject + where 1=1 + ``` + diff --git a/cn.net.connor.std.processedit/build.properties b/cn.net.connor.std.processedit/build.properties new file mode 100644 index 0000000..eed0977 --- /dev/null +++ b/cn.net.connor.std.processedit/build.properties @@ -0,0 +1,8 @@ +source.. = src/ +output.. = bin/ +bin.includes = plugin.xml,\ + META-INF/,\ + .,\ + icons/,\ + lib/jsqlparser-4.3.jar,\ + lib/jacob.jar diff --git a/cn.net.connor.std.processedit/icons/T.png b/cn.net.connor.std.processedit/icons/T.png new file mode 100644 index 0000000..7e07e95 Binary files /dev/null and b/cn.net.connor.std.processedit/icons/T.png differ diff --git a/cn.net.connor.std.processedit/icons/add_24px.png b/cn.net.connor.std.processedit/icons/add_24px.png new file mode 100644 index 0000000..34c2886 Binary files /dev/null and b/cn.net.connor.std.processedit/icons/add_24px.png differ diff --git a/cn.net.connor.std.processedit/icons/delete_24px.png b/cn.net.connor.std.processedit/icons/delete_24px.png new file mode 100644 index 0000000..5e33b13 Binary files /dev/null and b/cn.net.connor.std.processedit/icons/delete_24px.png differ diff --git a/cn.net.connor.std.processedit/icons/down_24px.png b/cn.net.connor.std.processedit/icons/down_24px.png new file mode 100644 index 0000000..5188b82 Binary files /dev/null and b/cn.net.connor.std.processedit/icons/down_24px.png differ diff --git a/cn.net.connor.std.processedit/icons/edit16.png b/cn.net.connor.std.processedit/icons/edit16.png new file mode 100644 index 0000000..a743326 Binary files /dev/null and b/cn.net.connor.std.processedit/icons/edit16.png differ diff --git a/cn.net.connor.std.processedit/icons/folder_24.png b/cn.net.connor.std.processedit/icons/folder_24.png new file mode 100644 index 0000000..8b04344 Binary files /dev/null and b/cn.net.connor.std.processedit/icons/folder_24.png differ diff --git a/cn.net.connor.std.processedit/icons/meoperation_16.png b/cn.net.connor.std.processedit/icons/meoperation_16.png new file mode 100644 index 0000000..d31bd13 Binary files /dev/null and b/cn.net.connor.std.processedit/icons/meoperation_16.png differ diff --git a/cn.net.connor.std.processedit/icons/meprocess_16.png b/cn.net.connor.std.processedit/icons/meprocess_16.png new file mode 100644 index 0000000..125f218 Binary files /dev/null and b/cn.net.connor.std.processedit/icons/meprocess_16.png differ diff --git a/cn.net.connor.std.processedit/icons/reorder.png b/cn.net.connor.std.processedit/icons/reorder.png new file mode 100644 index 0000000..9fe1a82 Binary files /dev/null and b/cn.net.connor.std.processedit/icons/reorder.png differ diff --git a/cn.net.connor.std.processedit/icons/sample.png b/cn.net.connor.std.processedit/icons/sample.png new file mode 100644 index 0000000..02c4b79 Binary files /dev/null and b/cn.net.connor.std.processedit/icons/sample.png differ diff --git a/cn.net.connor.std.processedit/icons/sample@2x.png b/cn.net.connor.std.processedit/icons/sample@2x.png new file mode 100644 index 0000000..c1224d1 Binary files /dev/null and b/cn.net.connor.std.processedit/icons/sample@2x.png differ diff --git a/cn.net.connor.std.processedit/icons/search-2.png b/cn.net.connor.std.processedit/icons/search-2.png new file mode 100644 index 0000000..b925df1 Binary files /dev/null and b/cn.net.connor.std.processedit/icons/search-2.png differ diff --git a/cn.net.connor.std.processedit/icons/search.png b/cn.net.connor.std.processedit/icons/search.png new file mode 100644 index 0000000..b0a0594 Binary files /dev/null and b/cn.net.connor.std.processedit/icons/search.png differ diff --git a/cn.net.connor.std.processedit/icons/sort-line-2.png b/cn.net.connor.std.processedit/icons/sort-line-2.png new file mode 100644 index 0000000..5fe38f5 Binary files /dev/null and b/cn.net.connor.std.processedit/icons/sort-line-2.png differ diff --git a/cn.net.connor.std.processedit/icons/sort-line.png b/cn.net.connor.std.processedit/icons/sort-line.png new file mode 100644 index 0000000..9cb626c Binary files /dev/null and b/cn.net.connor.std.processedit/icons/sort-line.png differ diff --git a/cn.net.connor.std.processedit/icons/text.png b/cn.net.connor.std.processedit/icons/text.png new file mode 100644 index 0000000..24a206b Binary files /dev/null and b/cn.net.connor.std.processedit/icons/text.png differ diff --git a/cn.net.connor.std.processedit/icons/up_24px.png b/cn.net.connor.std.processedit/icons/up_24px.png new file mode 100644 index 0000000..94e9cc8 Binary files /dev/null and b/cn.net.connor.std.processedit/icons/up_24px.png differ diff --git a/cn.net.connor.std.processedit/lib/cn.net.connor.std.aifrcp_13000.1.0.jar b/cn.net.connor.std.processedit/lib/cn.net.connor.std.aifrcp_13000.1.0.jar new file mode 100644 index 0000000..5206255 Binary files /dev/null and b/cn.net.connor.std.processedit/lib/cn.net.connor.std.aifrcp_13000.1.0.jar differ diff --git a/cn.net.connor.std.processedit/lib/cn.net.connor.std.fx_13000.1.0.jar b/cn.net.connor.std.processedit/lib/cn.net.connor.std.fx_13000.1.0.jar new file mode 100644 index 0000000..97aabfd Binary files /dev/null and b/cn.net.connor.std.processedit/lib/cn.net.connor.std.fx_13000.1.0.jar differ diff --git a/cn.net.connor.std.processedit/lib/cn.net.connor.std.gdtex_13000.1.0.jar b/cn.net.connor.std.processedit/lib/cn.net.connor.std.gdtex_13000.1.0.jar new file mode 100644 index 0000000..598fbc7 Binary files /dev/null and b/cn.net.connor.std.processedit/lib/cn.net.connor.std.gdtex_13000.1.0.jar differ diff --git a/cn.net.connor.std.processedit/lib/jacob-1.18.zip b/cn.net.connor.std.processedit/lib/jacob-1.18.zip new file mode 100644 index 0000000..5ff043f Binary files /dev/null and b/cn.net.connor.std.processedit/lib/jacob-1.18.zip differ diff --git a/cn.net.connor.std.processedit/lib/jacob.jar b/cn.net.connor.std.processedit/lib/jacob.jar new file mode 100644 index 0000000..c35ad12 Binary files /dev/null and b/cn.net.connor.std.processedit/lib/jacob.jar differ diff --git a/cn.net.connor.std.processedit/lib/jfxswt.jar b/cn.net.connor.std.processedit/lib/jfxswt.jar new file mode 100644 index 0000000..2c5c7f1 Binary files /dev/null and b/cn.net.connor.std.processedit/lib/jfxswt.jar differ diff --git a/cn.net.connor.std.processedit/lib/jsqlparser-4.3.jar b/cn.net.connor.std.processedit/lib/jsqlparser-4.3.jar new file mode 100644 index 0000000..cff6c65 Binary files /dev/null and b/cn.net.connor.std.processedit/lib/jsqlparser-4.3.jar differ diff --git a/cn.net.connor.std.processedit/plugin.xml b/cn.net.connor.std.processedit/plugin.xml new file mode 100644 index 0000000..9bbdab8 --- /dev/null +++ b/cn.net.connor.std.processedit/plugin.xml @@ -0,0 +1,272 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/Activator.java b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/Activator.java new file mode 100644 index 0000000..dfa88fc --- /dev/null +++ b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/Activator.java @@ -0,0 +1,44 @@ +package cn.net.connor.std.processedit; + +import org.eclipse.ui.plugin.AbstractUIPlugin; +import org.osgi.framework.BundleContext; + +/** + * The activator class controls the plug-in life cycle + */ +public class Activator extends AbstractUIPlugin { + + // The plug-in ID + public static final String PLUGIN_ID = "cn.net.connor.std.processedit"; //$NON-NLS-1$ + + // The shared instance + private static Activator plugin; + + /** + * The constructor + */ + public Activator() { + } + + @Override + public void start(BundleContext context) throws Exception { + super.start(context); + plugin = this; + } + + @Override + public void stop(BundleContext context) throws Exception { + plugin = null; + super.stop(context); + } + + /** + * Returns the shared instance + * + * @return the shared instance + */ + public static Activator getDefault() { + return plugin; + } + +} diff --git a/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/KStartup.java b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/KStartup.java new file mode 100644 index 0000000..3769677 --- /dev/null +++ b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/KStartup.java @@ -0,0 +1,27 @@ +package cn.net.connor.std.processedit; + +import java.lang.reflect.Method; + +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.IStartup; + +import javafx.embed.swt.FXCanvas; + +public class KStartup implements IStartup { + + @Override + public void earlyStartup() { + Display.getDefault().asyncExec(()->{ + try { + Class c = FXCanvas.class; + Method m = c.getDeclaredMethod("initFx", new Class[0]); + m.setAccessible(true); + m.invoke(FXCanvas.class, new Object[0]); + System.out.println("FXCanvas inited"); + } catch (Exception e) { + e.printStackTrace(); + } + }); + } + +} diff --git a/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/choose/ChooseDialog.java b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/choose/ChooseDialog.java new file mode 100644 index 0000000..e379aef --- /dev/null +++ b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/choose/ChooseDialog.java @@ -0,0 +1,187 @@ +package cn.net.connor.std.processedit.choose; + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.ArrayList; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextField; + +import com.teamcenter.rac.aif.AbstractAIFDialog; +import com.teamcenter.rac.util.MessageBox; +import com.teamcenter.rac.util.Registry; + +import cn.net.connor.std.aifrcp.KDialog; +import cn.net.connor.std.aifrcp.KDialogController; +import cn.net.connor.std.aifrcp.util.KUtil; + +@SuppressWarnings("serial") +public class ChooseDialog extends KDialog { + + private ChooseDialogController controller; + private JButton b_ok; + private JButton b_cel; + private JButton b_search; + private static final Registry REG = Registry.getRegistry(ChooseDialog.class); + + public ChooseDialog(AbstractAIFDialog newMeopDialog, KDialogController controller) { + super(newMeopDialog,true,controller); + this.controller = (ChooseDialogController) controller; + } + + @Override + protected void addListeners() { + this.b_cel.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + disposeDialog(); + } + }); + this.b_ok.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + try { + controller.doSelect(); + } catch (Exception e1) { + e1.printStackTrace(); + MessageBox.post(ChooseDialog.this,e1); + } + } + }); + this.b_search.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + try { + controller.doSearch(); + } catch (Exception e1) { + e1.printStackTrace(); + MessageBox.post(ChooseDialog.this,e1); + } + } + }); + } + + @Override + protected void initUI() { + this.setTitle(REG.getString("select.TITLE")); + this.setPreferredSize(new Dimension(900, 500)); + this.setMinimumSize(new Dimension(550, 400)); + this.setLayout(new BorderLayout()); + this.add(BorderLayout.CENTER, initTablePanel()); + this.add(BorderLayout.EAST, initSearchPanel()); + } + + private Component initBtnPanel() { + JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 0)); + panel.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0)); + this.b_search = new JButton(REG.getString("search")); + this.b_ok = new JButton(REG.getString("ok")); + this.b_cel = new JButton(REG.getString("cancel")); + if (controller.searchCols.size() > 0) { + panel.add(b_search); + } + panel.add(b_ok); + panel.add(b_cel); + return panel; + } + + private Component initSearchPanel() { + JPanel panel = new JPanel(new BorderLayout()); + if (controller.searchCols.size() == 0) { + this.add(BorderLayout.SOUTH, initBtnPanel()); + return panel; + } + JPanel searchPanel = new JPanel(new GridBagLayout()); + searchPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + GridBagConstraints s = getGridBagConstraints(0, 0, new Insets(5, 5, 5, 5)); + for (String title : controller.searchCols) { + + //20241119 ӹ + if(title.equals("")) { + KUtil.newRow(searchPanel, new JLabel(title), s, 1); + JComboBox jComboBox = new JComboBox(); + //ȡ + ArrayList array = new ArrayList(); + Object[][] data = controller.tableBean.data; + for (int i = 0; i < data.length; i++) { + System.out.println("================================"+data[i][0]); + if(!array.contains(data[i][0])) { + array.add((String)data[i][0]); + jComboBox.addItem((String)data[i][0]); + } + } + controller.jComboboxMap.put(title, jComboBox); + KUtil.addCol(searchPanel, jComboBox, s, 1, 1); + jComboBox.addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent e) { + if (e.getStateChange() == ItemEvent.SELECTED) { + System.out.println("Selected: " + e.getItem()); + b_search.doClick(); + } + } + }); + + }else { + KUtil.newRow(searchPanel, new JLabel(title), s, 1); + JTextField textField = new JTextField(12); + controller.searchComps.put(title, textField); + KUtil.addCol(searchPanel, textField, s, 1, 1); + textField.addKeyListener(new KeyAdapter() { + public void keyPressed(KeyEvent e) { + if (e.getKeyChar() == KeyEvent.VK_ENTER) { + b_search.doClick(); + } + } + }); + } + + + + } + s.weighty = 1; + KUtil.newRow(searchPanel, new JLabel(""), s, 1); + JScrollPane scroll = new JScrollPane(searchPanel); + scroll.setBorder(null); + panel.add(BorderLayout.CENTER, scroll); + panel.add(BorderLayout.SOUTH, initBtnPanel()); + return panel; + } + + private Component initTablePanel() { + JPanel panel = new JPanel(new BorderLayout()); + panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 0)); + JScrollPane scroll = new JScrollPane(controller.tableBean.getTable()); + panel.add(BorderLayout.CENTER, scroll); + if(!controller.isNHJSChooseSafeDesc) { + controller.tableBean.getTable().addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + if(e.getButton() == MouseEvent.BUTTON1 && e.getClickCount()==2) { + b_ok.doClick(); + } + } + }); + } + return panel; + } + +} diff --git a/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/choose/ChooseDialogController.java b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/choose/ChooseDialogController.java new file mode 100644 index 0000000..ef43346 --- /dev/null +++ b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/choose/ChooseDialogController.java @@ -0,0 +1,182 @@ +package cn.net.connor.std.processedit.choose; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import javax.swing.JComboBox; +import javax.swing.JTextArea; +import javax.swing.JTextField; + +import com.teamcenter.rac.aif.AbstractAIFApplication; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCException; +import com.teamcenter.rac.util.Registry; + +import cn.net.connor.std.aifrcp.KDialogController; +import cn.net.connor.std.aifrcp.util.KUtil; +import cn.net.connor.std.processedit.util.KExcelTable; +import cn.net.connor.std.processedit.util.KExcelTable.Config; +import cn.net.connor.std.processedit.util.PrefComponent; + +public class ChooseDialogController extends KDialogController { + + private String typeName; + private String[] config; + private List prefComponents; + // private Map otherComps; + private ChooseDialog dialog; + protected File excelFile; + protected List configs = new ArrayList(); + protected List searchCols = new ArrayList(); + protected Map searchComps = new HashMap(); + protected Map> jComboboxMap = new HashMap>(); + protected KExcelTable tableBean; + protected boolean isNHJSChooseSafeDesc = false; + private static final String PREFIX_NHJS_CHOOSE_SAFE_DESC = "#NHJS_SAFE_DESC#"; + private static final Registry REG = Registry.getRegistry(ChooseDialogController.class); + + public ChooseDialogController(AbstractAIFApplication app, String type, PrefComponent bean, List prefComponents) { + this.typeName = type; + this.config = bean.getExcelConfig(); + this.prefComponents = prefComponents; + } + + @Override + public boolean init() throws Exception { + this.dialog = (ChooseDialog) aifDialog; + int len = KUtil.getLen(config); + if (len == 0) { + System.out.println("No Choose Config"); + throw new TCException(REG.getString("novalidchooseconfig.ERROR")); + } + String uid = config[0]; + this.isNHJSChooseSafeDesc = uid.startsWith(PREFIX_NHJS_CHOOSE_SAFE_DESC); + if(this.isNHJSChooseSafeDesc) { + uid = uid.substring(PREFIX_NHJS_CHOOSE_SAFE_DESC.length()); + } + System.out.println(">> Uid: " + uid); + if (!KUtil.isEmpty(typeName)) { + int ind = uid.indexOf("" + typeName + ":"); + if (ind > 0) { + uid = uid.substring(ind + typeName.length() + 1); + } + } + int ind = uid.indexOf(';'); + if (ind > 0) { + uid = uid.substring(0, ind); + } + System.out.println(">> Uid for type [" + typeName + "] is: " + uid); + if (KUtil.isEmpty(uid)) { + throw new TCException(REG.getString("novalidchooseconfig.ERROR")); + } + TCComponentDataset excelDataset = null; + try { + excelDataset = (TCComponentDataset) session.stringToComponent(uid); + } catch (Exception e) { + e.printStackTrace(); + } + if (excelDataset == null || !"MSExcelX".equals(excelDataset.getType())) { + throw new TCException(REG.getString("novalidchooseconfig.ERROR")); + } + // Read Config + for (int i = 1; i < len; i++) { + String pref = config[i]; + String[] split = pref.split("=", -1); + int splitCnt = KUtil.getLen(split); + String tableCol = null, excelCol = null, propConfig = null; + int prefW = 100; + if (splitCnt > 0) { + tableCol = split[0]; + } + if (splitCnt > 1) { + excelCol = split[1]; + } + if (splitCnt > 2) { + propConfig = split[2]; + } + if (splitCnt > 3) { + try { + prefW = Integer.parseInt(split[3]); + } catch (Exception e) { + e.printStackTrace(); + } + } + if (!KUtil.isEmpty(tableCol) && !KUtil.isEmpty(excelCol)) { + if (tableCol.startsWith("#")) { + tableCol = tableCol.substring(1); + System.out.println(">> Add Search: " + tableCol); + if (!this.searchCols.contains(tableCol)) { + this.searchCols.add(tableCol); + } + } + this.configs.add(new Config(tableCol, excelCol, propConfig, prefW)); + } else { + System.out.println("ERROR Config: " + pref); + } + } + this.excelFile = KUtil.getDatasetFile(excelDataset); + if (this.excelFile == null || !this.excelFile.exists()) { + throw new TCException(REG.getString("novalidchooseconfig.ERROR")); + } + this.tableBean = new KExcelTable(configs, excelFile.getAbsolutePath(), this.isNHJSChooseSafeDesc); + return true; + } + + public void doSearch() throws Exception { + Map searchInfo = new HashMap(); + System.out.println("Perform Search.."); + for (String colName : this.searchComps.keySet()) { + String value = this.searchComps.get(colName).getText(); + if (!KUtil.isEmpty(value)) { + System.out.println(">> " + colName + " = " + value); + searchInfo.put(colName, value); + } + } + //20241119 ӹ + for (String colName : this.jComboboxMap.keySet()) { + String value = (String)this.jComboboxMap.get(colName).getSelectedItem(); + if (!KUtil.isEmpty(value)) { + System.out.println(">>---------------- " + colName + " = " + value); + searchInfo.put(colName, value); + } + } + this.tableBean.performSearch(searchInfo); + } + + public void doSelect() throws Exception { + LinkedHashMap data = this.tableBean.getSelectedData(); + if (data == null || data.size() <= 0) { + System.out.println("No Select Info"); + dialog.disposeDialog(); + return; + } + System.out.println("Selected Row: " + Arrays.toString(data.values().toArray())); + for (Config colConfig : data.keySet()) { + String val = data.get(colConfig); + String addition = colConfig.getAdditionalInfo(); + if (KUtil.isEmpty(addition)) { + continue; + } + System.out.println(">> Set " + addition + " = " + val); + for (PrefComponent comp : this.prefComponents) { + if (addition.equals(comp.getPropConfig())) { + System.out.println(comp.getValueComp()); + if (comp.getValueComp() instanceof JTextArea) { + // 安全说明进行追加 + JTextArea textArea = (JTextArea) comp.getValueComp(); + textArea.setText(textArea.getText() + val); + } else { + comp.setValue(val); + } + } + } + } + dialog.disposeDialog(); + } + +} diff --git a/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/choose/choose.properties b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/choose/choose.properties new file mode 100644 index 0000000..fd21fb9 --- /dev/null +++ b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/choose/choose.properties @@ -0,0 +1,5 @@ +select.TITLE=\u9009\u62E9 +search=\u67E5\u8BE2 +ok=\u786E\u5B9A +cancel=\u53D6\u6D88 +novalidchooseconfig.ERROR=\u6CA1\u6709\u627E\u5230\u6709\u6548\u914D\u7F6E diff --git a/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/choosefromsql/ChooseFromSqlDialog.java b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/choosefromsql/ChooseFromSqlDialog.java new file mode 100644 index 0000000..bf54938 --- /dev/null +++ b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/choosefromsql/ChooseFromSqlDialog.java @@ -0,0 +1,158 @@ +package cn.net.connor.std.processedit.choosefromsql; + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.List; +import java.util.Map; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextField; + +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.util.MessageBox; +import com.teamcenter.rac.util.Registry; + +import cn.net.connor.std.aifrcp.KDialog; +import cn.net.connor.std.aifrcp.util.KUtil; +import cn.net.connor.std.processedit.util.PrefComponent; + +@SuppressWarnings("serial") +public class ChooseFromSqlDialog extends KDialog { + + private ChooseFromSqlDialogController controller; + private JButton b_ok; + private JButton b_cel; + private JButton b_search; + protected String[] config; + protected List prefComponents; + protected Map revChildren; + private static final Registry REG = Registry.getRegistry(ChooseFromSqlDialog.class); + + public ChooseFromSqlDialog(PrefComponent bean, List prefComponents, Map revChildren) { + super(); + this.config = bean.getSqlConfig(); + this.prefComponents = prefComponents; + this.revChildren = revChildren; + } + + @Override + protected void addListeners() { + this.b_cel.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + disposeDialog(); + } + }); + this.b_ok.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + try { + controller.doSelect(); + } catch (Exception e1) { + e1.printStackTrace(); + MessageBox.post(ChooseFromSqlDialog.this, e1); + } + } + }); + this.b_search.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + try { + controller.doSearch(); + } catch (Exception e1) { + e1.printStackTrace(); + MessageBox.post(ChooseFromSqlDialog.this, e1); + } + } + }); + } + + @Override + protected void initUI() { + this.controller = (ChooseFromSqlDialogController) aifController; + this.setTitle(REG.getString("select.TITLE")); + this.setPreferredSize(new Dimension(900, 500)); + this.setMinimumSize(new Dimension(550, 400)); + this.setLayout(new BorderLayout()); + this.add(BorderLayout.CENTER, initTablePanel()); + this.add(BorderLayout.WEST, initSearchPanel()); + } + + private Component initBtnPanel() { + JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 0)); + panel.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0)); + this.b_search = new JButton(REG.getString("search")); + this.b_ok = new JButton(REG.getString("ok")); + this.b_cel = new JButton(REG.getString("cancel")); + if (controller.searchCols_DB_UI.size() > 0) { + panel.add(b_search); + } + panel.add(b_ok); + panel.add(b_cel); + return panel; + } + + private Component initSearchPanel() { + JPanel panel = new JPanel(new BorderLayout()); + if (controller.searchCols_DB_UI.size() == 0) { + this.add(BorderLayout.SOUTH, initBtnPanel()); + return panel; + } + JPanel searchPanel = new JPanel(new GridBagLayout()); + searchPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 10)); + GridBagConstraints s = getGridBagConstraints(0, 0, new Insets(0, 10, 10, 0)); + for (String dbColName : controller.searchCols_DB_UI.keySet()) { + String title = controller.searchCols_DB_UI.get(dbColName); + KUtil.newRow(searchPanel, new JLabel(title), s, 1); + JTextField textField = new JTextField(12); + controller.searchComps.put(dbColName, textField); + KUtil.addCol(searchPanel, textField, s, 1, 1); + textField.addKeyListener(new KeyAdapter() { + public void keyPressed(KeyEvent e) { + if (e.getKeyChar() == KeyEvent.VK_ENTER) { + b_search.doClick(); + } + } + }); + } + s.weighty = 1; + KUtil.newRow(searchPanel, new JLabel(""), s, 1); + JScrollPane scroll = new JScrollPane(searchPanel); + scroll.setBorder(null); + panel.add(BorderLayout.CENTER, scroll); + panel.add(BorderLayout.SOUTH, initBtnPanel()); + return panel; + } + + private Component initTablePanel() { + JPanel panel = new JPanel(new BorderLayout()); + panel.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 10)); + JScrollPane scroll = new JScrollPane(controller.tableBean.getTable()); + panel.add(BorderLayout.CENTER, scroll); + controller.tableBean.getTable().addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) { + b_ok.doClick(); + } + } + }); + return panel; + } + +} diff --git a/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/choosefromsql/ChooseFromSqlDialogController.java b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/choosefromsql/ChooseFromSqlDialogController.java new file mode 100644 index 0000000..d904801 --- /dev/null +++ b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/choosefromsql/ChooseFromSqlDialogController.java @@ -0,0 +1,242 @@ +package cn.net.connor.std.processedit.choosefromsql; + +import java.io.StringReader; +import java.sql.Connection; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import javax.swing.JTextField; + +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentItem; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCComponentItemType; +import com.teamcenter.rac.kernel.TCException; +import com.teamcenter.rac.util.Registry; + +import cn.net.connor.std.aifrcp.KDialogController; +import cn.net.connor.std.aifrcp.util.KSqlUtil; +import cn.net.connor.std.aifrcp.util.KUtil; +import cn.net.connor.std.processedit.util.KSqlTable; +import cn.net.connor.std.processedit.util.KSqlTable.Config; +import cn.net.connor.std.processedit.util.PrefComponent; +import cn.net.connor.std.processedit.util.ProcessUtil; +import net.sf.jsqlparser.JSQLParserException; +import net.sf.jsqlparser.expression.Alias; +import net.sf.jsqlparser.parser.CCJSqlParserManager; +import net.sf.jsqlparser.statement.Statement; +import net.sf.jsqlparser.statement.select.AllTableColumns; +import net.sf.jsqlparser.statement.select.PlainSelect; +import net.sf.jsqlparser.statement.select.Select; +import net.sf.jsqlparser.statement.select.SelectExpressionItem; +import net.sf.jsqlparser.statement.select.SelectItem; + +public class ChooseFromSqlDialogController extends KDialogController { + + private String[] config; + private List prefComponents; + // private Map otherComps; + private ChooseFromSqlDialog dialog; + protected List configs = new ArrayList(); + protected Map searchCols_DB_UI = new LinkedHashMap<>(); + protected Map searchComps = new HashMap(); + protected KSqlTable tableBean; + private Map revChildren; + private TCComponentItemType itemType; + private static final Registry REG = Registry.getRegistry(ChooseFromSqlDialogController.class); + + public static void getTableNameBySql(String sql, List headers, List fields) throws JSQLParserException { + try { + CCJSqlParserManager pm = new CCJSqlParserManager(); + Statement statement = pm.parse(new StringReader(sql)); + if (statement instanceof Select) { + Select selectStatement = (Select) statement; + PlainSelect selectBody = (PlainSelect) selectStatement.getSelectBody(); + List selectItemlist = selectBody.getSelectItems(); + SelectItem selectItem = null; + SelectExpressionItem selectExpressionItem = null; + AllTableColumns allTableColumns = null; + Alias alias = null; + if (selectItemlist != null) { + for (int i = 0; i < selectItemlist.size(); i++) { + selectItem = selectItemlist.get(i); + if (selectItem instanceof SelectExpressionItem) { + selectExpressionItem = (SelectExpressionItem) selectItemlist.get(i); + alias = selectExpressionItem.getAlias(); + String columnName = ""; + if (alias != null) { + columnName = alias.getName(); + } else { + columnName = selectExpressionItem.getExpression().toString(); + } + headers.add(columnName); + fields.add(selectExpressionItem.getExpression().toString()); + } else if (selectItem instanceof AllTableColumns) { + allTableColumns = (AllTableColumns) selectItemlist.get(i); + headers.add(allTableColumns.toString()); + fields.add(allTableColumns.toString()); + } else { + headers.add(selectItem.toString()); + fields.add(selectItem.toString()); + } + + } + } + } + } catch (JSQLParserException e) { + e.printStackTrace(); + } + } + + @Override + public boolean init() throws Exception { + this.dialog = (ChooseFromSqlDialog) aifDialog; + this.config = dialog.config; + this.prefComponents = dialog.prefComponents; + this.revChildren = dialog.revChildren; + int len = KUtil.getLen(config); + if (len == 0) { + System.out.println("No Choose Config"); + throw new TCException(REG.getString("novalidchooseconfig.ERROR")); + } + String sql = String.join("\n", config); + System.out.println(">> sql: \n" + sql); + List headers = new ArrayList<>(); + List fields = new ArrayList<>(); + getTableNameBySql(sql, headers, fields); + System.out.println(">> headers: " + headers); + System.out.println(">> fields: " + fields); + len = headers == null ? 0 : headers.size(); + // Read Config + for (int i = 0; i < len; i++) { + String dbColName = headers.get(i); + String dbFieldName = fields.get(i); + String[] split = dbColName.replace("\"", "").split("=", -1); + int splitCnt = KUtil.getLen(split); + String tableCol = null, propConfig = null; + int prefW = 100; + if (splitCnt > 0) { + tableCol = split[0]; + } + if (splitCnt > 1) { + propConfig = split[1]; + } + if (splitCnt > 2) { + try { + prefW = Integer.parseInt(split[2]); + } catch (Exception e) { + e.printStackTrace(); + } + } + if (!KUtil.isEmpty(tableCol)) { + if (tableCol.startsWith("#")) { + tableCol = tableCol.substring(1); + System.out.println(">> Add Search: " + tableCol); + if (!this.searchCols_DB_UI.containsKey(dbFieldName)) { + this.searchCols_DB_UI.put(dbFieldName, tableCol); + } + } + this.configs.add(new Config(tableCol, dbFieldName, propConfig, prefW)); + } else { + System.out.println("ERROR Config: " + dbColName); + } + if (dbColName.startsWith("\"")) { + sql = sql.replace(dbColName, ""); + } + } + System.out.println("Formated Sql: \n" + sql); + this.tableBean = new KSqlTable(configs, sql); + this.itemType = (TCComponentItemType) session.getTypeComponent("Item"); + return true; + } + + public void doSearch() throws Exception { + Map searchInfo = new HashMap(); + System.out.println("Perform Search.."); + for (String colName : this.searchComps.keySet()) { + String value = this.searchComps.get(colName).getText(); + if (!KUtil.isEmpty(value)) { + System.out.println(">> " + colName + " = " + value); + searchInfo.put(colName, value); + } + } + Connection conn = KSqlUtil.getOracleConnection(session, ProcessUtil.PREF_DB_CONN); + try { + this.tableBean.performSearch(searchInfo, conn); + } finally { + KSqlUtil.free(conn); + } + } + + public void doSelect() throws Exception { + revChildren.clear(); + LinkedHashMap data = this.tableBean.getSelectedData(); + if (data == null || data.size() <= 0) { + System.out.println("No Select Info"); + dialog.disposeDialog(); + return; + } + System.out.println("Selected Row: " + Arrays.toString(data.values().toArray())); + for (Config colConfig : data.keySet()) { + String val = data.get(colConfig); + String addition = colConfig.getAdditionalInfo(); + if (KUtil.isEmpty(addition)) { + continue; + } + if ("UID".equalsIgnoreCase(colConfig.getColName())) { + String relationName = addition; + System.out.println(">> Add " + relationName + " = " + val); + if (!KUtil.isEmpty(val)) { + TCComponent comp = null; + try { + comp = session.stringToComponent(val); + } catch (TCException e) { + e.printStackTrace(); + } + System.out.println(">> Find component: " + comp); + if (comp == null) { + throw new TCException(REG.getString("loaduid.ERROR")); + } + revChildren.put(relationName, comp); + } + continue; + } else if ("ID".equalsIgnoreCase(colConfig.getColName())) { + String relationName = addition; + System.out.println(">> Add " + relationName + " = " + val); + if (!KUtil.isEmpty(val)) { + TCComponent[] items = null; + try { + items = itemType.findItems(val); + } catch (TCException e) { + e.printStackTrace(); + } + System.out.println(">> Find item: " + Arrays.toString(items)); + int itemCnt = KUtil.getLen(items); + TCComponentItemRevision rev = null; + for (int i = 0; i < itemCnt; i++) { + TCComponentItem item = (TCComponentItem) items[i]; + rev = item.getLatestItemRevision(); + } + System.out.println(">> Revision: " + rev); + if (rev == null) { + throw new TCException(String.format(REG.getString("loadid.ERROR1"), val)); + } + revChildren.put(relationName, rev); + } + continue; + } + System.out.println(">> Set " + addition + " = " + val); + for (PrefComponent comp : this.prefComponents) { + if (addition.equals(comp.getPropConfig())) { + comp.setValue(val); + } + } + } + dialog.disposeDialog(); + } + +} diff --git a/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/choosefromsql/choosefromsql.properties b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/choosefromsql/choosefromsql.properties new file mode 100644 index 0000000..2b1aba1 --- /dev/null +++ b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/choosefromsql/choosefromsql.properties @@ -0,0 +1,7 @@ +select.TITLE=\u9009\u62E9 +search=\u67E5\u8BE2 +ok=\u786E\u5B9A +cancel=\u53D6\u6D88 +novalidchooseconfig.ERROR=\u6CA1\u6709\u627E\u5230\u6709\u6548\u914D\u7F6E +loaduid.ERROR=\u65E0\u6CD5\u52A0\u8F7D\u5BF9\u8C61\uFF0C\u8BF7\u68C0\u67E5\u662F\u5426\u6709\u76F8\u5173\u6743\u9650\u3002 +loadid.ERROR1=\u672A\u627E\u5230\u5BF9\u8C61\u201C%s\u201D\u7684\u6700\u65B0\u7248\u672C \ No newline at end of file diff --git a/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/commands/ModifyMeopNoCommand.java b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/commands/ModifyMeopNoCommand.java new file mode 100644 index 0000000..bd42fd6 --- /dev/null +++ b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/commands/ModifyMeopNoCommand.java @@ -0,0 +1,15 @@ +package cn.net.connor.std.processedit.commands; + +import com.teamcenter.rac.aif.AbstractAIFApplication; + +import cn.net.connor.std.aifrcp.KCommand; +import cn.net.connor.std.processedit.modifymeopno.ModifyMeopNoDialog; + +public class ModifyMeopNoCommand extends KCommand{ + + public ModifyMeopNoCommand(AbstractAIFApplication app, String commandId, String actionInfo) { + super(app, commandId, actionInfo); + this.setRunnable(new ModifyMeopNoDialog()); + } + +} diff --git a/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/commands/NewDatasetFromTemplateCommand.java b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/commands/NewDatasetFromTemplateCommand.java new file mode 100644 index 0000000..1060e88 --- /dev/null +++ b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/commands/NewDatasetFromTemplateCommand.java @@ -0,0 +1,15 @@ +package cn.net.connor.std.processedit.commands; + +import com.teamcenter.rac.aif.AbstractAIFApplication; + +import cn.net.connor.std.aifrcp.KCommand; +import cn.net.connor.std.processedit.newdatasetfromtemplate.NewDatasetFromTemplateOperation; + +public class NewDatasetFromTemplateCommand extends KCommand{ + + public NewDatasetFromTemplateCommand(AbstractAIFApplication app, String commandId, String actionInfo) { + super(app, commandId, actionInfo); + this.setRunnable(new NewDatasetFromTemplateOperation(app, actionInfo)); + } + +} diff --git a/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/commands/NewMeopCommand.java b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/commands/NewMeopCommand.java new file mode 100644 index 0000000..c77df7b --- /dev/null +++ b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/commands/NewMeopCommand.java @@ -0,0 +1,17 @@ +package cn.net.connor.std.processedit.commands; + +import com.teamcenter.rac.aif.AbstractAIFApplication; + +import cn.net.connor.std.aifrcp.KCommand; +import cn.net.connor.std.processedit.newmeop.NewMeopDialog; +import cn.net.connor.std.processedit.newmeop.NewMeopDialogController; + +public class NewMeopCommand extends KCommand { + + public NewMeopCommand(AbstractAIFApplication app, String commandId, String actionInfo) { + super(app, commandId, actionInfo); + System.out.println("NewMeopCommand"); + this.setRunnable(new NewMeopDialog(new NewMeopDialogController(app))); + } + +} diff --git a/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/commands/NewProcessCommand.java b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/commands/NewProcessCommand.java new file mode 100644 index 0000000..ae8c7ba --- /dev/null +++ b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/commands/NewProcessCommand.java @@ -0,0 +1,17 @@ +package cn.net.connor.std.processedit.commands; + +import com.teamcenter.rac.aif.AbstractAIFApplication; + +import cn.net.connor.std.aifrcp.KCommand; +import cn.net.connor.std.processedit.newmeprocess.NewProcessDialog; +import cn.net.connor.std.processedit.newmeprocess.NewProcessDialogController; + +public class NewProcessCommand extends KCommand{ + + public NewProcessCommand(AbstractAIFApplication app, String commandId, String actionInfo) { + super(app, commandId, actionInfo); + System.out.println("NewProcessCommand"); + this.setRunnable(new NewProcessDialog(new NewProcessDialogController(app))); + } + +} diff --git a/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/commands/OpenViewCommand.java b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/commands/OpenViewCommand.java new file mode 100644 index 0000000..dcf22f4 --- /dev/null +++ b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/commands/OpenViewCommand.java @@ -0,0 +1,75 @@ +package cn.net.connor.std.processedit.commands; + +import java.util.Arrays; + +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.IViewPart; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchWindow; + +import com.teamcenter.rac.aif.AbstractAIFApplication; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.cme.time.common.ActivityUtils; +import com.teamcenter.rac.cme.time.common.CommonUtils; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentBOMLine; +import com.teamcenter.rac.kernel.TCComponentCfgActivityLine; +import com.teamcenter.rac.kernel.TCException; +import com.teamcenter.rac.util.MessageBox; +import com.teamcenter.rac.util.PlatformHelper; + +import cn.net.connor.std.aifrcp.KCommand; +import cn.net.connor.std.aifrcp.util.KUtil; + +public class OpenViewCommand extends KCommand { + + public OpenViewCommand(AbstractAIFApplication app, String commandId, String actionInfo) { + super(app, commandId, actionInfo); + } + + + @Override + protected void executeCommand() throws Exception { + System.out.println("Open View: " + actionInfo); + if (KUtil.isEmpty(actionInfo)) { + return; + } + Display.getDefault().asyncExec(new Runnable() { + @Override + public void run() { + try { + IWorkbenchWindow var1 = AIFUtility.getActiveDesktop().getDesktopWindow(); + IWorkbenchPage var2 = var1.getActivePage(); + IViewPart sv = var2.findView(actionInfo); + if (sv == null) { + sv = var2.showView(actionInfo); + } + PlatformHelper.getCurrentPage().activate(sv); + } catch (Exception e) { + e.printStackTrace(); + } + } + }); + } + + + protected void test() throws Exception{ + TCComponentBOMLine targetLine = (TCComponentBOMLine) app.getTargetComponent(); + TCComponentCfgActivityLine actLine = (TCComponentCfgActivityLine) targetLine.getReferenceProperty("bl_me_activity_lines"); + if (actLine != null) { + TCComponent[] cc = ActivityUtils.getSortedActivityChildren(actLine); + System.out.println(">> " + Arrays.toString(cc)); + int len = KUtil.getLen(cc); + if (len > 1) { + CommonUtils.getSession().suspendEvent(); + try { + ActivityUtils.moveActivityBefore(cc[1], cc[0]); + } catch (TCException tCException) { + MessageBox.post(tCException); + } finally { + CommonUtils.getSession().resumeEvent(); + } + } + } + } +} diff --git a/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/MEOPEditView.java b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/MEOPEditView.java new file mode 100644 index 0000000..b494043 --- /dev/null +++ b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/MEOPEditView.java @@ -0,0 +1,67 @@ +package cn.net.connor.std.processedit.meopviewfx; + +import java.util.List; + +import org.eclipse.swt.layout.FillLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.ui.IWorkbenchPart; + +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.ui.views.AbstractContentViewPart; + +import cn.net.connor.std.processedit.meopviewfx.ui.MEOPPanel; +import javafx.embed.swt.FXCanvas; +import javafx.scene.Scene; + +public class MEOPEditView extends AbstractContentViewPart { + public static final String ID = MEOPEditView.class.getName(); + private Object currentObj = null; + private MEOPPanel meopPanel; + + @Override + protected void processEmptySelection(IWorkbenchPart iWorkbenchPart, List list) { + System.out.println("333333333333333333333"); + if (list == null || list.size() != 1) { + return; + } + final Object target = list.get(0); + if (target != null && !(target.equals(currentObj))) { + System.out.println("Select: " + target); + currentObj = target; + new Thread(new Runnable() { + @Override + public void run() { + if (meopPanel != null) + meopPanel.updateSelection(target); + } + }).start(); + } + System.out.println("555555555555555555555555555555555"); + } + + public MEOPEditView() { + System.out.println("1111111111111111111111111111"); + this.setProcessNullSelectionsEnabled(true); + this.setUseScrolledForm(false); + this.setShowHeader(true); + this.setMultiSelectionSupported(true); + this.setUISupportsAssociate(false); + this.setUISupportsSetScope(false); + this.setUISupportsViewLocking(true); + this.setUseInitialInputJobEnabled(false); + this.setProcessSelectionFromSiblingViewEnabled(true); + System.out.println("22222222222222222222222"); + } + + @Override + protected void createContent(Composite parent) { + System.out.println("Init UI..."); + parent.setLayout(new FillLayout()); + FXCanvas fxCanvas = new FXCanvas(parent, 16777216); + this.meopPanel = new MEOPPanel(AIFUtility.getCurrentApplication().getDesktop()); + Scene scene = this.meopPanel.getScene(); + System.out.println("Init UI Complete"); + fxCanvas.setScene(scene); + } + +} \ No newline at end of file diff --git a/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/bean/KTableRow.java b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/bean/KTableRow.java new file mode 100644 index 0000000..daae5ef --- /dev/null +++ b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/bean/KTableRow.java @@ -0,0 +1,334 @@ +package cn.net.connor.std.processedit.meopviewfx.bean; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.SoaUtil; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentBOMLine; +import com.teamcenter.rac.kernel.TCComponentItem; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCComponentItemType; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.services.internal.rac.structuremanagement.StructureService; +import com.teamcenter.services.internal.rac.structuremanagement._2011_06.Structure; + +import cn.net.connor.std.aifrcp.util.KUtil; +import javafx.beans.property.SimpleStringProperty; +import javafx.scene.layout.Region; +import javafx.scene.web.WebEngine; +import javafx.scene.web.WebView; + +public class KTableRow { + + public static final String BOMLINE = "BOMLINE"; + public static final String ITEM = "ITEM"; + public static final String ITEMMASTER = "ITEMMASTER"; + public static final String REV = "REV"; + public static final String REVMASTER = "REVMASTER"; + private static double ZOOM = 1; + static { + try { + ZOOM = ((TCSession) AIFUtility.getCurrentApplication().getSession()).getPreferenceService().getDoubleValue("Connor_LY6_GXBZ_Web_Zoom"); + } catch (Exception e) { + } + if (ZOOM < 0) { + ZOOM = 1; + } + System.out.println("GDT ZOOM = " + ZOOM); + } + + private TCComponentBOMLine bomline; + private TCComponentItem item; + private TCComponentItemRevision rev; + private TCComponent itemMaster; + private TCComponent revMaster; + private boolean showWebView = true; + private WebView webView; + private String webContent; + + public KTableRow(TCComponentBOMLine bomline, TCComponentItem item, TCComponentItemRevision rev, TCComponent itemMaster, TCComponent revMaster) { + this.bomline = bomline; + this.item = item; + this.rev = rev; + this.itemMaster = itemMaster; + this.revMaster = revMaster; + } + + public Map stringProps = new HashMap(); + protected Map savedValues = new HashMap(); + + public TCComponentBOMLine getBomLine() { + return this.bomline; + } + + public void setValueByPropName(String config, String value) throws Exception { + if (KUtil.isEmpty(config)) { + return; + } + System.out.println("Set Row Value [" + config + "] = [" + value + "]"); + for (PropConfig propConfig : stringProps.keySet()) { + if (config.equalsIgnoreCase(propConfig.propName)) { + stringProps.get(propConfig).setValue(value); + } + } + System.out.println(">> config not found"); + } + + public boolean parseConfig(PropConfig config) throws Exception { + if (config == null) { + return true; + } + String value = getTCValue(config.propLoc, config.propName); + stringProps.put(config, new SimpleStringProperty(value)); + savedValues.put(config, value); + if (!KUtil.isEmpty(config.filterValue)) { + // && !config.filterValue.equals(value) + // 20200722 split filter + String[] filters = config.filterValue.split(";"); + boolean checkOK = false; + for (String string : filters) { + if (string.equals(value)) { + checkOK = true; + break; + } + } + return checkOK; + } + return true; + } + + public String getTCValue(String proploc, String propName) throws Exception { + TCComponent comp = getTCComponent(proploc); + if (comp == null) { + return ""; + } + return comp.getStringProperty(propName); + } + + public TCComponent getTCComponent(String proploc) { + if (KUtil.isEmpty(proploc)) { + return bomline; + } + proploc = proploc.toUpperCase(); + switch (proploc) { + case BOMLINE: + return bomline; + case ITEM: + return item; + case REV: + return rev; + case ITEMMASTER: + return itemMaster; + case REVMASTER: + return revMaster; + default: + System.out.println(">> Prop location error: " + proploc); + break; + } + return null; + } + + private boolean loadTCValues(Map bomlinePropMap, Map itemPropMap, Map revPropMap, Map itemMasterPropMap, + Map revMasterPropMap) { + boolean modified = false; + for (PropConfig config : stringProps.keySet()) { + if (!config.canEdit) { + continue; + } + String value = stringProps.get(config).getValueSafe(); + if (savedValues.containsKey(config)) { + String savedValue = savedValues.get(config); + if (value.equals(savedValue)) { + continue; + } + } + modified = true; + String propName = config.propName; + String proploc = config.propLoc.toUpperCase(); + System.out.println(">> " + proploc + "." + propName + " = " + value); + switch (proploc) { + case BOMLINE: + bomlinePropMap.put(propName, value); + break; + case ITEM: + itemPropMap.put(propName, value); + if ("object_name".equals(propName)) { + revPropMap.put(propName, value); + } + break; + case REV: + revPropMap.put(propName, value); + if ("object_name".equals(propName)) { + itemPropMap.put(propName, value); + } + break; + case ITEMMASTER: + itemMasterPropMap.put(propName, value); + break; + case REVMASTER: + revMasterPropMap.put(propName, value); + break; + default: + System.out.println(">> Prop location error: " + proploc); + break; + } + } + return modified; + } + + public void saveTCData(TCComponentBOMLine parentLine, TCComponentItemType itemType, int precise, TCComponent viewTypeTag) throws Exception { + if (bomline == null) { + if (itemType != null && parentLine != null) { + System.out.println("Create New Row..."); + item = itemType.create(itemType.getNewID(), itemType.getNewRev(null), itemType.getName(), "-", "", null); + System.out.println(">> new item: " + item); + rev = item.getLatestItemRevision(); + itemMaster = item.getRelatedComponent("IMAN_master_form"); + revMaster = rev.getRelatedComponent("IMAN_master_form_rev"); + bomline = parentLine.add(item, rev, null, false, ""); + } + } + if (bomline == null) { + return; + } + System.out.println("Update: " + bomline + ", Precise = " + precise); + if (precise != 0) { + TCComponent[] bvrs = rev.getReferenceListProperty("structure_revisions"); + System.out.println("BVR: " + Arrays.toString(bvrs)); + if (KUtil.getLen(bvrs) == 0) { + TCSession session = rev.getSession(); + StructureService structureService = StructureService.getService(session); + Structure.CreateOrSaveAsPSBOMViewRevisionResponse createOrSaveAsPSBOMViewRevisionResponse = null; + Structure.CreateOrSaveAsPSBOMViewRevisionInput[] arrayOfCreateOrSaveAsPSBOMViewRevisionInput = new Structure.CreateOrSaveAsPSBOMViewRevisionInput[1]; + arrayOfCreateOrSaveAsPSBOMViewRevisionInput[0] = new Structure.CreateOrSaveAsPSBOMViewRevisionInput(); + (arrayOfCreateOrSaveAsPSBOMViewRevisionInput[0]).clientId = (new Integer(0)).toString(); + (arrayOfCreateOrSaveAsPSBOMViewRevisionInput[0]).isPrecise = precise > 0; + (arrayOfCreateOrSaveAsPSBOMViewRevisionInput[0]).viewTypeTag = viewTypeTag; + (arrayOfCreateOrSaveAsPSBOMViewRevisionInput[0]).itemObject = rev.getItem(); + (arrayOfCreateOrSaveAsPSBOMViewRevisionInput[0]).itemRevObj = rev; + createOrSaveAsPSBOMViewRevisionResponse = structureService.createOrSavePSBOMViewRevision(arrayOfCreateOrSaveAsPSBOMViewRevisionInput); + SoaUtil.checkPartialErrors(createOrSaveAsPSBOMViewRevisionResponse.serviceData); + } else { + bomline.setPrecision(precise > 0); + } + } + Map revPropMap = new HashMap<>(); + Map revMasterPropMap = new HashMap<>(); + Map itemPropMap = new HashMap<>(); + Map itemMasterPropMap = new HashMap<>(); + Map bomlinePropMap = new HashMap<>(); + if (!loadTCValues(bomlinePropMap, itemPropMap, revPropMap, itemMasterPropMap, revMasterPropMap)) { + return; + } + if (itemPropMap.size() > 0) { + item.setProperties(itemPropMap); + } + if (revPropMap.size() > 0) { + rev.setProperties(revPropMap); + } + if (itemMasterPropMap.size() > 0) { + itemMaster.setProperties(itemMasterPropMap); + } + if (revMasterPropMap.size() > 0) { + revMaster.setProperties(revMasterPropMap); + } + if (bomlinePropMap.size() > 0) { + bomline.setProperties(bomlinePropMap); + } + bomline.refresh(); + } + + public void removeLine() throws Exception { + if (bomline != null) { + System.out.println(">> Remove: " + bomline); + bomline.cut(); + } + } + + public void showWebView(boolean showWebView) { + this.showWebView = showWebView; + } + + public boolean showWebView() { + return showWebView; + } + + public WebView getWebView() { + return this.webView; + } + + public WebView checkWebView() { + if (!showWebView) { + return null; + } + if (webView == null) { + webView = new WebView(); + webView.setDisable(true); + webView.setMouseTransparent(true); + webView.setPrefHeight(Region.USE_COMPUTED_SIZE); + webView.setZoom(ZOOM); + // webView.getEngine().documentProperty().addListener((obj, prev, newv) -> { + // if (newv == null) { + // return; + // } + // try { + // // String heightText = webView.getEngine().executeScript( + // // "var body = document.body, html = document.documentElement;Math.max( + // // body.scrollHeight, body.offsetHeight, html.clientHeight, + // html.scrollHeight, + // // html.offsetHeight );") + // // .toString(); + // + // // double height = Double.parseDouble(heightText.replace("px", "")); + // // webView.setPrefHeight(height + 12); + // // System.out.println("Set Height [" + getTCComponent(BOMLINE) + "]: " + + // // height); + // new Thread(() -> { + // Platform.runLater(() -> { + // String heightText = webView.getEngine().executeScript("var body = + // document.body, html = document.documentElement;Math.max( body.scrollHeight, + // body.offsetHeight );") + // .toString(); + // double height2 = Double.parseDouble(heightText.replace("px", "")) + 12; + // System.out.println("Set Height [" + getTCComponent(BOMLINE) + "][" + + // webView.getWidth() + "]: " + height2); + // webView.setPrefHeight(height2); + // webView.getParent().layout(); + // webView.layout(); + // }); + // }).start(); + // } catch (Exception e) { + // e.printStackTrace(); + // } + // }); + // webView.getEngine().getLoadWorker().stateProperty().addListener(new + // ChangeListener() { + // @Override + // public void changed(ObservableValue observable, State + // oldValue, State newValue) { + // if (newValue == State.SUCCEEDED) { + // // webView.setPrefHeight(Region.USE_COMPUTED_SIZE); + // } + // } + // }); + } + return webView; + } + + public void loadContent(String html) { + if (html == null) { + html = ""; + } + if (html.equals(this.webContent)) { + return; + } + webView.setPrefWidth(Region.USE_COMPUTED_SIZE); + webView.setPrefHeight(Region.USE_COMPUTED_SIZE); + WebEngine engine = webView.getEngine(); + this.webContent = html; + engine.loadContent(html); + } +} diff --git a/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/bean/KTableRowBackup20220509.java b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/bean/KTableRowBackup20220509.java new file mode 100644 index 0000000..0341356 --- /dev/null +++ b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/bean/KTableRowBackup20220509.java @@ -0,0 +1,217 @@ +package cn.net.connor.std.processedit.meopviewfx.bean; + +import java.util.HashMap; +import java.util.Map; + +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentBOMLine; +import com.teamcenter.rac.kernel.TCComponentItem; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCComponentItemType; + +import cn.net.connor.std.aifrcp.util.KUtil; +import javafx.beans.property.SimpleStringProperty; + +public class KTableRowBackup20220509 { + + public static final String BOMLINE = "BOMLINE"; + public static final String ITEM = "ITEM"; + public static final String ITEMMASTER = "ITEMMASTER"; + public static final String REV = "REV"; + public static final String REVMASTER = "REVMASTER"; + + private TCComponentBOMLine bomline; + private TCComponentItem item; + private TCComponentItemRevision rev; + private TCComponent itemMaster; + private TCComponent revMaster; + private boolean showWebView = true; + + public KTableRowBackup20220509(TCComponentBOMLine bomline, TCComponentItem item, TCComponentItemRevision rev, TCComponent itemMaster, TCComponent revMaster) { + this.bomline = bomline; + this.item = item; + this.rev = rev; + this.itemMaster = itemMaster; + this.revMaster = revMaster; + } + + public Map stringProps = new HashMap(); + protected Map savedValues = new HashMap(); + + public TCComponentBOMLine getBomLine() { + return this.bomline; + } + + public void setValueByPropName(String config, String value) throws Exception{ + if(KUtil.isEmpty(config)) { + return; + } + System.out.println("Set Row Value ["+config+"] = ["+value+"]"); + for (PropConfig propConfig : stringProps.keySet()) { + if(config.equalsIgnoreCase(propConfig.propName)) { + stringProps.get(propConfig).setValue(value); + } + } + System.out.println(">> config not found"); + } + + public boolean parseConfig(PropConfig config) throws Exception { + if (config == null) { + return true; + } + String value = getTCValue(config.propLoc, config.propName); + stringProps.put(config, new SimpleStringProperty(value)); + savedValues.put(config, value); + if (!KUtil.isEmpty(config.filterValue)) { + // && !config.filterValue.equals(value) + // 20200722 split filter + String[] filters = config.filterValue.split(";"); + boolean checkOK = false; + for (String string : filters) { + if (string.equals(value)) { + checkOK = true; + break; + } + } + return checkOK; + } + return true; + } + + public String getTCValue(String proploc, String propName) throws Exception { + TCComponent comp = getTCComponent(proploc); + if (comp == null) { + return ""; + } + return comp.getStringProperty(propName); + } + + public TCComponent getTCComponent(String proploc) { + if (KUtil.isEmpty(proploc)) { + return bomline; + } + proploc = proploc.toUpperCase(); + switch (proploc) { + case BOMLINE: + return bomline; + case ITEM: + return item; + case REV: + return rev; + case ITEMMASTER: + return itemMaster; + case REVMASTER: + return revMaster; + default: + System.out.println(">> Prop location error: " + proploc); + break; + } + return null; + } + + private boolean loadTCValues(Map bomlinePropMap, Map itemPropMap, Map revPropMap, Map itemMasterPropMap, + Map revMasterPropMap) { + boolean modified = false; + for (PropConfig config : stringProps.keySet()) { + if (!config.canEdit) { + continue; + } + String value = stringProps.get(config).getValueSafe(); + if (savedValues.containsKey(config)) { + String savedValue = savedValues.get(config); + if (value.equals(savedValue)) { + continue; + } + } + modified = true; + String propName = config.propName; + String proploc = config.propLoc.toUpperCase(); + System.out.println(">> " + proploc + "." + propName + " = " + value); + switch (proploc) { + case BOMLINE: + bomlinePropMap.put(propName, value); + break; + case ITEM: + itemPropMap.put(propName, value); + if ("object_name".equals(propName)) { + revPropMap.put(propName, value); + } + break; + case REV: + revPropMap.put(propName, value); + if ("object_name".equals(propName)) { + itemPropMap.put(propName, value); + } + break; + case ITEMMASTER: + itemMasterPropMap.put(propName, value); + break; + case REVMASTER: + revMasterPropMap.put(propName, value); + break; + default: + System.out.println(">> Prop location error: " + proploc); + break; + } + } + return modified; + } + + public void saveTCData(TCComponentBOMLine parentLine, TCComponentItemType itemType) throws Exception { + if (bomline == null) { + if (itemType != null && parentLine != null) { + System.out.println("Create New Row..."); + item = itemType.create(itemType.getNewID(), itemType.getNewRev(null), itemType.getName(), "-", "", null); + System.out.println(">> new item: " + item); + rev = item.getLatestItemRevision(); + itemMaster = item.getRelatedComponent("IMAN_master_form"); + revMaster = rev.getRelatedComponent("IMAN_master_form_rev"); + bomline = parentLine.add(item, rev, null, false, ""); + } + } + if (bomline == null) { + return; + } + System.out.println("Update: " + bomline); + Map revPropMap = new HashMap<>(); + Map revMasterPropMap = new HashMap<>(); + Map itemPropMap = new HashMap<>(); + Map itemMasterPropMap = new HashMap<>(); + Map bomlinePropMap = new HashMap<>(); + if (!loadTCValues(bomlinePropMap, itemPropMap, revPropMap, itemMasterPropMap, revMasterPropMap)) { + return; + } + if (itemPropMap.size() > 0) { + item.setProperties(itemPropMap); + } + if (revPropMap.size() > 0) { + rev.setProperties(revPropMap); + } + if (itemMasterPropMap.size() > 0) { + itemMaster.setProperties(itemMasterPropMap); + } + if (revMasterPropMap.size() > 0) { + revMaster.setProperties(revMasterPropMap); + } + if (bomlinePropMap.size() > 0) { + bomline.setProperties(bomlinePropMap); + } + bomline.refresh(); + } + + public void removeLine() throws Exception { + if (bomline != null) { + System.out.println(">> Remove: " + bomline); + bomline.cut(); + } + } + + public void showWebView(boolean showWebView) { + this.showWebView = showWebView; + } + + public boolean showWebView() { + return showWebView; + } + +} diff --git a/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/bean/KTableRowMEActivity.java b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/bean/KTableRowMEActivity.java new file mode 100644 index 0000000..9eaf910 --- /dev/null +++ b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/bean/KTableRowMEActivity.java @@ -0,0 +1,113 @@ +package cn.net.connor.std.processedit.meopviewfx.bean; + +import java.util.HashMap; +import java.util.Map; + +import com.teamcenter.rac.cme.time.common.ActivityUtils; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentCfgActivityLine; +import com.teamcenter.rac.kernel.TCComponentMEActivity; +import com.teamcenter.rac.kernel.TCComponentMEActivityType; +import com.teamcenter.rac.kernel.TCComponentMECfgLine; + +import cn.net.connor.std.aifrcp.util.KUtil; + +public class KTableRowMEActivity extends KTableRow { + + public TCComponentCfgActivityLine actline; + private TCComponentMEActivity folder; + + public KTableRowMEActivity(TCComponentCfgActivityLine bomline,TCComponentMEActivity folder) { + super(null,null,null,null,null); + this.actline = bomline; + this.folder = folder; + } + + @Override + public TCComponent getTCComponent(String proploc) { + if(KUtil.isEmpty(proploc)) { + return folder; + } + proploc = proploc.toUpperCase(); + switch (proploc) { + case BOMLINE: + return actline; + case ITEM: + return folder; + default: + System.out.println(">> Prop location error: " + proploc); + break; + } + return null; + } + + private boolean loadTCValues(Map bomlinePropMap , Map itemPropMap) { + boolean modified = false; + for (PropConfig config : stringProps.keySet()) { + if(!config.canEdit) { + continue; + } + String value = stringProps.get(config).getValueSafe(); + String propName = config.propName; + String proploc = config.propLoc.toUpperCase(); + if(savedValues.containsKey(config)) { + String savedValue = savedValues.get(config); + if(value.equals(savedValue)) { + continue; + } + } + modified = true; + System.out.println(">> "+proploc+"."+propName+" = "+value); + switch(proploc) { + case BOMLINE: + bomlinePropMap.put(propName, value); + break; + case ITEM: + itemPropMap.put(propName, value); + break; + default: + System.out.println(">> Prop location error: " + proploc); + break; + } + } + return modified; + } + + public void saveTCData(TCComponentCfgActivityLine parentLine, TCComponentMEActivityType itemType) throws Exception{ + if(actline==null) { + if(itemType!=null&&parentLine!=null) { + System.out.println("Create New Activity..."); + folder= itemType.createActivity("-", itemType.getName(), "", 0.0D); + System.out.println(">> New Activity: "+folder); + this.actline = (TCComponentCfgActivityLine) ActivityUtils.addActivity(parentLine, folder); + System.out.println(">> New Line: "+this.actline); + } + } + if(actline==null) { + return; + } + System.out.println("Update: "+actline); + Map itemPropMap = new HashMap<>(); + Map bomlinePropMap = new HashMap<>(); + if(!loadTCValues(bomlinePropMap, itemPropMap)) { + System.out.println(">> No modified property"); + return; + } + if(itemPropMap.size()>0) { + folder.setProperties(itemPropMap); + } + if(bomlinePropMap.size()>0) { + actline.setProperties(bomlinePropMap); + } + actline.refresh(); + } + + @Override + public void removeLine() throws Exception{ + if(actline!=null) { + System.out.println(">> Remove Activity: "+actline); + ActivityUtils.removeActivity((TCComponentMECfgLine)actline); + } + } + +} diff --git a/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/bean/PropConfig.java b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/bean/PropConfig.java new file mode 100644 index 0000000..a2fd32e --- /dev/null +++ b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/bean/PropConfig.java @@ -0,0 +1,61 @@ +package cn.net.connor.std.processedit.meopviewfx.bean; + +import com.teamcenter.rac.kernel.TCComponentListOfValues; +import com.teamcenter.rac.kernel.TCPropertyDescriptor; + +import javafx.scene.control.Control; + +public class PropConfig { + public String propName; + public String propDisplayName; + public String propLoc; + public TCComponentListOfValues lov; + public String filterValue; + public TCPropertyDescriptor propDesc; + public int width; + public int maxCharacterInRow; + public boolean canEdit; + private Control control; + private Object savedValue; + public int height; + + public PropConfig(String propLoc, TCPropertyDescriptor propDesc, String filterValue, int width, int height, int maxCharacterInRow) { + this.propName = propDesc.getName(); + this.propDisplayName = propDesc.getDisplayName(); + this.propLoc = propLoc; + this.filterValue = filterValue; + this.lov = propDesc.getLOV(); + this.propDesc = propDesc; + this.width = width; + this.height = height; + this.maxCharacterInRow = maxCharacterInRow; + // this.canEdit = + // propDesc.isModifiable()&&!"bl_occ_type".equals(propName)&&!"item_id".equals(propName); + this.canEdit = propDesc.isModifiable() && !"item_id".equals(propName); + System.out.println(propName + " >> " + lov + " >> " + canEdit + " >> " + width + "x" + height); + } + + public void setSavedValue(Object savedValue) { + this.savedValue = savedValue; + } + + public boolean valueChanged(Object newValue) { + if (savedValue != null) { + return !savedValue.equals(newValue); + } + return newValue != null; + } + + public void setControl(Control control) { + this.control = control; + } + + public Control getControl() { + return control; + } + + @Override + public String toString() { + return propName; + } +} diff --git a/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/bean/TextBean.java b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/bean/TextBean.java new file mode 100644 index 0000000..041577a --- /dev/null +++ b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/bean/TextBean.java @@ -0,0 +1,46 @@ +package cn.net.connor.std.processedit.meopviewfx.bean; + +import java.util.ArrayList; +import java.util.List; + +import cn.net.connor.std.aifrcp.util.KUtil; + +public class TextBean { + + private String text; + private String realValue; + public List children = new ArrayList(); + + public TextBean(String text) { + this.text = text; + } + + public void setRealValue(String realValue) { + this.realValue = realValue; + } + + public String getRealValue() { + return KUtil.isEmpty(realValue)?text:realValue; + } + + public String getDisplayValue() { + return text; + } + + @Override + public String toString() { + return getDisplayValue(); + } + + @Override + public boolean equals(Object obj) { + if(obj==null) { + return false; + } + if(obj instanceof TextBean) { + return text.equals(((TextBean) obj).text); + } + return false; + } + +} diff --git a/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/reorder/ReorderDialog.java b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/reorder/ReorderDialog.java new file mode 100644 index 0000000..349391a --- /dev/null +++ b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/reorder/ReorderDialog.java @@ -0,0 +1,134 @@ +package cn.net.connor.std.processedit.meopviewfx.reorder; + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.FlowLayout; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.Map; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JPanel; + +import com.teamcenter.rac.kernel.TCException; +import com.teamcenter.rac.util.MessageBox; +import com.teamcenter.rac.util.Registry; +import com.teamcenter.rac.util.iTextField; + +import cn.net.connor.std.aifrcp.KDialog; +import cn.net.connor.std.aifrcp.util.KUtil; +import cn.net.connor.std.processedit.meopviewfx.bean.KTableRow; +import cn.net.connor.std.processedit.meopviewfx.bean.PropConfig; +import javafx.application.Platform; +import javafx.scene.control.TableView; + +@SuppressWarnings("serial") +public class ReorderDialog extends KDialog { + + public static final Registry REG = Registry.getRegistry(ReorderDialog.class); + private JButton b_Ok; + private JButton b_Cancel; + private iTextField tf_startNum; + private iTextField tf_stepNum; + private int startNum; + private int stepNum; + private TableView table; + private Map sequenceConfigMap; + + public ReorderDialog(TableView table, Map sequenceConfigMap) { + super(); + this.table = table; + this.sequenceConfigMap = sequenceConfigMap; + } + + @Override + protected void addListeners() { + b_Cancel.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + disposeDialog(); + } + }); + b_Ok.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + try { + loadNumbers(); + disposeDialog(); + } catch (Exception e1) { + e1.printStackTrace(); + MessageBox.post(ReorderDialog.this, e1); + } + } + }); + } + + protected void loadNumbers() throws Exception { + String startNumStr = tf_startNum.getText().trim(); + String stepNumStr = tf_stepNum.getText().trim(); + if (KUtil.isEmpty(startNumStr) || KUtil.isEmpty(stepNumStr)) { + throw new TCException(REG.getString("require.error")); + } + this.startNum = -1; + this.stepNum = -1; + try { + startNum = Integer.parseInt(startNumStr); + } catch (NumberFormatException e) { + e.printStackTrace(); + throw new TCException(String.format(REG.getString("format.error1"), startNumStr)); + } + try { + stepNum = Integer.parseInt(stepNumStr); + } catch (NumberFormatException e) { + e.printStackTrace(); + throw new TCException(String.format(REG.getString("format.error1"), stepNumStr)); + } + Platform.runLater(() -> { + KTableRow[] rows = table.getItems().toArray(new KTableRow[] {}); + int len = KUtil.getLen(rows); + for (int i = 0; i < len; i++) { + KTableRow row = rows[i]; + String seq = String.valueOf(startNum + i * stepNum); + for (PropConfig sequenceConfig : this.sequenceConfigMap.keySet()) { + row.stringProps.get(sequenceConfig).setValue(seq); + } + } + int maxSeq = startNum + stepNum * (len - 1); + for (PropConfig sequenceConfig : this.sequenceConfigMap.keySet()) { + sequenceConfigMap.put(sequenceConfig, maxSeq); + } + }); + } + + @Override + protected void initUI() { + this.setTitle(REG.getString("dialog.title")); + this.setLayout(new BorderLayout()); + this.add(BorderLayout.CENTER, initCenterPanel()); + this.add(BorderLayout.SOUTH, initBtnPanel()); + } + + private Component initBtnPanel() { + JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 25, 8)); + panel.add(this.b_Ok = new JButton(REG.getString("ok.btn"))); + panel.add(this.b_Cancel = new JButton(REG.getString("cancel.btn"))); + return panel; + } + + private Component initCenterPanel() { + JPanel panel = new JPanel(new GridBagLayout()); + GridBagConstraints s = getGridBagConstraints(0, 0, new Insets(8, 8, 0, 0)); + panel.setBorder(BorderFactory.createEmptyBorder(0, 0, 8, 8)); + KUtil.newRow(panel, new JLabel(REG.getString("startnum.label")), s, 1); + KUtil.addCol(panel, this.tf_startNum = new iTextField(16, true), s, 1, 0); + KUtil.newRow(panel, new JLabel(REG.getString("stepnum.label")), s, 1); + KUtil.addCol(panel, this.tf_stepNum = new iTextField(16, true), s, 1, 0); + return panel; + } + +} diff --git a/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/reorder/ReorderDialogController.java b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/reorder/ReorderDialogController.java new file mode 100644 index 0000000..3539e97 --- /dev/null +++ b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/reorder/ReorderDialogController.java @@ -0,0 +1,12 @@ +package cn.net.connor.std.processedit.meopviewfx.reorder; + +import cn.net.connor.std.aifrcp.KDialogController; + +public class ReorderDialogController extends KDialogController{ + + @Override + public boolean init() throws Exception { + return true; + } + +} diff --git a/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/reorder/reorder.properties b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/reorder/reorder.properties new file mode 100644 index 0000000..237f9ed --- /dev/null +++ b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/reorder/reorder.properties @@ -0,0 +1,7 @@ +dialog.title=\u5BF9\u7ED3\u6784\u91CD\u6392\u5E8F +ok.btn=\u786E\u5B9A +cancel.btn=\u53D6\u6D88 +startnum.label=\u5F00\u59CB\u6570\u5B57\uFF1A +stepnum.label=\u589E\u91CF\uFF1A +format.error1=\u201C%s\u201D\u4E0D\u662F\u6709\u6548\u7684\u503C +require.error=\u8BF7\u586B\u5199\u5FC5\u586B\u503C \ No newline at end of file diff --git a/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/ui/KFXEditableStringAreaHtmlTableCell.java b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/ui/KFXEditableStringAreaHtmlTableCell.java new file mode 100644 index 0000000..645ec70 --- /dev/null +++ b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/ui/KFXEditableStringAreaHtmlTableCell.java @@ -0,0 +1,323 @@ +package cn.net.connor.std.processedit.meopviewfx.ui; + +import com.teamcenter.rac.treetable.SwingTextContextActivator; +import com.teamcenter.rac.util.Utilities; + +import cn.net.connor.std.aifrcp.util.KUtil; +import cn.net.connor.std.fx.KFXTextLocator; +import cn.net.connor.std.gdtex.KGenerateGDTHTML; +import cn.net.connor.std.processedit.meopviewfx.bean.KTableRow; +import cn.net.connor.std.processedit.meopviewfx.bean.PropConfig; +import javafx.beans.value.ChangeListener; +import javafx.beans.value.ObservableValue; +import javafx.event.Event; +import javafx.geometry.Bounds; +import javafx.scene.control.TableCell; +import javafx.scene.control.TableColumn; +import javafx.scene.control.TableColumn.CellEditEvent; +import javafx.scene.control.TablePosition; +import javafx.scene.control.TableRow; +import javafx.scene.control.TableView; +import javafx.scene.control.TextArea; +import javafx.scene.input.KeyCode; +import javafx.scene.text.Text; +import javafx.scene.web.WebView; + +/** + * select color: + * + * .table-row-cell .ktext { -fx-fill: black; } + * + * .table-row-cell:selected .ktext { -fx-fill: white; } + * + * .table-cell .ktext { -fx-fill: black; } + * + * .table-cell:selected .ktext { -fx-fill: white; } + * + * @author Administrator + * + * @param + * @param + */ + +public class KFXEditableStringAreaHtmlTableCell extends TableCell { + + protected PropConfig config; + protected TextArea textArea; + + // private static final Registry REG = + // Registry.getRegistry(KFXEditableStringAreaHtmlTableCell.class); + // private static int FONTSIZE = -1; + // static { + // try { + // // String zoomStr = REG.getString("zoom"); + // // if (!KUtil.isEmpty(zoomStr)) { + // // double d = Double.parseDouble(zoomStr); + // // System.out.println("Zoom: " + d); + // // ZOOM = d; + // // } + // // FONTSIZE = REG.getInt("fontsize", -1); + // } catch (Exception e) { + // } + // if (ZOOM < 0) { + // ZOOM = 1; + // } + // } + protected ChangeListener changeListener = (obs, ov, nv) -> { + if (!nv) { + commitEdit(textArea.getText()); + } + }; + private Text text; + private KFXTextLocator textLocator; + + public KFXEditableStringAreaHtmlTableCell(PropConfig config, KFXTextLocator textLocator) { + super(); + this.config = config; + this.textLocator = textLocator; + // this.localToSceneTransformProperty().addListener((obs, oldIndex, newIndex) -> + // { + // if (getGraphic() == null || oldIndex==newIndex) { + // return; + // } + // if(!(getGraphic() instanceof WebView)) { + // return; + // } + // }); + + } + + @Override + public void startEdit() { + if (editableProperty().get()) { + if (!isEmpty()) { + super.startEdit(); + createTextField(); + setText(null); + setGraphic(textArea); + textArea.requestFocus(); + } + } + } + + public void startEdit(int temp) { + if (isEditing()) { + System.out.println("=====>" + temp); + textArea.positionCaret(temp); + } + } + + public KTableRow showWebView() { + Object obj = null; + try { + obj = super.getTableRow().getItem(); + } catch (Exception e1) { + } + if (obj != null && (obj instanceof KTableRow)) { + WebView webView = ((KTableRow) obj).checkWebView(); + if (webView != null) { + webView.setOnScroll(e -> { + Event.fireEvent(KFXEditableStringAreaHtmlTableCell.this, e); + }); + // webView.setOnMouseClicked(null); + // if (isEditable()) { + // webView.setOnMouseClicked(e -> { + // System.out.println("?????????/"); + // TableView table = getTableView(); + // if (table == null) { + // return; + // } + // TableRow row = getTableRow(); + // int rowNum = row.getIndex(); + // if (rowNum < 0) { + // return; + // } + // TableColumn col = getTableColumn(); + // if (e.getButton() != MouseButton.PRIMARY || e.getClickCount() != 2) { + // table.getSelectionModel().select(rowNum, col); + // return; + // } + // KTableRow bean = (KTableRow) table.getItems().get(rowNum); + // bean.showWebView(false); + // updateItem(getItem(), isEmpty()); + // table.layout(); + // table.edit(rowNum, col); + // }); + // } + return ((KTableRow) obj); + } + } + return null; + } + + @Override + public void cancelEdit() { + super.cancelEdit(); + // setText((String) getItem()); + // setGraphic(null); + KTableRow webView = showWebView(); + if (webView != null) { + setGraphic(webView.getWebView()); + } else { + setGraphic(text); + } + } + + @Override + public void updateItem(String item, boolean empty) { + super.updateItem(item, empty); + // if (webView == null) { + // createWebView(); + // } + if (text == null) { + text = new Text(); + text.wrappingWidthProperty().bind(getTableColumn().widthProperty().subtract(20)); + text.textProperty().bind(itemProperty()); + text.getStyleClass().add("ktext"); + text.layoutBoundsProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, Bounds oldValue, Bounds newValue) { + KTableRow webView = showWebView(); + if (webView == null) { + return; + } + double height = text.getLayoutBounds().getHeight() + 30; // +20 is for paddings + webView.getWebView().setPrefHeight(height); + } + }); + } + KTableRow webView = showWebView(); + if (empty) { + setText(null); + setGraphic(null); + } else if (webView != null) { + String newValue = item; + String html = KUtil.isEmpty(newValue) || newValue.startsWith("") ? newValue : KGenerateGDTHTML.generatePage(newValue); + // createWebView(html); + webView.loadContent(html); + setGraphic(webView.getWebView()); + double height = text.getLayoutBounds().getHeight() + 30; // +20 is for paddings + // System.out.println("Set Height [" + webView.getTCComponent(KTableRow.BOMLINE) + // + "]: " + height); + webView.getWebView().setPrefHeight(height); + // webView.setPrefHeight(Region.USE_COMPUTED_SIZE); + // Platform.runLater(() -> { + // try { + // // System.out.println("Load Html: " + newValue); + // // System.out.println(">> " + html); + // String html = newValue == null || newValue.startsWith("") ? newValue : + // GenerateGDTHTML.generatePage(newValue); + // webView.getEngine().loadContent(html); + // } catch (Exception e) { + // e.printStackTrace(); + // } + // }); + // setGraphic(webView); + } else { + if (isEditing()) { + if (textArea != null) { + textArea.setText(getString()); + // textArea.selectAll(); + } + setText(null); + setGraphic(textArea); + } else { + setGraphic(text); + // setText(getString()); + // setGraphic(null); + } + } + } + + protected void createTextField() { + if (textArea == null) { + textArea = new TextArea(); + textArea.setWrapText(true); + // if (FONTSIZE > 0) { + // try { + // textArea.setFont(Font.font(FONTSIZE)); + // } catch (Exception e) { + // e.printStackTrace(); + // } + // } + textArea.setOnKeyPressed((ke) -> { + if (ke.getCode().equals(KeyCode.ESCAPE)) { + textArea.focusedProperty().removeListener(changeListener); + cancelEdit(); + } + if (ke.getCode().equals(KeyCode.TAB)) { + commitEdit(textArea.getText()); + } + }); + textArea.focusedProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue arg0, Boolean arg1, Boolean arg2) { + if (arg2) { + SwingTextContextActivator.instance().activateContext(); + } else { + SwingTextContextActivator.instance().deactivateContext(); + } + } + }); + if (textLocator != null) { + textArea.focusedProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, Boolean oldValue, Boolean newValue) { + if (newValue) { + System.out.println("focus get:" + getTableColumn().getText() + ":" + getTableRow().getIndex()); + textLocator.updateControl(KFXEditableStringAreaHtmlTableCell.this); + } else { + System.out.println("focus lost: " + getTableColumn().getText() + ":" + getTableRow().getIndex()); + } + } + }); + textArea.caretPositionProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, Number oldValue, Number newValue) { + if (textArea.isFocused()) { + System.out.println("caret: " + oldValue + " -> " + newValue); + Utilities.setPrivateField(textLocator, "currentCaret", newValue.intValue()); + // textLocator.currentCaret = newValue.intValue(); + } + } + }); + } + } + textArea.setText(getString()); + textArea.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2); + textArea.setPrefHeight(this.getHeight()); + textArea.focusedProperty().addListener(changeListener); + // textArea.setOnAction(evt -> commitEdit(textField.getText())); + } + + protected String getString() { + return getItem() == null ? "" : getItem().toString(); + } + + @Override + @SuppressWarnings({ "unchecked", "rawtypes" }) + public void commitEdit(String item) { + if (isEditing()) { + super.commitEdit(item); + } else { + final TableView table = getTableView(); + if (table != null) { + TablePosition position = new TablePosition(getTableView(), getTableRow().getIndex(), getTableColumn()); + CellEditEvent editEvent = new CellEditEvent(table, position, TableColumn.editCommitEvent(), item); + Event.fireEvent(getTableColumn(), editEvent); + } + updateItem(item, false); + if (table != null) { + table.edit(-1, null); + } + // super.commitEdit(item); // 20201217 bug fix + } + TableRow row = getTableRow(); + if (row != null && row.getIndex() >= 0) { + KTableRow bean = (KTableRow) getTableView().getItems().get(row.getIndex()); + bean.showWebView(true); + updateItem(item, isEmpty()); + } + } + +} diff --git a/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/ui/KFXEditableStringAreaHtmlTableCellBackup20220409.java b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/ui/KFXEditableStringAreaHtmlTableCellBackup20220409.java new file mode 100644 index 0000000..b4c8b8b --- /dev/null +++ b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/ui/KFXEditableStringAreaHtmlTableCellBackup20220409.java @@ -0,0 +1,431 @@ +package cn.net.connor.std.processedit.meopviewfx.ui; + +import com.teamcenter.rac.stylesheet.gdt.GenerateGDTHTML; +import com.teamcenter.rac.util.Registry; +import com.teamcenter.rac.util.Utilities; + +import cn.net.connor.std.aifrcp.util.KUtil; +import cn.net.connor.std.fx.KFXTextLocator; +import cn.net.connor.std.processedit.meopviewfx.bean.KTableRow; +import cn.net.connor.std.processedit.meopviewfx.bean.PropConfig; +import javafx.beans.value.ChangeListener; +import javafx.beans.value.ObservableValue; +import javafx.concurrent.Worker.State; +import javafx.event.Event; +import javafx.scene.control.TableCell; +import javafx.scene.control.TableColumn; +import javafx.scene.control.TableColumn.CellEditEvent; +import javafx.scene.control.TablePosition; +import javafx.scene.control.TableRow; +import javafx.scene.control.TableView; +import javafx.scene.control.TextArea; +import javafx.scene.input.KeyCode; +import javafx.scene.input.MouseButton; +import javafx.scene.layout.Region; +import javafx.scene.text.Font; +import javafx.scene.text.Text; +import javafx.scene.web.WebEngine; +import javafx.scene.web.WebView; + +/** + * select color: + * + * .table-row-cell .ktext { -fx-fill: black; } + * + * .table-row-cell:selected .ktext { -fx-fill: white; } + * + * .table-cell .ktext { -fx-fill: black; } + * + * .table-cell:selected .ktext { -fx-fill: white; } + * + * @author Administrator + * + * @param + * @param + */ + +public class KFXEditableStringAreaHtmlTableCellBackup20220409 extends TableCell { + protected WebView webView; + protected PropConfig config; + protected TextArea textArea; + private static final Registry REG = Registry.getRegistry(KFXEditableStringAreaHtmlTableCellBackup20220409.class); + private static double ZOOM = 1; + private static int FONTSIZE = -1; + static { + try { + String zoomStr = REG.getString("zoom"); + if (!KUtil.isEmpty(zoomStr)) { + double d = Double.parseDouble(zoomStr); + System.out.println("Zoom: " + d); + ZOOM = d; + } + FONTSIZE = REG.getInt("fontsize", -1); + } catch (Exception e) { + } + if (ZOOM < 0) { + ZOOM = 1; + } + } + protected ChangeListener changeListener = (obs, ov, nv) -> { + if (!nv) { + commitEdit(textArea.getText()); + } + }; + private Text text; + private KFXTextLocator textLocator; + + public KFXEditableStringAreaHtmlTableCellBackup20220409(PropConfig config, KFXTextLocator textLocator) { + super(); + this.config = config; + this.textLocator = textLocator; + } + + @Override + public void startEdit() { + if (editableProperty().get()) { + if (!isEmpty()) { + super.startEdit(); + createTextField(); + setText(null); + setGraphic(textArea); + textArea.requestFocus(); + } + } + } + + public void startEdit(int temp) { + if (isEditing()) { + System.out.println("=====>" + temp); + textArea.positionCaret(temp); + } + } + + public boolean showWebView() { + Object obj = super.getTableRow().getItem(); + boolean showWebView = true; + if (obj != null && (obj instanceof KTableRow)) { + showWebView = ((KTableRow) obj).showWebView(); + } + return showWebView; + } + + @Override + public void cancelEdit() { + super.cancelEdit(); + // setText((String) getItem()); + // setGraphic(null); + if (showWebView()) { + setGraphic(webView); + } else { + setGraphic(text); + } + } + + @Override + public void updateItem(String item, boolean empty) { + super.updateItem(item, empty); + // if (webView == null) { + // createWebView(); + // } + if (text == null) { + text = new Text(); + text.wrappingWidthProperty().bind(getTableColumn().widthProperty().subtract(20)); + text.textProperty().bind(itemProperty()); + text.getStyleClass().add("ktext"); + } + boolean showWebView = showWebView(); + if (empty) { + setText(null); + setGraphic(null); + } else if (showWebView) { + String newValue = item; + String html = KUtil.isEmpty(newValue) || newValue.startsWith("") ? newValue : GenerateGDTHTML.generatePage(newValue); + createWebView(html); + // webView.setPrefHeight(Region.USE_COMPUTED_SIZE); + // Platform.runLater(() -> { + // try { + // // System.out.println("Load Html: " + newValue); + // // System.out.println(">> " + html); + // String html = newValue == null || newValue.startsWith("") ? newValue : + // GenerateGDTHTML.generatePage(newValue); + // webView.getEngine().loadContent(html); + // } catch (Exception e) { + // e.printStackTrace(); + // } + // }); + // setGraphic(webView); + } else { + if (isEditing()) { + if (textArea != null) { + textArea.setText(getString()); + // textArea.selectAll(); + } + setText(null); + setGraphic(textArea); + } else { + setGraphic(text); + // setText(getString()); + // setGraphic(null); + } + } + } + + protected void createTextField() { + if (textArea == null) { + textArea = new TextArea(); + textArea.setWrapText(true); + if (FONTSIZE > 0) { + try { + textArea.setFont(Font.font(FONTSIZE)); + } catch (Exception e) { + e.printStackTrace(); + } + } + textArea.setOnKeyPressed((ke) -> { + if (ke.getCode().equals(KeyCode.ESCAPE)) { + textArea.focusedProperty().removeListener(changeListener); + cancelEdit(); + } + if (ke.getCode().equals(KeyCode.TAB)) { + commitEdit(textArea.getText()); + } + }); + + if (textLocator != null) { + textArea.focusedProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, Boolean oldValue, Boolean newValue) { + if (newValue) { + System.out.println("focus get:" + getTableColumn().getText() + ":" + getTableRow().getIndex()); + textLocator.updateControl(KFXEditableStringAreaHtmlTableCellBackup20220409.this); + } else { + System.out.println("focus lost: " + getTableColumn().getText() + ":" + getTableRow().getIndex()); + } + } + }); + textArea.caretPositionProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, Number oldValue, Number newValue) { + if (textArea.isFocused()) { + System.out.println("caret: " + oldValue + " -> " + newValue); + Utilities.setPrivateField(textLocator, "currentCaret", newValue.intValue()); + // textLocator.currentCaret = newValue.intValue(); + } + } + }); + } + } + textArea.setText(getString()); + textArea.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2); + textArea.setPrefHeight(this.getHeight()); + textArea.focusedProperty().addListener(changeListener); + // textArea.setOnAction(evt -> commitEdit(textField.getText())); + } + + protected synchronized void createWebView(String value) { + if(webView==null) { + webView = new WebView(); + webView.setCache(false); + if (ZOOM != 1) { + webView.setZoom(ZOOM); + } + webView.setPrefHeight(120 * ZOOM); +// webView.getEngine().getLoadWorker().stateProperty().addListener(new ChangeListener() { +// @Override +// public void changed(ObservableValue observable, State oldValue, State newValue) { +// if (newValue != State.SUCCEEDED) { +// // System.out.println("Load Failed: "+newValue); +// webView.setPrefHeight(Region.USE_COMPUTED_SIZE); +// KFXEditableStringAreaHtmlTableCell.this.setPrefHeight(Region.USE_COMPUTED_SIZE); +// return; +// } +// try { +// Object res = webView.getEngine().executeScript( +// "var body = document.body, html = document.documentElement; Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight );"); +// double height = Integer.parseInt(res.toString()) * ZOOM + 20; +// webView.setPrefHeight(height); +// KFXEditableStringAreaHtmlTableCell.this.setPrefHeight(height); +// webView.getEngine().reload(); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// +// } +// }); + } + WebEngine engine = webView.getEngine(); + //webView.setPrefHeight(Region.USE_COMPUTED_SIZE); + // KFXEditableStringAreaHtmlTableCell.this.setPrefHeight(Region.USE_COMPUTED_SIZE); + setGraphic(webView); + engine.loadContent(value); + engine.reload(); +// Platform.runLater(()->{ +// engine.loadContent(value); +// }); +// engine.documentProperty().addListener((obj, prev, newv) -> { +// Double height = 20.0; +// if(!KUtil.isEmpty(value)) { +// String heightText = engine.executeScript("var body = document.body," + "html = document.documentElement;" + "Math.max( body.scrollHeight , body.offsetHeight, " +// + "html.clientHeight, html.scrollHeight , html.offsetHeight );").toString(); +// height = Double.parseDouble(heightText.replace("px", "")) * ZOOM + 10; +// } +// webView.setPrefHeight(height); +// this.setPrefHeight(height); +// }); + webView.setOnScroll(e -> { + Event.fireEvent(KFXEditableStringAreaHtmlTableCellBackup20220409.this, e); + }); + if (isEditable()) { + webView.setOnMouseClicked(e -> { + TableView table = getTableView(); + if (table == null) { + return; + } + TableRow row = getTableRow(); + int rowNum = row.getIndex(); + if (rowNum < 0) { + return; + } + TableColumn col = getTableColumn(); + if (e.getButton() != MouseButton.PRIMARY || e.getClickCount() != 2) { + table.getSelectionModel().select(rowNum, col); + return; + } + KTableRow bean = (KTableRow) table.getItems().get(rowNum); + bean.showWebView(false); + updateItem(getItem(), isEmpty()); + table.layout(); + table.edit(rowNum, col); + }); + } + } + + protected void createWebViewBackup() { + webView = new WebView(); + webView.setPrefHeight(Region.USE_COMPUTED_SIZE); + if (ZOOM != 1) { + webView.setZoom(ZOOM); + } + webView.getEngine().getLoadWorker().stateProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, State oldValue, State newValue) { + if (newValue != State.SUCCEEDED) { + return; + } + try { + Object res = webView.getEngine().executeScript( + "var body = document.body, html = document.documentElement; Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight );"); + // System.out.println("Height: " + res); + int height = Integer.parseInt(res.toString()); + // int width = Integer.parseInt(webView.getEngine().executeScript("var body = + // document.body, html = document.documentElement; Math.max( body.scrollWidth, + // body.offsetWidth, html.clientWidth, html.scrollWidth, html.offsetWidth + // );").toString()); + webView.setPrefHeight(height * ZOOM); + KFXEditableStringAreaHtmlTableCellBackup20220409.this.setPrefHeight(height * ZOOM + 20); + } catch (Exception e) { + e.printStackTrace(); + } + } + }); + if (isEditable()) { + webView.setOnScroll(e -> { + Event.fireEvent(getTableColumn(), e); + }); + webView.setOnMouseClicked(e -> { + TableView table = getTableView(); + if (table == null) { + return; + } + TableRow row = getTableRow(); + int rowNum = row.getIndex(); + if (rowNum < 0) { + return; + } + TableColumn col = getTableColumn(); + if (e.getButton() != MouseButton.PRIMARY || e.getClickCount() != 2) { + table.getSelectionModel().select(rowNum, col); + return; + } + KTableRow bean = (KTableRow) table.getItems().get(rowNum); + bean.showWebView(false); + updateItem(getItem(), isEmpty()); + table.layout(); + table.edit(rowNum, col); + }); + // webView.setOnMouseClicked(e -> { + // if (e.getButton() != MouseButton.PRIMARY || e.getClickCount() != 2) { + // if (e.getButton() == MouseButton.SECONDARY && e.getClickCount() == 1) { + // Object obj = super.getTableRow().getItem(); + // if (obj != null && (obj instanceof KTableRow)) { + // Event.fireEvent(getTableColumn(), e); + // } + // } + // return; + // } + // TableRow row = getTableRow(); + // KTableRow bean = (KTableRow) getTableView().getItems().get(row.getIndex()); + // String oldValue = bean.stringProps.get(config).getValueSafe(); + // System.out.println("Modify [" + row + "]: " + oldValue); + // Display localDisplay = Display.getCurrent(); + // if (localDisplay == null) { + // localDisplay = Display.getDefault(); + // } + // GdtEditor editor = new GdtEditor(new JTextArea(oldValue)); + // editor.setValue(oldValue); + // localDisplay.asyncExec(new Runnable() { + // public void run() { + // Shell localShell = UIUtilities.getCurrentModalShell(); + // GdtDialog gdtDialog = new GdtDialog(localShell, null, editor, true) { + // public boolean close() { + // try { + // String newValue = editor.getValue(); + // System.out.println("New Value: " + newValue); + // bean.stringProps.get(config).setValue(newValue); + // + // } catch (Exception e) { + // e.printStackTrace(); + // } + // return super.close(); + // } + // }; + // editor.setGdtDialog(gdtDialog); + // gdtDialog.open(); + // } + // }); + // }); + } + // webView.prefWidthProperty().bind(getTableColumn().widthProperty().subtract(20)); + } + + protected String getString() { + return getItem() == null ? "" : getItem().toString(); + } + + @Override + @SuppressWarnings({ "unchecked", "rawtypes" }) + public void commitEdit(String item) { + if (isEditing()) { + super.commitEdit(item); + } else { + final TableView table = getTableView(); + if (table != null) { + TablePosition position = new TablePosition(getTableView(), getTableRow().getIndex(), getTableColumn()); + CellEditEvent editEvent = new CellEditEvent(table, position, TableColumn.editCommitEvent(), item); + Event.fireEvent(getTableColumn(), editEvent); + } + updateItem(item, false); + if (table != null) { + table.edit(-1, null); + } + // super.commitEdit(item); // 20201217 bug fix + } + TableRow row = getTableRow(); + if (row != null && row.getIndex() >= 0) { + KTableRow bean = (KTableRow) getTableView().getItems().get(row.getIndex()); + bean.showWebView(true); + updateItem(item, isEmpty()); + } + } + +} diff --git a/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/ui/KFXEditableStringAreaHtmlTableCellBackup20220509.java b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/ui/KFXEditableStringAreaHtmlTableCellBackup20220509.java new file mode 100644 index 0000000..5793ffd --- /dev/null +++ b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/ui/KFXEditableStringAreaHtmlTableCellBackup20220509.java @@ -0,0 +1,448 @@ +package cn.net.connor.std.processedit.meopviewfx.ui; + +import com.teamcenter.rac.treetable.SwingTextContextActivator; +import com.teamcenter.rac.util.Utilities; + +import cn.net.connor.std.aifrcp.util.KUtil; +import cn.net.connor.std.fx.KFXTextLocator; +import cn.net.connor.std.gdtex.KGenerateGDTHTML; +import cn.net.connor.std.processedit.meopviewfx.bean.KTableRow; +import cn.net.connor.std.processedit.meopviewfx.bean.PropConfig; +import javafx.beans.value.ChangeListener; +import javafx.beans.value.ObservableValue; +import javafx.concurrent.Worker.State; +import javafx.event.Event; +import javafx.scene.control.TableCell; +import javafx.scene.control.TableColumn; +import javafx.scene.control.TableColumn.CellEditEvent; +import javafx.scene.control.TablePosition; +import javafx.scene.control.TableRow; +import javafx.scene.control.TableView; +import javafx.scene.control.TextArea; +import javafx.scene.input.KeyCode; +import javafx.scene.input.MouseButton; +import javafx.scene.layout.Region; +import javafx.scene.text.Text; +import javafx.scene.web.WebEngine; +import javafx.scene.web.WebView; + +/** + * select color: + * + * .table-row-cell .ktext { -fx-fill: black; } + * + * .table-row-cell:selected .ktext { -fx-fill: white; } + * + * .table-cell .ktext { -fx-fill: black; } + * + * .table-cell:selected .ktext { -fx-fill: white; } + * + * @author Administrator + * + * @param + * @param + */ + +public class KFXEditableStringAreaHtmlTableCellBackup20220509 extends TableCell { + + protected WebView webView; + protected PropConfig config; + protected TextArea textArea; + // private static final Registry REG = + // Registry.getRegistry(KFXEditableStringAreaHtmlTableCell.class); + private static double ZOOM = 1; + private int dy = 1; + // private static int FONTSIZE = -1; + // static { + // try { + // // String zoomStr = REG.getString("zoom"); + // // if (!KUtil.isEmpty(zoomStr)) { + // // double d = Double.parseDouble(zoomStr); + // // System.out.println("Zoom: " + d); + // // ZOOM = d; + // // } + // // FONTSIZE = REG.getInt("fontsize", -1); + // } catch (Exception e) { + // } + // if (ZOOM < 0) { + // ZOOM = 1; + // } + // } + protected ChangeListener changeListener = (obs, ov, nv) -> { + if (!nv) { + commitEdit(textArea.getText()); + } + }; + private Text text; + private KFXTextLocator textLocator; + + public KFXEditableStringAreaHtmlTableCellBackup20220509(PropConfig config, KFXTextLocator textLocator) { + super(); + this.config = config; + this.textLocator = textLocator; + webView = new WebView(); + webView.setPrefHeight(Region.USE_COMPUTED_SIZE); + webView.getEngine().documentProperty().addListener((obj, prev, newv) -> { + try { + String heightText = webView.getEngine() + .executeScript( + "var body = document.body, html = document.documentElement;Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight );") + .toString(); + double height = Double.parseDouble(heightText.replace("px", "")) * ZOOM; + webView.setPrefHeight(height); + } catch (Exception e) { + e.printStackTrace(); + } + }); + webView.getEngine().getLoadWorker().stateProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, State oldValue, State newValue) { + if (newValue != State.SUCCEEDED) { + webView.setPrefHeight(Region.USE_COMPUTED_SIZE); + } + } + }); + this.localToSceneTransformProperty().addListener((obs, oldIndex, newIndex) -> { + if (getGraphic() == webView) { + try { + webView.getEngine().reload(); + webView.setPrefHeight(webView.getPrefHeight() + dy); + dy = -dy; + } catch (Exception e) { + e.printStackTrace(); + } + } + }); + webView.setOnScroll(e -> { + Event.fireEvent(KFXEditableStringAreaHtmlTableCellBackup20220509.this, e); + }); + if (isEditable()) { + webView.setOnMouseClicked(e -> { + TableView table = getTableView(); + if (table == null) { + return; + } + TableRow row = getTableRow(); + int rowNum = row.getIndex(); + if (rowNum < 0) { + return; + } + TableColumn col = getTableColumn(); + if (e.getButton() != MouseButton.PRIMARY || e.getClickCount() != 2) { + table.getSelectionModel().select(rowNum, col); + return; + } + KTableRow bean = (KTableRow) table.getItems().get(rowNum); + bean.showWebView(false); + updateItem(getItem(), isEmpty()); + table.layout(); + table.edit(rowNum, col); + }); + } + } + + @Override + public void startEdit() { + if (editableProperty().get()) { + if (!isEmpty()) { + super.startEdit(); + createTextField(); + setText(null); + setGraphic(textArea); + textArea.requestFocus(); + } + } + } + + public void startEdit(int temp) { + if (isEditing()) { + System.out.println("=====>" + temp); + textArea.positionCaret(temp); + } + } + + public boolean showWebView() { + Object obj = super.getTableRow().getItem(); + boolean showWebView = true; + if (obj != null && (obj instanceof KTableRow)) { + showWebView = ((KTableRow) obj).showWebView(); + } + return showWebView; + } + + @Override + public void cancelEdit() { + super.cancelEdit(); + // setText((String) getItem()); + // setGraphic(null); + if (showWebView()) { + setGraphic(webView); + } else { + setGraphic(text); + } + } + + @Override + public void updateItem(String item, boolean empty) { + super.updateItem(item, empty); + // if (webView == null) { + // createWebView(); + // } + if (text == null) { + text = new Text(); + text.wrappingWidthProperty().bind(getTableColumn().widthProperty().subtract(20)); + text.textProperty().bind(itemProperty()); + text.getStyleClass().add("ktext"); + } + boolean showWebView = showWebView(); + if (empty) { + setText(null); + setGraphic(null); + } else if (showWebView) { + String newValue = item; + String html = KUtil.isEmpty(newValue) || newValue.startsWith("") ? newValue : KGenerateGDTHTML.generatePage(newValue); + createWebView(html); + // webView.setPrefHeight(Region.USE_COMPUTED_SIZE); + // Platform.runLater(() -> { + // try { + // // System.out.println("Load Html: " + newValue); + // // System.out.println(">> " + html); + // String html = newValue == null || newValue.startsWith("") ? newValue : + // GenerateGDTHTML.generatePage(newValue); + // webView.getEngine().loadContent(html); + // } catch (Exception e) { + // e.printStackTrace(); + // } + // }); + // setGraphic(webView); + } else { + if (isEditing()) { + if (textArea != null) { + textArea.setText(getString()); + // textArea.selectAll(); + } + setText(null); + setGraphic(textArea); + } else { + setGraphic(text); + // setText(getString()); + // setGraphic(null); + } + } + } + + protected void createTextField() { + if (textArea == null) { + textArea = new TextArea(); + textArea.setWrapText(true); + // if (FONTSIZE > 0) { + // try { + // textArea.setFont(Font.font(FONTSIZE)); + // } catch (Exception e) { + // e.printStackTrace(); + // } + // } + textArea.setOnKeyPressed((ke) -> { + if (ke.getCode().equals(KeyCode.ESCAPE)) { + textArea.focusedProperty().removeListener(changeListener); + cancelEdit(); + } + if (ke.getCode().equals(KeyCode.TAB)) { + commitEdit(textArea.getText()); + } + }); + textArea.focusedProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue arg0, Boolean arg1, Boolean arg2) { + if(arg2) { + SwingTextContextActivator.instance().activateContext(); + }else { + SwingTextContextActivator.instance().deactivateContext(); + } + } + }); + if (textLocator != null) { + textArea.focusedProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, Boolean oldValue, Boolean newValue) { + if (newValue) { + System.out.println("focus get:" + getTableColumn().getText() + ":" + getTableRow().getIndex()); + textLocator.updateControl(KFXEditableStringAreaHtmlTableCellBackup20220509.this); + } else { + System.out.println("focus lost: " + getTableColumn().getText() + ":" + getTableRow().getIndex()); + } + } + }); + textArea.caretPositionProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, Number oldValue, Number newValue) { + if (textArea.isFocused()) { + System.out.println("caret: " + oldValue + " -> " + newValue); + Utilities.setPrivateField(textLocator, "currentCaret", newValue.intValue()); + // textLocator.currentCaret = newValue.intValue(); + } + } + }); + } + } + textArea.setText(getString()); + textArea.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2); + textArea.setPrefHeight(this.getHeight()); + textArea.focusedProperty().addListener(changeListener); + // textArea.setOnAction(evt -> commitEdit(textField.getText())); + } + + protected synchronized void createWebView(String value) { + // webWrapper.styleProperty().setValue("-fx-border-color: blue"); + setGraphic(webView); + WebEngine engine = webView.getEngine(); + // webView.setPrefHeight(Region.USE_COMPUTED_SIZE); + // KFXEditableStringAreaHtmlTableCell.this.setPrefHeight(Region.USE_COMPUTED_SIZE); + engine.loadContent(value); + // Platform.runLater(()->{ + // engine.loadContent(value); + // }); + // engine.documentProperty().addListener((obj, prev, newv) -> { + // Double height = 20.0; + // if(!KUtil.isEmpty(value)) { + // String heightText = engine.executeScript("var body = document.body," + "html + // = document.documentElement;" + "Math.max( body.scrollHeight , + // body.offsetHeight, " + // + "html.clientHeight, html.scrollHeight , html.offsetHeight );").toString(); + // height = Double.parseDouble(heightText.replace("px", "")) * ZOOM + 10; + // } + // webView.setPrefHeight(height); + // this.setPrefHeight(height); + // }); + + } + + protected void createWebViewBackup() { + WebView webView = new WebView(); + webView.setPrefHeight(Region.USE_COMPUTED_SIZE); + if (ZOOM != 1) { + webView.setZoom(ZOOM); + } + webView.getEngine().getLoadWorker().stateProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, State oldValue, State newValue) { + if (newValue != State.SUCCEEDED) { + return; + } + try { + Object res = webView.getEngine().executeScript( + "var body = document.body, html = document.documentElement; Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight );"); + // System.out.println("Height: " + res); + int height = Integer.parseInt(res.toString()); + // int width = Integer.parseInt(webView.getEngine().executeScript("var body = + // document.body, html = document.documentElement; Math.max( body.scrollWidth, + // body.offsetWidth, html.clientWidth, html.scrollWidth, html.offsetWidth + // );").toString()); + webView.setPrefHeight(height * ZOOM); + KFXEditableStringAreaHtmlTableCellBackup20220509.this.setPrefHeight(height * ZOOM + 20); + } catch (Exception e) { + e.printStackTrace(); + } + } + }); + if (isEditable()) { + webView.setOnScroll(e -> { + Event.fireEvent(getTableColumn(), e); + }); + webView.setOnMouseClicked(e -> { + TableView table = getTableView(); + if (table == null) { + return; + } + TableRow row = getTableRow(); + int rowNum = row.getIndex(); + if (rowNum < 0) { + return; + } + TableColumn col = getTableColumn(); + if (e.getButton() != MouseButton.PRIMARY || e.getClickCount() != 2) { + table.getSelectionModel().select(rowNum, col); + return; + } + KTableRow bean = (KTableRow) table.getItems().get(rowNum); + bean.showWebView(false); + updateItem(getItem(), isEmpty()); + table.layout(); + table.edit(rowNum, col); + }); + // webView.setOnMouseClicked(e -> { + // if (e.getButton() != MouseButton.PRIMARY || e.getClickCount() != 2) { + // if (e.getButton() == MouseButton.SECONDARY && e.getClickCount() == 1) { + // Object obj = super.getTableRow().getItem(); + // if (obj != null && (obj instanceof KTableRow)) { + // Event.fireEvent(getTableColumn(), e); + // } + // } + // return; + // } + // TableRow row = getTableRow(); + // KTableRow bean = (KTableRow) getTableView().getItems().get(row.getIndex()); + // String oldValue = bean.stringProps.get(config).getValueSafe(); + // System.out.println("Modify [" + row + "]: " + oldValue); + // Display localDisplay = Display.getCurrent(); + // if (localDisplay == null) { + // localDisplay = Display.getDefault(); + // } + // GdtEditor editor = new GdtEditor(new JTextArea(oldValue)); + // editor.setValue(oldValue); + // localDisplay.asyncExec(new Runnable() { + // public void run() { + // Shell localShell = UIUtilities.getCurrentModalShell(); + // GdtDialog gdtDialog = new GdtDialog(localShell, null, editor, true) { + // public boolean close() { + // try { + // String newValue = editor.getValue(); + // System.out.println("New Value: " + newValue); + // bean.stringProps.get(config).setValue(newValue); + // + // } catch (Exception e) { + // e.printStackTrace(); + // } + // return super.close(); + // } + // }; + // editor.setGdtDialog(gdtDialog); + // gdtDialog.open(); + // } + // }); + // }); + } + // webView.prefWidthProperty().bind(getTableColumn().widthProperty().subtract(20)); + } + + protected String getString() { + return getItem() == null ? "" : getItem().toString(); + } + + @Override + @SuppressWarnings({ "unchecked", "rawtypes" }) + public void commitEdit(String item) { + if (isEditing()) { + super.commitEdit(item); + } else { + final TableView table = getTableView(); + if (table != null) { + TablePosition position = new TablePosition(getTableView(), getTableRow().getIndex(), getTableColumn()); + CellEditEvent editEvent = new CellEditEvent(table, position, TableColumn.editCommitEvent(), item); + Event.fireEvent(getTableColumn(), editEvent); + } + updateItem(item, false); + if (table != null) { + table.edit(-1, null); + } + // super.commitEdit(item); // 20201217 bug fix + } + TableRow row = getTableRow(); + if (row != null && row.getIndex() >= 0) { + KTableRow bean = (KTableRow) getTableView().getItems().get(row.getIndex()); + bean.showWebView(true); + updateItem(item, isEmpty()); + } + } + +} diff --git a/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/ui/MEOPPanel.fxml b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/ui/MEOPPanel.fxml new file mode 100644 index 0000000..27bbf77 --- /dev/null +++ b/cn.net.connor.std.processedit/src/cn/net/connor/std/processedit/meopviewfx/ui/MEOPPanel.fxml @@ -0,0 +1,94 @@ + + + + + + + + + + + +
+ + + + + +
+ +
+
+ + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + +
+ + + + + + + + + + +