first commit

main
李建辉 1 month ago
commit fede81f840

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry exported="true" kind="lib" path="lib/ojdbc7.jar"/>
<classpathentry exported="true" kind="lib" path="lib/sqljdbc4-2.0.jar"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="output" path="bin"/>
</classpath>

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>cn.net.connor.std.aifrcp</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.ManifestBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.SchemaBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.pde.PluginNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

@ -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

@ -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

@ -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”不允许存在关系路径
```

@ -0,0 +1,6 @@
source.. = src/
output.. = bin/
bin.includes = META-INF/,\
.,\
lib/ojdbc7.jar,\
lib/sqljdbc4-2.0.jar

@ -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;
}
}

@ -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);
}
}
}

@ -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;
}
}

@ -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();
}

@ -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;
}

@ -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();
}
}

@ -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;
}

@ -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;
}
}

@ -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);
}
}

@ -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);
}
}
}
}

@ -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;
}
}

@ -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<String> getDivideVals(String propVal, int maxLen) {
return getDivideVals(propVal, maxLen, "\n");
// List<String> 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<String> splitRes = splitStrFullCharacter(text, maxLen);
// res.addAll(splitRes);
// } else {
// res.add(text);
// }
// }
// return res;
}
public static List<String> getDivideVals(String propVal, int maxLen, String splitFlag) {
List<String> 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<String> splitRes = splitStrFullCharacter(text, maxLen);
res.addAll(splitRes);
} else {
res.add(text);
}
}
return res;
}
public static List<String> splitStrFullCharacter(String str, int charNum) {
List<String> 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);
}
}

@ -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);
}
}

@ -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());
}
}

@ -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<String> queryStringArray(Connection conn, String sql, Object[] params) throws Exception {
ResultSet rs = null;
PreparedStatement ps = null;
List<String> res = new ArrayList<String>();
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<String[]> queryStringArray(Connection conn, String sql, Object[] params, int colCnt) throws Exception {
if (colCnt == 0) {
return null;
}
ResultSet rs = null;
PreparedStatement ps = null;
List<String[]> res = new ArrayList<String[]>();
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();
}
}
}
}

@ -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<KTableRow> 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<TCComponent> 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<String, String> rowStringProps = new HashMap<String, String>();
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;
}
}
}

@ -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<Element> getChildNodes(Element node, String nodeName) throws Exception {
List<Element> 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);
}
}

@ -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<Integer, String> 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<CellRangeAddress> copyRanges = new ArrayList<CellRangeAddress>();
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;
// <20><><EFBFBD><EFBFBD>ϲ<EFBFBD><CFB2><EFBFBD>Ԫ<EFBFBD><D4AA>
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<Point, String> 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<Integer, XSSFSheet> 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<XSSFShape> 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<Integer, String> 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<Integer, String> data = new LinkedHashMap<Integer, String>();
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<Integer, String> 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<Integer, String> data = new LinkedHashMap<Integer, String>();
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<String, String> 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<XSSFFont, XSSFFont> 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;
}
}

@ -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<String, TCComponent> 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<String, TCComponent> 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<String, TCComponent> 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<String, TCComponent> 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<String, TCComponent> 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"));
}
}

@ -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<String, String> 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<String, String> 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<com.teamcenter.services.rac.projectmanagement._2012_02.ScheduleManagement.AttributeUpdateContainer> 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<attrCnt;i++) {
// String[] defautAttr = defaultAttrs.get(i);
// if(KUtil.getLen(defautAttr)!=3) {
// continue;
// }
// AttributeUpdateContainer attr = new
// com.teamcenter.services.rac.projectmanagement._2012_02.ScheduleManagement.AttributeUpdateContainer();
// attr.attrName = defautAttr[0];
// try {
// attr.attrType = Integer.parseInt(defautAttr[1]); // reference
// } catch (Exception e) {
// e.printStackTrace();
// continue;
// }
// attr.attrValue = defautAttr[2];// workflowUID;
// attrList.add(attr);
// }
container.otherAttributes = attrList.toArray(new com.teamcenter.services.rac.projectmanagement._2012_02.ScheduleManagement.AttributeUpdateContainer[] {});
}
CreatedObjectsContainer resp = smService.createTasks(schedule, new TaskCreateContainer[] { container });
SoaUtil.checkPartialErrors(resp.serviceData);
int cnt = resp.serviceData.sizeOfCreatedObjects();
TCComponentScheduleTask newTask = null;
if (cnt > 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<String, String> 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;
}
}

@ -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

@ -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

@ -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;
}
}

@ -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<String, String> attrs;
// TC对象路径 bom bop rel & type
private String path;
// 属性配置
private String property;
// 子节点
private List<KXmlConfigNode> children;
// 如果为空则删除父节点
private boolean removeParentIfNoChild;
private KXmlConfigNode(String name, String value, String path, String property, Map<String, String> attrs, List<KXmlConfigNode> 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<TCComponent> 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</%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<String, String> attrs = new HashMap<String, String>();
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<KXmlConfigNode> 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);
}
}

@ -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<String, String> attrs;
// 子节点
private List<KXmlNode> children;
public KXmlNode(String name, String value, Map<String, String> attrs, List<KXmlNode> 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<KXmlNode> 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<childCnt; i++) {
KXmlNode c = children.get(i);
if(nodeName.equalsIgnoreCase(c.name)) {
return c;
}
}
return null;
}
public void print(String space) {
System.out.print(String.format("\n%s<%s%s>%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</%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<String, String> attrs = null;
NamedNodeMap nodeAttrMap = node.getAttributes();
int attrCnt = nodeAttrMap.getLength();
if (attrCnt > 0) {
attrs = new HashMap<String, String>();
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<KXmlNode> 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);
}
}

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry exported="true" kind="lib" path="lib/jfxrt.jar"/>
<classpathentry exported="true" kind="lib" path="lib/jfxswt.jar"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="output" path="bin"/>
</classpath>

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>cn.net.connor.std.fx</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.ManifestBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.SchemaBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.pde.PluginNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

@ -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

@ -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

@ -0,0 +1,6 @@
source.. = src/
output.. = bin/
bin.includes = META-INF/,\
.,\
lib/jfxrt.jar,\
lib/jfxswt.jar

@ -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;
}
}

@ -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<T, E> extends TableCell<T, Date> {
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<? super Boolean> 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<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> 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
}
}
}

@ -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 <T>
* @param <E>
*/
public class KFXEditableStringAreaTableCell<T, E> extends TableCell<T, String> {
protected TextArea textArea;
protected boolean showToolTip = false;
protected ChangeListener<? super Boolean> 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<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> arg0, Boolean arg1, Boolean arg2) {
if(arg2) {
SwingTextContextActivator.instance().activateContext();
}else {
SwingTextContextActivator.instance().deactivateContext();
}
}
});
if (textLocator != null) {
textArea.focusedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> 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<Number>() {
@Override
public void changed(ObservableValue<? extends Number> 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
}
}
}

@ -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<T, E> extends TableCell<T, String> {
protected TextField textField;
protected boolean showToolTip = false;
protected ChangeListener<? super Boolean> 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<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> 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
}
}
}

@ -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);
}
}

@ -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();
}
}
}
}

@ -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);
}

@ -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<T> {
boolean matches(String typedText, T objectToCompare);
}
public static <T> void autoCompleteComboBoxPlus(ComboBox<T> comboBox, AutoCompleteComparator<T> comparatorMethod, boolean checkText) {
ObservableList<T> 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<KeyEvent>() {
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<T> 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 <T> void autoCompleteComboBoxPlus(ComboBox<T> comboBox, AutoCompleteComparator<T> comparatorMethod) {
autoCompleteComboBoxPlus(comboBox, comparatorMethod, true);
}
public static <T> T getComboBoxValue(ComboBox<T> comboBox) {
if (comboBox.getSelectionModel().getSelectedIndex() < 0) {
return null;
} else {
return comboBox.getItems().get(comboBox.getSelectionModel().getSelectedIndex());
}
}
}

@ -0,0 +1,22 @@
package cn.net.connor.std.fx;
import javafx.scene.control.CheckBox;
public class KIndexCheckBox extends CheckBox implements Comparable<KIndexCheckBox>{
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;
}
}

@ -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<String>{
public KLOVComboBox(TCComponentListOfValues lov) throws Exception{
super();
if(lov==null) {
return;
}
ObservableList<String> items = FXCollections.observableArrayList();
Map<String, String> real_dis = new HashMap<String, String>();
Map<String, String> dis_real = new HashMap<String, String>();
List<LovValue> lovs = lov.getListOfValues().getValues();
int size = lovs==null?0:lovs.size();
for(int i=0;i<size;i++) {
LovValue lv = lovs.get(i);
String realValue = lv.getValue()+"";
String disValue = lv.getDisplayValue();
items.add(realValue);
real_dis.put(realValue, disValue);
dis_real.put(disValue,realValue);
}
StringConverter<String> converter = new StringConverter<String>() {
@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 );
}
}

@ -0,0 +1,4 @@
.table-view {
-fx-faint-focus-color: transparent;
-fx-focus-color: rgba(0,0,0,0.2);
}

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="output" path="bin"/>
</classpath>

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>cn.net.connor.std.gdtex</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.ManifestBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.SchemaBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.pde.PluginNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

@ -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

@ -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

@ -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
&#x007F;=&#x0100;
&#x0081;=&#x0101;
```

@ -0,0 +1,5 @@
source.. = src/
output.. = bin/
bin.includes = META-INF/,\
.,\
plugin.xml

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.8"?>
<plugin>
<extension point="com.teamcenter.rac.common.renderingHint">
<renderingHint id="gdtpanel" priority="1">
<legacyPropertyBean class="cn.net.connor.std.gdtex.KPropertyGdtPanel"/>
</renderingHint>
<renderingHint id="gdtpanel_titled" priority="1">
<legacyPropertyBean class="cn.net.connor.std.gdtex.KTitledPropertyGdtPanel"/>
</renderingHint>
</extension>
</plugin>

@ -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;
}
}

@ -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;
}
}

@ -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<String, String> 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<String, String> symbolMap = new HashMap<String, String>();
// 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<GenerateGDTHTML> 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 + ";");
}
}
}
}

@ -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")));
}
}

@ -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");
}
}

@ -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

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry exported="true" kind="lib" path="lib/jacob.jar"/>
<classpathentry exported="true" kind="lib" path="lib/jsqlparser-4.3.jar"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="output" path="bin"/>
</classpath>

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>cn.net.connor.std.processedit</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.ManifestBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.SchemaBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.pde.PluginNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

@ -0,0 +1,2 @@
eclipse.preferences.version=1
encoding//src/cn/net/connor/std/processedit/util/PrefComponent.java=UTF-8

@ -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

@ -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

@ -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
属性位置工步如不写默认为文件夹属性位置包含bomlineitem
#:属性名称前加#表示改列为手动序号列,用于重排序功能,支持多列
##:属性名称前加##表示改列为自动序号列,不跟随上下移动,删除行时也会自动调整,支持多列
属性真实名称定义的属性名称如要支持换行请务必配置“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
<definition id="com.teamcenter.rac.common.textActive">
<with variable="activeContexts">
<iterate operator="or" ifEmpty="false">
<or>
<equals value="com.teamcenter.rac.aifrcp.swingtext"/>
<equals value="com.teamcenter.rac.aifrcp.swttext"/>
</or>
</iterate>
</with>
</definition>
```
修改为
```xml
<definition id="com.teamcenter.rac.common.textActive">
<or>
<with variable="activeContexts">
<iterate operator="or" ifEmpty="false">
<or>
<equals value="com.teamcenter.rac.aifrcp.swingtext"/>
<equals value="com.teamcenter.rac.aifrcp.swttext"/>
</or>
</iterate>
</with>
<with variable="activePartId">
<equals value="cn.net.connor.process.meopview.MEOPEditView"/>
</with>
</or>
</definition>
```
## 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. 工道编辑,序号特殊配置
更新配置:序号属性名称前加#
属性位置工步如不写默认为文件夹属性位置包含bomlineitem
```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
```

@ -0,0 +1,8 @@
source.. = src/
output.. = bin/
bin.includes = plugin.xml,\
META-INF/,\
.,\
icons/,\
lib/jsqlparser-4.3.jar,\
lib/jacob.jar

Binary file not shown.

After

Width:  |  Height:  |  Size: 456 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 942 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 727 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 474 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 800 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 332 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 526 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 793 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 912 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save