first commit

main
李建辉 1 month ago
commit 79ab5ea130

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry exported="true" kind="lib" path="lib/ojdbc8.jar"/>
<classpathentry kind="lib" path="lib/mssql-jdbc-7.0.0.jre8.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="lib" path="lib/swingx-1.6.1.jar"/>
<classpathentry kind="lib" path="lib/poi-4.0.1.jar"/>
<classpathentry kind="lib" path="lib/dom4j-2.1.1.jar"/>
<classpathentry kind="lib" path="lib/poi-examples-3.7-20101029.jar"/>
<classpathentry kind="lib" path="lib/poi-ooxml-3.7-20101029.jar"/>
<classpathentry kind="lib" path="lib/poi-ooxml-schemas-3.7-20101029.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>com.connor.jd</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,20 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Jd
Bundle-SymbolicName: com.connor.jd;singleton:=true
Bundle-Version: 1.0.0
Bundle-Vendor: CONNOR
Require-Bundle: org.eclipse.ui,
com.teamcenter.rac.kernel;bundle-version="13000.1.0",
com.teamcenter.rac.util;bundle-version="13000.1.0",
com.teamcenter.rac.common;bundle-version="13000.1.0",
com.teamcenter.rac.aifrcp;bundle-version="13000.1.0",
org.eclipse.core.runtime;bundle-version="3.15.100",
TcSoaStructureManagementLoose;bundle-version="13000.1.0",
org.apache.poi.39;bundle-version="3.9.0"
Automatic-Module-Name: com.connor.jd
Bundle-RequiredExecutionEnvironment: JavaSE-1.8
Bundle-ClassPath: lib/ojdbc8.jar,
.,
lib/swingx-1.6.1.jar,
lib/mssql-jdbc-7.0.0.jre8.jar

1
bin/.gitignore vendored

@ -0,0 +1 @@
/com/

@ -0,0 +1,9 @@
source.. = src/
output.. = bin/
bin.includes = plugin.xml,\
META-INF/,\
.,\
icons/,\
lib/ojdbc8.jar,\
lib/swingx-1.6.1.jar,\
lib/mssql-jdbc-7.0.0.jre8.jar

Binary file not shown.

After

Width:  |  Height:  |  Size: 332 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 526 B

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

@ -0,0 +1,60 @@
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<plugin>
<extension
point="org.eclipse.ui.commands">
<category
id="test.commands.category"
name="Sample Category">
</category>
<command
categoryId="test.commands.category"
name="图号申请"
id="DrawingNoApplyHandler">
</command>
</extension>
<extension
point="org.eclipse.ui.handlers">
<handler
class="com.connor.jingdiao.handlers.DrawingNoApplyHandler"
commandId="DrawingNoApplyHandler">
</handler>
</extension>
<extension
point="org.eclipse.ui.bindings">
<key
commandId="test.commands.sampleCommand"
schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"
contextId="org.eclipse.ui.contexts.window"
sequence="M1+6">
</key>
</extension>
<extension
point="org.eclipse.ui.menus">
<menuContribution
locationURI="menu:org.eclipse.ui.main.menu?after=additions">
<menu
id="com.connor.jingdiao.menus"
label="精雕菜单"
mnemonic="M">
<command
commandId="DrawingNoApplyHandler"
mnemonic="S">
</command>
</menu>
</menuContribution>
<menuContribution
locationURI="toolbar:org.eclipse.ui.main.toolbar?after=additions">
<toolbar
id="test.toolbars.sampleToolbar">
<command
id="test.toolbars.sampleCommand"
commandId="test.commands.sampleCommand"
icon="icons/sample.png"
tooltip="Say hello world">
</command>
</toolbar>
</menuContribution>
</extension>
</plugin>

@ -0,0 +1,52 @@
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<plugin>
<extension point="org.eclipse.ui.commands">
<command name="查询物料库存信息" id="erpIntegrationHandler"/>
<command name="派生中间件" id="deriveCenterHandler"/>
<command name="派生MBOM产品" id="deriveMBOMHandler"/>
<command name="图号申请" id="DrawingNoApplyHandler"/>
<!-- <command name="申请物料编码" id="WlbmApplyHandler"/> -->
<command id="CodeApplyHandler" name="物料编码申请"/>
<!--command name="DBOM转EBOM" categoryId="com.connor.ml.tcm.outfile.commands.category" id="DBOMtoEBOM"> </command!-->
<command name="依据设计创建物料" id="DesignToPartHandler"/>
<command name="标准化审核" id="StandardHandler"/>
<command name="用户登录设置" id="LoginIPSetHandler"/>
</extension>
<extension point="org.eclipse.ui.handlers">
<handler class="com.connor.jingdiao.handlers.DrawingNoApplyHandler" commandId="DrawingNoApplyHandler"/>
<!-- <handler class="com.connor.jingdiao.handlers.WlbmApplyHandler" commandId="WlbmApplyHandler"/> -->
<!--handler class="com.connor.ml.tcm.outfile.ML_01.DbomTransitionToEbomHandler" commandId="DBOMtoEBOM"> </handler!-->
<handler commandId="CodeApplyHandler" class="com.connor.jingdiao.handlers.CodeApplyHandler"/>
<handler commandId="DesignToPartHandler" class="com.connor.jingdiao.handlers.DesignToPartHandler"/>
<handler commandId="StandardHandler" class="com.connor.jingdiao.handlers.StandardHandler"/>
<handler commandId="LoginIPSetHandler" class="com.connor.jingdiao.handlers.LoginIPSetHandler"/>
<handler class="com.connor.jd.erp.erpIntegrationHandler" commandId="erpIntegrationHandler"/>
<handler class="com.connor.jd.derive.deriveCenterHandler" commandId="deriveCenterHandler"/>
<handler class="com.connor.jd.derive.deriveMBOMHandler" commandId="deriveMBOMHandler"/>
</extension>
<extension point="org.eclipse.ui.menus">
<menuContribution locationURI="menu:com.connor.plm.test.menus.sampleMenu?after=additions">
<command commandId="DrawingNoApplyHandler" style="push"> </command>
<command commandId="DesignToPartHandler" style="push"> </command>
<!-- <command commandId="WlbmApplyHandler" style="push">
</command>
BOM转换 -->
<!--command commandId="DBOMtoEBOM" style="push"/!-->
<command commandId="CodeApplyHandler" style="push"> </command>
<command commandId="StandardHandler" style="push"> </command>
<command commandId="erpIntegrationHandler" style="push"> </command>
<command commandId="deriveCenterHandler" style="push"> </command>
<command commandId="deriveMBOMHandler" style="push"> </command>
<command commandId="LoginIPSetHandler" style="push"> </command>
</menuContribution>
<!--menuContribution locationURI="menu:org.eclipse.ui.main.menu?after=additions">
<menu id="com.connor.jingdiao.menus" label="精雕菜单">
<command commandId="DrawingNoApplyHandler" mnemonic="S">
</command>
</menu>
</menuContribution-->
</extension>
</plugin>

@ -0,0 +1,65 @@
package com.connor.jd.derive;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import com.connor.jd.erp.erpIntegrationOpertaion;
import com.teamcenter.rac.aif.AbstractAIFApplication;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.common.lov.testingservice.LOVTestingService;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;
public class deriveCenterHandler extends AbstractHandler {
@Override
public Object execute(ExecutionEvent arg0) throws ExecutionException {
// TODO Auto-generated method stub
// 获取当前系统活动
AbstractAIFApplication app = AIFUtility.getCurrentApplication();
TCSession session = (TCSession) app.getSession();
// 获取tc当前选择的操作
InterfaceAIFComponent target = app.getTargetComponent();
if (target instanceof TCComponentItemRevision) {
try {
String[] value = session.getPreferenceService().getStringValues("JD_SERIVECENT");
List<String> list = new ArrayList<>(Arrays.asList(value));
List<String> typeList = new ArrayList<>(Arrays.asList(value));
Map<String, String> typeMap = new HashMap<String, String>();
for(String string : list) {
System.out.println("首选项配置属性:"+string);
System.out.println("开始分割属性");
String[] split = string.split("-");
typeList.add(split[0]);
typeMap.put(split[0], split[1]);
}
String stringProperty = ((TCComponentItemRevision) target).getItem().getStringProperty("object_type");
System.out.println("选中对象item类型"+stringProperty);
if (typeList.contains(((TCComponentItemRevision) target).getItem().getStringProperty("object_type"))) {
String createType = typeMap.get(stringProperty);
TCComponentItemRevision f = (TCComponentItemRevision) target;
deriveOpertion operation = new deriveOpertion(session, f, 1,createType);
session.queueOperation(operation);
} else {
MessageBox.post("请选择中间件版本执行操作", "提示", MessageBox.INFORMATION);
return null;
}
} catch (TCException e) {
e.printStackTrace();
}
}
return null;
}
}

@ -0,0 +1,65 @@
package com.connor.jd.derive;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import com.connor.jd.erp.erpIntegrationOpertaion;
import com.teamcenter.rac.aif.AbstractAIFApplication;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;
public class deriveMBOMHandler extends AbstractHandler {
@Override
public Object execute(ExecutionEvent arg0) throws ExecutionException {
// TODO Auto-generated method stub
// 获取当前系统活动
AbstractAIFApplication app = AIFUtility.getCurrentApplication();
TCSession session = (TCSession) app.getSession();
// 获取tc当前选择的操作
InterfaceAIFComponent target = app.getTargetComponent();
if (target instanceof TCComponentItemRevision) {
try {
String[] value = session.getPreferenceService().getStringValues("JD_SERIVEMBOM");
List<String> list = new ArrayList<>(Arrays.asList(value));
List<String> typeList = new ArrayList<>(Arrays.asList(value));
Map<String, String> typeMap = new HashMap<String, String>();
for(String string : list) {
System.out.println("首选项配置属性:"+string);
System.out.println("开始分割属性");
String[] split = string.split("-");
typeList.add(split[0]);
typeMap.put(split[0], split[1]);
}
String stringProperty = ((TCComponentItemRevision) target).getItem().getStringProperty("object_type");
System.out.println("选中对象item类型"+stringProperty);
if (typeList.contains(((TCComponentItemRevision) target).getItem().getStringProperty("object_type"))) {
String createType = typeMap.get(stringProperty);
TCComponentItemRevision f = (TCComponentItemRevision) target;
deriveOpertion operation = new deriveOpertion(session, f,2,createType);
session.queueOperation(operation);
} else {
MessageBox.post("请选择MBOM产品执行操作", "提示", MessageBox.INFORMATION);
return null;
}
} catch (TCException e) {
e.printStackTrace();
}
}
return null;
}
}

@ -0,0 +1,146 @@
package com.connor.jd.derive;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.jdesktop.swingx.MultiSplitLayout.Split;
import com.connor.ml.tcm.outfile.util.MethodUtil;
import com.teamcenter.rac.aif.AbstractAIFOperation;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentFolder;
import com.teamcenter.rac.kernel.TCComponentForm;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentItemType;
import com.teamcenter.rac.kernel.TCComponentType;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCProperty;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;
public class deriveOpertion extends AbstractAIFOperation{
private TCSession session;
private TCComponentItemRevision rev;
private int i;
private String createType;
public deriveOpertion(TCSession session, TCComponentItemRevision f, int i, String createType) {
// TODO Auto-generated constructor stub
this.session = session;
this.rev = f;
this.i = i;
this.createType = createType;
}
@Override
public void executeOperation() throws Exception {
// TODO Auto-generated method stub
System.out.println("根据属性值创建对象");
//根据属性值创建对象
TCComponentItemType tccomponentitemtype = (TCComponentItemType)session.getTypeComponent(createType);
//获取流水码
String itemId = tccomponentitemtype.getNewID();
//获取版本号
String itemRev = tccomponentitemtype.getNewRev(null);
//Item的idItem的版本号Item的类型零组件的名称零组件的描述零组件的单位(可以为null)
TCComponentItem newitem = tccomponentitemtype.create(itemId,itemRev,createType,"","",null);
System.out.println("创建成功,开始同步属性");
//获取item
TCComponentItem oldItem = rev.getItem();
//给rev赋值
TCComponentItemRevision newItemRevision = newitem.getLatestItemRevision();
//给表单赋值
TCComponent[] oldreferenceListProperty = rev.getReferenceListProperty("IMAN_master_form_rev");
TCComponentForm oldform = (TCComponentForm) oldreferenceListProperty[0];
TCComponent[] newreferenceListProperty1 = newItemRevision.getReferenceListProperty("IMAN_master_form_rev");
TCComponentForm newform = (TCComponentForm) newreferenceListProperty1[0];
//开始赋值属性
System.out.println("获取首选项配置,开始赋值");
String[] value = null;
if(i==1) {
value = session.getPreferenceService().getStringValues("JD_J6_ZX_Copy_Properties");
}else {
value = session.getPreferenceService().getStringValues("JD_J6_MPRODUCT_Copy_Properties");
}
for(int i=0;i<value.length;i++) {
String[] getValueNums = value[i].split(";");
System.out.println("获取首选项的值,根据分号分割");
for(String getvalString:getValueNums) {
System.out.println(getvalString);
}
if(getValueNums.length>0) {
for(int j=0;j<getValueNums.length;j++) {
System.out.println("根据等号分割");
String[] getVal = getValueNums[j].split("=");
System.out.println("左边部分分割");
String[] getValues = getVal[0].split("\\.");
System.out.println("右边部分分割");
String[] setValues = getVal[1].split("\\.");
Object val = "";
System.out.println("转移"+getValues[0]+"上的属性"+getValues[1]+"去"+setValues[0]+"的"+getValues[1]+"上");
if(getValues[0].equals("item")) {
val = MethodUtil.getTCPropertyValue(oldItem, getValues[1]);
//val = item.getProperty(getValues[1]);
}else if(getValues[0].equals("rev")) {
val = MethodUtil.getTCPropertyValue(rev, getValues[1]);
//val = rev.getProperty(getValues[1]);
}else if(getValues[0].equals("revmaster")) {
val = MethodUtil.getTCPropertyValue(oldform, getValues[1]);
//val = form.getProperty(getValues[1]);
}
System.out.println("val:"+val);
if(setValues[0].equals("item")) {
MethodUtil.setTCPropertyValue(newitem, setValues[1], val);
}else if(setValues[0].equals("rev")) {
MethodUtil.setTCPropertyValue(newItemRevision, setValues[1], val);
}else if(setValues[0].equals("revmaster")) {
MethodUtil.setTCPropertyValue(newform, setValues[1], val);
}
// if("item".equals(getValues[0])) {
// stringProperty = newitem.getProperty(getValues[1]);
// }else if("rev".equals(getValues[0])){
// stringProperty = rev.getProperty(getValues[1]);
// }else if("revmaster".equals(getValues[0])) {
// stringProperty = oldform.getProperty(getValues[1]);
// }
// if("item".equals(setValues[0])) {
// newitem.setStringProperty(setValues[1], stringProperty);
// }else if("rev".equals(setValues[0])){
// if(setValues[1].equals("j6_weight")) {
// newItemRevision.setProperty(setValues[1], stringProperty);
// }else {
// newItemRevision.setStringProperty(setValues[1], stringProperty);
// }
//
// }else if("revmaster".equals(setValues[0])) {
// newform.setStringProperty(setValues[1], stringProperty);
// }
//
}
}else {
MessageBox.post("首选项设置有误,清仔细检查", "提示", MessageBox.INFORMATION);
}
}
System.out.println("开始挂载");
// 放到newstuff
TCComponentFolder newStuffFolder = session.getUser().getNewStuffFolder();
newStuffFolder.add("contents", newitem);
MessageBox.post("创建成功,新对象在newstuff文件夹下", "提示", MessageBox.INFORMATION);
System.out.println("执行结束");
}
}

@ -0,0 +1,49 @@
package com.connor.jd.erp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import com.teamcenter.rac.aif.AbstractAIFApplication;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;
public class erpIntegrationHandler extends AbstractHandler {
@Override
public Object execute(ExecutionEvent arg0) throws ExecutionException {
// TODO Auto-generated method stub
// 获取当前系统活动
AbstractAIFApplication app = AIFUtility.getCurrentApplication();
TCSession session = (TCSession) app.getSession();
// 获取tc当前选择的操作
InterfaceAIFComponent target = app.getTargetComponent();
if (target instanceof TCComponentItemRevision) {
try {
String[] value = session.getPreferenceService().getStringValues("JD_WLKCCXLX");
List<String> list = new ArrayList<>(Arrays.asList(value));
if (list.contains(((TCComponentItemRevision) target).getStringProperty("object_type"))) {
TCComponentItemRevision f = (TCComponentItemRevision) target;
erpIntegrationOpertaion operation = new erpIntegrationOpertaion(session, f);
session.queueOperation(operation);
} else {
MessageBox.post("请选择物料执行操作", "提示", MessageBox.INFORMATION);
return null;
}
} catch (TCException e) {
e.printStackTrace();
}
}
return null;
}
}

@ -0,0 +1,111 @@
package com.connor.jd.erp;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import com.teamcenter.rac.aif.AbstractAIFOperation;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;
public class erpIntegrationOpertaion extends AbstractAIFOperation{
private TCSession session;
private TCComponentItemRevision rev;
// private Connection conn;
// private CallableStatement stat;
// private ResultSet rs;
private String url;
private String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private String username;
private String password;
// private String sql;
public erpIntegrationOpertaion(TCSession session, TCComponentItemRevision f) {
// TODO Auto-generated constructor stub
this.session = session;
this.rev = f;
}
@Override
public void executeOperation() throws Exception {
// TODO Auto-generated method stub
String wlbm = rev.getStringProperty("j6_wlbm") + "-" + rev.getProperty("item_revision_id");
System.out.println("获取的物料编码:" + wlbm);
if(wlbm!=null && !"".equals(wlbm)) {
//查询首选项,获取连接
String[] value1 = session.getPreferenceService().getStringValues("Jd_Erp_Info_Connect");
for (int i = 0; i < value1.length; i++) {
System.out.println(value1[i]);
}
url = value1[0];
username = value1[1];
password = value1[2];
//查询首选项获取查询的存储过程
String[] value2 = session.getPreferenceService().getStringValues("Jd_Erp_Info_inventory");
for (int i = 0; i < value2.length; i++) {
System.out.println(value2[i]);
}
String[] split = value2[0].split("@");
try {
Class.forName(driverName); // 加载数据库驱动
Connection conn = DriverManager.getConnection(url, username, password); // 获取数据库连接对象
System.out.println("================开始调用存储过程=====================");
CallableStatement cs = conn.prepareCall("{ CALL "+split[0]+"(?) }"); // 准备调用存储过程
cs.setString(1, wlbm); // 设置存储过程的参数
ResultSet rs = cs.executeQuery(); // 执行存储过程并获取结果集
System.out.println("================存储过程执行结束=====================");
System.out.println("================将结果写入table=====================");
JTable table = new JTable(buildTableModel(rs)); // 创建一个 JTable并将查询结果放到其中
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); // 设置表格的自动调整模式为关闭自动调整
JScrollPane scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
// 创建一个带滚动条的 JScrollPane并将 JTable 放到其中
//JScrollPane scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
//JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
//scrollPane.setPreferredSize(new Dimension(500, 300)); // 设置JScrollPane的首选大小
JFrame frame = new JFrame("物料库存信息"); // 创建一个 JFrame并将 JScrollPane 放到其中
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);//关闭窗口不退出
frame.add(scrollPane);
frame.pack();
frame.setVisible(true);
rs.close(); // 关闭 ResultSet
cs.close(); // 关闭 CallableStatement
conn.close(); // 关闭 Connection
} catch (Exception ex) {
ex.printStackTrace();
}
}else {
MessageBox.post("选中物料的编码为空", "提示", MessageBox.INFORMATION);
return;
}
}
public static TableModel buildTableModel(ResultSet rs) throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
Vector<String> columnNames = new Vector<String>();
for (int column = 1; column <= columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
}
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> row = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
row.add(rs.getObject(columnIndex));
}
data.add(row);
}
return new DefaultTableModel(data, columnNames);
}
}

@ -0,0 +1,21 @@
package com.connor.jd.handlers;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.jface.dialogs.MessageDialog;
public class SampleHandler extends AbstractHandler {
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
MessageDialog.openInformation(
window.getShell(),
"Jd",
"Hello, Eclipse world");
return null;
}
}

@ -0,0 +1,87 @@
package com.connor.jingdiao.handlers;
import java.util.ArrayList;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import com.teamcenter.rac.aif.AIFDesktop;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentBOMLine;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;
//创建常规文件夹结构
public class CodeApplyHandler extends AbstractHandler implements IHandler{
public Object execute(ExecutionEvent arg0) throws ExecutionException {
System.out.println("CodeApplyHandler");
TCSession session = (TCSession) AIFUtility.getCurrentApplication().getSession();
AIFDesktop desktop = AIFUtility.getActiveDesktop();
try {
InterfaceAIFComponent[] targets = AIFUtility.getCurrentApplication().getTargetComponents();
ArrayList<TCComponent> target = new ArrayList<>();
ArrayList<TCComponent> boms = new ArrayList<>();
StringBuilder msg = new StringBuilder("");
for(InterfaceAIFComponent t : targets) {
TCComponentItemRevision rev;
TCComponentBOMLine bom = null;
if(t instanceof TCComponentItemRevision) {
rev = (TCComponentItemRevision) t;
}else if(t instanceof TCComponentBOMLine) {
bom = (TCComponentBOMLine) t;
rev = bom.getItemRevision();
}else {
msg.append("选中对象 ").append(t).append(" 不是BOM或版本对象\n");
continue;
// MessageBox.post(desktop, "选中对象 "+t+" 不是BOM或版本对象请重新选择", "ERROR", MessageBox.ERROR);
// return null;
}
if(rev.getTCProperty("j6_wlbm")==null) {
msg.append("选中对象 ").append(t).append(" 没有物料编码属性\n");
continue;
// MessageBox.post(desktop, "选中对象 "+rev+" 没有物料编码属性,请正确选择物料对象!", "ERROR", MessageBox.ERROR);
// return null;
}
if(!rev.getProperty("j6_wlbm").isEmpty()) {
msg.append("选中对象 ").append(t).append(" 已有物料编码,无法再次申请\n");
continue;
// MessageBox.post(desktop, "选中对象"+t+"已有物料编码,无法再次申请!", "ERROR", MessageBox.ERROR);
// return null;
}
if(bom != null)
boms.add(bom);
else
target.add(rev);
}
ArrayList<String[]> list = new ArrayList<>();
String[] ops = new String[] { "Jd_Code_Apply", "Jd_TC_Info_Connect", "Jd_TICODE_Info_Connect", "Jd_Code_Product_Class" };
if(boms.size()>0)
ops[0] = "Jd_BOM_Code_Apply";
for(String name : ops) {
String[] options = session.getPreferenceService().getStringValues(name);
if(options == null || options.length == 0) {
MessageBox.post(desktop, "首选项"+name+"配置不正确!", "ERROR", MessageBox.ERROR);
return null;
}
list.add(options);
}
if(boms.size()==0 && target.size()==0) {
MessageBox.post(desktop, "以下对象申请物料编码遇到问题:\n"+msg, "提示", MessageBox.ERROR);
return null;
}else if(boms.size()>0)
new CodeApplyOperation(session, boms, list, msg).executeOperation();
else
new CodeApplyOperation(session, target, list, msg).executeOperation();
}catch(Exception e) {
e.printStackTrace();
MessageBox.post(desktop, "错误:"+e.getMessage(), "ERROR", MessageBox.ERROR);
return null;
}
return null;
}
}

@ -0,0 +1,232 @@
package com.connor.jingdiao.handlers;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.connor.jingdiao.util.SqlUtil;
import com.connor.jingdiao.util.TCUtil;
import com.teamcenter.rac.aif.AIFDesktop;
import com.teamcenter.rac.aif.AbstractAIFOperation;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentBOMLine;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;
public class CodeApplyOperation extends AbstractAIFOperation {
// private TCSession session;
private ArrayList<TCComponent> revs;
private ArrayList<String[]> options;
private StringBuilder msg;
private HashMap<String, String> classmap;
public CodeApplyOperation(TCSession session, ArrayList<TCComponent> revs, ArrayList<String[]> options, StringBuilder msg) {
// this.session = session;
this.revs = revs;
this.options = options;
this.msg = msg;
this.classmap = new HashMap<>();
}
@Override
public void executeOperation() throws Exception {
AIFDesktop desktop = AIFUtility.getActiveDesktop();
try {
HashMap<String[], String[]> opmap = new HashMap<>();
for(String s : options.get(0)) {
String[] ss = s.split("@@");
opmap.put(ss[0].split("@"), ss[1].split("\\+"));
}
for(String s : options.get(3)) {
String[] ss = s.split("=");
classmap.put(ss[0], ss[1]);
}
String[] sqlOptions = options.get(1);
Connection conn1 = SqlUtil.getSqlserverConnection("oracle.jdbc.driver.OracleDriver",
"jdbc:oracle:thin:@" + sqlOptions[0] + ":1521:" + sqlOptions[3], sqlOptions[1], sqlOptions[2]);
sqlOptions = options.get(2);
// Connection conn2 = SqlUtil.getSqlserverConnection("oracle.jdbc.driver.OracleDriver",
// "jdbc:oracle:thin:@" + sqlOptions[0] + ":1521:" + sqlOptions[3], sqlOptions[1], sqlOptions[2]);
// Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn2 = DriverManager.getConnection("jdbc:oracle:thin:@" + sqlOptions[0] + ":1521:" + sqlOptions[3], sqlOptions[1], sqlOptions[2]);
conn2.setAutoCommit(false);
// StringBuilder msg = new StringBuilder("");
for(TCComponent comp : revs) {
try {
TCComponentItemRevision rev = null;
TCComponentBOMLine bom = null;
if(comp instanceof TCComponentItemRevision) {
rev = (TCComponentItemRevision) comp;
}else {
bom = (TCComponentBOMLine) comp;
rev = bom.getItemRevision();
}
String[] ops = null;
OPTS:for(String[] ss : opmap.keySet()) {
for(String s : ss) {
String[] ps = s.split("=");
String[] pss = ps[1].split(";");
if(!TCUtil.contains(pss, getProp(rev, ps[0]))) {
continue OPTS;
}
}
ops = opmap.get(ss);
}
if(ops==null) {
continue;
}
StringBuilder sb = new StringBuilder("");
int lshc = 0;
for(String op : ops) {
if(op.equals(".")) {
sb.append(op);
}else if(op.contains(".")) {
sb.append(getProp(rev, bom, op));
}else if(op.startsWith("LSH")) {
sb.append("LSH");
lshc = Integer.parseInt(op.substring(3));
}else if(op.startsWith("#")) {
throw new Exception(op.substring(1));
}else {
sb.append(op);
}
}
String code = sb.toString();
if(lshc>0) {
String lsh = "%" + String.format("%02d", lshc) + "d";
ArrayList<HashMap<String, Object>> results = SqlUtil.getDBInfo(conn1, "select SERIALNUMBER from JD_CODE_RULE where CODEKEY='"+sb+"'");
if(results.size()>0) {
int no = (Integer) results.get(0).get("SERIALNUMBER") + 1;
if((no+"").length() > lshc)
throw new Exception(rev+" 的物料编码的流水号已满,请调整相关的属性项值后再次进行申请!\n");
SqlUtil.update("update JD_CODE_RULE set SERIALNUMBER=" + no + " where CODEKEY='" + code + "'");
code = code.replace("LSH", String.format(lsh, no));
}else {
String id = sb.substring(0, sb.indexOf("LSH")).replaceAll("\\.", "");
String sql = "select max(ECMS_CODE) as ECMS_NEXTCODE from ECMS_SERIAL where ECMS_PRE='" +id+ "' group by ECMS_PRE";
System.out.println("ECMS_SERIAL:"+sql);
results = SqlUtil.getDBInfo(conn2, sql);
if(results.size()>0) {
int no = Integer.parseInt(results.get(0).get("ECMS_NEXTCODE").toString()) + 1;
if((no+"").length() > lshc)
throw new Exception(rev+" 的物料编码的流水号已满,请调整相关的属性项值后再次进行申请!\n");
SqlUtil.update("insert into JD_CODE_RULE values('" +code+ "',"+no+")");
code = code.replace("LSH", String.format(lsh, no));
}else {
int no = 1;
SqlUtil.update("insert into JD_CODE_RULE values('" +code+ "',1)");
code = code.replace("LSH", String.format(lsh, no));
}
}
}else {
List<HashMap<String, Object>> results = SqlUtil.getDBInfo(conn1,
"select SERIALNUMBER from JD_CODE_RULE where CODEKEY='"+code+"'");
if (results.size() == 0) {
SqlUtil.update("insert into JD_CODE_RULE values('" +code+ "',0)");
}else {
throw new Exception(rev+" 的物料编码 "+code+" 已存在,请检查相关属性值\n");
}
}
rev.setProperty("j6_wlbm", code);
} catch (Exception e) {
e.printStackTrace();
msg.append(comp).append(" ").append(e.getMessage()).append("\n");
}
}
if(msg.length()==0)
MessageBox.post(desktop, "物料编码申请完成!", "提示", MessageBox.INFORMATION);
else
MessageBox.post(desktop, "以下对象申请物料编码遇到问题:\n"+msg, "提示", MessageBox.WARNING);
} catch (Exception e) {
e.printStackTrace();
MessageBox.post(desktop, "错误:"+e.getMessage(), "ERROR", MessageBox.ERROR);
}
}
private String getProp(TCComponentItemRevision rev, TCComponentBOMLine bom, String op) throws Exception {
String value = "";
String[] split = op.split(";");
String[] ss = split[0].split("\\.");
if(ss[0].equals("rev")) {
if(ss[1].contains("@Jd_Code_Product_Class")) {
String v = ss[1].substring(0, ss[1].indexOf("@"));
value = classmap.get(getProp(rev, v));
}else
value = getProp(rev, ss[1]);
}else if(ss[0].equals("part")) {
AIFComponentContext[] zjtz = TCUtil.getPseudoFolder(rev, "TC_Is_Represented_By").getChildren();
if(zjtz.length>0) {
AIFComponentContext[] ljtz = ((TCComponent)zjtz[0].getComponent()).whereReferencedByTypeRelation(null, new String[] { "J6_ASSOCIATED_REL" });
if(ljtz.length>0) {
AIFComponentContext[] ljwl = TCUtil.getPseudoFolder((TCComponent)ljtz[0].getComponent(), "representation_for").getChildren();
if(ljwl.length>0) {
value = getProp((TCComponent)ljwl[0].getComponent(), ss[1]);
}
}
}
}else if(ss[0].equals("parent")) {
if(bom==null)
throw new Exception("所选对象不是BOM行不支持parent属性");
TCComponentBOMLine parent = bom.parent();
if(parent==null)
throw new Exception("未找到父级BOM");
value = getProp(parent.getItemRevision(), ss[1]);
}
if(value.isEmpty()) {
if(ss[0].equals("part"))
throw new Exception("获取零件物料编码失败");
else
throw new Exception(ss[1]+" 属性为空");
}
if(split.length==1)
return value;
if(split[1].startsWith("LEN")) {
value = "" + Integer.parseInt(value) / Integer.parseInt(split[1].substring(3));
if(value.length() > 4)
throw new Exception("“线束线缆长度”信息填写错误,请重新编写");
while(value.length() < 4) {
value = "0" + value;
}
//lidy20240711先判断长度长度超出则截取不足则补0
//20240715客户又要求还原回去
// int length = value.length();
// if(length > 5)
// throw new Exception("“线束线缆长度”信息填写错误,请重新编写");
// String divisor = split[1].substring(3);
// int len = 5 - divisor.length() + 1;
// System.out.println("LEN" + split[1] + "=" + value + "=" + length + "=" + divisor + "=" + len);
// if(length > len)
// value = "" + Integer.parseInt(value) / Integer.parseInt(divisor);
// System.out.println("value1" + value);
// while(value.length() < len) {
// value = "0" + value;
// }
System.out.println("value2" + value);
value = value.substring(0, 2) + "." + value.substring(2);
}else if(split[1].contains(">")) {
String[] sp = split[1].split(">");
int n = Integer.parseInt(sp[0])-1;
value = value.substring(n, n+Integer.parseInt(sp[1]));
}else {
int len = Integer.parseInt(split[1]);
while(value.length()<len) {
value = "0"+value;
}
}
return value;
}
private String getProp(TCComponent comp, String prop) throws Exception {
try {
return comp.getStringProperty(prop);
}catch(Exception e) {
return comp.getProperty(prop);
}
}
}

@ -0,0 +1,242 @@
package com.connor.jingdiao.handlers;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import com.connor.jingdiao.util.TCUtil;
import com.connor.ml.tcm.outfile.util.MethodUtil;
import com.teamcenter.rac.aif.AbstractAIFDialog;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.kernel.TCAccessControlService;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentForm;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentItemType;
import com.teamcenter.rac.kernel.TCProperty;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;
public class DesignToPartDialog extends AbstractAIFDialog {
private static final long serialVersionUID = 1L;
private TCSession session;
private JButton exportBtn;
private JButton closeBtn;
private JTable impTable;
private DefaultTableModel impModel;
private ArrayList<TCComponentItemRevision> list;
private HashMap<String, Integer> map;
// public DrawingNoApplyDialog(TCSession session, String tables[], String[] options, String[] sqlOptions, InterfaceAIFComponent[] targets) throws Exception {
public DesignToPartDialog(TCSession session, ArrayList<String[]> options, InterfaceAIFComponent[] targets) throws Exception {
super(AIFUtility.getActiveDesktop());
this.session = session;
list = new ArrayList<>();
map = new HashMap<>();
setTitle("创建物料");
exportBtn = new JButton("创建");
closeBtn = new JButton("关闭");
JPanel btnPanel = new JPanel(new FlowLayout());
btnPanel.add(exportBtn);
btnPanel.add(closeBtn);
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.add(BorderLayout.SOUTH, btnPanel);
ArrayList<String[]> props = new ArrayList<>();
// String[] tableHeader = new String[] { "序号", "itemID", "名称", "版本", "加工类型", "产品分类码", "课题号", "配置码", "部件码", "图纸类型", "新图号" };
String[] tables = options.get(0);
String[] tableHeader = new String[tables.length + 1];
tableHeader[0] = "序号";
for (int i = 0; i < tables.length; i++) {
String[] split = tables[i].split("=");
props.add(split[1].split("\\."));
tableHeader[i + 1] = split[0];
map.put(split[1], i + 1);
}
impModel = new DefaultTableModel(tableHeader, 0);
impTable = new JTable() {
private static final long serialVersionUID = 1L;
@Override
public boolean isCellEditable(int row, int col) {
return false;
}
};
impTable.getTableHeader().setReorderingAllowed(false);
impTable.setFillsViewportHeight(true);
// impTable.setEnabled(false);
impTable.setEnabled(true);
// impTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
impTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
impTable.setModel(impModel);
for (int i = 1; i < impModel.getColumnCount(); i++)
impTable.getColumnModel().getColumn(i).setPreferredWidth(150);
int r = 1;
TCAccessControlService acs = session.getTCAccessControlService();
TCComponent[] user = new TCComponent[]{ session.getUser(), session.getGroup(), session.getRole() };
StringBuilder msg = new StringBuilder("");
StringBuilder msg2 = new StringBuilder("");
for (InterfaceAIFComponent t : targets) {
TCComponentItemRevision rev = (TCComponentItemRevision) t;
if (rev.getProperty("j6_drawingno").isEmpty()) {
msg.append(rev).append("、");
continue;
}
if(!acs.checkAccessorsPrivilege(user, rev, "WRITE")) {
msg2.append(rev).append("、");
continue;
}
TCComponentItem item = rev.getItem();
int size = props.size() + 1;
Object[] data = new Object[size];
data[0] = r++;
for (int i = 1; i < size; i++) {
String[] ss = props.get(i-1);
if (ss[0].equals("item")) {
data[i] = item.getStringProperty(ss[1]);
} else {
data[i] = rev.getStringProperty(ss[1]);
}
}
impModel.addRow(data);
list.add(rev);
}
if (targets.length > list.size()) {
StringBuilder m = new StringBuilder("所选对象:\n");
if(msg.length()>0) {
m.append(msg.deleteCharAt(msg.length() - 1)).append(" 图号为空,无法创建物料!\n");
}
if(msg2.length()>0) {
m.append(msg2.deleteCharAt(msg2.length() - 1)).append(" 无编辑权限,无法创建物料!");
}
MessageBox.post(AIFUtility.getActiveDesktop(), m.toString(), "警告", MessageBox.WARNING);
}
if (list.size() == 0) {
return;
}
JScrollPane tablePanel = new JScrollPane(impTable);
addActionListener(options);
setLayout(new BorderLayout());
add(BorderLayout.NORTH, topPanel);
add(BorderLayout.CENTER, tablePanel);
pack();
setSize(new Dimension(1400, 700));
setDefaultLookAndFeelDecorated(true);
Dimension screen = getToolkit().getScreenSize();
setLocation((screen.width - getSize().width) / 2, (screen.height - getSize().height) / 2);
// setAlwaysOnTop(true);
setVisible(true);
}
private void addActionListener(ArrayList<String[]> options) {
exportBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
new Thread() {
public void run() {
try {
exportBtn.setEnabled(false);
closeBtn.setEnabled(false);
for (int i = 0; i < list.size(); i++) {
TCComponentItemRevision rev = list.get(i);
TCComponentItem item = rev.getItem();
TCComponentForm form = TCUtil.getItemRevisionMasterForm(rev);
String type = "", dtype = item.getType(), ptype = rev.getProperty("j6_processtype");
String t = dtype+";"+ptype+"=";
for(String ss : options.get(1)) {
if(ss.startsWith(t)) {
type = ss.substring(ss.indexOf("=")+1);
break;
}
}
if(type.isEmpty())
continue;
AIFComponentContext[] rfs = rev.getChildren("representation_for")[0].getComponent().getChildren();
if(rfs!=null && rfs.length>0) {
int choose = JOptionPane.showOptionDialog(DesignToPartDialog.this, rev+" 下已存在物料,是否继续创建?", "提示",
JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new String[] {"是","否"}, "结束操作");
if(choose==1)
continue;
}
TCComponentItemType typec = (TCComponentItemType)session.getTypeComponent(type);
TCComponentItem pitem = typec.create(typec.getNewID(), null, type, item.getProperty("object_name"), "", null);
TCComponentItemRevision prev = pitem.getLatestItemRevision();
TCComponentForm pform = TCUtil.getItemRevisionMasterForm(prev);
t = dtype+";"+type+"@@";
for(String s : options.get(2)) {
if(!s.startsWith(t))
continue;
String[] ss = s.substring(s.indexOf("@@")+2).split(";");
for(String s1 : ss) {
String[] ps = s1.split("=");
setProp(ps, pitem, prev, pform, item, rev, form);
}
break;
}
rev.add("representation_for", prev);
}
MessageBox.post(DesignToPartDialog.this, "物料创建完成!", "提示", MessageBox.INFORMATION);
} catch (Exception e1) {
e1.printStackTrace();
MessageBox.post(DesignToPartDialog.this, "错误:" + e1.getMessage(), "ERROR", MessageBox.ERROR);
}
exportBtn.setEnabled(true);
closeBtn.setEnabled(true);
}
}.start();
}
});
closeBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
dispose();
}
});
}
private void setProp(String[] ps, TCComponentItem pitem, TCComponentItemRevision prev, TCComponentForm pform,
TCComponentItem item, TCComponentItemRevision rev, TCComponentForm form) throws Exception {
String[] p1 = ps[0].split("\\."), p2 = ps[1].split("\\.");
Object val = "";
if(p2.length<2) {
val = p2[0];
}else if(p2[0].equals("item")) {
val = MethodUtil.getTCPropertyValue(item, p2[1]);
//val = item.getProperty(p2[1]);
}else if(p2[0].equals("rev")) {
val = MethodUtil.getTCPropertyValue(rev, p2[1]);
//val = rev.getProperty(p2[1]);
}else if(p2[0].equals("revmaster")) {
val = MethodUtil.getTCPropertyValue(form, p2[1]);
//val = form.getProperty(p2[1]);
}
System.out.println("val:"+val);
if(p1[0].equals("item")) {
MethodUtil.setTCPropertyValue(pitem, p1[1], val);
}else if(p1[0].equals("rev")) {
MethodUtil.setTCPropertyValue(prev, p1[1], val);
}else if(p1[0].equals("revmaster")) {
MethodUtil.setTCPropertyValue(pform, p1[1], val);
}
}
}

@ -0,0 +1,73 @@
package com.connor.jingdiao.handlers;
import java.util.ArrayList;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import com.teamcenter.rac.aif.AIFDesktop;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;
//创建常规文件夹结构
public class DesignToPartHandler extends AbstractHandler implements IHandler{
public Object execute(ExecutionEvent arg0) throws ExecutionException {
System.out.println("DesignToPartHandler");
TCSession session = (TCSession) AIFUtility.getCurrentApplication().getSession();
AIFDesktop desktop = AIFUtility.getActiveDesktop();
try {
String[] types = session.getPreferenceService().getStringValues("JD6_Part_Design_Type");
if(types == null || types.length == 0) {
MessageBox.post(desktop, "首选项JD6_Part_Design_Type配置不正确", "ERROR", MessageBox.ERROR);
return null;
}
InterfaceAIFComponent[] targets = AIFUtility.getCurrentApplication().getTargetComponents();
for(InterfaceAIFComponent t : targets) {
if(t instanceof TCComponentItemRevision) {
TCComponentItemRevision rev = (TCComponentItemRevision) t;
if(rev.getProperty("j6_drawingno").isEmpty()) {
MessageBox.post(desktop, "选中对象"+t+"未申请图号,无法创建物料!", "ERROR", MessageBox.ERROR);
return null;
}
String type = rev.getItem().getType()+";";
boolean no = true;
for(String s : types) {
if(s.startsWith(type)) {
no = false;
break;
}
}
if(no) {
MessageBox.post(desktop, "选中对象"+t+"不是设计版本类型,无法创建物料!", "ERROR", MessageBox.ERROR);
return null;
}
}else {
MessageBox.post(desktop, "选中对象"+t+"不是设计版本类型,无法创建物料!", "ERROR", MessageBox.ERROR);
return null;
}
}
ArrayList<String[]> list = new ArrayList<>();
String[] ops = new String[] { "Jd_Code_Table_Design", "JD6_Part_Design_Type", "JD6_Part_Design_Copy_Properties" };
for(String name : ops) {
String[] options = session.getPreferenceService().getStringValues(name);
if(options == null || options.length == 0) {
MessageBox.post(desktop, "首选项"+name+"配置不正确", "ERROR", MessageBox.ERROR);
return null;
}
list.add(options);
}
new DesignToPartDialog(session, list, targets);
}catch(Exception e) {
e.printStackTrace();
MessageBox.post(desktop, "错误:"+e.getMessage(), "ERROR", MessageBox.ERROR);
return null;
}
return null;
}
}

@ -0,0 +1,376 @@
package com.connor.jingdiao.handlers;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import com.connor.jingdiao.util.SqlUtil;
import com.connor.jingdiao.util.TCUtil;
import com.connor.ml.tcm.outfile.util.MethodUtil;
import com.teamcenter.rac.aif.AbstractAIFDialog;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.kernel.TCAccessControlService;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentForm;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentItemType;
import com.teamcenter.rac.kernel.TCProperty;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;
public class DrawingNoApplyDialog extends AbstractAIFDialog {
private static final long serialVersionUID = 1L;
private TCSession session;
private JCheckBox createChx;
private JButton exportBtn;
private JButton closeBtn;
private JTable impTable;
private DefaultTableModel impModel;
private ArrayList<TCComponentItemRevision> list;
private HashMap<String, Integer> map;
private Map<String, String[]> ruleOpsMap;
// public DrawingNoApplyDialog(TCSession session, String tables[], String[] options, String[] sqlOptions, InterfaceAIFComponent[] targets) throws Exception {
public DrawingNoApplyDialog(TCSession session, ArrayList<String[]> options,
InterfaceAIFComponent[] targets,Map<String, String[]> ruleOpsMap) throws Exception {
super(AIFUtility.getActiveDesktop());
this.session = session;
list = new ArrayList<>();
map = new HashMap<>();
setTitle("图号申请");
this.ruleOpsMap = ruleOpsMap;
System.out.println(ruleOpsMap.toString());
createChx = new JCheckBox("生成物料");
createChx.setSelected(true);
exportBtn = new JButton("申请");
closeBtn = new JButton("关闭");
JPanel btnPanel = new JPanel(new FlowLayout());
btnPanel.add(createChx);
btnPanel.add(exportBtn);
btnPanel.add(closeBtn);
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.add(BorderLayout.SOUTH, btnPanel);
ArrayList<String[]> props = new ArrayList<>();
// String[] tableHeader = new String[] { "序号", "itemID", "名称", "版本", "加工类型", "产品分类码", "课题号", "配置码", "部件码", "图纸类型", "新图号" };
String[] tables = options.get(0);
String[] tableHeader = new String[tables.length + 1];
tableHeader[0] = "序号";
for (int i = 0; i < tables.length; i++) {
String[] split = tables[i].split("=");
props.add(split[1].split("\\."));
tableHeader[i + 1] = split[0];
map.put(split[1], i + 1);
}
impModel = new DefaultTableModel(tableHeader, 0);
impTable = new JTable() {
private static final long serialVersionUID = 1L;
@Override
public boolean isCellEditable(int row, int col) {
return false;
}
};
impTable.getTableHeader().setReorderingAllowed(false);
impTable.setFillsViewportHeight(true);
// impTable.setEnabled(false);
impTable.setEnabled(true);
// impTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
impTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
impTable.setModel(impModel);
for (int i = 1; i < impModel.getColumnCount(); i++)
impTable.getColumnModel().getColumn(i).setPreferredWidth(150);
int r = 1;
TCAccessControlService acs = session.getTCAccessControlService();
TCComponent[] user = new TCComponent[]{ session.getUser(), session.getGroup(), session.getRole() };
StringBuilder msg = new StringBuilder("");
StringBuilder msg2 = new StringBuilder("");
for (InterfaceAIFComponent t : targets) {
TCComponentItemRevision rev = (TCComponentItemRevision) t;
if (!rev.getProperty("j6_drawingno").isEmpty()) {
msg.append(rev).append("、");
continue;
}
if(!acs.checkAccessorsPrivilege(user, rev, "WRITE")) {
msg2.append(rev).append("、");
continue;
}
TCComponentItem item = rev.getItem();
int size = props.size() + 1;
Object[] data = new Object[size];
data[0] = r++;
for (int i = 1; i < size; i++) {
String[] ss = props.get(i-1);
if (ss[0].equals("item")) {
data[i] = item.getStringProperty(ss[1]);
} else {
data[i] = rev.getStringProperty(ss[1]);
}
}
impModel.addRow(data);
list.add(rev);
}
if (targets.length > list.size()) {
StringBuilder m = new StringBuilder("所选对象:\n");
if(msg.length()>0) {
m.append(msg.deleteCharAt(msg.length() - 1)).append(" 已有图号,无法再次申请!\n");
}
if(msg2.length()>0) {
m.append(msg2.deleteCharAt(msg2.length() - 1)).append(" 无编辑权限,无法申请图号!");
}
MessageBox.post(AIFUtility.getActiveDesktop(), m.toString(), "警告", MessageBox.WARNING);
}
if (list.size() == 0) {
return;
}
JScrollPane tablePanel = new JScrollPane(impTable);
addActionListener(options);
setLayout(new BorderLayout());
add(BorderLayout.NORTH, topPanel);
add(BorderLayout.CENTER, tablePanel);
pack();
setSize(new Dimension(1400, 700));
setDefaultLookAndFeelDecorated(true);
Dimension screen = getToolkit().getScreenSize();
setLocation((screen.width - getSize().width) / 2, (screen.height - getSize().height) / 2);
// setAlwaysOnTop(true);
setVisible(true);
}
private void addActionListener(ArrayList<String[]> options) {
exportBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
new Thread() {
public void run() {
try {
createChx.setEnabled(false);
exportBtn.setEnabled(false);
closeBtn.setEnabled(false);
String[] sqlOptions = options.get(2);
Connection conn = SqlUtil.getSqlserverConnection("oracle.jdbc.driver.OracleDriver",
"jdbc:oracle:thin:@" + sqlOptions[0] + ":1521:" + sqlOptions[3], sqlOptions[1], sqlOptions[2]);
if (conn == null) {
throw new Exception("无法获取数据库连接信息");
}
StringBuilder msg = new StringBuilder("");
for (int i = 0; i < list.size(); i++) {
TCComponentItemRevision rev = list.get(i);
String itemtype = rev.getItem().getType();
HashMap<String[], String> opm = new HashMap<>();
if(ruleOpsMap.containsKey(itemtype)) {
String[] ops = ruleOpsMap.get(itemtype);
for (int tt = 0; tt < ops.length; tt++) {
String[] ss = ops[tt].split("@@");
opm.put(ss[0].split("@"), ss[1]);
}
}
String dno = "";
boolean norule = true;
OPM: for (String[] ss : opm.keySet()) {
boolean check = false;
for (int j = 0; j < ss.length; j++) {
String[] s2 = ss[j].split("=");
String[] ss2 = s2[1].split(";");
boolean c = true;
for(String s : ss2) {
System.out.println(i+"::"+s+"=="+impTable.getValueAt(i, map.get(s2[0]))+"<<"+s2[0]);
if(s.equals(impTable.getValueAt(i, map.get(s2[0])))){
c = false;
break;
}
}
System.out.println(c);
if(c)
check = true;
}
System.out.println("check:"+check);
if(check)
continue;
norule = false;
StringBuilder id = new StringBuilder("");
String rul = opm.get(ss);
String[] rule = rul.split("\\+");
for(String s : rule) {
if(s.startsWith(".")) {
id.append(s);
}else if(s.startsWith("LSH")) {
String lsh = "%" + String.format("%02d", Integer.parseInt(s.substring(3))) + "d";
List<HashMap<String, Object>> results = SqlUtil.getDBInfo(conn, "select SERIALNUMBER from JD_CODE_RULE where CODEKEY='"+id+"'");
if (results.size() == 0) {
SqlUtil.update("insert into JD_CODE_RULE values('" +id+ "',1)");
id.append(String.format(lsh, 1));
} else {
int no = (Integer) results.get(0).get("SERIALNUMBER") + 1;
SqlUtil.update("update JD_CODE_RULE set SERIALNUMBER=" + no + " where CODEKEY='" +id+ "'");
id.append(String.format(lsh, no));
}
}else if(s.startsWith("#rev.")) {
String value = rev.getStringProperty(s.substring(5));
if(value.isEmpty()) {
msg.append(rev).append(" 的部分图号相关属性为空,请检查\n");
break OPM;
}
id.append(value);
}else if(map.containsKey(s)) {
String value = impTable.getValueAt(i, map.get(s)).toString();
if(value.isEmpty()) {
msg.append(rev).append(" 的部分图号相关属性为空,请检查\n");
break OPM;
}
id.append(value);
}else if(s.contains(".")) {//.startsWith("J6_ASSOCIATED_REL.j6_drawingno")
String[] sp = s.split("\\.");
AIFComponentContext[] parent = rev.whereReferencedByTypeRelation(null, new String[] { sp[0] });
if(parent==null || parent.length==0) {
msg.append(rev).append(" 与零件未关联,请关联后再申请图号\n");
break OPM;
}
String p = parent[0].getComponent().getProperty(sp[1]);
if(p.isEmpty()) {
if(sp[1].equals("j6_drawingno")) {
msg.append(rev).append(" 上级图纸无图号,请先申请上级图号后再申请本图图号\n");
break OPM;
}else {
msg.append(rev).append(" 上级对象属性为空,请检查\n");
break OPM;
}
}
id.append(p);
}else {
id.append(s);
}
}
if(!rul.contains("LSH")) {
List<HashMap<String, Object>> results = SqlUtil.getDBInfo(conn,
"select SERIALNUMBER from JD_CODE_RULE where CODEKEY='"+id+"'");
if (results.size() == 0) {
SqlUtil.update("insert into JD_CODE_RULE values('" +id+ "',0)");
}else {
msg.append(rev).append(" 的图号 ").append(id).append(" 已存在,请检查相关属性值\n");
break;
}
}
dno = id.toString();
rev.setProperty("j6_drawingno", dno);
impTable.setValueAt(dno, i, map.get("rev.j6_drawingno"));
break;
}
if(norule) {
msg.append(rev).append(" 无满足条件的规则,无法申请图号 ");
}
norule = true;
if(dno.isEmpty())
continue;
if(!createChx.isSelected())
continue;
TCComponentItem item = rev.getItem();
TCComponentForm form = TCUtil.getItemRevisionMasterForm(rev);
String type = "", dtype = item.getType(), ptype = rev.getProperty("j6_processtype");
String t = dtype+";"+ptype+"=";
for(String ss : options.get(3)) {
if(ss.startsWith(t)) {
type = ss.substring(ss.indexOf("=")+1);
break;
}
}
if(type.isEmpty())
continue;
AIFComponentContext[] rfs = rev.getChildren("representation_for")[0].getComponent().getChildren();
if(rfs!=null && rfs.length>0) {
int choose = JOptionPane.showOptionDialog(DrawingNoApplyDialog.this, rev+" 下已存在物料,是否继续创建?", "提示",
JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new String[] {"是","否"}, "结束操作");
if(choose==1)
continue;
}
TCComponentItemType typec = (TCComponentItemType)session.getTypeComponent(type);
TCComponentItem pitem = typec.create(typec.getNewID(), null, type, item.getProperty("object_name"), "", null);
TCComponentItemRevision prev = pitem.getLatestItemRevision();
TCComponentForm pform = TCUtil.getItemRevisionMasterForm(prev);
t = dtype+";"+type+"@@";
for(String s : options.get(4)) {
if(!s.startsWith(t))
continue;
String[] ss = s.substring(s.indexOf("@@")+2).split(";");
for(String s1 : ss) {
String[] ps = s1.split("=");
setProp(ps, pitem, prev, pform, item, rev, form);
}
break;
}
rev.add("representation_for", prev);
}
if(msg.length()>0)
MessageBox.post(DrawingNoApplyDialog.this, "以下对象图号申请遇到问题,请检查:\n" + msg, "提示", MessageBox.WARNING);
else
MessageBox.post(DrawingNoApplyDialog.this, "图号申请完成!", "提示", MessageBox.INFORMATION);
} catch (Exception e1) {
e1.printStackTrace();
MessageBox.post(DrawingNoApplyDialog.this, "错误:" + e1.getMessage(), "ERROR", MessageBox.ERROR);
}
createChx.setEnabled(true);
exportBtn.setEnabled(true);
closeBtn.setEnabled(true);
}
}.start();
}
});
closeBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
dispose();
}
});
}
private void setProp(String[] ps, TCComponentItem pitem, TCComponentItemRevision prev, TCComponentForm pform,
TCComponentItem item, TCComponentItemRevision rev, TCComponentForm form) throws Exception {
String[] p1 = ps[0].split("\\."), p2 = ps[1].split("\\.");
Object val = "";
if(p2.length<2) {
val = p2[0];
}else if(p2[0].equals("item")) {
val = MethodUtil.getTCPropertyValue(item, p2[1]);
//val = item.getProperty(p2[1]);
}else if(p2[0].equals("rev")) {
val = MethodUtil.getTCPropertyValue(rev, p2[1]);
//val = rev.getProperty(p2[1]);
}else if(p2[0].equals("revmaster")) {
val = MethodUtil.getTCPropertyValue(form, p2[1]);
//val = form.getProperty(p2[1]);
}
System.out.println("val:"+val);
if(p1[0].equals("item")) {
MethodUtil.setTCPropertyValue(pitem, p1[1], val);
}else if(p1[0].equals("rev")) {
MethodUtil.setTCPropertyValue(prev, p1[1], val);
}else if(p1[0].equals("revmaster")) {
MethodUtil.setTCPropertyValue(pform, p1[1], val);
}
}
}

@ -0,0 +1,88 @@
package com.connor.jingdiao.handlers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import com.teamcenter.rac.aif.AIFDesktop;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.kernel.TCComponentBOMLine;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;
//创建常规文件夹结构
public class DrawingNoApplyHandler extends AbstractHandler implements IHandler{
public Object execute(ExecutionEvent arg0) throws ExecutionException {
System.out.println("DrawingNoApplyHandler");
TCSession session = (TCSession) AIFUtility.getCurrentApplication().getSession();
AIFDesktop desktop = AIFUtility.getActiveDesktop();
try {
Map<String, String[]> ruleOpsMap = new HashMap<String, String[]>();
String ruleString = "Jd_Code_Rule_";
InterfaceAIFComponent[] targets = AIFUtility.getCurrentApplication().getTargetComponents();
for(InterfaceAIFComponent t : targets) {
TCComponentItemRevision revision;
if(t instanceof TCComponentItemRevision) {
revision = (TCComponentItemRevision) t;
}else if(t instanceof TCComponentBOMLine) {
revision = ((TCComponentBOMLine) t).getItemRevision();
}else {
MessageBox.post(desktop, "选中对象"+t+"不是设计版本类型,无法申请图号!", "ERROR", MessageBox.ERROR);
return null;
}
String type = revision.getItem().getType();
if(!ruleOpsMap.containsKey(type)) {
String[] options = session.getPreferenceService().getStringValues(ruleString+type);
if(options==null || options.length==0) {
MessageBox.post(desktop, "选中对象"+t+"不是设计版本类型,无法申请图号!", "ERROR", MessageBox.ERROR);
return null;
}else {
ruleOpsMap.put(type, options);
}
}
// if(!(t instanceof TCComponentItemRevision) || !t.getType().contains("Design")) {// Revision
// MessageBox.post(desktop, "选中对象"+t+"不是设计版本类型,无法申请图号!", "ERROR", MessageBox.ERROR);
// return null;
// }else {
// TCComponentItemRevision revision = (TCComponentItemRevision)t;
// String type = revision.getItem().getType();
// if(!ruleOpsMap.containsKey(type)) {
// String typeString = ruleString + type;
// String[] options = session.getPreferenceService().getStringValues(typeString);
// ruleOpsMap.put(type, options);
// }
//
// }
}
String ruleType = "Jd_Code_Rule_Design";
ArrayList<String[]> list = new ArrayList<>();
String[] ops = new String[] { "Jd_Code_Table_Design", ruleType, "Jd_TC_Info_Connect",
"JD6_Part_Design_Type", "JD6_Part_Design_Copy_Properties" };
for(String name : ops) {
String[] options = session.getPreferenceService().getStringValues(name);
if(options == null || options.length == 0) {
MessageBox.post(desktop, "首选项"+name+"配置不正确", "ERROR", MessageBox.ERROR);
return null;
}
list.add(options);
}
new DrawingNoApplyDialog(session, list, targets,ruleOpsMap);
}catch(Exception e) {
e.printStackTrace();
MessageBox.post(desktop, "错误:"+e.getMessage(), "ERROR", MessageBox.ERROR);
return null;
}
return null;
}
}

@ -0,0 +1,976 @@
package com.connor.jingdiao.handlers;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.ListSelectionModel;
import javax.swing.filechooser.FileSystemView;
import javax.swing.tree.DefaultMutableTreeNode;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.connor.jingdiao.util.SqlUtil;
import com.teamcenter.rac.aif.AbstractAIFDialog;
import com.teamcenter.rac.aif.common.AIFTreeNode;
import com.teamcenter.rac.common.organization.OrgTreePanel;
import com.teamcenter.rac.common.organization.OrganizationTree;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentDataset;
import com.teamcenter.rac.kernel.TCComponentGroup;
import com.teamcenter.rac.kernel.TCComponentGroupMember;
import com.teamcenter.rac.kernel.TCComponentProject;
import com.teamcenter.rac.kernel.TCComponentRole;
import com.teamcenter.rac.kernel.TCComponentTcFile;
import com.teamcenter.rac.kernel.TCComponentUser;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;
import com.teamcenter.rac.util.PropertyLayout;
@SuppressWarnings("serial")
public class LoginIPSetDialog extends AbstractAIFDialog {
private TCSession session;
// private JButton b_ok;
private JButton b_cel;
private JButton add;
private JButton remove;
private OrganizationTree tree;
private JTree projectTree;
private JList<String> l_user;
private DefaultListModel<String> lm_user;
private JList<String> l_ip;
private DefaultListModel<String> lm_ip;
private String group;
private String role;
private boolean isMulti;
// private boolean isAll;
private JTable table;
private int[] colIndex;
private int rowIndex;
private TCComponentProject project;
private HashMap<String, String[]> ipmap = new HashMap<>();
private TCComponentDataset model;
public LoginIPSetDialog(TCSession session, TCComponent model, String[] options) throws Exception {
super(true);
this.session = session;
this.isMulti = true;
this.model = (TCComponentDataset) model;
getConn("jdbc:oracle:thin:@" + options[0] + ":1521:" + options[3], options[1], options[2]);
initUI();
}
/*public LoginIPSetDialog(JTable table, String text, int[] colIndex, int rowIndex, TCComponentProject projectID) throws Exception {
super(true);
this.table = table;
this.isMulti = text.contains("M");
this.isAll = text.contains("A");
this.colIndex = colIndex;
this.rowIndex = rowIndex;
this.project = projectID;
initUI();
}*/
private void getConn(String url, String user, String password) throws Exception {
// Class.forName("oracle.jdbc.driver.OracleDriver");
// Connection connection = DriverManager.getConnection(url, user, password);
// connection.setAutoCommit(false);
Connection connection = SqlUtil.getOracleConnection(url, user, password);
String sql = "select PUSER,IP from CONNOR_USER_IP";
ArrayList<HashMap<String, Object>> results = SqlUtil.getDBInfo(connection, sql);
for(HashMap<String, Object> map : results) {
String ips = ""+map.get("IP");
if(ips.isEmpty() || ips.equals("null"))
ipmap.put(""+map.get("PUSER"), new String[] { });
else
ipmap.put(""+map.get("PUSER"), ips.split(","));
System.out.println("PUSER:"+map.get("PUSER"));
}
}
private String getValue() {
String val = "";
if (table != null) {
val = (String) table.getValueAt(rowIndex, colIndex[0]);
}
System.out.println("getValue:"+val);
return val;
}
/*private void setValue(String text) {
System.out.println("setValue:"+text);
if (table != null) {
if(isAll) {
for(int i=0; i<table.getRowCount(); i++) {
table.setValueAt(text, i, colIndex[0]);
if (colIndex.length>1)
table.setValueAt(group, i, colIndex[1]);
}
}else {
table.setValueAt(text, rowIndex, colIndex[0]);
if (colIndex.length>1)
table.setValueAt(group, rowIndex, colIndex[1]);
}
}
}*/
private void initUI() throws Exception {//TODO initUI
this.setTitle("允许用户登录IP设置");
this.setLayout(new BorderLayout());
int pweight = 440, pheight = 480;//, mweight = 280, mheight = 320;
if (isMulti) {
// this.setPreferredSize(new Dimension(640, 480));
// this.setMinimumSize(new Dimension(480, 320));
pweight = 1000;
// mweight = 480;
}
if(project != null) {
pheight = 1200;
// mheight = 700;
}
// this.setPreferredSize(new Dimension(pweight, pheight));
// this.setMinimumSize(new Dimension(mweight, mheight));
OrgTreePanel orgPanel = new OrgTreePanel(session);
this.tree = orgPanel.getOrgTree();
this.add(BorderLayout.SOUTH, initBtnPanel());
JPanel lp = initListPanel();
/*if(project != null) {
JPanel panel = new JPanel(new PropertyLayout());
panel.add("1.1.center.center", orgPanel);
panel.add("2.1.center.center", initProjectPanel(orgPanel));
// FlowLayout flow = new FlowLayout();
// flow.setAlignOnBaseline(true);
// JPanel panel = new JPanel(flow);
// panel.add(orgPanel);
// panel.add(initProjectPanel(orgPanel));
this.add(BorderLayout.WEST, panel);
}else {
this.add(BorderLayout.CENTER, orgPanel);
}
if (isMulti) {
}
this.add(BorderLayout.EAST, lp);*/
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
splitPane.setOneTouchExpandable(true);// 让分割线显示出箭头
splitPane.setContinuousLayout(true);// 操作箭头,重绘图形
splitPane.setLeftComponent(orgPanel);
splitPane.setRightComponent(lp);
this.add(BorderLayout.CENTER, splitPane);
initData();
addListeners();
pack();
// centerToScreen();
setSize(new Dimension(pweight, pheight));
setDefaultLookAndFeelDecorated(true);
Dimension screen = getToolkit().getScreenSize();
setLocation((screen.width - getSize().width) / 2, (screen.height - getSize().height) / 2);
setVisible(true);
}
private void initData() {
String text = getValue();
if (text.isEmpty()) {
return;
}
String[] split = text.split(",");
for (int i = 0; i < split.length; i++) {
lm_user.addElement(split[i]);
}
}
private JPanel initListPanel() {
JPanel listPanel = new JPanel(new BorderLayout());
FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
// flow.setVgap(100);
flow.setAlignOnBaseline(true);
JPanel btnPanel = new JPanel(flow);//new PropertyLayout()
btnPanel.setPreferredSize(new Dimension(40, 100));//.setSize(30, 100);
btnPanel.add(this.add);
btnPanel.add(this.remove);//"2.1.center.center",
this.lm_user = new DefaultListModel<>();
this.l_user = new JList<>(lm_user);
l_user.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
// this.l_user.setCellRenderer(new DeleteListRenderer(l_user));
JScrollPane scroll = new JScrollPane(l_user);
// scroll.setPreferredSize(new Dimension(300, 500));
// this.add.setPreferredSize(new Dimension(50, 30));
listPanel.add(BorderLayout.NORTH, new JLabel("待设置用户列表"));
listPanel.add(BorderLayout.WEST, btnPanel);
listPanel.add(BorderLayout.CENTER, scroll);
JPanel ipPanel = new JPanel(new BorderLayout());
lm_ip = new DefaultListModel<>();
l_ip = new JList<>(lm_ip);
JScrollPane ipsr = new JScrollPane(l_ip);
// ipsr.setPreferredSize(new Dimension(300, 0));
JPanel ibPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JButton editIP = new JButton("编辑IP");
JButton export = new JButton("导出用户列表");
editIP.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(lm_user.isEmpty()) {
MessageBox.post("请先将待设置的用户加入列表!", "ERROR", MessageBox.WARNING);
return;
}
new IPDialog();
}
});
export.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
export();
}
});
ibPanel.add(editIP);
ibPanel.add(export);
ipPanel.add(BorderLayout.NORTH, ibPanel);
ipPanel.add(BorderLayout.CENTER, ipsr);
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
splitPane.setOneTouchExpandable(true);// 让分割线显示出箭头
splitPane.setContinuousLayout(true);// 操作箭头,重绘图形
splitPane.setTopComponent(listPanel);
splitPane.setBottomComponent(ipPanel);
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.CENTER, splitPane);
// listPanel.add(BorderLayout.SOUTH, ipPanel);
return panel;
}
private void export() {//TODO export
new Thread() {
public void run(){
FileInputStream input = null;
FileOutputStream output = null;
try {
String export = FileSystemView.getFileSystemView().getHomeDirectory().getPath()+"\\允许用户登录IP设置_"+String.format("%tF", new Date())+".xlsx";
File ef = new File(export);
if(ef.exists()) {
int op = JOptionPane.showOptionDialog(LoginIPSetDialog.this, export+"文件已存在,是否替换?", "提示", JOptionPane.YES_NO_OPTION,
JOptionPane.INFORMATION_MESSAGE, null, null, null);
if(op == JOptionPane.YES_OPTION) {
ef.delete();
}else {
return;
}
}
// Enumeration<String> ipe = lm_user.elements();
// while(ipe.hasMoreElements()) {
// }
TCComponentTcFile[] files = model.getTcFiles();
File file = files[0].getFile(System.getProperty("java.io.tmpdir"));
input = new FileInputStream(file);
XSSFWorkbook wb = new XSSFWorkbook(input);
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row;
XSSFCell cell;
ArrayList<String> list = new ArrayList<>();
group = "";
role = "";
recycleNode(tree.getRootNode(), list, 0, true);
System.out.println("list:"+list.size());
for(int i=0; i<list.size(); i++) {
row = getRow(sheet, i+1);
String u = list.get(i);
String[] gru = u.split("@@");
if(gru.length<3)
System.out.println("gru:"+u);
String[] user = userString(gru[2]);
// System.out.println(user[0]+"=>"+user[1]);
cell = getCell(row, 0);
cell.setCellValue(i+1);
cell = getCell(row, 1);
cell.setCellValue(user[0]);
cell = getCell(row, 2);
cell.setCellValue(user[1]);
cell = getCell(row, 3);
if(ipmap.containsKey(gru[2])) {
String[] a = ipmap.get(gru[2]);
if(a!=null && a.length>0) {
String ips = Arrays.toString(a);
cell.setCellValue(ips.substring(1, ips.length()-1));
}
}
cell = getCell(row, 4);
cell.setCellValue(gru[0]);
cell = getCell(row, 5);
cell.setCellValue(gru[1]);
}
output = new FileOutputStream(file.getPath());
wb.write(output);
input.close();
output.close();
file.renameTo(new File(export));
MessageBox.post(LoginIPSetDialog.this, "导出完成!", "提示", MessageBox.INFORMATION);
} catch (Exception e) {
e.printStackTrace();
MessageBox.post("Error:"+e.getMessage(), "ERROR", MessageBox.ERROR);
}finally {
if(input!=null)
try {
input.close();
} catch (Exception e) {
e.printStackTrace();
}
if(output!=null)
try {
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}.start();
}
private JPanel initBtnPanel() {
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 5));
// this.b_ok = new JButton("OK");
this.b_cel = new JButton("确定");
this.add = new JButton("+");
this.remove = new JButton("-");
// panel.add(b_ok);
panel.add(b_cel);
return panel;
}
/*private JScrollPane initProjectPanel(OrgTreePanel orgPanel) throws Exception {//
Dimension orgDimension = orgPanel.getPreferredSize();
orgPanel.setPreferredSize(new Dimension(orgDimension.width*2, orgDimension.height-100));
DefaultMutableTreeNode root = new DefaultMutableTreeNode(project.getProjectID(), true);
projectTree = new JTree(root);
List<Object> team = project.getTeam();
TCComponent[] members = (TCComponent[])team.get(0);
for(TCComponent c : members) {
if(c instanceof TCComponentGroupMember) {
TCComponentGroupMember member = (TCComponentGroupMember)c;
DefaultMutableTreeNode childRoot = new DefaultMutableTreeNode(member, true);
root.add(childRoot);
}
}
projectTree.setPreferredSize(new Dimension(orgDimension.width*2, orgDimension.height/2));
// projectTree.setMaximumSize(new Dimension(orgDimension.width*2, orgDimension.height/2));
JScrollPane projectPane = new JScrollPane(projectTree);
return projectPane;
}*/
private String getSelectUser() throws Exception {
// Object[] comps = tree.getSelectedOrgObjects();
AIFTreeNode[] comps = tree.getSelectedNodes();
// System.out.println("comps:"+(comps==null));
if (comps == null) {
return null;
}
DefaultMutableTreeNode selectNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
if(!selectNode.isLeaf())
return null;
// System.out.println("comps:"+comps.length);
for (int i = 0; i < comps.length; i++) {
// OrgObject comp = (OrgObject) comps[i];
TCComponent gm = (TCComponent) comps[i].getContextComponent().getComponent();
// System.out.println("gm:"+gm);
if (gm != null && (gm instanceof TCComponentGroupMember)) {
TCComponentUser user = ((TCComponentGroupMember) gm).getUser();
if (user != null) {
/*group = ((DefaultMutableTreeNode)comps[i].getParent().getParent()).getUserObject().toString();
if(group.indexOf(".")>0)
group = group.substring(0, group.indexOf("."));
else if(group.indexOf("\\.")>0)
group = group.substring(0, group.indexOf("\\."));*/
return userString(user);
}
}
}
return null;
}
private ArrayList<String> getSelectUsers() throws Exception {//TODO getSelectUsers
ArrayList<String> list = new ArrayList<>();
for (AIFTreeNode comp : tree.getSelectedNodes()) {
recycleNode(comp, list, 0, false);
}
return list;
}
private void recycleNode(AIFTreeNode comp, ArrayList<String> list, int level, boolean b) throws Exception {
System.out.println("recycleNode:"+comp);
if(comp==null)
return;
if(comp.isLeaf()) {
TCComponent gm = (TCComponent) comp.getContextComponent().getComponent();
System.out.println("isLeaf:"+gm);
if (gm != null && (gm instanceof TCComponentGroupMember)) {
TCComponentUser user = ((TCComponentGroupMember) gm).getUser();
if (user != null) {
System.out.println(((TCComponentGroupMember) gm).getGroup()+"=="+((TCComponentGroupMember) gm).getRole());
String users = userString(user);
if(b) {
role = ""+((TCComponentGroupMember) gm).getRole();
users = group+"@@"+role+"@@"+users;
}
if (!lm_user.contains(users) && !list.contains(users)) {
System.out.println("add1:"+users);
list.add(users);
}
}
}
}else {
// System.out.println("comp:"+comp+"=="+comp.getChildCount());
if(comp.getChildCount()==0) {
TCComponent c = (TCComponent) comp.getContextComponent().getComponent();
System.out.println("getChildCount()==0:"+c);
if(c instanceof TCComponentRole) {
System.out.println("parent:"+comp.getParent());
AIFTreeNode parent = (AIFTreeNode) comp.getParent();
recycleGroup((TCComponentGroup) parent.getContextComponent().getComponent(), list, level-1, b);
// for(TCComponentUser user : ((TCComponentRole)c).getUsers((TCComponentGroup) parent.getContextComponent().getComponent())) {
// String users = userString(user);
// if(b)
// users = group+"@@"+role+"@@"+users;
// if (!lm_user.contains(users) && !list.contains(users))
// list.add(users);
// }
}else {
TCComponentGroup gm = (TCComponentGroup) comp.getContextComponent().getComponent();
if(level<=2)
group = gm.getLocalizedName();
recycleGroup(gm, list, level+1, b);
}
}else {
if(comp.getContextComponent()==null) {
System.out.println("AIFTreeNode:"+comp);
for(int i=0; i<comp.getChildCount(); i++) {
recycleNode((AIFTreeNode) comp.getChildAt(i), list, level+1, b);
}
return;
}
TCComponent cp = (TCComponent) comp.getContextComponent().getComponent();
System.out.println("cp:"+cp);
if(cp instanceof TCComponentRole) {
role = ((TCComponentRole)cp).getRoleName();
}else if(level<=2) {
group = ((TCComponentGroup)cp).getLocalizedName();
}
for (Object c : comp.getChildNodes()) {
recycleNode((AIFTreeNode) c, list, level+1, b);
}
}
}
}
private void recycleGroup(TCComponentGroup gm, ArrayList<String> list, int level, boolean b) throws Exception {
System.out.println("recycleGroup:"+gm);
for(TCComponentGroup g : gm.getGroups()) {
if(level<=2)
group = g.getLocalizedName();
recycleGroup(g, list, level+1, b);
}
for(TCComponentRole role : gm.getRoles()) {
this.role = role.getRoleName();
System.out.println("getRoleName:"+role);
for(TCComponentUser user : role.getUsers(gm)) {
String users = userString(user);
// System.out.println("userString:"+users);
if(b) {
String[] gs = (""+gm).split("\\.");
if(gs.length>1)
group = gs[gs.length-2];
users = group+"@@"+role+"@@"+users;
}
if (!lm_user.contains(users) && !list.contains(users)) {
System.out.println("add2:"+users);
list.add(users);
}
}
}
}
private void addListeners() {
this.b_cel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SqlUtil.free();
disposeDialog();
}
});
/*this.b_ok.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
if (isMulti) {
int size = lm_user.getSize();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++) {
String text = lm_user.getElementAt(i);
if (text != null) {
sb.append(text).append(",");
}
}
if (sb.length() > 0) {
sb.setLength(sb.length() - 1);
}
setValue(sb.toString());
} else {
String user = getSelectUser();
if (user != null) {
setValue(user);
} else {
setValue("");
}
}
SqlUtil.free();
disposeDialog();
} catch (Exception e1) {
e1.printStackTrace();
MessageBox.post("Error:"+e1.getMessage(), "ERROR", MessageBox.ERROR);
}
}
});*/
tree.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
try {
super.mouseClicked(e);
if(projectTree != null)
projectTree.clearSelection();
String user = getSelectUser();
if(user == null)
return;
if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
System.out.println("user:"+user);
if (isMulti) {
if (!lm_user.contains(user)) {
lm_user.addElement(user);
}
} else {
// setValue(user);
// disposeDialog();
}
}
lm_ip.removeAllElements();
if(!ipmap.containsKey(user))
return;
String[] ips = ipmap.get(user);
for(int i=0; i<ips.length; i++) {
lm_ip.add(i, ips[i]);
}
} catch (Exception e1) {
e1.printStackTrace();
MessageBox.post("Error:"+e1.getMessage(), "ERROR", MessageBox.ERROR);
}
}
});
//TODO Listener
this.add.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
ArrayList<String> list = getSelectUsers();
if(list.size()==0)
return;
for(String user : list) {
lm_user.addElement(user);
}
} catch (Exception e1) {
e1.printStackTrace();
MessageBox.post("Error:"+e1.getMessage(), "ERROR", MessageBox.ERROR);
}
}
});
this.remove.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int[] ind = l_user.getSelectedIndices();//.getSelectedIndex();
if(ind==null)
return;
for(int i=ind.length-1; i>=0; i--)
lm_user.remove(ind[i]);
}
});
/*
if(projectTree != null) {
projectTree.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
try {
super.mouseClicked(e);
tree.clearSelection();
if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
String user = getSelectUser();
if (user != null) {
if (isMulti) {
if (!lm_user.contains(user)) {
lm_user.addElement(user);
}
} else {
setValue(user);
disposeDialog();
}
}
}
} catch (Exception e1) {
e1.printStackTrace();
MessageBox.post("Error:"+e1.getMessage(), "ERROR", MessageBox.ERROR);
}
}
});
}
if(l_user != null) {
this.l_user.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
int ind = l_user.getSelectedIndex();
if (ind >= 0) {
lm_user.remove(ind);
}
}
@Override
public void mouseEntered(MouseEvent e) {
super.mouseEntered(e);
}
@Override
public void mouseExited(MouseEvent e) {
super.mouseExited(e);
}
});
}*/
}
private String userString(TCComponentUser user) {
// return user.getProperty("user_name");
return user.toString();
}
private String[] userString(String user) {
String[] users = new String[2];
int i = user.indexOf(" (");
users[0] = user.substring(i+2, user.length()-1);
users[1] = user.substring(0, i);
return users;
}
private XSSFRow getRow(XSSFSheet sheet, int num) throws Exception {
XSSFRow row = sheet.getRow(num);
if(row==null)
row = sheet.createRow(num);
return row;
}
private XSSFCell getCell(XSSFRow row, int col) throws Exception {
XSSFCell cell = row.getCell(col);
if(cell==null)
cell = row.createCell(col);
// if(row.getRowNum()>1)
// cell.setCellStyle(getCell(sourceRow, col).getCellStyle());
return cell;
}
class IPDialog extends AbstractAIFDialog {
private JList<String> ipl;
private DefaultListModel<String> ipm;
private HashMap<String, JTextField> dmap = new HashMap<>();
IPDialog(){
super(LoginIPSetDialog.this, true);
setTitle("IP段修改");
setLayout(new BorderLayout());
ipm = new DefaultListModel<>();
ipl = new JList<>(ipm);
JScrollPane ipsr = new JScrollPane(ipl);
if(lm_user.getSize()==1) {
String user = lm_user.elementAt(0);
if(ipmap.containsKey(user)) {
for(String ip : ipmap.get(user)) {
ipm.addElement(ip);
}
}
}
KeyAdapter ipcheck = new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char in = e.getKeyChar();
JTextField field = (JTextField) e.getComponent();
// String name = field.getName();
// boolean f = name.substring(name.length()-1).equals("1");
if (in >= KeyEvent.VK_0 && in <= KeyEvent.VK_9) {//数字
String text = field.getText()+in;
// System.out.println(name+"=>"+text+"=>"+in);
// int ip = Integer.parseInt(text);
// if(f && ip>233) {
// e.consume();
// MessageBox.post(text+" 不是有效项。请指定一个介于 1 和223 间的值。", "错误", MessageBox.WARNING);
// text = "223";
// field.setText(text);
// }else if(!f && ip>255) {
// e.consume();
// MessageBox.post(text+" 不是有效项。请指定一个介于 1 和255 间的值。", "错误", MessageBox.WARNING);
// text = "255";
// field.setText(text);
// }
if(text.length()==3)
field.transferFocus();
}else if(in == KeyEvent.VK_PERIOD) {//点
e.consume();
field.transferFocus();
}else if(in == KeyEvent.VK_BACK_SPACE) {//退格
super.keyTyped(e);
}else {
e.consume();
}
}
};
JPanel ipPanel = new JPanel(new PropertyLayout());//new FlowLayout(FlowLayout.CENTER)
ipPanel.add("1.1.center.center", new JLabel("IP"));
for(int i=1; i<5; i++) {
JTextField text = new JTextField(3);
text.setName("ip"+i);
text.addKeyListener(ipcheck);
ipPanel.add("1."+(i+1)+".center.center", text);
dmap.put("ip"+i, text);
}
JButton add = new JButton("+");
add.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StringBuilder ip = new StringBuilder("");
for(int i=1; i<5; i++) {
String text = dmap.get("ip"+i).getText();
if(text.isEmpty())
text = "0";
int ipi = Integer.parseInt(text);
if(i==1 && ipi>223) {
MessageBox.post(IPDialog.this, text+" 不是首段有效项。请指定一个介于 1 和223 间的值。", "错误", MessageBox.WARNING);
return;
}
if(ipi>255) {
MessageBox.post(IPDialog.this, text+" 不是有效项。请指定一个介于 1 和255 间的值。", "错误", MessageBox.WARNING);
return;
}
ip.append(".").append(text.isEmpty() ? "0" : Integer.parseInt(text));
}
String text = ip.substring(1);
if(!ipm.contains(text))
ipm.addElement(text);
for(int i=1; i<5; i++) {
dmap.get("ip"+i).setText("");
}
}
});
ipPanel.add("1.6.center.center", add);
ipPanel.add("2.1.center.center", new JLabel(" "));
ipPanel.add("3.1.center.center", new JLabel("IP段"));
for(int i=1; i<5; i++) {
JTextField text = new JTextField(3);
text.setName("ips"+i);
text.addKeyListener(ipcheck);
ipPanel.add("3."+(i+1)+".center.center", text);
dmap.put("ips"+i, text);
}
ipPanel.add("4.1.center.center", new JLabel("-"));
for(int i=5; i<9; i++) {
JTextField text = new JTextField(3);
text.setName("ips"+i);
text.addKeyListener(ipcheck);
ipPanel.add("4."+(i-3)+".center.center", text);
dmap.put("ips"+i, text);
}
JButton sadd = new JButton("+");
sadd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StringBuilder ip = new StringBuilder("");
for(int i=1; i<9; i++) {
String text = dmap.get("ips"+i).getText();
if(text.isEmpty())
text = "0";
int ipi = Integer.parseInt(text);
if((i==1 || i==5) && ipi>223) {
MessageBox.post(IPDialog.this, text+" 不是首段有效项。请指定一个介于 1 和223 间的值。", "错误", MessageBox.WARNING);
return;
}
if(ipi>255) {
MessageBox.post(IPDialog.this, text+" 不是有效项。请指定一个介于 1 和255 间的值。", "错误", MessageBox.WARNING);
return;
}
if(i==5)
ip.append("-");
else
ip.append(".");
ip.append(text.isEmpty() ? 0 : Integer.parseInt(text));
}
String text = ip.substring(1);
String[] ips = text.split("-");
if(compare(ips[0], ips[1])>=0) {
MessageBox.post("IP范围无效", "错误", MessageBox.WARNING);
return;
}
if(!ipm.contains(text))
ipm.addElement(text);
for(int i=1; i<9; i++) {
dmap.get("ips"+i).setText("");
}
}
});
ipPanel.add("4.6.center.center", sadd);
JButton remove = new JButton("移除IP");
remove.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int[] ind = ipl.getSelectedIndices();
if(ind==null)
return;
for(int i=ind.length-1; i>=0; i--)
ipm.remove(ind[i]);
}
});
JPanel removePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
removePanel.add(remove);
JPanel ripPanel = new JPanel(new BorderLayout());
ripPanel.add(BorderLayout.NORTH, removePanel);
ripPanel.add(BorderLayout.CENTER, ipPanel);
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
splitPane.setOneTouchExpandable(true);// 让分割线显示出箭头
splitPane.setContinuousLayout(true);// 操作箭头,重绘图形
splitPane.setTopComponent(ipsr);
splitPane.setBottomComponent(ripPanel);
JPanel ibPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JButton editIP = new JButton("确认修改");
JButton cancel = new JButton("取消");
ibPanel.add(editIP);
ibPanel.add(cancel);
editIP.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
StringBuilder ips = new StringBuilder("");
Enumeration<String> ipe = ipm.elements();
while(ipe.hasMoreElements()) {
ips.append(",").append(ipe.nextElement());
}
if(ips.length()>0)
ips.deleteCharAt(0);
String[] ipa = ips.toString().split(",");
String select = getSelectUser();
StringBuilder sql = new StringBuilder("update CONNOR_USER_IP set IP='");
sql.append(ips).append("' where PUSER in (");
boolean update = false;
Enumeration<String> users = lm_user.elements();
while(users.hasMoreElements()) {
String user = users.nextElement();
if(!ipmap.containsKey(user)) {
String insert = "insert into CONNOR_USER_IP values('"+user+"','"+ips+"')";
System.out.println("insert:"+insert);
SqlUtil.update(insert);
ipmap.put(user, ipa);
continue;
}
ipmap.put(user, ipa);
update = true;
sql.append("'").append(user).append("',");
if(select!=null && select.equals(user)){
lm_ip.removeAllElements();
for(String ip : ipa) {
lm_ip.addElement(ip);//TODO
}
}
}
if(update) {
sql.deleteCharAt(sql.length()-1).append(")");
System.out.println("update:"+sql);
SqlUtil.update(sql.toString());
}
dispose();
}catch(Exception ex) {
ex.printStackTrace();
MessageBox.post("错误:"+ex.getMessage(), "ERROR", MessageBox.ERROR);
}
}
});
cancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
add(BorderLayout.CENTER, splitPane);
add(BorderLayout.SOUTH, ibPanel);
setPreferredSize(new Dimension(400, 500));
pack();
centerToScreen();
setVisible(true);
}
private int compare(String ip, String str) {
String[] ips = ip.split("\\."), s = str.split("\\.");
for(int i=0; i<4; i++) {
int p = Integer.parseInt(ips[i]), n = Integer.parseInt(s[i]);
System.out.println("compare:"+p+","+n+"=="+(p>n));
if(p>n)
return 1;
else if(p<n)
return -1;
}
return 0;
}
}
}

@ -0,0 +1,55 @@
package com.connor.jingdiao.handlers;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import com.teamcenter.rac.aif.AIFDesktop;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentUser;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;
//标准化审核
public class LoginIPSetHandler extends AbstractHandler implements IHandler{
public Object execute(ExecutionEvent arg0) throws ExecutionException {
System.out.println("LoginIPSetHandler");
new Thread() {
public void run() {
AIFDesktop desktop = AIFUtility.getActiveDesktop();
try {
TCSession session = (TCSession) AIFUtility.getCurrentApplication().getSession();
TCComponentUser user = session.getUser();
if(!user.getUserId().equals("infodba")) {
MessageBox.post(desktop, "禁止操作", "ERROR", MessageBox.ERROR);
return;
}
String[] options = session.getPreferenceService().getStringValues("Jd_TC_Info_Connect");
if(options == null || options.length < 4) {
MessageBox.post(desktop, "首选项Jd_TC_Info_Connect配置不正确", "ERROR", MessageBox.ERROR);
return;
}
String option = session.getPreferenceService().getStringValue("Jd6_IP_model");
if(option == null || option.isEmpty()) {
MessageBox.post(desktop, "首选项Jd6_IP_model配置不正确", "ERROR", MessageBox.ERROR);
return;
}
TCComponent dataset = session.stringToComponent(option);
if(dataset==null || !dataset.getType().equals("MSExcelX")) {
MessageBox.post(desktop, "首选项Jd6_IP_model配置不正确", "ERROR", MessageBox.ERROR);//QiAAAI4S5kSPsC
return;
}
new LoginIPSetDialog(session, dataset, options);
}catch(Exception e) {
e.printStackTrace();
MessageBox.post(desktop, "错误:"+e.getMessage(), "ERROR", MessageBox.ERROR);
return;
}
}
}.start();
return null;
}
}

@ -0,0 +1,421 @@
package com.connor.jingdiao.handlers;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JDialog;
//import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.connor.jingdiao.util.TCUtil;
import com.connor.ml.tcm.outfile.util.MethodUtil;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentDataset;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentTask;
import com.teamcenter.rac.kernel.TCComponentTcFile;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;
public class StandardDialog extends JDialog {
private static final long serialVersionUID = 1L;
private TCSession session;
private JTextArea remark;
private JButton remarkBtn;
private JButton exportBtn;
private JButton closeBtn;
private JTable impTable;
private DefaultTableModel impModel;
private ArrayList<TCComponentItemRevision> revlist;
private String[] mark;
private int mrow = -1;
// private HashMap<String, Integer> map;
// private LinkedHashMap<String, String[]> ruleOpsMap;
// public DrawingNoApplyDialog(TCSession session, String tables[], String[] options, String[] sqlOptions, InterfaceAIFComponent[] targets) throws Exception {
public StandardDialog(TCSession session, TCComponent[] models, TCComponentTask task, LinkedHashMap<String, String[]> ruleOpsMap, int[] cols)
throws Exception {
super(AIFUtility.getActiveDesktop());
this.session = session;
// list = new ArrayList<>();
// map = new HashMap<>();
// this.ruleOpsMap = ruleOpsMap;
// System.out.println(ruleOpsMap.toString());
setTitle("标准化审核");
remark = new JTextArea();
// remark.setPreferredSize(new Dimension(10, 10));
remark.setLineWrap(true);
remarkBtn = new JButton("修改备注");
exportBtn = new JButton("导出Excel");
closeBtn = new JButton("关闭");
JPanel btnPanel = new JPanel(new FlowLayout());
btnPanel.add(remarkBtn);
btnPanel.add(exportBtn);
btnPanel.add(closeBtn);
JScrollPane remarkPanel = new JScrollPane(remark);
remarkPanel.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.add(BorderLayout.NORTH, new JLabel("标准化备注"));
topPanel.add(BorderLayout.CENTER, remarkPanel);
topPanel.add(BorderLayout.SOUTH, btnPanel);
// ArrayList<String[]> props = new ArrayList<>();
// String[] tableHeader = new String[] { "序号", "itemID", "名称", "版本", "加工类型", "产品分类码", "课题号", "配置码", "部件码", "图纸类型", "新图号" };
// String[] tables = options.get(0);
String[] tableHeader = new String[ruleOpsMap.size() + 1];
tableHeader[0] = "序号";
int h = 1;
for (String s : ruleOpsMap.keySet()) {
// String[] split = tables[h].split("=");
// props.add(split[1].split("\\."));
tableHeader[h] = s;
if(s.equals("标准化备注")) {
mark = ruleOpsMap.get(s);
mrow = h;
}
// map.put(split[1], h);
h++;
}
if(mrow < 0)
throw new Exception("首选项Jd_Standard_UI配置不正确");
impModel = new DefaultTableModel(tableHeader, 0);
impTable = new JTable() {
private static final long serialVersionUID = 1L;
@Override
public boolean isCellEditable(int row, int col) {
return false;
}
};
impTable.getTableHeader().setReorderingAllowed(false);
impTable.setFillsViewportHeight(true);
// impTable.setEnabled(false);
impTable.setEnabled(true);
// impTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
impTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
impTable.setModel(impModel);
for (int i = 1; i < impModel.getColumnCount(); i++) {
TableColumn col = impTable.getColumnModel().getColumn(i);
col.setCellRenderer(new TextAreaRenderer());
col.setPreferredWidth(150);
}
setDatas(task, (TCComponentDataset) models[0], ruleOpsMap);
addActionListener(models, cols);
setLayout(new BorderLayout());
add(BorderLayout.EAST, topPanel);
add(BorderLayout.CENTER, new JScrollPane(impTable));
pack();
setSize(new Dimension(1400, 500));
setDefaultLookAndFeelDecorated(true);
Dimension screen = getToolkit().getScreenSize();
setLocation((screen.width - getSize().width) / 2, (screen.height - getSize().height) / 2);
setAlwaysOnTop(true);
setVisible(true);
}
@SuppressWarnings("rawtypes")
private void setDatas(TCComponentTask task, TCComponentDataset model, LinkedHashMap<String, String[]> ruleOpsMap) throws Exception {
TCComponentTcFile[] files = model.getTcFiles();
File file = files[0].getFile(System.getProperty("java.io.tmpdir"));
SAXReader saxReader = new SAXReader();
Document doc = saxReader.read(file);
Element root = doc.getRootElement();
Element condizione = root.element("condizione");
List typeEs = condizione.element("object_type").elements();
ArrayList<String> types = new ArrayList<>();
for(Object e : typeEs) {
types.add(((Element)e).getText());
}
List regolaEs = condizione.element("regola").elements();
HashMap<String, Boolean> regolas = new HashMap<>();
for(Object e : regolaEs) {
String t = ((Element)e).getText();
String name = ((Element)e).getName();
if(name.equals("item"))
name = "object_type";
if(t.equals("*")) {
regolas.put(name, false);
}else {
regolas.put(name, true);
}
}
List rows = root.element("data").elements();
AIFComponentContext[] contexts = TCUtil.getPseudoFolder(task, "root_target_attachments").getChildren();
revlist = new ArrayList<>();
for(AIFComponentContext c : contexts) {
if(!types.contains(c.getComponent().getType()))
continue;
TCComponentItemRevision rev = (TCComponentItemRevision) c.getComponent();
HashMap<String, String> props = new HashMap<>();
for(String s : regolas.keySet()) {
if(rev.getTCProperty(s) == null) {
System.out.println(rev+" >> "+s+"\n属性未找到");
throw new Exception("判断条件配置错误,请检查配置信息");
}
props.put(s, rev.getProperty(s));
}
ROW:for(Object e : rows) {
for(Object t : ((Element)e).elements()) {
String name = ((Element)t).getName();
if(!props.containsKey(name))
continue;
String text = ((Element)t).getText();
String val = props.get(name);
if(regolas.get(name)) {
if(text.equals("null")) {
if(!val.isEmpty())
continue ROW;
}else if(!val.equals(text))
continue ROW;
}else if(!regolas.get(name) && !val.contains(text)) {
continue ROW;
}
}
TCComponentItem item = rev.getItem();
String[] row = new String[ruleOpsMap.size()+1];
row[0] = impTable.getRowCount()+1+"";
int i = 1;
for(String n : ruleOpsMap.keySet()) {
row[i] = getProp(ruleOpsMap.get(n), item, rev);
i++;
}
System.out.println("row:"+Arrays.toString(row));
impModel.addRow(row);
revlist.add(rev);
break;
}
}
}
private void addActionListener(TCComponent[] models, int[] cols) {
impTable.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
try {
int row = impTable.getSelectedRow();
if(row < 0) {
return;
}
remark.setText(""+impTable.getValueAt(row, mrow));
} catch (Exception e1) {
e1.printStackTrace();
MessageBox.post(StandardDialog.this, "错误:" + e1.getMessage(), "ERROR", MessageBox.ERROR);
}
}
});
remarkBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
try {
int row = impTable.getSelectedRow();
if(row < 0) {
MessageBox.post(StandardDialog.this, "请选择要编辑的行!", "ERROR", MessageBox.ERROR);
return;
}
String text = remark.getText();
if(text.getBytes().length > 1024) {
MessageBox.post(StandardDialog.this, "标准化备注填写长度过长,无法修改!", "ERROR", MessageBox.ERROR);
return;
}
TCComponentItemRevision rev = revlist.get(row);
TCComponentItem item = rev.getItem();
if(mark[0].equals("item") && item.isCheckedOut()) {
MessageBox.post(StandardDialog.this, item+" 已签出,无法修改!", "ERROR", MessageBox.ERROR);
return;
}else if(mark[0].equals("rev") && rev.isCheckedOut()) {
MessageBox.post(StandardDialog.this, rev+" 已签出,无法修改!", "ERROR", MessageBox.ERROR);
return;
}
MethodUtil.openByPass(session);
if(mark[0].equals("item")) {
item.setProperty(mark[1], text);
}else if(mark[0].equals("rev")) {
rev.setProperty(mark[1], text);
}
impTable.setValueAt(text, row, mrow);
MethodUtil.closeByPass(session);
}catch(Exception e1) {
e1.printStackTrace();
MessageBox.post(StandardDialog.this, "错误:"+e1.getMessage(), "ERROR", MessageBox.ERROR);
}finally {
try {
MethodUtil.closeByPass(session);
}catch(Exception e1) {
e1.printStackTrace();
}
}
}
});
//TODO
exportBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
FileInputStream input = null;
FileOutputStream output = null;
XSSFWorkbook wb = null;
try {
File directory = TCUtil.saveExcelChooser(StandardDialog.this, "");
if(directory==null)
return;
if(directory.exists())
directory.delete();
TCComponentDataset model = (TCComponentDataset) models[1];
TCComponentTcFile[] files = model.getTcFiles();
File file = files[0].getFile(System.getProperty("java.io.tmpdir"));
input = new FileInputStream(file);
wb = new XSSFWorkbook(input);
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row;
XSSFCell cell;
row = getRow(sheet, cols[0]);
TableColumnModel cm = impTable.getColumnModel();
for(int i=0; i<cm.getColumnCount(); i++) {
cell = getCell(row, i);
cell.setCellValue(cm.getColumn(i).getHeaderValue().toString());
}
for(int i=0; i<impTable.getRowCount(); i++) {
row = getRow(sheet, i + cols[1]);
for(int j=0; j<impTable.getColumnCount(); j++) {
cell = getCell(row, j);
cell.setCellValue(impTable.getValueAt(i, j).toString());
}
}
output = new FileOutputStream(file.getPath());
wb.write(output);
input.close();
output.close();
file.renameTo(directory);
MessageBox.post(StandardDialog.this, "导出完成!", "提示", MessageBox.INFORMATION);
}catch(Exception e1) {
e1.printStackTrace();
MessageBox.post(StandardDialog.this, "错误:"+e1.getMessage(), "ERROR", MessageBox.ERROR);
}finally {
if(input!=null)
try {
input.close();
} catch (Exception e) {
e.printStackTrace();
}
if(output!=null)
try {
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
closeBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
dispose();
}
});
}
private String getProp(String[] ps, TCComponentItem item, TCComponentItemRevision rev) throws Exception {
if(ps[0].equals("item")) {
return item.getProperty(ps[1]);
}else if(ps[0].equals("rev")) {
return rev.getProperty(ps[1]);
}
return "";
}
private XSSFRow getRow(XSSFSheet sheet, int num) throws Exception {
XSSFRow row = sheet.getRow(num);
if(row==null)
row = sheet.createRow(num);
return row;
}
private XSSFCell getCell(XSSFRow row, int col) throws Exception {
XSSFCell cell = row.getCell(col);
if(cell==null)
cell = row.createCell(col);
// if(row.getRowNum()>1)
// cell.setCellStyle(getCell(sourceRow, col).getCellStyle());
return cell;
}
public class TextAreaRenderer extends JTextArea implements TableCellRenderer {
private static final long serialVersionUID = 1L;
// ArrayList<Integer> area;
public TextAreaRenderer() {
// this.area = area;
setLineWrap(true); //利用JTextArea的自动换行方法
setWrapStyleWord(true);
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
// 计算当下行的最佳高度
int maxPreferredHeight = 22;
JTextArea cell = new JTextArea();
// cell.setLineWrap(true);
for (int i=0; i<table.getColumnCount(); i++) {
cell.setText("" + table.getValueAt(row, i));
// maxPreferredHeight = Math.max(maxPreferredHeight,cell.getPreferredSize().height);
// if(row == 19)
// System.out.println(i+">>>"+table.getValueAt(row, i)+">>>"+cell.getPreferredSize().width+","+cell.getPreferredSize().height);
maxPreferredHeight = Math.max(maxPreferredHeight,
(cell.getPreferredSize().width/table.getColumnModel().getColumn(i).getWidth()+1)*cell.getPreferredSize().height+7);
}
if (table.getRowHeight(row) != maxPreferredHeight)
// 少了这行则处理器瞎忙
table.setRowHeight(row, maxPreferredHeight);
//System.out.println(row+":"+maxPreferredHeight);
setText(value == null ? "" : value.toString());
fillColor(table,this,isSelected);
return this;
}
public void fillColor(JTable t,JTextArea l,boolean isSelected ){
if(isSelected){
l.setBackground(t.getSelectionBackground());
l.setForeground(t.getSelectionForeground());
} else {
l.setBackground(t.getBackground());
l.setForeground(t.getForeground());
}
}
}
}

@ -0,0 +1,80 @@
package com.connor.jingdiao.handlers;
import java.util.LinkedHashMap;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import com.teamcenter.rac.aif.AIFDesktop;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentTask;
import com.teamcenter.rac.kernel.TCComponentTaskTemplate;
import com.teamcenter.rac.kernel.TCHandlerType;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;
//标准化审核
public class StandardHandler extends AbstractHandler implements IHandler{
public Object execute(ExecutionEvent arg0) throws ExecutionException {
System.out.println("StandardHandler");
TCSession session = (TCSession) AIFUtility.getCurrentApplication().getSession();
AIFDesktop desktop = AIFUtility.getActiveDesktop();
try {
InterfaceAIFComponent target = AIFUtility.getCurrentApplication().getTargetComponent();
if(!(target instanceof TCComponentTask)) {
MessageBox.post(desktop, "请选择流程任务进行标准化审核!", "ERROR", MessageBox.ERROR);
return null;
}
TCComponentTask task = (TCComponentTask) target;
TCComponent handler = task.getHandler(TCHandlerType.ACTION, TCComponentTaskTemplate.COMPLETE_ACTION, "j6_Standard");//Connor_check_process_member
if(handler == null) {
MessageBox.post(desktop, "节点handler配置不满足要求无法执行", "ERROR", MessageBox.ERROR);
return null;
}
LinkedHashMap<String, String[]> ruleOpsMap = new LinkedHashMap<>();
String[] options = session.getPreferenceService().getStringValues("Jd_Standard_UI");
if(options == null || options.length == 0) {
MessageBox.post(desktop, "首选项Jd_Standard_UI配置不正确", "ERROR", MessageBox.ERROR);
return null;
}
int[] cols = new int[2];
for(String s : options) {
if(!s.contains("=")) {
String[] sp = s.split(";");
cols[0] = Integer.parseInt(sp[0]) - 1;
cols[1] = Integer.parseInt(sp[1]) - 1;
continue;
}
String[] sp = s.split("=");
String[] pp = sp[0].split("\\.");
ruleOpsMap.put(sp[1], new String[] { pp[0].toLowerCase(), pp[1] });
}
options = session.getPreferenceService().getStringValues("j6_Standard_puid");
if(options == null || options.length < 2) {
MessageBox.post(desktop, "首选项j6_Standard_puid配置不正确", "ERROR", MessageBox.ERROR);
return null;
}
TCComponent[] datasets = session.stringToComponent(options);
if(datasets.length<2 || datasets[0]==null || !datasets[0].getType().equals("XMLRenderingStylesheet")) {
MessageBox.post(desktop, "首选项j6_Standard_puid配置不正确", "ERROR", MessageBox.ERROR);//QKIAAI4S5kSPsC
return null;
}
if(datasets[1]==null || !datasets[1].getType().equals("MSExcelX")) {
MessageBox.post(desktop, "首选项j6_Standard_puid配置不正确", "ERROR", MessageBox.ERROR);//QiAAAI4S5kSPsC
return null;
}
new StandardDialog(session, datasets, task, ruleOpsMap, cols);
}catch(Exception e) {
e.printStackTrace();
MessageBox.post(desktop, "错误:"+e.getMessage(), "ERROR", MessageBox.ERROR);
return null;
}
return null;
}
}

@ -0,0 +1,101 @@
package com.connor.jingdiao.handlers;
import java.util.HashMap;
import java.util.Optional;
public class Test {
public static void main(String[] args) {
HashMap<String[], String> opm = new HashMap<>();
// for (int i = 0; i < options.length; i++) {
String optionString = "rev.j6_drawingtype=零件@rev.j6_processtype=外购件@@#rev.j6_productseries+rev.j6_topicno";
String[] sss = optionString.split("@@");
opm.put(sss[0].split("@"), sss[1]);
boolean present = Optional.ofNullable("ss").isPresent();
System.out.println("::"+present);
OPM: for (String[] ss : opm.keySet()) {
boolean check = false;
for (int j = 0; j < ss.length; j++) {
String[] s2 = ss[j].split("=");
String[] ss2 = s2[1].split(";");
boolean c = true;
for(String s : ss2) {
System.out.println("::"+s+"=="+"<<"+s2[0]);
// if(s.equals(impTable.getValueAt(i, map.get(s2[0])))){
// c = false;
// break;
// }
}
System.out.println(c);
if(c)
check = true;
}
System.out.println("check:"+check);
// if(check)
// continue;
// norule = false;
StringBuilder id = new StringBuilder("");
String rul = opm.get(ss);
String[] rule = rul.split("\\+");
for(String s : rule) {
if(s.startsWith(".")) {
id.append(s);
}else if(s.startsWith("LSH")) {
String lsh = "%" + String.format("%02d", Integer.parseInt(s.substring(3))) + "d";
id.append(String.format(lsh, 2));
// List<HashMap<String, Object>> results = SqlUtil.getDBInfo(conn, "select SERIALNUMBER from JD_CODE_RULE where CODEKEY='"+id+"'");
// if (results.size() == 0) {
// SqlUtil.update("insert into JD_CODE_RULE values('" +id+ "',1)");
// id.append(String.format(lsh, 1));
// } else {
// int no = (Integer) results.get(0).get("SERIALNUMBER") + 1;
// SqlUtil.update("update JD_CODE_RULE set SERIALNUMBER=" + no + " where CODEKEY='" +id+ "'");
// id.append(String.format(lsh, no));
// }
}else if(s.startsWith("#rev.")) {
System.out.println("s.substring(5)==>"+s.substring(5));
// String value = rev.getStringProperty(s.substring(5));
// if(value.isEmpty()) {
// msg.append(rev).append(" 的部分图号相关属性为空,请检查\n");
// break OPM;
// }
id.append("revVal");
}
// else if(map.containsKey(s)) {
// String value = impTable.getValueAt(i, map.get(s)).toString();
// if(value.isEmpty()) {
// msg.append(rev).append(" 的部分图号相关属性为空,请检查\n");
// break OPM;
// }
// id.append(value);
// }
else if(s.contains(".")) {//.startsWith("J6_ASSOCIATED_REL.j6_drawingno")
String[] sp = s.split("\\.");
System.out.println("sp[0]"+sp[0]+"sp[1]"+sp[1]);
// id.append(s);
}else {
id.append(s);
}
}
if(!rul.contains("LSH")) {
System.out.println("sql==>"+"select SERIALNUMBER from JD_CODE_RULE where CODEKEY='"+id+"'");
// List<HashMap<String, Object>> results = SqlUtil.getDBInfo(conn, "select SERIALNUMBER from JD_CODE_RULE where CODEKEY='"+id+"'");
// if (results.size() == 0) {
//
// SqlUtil.update("insert into JD_CODE_RULE values('" +id+ "',0)");
// }else {
// msg.append(rev).append(" 的物料编码 ").append(id).append(" 已存在,请检查相关属性值\n");
// break;
// }
}
String dno = id.toString();
System.out.println("dno==>"+dno);
break;
}
// }
}
}

@ -0,0 +1,377 @@
package com.connor.jingdiao.handlers;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import com.connor.jingdiao.util.SqlTIUtil;
import com.connor.jingdiao.util.SqlUtil;
import com.teamcenter.rac.aif.AbstractAIFDialog;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.kernel.TCAccessControlService;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;
public class WlbmApplyDialog extends AbstractAIFDialog {
private JButton exportBtn;
private JButton closeBtn;
private JTable impTable;
private DefaultTableModel impModel;
private ArrayList<TCComponentItemRevision> list;
private HashMap<String, Integer> map;
private HashMap<String, String> productClassMap;
public WlbmApplyDialog(TCSession session, String tables[], String[] options,
String[] sqlOptions, InterfaceAIFComponent[] targets,String[] sqlOptionsTI,String[] productClass) throws Exception {
super(AIFUtility.getActiveDesktop());
// this.session = session;
list = new ArrayList<>();
map = new HashMap<>();
productClassMap = new HashMap<String, String>();
setTitle("物料编码申请");
exportBtn = new JButton("申请");
closeBtn = new JButton("关闭");
JPanel btnPanel = new JPanel(new FlowLayout());
btnPanel.add(exportBtn);
btnPanel.add(closeBtn);
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.add(BorderLayout.SOUTH, btnPanel);
ArrayList<String[]> props = new ArrayList<>();
// String[] tableHeader = new String[] { "序号", "itemID", "名称", "版本", "加工类型", "产品分类码", "课题号", "配置码", "部件码", "图纸类型", "新图号" };
String[] tableHeader = new String[tables.length + 1];
tableHeader[0] = "序号";
for(int i=0;i<productClass.length;i++) {
String[] split = productClass[i].split("=");
productClassMap.put(split[0], split[1]);
}
for (int i = 0; i < tables.length; i++) { //存放表头信息
String[] split = tables[i].split("=");
props.add(split[1].split("\\."));
tableHeader[i + 1] = split[0];
map.put(split[1], i + 1);
}
System.out.println("MAP==>"+map.toString());
impModel = new DefaultTableModel(tableHeader, 0);
impTable = new JTable() {
private static final long serialVersionUID = 1L;
@Override
public boolean isCellEditable(int row, int col) {
return false;
}
};
impTable.getTableHeader().setReorderingAllowed(false);
impTable.setFillsViewportHeight(true);
// impTable.setEnabled(false);
impTable.setEnabled(true);
// impTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
impTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
impTable.setModel(impModel);
for (int i = 1; i < impModel.getColumnCount(); i++)
impTable.getColumnModel().getColumn(i).setPreferredWidth(150);
int r = 1;
TCAccessControlService acs = session.getTCAccessControlService();
TCComponent[] user = new TCComponent[]{ session.getUser(), session.getGroup(), session.getRole() };
StringBuilder msg = new StringBuilder("");
StringBuilder msg2 = new StringBuilder("");
for (InterfaceAIFComponent t : targets) {
TCComponentItemRevision rev = (TCComponentItemRevision) t;
if (!rev.getProperty("j6_wlbm").isEmpty()) {
msg.append(rev).append("、");
continue;
}
if(!acs.checkAccessorsPrivilege(user, rev, "WRITE")) {
msg2.append(rev).append("、");
continue;
}
TCComponentItem item = rev.getItem();
int size = props.size() + 1;
Object[] data = new Object[size];
data[0] = r++;
for (int i = 1; i < size; i++) {
String[] ss = props.get(i-1);
System.out.println("prop==>"+ss[1]);
if (ss[0].equals("item")) {
data[i] = item.getProperty(ss[1]);
} else {
data[i] = rev.getProperty(ss[1]);
}
}
impModel.addRow(data);
list.add(rev);
}
if (targets.length > list.size()) {
StringBuilder m = new StringBuilder("所选对象:\n");
if(msg.length()>0) {
m.append(msg.deleteCharAt(msg.length() - 1)).append(" 已有物料编码,无法再次申请!\n");
}
if(msg2.length()>0) {
m.append(msg2.deleteCharAt(msg2.length() - 1)).append(" 无编辑权限,无法申请物料编码!");
}
MessageBox.post(AIFUtility.getActiveDesktop(), m.toString(), "警告", MessageBox.WARNING);
}
if (list.size() == 0) {
return;
}
JScrollPane tablePanel = new JScrollPane(impTable);
addActionListener(options, sqlOptions,sqlOptionsTI);
setLayout(new BorderLayout());
add(BorderLayout.NORTH, topPanel);
add(BorderLayout.CENTER, tablePanel);
pack();
setSize(new Dimension(1400, 700));
setDefaultLookAndFeelDecorated(true);
Dimension screen = getToolkit().getScreenSize();
setLocation((screen.width - getSize().width) / 2, (screen.height - getSize().height) / 2);
// setAlwaysOnTop(true);
setVisible(true);
}
private void addActionListener(String[] options, String[] sqlOptions, String[] sqlOptionsTI) {
exportBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
try {
Connection conn = SqlUtil.getSqlserverConnection("oracle.jdbc.driver.OracleDriver",
"jdbc:oracle:thin:@" + sqlOptions[0] + ":1521:" + sqlOptions[3], sqlOptions[1], sqlOptions[2]);
if (conn == null) {
throw new Exception("无法获取数据库连接信息");
}
Connection connTI = SqlTIUtil.getSqlserverConnection("oracle.jdbc.driver.OracleDriver",
"jdbc:oracle:thin:@" + sqlOptionsTI[0] + ":1521:" + sqlOptionsTI[3], sqlOptionsTI[1], sqlOptionsTI[2]);
if (connTI == null) {
throw new Exception("无法获取TI数据库连接信息");
}
StringBuilder msg = new StringBuilder("");
HashMap<String[], String> opm = new HashMap<>();
for (int i = 0; i < options.length; i++) {
String[] ss = options[i].split("@@");
opm.put(ss[0].split("@"), ss[1]);
}
for (int i = 0; i < list.size(); i++) {
TCComponentItemRevision rev = list.get(i);
//加工方式为零件的Part 找bom上级
String processType = rev.getProperty("j6_processtype");
String itemType = rev.getItem().getType();
if(itemType.equals("Part")&&processType.equals("零件")) {
TCComponent[] procs = rev.whereUsed(TCComponentItemRevision.WHERE_USED_ALL);
for(TCComponent component : procs) {
if(component instanceof TCComponentItemRevision) {
TCComponentItemRevision zjRevision = (TCComponentItemRevision) component;
String zjType = zjRevision.getProperty("j6_processtype");
if(zjRevision.getType().contains("Part") && zjType.equals("组件")) {
String pDon = zjRevision.getProperty("j6_wlbm");
if(pDon.isEmpty()) {
msg.append(rev).append(" 上级图纸无物料编码,请先申请上级物料编码后再申请本物料编码\n");
break;
}
if(pDon.endsWith("00")) {
String id = pDon.substring(0, pDon.length()-2);
StringBuffer code = new StringBuffer("");
List<HashMap<String, Object>> results = SqlUtil.getDBInfo(conn, "select SERIALNUMBER from JD_CODE_RULE where CODEKEY='"+id+"'");
if (results.size() == 0) {
List<HashMap<String, Object>> resultsTi = SqlTIUtil.getDBInfo(connTI, "select ECMS_NEXTCODE from ECMS_SERIAL where ECMS_PRE='"+id+"'");
if(resultsTi.size()==0) {
SqlUtil.update("insert into JD_CODE_RULE values('" +id+ "',1)");
code.append(String.format("%02d", 1));
}else {
int no = (Integer) results.get(0).get("ECMS_NEXTCODE") + 1;
SqlUtil.update("update JD_CODE_RULE set SERIALNUMBER=" + no + " where CODEKEY='" +id+ "'");
code.append(String.format("%02d", no));
}
} else {
int no = (Integer) results.get(0).get("SERIALNUMBER") + 1;
SqlUtil.update("update JD_CODE_RULE set SERIALNUMBER=" + no + " where CODEKEY='" +id+ "'");
code.append(String.format("%02d", no));
}
rev.setProperty("j6_wlbm", code.toString());
impTable.setValueAt(code, i, map.get("rev.j6_wlbm"));
break;
}
}
}
}
continue;
}
boolean norule = true;
OPM: for (String[] ss : opm.keySet()) {
boolean check = false;
for (int j = 0; j < ss.length; j++) {
String[] s2 = ss[j].split("=");
String[] ss2 = s2[1].split(";");
boolean c = true;
for(String s : ss2) {
System.out.println(i+"::"+s+"=="+impTable.getValueAt(i, map.get(s2[0]))+"<<"+s2[0]);
if(s.equals(impTable.getValueAt(i, map.get(s2[0])))){
c = false;
break;
}
}
System.out.println(c);
if(c) {
check = true;
}else {
check = false;
}
}
System.out.println("check:"+check);
if(check) {
continue;
}
norule = false;
StringBuilder id = new StringBuilder("");
String rul = opm.get(ss);
System.out.println("rule==>"+rul);
String[] rule = rul.split("\\+");
for(String s : rule) {
System.out.println(s);
if(s.startsWith(".")) {
System.out.println("startWish . "+s);
id.append(s);
}else if(s.startsWith("LSH")) {
String lsh = "%" + String.format("%02d", Integer.parseInt(s.substring(3))) + "d";
List<HashMap<String, Object>> results = SqlUtil.getDBInfo(conn, "select SERIALNUMBER from JD_CODE_RULE where CODEKEY='"+id+"'");
if (results.size() == 0) {
List<HashMap<String, Object>> resultsTi = SqlTIUtil.getDBInfo(connTI, "select ECMS_NEXTCODE from ECMS_SERIAL where ECMS_PRE='"+id+"'");
if(resultsTi.size()==0) {
SqlUtil.update("insert into JD_CODE_RULE values('" +id+ "',1)");
id.append(String.format(lsh, 1));
}else {
int no = (Integer) results.get(0).get("ECMS_NEXTCODE") + 1;
SqlUtil.update("update JD_CODE_RULE set SERIALNUMBER=" + no + " where CODEKEY='" +id+ "'");
id.append(String.format(lsh, no));
}
} else {
int no = (Integer) results.get(0).get("SERIALNUMBER") + 1;
SqlUtil.update("update JD_CODE_RULE set SERIALNUMBER=" + no + " where CODEKEY='" +id+ "'");
id.append(String.format(lsh, no));
}
}else if(s.startsWith("#rev.")) {
String prop = s.substring(5);
String value = rev.getStringProperty(prop);
if(value.isEmpty()) {
msg.append(rev).append(" 的部分物料编码相关属性为空,请检查\n");
break OPM;
}else if(prop.equals("j6_productseries")){
if(productClassMap.containsKey(value)) {
value = productClassMap.get(value);
}else {
msg.append("产品分类码 ").append(value).append(" 在首选项 Jd_Code_Product_Class 中未找到配置,请检查\n");
}
}
id.append(value);
}else if(s.startsWith("rev.")) {
System.out.println("rev==>"+s);
String prop = s.substring(4);
String value = "";
value = rev.getStringProperty(prop);
System.out.println(value);
if(s.contains("j6_topicno")) {
value = value.substring(0,3);
}
id.append(value);
}
else if(map.containsKey(s)) {
String value = impTable.getValueAt(i, map.get(s)).toString();
if(value.isEmpty()) {
msg.append(rev).append(" 的部分物料编码相关属性为空,请检查\n");
break OPM;
}
id.append(value);
}else if(s.contains(".")) {//.startsWith("J6_ASSOCIATED_REL.j6_drawingno")
String[] sp = s.split("\\.");
AIFComponentContext[] parent = rev.whereReferencedByTypeRelation(null, new String[] { sp[0] });
if(parent==null || parent.length==0) {
msg.append(rev).append(" 与零件未关联,请关联后再申请图号\n");
break OPM;
}
String p = parent[0].getComponent().getProperty(sp[1]);
if(p.isEmpty()) {
if(sp[1].equals("j6_drawingno")) {
msg.append(rev).append(" 上级图纸无物料编码,请先申请上级物料编码后再申请本物料编码\n");
break OPM;
}else {
msg.append(rev).append(" 上级对象属性为空,请检查\n");
break OPM;
}
}
id.append(p);
}else {
id.append(s);
}
}
if(!rul.contains("LSH")) {
List<HashMap<String, Object>> results = SqlUtil.getDBInfo(conn, "select SERIALNUMBER from JD_CODE_RULE where CODEKEY='"+id+"'");
if (results.size() == 0) {
SqlUtil.update("insert into JD_CODE_RULE values('" +id+ "',0)");
}else {
msg.append(rev).append(" 的物料编码 ").append(id).append(" 已存在,请检查相关属性值\n");
break;
}
}
String dno = id.toString();
rev.setProperty("j6_wlbm", dno);
if(map.containsKey("rev.j6_wlbm")) {
impTable.setValueAt(dno, i, map.get("rev.j6_wlbm"));
}
break;
}
if(norule) {
msg.append(rev).append(" 无满足条件的规则,无法申请物料编码 ");
}
norule = true;
}
if(msg.length()>0)
MessageBox.post(WlbmApplyDialog.this, "以下对象物料编码申请遇到问题,请检查:\n" + msg, "提示", MessageBox.WARNING);
else
MessageBox.post(WlbmApplyDialog.this, "物料编码申请完成!", "提示", MessageBox.INFORMATION);
} catch (Exception e1) {
e1.printStackTrace();
MessageBox.post(WlbmApplyDialog.this, "错误:" + e1.getMessage(), "ERROR", MessageBox.ERROR);
}finally {
SqlUtil.freeAll();
SqlTIUtil.freeAll();
}
}
});
closeBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
dispose();
}
});
}
}

@ -0,0 +1,97 @@
package com.connor.jingdiao.handlers;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import com.teamcenter.rac.aif.AIFDesktop;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;
public class WlbmApplyHandler extends AbstractHandler implements IHandler{
public Object execute(ExecutionEvent arg0) throws ExecutionException {
System.out.println("DrawingNoApplyHandler");
TCSession session = (TCSession) AIFUtility.getCurrentApplication().getSession();
AIFDesktop desktop = AIFUtility.getActiveDesktop();
try {
// TCComponent
String typeName = "";
List<String> typeList = new ArrayList<String>();
typeList.add("Part");
typeList.add("J6_PRODUCT");
typeList.add("J6_FUNCTIONASS");
typeList.add("J6_DQPart");
typeList.add("J6_WGPart");
typeList.add("J6_VMPART");
typeList.add("J6_GZPart");
InterfaceAIFComponent[] targets = AIFUtility.getCurrentApplication().getTargetComponents();
for(InterfaceAIFComponent t : targets) {
if(t instanceof TCComponentItemRevision) {
TCComponentItemRevision revision = (TCComponentItemRevision) t;
String type = revision.getItem().getType();
System.out.println("type==>"+type);
if(!typeList.contains(type)) {
MessageBox.post(desktop, "选中对象"+t+"不是物料版本类型,无法申请物料编码!", "ERROR", MessageBox.ERROR);
return null;
}
typeName = type;
}else if(t.getType().contains("J6_FUNCTIONASS")) {
typeName = "J6_FUNCTIONASS";
}
else {
MessageBox.post(desktop, "选中对象"+t+"不是物料版本类型,无法申请物料编码!", "ERROR", MessageBox.ERROR);
return null;
}
// if(!t.getType().equals("Design Revision")) {
// //判断是否为
// return null;
// }
}
String ruleNameString = "Jd_Code_Rule_"+typeName;
String tables[] = session.getPreferenceService().getStringValues("Jd_Code_Table_Design"); //表头配置
if(tables==null || tables.length==0) {
MessageBox.post(desktop, "首选项配置Jd_Code_Table_Design不正确", "ERROR", MessageBox.ERROR);
return null;
}
String options[] = session.getPreferenceService().getStringValues(ruleNameString); //编码规则配置
if(options == null || options.length == 0) {
MessageBox.post(desktop, "首选项"+ruleNameString+"配置不正确", "ERROR", MessageBox.ERROR);
return null;
}
String sqlOptions[] = session.getPreferenceService().getStringValues("Jd_TC_Info_Connect"); //tc数据库链接
if(sqlOptions==null || sqlOptions.length<4) {
MessageBox.post(desktop, "首选项Jd_TC_Info_Connect配置不正确", "ERROR", MessageBox.ERROR);
return null;
}
String sqlOptionsTI[] = session.getPreferenceService().getStringValues("Jd_TICODE_Info_Connect"); //TI数据库链接
if(sqlOptionsTI==null || sqlOptionsTI.length<4) {
MessageBox.post(desktop, "首选项Jd_TICODE_Info_Connect配置不正确", "ERROR", MessageBox.ERROR);
return null;
}
String productClass[] = session.getPreferenceService().getStringValues("Jd_Code_Product_Class"); //TI数据库链接
if(productClass==null || productClass.length==0) {
MessageBox.post(desktop, "首选项Jd_Code_Product_Class配置不正确", "ERROR", MessageBox.ERROR);
return null;
}
new WlbmApplyDialog(session, tables, options, sqlOptions, targets,sqlOptionsTI,productClass);
}catch(Exception e) {
e.printStackTrace();
MessageBox.post(desktop, "错误:"+e.getMessage(), "ERROR", MessageBox.ERROR);
return null;
}
return null;
}
}

@ -0,0 +1,687 @@
package com.connor.jingdiao.util;
import java.io.Reader;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
public class SqlTIUtil {
public static Connection connection = null;
public static PreparedStatement ps = null;
public static ResultSet rs = null;
// public static Registry reg = Registry.getRegistry(SqlUtil.class);
public static int ORACLE = 1;
public static int SQLSERVER = 2;
// public static Connection getConnection(int dbType) {
// if (dbType == ORACLE) {
// return getOracleConnection();
// } else if (dbType == SQLSERVER) {
// return getSqlserverConnection();
// }
// return null;
// }
public static Date getDate(java.sql.Date date) {
if (date == null) {
return null;
}
return new Date(date.getTime());
}
/**
*
public static Connection getSqlserverConnection() {
String driver = reg.getString("SQL.SQLSERVER.DRIVER");
String url = reg.getString("SQL.SQLSERVER.URL");
String user = reg.getString("SQL.SQLSERVER.USER");
String password = reg.getString("SQL.SQLSERVER.PASSWORD");
System.out.println("连接数据库信息:");
System.out.println("DRIVER: " + driver);
System.out.println("URL: " + url);
System.out.println("USER: " + user);
if (connection != null) {
try {
connection.close();
} catch (Exception e1) {
e1.printStackTrace();
}
connection = null;
}
try {
// 加载驱动程序
Class.forName(driver);
connection = DriverManager.getConnection(url, user, password);
connection.setAutoCommit(false);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}*/
public static Connection getSqlserverConnection(String driver, String url, String user, String password) {
// String driver = reg.getString("SQL.SQLSERVER.DRIVER");
// String url = reg.getString("SQL.SQLSERVER.URL");
// String user = reg.getString("SQL.SQLSERVER.USER");
// String password = reg.getString("SQL.SQLSERVER.PASSWORD");
System.out.println("连接数据库信息:");
// System.out.println("DRIVER: " + driver);
// System.out.println("URL: " + url);
// System.out.println("USER: " + user);
if (connection != null) {
try {
connection.close();
} catch (Exception e1) {
e1.printStackTrace();
}
connection = null;
}
try {
// 加载驱动程序
Class.forName(driver);
connection = DriverManager.getConnection(url, user, password);
connection.setAutoCommit(false);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
public static Connection getOracleConnection(String url, String user, String password) {
String driver = "oracle.jdbc.driver.OracleDriver";
System.out.println("连接数据库信息:");
System.out.println("DRIVER: " + driver);
System.out.println("URL: " + url);
System.out.println("USER: " + user);
if (connection != null) {
try {
connection.close();
} catch (Exception e1) {
e1.printStackTrace();
}
connection = null;
}
try {
// 加载驱动程序
Class.forName(driver);
// 1.getConnection()方法连接MySQL数据库
connection = DriverManager.getConnection(url, user, password);
connection.setAutoCommit(false);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
/*
public static Connection getOracleConnection() {
// String driver = reg.getString("SQL.ORACLE.DRIVER");
String url = reg.getString("SQL.ORACLE.URL");
String user = reg.getString("SQL.ORACLE.USER");
String password = reg.getString("SQL.ORACLE.PASSWORD");
// if(prefs!=null&&prefs.length==5) {
// url = "jdbc:oracle:thin:@"+prefs[0]+":"+prefs[1]+":"+prefs[2];
// user = prefs[3];
// password = prefs[4];
// }
return getOracleConnection(url, user, password);
}*/
/**
* new
*/
private SqlTIUtil() {
}
/**
* SELECT
*
* @param tableName
* @param selectElement
* @param args
* @return
*/
public static String getSelectSql(String tableName, String[] selectElement, String... args) {
StringBuffer valuesSB = new StringBuffer("SELECT ");
if (selectElement != null) {
for (String element : selectElement) {
valuesSB.append(element).append(",");
}
valuesSB.delete(valuesSB.length() - 1, valuesSB.length());
}
valuesSB.append(" FROM ");
valuesSB.append(tableName);
valuesSB.append(" WHERE");
for (int i = 0; i < args.length; i++) {
valuesSB.append(" ");
valuesSB.append(args[i]);
valuesSB.append("=? ");
valuesSB.append("AND");
}
valuesSB.delete(valuesSB.length() - 3, valuesSB.length());
return valuesSB.toString();
}
/**
* SELECT
*
* @param tableName
* @param args
* @return
*/
public static String getSelectSql(String tableName, String... args) {
StringBuffer valuesSB = new StringBuffer("SELECT * FROM ");
valuesSB.append(tableName);
valuesSB.append(" WHERE");
for (int i = 0; i < args.length; i++) {
valuesSB.append(" ");
valuesSB.append(args[i]);
valuesSB.append("=? ");
valuesSB.append("AND");
}
valuesSB.delete(valuesSB.length() - 3, valuesSB.length());
return valuesSB.toString();
}
/**
*
*
* @param tableName
* @param args
* @param args2
* @return
*/
public static String getUpdataSQL(String tableName, String[] args, String[] args2) {
StringBuffer updateSB = new StringBuffer("UPDATE ");
updateSB.append(tableName);
updateSB.append(" SET ");
// 拼接更新语句
for (int i = 0; i < args.length; i++) {
if (args[i].toUpperCase().equals("CREATED_DATE") || args[i].toUpperCase().equals("LAST_UPDATE_DATE")) {
updateSB.append(args[i]).append("=to_date(?,'yyyy-MM-dd HH24:mi:ss') ,");
} else {
updateSB.append(args[i]).append("=? ,");
}
}
updateSB.delete(updateSB.length() - 2, updateSB.length());
;
updateSB.append(" WHERE ");
for (int i = 0; i < args2.length; i++) {
updateSB.append(args2[i]).append("=? AND ");
}
updateSB.delete(updateSB.length() - 4, updateSB.length());
return updateSB.toString();
}
/**
* SQLinsert
*
* @param tableName
* @param args
* @return
*/
public static String getInsertSql(String tableName, String... args) {
StringBuffer insertSql = new StringBuffer("insert into ");
StringBuffer values = new StringBuffer("values(");
if (tableName != null && args != null && args.length > 0) {
insertSql.append(tableName);
insertSql.append("(");
for (int i = 0; i < args.length; i++) {
insertSql.append(args[i]);
insertSql.append(", ");
if (args[i].toUpperCase().equals("LAST_UPDATE_DATE") || args[i].toUpperCase().equals("CREATED_DATE")) {
values.append("to_date(?,'yyyy-MM-dd HH24:mi:ss'), ");
} else {
values.append("?, ");
}
}
} else {
return null;
}
insertSql.delete(insertSql.length() - 2, insertSql.length());
values.delete(values.length() - 2, values.length());
insertSql.append(") ").append(values).append(")");
return insertSql.toString();
}
/**
*
*
* @param tableName
* @param args
*
* @param args2
*
* @return
*/
public final static String GetCreateTableSQL(String tableName, String[] args, String[] args2) {
if (args == null || args2 == null || args.length != args2.length) {
System.out.println("THE INPUT PRAGREMS IS ERROR");
return null;
}
StringBuffer createSQL = new StringBuffer("create table ");
createSQL.append(tableName);
createSQL.append("(");
for (int i = 0; i < args.length; i++) {
createSQL.append(args[i] + " ");
createSQL.append(args2[i] + ", ");
}
createSQL.delete(createSQL.length() - 2, createSQL.length());
createSQL.append(")");
return createSQL.toString();
}
/**
* Statement
*/
public final static PreparedStatement getPs(String sql) throws Exception {
return getPs(sql, null);
}
/**
* Statement
*/
public final static PreparedStatement getPs(Object[] argments, String sql) throws Exception {
return getPs(sql, argments);
}
/**
* Statement
*/
public final static PreparedStatement getPs(String sql, Object[] argments) throws Exception {
SqlUtil.ps = SqlUtil.connection.prepareStatement(sql);
if (argments != null) {
for (int i = 0; i < argments.length; i++) {
SqlUtil.ps.setObject(i + 1, argments[i]);
}
}
return SqlUtil.ps;
}
/**
*
*/
public final static int write(String sql) {
return write(sql, null);
}
/**
*
*/
public final static int write(Object[] argments, String sql) {
return write(sql, argments);
}
/**
*
*/
public final static int write(String sql, Object[] argments) {
return update(sql, argments);
}
/**
*
*/
public final static int delete(String sql) {
return delete(sql, null);
}
/**
*
*/
public final static int delete(Object[] argments, String sql) {
return delete(sql, argments);
}
/**
*
*/
public final static int delete(String sql, Object[] argments) {
return update(sql, argments);
}
/**
*
*/
public final static int update(String sql) {
return update(sql, null);
}
/**
*
*/
public final static int update(String[] argments, String sql) {
return update(sql, argments);
}
/**
* (Connection)
*/
public final static int update(String sql, Object[] argments) {
int i = -1;
try {
i = SqlUtil.getPs(argments, sql).executeUpdate();
SqlUtil.connection.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
free(SqlUtil.rs, SqlUtil.ps);
}
return i;
}
/**
*
*/
public final static ResultSet read(String sql) throws Exception {
return read(sql, null);
}
/**
*
*/
public final static ResultSet read(Object[] argments, String sql) throws Exception {
return read(sql, argments);
}
/**
* (便finally)
*
* @throws SQLException
*/
public final static ResultSet read(String sql, Object[] argments) throws Exception {
System.out.println("argments=" + argments.length);
return SqlUtil.rs = SqlUtil.getPs(argments, sql).executeQuery();
}
/**
*
*/
public final static boolean createTable(String sql) {
return go(sql, null);
}
/**
*
*/
public final static boolean dropTable(String sql) {
return go(sql, null);
}
/**
*
*/
public final static boolean alterTable(String sql) {
return go(sql, null);
}
/**
* DDL(,,)
*/
private final static boolean go(String sql, Object[] argments) {
boolean flag = false;
try {
flag = SqlUtil.getPs(sql, argments).execute();
} catch (Exception e) {
e.printStackTrace();
} finally {
free(SqlUtil.rs, SqlUtil.ps);
}
if (flag) {
try {
SqlUtil.connection.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
return flag;
}
/**
*
*/
public final static void free(ResultSet resultSet) {
free(resultSet, null, null);
}
/**
*
*/
public final static void free(Statement statement) {
free(null, statement, null);
}
/**
*
*/
public final static void free(Connection connection) {
free(null, null, connection);
}
/**
*
*/
public final static void free(ResultSet resultSet, Statement statement) {
free(resultSet, statement, null);
}
/**
*
*/
public final static void free(Statement statement, Connection connection) {
free(null, statement, connection);
}
/**
* ()
*/
public final static void free() {
free(SqlUtil.rs, SqlUtil.ps);
}
/**
* ()
*/
public final static void freeAll() {
free(SqlUtil.rs, SqlUtil.ps, SqlUtil.connection);
}
/**
* ()
*/
public final static void free(ResultSet resultSet, Statement statement, Connection connection) {
try {
if (resultSet != null) {
try {
resultSet.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} finally {
try {
if (statement != null) {
try {
statement.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} finally {
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public static List<HashMap<String, Object>> getDBInfo(Connection connection, String sql) throws Exception {
if (connection == null) {
throw new Exception("无法获取数据库连接信息");
}
List<HashMap<String, Object>> vecData = new ArrayList<HashMap<String, Object>>();
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
ResultSetMetaData meta = rs.getMetaData();
System.out.println("meta"+meta.getColumnCount());
String[] columnNames = new String[meta.getColumnCount()];
int[] columnTypes = new int[meta.getColumnCount()];
for (int i = 0; i < columnNames.length; i++) {
columnNames[i] = meta.getColumnName(i + 1);
columnTypes[i] = meta.getColumnType(i + 1);
System.out.println("columnTypes"+i+"=="+columnNames[i]);
}
while (rs.next()) {
HashMap<String, Object> dataTable = new HashMap<String, Object>();
for (int i = 1; i <= columnNames.length; i++) {
Object value = null;
switch (columnTypes[i-1]) {
case Types.NVARCHAR:
case Types.VARCHAR:
value = rs.getString(i);//columnNames[i]
if (value == null) {
value = "";
}
break;
case Types.INTEGER:
case Types.NUMERIC:
value = rs.getInt(i);
break;
case Types.DATE:
Timestamp timestamp = rs.getTimestamp(i);
if (timestamp != null) {
value = new Date(timestamp.getTime());
}
break;
case Types.TIMESTAMP:
value = rs.getTimestamp(i);
break;
case Types.CLOB:
Clob clob = rs.getClob(i);
if (clob != null) {
Reader inStream = clob.getCharacterStream();
char[] c = new char[(int) clob.length()];
inStream.read(c);
value = new String(c);
inStream.close();
}
if (value == null) {
value = "";
}
break;
default:
value = "";
break;
}
// if (value == null) {
// value = "";
// }
dataTable.put(columnNames[i-1], value);
// System.out.println("data"+columnNames[i]+"=="+columnTypes[i]);
}
vecData.add(dataTable);
}
rs.close();
statement.close();
return vecData;
}
public static List<Object[]> getArrayDBInfo(Connection connection, String sql) throws Exception {
if (connection == null) {
throw new Exception("无法获取数据库连接信息");
}
List<Object[]> vecData = new LinkedList<Object[]>();
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
ResultSetMetaData meta = rs.getMetaData();
String[] columnNames = new String[meta.getColumnCount()];
int[] columnTypes = new int[meta.getColumnCount()];
for (int i = 0; i < columnNames.length; i++) {
columnNames[i] = meta.getColumnName(i + 1);
columnTypes[i] = meta.getColumnType(i + 1);
}
while (rs.next()) {
Object[] result = new Object[columnNames.length];
for (int i = 0; i < columnNames.length; i++) {
Object value = null;
switch (columnTypes[i]) {
case Types.VARCHAR:
value = rs.getString(columnNames[i]);
if (value == null) {
value = "";
}
break;
case Types.INTEGER:
case Types.NUMERIC:
value = rs.getInt(columnNames[i]);
break;
case Types.DATE:
Timestamp timestamp = rs.getTimestamp(columnNames[i]);
if (timestamp != null) {
value = new Date(timestamp.getTime());
}
break;
case Types.TIMESTAMP:
value = rs.getTimestamp(columnNames[i]);
break;
case Types.CLOB:
Clob clob = rs.getClob(columnNames[i]);
if (clob != null) {
Reader inStream = clob.getCharacterStream();
char[] c = new char[(int) clob.length()];
inStream.read(c);
value = new String(c);
inStream.close();
}
if (value == null) {
value = "";
}
break;
default:
value = "";
break;
}
// if (value == null) {
// value = "";
// }
// dataTable.put(columnNames[i], value);
// System.out.println("data"+columnNames[i]+"=="+columnTypes[i]);
result[i] = value;
}
vecData.add(result);
}
rs.close();
statement.close();
return vecData;
}
}

@ -0,0 +1,688 @@
package com.connor.jingdiao.util;
import java.io.Reader;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
public class SqlUtil {
public static Connection connection = null;
public static PreparedStatement ps = null;
public static ResultSet rs = null;
// public static Registry reg = Registry.getRegistry(SqlUtil.class);
public static int ORACLE = 1;
public static int SQLSERVER = 2;
// public static Connection getConnection(int dbType) {
// if (dbType == ORACLE) {
// return getOracleConnection();
// } else if (dbType == SQLSERVER) {
// return getSqlserverConnection();
// }
// return null;
// }
public static Date getDate(java.sql.Date date) {
if (date == null) {
return null;
}
return new Date(date.getTime());
}
/**
*
public static Connection getSqlserverConnection() {
String driver = reg.getString("SQL.SQLSERVER.DRIVER");
String url = reg.getString("SQL.SQLSERVER.URL");
String user = reg.getString("SQL.SQLSERVER.USER");
String password = reg.getString("SQL.SQLSERVER.PASSWORD");
System.out.println("连接数据库信息:");
System.out.println("DRIVER: " + driver);
System.out.println("URL: " + url);
System.out.println("USER: " + user);
if (connection != null) {
try {
connection.close();
} catch (Exception e1) {
e1.printStackTrace();
}
connection = null;
}
try {
// 加载驱动程序
Class.forName(driver);
connection = DriverManager.getConnection(url, user, password);
connection.setAutoCommit(false);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}*/
public static Connection getSqlserverConnection(String driver, String url, String user, String password) {
// String driver = reg.getString("SQL.SQLSERVER.DRIVER");
// String url = reg.getString("SQL.SQLSERVER.URL");
// String user = reg.getString("SQL.SQLSERVER.USER");
// String password = reg.getString("SQL.SQLSERVER.PASSWORD");
System.out.println("连接数据库信息:");
// System.out.println("DRIVER: " + driver);
// System.out.println("URL: " + url);
// System.out.println("USER: " + user);
if (connection != null) {
try {
connection.close();
} catch (Exception e1) {
e1.printStackTrace();
}
connection = null;
}
try {
// 加载驱动程序
Class.forName(driver);
connection = DriverManager.getConnection(url, user, password);
connection.setAutoCommit(false);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
public static Connection getOracleConnection(String url, String user, String password) {
String driver = "oracle.jdbc.driver.OracleDriver";
System.out.println("连接数据库信息:");
System.out.println("DRIVER: " + driver);
System.out.println("URL: " + url);
System.out.println("USER: " + user);
if (connection != null) {
try {
connection.close();
} catch (Exception e1) {
e1.printStackTrace();
}
connection = null;
}
try {
// 加载驱动程序
Class.forName(driver);
// 1.getConnection()方法连接MySQL数据库
connection = DriverManager.getConnection(url, user, password);
connection.setAutoCommit(false);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
/*
public static Connection getOracleConnection() {
// String driver = reg.getString("SQL.ORACLE.DRIVER");
String url = reg.getString("SQL.ORACLE.URL");
String user = reg.getString("SQL.ORACLE.USER");
String password = reg.getString("SQL.ORACLE.PASSWORD");
// if(prefs!=null&&prefs.length==5) {
// url = "jdbc:oracle:thin:@"+prefs[0]+":"+prefs[1]+":"+prefs[2];
// user = prefs[3];
// password = prefs[4];
// }
return getOracleConnection(url, user, password);
}*/
/**
* new
*/
private SqlUtil() {
}
/**
* SELECT
*
* @param tableName
* @param selectElement
* @param args
* @return
*/
public static String getSelectSql(String tableName, String[] selectElement, String... args) {
StringBuffer valuesSB = new StringBuffer("SELECT ");
if (selectElement != null) {
for (String element : selectElement) {
valuesSB.append(element).append(",");
}
valuesSB.delete(valuesSB.length() - 1, valuesSB.length());
}
valuesSB.append(" FROM ");
valuesSB.append(tableName);
valuesSB.append(" WHERE");
for (int i = 0; i < args.length; i++) {
valuesSB.append(" ");
valuesSB.append(args[i]);
valuesSB.append("=? ");
valuesSB.append("AND");
}
valuesSB.delete(valuesSB.length() - 3, valuesSB.length());
return valuesSB.toString();
}
/**
* SELECT
*
* @param tableName
* @param args
* @return
*/
public static String getSelectSql(String tableName, String... args) {
StringBuffer valuesSB = new StringBuffer("SELECT * FROM ");
valuesSB.append(tableName);
valuesSB.append(" WHERE");
for (int i = 0; i < args.length; i++) {
valuesSB.append(" ");
valuesSB.append(args[i]);
valuesSB.append("=? ");
valuesSB.append("AND");
}
valuesSB.delete(valuesSB.length() - 3, valuesSB.length());
return valuesSB.toString();
}
/**
*
*
* @param tableName
* @param args
* @param args2
* @return
*/
public static String getUpdataSQL(String tableName, String[] args, String[] args2) {
StringBuffer updateSB = new StringBuffer("UPDATE ");
updateSB.append(tableName);
updateSB.append(" SET ");
// 拼接更新语句
for (int i = 0; i < args.length; i++) {
if (args[i].toUpperCase().equals("CREATED_DATE") || args[i].toUpperCase().equals("LAST_UPDATE_DATE")) {
updateSB.append(args[i]).append("=to_date(?,'yyyy-MM-dd HH24:mi:ss') ,");
} else {
updateSB.append(args[i]).append("=? ,");
}
}
updateSB.delete(updateSB.length() - 2, updateSB.length());
;
updateSB.append(" WHERE ");
for (int i = 0; i < args2.length; i++) {
updateSB.append(args2[i]).append("=? AND ");
}
updateSB.delete(updateSB.length() - 4, updateSB.length());
return updateSB.toString();
}
/**
* SQLinsert
*
* @param tableName
* @param args
* @return
*/
public static String getInsertSql(String tableName, String... args) {
StringBuffer insertSql = new StringBuffer("insert into ");
StringBuffer values = new StringBuffer("values(");
if (tableName != null && args != null && args.length > 0) {
insertSql.append(tableName);
insertSql.append("(");
for (int i = 0; i < args.length; i++) {
insertSql.append(args[i]);
insertSql.append(", ");
if (args[i].toUpperCase().equals("LAST_UPDATE_DATE") || args[i].toUpperCase().equals("CREATED_DATE")) {
values.append("to_date(?,'yyyy-MM-dd HH24:mi:ss'), ");
} else {
values.append("?, ");
}
}
} else {
return null;
}
insertSql.delete(insertSql.length() - 2, insertSql.length());
values.delete(values.length() - 2, values.length());
insertSql.append(") ").append(values).append(")");
return insertSql.toString();
}
/**
*
*
* @param tableName
* @param args
*
* @param args2
*
* @return
*/
public final static String GetCreateTableSQL(String tableName, String[] args, String[] args2) {
if (args == null || args2 == null || args.length != args2.length) {
System.out.println("THE INPUT PRAGREMS IS ERROR");
return null;
}
StringBuffer createSQL = new StringBuffer("create table ");
createSQL.append(tableName);
createSQL.append("(");
for (int i = 0; i < args.length; i++) {
createSQL.append(args[i] + " ");
createSQL.append(args2[i] + ", ");
}
createSQL.delete(createSQL.length() - 2, createSQL.length());
createSQL.append(")");
return createSQL.toString();
}
/**
* Statement
*/
public final static PreparedStatement getPs(String sql) throws Exception {
return getPs(sql, null);
}
/**
* Statement
*/
public final static PreparedStatement getPs(Object[] argments, String sql) throws Exception {
return getPs(sql, argments);
}
/**
* Statement
*/
public final static PreparedStatement getPs(String sql, Object[] argments) throws Exception {
SqlUtil.ps = SqlUtil.connection.prepareStatement(sql);
if (argments != null) {
for (int i = 0; i < argments.length; i++) {
SqlUtil.ps.setObject(i + 1, argments[i]);
}
}
return SqlUtil.ps;
}
/**
*
*/
public final static int write(String sql) {
return write(sql, null);
}
/**
*
*/
public final static int write(Object[] argments, String sql) {
return write(sql, argments);
}
/**
*
*/
public final static int write(String sql, Object[] argments) {
return update(sql, argments);
}
/**
*
*/
public final static int delete(String sql) {
return delete(sql, null);
}
/**
*
*/
public final static int delete(Object[] argments, String sql) {
return delete(sql, argments);
}
/**
*
*/
public final static int delete(String sql, Object[] argments) {
return update(sql, argments);
}
/**
*
*/
public final static int update(String sql) {
return update(sql, null);
}
/**
*
*/
public final static int update(String[] argments, String sql) {
return update(sql, argments);
}
/**
* (Connection)
*/
public final static int update(String sql, Object[] argments) {
int i = -1;
try {
i = SqlUtil.getPs(argments, sql).executeUpdate();
SqlUtil.connection.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
free(SqlUtil.rs, SqlUtil.ps);
}
return i;
}
/**
*
*/
public final static ResultSet read(String sql) throws Exception {
return read(sql, null);
}
/**
*
*/
public final static ResultSet read(Object[] argments, String sql) throws Exception {
return read(sql, argments);
}
/**
* (便finally)
*
* @throws SQLException
*/
public final static ResultSet read(String sql, Object[] argments) throws Exception {
System.out.println("argments=" + argments.length);
return SqlUtil.rs = SqlUtil.getPs(argments, sql).executeQuery();
}
/**
*
*/
public final static boolean createTable(String sql) {
return go(sql, null);
}
/**
*
*/
public final static boolean dropTable(String sql) {
return go(sql, null);
}
/**
*
*/
public final static boolean alterTable(String sql) {
return go(sql, null);
}
/**
* DDL(,,)
*/
private final static boolean go(String sql, Object[] argments) {
boolean flag = false;
try {
flag = SqlUtil.getPs(sql, argments).execute();
} catch (Exception e) {
e.printStackTrace();
} finally {
free(SqlUtil.rs, SqlUtil.ps);
}
if (flag) {
try {
SqlUtil.connection.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
return flag;
}
/**
*
*/
public final static void free(ResultSet resultSet) {
free(resultSet, null, null);
}
/**
*
*/
public final static void free(Statement statement) {
free(null, statement, null);
}
/**
*
*/
public final static void free(Connection connection) {
free(null, null, connection);
}
/**
*
*/
public final static void free(ResultSet resultSet, Statement statement) {
free(resultSet, statement, null);
}
/**
*
*/
public final static void free(Statement statement, Connection connection) {
free(null, statement, connection);
}
/**
* ()
*/
public final static void free() {
free(SqlUtil.rs, SqlUtil.ps);
}
/**
* ()
*/
public final static void freeAll() {
free(SqlUtil.rs, SqlUtil.ps, SqlUtil.connection);
}
/**
* ()
*/
public final static void free(ResultSet resultSet, Statement statement, Connection connection) {
try {
if (resultSet != null) {
try {
resultSet.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} finally {
try {
if (statement != null) {
try {
statement.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} finally {
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public static ArrayList<HashMap<String, Object>> getDBInfo(Connection connection, String sql) throws Exception {
if (connection == null) {
throw new Exception("无法获取数据库连接信息");
}
ArrayList<HashMap<String, Object>> vecData = new ArrayList<HashMap<String, Object>>();
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
ResultSetMetaData meta = rs.getMetaData();
System.out.println("meta"+meta.getColumnCount());
String[] columnNames = new String[meta.getColumnCount()];
int[] columnTypes = new int[meta.getColumnCount()];
for (int i = 0; i < columnNames.length; i++) {
columnNames[i] = meta.getColumnName(i + 1);
columnTypes[i] = meta.getColumnType(i + 1);
System.out.println("columnTypes"+i+"=="+columnNames[i]);
}
while (rs.next()) {
HashMap<String, Object> dataTable = new HashMap<String, Object>();
for (int i = 1; i <= columnNames.length; i++) {
Object value = null;
switch (columnTypes[i-1]) {
case Types.NVARCHAR:
case Types.VARCHAR:
value = rs.getString(i);//columnNames[i]
if (value == null) {
value = "";
}
break;
case Types.INTEGER:
case Types.NUMERIC:
value = rs.getInt(i);
break;
case Types.DATE:
Timestamp timestamp = rs.getTimestamp(i);
if (timestamp != null) {
value = new Date(timestamp.getTime());
}
break;
case Types.TIMESTAMP:
value = rs.getTimestamp(i);
break;
case Types.CLOB:
Clob clob = rs.getClob(i);
if (clob != null) {
Reader inStream = clob.getCharacterStream();
char[] c = new char[(int) clob.length()];
inStream.read(c);
value = new String(c);
inStream.close();
}
if (value == null) {
value = "";
}
break;
default:
value = "";
break;
}
// if (value == null) {
// value = "";
// }
dataTable.put(columnNames[i-1], value);
// System.out.println("data"+columnNames[i]+"=="+columnTypes[i]);
}
vecData.add(dataTable);
}
rs.close();
statement.close();
return vecData;
}
public static List<Object[]> getArrayDBInfo(Connection connection, String sql) throws Exception {
if (connection == null) {
throw new Exception("无法获取数据库连接信息");
}
List<Object[]> vecData = new LinkedList<Object[]>();
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
ResultSetMetaData meta = rs.getMetaData();
String[] columnNames = new String[meta.getColumnCount()];
int[] columnTypes = new int[meta.getColumnCount()];
for (int i = 0; i < columnNames.length; i++) {
columnNames[i] = meta.getColumnName(i + 1);
columnTypes[i] = meta.getColumnType(i + 1);
}
while (rs.next()) {
Object[] result = new Object[columnNames.length];
for (int i = 0; i < columnNames.length; i++) {
Object value = null;
switch (columnTypes[i]) {
case Types.VARCHAR:
value = rs.getString(columnNames[i]);
if (value == null) {
value = "";
}
break;
case Types.INTEGER:
case Types.NUMERIC:
value = rs.getInt(columnNames[i]);
break;
case Types.DATE:
Timestamp timestamp = rs.getTimestamp(columnNames[i]);
if (timestamp != null) {
value = new Date(timestamp.getTime());
}
break;
case Types.TIMESTAMP:
value = rs.getTimestamp(columnNames[i]);
break;
case Types.CLOB:
Clob clob = rs.getClob(columnNames[i]);
if (clob != null) {
Reader inStream = clob.getCharacterStream();
char[] c = new char[(int) clob.length()];
inStream.read(c);
value = new String(c);
inStream.close();
}
if (value == null) {
value = "";
}
break;
default:
value = "";
break;
}
// if (value == null) {
// value = "";
// }
// dataTable.put(columnNames[i], value);
// System.out.println("data"+columnNames[i]+"=="+columnTypes[i]);
result[i] = value;
}
vecData.add(result);
}
rs.close();
statement.close();
return vecData;
}
}

@ -0,0 +1,349 @@
package com.connor.jingdiao.util;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.Window;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Vector;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JTable;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
import com.teamcenter.rac.aif.AbstractAIFDialog;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.commands.open.OpenFormDialog;
import com.teamcenter.rac.kernel.ListOfValuesInfo;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentBOMLine;
import com.teamcenter.rac.kernel.TCComponentBOMWindow;
import com.teamcenter.rac.kernel.TCComponentBOMWindowType;
import com.teamcenter.rac.kernel.TCComponentContextList;
import com.teamcenter.rac.kernel.TCComponentDataset;
import com.teamcenter.rac.kernel.TCComponentDatasetType;
import com.teamcenter.rac.kernel.TCComponentForm;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentListOfValues;
import com.teamcenter.rac.kernel.TCComponentListOfValuesType;
import com.teamcenter.rac.kernel.TCComponentPseudoFolder;
import com.teamcenter.rac.kernel.TCComponentQuery;
import com.teamcenter.rac.kernel.TCComponentQueryType;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCQueryClause;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;
public class TCUtil {
public static final int MINWIDTH = 1280;
public static final int MINHEIGHT = 768;
public static void fitToScreen(AbstractAIFDialog abstractAIFDialog) {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double screenWidth = screenSize.getWidth();
double screenHeight = screenSize.getHeight();
Dimension dialogSize = abstractAIFDialog.getSize();
if (screenWidth < MINWIDTH && dialogSize.getWidth() > screenWidth) {
abstractAIFDialog.setSize(new Dimension((int) Math.floor(screenWidth - 20), (int) Math.floor(dialogSize.getHeight())));
abstractAIFDialog.setLocation(10, (int) Math.floor(abstractAIFDialog.getLocation().getY()));
}
if (screenHeight < MINHEIGHT && dialogSize.getHeight() > screenHeight) {
abstractAIFDialog.setSize(new Dimension((int) Math.floor(dialogSize.getWidth()), (int) Math.floor(screenHeight - 20)));
abstractAIFDialog.setLocation((int) Math.floor(abstractAIFDialog.getLocation().getX()), 10);
}
/*
* if((screenWidth<MINWIDTH||screenHeight<MINHEIGHT)&&(dialogSize.getWidth()>
* MINWIDTH||dialogSize.getHeight()>MINHEIGHT)) { abstractAIFDialog.setSize(new
* Dimension((int)Math.floor(screenWidth-20),(int)Math.floor(screenHeight-20)));
* abstractAIFDialog.setLocation(10, 10); }
*/
}
public static void fitToScreen(OpenFormDialog openFormDialog) {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double screenWidth = screenSize.getWidth();
double screenHeight = screenSize.getHeight();
Dimension dialogSize = openFormDialog.getSize();
if (screenWidth < MINWIDTH && dialogSize.getWidth() > screenWidth) {
openFormDialog.setSize(new Dimension((int) Math.floor(screenWidth - 20), (int) Math.floor(dialogSize.getHeight())));
openFormDialog.setLocation(10, (int) Math.floor(openFormDialog.getLocation().getY()));
}
if (screenHeight < MINHEIGHT && dialogSize.getHeight() > screenHeight) {
openFormDialog.setSize(new Dimension((int) Math.floor(dialogSize.getWidth()), (int) Math.floor(screenHeight - 20)));
openFormDialog.setLocation((int) Math.floor(openFormDialog.getLocation().getX()), 10);
}
/*
* if((screenWidth<MINWIDTH||screenHeight<MINHEIGHT)&&(dialogSize.getWidth()>
* MINWIDTH||dialogSize.getHeight()>MINHEIGHT)) { openFormDialog.setSize(new
* Dimension((int)Math.floor(screenWidth-20),(int)Math.floor(screenHeight-20)));
* openFormDialog.setLocation(10, 10); }
*/
}
public static TCComponentBOMWindow getWindow(TCSession session) throws Exception{
TCComponentBOMWindow window = null;
TCComponentBOMWindowType bomWinType = (TCComponentBOMWindowType) session.getTypeComponent("BOMWindow");
window = bomWinType.create(null);
return window;
}
@SuppressWarnings("deprecation")
public static TCComponentBOMLine getBOMLine(TCSession session,TCComponentBOMWindow window, TCComponentItemRevision revision)
throws Exception {
window.lock();
TCComponentBOMLine bomLine = window.setWindowTopLine(null, revision, null, null);
window.save();
window.unlock();
return bomLine;
}
public static TCComponentPseudoFolder getPseudoFolder(TCComponent parent, String relation)
throws Exception {
TCComponentPseudoFolder pseudoFolder = null;
AIFComponentContext[] comps = parent.getChildren();
if (comps != null && comps.length > 0 && comps[0] != null) {
for (int i = 0; i < comps.length; i++) {
TCComponent comp = (TCComponent) comps[i].getComponent();
if (comp instanceof TCComponentPseudoFolder) {
if (comp.isTypeOf("PseudoFolder")) {
// System.out.println("PseudoFolder type:" + comp.getDefaultPasteRelation());
if (comp.getDefaultPasteRelation().equalsIgnoreCase(relation)) {
pseudoFolder = (TCComponentPseudoFolder) comp;
break;
}
}
}
}
}
return pseudoFolder;
}
public static TCComponentForm getItemRevisionMasterForm(TCComponentItemRevision revision) throws Exception {
if (revision != null) {
AIFComponentContext[] contexts = revision.getChildren("IMAN_master_form_rev");
if (contexts != null && contexts.length > 0) {
InterfaceAIFComponent component = contexts[0].getComponent();
if (component instanceof TCComponentForm) {
return (TCComponentForm) component;
}
}
}
return null;
}
public static LinkedHashMap<String, String> getlovValues(TCSession session, String lovName) throws TCException {
LinkedHashMap<String, String> lovVal = new LinkedHashMap<String, String>();
TCComponentListOfValuesType lovType = (TCComponentListOfValuesType) session.getTypeComponent("ListOfValues");
TCComponentListOfValues[] lovs = lovType.find(lovName);
if (lovs != null && lovs.length > 0) {
TCComponentListOfValues lov = lovs[0];
ListOfValuesInfo lovInfo = lov.getListOfValues();
String[] code = lovInfo.getStringListOfValues();
String[] name = lovInfo.getLOVDisplayValues();
if (code != null && name != null) {
for (int i = 0; i < code.length; i++) {
// System.out.printf("code[%d]=%s name[%d]=%s \n", i, code[i], i, name[i]);
lovVal.put(code[i], name[i]);
}
}
return lovVal;
}
return null;
}
public static String getTableValue(JTable table, int row, int col){
Object val = table.getValueAt(row, col);
if(val==null)
return "";
else
return val.toString();
}
public static TCComponent[] query(TCSession session, String queryName, String[] aKey, String[] aVal) throws Exception {
TCComponentQueryType imanQueryType = (TCComponentQueryType) session.getTypeComponent("ImanQuery");
TCComponentQuery imancomponentquery = (TCComponentQuery) imanQueryType.find(queryName);
if (imancomponentquery == null) {
throw new Exception("未找到查询构建器 " + queryName + "!");
}
aKey = session.getTextService().getTextValues(aKey);
// for (int i = 0; i < aKey.length; i++) {
// System.out.println(aKey[i] + "===============" + aVal[i]);
// }
TCComponentContextList componentContextList = imancomponentquery.getExecuteResultsList(aKey, aVal);
return componentContextList.toTCComponentArray();
}
public static TCComponent[] query(TCSession session, String queryName, Vector<String> Keys, Vector<String> Vals) throws Exception {
TCComponentQueryType imanQueryType = (TCComponentQueryType) session.getTypeComponent("ImanQuery");
TCComponentQuery imancomponentquery = (TCComponentQuery) imanQueryType.find(queryName);
if (imancomponentquery == null) {
System.out.println("未找到查询构建器" + queryName);
throw new Exception("Query:"+queryName+" cannot find");
}
TCQueryClause[] qc = imancomponentquery.describe();
// Map<String, String> clauseMap = new HashMap<>();
for(TCQueryClause c : qc) {
String key = c.getUserEntryNameDisplay();
String value = c.getDefaultValue();
// System.out.println(key + "==>" + c.getAttributeName());
if(!value.trim().isEmpty() && !Keys.contains(key)) {
if(key.isEmpty())
Keys.add(c.getAttributeName());
else
Keys.add(key);
Vals.add(value);
}
}
int size = Keys.size();
String[] keyA = new String[size];
String[] valueA = new String[size];
for(int i=0; i<size; i++) {
keyA[i] = Keys.get(i);
valueA[i] = Vals.get(i);
System.out.println(keyA[i] + ":" + valueA[i]);
}
TCComponentContextList componentContextList = imancomponentquery.getExecuteResultsList(keyA, valueA);
return componentContextList.toTCComponentArray();
}
public static String getSerialNo(TCSession session, String itemId, String objectType) throws Exception {
TCComponent[] comps = null;
if (objectType.equals("")) {
comps = query(session, "零组件 ID", new String[] { "ItemID" }, new String[] { itemId + "*" });
} else {
comps = query(session, "零组件...", new String[] { "ItemID", "Type" }, new String[] { itemId + "*", objectType });
}
// System.out.println("getSerialNo comps.len:" + (comps == null ? 0 : comps.length));
if (comps.length > 0) {
Integer maxId = 0;
for (TCComponent comp : comps) {
String pid = comp.getProperty("item_id");
System.out.println("pid:" + pid);
String pidSuffix = pid.substring(pid.length() - 3);
if (Integer.parseInt(pidSuffix) > maxId) {
maxId = Integer.parseInt(pidSuffix);
}
}
return String.format("%03d", maxId + 1);
}
return "001";
}
public static File saveExcelChooser() {
File dir = null;
JFileChooser chooser = new JFileChooser();
chooser.setAcceptAllFileFilterUsed(false);
// File currentDir = FileSystemView.getFileSystemView().getDefaultDirectory();
File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
chooser.setCurrentDirectory(desktopDir);
String saveType[] = { "xlsx" };
chooser.setFileFilter(new FileNameExtensionFilter("Excel工作簿", saveType));
int returnVal = chooser.showSaveDialog(new Frame());
if (returnVal == JFileChooser.APPROVE_OPTION) {
dir = chooser.getSelectedFile();
String path = dir.getPath();
if(!path.toLowerCase().endsWith(".xlsx")) {
path += ".xlsx";
dir = new File(path);
}
System.out.println("saveExcelChooser1:" + path);
}
return dir;
}
public static File saveExcelChooser(Window parent, String defaultFile) {
File dir = null;
JFileChooser chooser = new JFileChooser();
chooser.setAcceptAllFileFilterUsed(false);
// File currentDir = FileSystemView.getFileSystemView().getDefaultDirectory();
File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
chooser.setCurrentDirectory(desktopDir);
chooser.setSelectedFile(new File(defaultFile));
String saveType[] = { "xlsx" };
chooser.setFileFilter(new FileNameExtensionFilter("Excel工作簿", saveType));
int returnVal = chooser.showSaveDialog(new JDialog(parent));
if (returnVal == JFileChooser.APPROVE_OPTION) {
dir = chooser.getSelectedFile();
String path = dir.getPath();
if(!path.toLowerCase().endsWith(".xlsx")) {
path += ".xlsx";
dir = new File(path);
}
if(dir.exists())
dir.delete();
// System.out.println("saveExcelChooser1:" + dir.getPath());
}
return dir;
}
public static boolean contains(String[] array, String str) {
for(String s : array) {
// System.out.println("contains:"+s+"="+str);
if(s.equals(str))
return true;
}
return false;
}
public static Map<String, String> executeToMap(InputStream in){
System.out.println("Read properties file");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
String line = null;
Map<String, String> resultMap = new LinkedHashMap<>(16);
if (reader.ready()) {
while (null != (line = reader.readLine())) {
if (line.length() <= 0 || line.startsWith("#") || !line.contains("=")) {
continue;
}
resultMap.put(line.substring(0, line.indexOf("=")), line.substring(line.indexOf("=") + 1));
}
}
in.close();
reader.close();
return resultMap;
} catch (Exception e) {
e.printStackTrace();
MessageBox.post("Find properties file failed", "ERROR", MessageBox.ERROR);
}
return null;
}
public static TCComponentDataset createExcelDataset(TCSession session, File file, String datasetName) throws Exception {
String refType = null, objType = null, fileName = null;
fileName = file.getName().toLowerCase();
if (fileName.endsWith("xls")) {
refType = "excel";
objType = "MSExcel";
} else if (fileName.endsWith("xlsx")) {
refType = "excel";
objType = "MSExcelX";
}
TCComponentDatasetType compType = (TCComponentDatasetType) session.getTypeService().getTypeComponent("Dataset");
TCComponentDataset dataset = compType.create(datasetName, "description", objType);
dataset.setFiles(new String[] { file.getAbsolutePath() }, new String[] { refType });
return dataset;
}
public static Vector<TCComponent> getChildren(TCComponent parent, String relation, String name) throws Exception {
Vector<TCComponent> result = new Vector<>();
AIFComponentContext[] children;
if(relation==null || relation.isEmpty())
children = parent.getChildren();
else
children = parent.getChildren(relation);
for(AIFComponentContext c : children) {
TCComponent comp = (TCComponent) c.getComponent();
if(comp.getProperty("object_name").equals(name))
result.add(comp);
}
return result;
}
public static void setByPass(boolean b) {
// KUtil.setByPass(b);
}
}

@ -0,0 +1,34 @@
package com.connor.ml.tcm.outfile.ML_010;
public class BomValBean {
private String bl_czbh;
private String bl_jdjz;
private String bl_quantity;
public String getBl_quantity() {
return bl_quantity;
}
public void setBl_quantity(String bl_quantity) {
this.bl_quantity = bl_quantity;
}
public String getBl_czbh() {
return bl_czbh;
}
public void setBl_czbh(String bl_czbh) {
this.bl_czbh = bl_czbh;
}
public String getBl_jdjz() {
return bl_jdjz;
}
public void setBl_jdjz(String bl_jdjz) {
this.bl_jdjz = bl_jdjz;
}
@Override
public String toString() {
return "BomValBean [bl_czbh=" + bl_czbh + ", bl_jdjz=" + bl_jdjz + ", bl_quantity=" + bl_quantity + "]";
}
}

@ -0,0 +1,483 @@
package com.connor.ml.tcm.outfile.ML_010;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode;
import com.connor.ml.tcm.outfile.bean.NodeBean;
import com.teamcenter.rac.aif.AbstractAIFCommand;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.kernel.TCAccessControlService;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentBOMLine;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCProperty;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;
public class DbomTransitionToEbomCommand extends AbstractAIFCommand {
private InterfaceAIFComponent comp;
private TCSession session;
private TCComponentBOMLine bomLine = null;
static ArrayList<String> preList = new ArrayList<String>();
private TCAccessControlService acs;
private TCComponent[] user;
private String[] props;
public DbomTransitionToEbomCommand(InterfaceAIFComponent comp, TCSession session) {
// Auto-generated constructor stub
this.comp = comp;
this.session = session;
}
private List<String> ebomList;
@Override
public void executeModal() throws Exception {
// Auto-generated method stub
// TCComponentType compType = session.getTypeComponent("ML8_Washing");
// String[] allProperties=compType.getPropertyNames();//获取类所有属性
//TCProperty[] allProperties=compType.getPropertyNames();//获取类所有属性
acs = session.getTCAccessControlService();
user = new TCComponent[]{ session.getUser(), session.getGroup(), session.getRole() };
//获取选中的对象
if(!(comp instanceof TCComponentBOMLine))
{
MessageBox.post("请在结构管理器中选中BOMLine对象", "错误", MessageBox.ERROR);
return;
}
//System.out.println("11111111111");
bomLine = (TCComponentBOMLine) comp;
//判断对象类型
TCComponentItem item = bomLine.getItem();
// boolean isTypeof=false;
String[] prefValues = session.getPreferenceService().getStringValues("Pma0_Part_Design_Type");
String[] ebomType = session.getPreferenceService().getStringValues("Pma0_EBOM_Type");
ebomList = Arrays.asList(ebomType);
System.out.println("ebomList==>"+ebomList);
List<String> dtypeList = new ArrayList<String>();
Map<String,String> DETypeMap = new HashMap<String,String>();
for(String pref : prefValues) {
String[] split = pref.split(",");
String etypeString = split[0];
String dtypeString = split[1];
DETypeMap.put(dtypeString.replaceAll("DesignType:", ""), etypeString.replaceAll("PartType:", ""));
dtypeList.add(dtypeString.replaceAll("DesignType:", ""));
preList.add(dtypeString.replaceAll("DesignType:", ""));
// if(pref.equals(item.getType())) {
// isTypeof = true;
// }
}
System.out.println(item.getType()+"dtypeList==>"+dtypeList.toString());
if(!dtypeList.contains(item.getType())) {
MessageBox.post("请选中设计对象", "提示", 2);
return;
}
//lidy20240923界面中BOM属性列的显示做成可配置配置属性为BOMline属性的真实值
String[] options = session.getPreferenceService().getStringValues("Pma0_Table_Columns");
// if(options == null || options.length == 0) {
// MessageBox.post("首选项配置不正确", "提示", 2);
// return;
// }
String[] header = new String[options.length + 5];
props = new String[options.length];
header[0] = "DBOM对象";
header[1] = "对应父节点";
header[2] = "EBOM对象";
header[3] = "发布状态";
header[4] = "选中";
for(int i = 0; i < options.length; i++) {
String[] split = options[i].split("=");
header[i + 5] = split[0];
props[i] = split[1];
}
new Thread() {
@Override
public void run() {
ProcessBarDialog progress = new ProcessBarDialog("正在加载BOM转换页面...");
progress.open();
try {
DefaultMutableTreeTableNode node = getBomPropertyToNode(session, bomLine);
progress.close();
// DbomTransitionToEbomDialog dialog =
new DbomTransitionToEbomDialog(comp, session, node, preList, progress, header);
} catch (Exception e) {
// Auto-generated catch block
e.printStackTrace();
progress.close();
}
}
}.start();
// super.executeModal();
}
// private Map<TCComponentItemRevision, List<BomValBean>> bomValMap = new HashMap<TCComponentItemRevision, List<BomValBean>>();
/**
*
*
* @param topBomline
private void packAll(TCComponentBOMLine topBomline) throws Exception {
TCComponentBOMLine[] bomlines = new TCComponentBOMLine[1];
bomlines[0] = topBomline;
StructureService structureService = StructureService.getService(session.getSoaConnection());
// ServiceData serviceData =
structureService.packOrUnpack(bomlines, 2);
// serviceDat
// TCServiceExceptionUtils.validateServiceException(serviceData);
}*/
/**
* BOM
* @throws TCException
*/
private DefaultMutableTreeTableNode getBomPropertyToNode(TCSession session, TCComponentBOMLine topBomLine)
throws Exception {
// Auto-generated method stub
NodeBean nodeBean = new NodeBean();
//对象ID
nodeBean.setDbom("顶层");
nodeBean.setEbom("");
// nodeBean.setEbomId("");
nodeBean.setNum("");
nodeBean.setLabel("");
nodeBean.setRefreshStatus("");
nodeBean.setParentString("");
DefaultMutableTreeTableNode rootNode = new DefaultMutableTreeTableNode(nodeBean);
//获取BOM
try {
//getRepresentationPropertysToNode(topBomLine, rootNode, "");
getBomPropertysToNode(topBomLine, rootNode, "",null);
return rootNode;
} catch (Exception e) {
// : handle exception
e.printStackTrace();
}
return null;
}
/***
*
* @param bomLine
* @param rootNode
* @param parentID
* @throws TCException
*/
private Boolean getRepresentationPropertysToNode(TCComponentBOMLine bomLine, DefaultMutableTreeTableNode rootNode)
throws Exception {
// , String parentID,String quantity,String blJz) throws Exception {
Boolean jxZk = false;
TCComponentItemRevision itemRevision = bomLine.getItemRevision();
//刷新表示关系
//TCComponent referenceProperty = itemRevision.getReferenceProperty("representation_for");
//referenceProperty.refresh();
//获取表示关系下的对象
itemRevision.refresh();
TCComponent[] tcComponents = itemRevision.getReferenceListProperty("representation_for");
for (TCComponent tcComponent : tcComponents) {
TCProperty refreshStatusProperty = tcComponent.getTCProperty("release_status_list");
TCComponent[] refreshStatus = refreshStatusProperty.getReferenceValueArray();
TCProperty processProperty = tcComponent.getTCProperty("process_stage_list");
TCComponent[] processStage = processProperty.getReferenceValueArray();
NodeBean nodeBean = new NodeBean();
String stringProperty = tcComponent.getStringProperty("object_string");
nodeBean.setDbom("");
nodeBean.setEbom(stringProperty);
// nodeBean.setEbomId(tcComponent.getStringProperty("item_id"));
// nodeBean.setEbomDesc(tcComponent.getStringProperty("object_desc"));
nodeBean.setNum(bomLine.getStringProperty("bl_quantity"));
nodeBean.setBom(bomLine);
for(int i = 0; i < props.length; i++) {
System.out.println("setValueAt" + (i + 5) + "==" + props[i] + "==" + bomLine.getProperty(props[i]));
nodeBean.setValueAt(i + 5, tcComponent.getProperty(props[i]));//TODO lidy20240925D转E需要显示的属性调整成物料版本属性
}
nodeBean.setTcComponent(tcComponent);
nodeBean.setpRev(itemRevision);
nodeBean.setLabel("0");
// nodeBean.setBl_plmxml_abs_xform(bomLine.getProperty("bl_plmxml_occ_xform"));
if(refreshStatus.length > 0) {
StringBuffer stringBuffer = new StringBuffer();
//添加发布状态
for (int i = 0; i < refreshStatus.length; i++) {
stringBuffer.append(refreshStatus[i].toString());
if(i < refreshStatus.length - 1) {
stringBuffer.append(",");
}
}
nodeBean.setRefreshStatus(stringBuffer.toString());
}else if(processStage.length > 0) {
nodeBean.setRefreshStatus("流程中");
}else {
nodeBean.setRefreshStatus("");
}
nodeBean.setParentString(itemRevision.getStringProperty("object_string"));
DefaultMutableTreeTableNode node = new DefaultMutableTreeTableNode(nodeBean);
rootNode.add(node);
if(tcComponents.length == 1) {
if(getTopRefresh(node)) {
nodeBean.setLabel("0");
}else {
nodeBean.setLabel("1");
}
}
// String property = tcComponent.getProperty("j6_processtype");
if(!acs.checkAccessorsPrivilege(user, tcComponent, "WRITE")){ // || stringProperty.contains("55")
System.out.println(stringProperty + "=====stringProperty");
// jxZk = false;
// }else if(property!=null && (property.equals("外购件") || property.equals("外协件"))) {
// jxZk = false;
}else {
//一图多物的情况,只要对一个物具有写权限,就允许展开下级
jxZk = true;
}
}
return jxZk;
}
/***
*
* @param node
* @return
*/
private static boolean getTopRefresh(DefaultMutableTreeTableNode node) {
boolean result = false;
//判断上层是否勾选已发布的对象
DefaultMutableTreeTableNode parentNode = (DefaultMutableTreeTableNode) node.getParent();
if(parentNode != null) {
DefaultMutableTreeTableNode rootNode = (DefaultMutableTreeTableNode) parentNode.getParent();
if(rootNode != null) {
for (int i = 0; i < rootNode.getChildCount();) {
DefaultMutableTreeTableNode childNode = (DefaultMutableTreeTableNode) rootNode.getChildAt(i);
NodeBean childBean = (NodeBean) childNode.getUserObject();
if(childBean.getLabel().equals("1") && childBean.getRefreshStatus().indexOf("发布") >= 0) {
//MessageBox.post("上层["+childBean.getEbom()+"]已勾选发布的对象,下层不允许勾选!", "错误", MessageBox.ERROR);
return true;
}
else {
return getTopRefresh(childNode);
}
}
}
}
return result;
}
/**
* BOM
* @param bomLine
* @param bomPropertyList
* @param parentID
*/
private void getBomPropertysToNode(TCComponentBOMLine bomLine, DefaultMutableTreeTableNode rootNode,
String parentID, TCComponentBOMLine pLine) {
try {
NodeBean nodeBean = new NodeBean();
String itemType = bomLine.getStringProperty("bl_item_object_type");
System.out.println(itemType);
// if(bomLine.getStringProperty("bl_item_object_type").equals("LD6_3Ddesign")) {
// return;
// }
nodeBean.setDbom(bomLine.getStringProperty("bl_item_object_string"));
nodeBean.setNum(bomLine.getStringProperty("bl_quantity"));
nodeBean.setEbom("");
// nodeBean.setEbomId("");
for(int i = 0; i < props.length; i++) {
nodeBean.setValueAt(i + 5, bomLine.getProperty(props[i]));
}
if(preList.contains(itemType)) {
nodeBean.setLabel("3");
}else {
nodeBean.setLabel("");
}
nodeBean.setRev(bomLine.getItemRevision());
nodeBean.setRefreshStatus("");
nodeBean.setParentString("");
nodeBean.setBom(bomLine);
String type = bomLine.getItem().getType();
if(ebomList.contains(type) || "EDAComp".equals(itemType) || "J6_ZX".equals(itemType) ) {
nodeBean.setpRev(pLine.getItemRevision());
nodeBean.setRootNode(rootNode);
nodeBean.setIsTw(true);
}
// nodeBean.setBl_plmxml_abs_xform(bomLine.getProperty("bl_plmxml_abs_xform"));
DefaultMutableTreeTableNode node = new DefaultMutableTreeTableNode(nodeBean);
rootNode.add(node);
getPackMessage(nodeBean, bomLine);
Boolean jxZk = getRepresentationPropertysToNode(bomLine, node);//, bomLine.getStringProperty("bl_item_item_id"),
// bomLine.getStringProperty("bl_quantity"), bomLine.getProperty("bl_plmxml_occ_xform"));
if(jxZk && bomLine.getChildren().length > 0) {//TODO
AIFComponentContext aif[] = bomLine.getChildren();
for (int i = 0; i < aif.length; i++) {
TCComponentBOMLine subline = (TCComponentBOMLine) aif[i].getComponent();
if(subline.getLogicalProperty("bl_is_occ_suppressed"))//lidy20240925抑制的事例不应在D转E功能中被转化出来
continue;
getBomPropertysToNode(subline, node, bomLine.getStringProperty("bl_item_item_id"), bomLine);
}
}
} catch (Exception e) {
// Auto-generated catch block
e.printStackTrace();
}
}
private void getPackMessage(NodeBean nodeBean, TCComponentBOMLine bomLine) {
// Auto-generated method stub
try {
Map<TCComponentItemRevision, List<BomValBean>> bomValMap = new HashMap<TCComponentItemRevision, List<BomValBean>>();
AIFComponentContext[] children = bomLine.getChildren();
// boolean hasPack = false;
// unpack
for (int i = 0; i < children.length; i++) {
TCComponentBOMLine cLine = (TCComponentBOMLine) children[i].getComponent();
System.out.println(cLine + " 是否打包:" + cLine.isPacked());
if (cLine.isPacked()) {
String bl_quantity2 = cLine.getStringProperty("bl_quantity");
if(bl_quantity2.isEmpty()) {
bl_quantity2 = "1";
}
BigDecimal bigDecimal2 = new BigDecimal(bl_quantity2);
TCComponentBOMLine[] packedLines = cLine.getPackedLines();
for(TCComponentBOMLine ccLine : packedLines) {
// TCComponentBOMLine cLine = (TCComponentBOMLine) children2[i].getComponent();
TCComponentItemRevision itemRevision = ccLine.getItemRevision();
String bl_sequence_no = ccLine.getStringProperty("bl_sequence_no");
String bl_plmxml_abs_xform = ccLine.getStringProperty("bl_plmxml_abs_xform");//bl_plmxml_occ_xform
String bl_quantity = ccLine.getStringProperty("bl_quantity");
if(bl_quantity.isEmpty()) {
bl_quantity = "1";
}
bigDecimal2 = bigDecimal2.subtract(new BigDecimal(bl_quantity));
BomValBean bean = new BomValBean();
bean.setBl_czbh(bl_sequence_no);
bean.setBl_jdjz(bl_plmxml_abs_xform);
bean.setBl_quantity(bl_quantity);
if(bomValMap.containsKey(itemRevision)) {
List<BomValBean> list = bomValMap.get(itemRevision);
list.add(bean);
}else {
List<BomValBean> list = new ArrayList<BomValBean>();
list.add(bean);
bomValMap.put(itemRevision, list);
}
}
cLine.unpack();
cLine.refresh();
TCComponentItemRevision itemRevision = cLine.getItemRevision();
String bl_sequence_no = cLine.getStringProperty("bl_sequence_no");
String bl_plmxml_abs_xform = cLine.getStringProperty("bl_plmxml_abs_xform");
BomValBean bean = new BomValBean();
bean.setBl_czbh(bl_sequence_no);
bean.setBl_jdjz(bl_plmxml_abs_xform);
bean.setBl_quantity(bigDecimal2.toString());
if(bomValMap.containsKey(itemRevision)) {
List<BomValBean> list = bomValMap.get(itemRevision);
list.add(bean);
}else {
List<BomValBean> list = new ArrayList<BomValBean>();
list.add(bean);
bomValMap.put(itemRevision, list);
}
cLine.pack();
}else {
// TCComponentBOMLine cLine = (TCComponentBOMLine) children[i].getComponent();
TCComponentItemRevision itemRevision = cLine.getItemRevision();
String bl_sequence_no = cLine.getStringProperty("bl_sequence_no");
String bl_plmxml_abs_xform = cLine.getStringProperty("bl_plmxml_abs_xform");
String bl_quantity = cLine.getStringProperty("bl_quantity");
BomValBean bean = new BomValBean();
bean.setBl_czbh(bl_sequence_no);
bean.setBl_jdjz(bl_plmxml_abs_xform);
bean.setBl_quantity(bl_quantity);
if(bomValMap.containsKey(itemRevision)) {
List<BomValBean> list = bomValMap.get(itemRevision);
list.add(bean);
}else {
List<BomValBean> list = new ArrayList<BomValBean>();
list.add(bean);
bomValMap.put(itemRevision, list);
}
}
}
// AIFComponentContext[] children2 = null;
// if (hasPack) {
// bomLine.refresh();
// children2 = bomLine.getChildren();
// for(int i = 0; i < children2.length; i++) {
// TCComponentBOMLine cLine = (TCComponentBOMLine) children2[i].getComponent();
// TCComponentItemRevision itemRevision = cLine.getItemRevision();
// String bl_sequence_no = cLine.getStringProperty("bl_sequence_no");
// String bl_plmxml_abs_xform = cLine.getStringProperty("bl_plmxml_abs_xform");
// String bl_quantity = cLine.getStringProperty("bl_quantity");
// BomValBean bean = new BomValBean();
// bean.setBl_czbh(bl_sequence_no);
// bean.setBl_jdjz(bl_plmxml_abs_xform);
// bean.setBl_quantity(bl_quantity);
// if(bomValMap.containsKey(itemRevision)) {
// List<BomValBean> list = bomValMap.get(itemRevision);
// list.add(bean);
// }else {
// List<BomValBean> list = new ArrayList<BomValBean>();
// list.add(bean);
// bomValMap.put(itemRevision, list);
// }
// }
// }else {
// for(int i = 0; i < children.length; i++) {
// TCComponentBOMLine cLine = (TCComponentBOMLine) children[i].getComponent();
// TCComponentItemRevision itemRevision = cLine.getItemRevision();
// String bl_sequence_no = cLine.getStringProperty("bl_sequence_no");
// String bl_plmxml_abs_xform = cLine.getStringProperty("bl_plmxml_abs_xform");
// String bl_quantity = cLine.getStringProperty("bl_quantity");
// BomValBean bean = new BomValBean();
// bean.setBl_czbh(bl_sequence_no);
// bean.setBl_jdjz(bl_plmxml_abs_xform);
// bean.setBl_quantity(bl_quantity);
// if(bomValMap.containsKey(itemRevision)) {
// List<BomValBean> list = bomValMap.get(itemRevision);
// list.add(bean);
// }else {
// List<BomValBean> list = new ArrayList<BomValBean>();
// list.add(bean);
// bomValMap.put(itemRevision, list);
// }
// }
// }
nodeBean.setBomValMap(bomValMap);
// try {
// if(hasPack) {
// packAll(bomLine);
// bomLine.refresh();
// }
// } catch (Exception e1) {
// // Auto-generated catch block
// e1.printStackTrace();
// }
}catch (Exception e) {
// : handle exception
e.printStackTrace();
}
}
}

@ -0,0 +1,30 @@
package com.connor.ml.tcm.outfile.ML_010;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import com.teamcenter.rac.aif.AbstractAIFApplication;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.kernel.TCSession;
public class DbomTransitionToEbomHandler extends AbstractHandler {
@Override
public Object execute(ExecutionEvent arg0) throws ExecutionException {
// TODO Auto-generated method stub
AbstractAIFApplication app = AIFUtility.getCurrentApplication();
TCSession session = (TCSession) app.getSession();
try {
DbomTransitionToEbomCommand command = new DbomTransitionToEbomCommand(app.getTargetComponent(),session);
command.executeModal();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}

@ -0,0 +1,267 @@
package com.connor.ml.tcm.outfile.ML_010;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
//import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.swing.JButton;
//import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import com.teamcenter.rac.aif.AbstractAIFDialog;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.kernel.TCComponentForm;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCSession;
public class DbomTransitionToEbomSearchDialog extends AbstractAIFDialog {
/**
*
*/
private static final long serialVersionUID = 1L;
// private TCSession session;
private DbomTransitionToEbomDialog parent;
private JTable impTable;
private DefaultTableModel impModel;
private Map<String, JTextField> searchMap;
private JButton addBtn;
private JButton delBtn;
private JButton searchBtn;
private JButton okBtn;
private JButton cancelBtn;
public String codeID;
public DbomTransitionToEbomSearchDialog(TCSession session, DbomTransitionToEbomDialog parent, String[] head, String[][] tags) {
super(parent, true);
// this.session = session;
this.parent = parent;
searchMap = new LinkedHashMap<>();
String[] tableHeader = new String[] { "AND/OR", "属性名称", "运算符", "搜索值" };
int size = tableHeader.length;
impModel = new DefaultTableModel(tableHeader, 0);
impTable = new JTable() {
private static final long serialVersionUID = 1L;
@Override
public boolean isCellEditable(int row, int col) {
if(row == 0 && col == 0)
return false;
return true;
}
@Override
public TableCellRenderer getCellRenderer(int row, int column) {
return super.getCellRenderer(row, column);
}
};
impModel.setDataVector(tags, tableHeader);
impTable.getTableHeader().setReorderingAllowed(false);
impTable.setFillsViewportHeight(true);
impTable.setEnabled(true);
// impTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
impTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
impTable.setModel(impModel);
int[] widths = { 100, 100, 80, 150 };
TableColumnModel colModel = impTable.getColumnModel();
for (int i = 0; i < size; i++) {
colModel.getColumn(i).setPreferredWidth(widths[i]);
}
String[][] comboBoxItems = {{ "AND", "OR" }, head, { "=", "==", "!=" }, { "已勾选", "未勾选" }}; // 下拉框选项列表
for(int i = 0; i < comboBoxItems.length; i++) {
TableColumn column = colModel.getColumn(i); // 获取第三列模型对象
// JComboBox<Object> comboBox = new JComboBox<>(comboBoxItems[i]);
// comboBox.setEditable(i == comboBoxItems.length - 1);
// column.setCellEditor(new DefaultCellEditor(comboBox));
column.setCellEditor(new TableCellComboBoxEditor(comboBoxItems[i], i == comboBoxItems.length - 1));
column.setCellRenderer(new DefaultTableCellRenderer());
// 设置编辑器到第三列模型对象上,这将允许在该列编辑时显示下拉框。如果你也想设置渲染器:
// column.setCellRenderer(new TableCellComboBoxRenderer(comboBoxItems[i]));
// 设置渲染器到第三列模型对象上,这将允许在该列显示时显示下拉框。
}
impTable.setRowHeight(25);
impTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
// Container container = myframe.getContentPane();
JPanel CPanel = new JPanel(new BorderLayout(10, 10));
CPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
// JPanel leftPanel = new JPanel(new BorderLayout(10, 10));
JPanel msgPanel = new JPanel(new GridLayout(10,2,10,10));
for(Entry<String, JTextField> e : searchMap.entrySet()) {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.WEST, new JLabel(e.getKey()+" "));
panel.add(BorderLayout.EAST, e.getValue());
msgPanel.add(panel);
}
// leftPanel.add(BorderLayout.NORTH, msgPanel);
JPanel btnPanel = new JPanel(new FlowLayout());
addBtn = new JButton("+");
delBtn = new JButton("-");
searchBtn = new JButton("搜索");
okBtn = new JButton("确定");
cancelBtn = new JButton("取消");
btnPanel.add(addBtn);
btnPanel.add(delBtn);
btnPanel.add(searchBtn);
btnPanel.add(okBtn);
btnPanel.add(cancelBtn);
// leftPanel.add(BorderLayout.SOUTH, btnPanel);
JScrollPane tablePanel = new JScrollPane();
tablePanel.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
tablePanel.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
tablePanel.setViewportView(impTable);
CPanel.add(BorderLayout.SOUTH, btnPanel);
CPanel.add(BorderLayout.CENTER, tablePanel);
this.add(CPanel);
addActionListener();
setSize(750, 600);
//awtContainer.setSize(730, 570);
Dimension screen = getToolkit().getScreenSize();
setLocation((screen.width - getSize().width) / 2, (screen.height - getSize().height) / 2);
setAlwaysOnTop(true);
setVisible(true);
// open();
}
public void run(){
showDialog();
}
private void addActionListener() {
addBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if(impTable.getRowCount() > 0)
impModel.addRow(new String[] { "AND" });
else
impModel.addRow(new String[] { "" });
}
});
//final Shell dialog = shell;
delBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if(impTable.getRowCount() == 0)
return;
int[] rows = impTable.getSelectedRows();
if(rows.length == 0)
return;
if(impTable.getCellEditor() != null)
impTable.getCellEditor().stopCellEditing();
for(int i = rows.length - 1; i >= 0; i--) {
impModel.removeRow(rows[i]);
if(rows[i] == 0 && impTable.getRowCount() > 0)
impTable.setValueAt("", 0, 0);
}
}
});
searchBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if(impTable.getCellEditor() != null)
impTable.getCellEditor().stopCellEditing();
ArrayList<String[]> list = new ArrayList<>();
for(int i = 0, len = impTable.getRowCount(); i < len; i++) {
String[] val = new String[4];
for(int j = 0; j < 4; j++)
val[j] = "" + impTable.getValueAt(i, j);
list.add(val);
}
String[][] tags = list.toArray(new String[0][0]);
parent.search(tags);
}
});
okBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
/*
int[] selected = impTable.getSelectedRows();
if(selected==null || selected.length==0) {
MessageBox.post(CodeIDDialog.this, "请搜索并选择零部件", "ERROR", MessageBox.ERROR);
return;
}
parent.codeID = impTable.getValueAt(selected[0], codeCol).toString();
// new Thread() {
// public void run() {
// combo.setText(text.replace("[CodeID]", codeID));
// }
// }.start();
final String text = "[CodeID]<---->"+parent.codeID;
final int w = new JLabel(text).getPreferredSize().width+10;
Display display = Display.getDefault();
display.asyncExec(new Runnable() {
public void run() {
// String text = combo.getText().replaceAll("", "");
combo.add(text);
combo.setText(text);
Rectangle r = combo.getBounds();
combo.setBounds(r.x, r.y, w, r.height);
combo.getParent().redraw();
System.out.println("Text:"+combo.getText());
parent.updateMap(false);
// shell.getDisplay().sleep();
// shell.close();
// display.sleep();
}
});*/
dispose();
// while (!display.isDisposed()) {
// // Always gives a thread access error, but still calls async event:
// if (!display.readAndDispatch())
// display.sleep();
// }
}
});
cancelBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// Display.getDefault().asyncExec(new Runnable() {
// public void run() {
// parent.updateMap(false);
//// shell.getDisplay().sleep();
//// shell.close();
//// display.sleep();
// }
// });
// parent.updateMap(false);
dispose();
// shell.getDisplay().sleep();
}
});
}
public static TCComponentForm getItemRevisionMasterForm(TCComponentItemRevision revision) throws Exception {
if (revision != null) {
AIFComponentContext[] contexts = revision.getChildren("IMAN_master_form_rev");
if (contexts != null && contexts.length > 0) {
InterfaceAIFComponent component = contexts[0].getComponent();
if (component instanceof TCComponentForm) {
return (TCComponentForm) component;
}
}
}
return null;
}
}

@ -0,0 +1,93 @@
package com.connor.ml.tcm.outfile.ML_010;
import java.awt.event.MouseEvent;
import java.util.List;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import org.jdesktop.swingx.JXTreeTable;
import com.connor.ml.tcm.outfile.bean.NodeBean;
public class JTreeTable extends JXTreeTable {
/**
*
*/
private static final long serialVersionUID = 1L;
private List<Integer> isNotEditableRow;
//CheckBoxCellEditor checkBoxCellEditor = new CheckBoxCellEditor(this);
private TableCellCheckboxRenderer checkboxRenderer = new TableCellCheckboxRenderer(this);
public List<Integer> getIsNotEditableRow() {
return isNotEditableRow;
}
public void setIsNotEditableRow(List<Integer> isNotEditableRow) {
this.isNotEditableRow = isNotEditableRow;
}
public JTreeTable(JTreeTableModel testTreeTableModel) {
// Auto-generated constructor stub
super(testTreeTableModel);
}
@Override
public boolean isCellEditable(int arg0, int arg1) {
// Auto-generated method stub
return true;//super.isCellEditable(arg0, arg1);
}
@Override
public TableCellEditor getCellEditor(int row, int column) {
// Auto-generated method stub
//if(isNotEditableRow.contains(row) && column == 2)
return cellEditor;
//return super.getCellEditor(row, column);
}
public String getToolTipText(MouseEvent e) {
int row = this.rowAtPoint(e.getPoint());
int col = this.columnAtPoint(e.getPoint());
String tiptextString = null;
if (row > -1 && col > -1) {
Object value = this.getValueAt(row, col);
if (null != value && !"".equals(value))
tiptextString = value.toString();// 技륫鞫刻데禱목코휭
}
return tiptextString;
}
@Override
public TableCellRenderer getCellRenderer(int row, int column) {
// Auto-generated method stub
Object val = getValueAt(row, NodeBean.LABEL);
if(column == NodeBean.LABEL && val != null && (val.equals("0") || val.equals("1")))
{
return checkboxRenderer;
}
else
{
return super.getCellRenderer(row, column);
}
}
// 茶꾜죗
public void HiddenCell(int column) {
TableColumn tc = this.getTableHeader().getColumnModel()
.getColumn(column);
tc.setMaxWidth(0);
tc.setPreferredWidth(0);
tc.setWidth(0);
tc.setMinWidth(0);
this.getTableHeader().getColumnModel().getColumn(column).setMaxWidth(0);
this.getTableHeader().getColumnModel().getColumn(column).setMinWidth(0);
}
}

@ -0,0 +1,130 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.connor.ml.tcm.outfile.ML_010;
import java.util.List;
import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode;
import org.jdesktop.swingx.treetable.DefaultTreeTableModel;
import org.jdesktop.swingx.treetable.TreeTableNode;
import com.connor.ml.tcm.outfile.bean.NodeBean;
/**
*
* @author vearn
*/
public class JTreeTableModel extends DefaultTreeTableModel {
private String[] _names = { "DBOM对象", "EBOM对象","选中", "EBOMID", "物料描述","数量","发布状态","对应父节点"};
private List<Integer> isNotEditableRow;
public JTreeTableModel(TreeTableNode node, String[] names) {
super(node);
_names = names;
}
public List<Integer> getIsNotEditableRow() {
return isNotEditableRow;
}
public void setIsNotEditableRow(List<Integer> isNotEditableRow) {
this.isNotEditableRow = isNotEditableRow;
}
/**
*
*/
@Override
public int getColumnCount() {
return _names.length;
}
/**
*
*/
@Override
public String getColumnName(int column) {
return _names[column];
}
/**
* Object
*/
@Override
public Object getValueAt(Object node, int column) {
Object value = null;
if (node instanceof DefaultMutableTreeTableNode) {
DefaultMutableTreeTableNode mutableNode = (DefaultMutableTreeTableNode) node;
Object o = mutableNode.getUserObject();
if (o != null && o instanceof NodeBean) {
NodeBean bean = (NodeBean) o;
value = bean.getValueAt(column);
if(column == NodeBean.LABEL && value.equals("3")) {
value = "";
}
// if(column > 4)
// System.out.println("getValueAt" + column + "==" + value);
/*switch (column) {
case 0:
value = bean.getDbom();
break;
case 1:
value = bean.getEbom();
break;
case 2:
value = bean.getLabel();
if(value.equals("3")) {
value = "";
}
break;
case 3:
value = bean.getEbomId();
break;
case 4:
value = bean.getEbomDesc();
break;
case 5:
value = bean.getNum();
break;
case 6:
value = bean.getRefreshStatus();
break;
case 7:
value = bean.getParentString();
break;
}*/
}
}
return value;
}
/**
*
*
* @param the node (i.e. row) for which editing is to be determined
* @param the column for which editing is to be determined
* @return false
*/
@Override
public boolean isCellEditable(Object node, int column) {
//if(column == 5)
//{
return true;
//}
//else
//{
// return false;
//}
}
}

@ -0,0 +1,53 @@
package com.connor.ml.tcm.outfile.ML_010;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Dimension;
import java.util.TimerTask;
import java.util.Timer;
import javax.swing.*;
public class ProcessBarDialog extends JFrame {
private JProgressBar progressBar = new JProgressBar();
private Box box = Box.createVerticalBox();
private Box box2 = Box.createHorizontalBox();
private String name;
public ProcessBarDialog(String name) {
this.name = name;
}
public void open() {
this.setTitle("加载中...");
//需要用进程调用
setBounds(200, 200, 300, 100);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
progressBar.setIndeterminate(true);// 设置进度条的样式为不确定的进度条样式(进度条来回滚动)false为确定的进度条样式(即进度条从头到尾显示)
progressBar.setStringPainted(true);// 设置进度条显示提示信息
progressBar.setString(name);// 设置提示信息
progressBar.setPreferredSize(new Dimension(300, 100));
box2.add(progressBar);
box.add(box2);
add(box);
this.setAlwaysOnTop(true);
setVisible(true);
}
public void close() {
this.dispose();
}
}

@ -0,0 +1,76 @@
package com.connor.ml.tcm.outfile.ML_010;
import java.awt.Component;
import java.util.List;
import javax.swing.JCheckBox;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.EventListenerList;
import javax.swing.table.TableCellRenderer;
public class TableCellCheckboxRenderer extends JCheckBox implements
TableCellRenderer {
/**
*
*/
private static final long serialVersionUID = 1L;
private List<Integer> processRows;
protected EventListenerList listenerList = new EventListenerList();
protected ChangeEvent changeEvent = new ChangeEvent(this);
//private TestTreeTableModel tableModel;
public List<Integer> getProcessRows() {
return processRows;
}
public void setProcessRows(List<Integer> processRows) {
this.processRows = processRows;
}
public TableCellCheckboxRenderer(final JTreeTable table) {
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
// TODO Auto-generated method stub
this.setHorizontalAlignment(SwingConstants.CENTER);// ±íÍ·±êÇ©¾çÖÐ
this.setBorderPainted(true);
if(value != null)
{
// if(value.toString().equals("1"))
// {
// if(table.getColumnName(column).equals("¸ÄÖÆ") && hasFocus)
// {
// if(table.getValueAt(row, column + 1).toString().equals("1"))
// {
// table.setValueAt(0, row, column + 1);
// }
// }
// else if(table.getColumnName(column).equals("ɾ³ý") && hasFocus)
// {
// if(table.getValueAt(row, column - 1).toString().equals("1"))
// {
// table.setValueAt(0, row, column - 1);
// }
// }
// }
// if(value.toString().equals("1"))
// {
// System.out.println(value.toString().equals("1") + "====");
// }
this.setSelected(value.toString().equals("1"));
}
else
{
this.setSelected(false);
}
return this;
}
}

@ -0,0 +1,59 @@
package com.connor.ml.tcm.outfile.ML_010;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
public class TableCellComboBoxEditor extends DefaultCellEditor implements TableCellEditor {
/**
*
*/
private static final long serialVersionUID = 1L;
private JComboBox<Object> comboBox;
// private Object value;
private JTable table;
private int row;
private int column;
@SuppressWarnings("unchecked")
public TableCellComboBoxEditor(Object[] items, boolean editable) {
super(new JComboBox<>(items));
comboBox = (JComboBox<Object>) getComponent();
comboBox.setEditable(editable);
comboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// System.out.println("action1£º" + comboBox.getSelectedItem());
fireEditingStopped();
// System.out.println("action2£º" + comboBox.getSelectedItem());
if(table != null)
table.setValueAt(comboBox.getSelectedItem(), row, column);
}
});
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
// System.out.println("getTableCellEditorComponent1£º" + comboBox.getSelectedItem() + "==" + value);
this.table = table;
this.row = row;
this.column = column;
if(value == null)
comboBox.setSelectedItem("");
else
comboBox.setSelectedItem(value);
// this.value = value;
// System.out.println("getTableCellEditorComponent2£º" + comboBox.getSelectedItem() + "==" + table.getValueAt(row, column));
return comboBox;
}
@Override
public Object getCellEditorValue() {
return comboBox.getSelectedItem();
}
}

@ -0,0 +1,8 @@
package com.connor.ml.tcm.outfile.ML_010;
public class Test {
public static void main(String[] args) {
String s = "11111112-32222222-4444";
System.out.println(s.substring(0, s.indexOf("-")));
}
}

@ -0,0 +1,165 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.connor.ml.tcm.outfile.bean;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode;
import com.connor.ml.tcm.outfile.ML_010.BomValBean;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentBOMLine;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
/**
*
* @author vearn
*/
public class NodeBean {
private String dbom;//对象ID
private String ebom;//对象名称
// private String ebomId;//对象名称
// private String ebomDesc;//物料描述
private String num;//数量
private String label;//对象名称
private String refreshStatus;//发布状态
private String parentString;//对应父节点
// private String bl_plmxml_abs_xform ;//绝对变换矩阵
private TCComponentItemRevision pRev;//对应父节点
private TCComponentItemRevision rev;//对应父节点
private TCComponent tcComponent;
private Boolean isTw = false;
private DefaultMutableTreeTableNode rootNode;
private Map<TCComponentItemRevision, List<BomValBean>> bomValMap = new HashMap<TCComponentItemRevision, List<BomValBean>>();
public static int DBOM = 0;
public static int PARENT = 1;
public static int EBOM = 2;
public static int STATUS = 3;
public static int LABEL = 4;
private HashMap<Integer, String> values = new HashMap<>();
private TCComponentBOMLine bomLine;
public Boolean getIsTw() {
return isTw;
}
public DefaultMutableTreeTableNode getRootNode() {
return rootNode;
}
public void setRootNode(DefaultMutableTreeTableNode rootNode) {
this.rootNode = rootNode;
}
public void setIsTw(Boolean isTw) {
this.isTw = isTw;
}
public TCComponent getTcComponent() {
return tcComponent;
}
public void setTcComponent(TCComponent tcComponent) {
this.tcComponent = tcComponent;
}
public TCComponentItemRevision getRev() {
return rev;
}
public void setRev(TCComponentItemRevision rev) {
this.rev = rev;
}
public TCComponentItemRevision getpRev() {
return pRev;
}
public Map<TCComponentItemRevision, List<BomValBean>> getBomValMap() {
return bomValMap;
}
public void setBomValMap(Map<TCComponentItemRevision, List<BomValBean>> bomValMap) {
this.bomValMap = bomValMap;
}
public void setpRev(TCComponentItemRevision pRev) {
this.pRev = pRev;
}
// public String getBl_plmxml_abs_xform() {
// return bl_plmxml_abs_xform;
// }
// public void setBl_plmxml_abs_xform(String bl_plmxml_abs_xform) {
// this.bl_plmxml_abs_xform = bl_plmxml_abs_xform;
// }
public String getDbom() {//0
return dbom;
}
public void setDbom(String dbom) {//0
this.dbom = dbom;
setValueAt(DBOM, dbom);
}
public String getEbom() {//1
return ebom;
}
public void setEbom(String ebom) {//1
this.ebom = ebom;
setValueAt(EBOM, ebom);
}
public String getLabel() {//2
return label;
}
public void setLabel(String label) {//2
this.label = label;
setValueAt(LABEL, label);
}
// public String getEbomId() {//3
// return ebomId;
// }
// public void setEbomId(String ebomId) {//3
// this.ebomId = ebomId;
// }
// public String getEbomDesc() {//4
// return ebomDesc;
// }
// public void setEbomDesc(String ebomDesc) {//4
// this.ebomDesc = ebomDesc;
// }
public String getNum() {//5
return num;
}
public void setNum(String num) {//5
this.num = num;
}
public String getRefreshStatus() {//6
return refreshStatus;
}
public void setRefreshStatus(String refreshStatus) {//6
this.refreshStatus = refreshStatus;
setValueAt(STATUS, refreshStatus);
}
public String getParentString() {//7
return parentString;
}
public void setParentString(String parentString) {//7
this.parentString = parentString;
setValueAt(PARENT, parentString);
}
public String getValueAt(int i) {
if(values.containsKey(i))
return values.get(i);
return "";
}
public void setValueAt(int i, String val) {
values.put(i, val);
}
public TCComponentBOMLine getBom() {
return bomLine;
}
public void setBom(TCComponentBOMLine bomLine) {
this.bomLine = bomLine;
}
public String toString() {
return dbom + " >>> " + ebom + " == " + label;
}
}

@ -0,0 +1,299 @@
package com.connor.ml.tcm.outfile.util;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
/**
* Adapter JTables Excel
* JTables Excel
*/
public class Adapter implements ActionListener {
private String rowstring, value;
private Clipboard system;
private StringSelection stsel;
private JTable jTable1;
private List<List<Object>> selectValue = new ArrayList<List<Object>>();
/**
* Excel JTable JTable
*/
public Adapter(JTable myJTable) {
jTable1 = myJTable;
KeyStroke copy = KeyStroke.getKeyStroke(KeyEvent.VK_C,
ActionEvent.CTRL_MASK, false);
// 确定复制按键用户可以对其进行修改
// 以实现其它按键组合的复制功能。
KeyStroke paste = KeyStroke.getKeyStroke(KeyEvent.VK_V,
ActionEvent.CTRL_MASK, false);
// 确定粘贴按键用户可以对其进行修改
// 以实现其它按键组合的复制功能。
jTable1.registerKeyboardAction(this, "Copy", copy,
JComponent.WHEN_FOCUSED);
jTable1.registerKeyboardAction(this, "Paste", paste,
JComponent.WHEN_FOCUSED);
system = Toolkit.getDefaultToolkit().getSystemClipboard();
}
/**
*
*/
public JTable getJTable() {
return jTable1;
}
public void setJTable(JTable jTable1) {
this.jTable1 = jTable1;
}
/**
* ActionCommands
* JTable
*/
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().compareTo("Copy") == 0) {
StringBuffer sbf = new StringBuffer();
selectValue.clear();
// 检查以确保我们仅选择了单元格的
// 相邻块
int numcols = jTable1.getSelectedColumnCount();
int numrows = jTable1.getSelectedRowCount();
int[] rowsselected = jTable1.getSelectedRows();
int[] colsselected = jTable1.getSelectedColumns();
// if (!((numrows - 1 == rowsselected[rowsselected.length - 1]
// - rowsselected[0] && numrows == rowsselected.length) && (numcols - 1 == colsselected[colsselected.length - 1]
// - colsselected[0] && numcols == colsselected.length))) {
// JOptionPane.showMessageDialog(null, "Invalid Copy Selection",
// "Invalid Copy Selection", JOptionPane.ERROR_MESSAGE);
//
// return;
// }
for (int i=0;i<numrows;i++)
{
for (int j=0;j<numcols;j++)
{
if(jTable1.getValueAt(rowsselected[i],colsselected[j]) != null && jTable1.getValueAt(rowsselected[i],colsselected[j]).toString().indexOf("\n") >= 0)
{
sbf.append("\"");
sbf.append(jTable1.getValueAt(rowsselected[i],colsselected[j]));
sbf.append("\"");
}
else if(jTable1.getValueAt(rowsselected[i],colsselected[j]) == null)
{
sbf.append("");
}
else
{
sbf.append(jTable1.getValueAt(rowsselected[i],colsselected[j]));
}
if (j<numcols-1)
{
sbf.append("\t".toString());
}
}
sbf.append("\n".toString());
}
stsel = new StringSelection(sbf.toString().trim());
system = Toolkit.getDefaultToolkit().getSystemClipboard();
system.setContents(stsel,stsel);
}
if (e.getActionCommand().compareTo("Paste") == 0) {
System.out.println("Trying to Paste");
//int startRow = (jTable1.getSelectedRows())[0];
//int startCol = (jTable1.getSelectedColumns())[0];
try {
String trstring= (String)(system.getContents(this).getTransferData(DataFlavor.stringFlavor));
System.out.println("String is:"+trstring);
String[] values = trstring.split("\"");
StringBuffer sb = new StringBuffer();
//替换Excel中的换行符
for (int i = 0; i < values.length; i++) {
System.out.println(i+values[i]);
if(i % 2 ==0 && values[i].indexOf("\n") >= 0)
{
sb.append(values[i].replace("\n", " $"));
}
else
{
sb.append(values[i]);
}
//System.out.println(i+s[i]);
}
System.out.println("sb======"+sb.toString());
String copyValue = sb.toString();
String[] st1=copyValue.split("\\$"); //new StringTokenizer(sb.toString(),"$".toString());
int[] rows = jTable1.getSelectedRows();
int[] columns = jTable1.getSelectedColumns();
int startRow = rows[0];
int startCol = columns[0];
if(rows.length ==1 )
{
for(int i=0;i<st1.length;i++)
{
rowstring=st1[i];
System.out.println("rowstring============"+rowstring);
if(rowstring.indexOf("\t") >= 0)
{
String[] cellValue = rowstring.split("\t");
for(int j=0;j<cellValue.length;j++)
{
value=(String)cellValue[j];
System.out.println("value============"+value);
if (startRow+i< jTable1.getRowCount() &&
startCol+j < jTable1.getColumnCount()-1)
{
jTable1.setValueAt(value.trim(),startRow+i,startCol+j);
}
System.out.println("Putting "+ value+"atrow="+startRow+i+"column="+startCol+j);
}
}
else
{
jTable1.setValueAt(rowstring.trim(),startRow+i,startCol);
}
}
}
else if(rows.length > 1 )
{
//如果选择行大于复制行//选中行除以复制行
if(rows.length > st1.length)
{
// int num = rows.length / st1.length;
for (int i = 0; i < rows.length; i++) {
//for (int j = 0; j < num; j++) {
//for (int j2 = 0; j2 < st1.length; j2++) {
rowstring=st1[(i+st1.length)%st1.length];
System.out.println("rowstring============"+rowstring);
if(rowstring.indexOf("\t") >= 0)
{
String[] cellValue = rowstring.split("\t");
for (int k = 0; k < cellValue.length; k++) {
value=(String)cellValue[k];
System.out.println("value============"+value);
jTable1.setValueAt(value.trim(),rows[i],startCol+k);
System.out.println("Putting "+ value+"atrow="+startRow+i+"column="+startCol+k);
}
}
else
{
jTable1.setValueAt(rowstring.trim(),rows[i],startCol);
}
//}
//}
}
}
else //写入选中行内容
{
for(int i=0;i<st1.length;i++)
{
rowstring=st1[i];
System.out.println("rowstring============"+rowstring);
if(rowstring.indexOf("\t") >= 0)
{
String[] cellValue = rowstring.split("\t");
for(int j=0;j<cellValue.length;j++)
{
value=(String)cellValue[j];
System.out.println("value============"+value);
if (startRow+i< jTable1.getRowCount() &&
startCol+j< jTable1.getColumnCount()-1)
{
jTable1.setValueAt(value.trim(),startRow+i,startCol+j);
}
System.out.println("Putting "+ value+"atrow="+startRow+i+"column="+startCol+j);
}
}
else
{
jTable1.setValueAt(rowstring.trim(),startRow+i,startCol);
}
}
}
}
if(columns.length > st1[0].split("\t").length) //如果选中列数大于复制列数
{
System.out.println("========================================================================");
if(rows.length > st1.length)
{
for (int i = 0; i < rows.length; i++) {
for (int j = 0; j < columns.length; j++) {
rowstring=st1[(i+st1.length)%st1.length];
System.out.println("rowstring============"+rowstring);
if(rowstring.indexOf("\t") >= 0)
{
String[] cellValue = rowstring.split("\t");
for (int k = 0; k < cellValue.length; k++) {
value=(String)cellValue[(j+cellValue.length)%cellValue.length];
System.out.println("value============"+value);
jTable1.setValueAt(value.trim(),rows[i],columns[j]);
System.out.println("Putting "+ value+"atrow="+startRow+i+"column="+startCol+k);
}
}
else
{
jTable1.setValueAt(rowstring.trim(),rows[i],columns[j]);
}
}
}
}
else
{
for (int i = 0; i < st1.length; i++) {
for (int j = 0; j < columns.length; j++) {
rowstring=st1[(i+st1.length)%st1.length];
System.out.println("rowstring============"+rowstring);
if(rowstring.indexOf("\t") >= 0)
{
String[] cellValue = rowstring.split("\t");
for (int k = 0; k < cellValue.length; k++) {
value=(String)cellValue[(j+cellValue.length)%cellValue.length];
System.out.println("value============"+value);
jTable1.setValueAt(value.trim(),startRow+i,columns[j]);
System.out.println("Putting "+ value+"atrow="+startRow+i+"column="+startCol+k);
}
}
else
{
jTable1.setValueAt(rowstring.trim(),startRow+i,columns[j]);
}
}
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}

@ -0,0 +1,171 @@
package com.connor.ml.tcm.outfile.util;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.List;
import java.util.Vector;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JTextField;
@SuppressWarnings({ "serial", "rawtypes", "unchecked" })
public class JAutoCompleteComboBox extends JComboBox {
private AutoCompleter completer;
private String propName;
public JAutoCompleteComboBox() {
super();
addCompleter();
}
public JAutoCompleteComboBox(ComboBoxModel cm) {
super(cm);
addCompleter();
}
public JAutoCompleteComboBox(Object[] items) {
super(items);
addCompleter();
}
public JAutoCompleteComboBox(List v) {
super((Vector) v);
addCompleter();
}
public String getPropName() {
return propName;
}
public void setPropName(String propName) {
this.propName = propName;
}
private void addCompleter() {
setEditable(true);
completer = new AutoCompleter(this);
}
public void autoComplete(String str) {
this.completer.autoComplete(str, str.length());
}
public String getText() {
return ((JTextField) getEditor().getEditorComponent()).getText();
}
public void setText(String text) {
((JTextField) getEditor().getEditorComponent()).setText(text);
}
public boolean containsItem(String itemString) {
for (int i = 0; i < this.getModel().getSize(); i++) {
String _item = " " + this.getModel().getElementAt(i);
if (_item.equals(itemString))
return true;
}
return false;
}
}
@SuppressWarnings({"rawtypes"})
class AutoCompleter implements KeyListener, ItemListener {
private JComboBox owner = null;
private JTextField editor = null;
private ComboBoxModel model = null;
public AutoCompleter(JComboBox comboBox) {
owner = comboBox;
editor = (JTextField) comboBox.getEditor().getEditorComponent();
editor.addKeyListener(this);
model = comboBox.getModel();
owner.addItemListener(this);
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
}
@SuppressWarnings("unused")
public void keyReleased(KeyEvent e) {
char ch = e.getKeyChar();
// if (ch == KeyEvent.CHAR_UNDEFINED || Character.isISOControl(ch)
// || ch == KeyEvent.VK_DELETE)
// return;
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
int caretPosition = editor.getCaretPosition();
String str = editor.getText();
if (str.length() == 0)
return;
autoComplete(str, caretPosition);
}
}
@SuppressWarnings({ "unchecked", "unused" })
protected void autoComplete(String strf, int caretPosition) {
Object[] opts;
opts = getMatchingOptions(strf.substring(0, caretPosition));
if (owner != null) {
model = new DefaultComboBoxModel(opts);
owner.setModel(model);
}
if (opts.length > 0) {
String str = opts[0].toString();
editor.setCaretPosition(caretPosition);
if (owner != null) {
try {
owner.showPopup();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
@SuppressWarnings("unchecked")
protected Object[] getMatchingOptions(String str) {
List v = new Vector();
List v1 = new Vector();
// v.add(str);
for (int k = 0; k < model.getSize(); k++) {
Object itemObj = model.getElementAt(k);
if (itemObj != null) {
String item = itemObj.toString().toLowerCase();
if (item.indexOf((str.toLowerCase())) > -1)
v.add(model.getElementAt(k));
else
v1.add(model.getElementAt(k));
} else
v1.add(model.getElementAt(k));
}
for (int i = 0; i < v1.size(); i++) {
v.add(v1.get(i));
}
// if (v.isEmpty())
return v.toArray();
}
public void itemStateChanged(ItemEvent event) {
if (event.getStateChange() == ItemEvent.SELECTED) {
int caretPosition = editor.getCaretPosition();
if (caretPosition != -1) {
try {
editor.moveCaretPosition(caretPosition);
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
}
}
}
}
}

@ -0,0 +1,868 @@
package com.connor.ml.tcm.outfile.util;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import javax.swing.JOptionPane;
import com.teamcenter.rac.aif.AbstractAIFApplication;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.kernel.ListOfValuesInfo;
import com.teamcenter.rac.kernel.TCClassificationService;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentDataset;
import com.teamcenter.rac.kernel.TCComponentDatasetType;
import com.teamcenter.rac.kernel.TCComponentFolder;
import com.teamcenter.rac.kernel.TCComponentICO;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentItemType;
import com.teamcenter.rac.kernel.TCComponentListOfValues;
import com.teamcenter.rac.kernel.TCComponentListOfValuesType;
import com.teamcenter.rac.kernel.TCComponentProcess;
import com.teamcenter.rac.kernel.TCComponentProcessType;
import com.teamcenter.rac.kernel.TCComponentTaskTemplate;
import com.teamcenter.rac.kernel.TCComponentTaskTemplateType;
import com.teamcenter.rac.kernel.TCComponentTcFile;
import com.teamcenter.rac.kernel.TCComponentType;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCPreferenceService;
import com.teamcenter.rac.kernel.TCProperty;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.kernel.TCUserService;
import com.teamcenter.rac.kernel.ics.ICSKeyLov;
import com.teamcenter.rac.kernel.ics.ICSProperty;
import com.teamcenter.rac.kernel.ics.ICSPropertyDescription;
import com.teamcenter.rac.kernel.ics.ICSSearchResult;
import com.teamcenter.rac.util.MessageBox;
//import com.teamcenter.services.rac.core.DataManagementService;
//import net.sf.json.JSONArray;
//import net.sf.json.JSONObject;
public class MethodUtil {
private static final String SEP1 = ",";
/**
* BOM
*
* @param session session
* @param process
* @param processUser
* @param arctic
* @throws TCException
*/
public static void sendBom(TCSession session, TCComponentItemRevision itemRevision) throws TCException {
TCUserService userservice = session.getUserService();
Object[] obj = new Object[1];
obj[0] = itemRevision;
userservice.call("Super_Bom_Appent_Data", obj);
}
/**
* ID
*
* @param oldItemID ID
* @return ID
*/
public static String getRuleItemID(TCSession session, String oldItemID) {
// String[] oldItemIDs = oldItemID.split("-");
DecimalFormat df = new DecimalFormat("000");
// String newID = oldItemIDs[0] + "-" + oldItemIDs[1] + "-001";
String newID = oldItemID + "-001";
// String idTemp =
TCComponentItemType tccomponentitemtype;
try {
tccomponentitemtype = (TCComponentItemType) (session.getTypeComponent("Item"));
tccomponentitemtype.getNewID();
int i = 1;
while (tccomponentitemtype.find(newID) != null) {
i++;
// newID = oldItemIDs[0] + "-" + oldItemIDs[1] + "-"+ df.format(i);
newID = oldItemID + "-" + df.format(i);
}
} catch (TCException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return newID;
}
/**
* ListString
*
* @param list :List
* @return String
*/
public static String ListToString(List<?> list) {
StringBuffer sb = new StringBuffer();
if (list != null && list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == null || list.get(i) == "") {
continue;
}
// 如果值是list类型则调用自己
if (list.get(i) instanceof List) {
sb.append(ListToString((List<?>) list.get(i)));
sb.append(SEP1);
} else {
sb.append(list.get(i));
sb.append(SEP1);
}
}
}
return sb.toString();
}
// // 获取组的lov值
// public static String getGroupLov(TCSession session, String lovName, String key) {
// try {
// // 获取lov
// TCComponentListOfValues rtlistOfValues = TCLOVUtil.findLOVByName(session, "TM2_GROUP");
// ListOfValuesInfo rtlistOfValuesInfo = rtlistOfValues.getListOfValues();
// String[] groupName = rtlistOfValuesInfo.getStringListOfValues();
// String[] groupDisplayName = rtlistOfValuesInfo.getLOVDisplayValues();
// for (int i = 0; i < groupName.length; i++) {
// if (groupName[i].equals(key)) {
// return groupDisplayName[i];
// }
//
// }
// } catch (TCException e) {
// MessageBox.post("获取组的LOV错误请联系系统管理员", "错误!", MessageBox.ERROR);
// e.printStackTrace();
// }
// return "";
// }
/**
*
* @param session session
* @param fileName
* @param Filetype
* @return
*/
public static File getFile(TCSession session,String fileName,String Filetype) {
// TODO Auto-generated method stub
try {
TCPreferenceService service = session.getPreferenceService();
String[] modelFiles = service.getStringValues("ML_Doc_Teamplate");
if (modelFiles == null)
{
System.out.println("未找到首选项");
return null;
}
String itemId = "";
for (int i = 0; i < modelFiles.length; i++) {
if(modelFiles[i].split(":")[0].equals(fileName))
{
itemId = modelFiles[i].split(":")[1];
}
}
TCComponentItemType itemType = (TCComponentItemType) session.getTypeComponent("Item");
TCComponentItem fileItem = itemType.find(itemId);
TCComponentDataset dat = null;
TCComponentItemRevision fileItemLastRev = getLastItemRevision(fileItem);
TCComponent[] comps = fileItemLastRev.getReferenceListProperty("IMAN_specification");
System.out.println("count =" + comps == null ? "null"
: comps.length);
// 遍历TC_Attaches关系下的所有对象
for (TCComponent compt : comps) {
// 获取对象类型
String type = compt.getType();
System.out.println(" TYPE = " + type);
// 判断类型
if (type.equals(type)) {
dat = (TCComponentDataset)compt;
}
}
TCComponentTcFile[] tcFile = dat.getTcFiles();
if(tcFile != null && tcFile.length == 0)
{
System.out.println("未找到配置文件");
}
else
{
return tcFile[0].getFmsFile();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
/**
*
*
* @param item
* @return
*/
public static TCComponentItemRevision getLastItemRevision(TCComponentItem item) {
// TODO Auto-generated method stub
try {
TCComponentItemRevision[] items = item.getReleasedItemRevisions();
int revId = 0;
TCComponentItemRevision itemRevision = null;
for (int i = 0; i < items.length; i++) {
String revisionId = items[i].getStringProperty("item_revision_id");
if (letterToNumber(revisionId) >= revId) {
itemRevision = items[i];
revId = letterToNumber(revisionId);
}
}
return itemRevision;
} catch (TCException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
// 字母转数字 A-Z 1-26
public static int letterToNumber(String letter) {
int length = letter.length();
int num = 0;
int number = 0;
for (int i = 0; i < length; i++) {
char ch = letter.charAt(length - i - 1);
num = (int) (ch - 'A' + 1);
num *= Math.pow(26, i);
number += num;
}
return number;
}
/**
* LOVLOV
*
* @param tcsession
* @param s
* @return
*/
/**
* LOV KeyLOV
*
* @param tcsession
* @param s
* @return
*/
public static String findLovValueByKey(TCSession tcsession, String s, String key) {
TCComponentListOfValues tccomponentlistofvalues = null;
String resultValue = null;
try {
TCComponentListOfValuesType tccomponentlistofvaluestype = (TCComponentListOfValuesType) tcsession
.getTypeComponent("ListOfValues");
TCComponentListOfValues atccomponentlistofvalues[] = tccomponentlistofvaluestype.find(s);
if (atccomponentlistofvalues != null && atccomponentlistofvalues.length > 0) {
tccomponentlistofvalues = atccomponentlistofvalues[0];
ListOfValuesInfo rtlistOfValuesInfo = tccomponentlistofvalues.getListOfValues();
String[] groupName = rtlistOfValuesInfo.getStringListOfValues();
String[] groupDisplayName = rtlistOfValuesInfo.getLOVDisplayValues();
for (int i = 0; i < groupName.length; i++) {
// resultMap.put(groupDisplayName[i],groupName[i]);
if (groupName[i].equals(key)) {
resultValue = groupDisplayName[i];
}
}
}
} catch (TCException tcexception) {
tccomponentlistofvalues = null;
}
return resultValue;
}
/**
*
*
* @param session session
* @param process
* @param processUser
* @param arctic
* @throws TCException
*/
public static void setProcess(TCSession session, TCComponentProcess process, String processUser, String arctic)
throws TCException {
TCUserService userservice = session.getUserService();
Object[] obj = new Object[3];
obj[0] = process;
obj[1] = processUser;
obj[2] = arctic;
userservice.call("DMU_Review_Process", obj);
}
/**
*
*
* @param session session
* @param process
* @param processUser
* @param arctic
* @throws TCException
*/
public static void setRemodelProcess(TCSession session, TCComponentProcess process, String processUser,
String arctic) throws TCException {
TCUserService userservice = session.getUserService();
Object[] obj = new Object[3];
obj[0] = process;
obj[1] = processUser;
obj[2] = arctic;
userservice.call("Create_Remodel_Process", obj);
}
/**
*
*
* @param prefName
* @return
*/
public static String getPrefStr(String prefName) {
AbstractAIFApplication app = AIFUtility.getCurrentApplication();
TCSession session = (TCSession) app.getSession();
TCPreferenceService service = session.getPreferenceService();
String str = service.getString(TCPreferenceService.TC_preference_site, prefName);
if (str == null) {
str = new String("");
}
return str;
}
/***
*
*
* @param session
* @param preferenceName
* @return
*/
public static String[] getPreferenceValues(String preferenceName) {
AbstractAIFApplication app = AIFUtility.getCurrentApplication();
TCSession session = (TCSession) app.getSession();
if (preferenceName == null || session == null) {
System.out.println("");
return null;
}
String[] values = null;
TCPreferenceService service = session.getPreferenceService();
values = service.getStringArray(TCPreferenceService.TC_preference_site, preferenceName);
String[] resultValues = new String[values.length];
for (int i = 0; i < values.length; i++) {
if (values[i].indexOf("\\n") >= 0) {
resultValues[i] = values[i].replace("\\n", "\n");
} else {
resultValues[i] = values[i];
}
}
return resultValues;
}
/***
*
*
* @param session
* @param preferenceName
* @return
*/
public static String getPreferenceValue(String preferenceName) {
AbstractAIFApplication app = AIFUtility.getCurrentApplication();
TCSession session = (TCSession) app.getSession();
if (preferenceName == null || session == null) {
System.out.println("");
return null;
}
TCPreferenceService service = session.getPreferenceService();
return service.getString(TCPreferenceService.TC_preference_site, preferenceName);
}
public static void setByPass(boolean val,TCSession session) {
try {
TCUserService userservice = session.getUserService();
userservice.call(val ? "CONNOR_open_bypass" : "CONNOR_close_bypass", new Object[] { "" });
System.out.println(val ? "Open Bypass" : "Close Bypass");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void openByPass(TCSession session) throws TCException {
TCUserService userservice = session.getUserService();
Object[] obj = new Object[1];
obj[0] = "origin";
userservice.call("CONNOR_open_bypass", obj);
}
public static void closeByPass(TCSession session) throws TCException {
TCUserService userservice = session.getUserService();
Object[] obj = new Object[1];
obj[0] = "origin";
userservice.call("CONNOR_close_bypass", obj);
}
public static void setProperty(TCSession session,TCComponent[] items,String propname,String propvalue) throws TCException {
TCUserService userservice = session.getUserService();
Object[] obj = new Object[3];
obj[0] = items;
obj[1] = propname;
obj[2] = propvalue;
userservice.call("connor_set_prop_value", obj);
}
/***
* webService
*
* @param codeRemark ID
* @param rev
* @param propList
*/
/***
* webService
*
* @param codeRemark UID
*/
/***
* @param matnr
* @param ddlx
* @param type
* @return id
*/
public static String getClassficationId(String matnr, String ddlx, String type) {
// String classId = "jlcs01010101";
String classId = "";
if (ddlx.equals("车身") || ddlx.equals("KD")) {
String[] values = getPreferenceValues("JL_number_to_className");
String className = null;
for (String s : values) {
String[] split = s.split("=");
if (split[0].equals(matnr)) {
className = split[1];
break;
}
}
String[] values2 = getPreferenceValues("JL_name_to_id");
// split[1]--历史split[2]--流程 split[3]--废弃
for (String t : values2) {
String[] split = t.split("=");
if (split[0].equals(className)) {
if (type.equals("历史订单")) {
classId = split[1];
} else if (type.equals("流程中订单")) {
classId = split[2];
} else if (type.equals("废弃订单")) {
classId = split[3];
}
}
}
} else if (ddlx.equals("配件")) {
classId = "jlcs01010201";
String name = matnr.substring(0, 2) + "配件";
String[] values = getPreferenceValues("JL_name_to_id");
for (String t : values) {
String[] split = t.split("=");
if (split[0].equals(name)) {
if (type.equals("历史订单")) {
classId = split[1];
} else if (type.equals("流程中订单")) {
classId = split[2];
} else if (type.equals("废弃订单")) {
classId = split[3];
}
}
}
}
return classId;
}
/**
* LOV
*
* @param icsD
* @return
*/
public static String getClassDisplayableValue(String value, ICSPropertyDescription icsD) {
String result = "";
ICSKeyLov lov1 = icsD.getFormat().getKeyLov();
if (lov1 != null) {
String[] keys = lov1.getKeys();
for (String key : keys) {
if (value.equals(key)) {
result = lov1.getValueOfKey(key);
return result;
}
}
}
return result;
}
public static boolean isDouble(String value) {
try {
Double.parseDouble(value);
return true;
} catch (Exception e) {
// TODO: handle exception
return false;
}
}
/***
*
*
* @param session session
* @param value
* @param userId ID
* @return
*/
public static boolean havePrivilege(TCSession session, String commandName, String userId) {
TCPreferenceService service = session.getPreferenceService();
String[] values = service.getStringArray(TCPreferenceService.TC_preference_site, "JL_User_Rights");
if (values == null || values.length == 0) {
MessageBox.post("请配置首选项(管理权限)!请联系管理员", "错误", MessageBox.ERROR);
return false;
}
for (String value : values) {
// value = commandName + "——" + userId
String[] split = value.split("——");
if (split[0].equals(commandName)) {
if (split.length == 1) {
return true;
} else {
if (split[1].indexOf(userId) >= 0) {
return true;
} else {
return false;
}
}
}
}
return false;
}
public static int getCount(String mainStr, String subStr) {
int minLength = mainStr.length();
int subLength = subStr.length();
int count = 0;
int index = 0;
if (minLength >= subLength) {
while ((index = mainStr.indexOf(subStr, index)) != -1) {
count++;
index += subLength;
}
return count;
}
return 0;
}
/**
*
*
* @param session
* @param item
* @param fileName
* @param tcResource
* @param isDelete
* @param isReplace
*/
public static void setExcelToItem(TCSession session, TCComponentItemRevision item,String fileName, String tcResource,
boolean isDelete,boolean isReplace) {
try {
String as1[] = { tcResource };// 文件的物理路径
String as2[] = { "excel" };
String as3[] = { "MSExcelX" };
String as4[] = { "Plain" };
TCComponentDatasetType tccomponentDatasetType = (TCComponentDatasetType) session
.getTypeComponent("Dataset");
TCComponentDataset tccomponentDataset = tccomponentDatasetType.create(fileName, "excel", "MSExcelX");
tccomponentDataset.setFiles(as1, as3, as4, as2);
//是否替換
if(isReplace)
{
AIFComponentContext[] zyzdsChildrens = item.getChildren();
TCComponentItemRevision zyzdsRev = item;
for (AIFComponentContext zyzdsChildren : zyzdsChildrens) {
if ("MSExcelX".equals(zyzdsChildren.getComponent().getType())) {
TCComponentDataset dateSet = (TCComponentDataset) zyzdsChildren.getComponent();
zyzdsRev.remove("IMAN_specification", dateSet);
dateSet.delete();
}
}
}
item.add("IMAN_specification", tccomponentDataset);
if (isDelete) {
new File(tcResource).delete();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Object getTCPropertyValue(TCComponent item,String propertyName)
{
Object result = "";
try {
TCProperty tcProperty = item.getTCProperty(propertyName);
if(tcProperty == null)
{
System.out.println("未获取属性:"+propertyName);
return result;
}
switch (tcProperty.getPropertyType()) {
case TCProperty.PROP_double:
result = tcProperty.getDoubleValue();
break;
case TCProperty.PROP_int:
result = tcProperty.getIntValue();
break;
case TCProperty.PROP_string:
result = tcProperty.getStringValue();
break;
case TCProperty.PROP_date:
result = tcProperty.getDateValue();
break;
default:
break;
}
} catch (TCException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public static void setTCPropertyValue(TCComponent item,String propertyName,Object value)
{
try {
TCProperty tcProperty = item.getTCProperty(propertyName);
switch (tcProperty.getPropertyType()) {
case TCProperty.PROP_double:
if(value instanceof Double)
{
tcProperty.setDoubleValue((double) value);
}
else
{
tcProperty.setDoubleValue(Double.parseDouble(value.toString()));
}
break;
case TCProperty.PROP_int:
if(value instanceof Integer)
{
tcProperty.setIntValue((int) value);
}
else
{
tcProperty.setIntValue(Integer.parseInt(value.toString()));
}
break;
case TCProperty.PROP_string:
tcProperty.setStringValue(value.toString());
break;
case TCProperty.PROP_date:
if(value instanceof Date)
{
tcProperty.setDateValue((Date) value);
}
else
{
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-M-dd HH:mm");
tcProperty.setDateValue(sdf.parse(value.toString()));
}
break;
default:
break;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* ITEM
*
* @param itemList
* @return
*/
/**
*
*
* @param item
* @param name
* @return
*/
public static TCComponentFolder getParentFolder(TCComponentItem item,
String name) {
TCComponentFolder folder = null;
try {
AIFComponentContext[] comtexts = item.whereReferenced();
if (comtexts != null) {
for (int i = 0; i < comtexts.length; i++) {
if (comtexts[i].getComponent() instanceof TCComponentFolder) {
String nameT = ((TCComponentFolder) comtexts[i]
.getComponent())
.getStringProperty("object_name");
if (name.equals("工艺图纸") && nameT.equals("工艺图纸")) {
folder = (TCComponentFolder) comtexts[i]
.getComponent();
}
else if(nameT.equals(name))
{
folder = (TCComponentFolder) comtexts[i]
.getComponent();
}
}
}
}
} catch (TCException e) {
e.printStackTrace();
}
return folder;
}
/**
*
*
* @param session
* @return
*/
/**
* SOAITEM
*
* @param session
*
* @param itemID
* ID
* @param itemRev
*
* @param itemType
*
* @param itemName
*
* @param itemDesc
*
* @param unit
*
* @param itemPropMap
* ITEM
* @param itemRevPropMap
*
* @param itemRevMasterPropMap
*
*/
public static void CreateProcess(TCSession session,TCComponent target,String processName) throws TCException {
try {
TCComponentProcessType processType = (TCComponentProcessType) session.getTypeComponent("Job");
TCComponentTaskTemplateType taskTemplateType = (TCComponentTaskTemplateType) session.getTypeComponent("EPMTaskTemplate");
TCComponentTaskTemplate taskTemplate = taskTemplateType.find(processName, TCComponentTaskTemplate.PROCESS_TEMPLATE_TYPE);
if (taskTemplate == null) {
return;
}
// 创建一个流程 流程名称、描述、流程模板、目标对象、附件数
String name = target.getProperty("object_string");
processType.create(processName + "" + name, "", taskTemplate, new TCComponent[] { target }, new int[] { 1 });
} catch (TCException e) {
e.printStackTrace();
throw e;
}
}
public static void CreateProcess(TCSession session,TCComponent[] targets,int[] type,String processName) throws TCException {
try {
TCComponentProcessType processType = (TCComponentProcessType) session.getTypeComponent("Job");
TCComponentTaskTemplateType taskTemplateType = (TCComponentTaskTemplateType) session.getTypeComponent("EPMTaskTemplate");
TCComponentTaskTemplate taskTemplate = taskTemplateType.find(processName, TCComponentTaskTemplate.PROCESS_TEMPLATE_TYPE);
if (taskTemplate == null) {
return;
}
// 创建一个流程 流程名称、描述、流程模板、目标对象、附件数
String name = targets[0].getProperty("object_string");
processType.create(processName + "" + name, "", taskTemplate, targets, type);
} catch (TCException e) {
e.printStackTrace();
throw e;
}
}
/**
* EXCEL
*
* @param File excel_file
* @return List<DocDirectoryBean>
* @throws IOException
* @throws FileNotFoundException
*/
/**
* EXCEL
*
* @param File excel_file
* @return List<DocDirectoryBean>
* @throws IOException
* @throws FileNotFoundException
*/
/**
* EXCEL
*
* @param File excel_file
* @return List<DocDirectoryBean>
* @throws IOException
* @throws FileNotFoundException
*/
}
Loading…
Cancel
Save