commit 79ab5ea1301cf3e7169eee7b3464f562856385f3 Author: lijh Date: Tue Mar 10 11:34:21 2026 +0800 first commit diff --git a/.classpath b/.classpath new file mode 100644 index 0000000..a7220b2 --- /dev/null +++ b/.classpath @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/.project b/.project new file mode 100644 index 0000000..939c74c --- /dev/null +++ b/.project @@ -0,0 +1,28 @@ + + + com.connor.jd + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..9f6ece8 --- /dev/null +++ b/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.release=disabled +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/META-INF/MANIFEST.MF b/META-INF/MANIFEST.MF new file mode 100644 index 0000000..e584ab8 --- /dev/null +++ b/META-INF/MANIFEST.MF @@ -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 diff --git a/bin/.gitignore b/bin/.gitignore new file mode 100644 index 0000000..c2d9872 --- /dev/null +++ b/bin/.gitignore @@ -0,0 +1 @@ +/com/ diff --git a/build.properties b/build.properties new file mode 100644 index 0000000..0a4239b --- /dev/null +++ b/build.properties @@ -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 diff --git a/icons/sample.png b/icons/sample.png new file mode 100644 index 0000000..02c4b79 Binary files /dev/null and b/icons/sample.png differ diff --git a/icons/sample@2x.png b/icons/sample@2x.png new file mode 100644 index 0000000..c1224d1 Binary files /dev/null and b/icons/sample@2x.png differ diff --git a/lib/dom4j-2.1.1.jar b/lib/dom4j-2.1.1.jar new file mode 100644 index 0000000..cda47db Binary files /dev/null and b/lib/dom4j-2.1.1.jar differ diff --git a/lib/mssql-jdbc-7.0.0.jre8.jar b/lib/mssql-jdbc-7.0.0.jre8.jar new file mode 100644 index 0000000..9f68c4d Binary files /dev/null and b/lib/mssql-jdbc-7.0.0.jre8.jar differ diff --git a/lib/ojdbc8.jar b/lib/ojdbc8.jar new file mode 100644 index 0000000..8517287 Binary files /dev/null and b/lib/ojdbc8.jar differ diff --git a/lib/poi-4.0.1.jar b/lib/poi-4.0.1.jar new file mode 100644 index 0000000..be09297 Binary files /dev/null and b/lib/poi-4.0.1.jar differ diff --git a/lib/poi-examples-3.7-20101029.jar b/lib/poi-examples-3.7-20101029.jar new file mode 100644 index 0000000..914243d Binary files /dev/null and b/lib/poi-examples-3.7-20101029.jar differ diff --git a/lib/poi-ooxml-3.7-20101029.jar b/lib/poi-ooxml-3.7-20101029.jar new file mode 100644 index 0000000..5f36eb4 Binary files /dev/null and b/lib/poi-ooxml-3.7-20101029.jar differ diff --git a/lib/poi-ooxml-schemas-3.7-20101029.jar b/lib/poi-ooxml-schemas-3.7-20101029.jar new file mode 100644 index 0000000..82282b5 Binary files /dev/null and b/lib/poi-ooxml-schemas-3.7-20101029.jar differ diff --git a/lib/swingx-1.6.1.jar b/lib/swingx-1.6.1.jar new file mode 100644 index 0000000..b0bcc87 Binary files /dev/null and b/lib/swingx-1.6.1.jar differ diff --git a/plugin - 副本.xml b/plugin - 副本.xml new file mode 100644 index 0000000..b4febfd --- /dev/null +++ b/plugin - 副本.xml @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugin.xml b/plugin.xml new file mode 100644 index 0000000..db90484 --- /dev/null +++ b/plugin.xml @@ -0,0 +1,52 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/com/connor/jd/derive/deriveCenterHandler.java b/src/com/connor/jd/derive/deriveCenterHandler.java new file mode 100644 index 0000000..f41e71f --- /dev/null +++ b/src/com/connor/jd/derive/deriveCenterHandler.java @@ -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ǰѡIJ + InterfaceAIFComponent target = app.getTargetComponent(); + if (target instanceof TCComponentItemRevision) { + try { + String[] value = session.getPreferenceService().getStringValues("JD_SERIVECENT"); + List list = new ArrayList<>(Arrays.asList(value)); + List typeList = new ArrayList<>(Arrays.asList(value)); + Map typeMap = new HashMap(); + 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; + } + +} diff --git a/src/com/connor/jd/derive/deriveMBOMHandler.java b/src/com/connor/jd/derive/deriveMBOMHandler.java new file mode 100644 index 0000000..f29e2fd --- /dev/null +++ b/src/com/connor/jd/derive/deriveMBOMHandler.java @@ -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ǰѡIJ + InterfaceAIFComponent target = app.getTargetComponent(); + if (target instanceof TCComponentItemRevision) { + try { + String[] value = session.getPreferenceService().getStringValues("JD_SERIVEMBOM"); + List list = new ArrayList<>(Arrays.asList(value)); + List typeList = new ArrayList<>(Arrays.asList(value)); + Map typeMap = new HashMap(); + 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; + } + +} + diff --git a/src/com/connor/jd/derive/deriveOpertion.java b/src/com/connor/jd/derive/deriveOpertion.java new file mode 100644 index 0000000..e6076f1 --- /dev/null +++ b/src/com/connor/jd/derive/deriveOpertion.java @@ -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); + //ItemidItemİ汾ţ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;i0) { + for(int j=0;j 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; + } + +} diff --git a/src/com/connor/jd/erp/erpIntegrationOpertaion.java b/src/com/connor/jd/erp/erpIntegrationOpertaion.java new file mode 100644 index 0000000..024685f --- /dev/null +++ b/src/com/connor/jd/erp/erpIntegrationOpertaion.java @@ -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); // ô洢̵IJ + 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 columnNames = new Vector(); + for (int column = 1; column <= columnCount; column++) { + columnNames.add(metaData.getColumnName(column)); + } + Vector> data = new Vector>(); + while (rs.next()) { + Vector row = new Vector(); + for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) { + row.add(rs.getObject(columnIndex)); + } + data.add(row); + } + return new DefaultTableModel(data, columnNames); + } +} diff --git a/src/com/connor/jd/handlers/SampleHandler.java b/src/com/connor/jd/handlers/SampleHandler.java new file mode 100644 index 0000000..dadf88c --- /dev/null +++ b/src/com/connor/jd/handlers/SampleHandler.java @@ -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; + } +} diff --git a/src/com/connor/jingdiao/handlers/CodeApplyHandler.java b/src/com/connor/jingdiao/handlers/CodeApplyHandler.java new file mode 100644 index 0000000..874c383 --- /dev/null +++ b/src/com/connor/jingdiao/handlers/CodeApplyHandler.java @@ -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 target = new ArrayList<>(); + ArrayList 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 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; + } +} diff --git a/src/com/connor/jingdiao/handlers/CodeApplyOperation.java b/src/com/connor/jingdiao/handlers/CodeApplyOperation.java new file mode 100644 index 0000000..97e708e --- /dev/null +++ b/src/com/connor/jingdiao/handlers/CodeApplyOperation.java @@ -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 revs; + private ArrayList options; + private StringBuilder msg; + private HashMap classmap; + + public CodeApplyOperation(TCSession session, ArrayList revs, ArrayList 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 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> 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> 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() list; + private HashMap map; + +// public DrawingNoApplyDialog(TCSession session, String tables[], String[] options, String[] sqlOptions, InterfaceAIFComponent[] targets) throws Exception { + public DesignToPartDialog(TCSession session, ArrayList 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 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 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); + } + } +} \ No newline at end of file diff --git a/src/com/connor/jingdiao/handlers/DesignToPartHandler.java b/src/com/connor/jingdiao/handlers/DesignToPartHandler.java new file mode 100644 index 0000000..77f97f6 --- /dev/null +++ b/src/com/connor/jingdiao/handlers/DesignToPartHandler.java @@ -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 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; + } +} diff --git a/src/com/connor/jingdiao/handlers/DrawingNoApplyDialog.java b/src/com/connor/jingdiao/handlers/DrawingNoApplyDialog.java new file mode 100644 index 0000000..06c792a --- /dev/null +++ b/src/com/connor/jingdiao/handlers/DrawingNoApplyDialog.java @@ -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 list; + private HashMap map; + private Map ruleOpsMap; +// public DrawingNoApplyDialog(TCSession session, String tables[], String[] options, String[] sqlOptions, InterfaceAIFComponent[] targets) throws Exception { + public DrawingNoApplyDialog(TCSession session, ArrayList options, + InterfaceAIFComponent[] targets,Map 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 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 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 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> 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(" IJͼΪգ\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(" IJͼΪգ\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> 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); + } + } +} \ No newline at end of file diff --git a/src/com/connor/jingdiao/handlers/DrawingNoApplyHandler.java b/src/com/connor/jingdiao/handlers/DrawingNoApplyHandler.java new file mode 100644 index 0000000..89d0176 --- /dev/null +++ b/src/com/connor/jingdiao/handlers/DrawingNoApplyHandler.java @@ -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 ruleOpsMap = new HashMap(); + 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 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; + } +} diff --git a/src/com/connor/jingdiao/handlers/LoginIPSetDialog.java b/src/com/connor/jingdiao/handlers/LoginIPSetDialog.java new file mode 100644 index 0000000..94fa833 --- /dev/null +++ b/src/com/connor/jingdiao/handlers/LoginIPSetDialog.java @@ -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 l_user; + private DefaultListModel lm_user; + private JList l_ip; + private DefaultListModel 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 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> results = SqlUtil.getDBInfo(connection, sql); + for(HashMap 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; i1) + 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 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 list = new ArrayList<>(); + group = ""; + role = ""; + recycleNode(tree.getRootNode(), list, 0, true); + System.out.println("list:"+list.size()); + for(int i=0; i"+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 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 getSelectUsers() throws Exception {//TODO getSelectUsers + ArrayList list = new ArrayList<>(); + for (AIFTreeNode comp : tree.getSelectedNodes()) { + recycleNode(comp, list, 0, false); + } + + return list; + } + + private void recycleNode(AIFTreeNode comp, ArrayList 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 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 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 ipl; + private DefaultListModel ipm; + private HashMap 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 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 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 revlist; + private String[] mark; + private int mrow = -1; +// private HashMap map; +// private LinkedHashMap ruleOpsMap; + +// public DrawingNoApplyDialog(TCSession session, String tables[], String[] options, String[] sqlOptions, InterfaceAIFComponent[] targets) throws Exception { + public StandardDialog(TCSession session, TCComponent[] models, TCComponentTask task, LinkedHashMap 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 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 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 types = new ArrayList<>(); + for(Object e : typeEs) { + types.add(((Element)e).getText()); + } + List regolaEs = condizione.element("regola").elements(); + HashMap 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 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; i1) +// cell.setCellStyle(getCell(sourceRow, col).getCellStyle()); + return cell; + } + + public class TextAreaRenderer extends JTextArea implements TableCellRenderer { + private static final long serialVersionUID = 1L; +// ArrayList 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.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()); + } + } + } +} \ No newline at end of file diff --git a/src/com/connor/jingdiao/handlers/StandardHandler.java b/src/com/connor/jingdiao/handlers/StandardHandler.java new file mode 100644 index 0000000..8dc7429 --- /dev/null +++ b/src/com/connor/jingdiao/handlers/StandardHandler.java @@ -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 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; + } +} diff --git a/src/com/connor/jingdiao/handlers/Test.java b/src/com/connor/jingdiao/handlers/Test.java new file mode 100644 index 0000000..828d10a --- /dev/null +++ b/src/com/connor/jingdiao/handlers/Test.java @@ -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 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> 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(" IJͼΪգ\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(" IJͼΪգ\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> 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; + } + +// } + } + +} diff --git a/src/com/connor/jingdiao/handlers/WlbmApplyDialog.java b/src/com/connor/jingdiao/handlers/WlbmApplyDialog.java new file mode 100644 index 0000000..0dfab05 --- /dev/null +++ b/src/com/connor/jingdiao/handlers/WlbmApplyDialog.java @@ -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 list; + private HashMap map; + private HashMap 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(); + 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 props = new ArrayList<>(); +// String[] tableHeader = new String[] { "", "itemID", "", "汾", "ӹ", "Ʒ", "", "", "", "ͼֽ", "ͼ" }; + String[] tableHeader = new String[tables.length + 1]; + tableHeader[0] = ""; + + for(int i=0;i"+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 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> results = SqlUtil.getDBInfo(conn, "select SERIALNUMBER from JD_CODE_RULE where CODEKEY='"+id+"'"); + if (results.size() == 0) { + + List> 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> results = SqlUtil.getDBInfo(conn, "select SERIALNUMBER from JD_CODE_RULE where CODEKEY='"+id+"'"); + if (results.size() == 0) { + + List> 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(" IJϱΪգ\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(" IJϱΪգ\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> 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(); + } + }); + } + +} diff --git a/src/com/connor/jingdiao/handlers/WlbmApplyHandler.java b/src/com/connor/jingdiao/handlers/WlbmApplyHandler.java new file mode 100644 index 0000000..de5e032 --- /dev/null +++ b/src/com/connor/jingdiao/handlers/WlbmApplyHandler.java @@ -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 typeList = new ArrayList(); + 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; + } + +} diff --git a/src/com/connor/jingdiao/util/SqlTIUtil.java b/src/com/connor/jingdiao/util/SqlTIUtil.java new file mode 100644 index 0000000..8f9e28a --- /dev/null +++ b/src/com/connor/jingdiao/util/SqlTIUtil.java @@ -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> getDBInfo(Connection connection, String sql) throws Exception { + if (connection == null) { + throw new Exception("޷ȡݿϢ"); + } + + List> vecData = new ArrayList>(); + 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 dataTable = new HashMap(); + + 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 getArrayDBInfo(Connection connection, String sql) throws Exception { + if (connection == null) { + throw new Exception("޷ȡݿϢ"); + } + + List vecData = new LinkedList(); + 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; + } +} diff --git a/src/com/connor/jingdiao/util/SqlUtil.java b/src/com/connor/jingdiao/util/SqlUtil.java new file mode 100644 index 0000000..2f602ab --- /dev/null +++ b/src/com/connor/jingdiao/util/SqlUtil.java @@ -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> getDBInfo(Connection connection, String sql) throws Exception { + if (connection == null) { + throw new Exception("޷ȡݿϢ"); + } + + ArrayList> vecData = new ArrayList>(); + 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 dataTable = new HashMap(); + + 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 getArrayDBInfo(Connection connection, String sql) throws Exception { + if (connection == null) { + throw new Exception("޷ȡݿϢ"); + } + + List vecData = new LinkedList(); + 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; + } +} diff --git a/src/com/connor/jingdiao/util/TCUtil.java b/src/com/connor/jingdiao/util/TCUtil.java new file mode 100644 index 0000000..c85942f --- /dev/null +++ b/src/com/connor/jingdiao/util/TCUtil.java @@ -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||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||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 getlovValues(TCSession session, String lovName) throws TCException { + LinkedHashMap lovVal = new LinkedHashMap(); + 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 Keys, Vector 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 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 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 executeToMap(InputStream in){ + System.out.println("Read properties file"); + try { + BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8")); + String line = null; + Map 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 getChildren(TCComponent parent, String relation, String name) throws Exception { + Vector 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); + } +} diff --git a/src/com/connor/ml/tcm/outfile/ML_010/BomValBean.java b/src/com/connor/ml/tcm/outfile/ML_010/BomValBean.java new file mode 100644 index 0000000..9fd4817 --- /dev/null +++ b/src/com/connor/ml/tcm/outfile/ML_010/BomValBean.java @@ -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 + "]"; + } + + + +} diff --git a/src/com/connor/ml/tcm/outfile/ML_010/DbomTransitionToEbomCommand.java b/src/com/connor/ml/tcm/outfile/ML_010/DbomTransitionToEbomCommand.java new file mode 100644 index 0000000..acc2a91 --- /dev/null +++ b/src/com/connor/ml/tcm/outfile/ML_010/DbomTransitionToEbomCommand.java @@ -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 preList = new ArrayList(); + 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 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 dtypeList = new ArrayList(); + Map DETypeMap = new HashMap(); + 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> bomValMap = new HashMap>(); + + /** + * ȫ + * + * @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> bomValMap = new HashMap>(); + 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 list = bomValMap.get(itemRevision); + list.add(bean); + }else { + List list = new ArrayList(); + 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 list = bomValMap.get(itemRevision); + list.add(bean); + }else { + List list = new ArrayList(); + 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 list = bomValMap.get(itemRevision); + list.add(bean); + }else { + List list = new ArrayList(); + 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 list = bomValMap.get(itemRevision); +// list.add(bean); +// }else { +// List list = new ArrayList(); +// 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 list = bomValMap.get(itemRevision); +// list.add(bean); +// }else { +// List list = new ArrayList(); +// 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(); + } + } +} diff --git a/src/com/connor/ml/tcm/outfile/ML_010/DbomTransitionToEbomDialog.java b/src/com/connor/ml/tcm/outfile/ML_010/DbomTransitionToEbomDialog.java new file mode 100644 index 0000000..570fc7b --- /dev/null +++ b/src/com/connor/ml/tcm/outfile/ML_010/DbomTransitionToEbomDialog.java @@ -0,0 +1,1364 @@ +package com.connor.ml.tcm.outfile.ML_010; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Font; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.ListSelectionModel; +import javax.swing.tree.TreePath; +import com.teamcenter.rac.kernel.TCAccessControlService; + +import org.jdesktop.swingx.JXTable; +import org.jdesktop.swingx.decorator.HighlighterFactory; +import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode; + +import com.connor.ml.tcm.outfile.bean.NodeBean; +import com.connor.ml.tcm.outfile.util.MethodUtil; +import com.teamcenter.rac.aif.kernel.AIFComponentContext; +import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; +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.TCComponentItem; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCComponentItemType; +import com.teamcenter.rac.kernel.TCException; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; +//import com.teamcenter.soa.exceptions.NotLoadedException; + +public class DbomTransitionToEbomDialog extends JFrame implements ActionListener, MouseListener { + //AbstractAIFDialog + + /** + * + */ + private static final long serialVersionUID = 1L; + private TCSession session; + private InterfaceAIFComponent comp; + //private InterfaceAIFComponent comp;//ȡѡеĶ + + private List isNotEditableRow = new ArrayList(); + //private TCComponentBOMLine bomLine; + private DefaultMutableTreeTableNode node; + + private String[] header = new String[] { "DBOM", "EBOM","ѡ", "EBOMID", "","","״̬","Ӧڵ"}; + + private JPanel titlePanel; + private JLabel titleLabel; + private JTreeTable table; + private JTreeTableModel map; + + private JPanel rootPanel; + private JCheckBox choose; + private JButton searchButton; + private JButton okButton; + private JButton celButton; + private JButton refreshButton; +// private Map> bomValMap; + private ArrayList preList; + private StringBuilder builder = new StringBuilder(""); +// private ProcessBarDialog progress; + private Boolean falg1 = true; + private TCAccessControlService acs; + private TCComponent[] user; + private StringBuilder msg2; + private List items = new ArrayList(); + + Map>> bomStructMap = + new HashMap>>(); + TCComponentBOMLine resultTopline = null; + + TCComponentItem topLineItem = null; + + private HashMap> backMap; + private boolean search; + private String[][] tags; + private HashMap headMap; + private ArrayList dList; + + public DbomTransitionToEbomDialog(InterfaceAIFComponent comp, TCSession session, DefaultMutableTreeTableNode node, + ArrayList preList, ProcessBarDialog progress, String[] header) { + // Auto-generated constructor stub +// super(false); + this.session = session; + this.comp = comp; + this.node = node; + this.preList = preList; +// this.progress = progress; + this.header = header; + + acs = session.getTCAccessControlService(); + user = new TCComponent[]{ session.getUser(), session.getGroup(), session.getRole() }; + msg2 = new StringBuilder(""); +// this.bomValMap = bomValMap; +// System.out.println("bomValMap==>"+bomValMap.toString()); + init(); + } + + private void init() { + // Auto-generated method stub + this.setTitle("DBOMתEBOM"); + this.setPreferredSize(new Dimension(800, 600)); + // ʼⲿֿؼ + this.titlePanel = new JPanel(); + this.titleLabel = new JLabel("DBOMתEBOM"); + this.titleLabel.setFont(new Font("", 1, 18)); + this.titlePanel.add(titleLabel); + + JPanel panel = new JPanel(); + panel.add(this.titlePanel,BorderLayout.NORTH); + + getJTreeTable(); + + this.table.addMouseListener(this); +// Adapter adapter = new Adapter(table); + + this.rootPanel = new JPanel(new FlowLayout()); + this.choose = new JCheckBox("ѡ/ȡ"); + this.searchButton = new JButton("ɸѡ"); + this.okButton = new JButton("ȷ"); + this.celButton = new JButton("ȡ"); + this.refreshButton = new JButton("ˢ"); + + this.rootPanel.add(choose); + this.rootPanel.add(searchButton); + this.rootPanel.add(okButton); + this.rootPanel.add(celButton); + this.rootPanel.add(refreshButton); + //this.rootPanel.add(celValueButton); + + // + this.createActionEvent(); + this.setLayout(new BorderLayout()); + // this.add(centerPanel, BorderLayout.NORTH); + this.add(panel, BorderLayout.NORTH); + this.add(new JScrollPane(this.table), BorderLayout.CENTER); + // dialog.add(tablePanel, BorderLayout.CENTER); + this.add(rootPanel, BorderLayout.SOUTH); + //this.setAlwaysOnTop(true); + this.pack(); + this.setLocationRelativeTo(null); + this.setVisible(true); +// this.setAlwaysOnTop(true); + } + + //Ӽ + private void createActionEvent() { + this.okButton.addActionListener(this); + this.celButton.addActionListener(this); + this.refreshButton.addActionListener(this); + //this.celValueButton.addActionListener(this); + } + + //Jtableͨ÷ + private void getJTreeTable() { +// int simpleLen = 100; +// int totleLen = 1500; + if (table == null) { + this.map = new JTreeTableModel(this.node, header); + this.map.setIsNotEditableRow(this.isNotEditableRow); + //map.setColumnIdentifiers(titleNames); + + table = new JTreeTable(map); + table.setIsNotEditableRow(this.isNotEditableRow); + table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); + // partsTable.setRowHeight(1, 50); + // partsTable.setRowHeight(2, 100); + table.setRowHeight(30); + table.expandAll(); // չȫڵ + // +// partsTable.HiddenCell(0); + + table.getColumnModel().getColumn(NodeBean.DBOM).setPreferredWidth(188); // õһп + table.getColumnModel().getColumn(NodeBean.EBOM).setPreferredWidth(150); // õڶп + table.getColumnModel().getColumn(NodeBean.LABEL).setPreferredWidth(55); // õп + + table.setHighlighters(HighlighterFactory.createSimpleStriping()); + +// if (simpleLen * header.length >= totleLen) { +// for (int i = 0; i < header.length; i++) { +// table.getColumnModel().getColumn(i).setPreferredWidth(simpleLen); +// } +// table.setAutoResizeMode(JXTable.AUTO_RESIZE_OFF);//AUTO_RESIZE_OFF +// } else { +// table.setAutoResizeMode(JXTable.AUTO_RESIZE_OFF);//AUTO_RESIZE_NEXT_COLUMN +// } + table.setAutoResizeMode(JXTable.AUTO_RESIZE_OFF); + } + backMap = new HashMap<>(); + backMap(node);//(DefaultMutableTreeTableNode)node.getChildAt(0) + } + /** + * ṹ + * + * @param node ڵ + */ + private void backMap(DefaultMutableTreeTableNode node) { + ArrayList list = new ArrayList<>(); + for (int i = 0; i < node.getChildCount(); i++) { + DefaultMutableTreeTableNode tableNode = (DefaultMutableTreeTableNode)node.getChildAt(i); + list.add(tableNode); + backMap(tableNode); + } + backMap.put(node, list); + } + + @Override + public void mouseClicked(MouseEvent e) { + // Auto-generated method stub + if(e.getClickCount() == 2) { + TreePath treePath = table.getPathForLocation(e.getX(),e.getY()); + if (treePath != null) { + DefaultMutableTreeTableNode node = (DefaultMutableTreeTableNode) treePath.getLastPathComponent(); + NodeBean nodeBean = (NodeBean) node.getUserObject(); + String itemId = nodeBean.getDbom(); + if(itemId != null && !itemId.isEmpty()) { + try { + //ȡ + TCComponentItemType itemType = (TCComponentItemType) this.session.getTypeComponent("Item"); + TCComponentItem item = itemType.findItems(itemId.split("-")[0])[0]; + + com.teamcenter.rac.common.Activator.getDefault() + .openPerspective("com.teamcenter.rac.ui.perspectives.navigatorPerspective"); + com.teamcenter.rac.common.Activator.getDefault() + .openComponents("com.teamcenter.rac.ui.perspectives.navigatorPerspective", + new InterfaceAIFComponent[] { item }); + } catch (Exception e2) { + // : handle exception + e2.printStackTrace(); + } + } + } + } else if (e.getClickCount() > 0) { + // ѡ + int selectColumn = table.getTableHeader().columnAtPoint(e.getPoint()); + + if(selectColumn != NodeBean.LABEL) { + return; + } + TreePath treePath = table.getPathForLocation(e.getX(),e.getY()); + if (treePath != null) { + DefaultMutableTreeTableNode node = (DefaultMutableTreeTableNode) treePath.getLastPathComponent(); + NodeBean nodeBean = (NodeBean) node.getUserObject(); + if(nodeBean.getEbom().isEmpty()) + return; + try { + DefaultMutableTreeTableNode parentNode = (DefaultMutableTreeTableNode) node.getParent(); + //TODO ѡ¼ + if(nodeBean.getLabel().equals("0")) { + String status = nodeBean.getRefreshStatus(); + boolean access = !acs.checkAccessorsPrivilege(user, nodeBean.getTcComponent(), "WRITE") + || !status.equals("Է") && !status.equals("") && !status.isEmpty(); + if(access && getChildRefresh(parentNode, false)) { + MessageBox.post("²ѹѡϲ㲻ѡѷûȨ޶", "", MessageBox.ERROR); + return; + } + if(getTopRefresh(node)) { + MessageBox.post("ϲѹѡȨ޵Ͳ㲻ѡ", "", MessageBox.ERROR); + return; + } + //жͬһǷѹѡ + if(parentNode != null) { +// for (int i = 0; i < parentNode.getChildCount(); i++) { +// DefaultMutableTreeTableNode childNode = (DefaultMutableTreeTableNode) parentNode.getChildAt(i); + for (DefaultMutableTreeTableNode childNode : backMap.get(parentNode)) { + NodeBean childBean = (NodeBean) childNode.getUserObject(); + if(childBean.getLabel().equals("1") && !childBean.getEbom().isEmpty() && !nodeBean.getEbom().isEmpty()) { + MessageBox.post(this, "ͬһ㼶ֻѡһ", "", MessageBox.ERROR); + return; + } + } + } + nodeBean.setLabel("1"); + if(!access && parentNode != null) + autoCheck(parentNode, "1"); + //isHaveBom(node, nodeBean.getEbomId(), "1", itemType); + }else if(nodeBean.getLabel().equals("1")) { + nodeBean.setLabel("0"); + if(parentNode != null) + autoCheck(parentNode, "0"); + //isHaveBom(node, nodeBean.getEbomId(), "0", itemType); + } + this.repaint(); +// Robot robot = new Robot(); +// robot.keyPress(KeyEvent.VK_TAB); +// robot.keyRelease(KeyEvent.VK_TAB); + } catch (Exception e2) { + // : handle exception + e2.printStackTrace(); + MessageBox.post("" + e2, "", MessageBox.ERROR); + } + } + } + } + + /*** + * жϼǷѡ + * @param node + * @return + * @throws TCException + */ +// private void isHaveBom(DefaultMutableTreeTableNode node,String parentID,String status,TCComponentItemType itemType) +// throws Exception { +// TCComponentItem item = itemType.findItems(parentID)[0]; +// TCComponentItemRevision itemRevision = item.getLatestItemRevision(); +// +// TCComponent[] tcComponents = itemRevision.getReferenceListProperty("view"); +// if(tcComponents.length > 0) +// { +// for (int ii = 0; ii < node.getParent().getChildCount(); ii++) { +// DefaultMutableTreeTableNode tableNode = (DefaultMutableTreeTableNode)node.getParent().getChildAt(ii); +// +// if(tableNode.getChildCount() > 0) +// { +// for (int i = 0; i < tcComponents.length; i++) { +// TCComponent childBomLine = tcComponents[i]; +// List haveItemID = new ArrayList(); +// for (int j = 0; j < tableNode.getChildCount(); j++) { +// String childItemId = childBomLine.getStringProperty("item_id"); +// NodeBean childNodeBean = (NodeBean) tableNode.getChildAt(j).getUserObject(); +// if(childItemId.equals(childNodeBean.getEbomId()) && !haveItemID.contains(childNodeBean.getEbomId())) +// { +// haveItemID.add(childNodeBean.getEbomId()); +// childNodeBean.setLabel(status); +// isHaveBom((DefaultMutableTreeTableNode)(tableNode.getChildAt(j)), childNodeBean.getEbomId(), status, itemType); +// } +// } +// } +// } +// } +// } +// } + + /*** + * жϼǷѡ + * @param node + * @return + */ +// private boolean getTop(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(); i++) { +// DefaultMutableTreeTableNode childNode = (DefaultMutableTreeTableNode) rootNode.getChildAt(i); +// NodeBean childBean = (NodeBean) childNode.getUserObject(); +// if(childBean.getLabel().equals("1") && !childBean.getEbom().isEmpty()) +// { +// //MessageBox.post("ϲ["+childBean.getEbom()+"]ѹѡͲ㲻ѡ", "", MessageBox.ERROR); +// return true; +// } +// } +// } +// } +// +// return result; +// } + + /*** + * жϼǷѡѷ + * @param node + * @return + */ + private boolean getTopRefresh(DefaultMutableTreeTableNode node) throws Exception { + 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(); i++) { + DefaultMutableTreeTableNode childNode = (DefaultMutableTreeTableNode) rootNode.getChildAt(i); + NodeBean childBean = (NodeBean) childNode.getUserObject(); + + if(childBean.getLabel().equals("1")) { + TCComponent tcComponent = childBean.getTcComponent(); +// String property = tcComponent.getProperty("j6_processtype"); + String status = childBean.getRefreshStatus(); + if(!status.equals("Է") && !status.equals("") && !status.isEmpty()) { + System.out.println("" + tcComponent); + result = true; + break; +// }else if(property != null && (property.equals("⹺") || property.equals("Э"))) { +// result = true; +// break; + }else if(!acs.checkAccessorsPrivilege(user, tcComponent, "WRITE")) { + System.out.println("Ȩ" + tcComponent); + result = true; + break; + } + }else{ + if(getTopRefresh(childNode)) { + result = true; + break; + } + } + } + } + } + + return result; + } + + /*** + * ж¼Ƿѡ + * @param node ڵ + * @param p Ƿ鵱ǰ + * @return ¼Ƿѡ + */ + private boolean getChildRefresh(DefaultMutableTreeTableNode node, boolean p) throws Exception { + if(node == null) + return false; + boolean result = false; + int count = node.getChildCount(); + for(int i = 0; !result && i < count; i++) { + DefaultMutableTreeTableNode childNode = (DefaultMutableTreeTableNode) node.getChildAt(i); + if(p) { + NodeBean childBean = (NodeBean) childNode.getUserObject(); + if(childBean.getLabel().equals("1")) { + return true; + } + } + result = getChildRefresh(childNode, true); + } + return result; + } + /*** + * ϼȡѡ¼ͬʱȡѡϼѡ¼ͬʱѡһͼĿǰDzĬϹѡ״ + * @param parentNode ڵ + * @param val ùѡֵ01 + */ + private void autoCheck(DefaultMutableTreeTableNode parentNode, String val) { +// for (int i = 0; i < parentNode.getChildCount(); i++) { +// DefaultMutableTreeTableNode node = (DefaultMutableTreeTableNode) parentNode.getChildAt(i); + for (DefaultMutableTreeTableNode node : backMap.get(parentNode)) { + NodeBean bean = (NodeBean) node.getUserObject(); + if(!bean.getDbom().isEmpty()) { + boolean change = true; + NodeBean eBean = null; +// for (int j = 0; j < node.getChildCount(); j++) { +// DefaultMutableTreeTableNode childNode = (DefaultMutableTreeTableNode) node.getChildAt(j); + for (DefaultMutableTreeTableNode childNode : backMap.get(node)) { + NodeBean childBean = (NodeBean) childNode.getUserObject(); + if(!childBean.getEbom().isEmpty()) { + if(val.equals("0")) { + childBean.setLabel(val); + }else if(eBean == null) { + eBean = childBean; + }else { + change = false; + } + } + } + System.out.println("autoCheck" + bean.getDbom() + "==" + change + "==" + eBean + ">>" + val); + if(val.equals("1") && eBean != null && change) { + eBean.setLabel(val); + } + autoCheck(node, val); + } + } + } + + /*** + * жϼǷѡж + * @param node + * @return + */ +// private boolean getTopProcessRefresh(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(); i++) { +// DefaultMutableTreeTableNode childNode = (DefaultMutableTreeTableNode) rootNode.getChildAt(i); +// NodeBean childBean = (NodeBean) childNode.getUserObject(); +// if(childBean.getLabel().equals("1") && childBean.getRefreshStatus().equals("")) { +// result = true; +// break; +// }else { +// if(getTopProcessRefresh(childNode)) { +// result = true; +// break; +// } +// } +// } +// } +// } +// return result; +// } + + @Override + public void mousePressed(MouseEvent e) { + // Auto-generated method stub + + } + + @Override + public void mouseReleased(MouseEvent e) { + // Auto-generated method stub + + } + + @Override + public void mouseEntered(MouseEvent e) { + // Auto-generated method stub + + } + + @Override + public void mouseExited(MouseEvent e) { + // Auto-generated method stub + + } + + @Override + public void actionPerformed(ActionEvent e) { + // Auto-generated method stub + Object source = e.getSource(); + if (source.equals(this.okButton)) + { + if(search) { + search(new String[0][0]); + MessageBox.post("ɸѡȡEBOMٴȷɣ", "ʾ", MessageBox.WARNING); + return; + } + //ȡѡеEBOM + new Thread() { + @Override + public void run() { + try { + topLineItem = null; + builder.setLength(0); + falg1 = true; +// MethodUtil.openByPass(session); + TCComponentItemType itemType = (TCComponentItemType) session + .getTypeComponent("Item"); + bomStructMap.clear(); + msg2.setLength(0); + items.clear(); + + //lidy20240914Ȩ޼飬˽󷢲 + DefaultMutableTreeTableNode top = (DefaultMutableTreeTableNode) node.getChildAt(0); + for(int i = 0, size = top.getChildCount(); i < size; i++) { + DefaultMutableTreeTableNode childNode = (DefaultMutableTreeTableNode) top.getChildAt(i); + NodeBean childBean = (NodeBean) childNode.getUserObject(); + if(childBean.getLabel().equals("1")) { + TCComponent comp = childBean.getTcComponent(); + comp.refresh(); + TCComponent[] bom = comp.getRelatedComponents("structure_revisions"); + System.out.println("top" + comp + "==" + Arrays.toString(bom)); + if(!acs.checkAccessorsPrivilege(user, comp, "WRITE") || + bom.length > 0 && !acs.checkAccessorsPrivilege(user, bom[0], "WRITE")) { + MessageBox.post(comp + " ޱ༭ȨޣBOMת", "ɹ", MessageBox.INFORMATION); + dispose(); + return; + } + } + } + + adaptiveVariants(top, itemType,true); + if(!builder.toString().equals("")) { + JTextArea jTextArea = new JTextArea(builder.toString()); + jTextArea.setEditable(false); + JScrollPane jScrollPane = new JScrollPane(jTextArea); + jScrollPane.setBorder(BorderFactory.createTitledBorder("Ƿ")); + jScrollPane.setPreferredSize(new Dimension(300, 100)); + int option = JOptionPane.showOptionDialog(null, jScrollPane, "", 0, 1, null, null, + Integer.valueOf(0)); + if(option!=0) { + MethodUtil.closeByPass(session); + return; + } + } +// builder.append("Ƿת?"); + + if(!falg1) { + return; + } +// MethodUtil.closeByPass(session); + ProcessBarDialog progress = new ProcessBarDialog("ڽBOMת..."); + progress.open(); + + reBuildBOM(); + + progress.close(); + StringBuilder m = new StringBuilder("\n"); + if(msg2.length()>0) { + m.append(msg2.deleteCharAt(msg2.length() - 1)).append(" ޱ༭ȨޣBOMת"); + MessageBox.post(m.toString(), "ɹ", MessageBox.INFORMATION); + }else { + MessageBox.post("תɹ", "ɹ", MessageBox.INFORMATION); + } + dispose(); + } catch (Exception e1) { + // Auto-generated catch block + e1.printStackTrace(); + } + + } + }.start(); + + } + else if(source.equals(this.refreshButton)) + { + this.dispose(); + try { + DbomTransitionToEbomCommand command = new DbomTransitionToEbomCommand(comp, session); + command.executeModal(); + } catch (Exception e1) { + // Auto-generated catch block + e1.printStackTrace(); + } + } + else if(source.equals(this.searchButton)) + {//TODO + System.out.println("search start"); + new DbomTransitionToEbomSearchDialog(session, this, header, tags);//.showDialog() + System.out.println("search end"); + } + else if(source.equals(this.choose)) + { + boolean ch = choose.isSelected(); + int[] cols = table.getSelectedRows(); + for(int i : cols) { + try { + System.out.println("choose" + i); + TreePath treePath = table.getPathForRow(i); + DefaultMutableTreeTableNode node = (DefaultMutableTreeTableNode) treePath.getLastPathComponent(); + NodeBean nodeBean = (NodeBean) node.getUserObject(); + System.out.println("choose" + nodeBean); + if(nodeBean.getEbom().isEmpty()) + continue; + DefaultMutableTreeTableNode parentNode = (DefaultMutableTreeTableNode) node.getParent(); + if(ch) { + if(nodeBean.getLabel().equals("0")) { + String status = nodeBean.getRefreshStatus(); + boolean access = !acs.checkAccessorsPrivilege(user, nodeBean.getTcComponent(), "WRITE") + || !status.equals("Է") && !status.equals("") && !status.isEmpty(); + if(access && getChildRefresh(parentNode, false)) { +// MessageBox.post("²ѹѡϲ㲻ѡѷûȨ޶", "", MessageBox.ERROR); + continue; + } + if(getTopRefresh(node)) { +// MessageBox.post("ϲѹѡȨ޵Ͳ㲻ѡ", "", MessageBox.ERROR); + continue; + } + //жͬһǷѹѡ + if(parentNode != null) { + boolean check = false; + for (DefaultMutableTreeTableNode childNode : backMap.get(parentNode)) { + NodeBean childBean = (NodeBean) childNode.getUserObject(); + if(childBean.getLabel().equals("1") && !childBean.getEbom().isEmpty() && !nodeBean.getEbom().isEmpty()) { +// MessageBox.post(this, "ͬһ㼶ֻѡһ", "", MessageBox.ERROR); + check = true; + break; + } + } + if(check) + continue; + } + nodeBean.setLabel("1"); + if(!access && parentNode != null) + autoCheck(parentNode, "1"); + } + }else { + nodeBean.setLabel("0"); + if(parentNode != null) + autoCheck(parentNode, "0"); + } + }catch(Exception ex) { + ex.printStackTrace(); +// MessageBox.post("" + ex, "", MessageBox.ERROR); + } + } + this.repaint(); + } + else + { + this.dispose(); + } + } + /** + * ɸѡ + * + * @param tags + */ + protected void search(String[][] tags) { + boolean same = true; + if(tags == null && this.tags != null || this.tags == null && tags != null || tags.length != this.tags.length) + same = false; + ArrayList> tagList = new ArrayList<>(); + ArrayList andList = new ArrayList<>(); + for(int i = 0; i < tags.length; i++) { + if(same) { + if(!Arrays.toString(tags[i]).equals(Arrays.toString(this.tags[i]))) + same = false; + } + if(i == 0) { + andList.add(tags[i]); + continue; + } + if(tags[i][0].equals("OR")) { + tagList.add(andList); + andList = new ArrayList<>(); + andList.add(tags[i]); + }else { + andList.add(tags[i]); + } + } + if(same) + return; + tagList.add(andList); + for(ArrayList or : tagList) { + System.out.println("or==>"); + for(String[] and : or) { + System.out.println("and==>" + Arrays.toString(and)); + } + } + if(search) { + search = false; + search(node, tagList); + add(node); +// table.expandAll(); + } + search = (tags != null && tags.length > 0); + if(search) { + search(node, tagList); +// if(!search) { +// add(node); +// } + } + table.expandAll(); + this.tags = tags; +// search = !search; + } + /** + * ɸѡ + * + * @param rootNode ڵ + * @param tags ɸѡ + */ + private void search(DefaultMutableTreeTableNode rootNode, ArrayList> tagList) { + if(search) { + ArrayList list = new ArrayList<>(); + int count = rootNode.getChildCount(); + for(int i = count - 1; i >= 0 ; i--) { + DefaultMutableTreeTableNode tableNode = (DefaultMutableTreeTableNode)rootNode.getChildAt(i); + if(tableNode.getChildCount() > 0) { + search(tableNode, tagList); + } + NodeBean bean = (NodeBean)tableNode.getUserObject(); + if(!bean.getDbom().isEmpty()) { + ArrayList beans = new ArrayList<>(); + for(int j = 0; j < tableNode.getChildCount(); j++) { + DefaultMutableTreeTableNode childNode = (DefaultMutableTreeTableNode)tableNode.getChildAt(j); + NodeBean childBean = (NodeBean)childNode.getUserObject(); + if(!childBean.getEbom().isEmpty()) + beans.add(childBean); + } + beans.add(bean); + int len = beans.size(); + boolean[] res = checkBean(beans, tagList); + System.out.println(bean + " checkBean" + Arrays.toString(res)); + if(res[len - 1]) { + //DϣƳϵE + for(int j = res.length - 1; j >= 0; j--) { + if(!res[j]) { + DefaultMutableTreeTableNode cnode = (DefaultMutableTreeTableNode)tableNode.getChildAt(j); + System.out.println(cnode.getParent() + " remove1" + cnode); +// if(!cnode.getParent().toString().contains("003")) + map.removeNodeFromParent(cnode); + } + } + }else { + //DϣƳ + for(int j = tableNode.getChildCount() - 1; j >= 0; j--) { + DefaultMutableTreeTableNode cnode = (DefaultMutableTreeTableNode)tableNode.getChildAt(j); + NodeBean cbean = (NodeBean)cnode.getUserObject(); + if(!cbean.getDbom().isEmpty()) + list.add(cnode); + System.out.println(cnode.getParent() + " remove2" + cnode); + map.removeNodeFromParent(cnode); + } + System.out.println(tableNode.getParent() + " remove3" + tableNode); + map.removeNodeFromParent(tableNode); + } + } + } + for(DefaultMutableTreeTableNode tableNode : list) { + count = rootNode.getChildCount(); + System.out.println(rootNode + " insert" + tableNode); + map.insertNodeInto(tableNode, rootNode, count); + } +// for(DefaultMutableTreeTableNode tableNode : backMap.get(rootNode)) { +// NodeBean bean = (NodeBean)tableNode.getUserObject(); +// System.out.println("back" + bean.toString()); +// } + }else { +// for(DefaultMutableTreeTableNode tableNode : backMap.get(rootNode)) { + for(int i = rootNode.getChildCount() - 1; i >= 0 ; i--) { + DefaultMutableTreeTableNode tableNode = (DefaultMutableTreeTableNode)rootNode.getChildAt(i); + search(tableNode, tagList); + System.out.println(tableNode.getParent() + " remove4" + tableNode); + if(tableNode.getParent() != null) + map.removeNodeFromParent(tableNode); + } + } + } + /** + * ´ṹ + * + * @param rootNode ڵ + */ + private void add(DefaultMutableTreeTableNode rootNode) { + System.out.println("search add" + rootNode.getUserObject()); +// for(DefaultMutableTreeTableNode tableNode : backMap.get(rootNode)) { + ArrayList list = backMap.get(rootNode); + for(int i = 0; i < list.size(); i++) { + DefaultMutableTreeTableNode tableNode = list.get(i); + NodeBean bean = (NodeBean)tableNode.getUserObject(); + System.out.println(i + "back add" + bean.toString()); + map.insertNodeInto(tableNode, rootNode, i); + add(tableNode); + } + } + /** + * ж + * + * @param bean жϽڵ + * @param tags ɸѡ + * @return жϽ + */ + private boolean[] getArray(boolean val, int num) { + boolean[] array = new boolean[num]; + for(int i = 0; i < num; i++) + array[i] = val; + return array; + } + /** + * DEж + * + * @param beans жϽڵ㣬һD + * @param tagList ɸѡ + * @return жϽ + */ + private boolean[] checkBean(ArrayList beans, ArrayList> tagList) { + int len = beans.size(); + boolean[] result = getArray(false, len); + NodeBean dbean = beans.get(len - 1); + for(ArrayList l : tagList) { + //жAND + boolean[] res = getArray(true, len); + boolean[] has = getArray(false, 2); + for(String[] tag : l) { + if(dList.contains(tag[1])) { + has[0] = true; + if(!checkBean(dbean, tag)) { + res[len - 1] = false; + break; + } + }else { + has[1] = true; + for(int i = 0; i < len - 1; i++) { + NodeBean bean = beans.get(i); + if(!checkBean(bean, tag)) { + res[i] = false; +// break; + } + } + } + } + if(has[0] && has[1]) { + //DEand + if(res[len - 1]) { + boolean ng = true; + for(int i = 0; i < len - 1; i++) { + if(res[i]) { + ng = false; + break; + } + } + if(ng) {//EDҲ + continue; + } + }else {//D򶼲 + continue; + } + }else if(has[0] && !res[len - 1]) {//жDDEҪʾ + continue; + }else if(has[1]) {//жEֻҪһEDҲҪʾ + boolean ng = true; + for(int i = 0; i < len - 1; i++) { + if(res[i]) { + ng = false; + break; + } + } + if(ng) { + continue; + } + } + boolean ok = true; + for(int i = 0; i < len; i++) {//жOR + if(res[i]) + result[i] = true; + if(!result[i]) + ok = false; + } + if(ok) + break; + } + return result; + } + /** + * ڵж + * + * @param bean жϽڵ + * @param tag ɸѡ + * @return жϽ + */ + private boolean checkBean(NodeBean bean, String[] tag) { + System.out.println("checkBean" + bean); + boolean res = false; + String val = bean.getValueAt(headMap.get(tag[1])); + System.out.println("val" + val); + String value = tag[3]; + if(value.equals("ѹѡ")) + value = "1"; + else if(value.equals("δѡ")) + value = "0"; + switch(tag[2]) { + case "=": + res = val.contains(value); + break; + case "==": + res = val.equals(value); + break; + case "!=": + res = !val.contains(value); + break; + } + System.out.println("checkBean==" + res); + return res; + } + + /** + * ´BOM + * + * @param topItem + * @throws TCException + */ + private void adaptiveVariants(DefaultMutableTreeTableNode tableNode, TCComponentItemType itemType, + boolean ifCreate) throws Exception { + TCComponentItem topItem = null; + //idͬʱ +// LinkedHashMap countMap = +// new LinkedHashMap(); +// idͬʱ +// List +// LinkedHashMap pcMap = +// new LinkedHashMap(); +// ArrayList itemList = new ArrayList(); +// Map itemNumMap = new HashMap(); + + NodeBean pBean = (NodeBean) tableNode.getUserObject(); + Map> bomValMap = pBean.getBomValMap(); + System.out.println("bomValMap:" + bomValMap.toString()); + TCComponentItemRevision parentRev = pBean.getRev(); + Map> childMap = + new HashMap>(); + boolean topFlag = false; + for (int i = 0; i < tableNode.getChildCount(); i++) { + DefaultMutableTreeTableNode childNode = (DefaultMutableTreeTableNode) tableNode.getChildAt(i); + NodeBean childBean = (NodeBean) childNode.getUserObject(); + if(childBean.getLabel().equals("1") && !childBean.getEbom().isEmpty()) { + topFlag = true; +// topItem = itemType.findItems(childBean.getEbomId())[0]; + TCComponentItemRevision comp = (TCComponentItemRevision) childBean.getTcComponent(); + System.out.println("childBean:" + comp); + topItem = comp.getItem(); + for (int j = 0; j < tableNode.getChildCount(); j++) { + DefaultMutableTreeTableNode node = (DefaultMutableTreeTableNode) tableNode.getChildAt(j); + NodeBean topBean = (NodeBean) node.getUserObject(); + + if(topBean.getIsTw()) { + System.out.println("================="); + DefaultMutableTreeTableNode rootNode = topBean.getRootNode(); + NodeBean rootBean = (NodeBean) rootNode.getUserObject(); + Map> rootValMap = rootBean.getBomValMap(); +// System.out.println(topBean.getpRev()); + System.out.println(topBean.getRev()); + if(rootValMap.containsKey(topBean.getRev())) { + List list = rootValMap.get(topBean.getRev()); + childMap.put(topBean.getRev(), list); + System.out.println("list==" + list.toString()); + } + System.out.println(rootValMap.toString()); + if(topLineItem == null) { + topLineItem = topItem; + } + continue; + } + +// System.out.println(bomValMap.toString() + "pBean==" + pBean.getDbom()); + System.out.println("topBean==" + topBean.getDbom() + "==>" + topBean.getTcComponent()); + TCComponentBOMLine dbom = topBean.getBom(); + System.out.println("dbom:" + dbom + "==>" + dbom.isPacked()); + BomValBean pValBean = new BomValBean(); + pValBean.setBl_czbh(dbom.getStringProperty("bl_sequence_no")); + pValBean.setBl_jdjz(dbom.getStringProperty("bl_plmxml_abs_xform")); + pValBean.setBl_quantity(dbom.getProperty("bl_quantity")); + if(pValBean.getBl_quantity().isEmpty()) + pValBean.setBl_quantity("1"); + int index = 0; + for (int k = 0; k < node.getChildCount(); k++) { + DefaultMutableTreeTableNode childTableNode = (DefaultMutableTreeTableNode) node.getChildAt(k); + NodeBean childNodeBean = (NodeBean) childTableNode.getUserObject(); + if(childNodeBean.getLabel().equals("1")) { + if(index > 0) { + builder.append(pBean.getDbom()).append("ѡ˶;\n"); + } + index = index + 1; + TCComponentItemRevision nodeComp = (TCComponentItemRevision) childNodeBean.getTcComponent(); + TCComponentItem item = nodeComp.getItem(); + System.out.println("childNodeBean:" + nodeComp); +// if(childNodeBean.getEbomId() == null || childNodeBean.getEbomId().isEmpty()) { +// String dbom = childNodeBean.getDbom(); +// String id = ""; +// if(dbom.contains("-")) { +// id = dbom.substring(0, dbom.indexOf("-")); +// }else { +// id = dbom; +// } +// item = itemType.findItems(id)[0]; +// }else { +// item = itemType.findItems(childNodeBean.getEbomId())[0]; +// } + if(preList.contains(item.getType())){ + continue; + } + String num = childNodeBean.getNum(); + if(num == null || num.isEmpty() || num.equals("0")) { + num = "1"; + } +// TCComponentItemRevision latestItemRevision = item.getLatestItemRevision(); + + TCComponentItemRevision pRev = childNodeBean.getpRev(); + System.out.println("pRev" + pRev); + if(dbom.isPacked() && bomValMap.containsKey(pRev)) { + List list = bomValMap.get(pRev); + childMap.put(nodeComp, list); + }else if(childMap.containsKey(nodeComp)) {//TODO lidy20250221 + childMap.get(nodeComp).add(pValBean); + }else { + // lidy20241211 + List list = new ArrayList<>(); + list.add(pValBean); + childMap.put(nodeComp, list); + } + + TCComponent tcComponent = childNodeBean.getTcComponent(); + Boolean jxzjBoolean = true; + if(parentRev != null) { + TCComponent rev = tcComponent; + jxzjBoolean = acs.checkAccessorsPrivilege(user, rev, "WRITE"); + if(!jxzjBoolean ) { //|| childNodeBean.getEbom().contains("55") +// System.out.println(topItem+"Ȩ޼iiiiiiii"); + //lidy20240914ûӼĶʾ + boolean has = false; + for (int l = 0; l < node.getChildCount(); l++) { + DefaultMutableTreeTableNode cn = (DefaultMutableTreeTableNode) node.getChildAt(l); + NodeBean cnb = (NodeBean) cn.getUserObject(); + if(!cnb.getDbom().isEmpty()) { + has = true; + break; + } + } + if(has) + msg2.append(rev).append(""); + if(rev instanceof TCComponentItemRevision) { + items.add(((TCComponentItemRevision)rev).getItem()); + }else if(rev instanceof TCComponentItem){ + items.add((TCComponentItem)rev); + } + } + } + if(topLineItem == null) { + topLineItem = topItem; + } + System.out.println(tcComponent + "Ȩ޼" + jxzjBoolean); + if(!jxzjBoolean) { + continue; + } + String status = childNodeBean.getRefreshStatus(); + if(status.equals("Է") || status.equals("") || status.equals("")) { + adaptiveVariants((DefaultMutableTreeTableNode)(childTableNode.getParent()), + itemType,true); + } + } + } + if(!topBean.getDbom().equals("") && index == 0) { + builder.append(topBean.getDbom()).append("ûйѡ;\n"); + } + } + } + } + if(!topFlag) { + falg1 = false; + MessageBox.post("δѡ񶥲ϣ޷","ʾ",2); + } + if(topItem != null) { + bomStructMap.put(topItem, childMap); + } + } + @SuppressWarnings("deprecation") + private void reBuildBOM() throws Exception { + + System.out.println("reBuildBOM==>" + bomStructMap.toString()); + + if(topLineItem != null) { + Map> map2 = bomStructMap.get(topLineItem); + + TCComponentBOMWindow bomWindow = null; + try { + TCComponentBOMWindowType bomWindowType = (TCComponentBOMWindowType) session + .getTypeComponent("BOMWindow"); + bomWindow = bomWindowType.create(null); + TCComponentBOMLine topline = bomWindow.setWindowTopLine(topLineItem, + topLineItem.getLatestItemRevision(), null, null); + bomWindow.lock(); + recreateBom2(topLineItem, map2, topline, bomWindow); + }catch(Exception e) { + e.printStackTrace(); + } + + bomWindow.save(); + bomWindow.unlock(); + bomWindow.refresh(); + } + + } + /** + * ´BOM + * @param bomWindow + * + * @param item + * @param itemlists + * @throws TCException + */ + @SuppressWarnings("deprecation") + private void recreateBom2(TCComponentItem topItem, + Map> map2, TCComponentBOMLine topline, TCComponentBOMWindow bomWindow) + throws Exception { +// TCComponentBOMWindow bomWindow = null; + try { + topline.refresh(); + topline.lock(); + System.out.println("items==>" + items.toString()); + List bomLines = new ArrayList(); + Set set = map2.keySet(); + + if (topline.hasChildren()) { + System.out.println(topItem); + if(items.contains(topItem)) { + return; + } + AIFComponentContext[] childrens = topline.getChildren(); + for (AIFComponentContext children : childrens) { + TCComponentBOMLine bLine = (TCComponentBOMLine) children.getComponent(); + if(bLine.isPacked()) + bLine.unpack(); + } + topline.refresh(); + childrens = topline.getChildren(); + for (AIFComponentContext children : childrens) { + TCComponentBOMLine bLine = (TCComponentBOMLine) children.getComponent(); + System.out.println("addorcut===>" + bLine); + if(bLine.getStringProperty("J6_BOM_DTE").equals("DBOMת")) { //J6_BOM_DTE bl_ref_designator + System.out.println("cut"); + bLine.cut(); + }else { + System.out.println("add"); + bomLines.add(bLine); + } + } + }else if(set.size() > 0) {//lidy20250225 BOMͼ汾޷þȷ + TCComponentItemRevision rev = (TCComponentItemRevision) set.toArray()[0]; + TCComponentItem item = rev.getItem(); + TCComponentBOMLine line = topline.add(item, rev, null, false, ""); + bomWindow.save(); + line.cut(); + bomWindow.save(); + } + String maxSeq = ""; + + System.out.println("topline===>" + topline); + topline.setPrecision(true); + for(TCComponentItemRevision rev : set) { + List list = map2.get(rev); + System.out.println("list===>" + list.toString()); + for(BomValBean bean : list) { + TCComponentItem item = rev.getItem(); + TCComponentBOMLine add = topline.add(item, rev, null, false, ""); + add.lock(); + add.setStringProperty("bl_quantity", bean.getBl_quantity()); + add.setStringProperty("bl_plmxml_abs_xform", bean.getBl_jdjz());//bl_plmxml_occ_xform + add.setStringProperty("bl_sequence_no", bean.getBl_czbh()); + System.out.println("add===>" + add + ">>>" + bean.getBl_quantity());//TODO add +// System.out.println("bean.getBl_czbh()==>" + bean.getBl_czbh()); +// System.out.println("maxSeq==>" + maxSeq); + if(maxSeq.compareTo(bean.getBl_czbh())<0) { +// System.out.println(maxSeq); + maxSeq = bean.getBl_czbh(); + } + add.setStringProperty("J6_BOM_DTE", "DBOMת"); ////J6_BOM_DTE + add.save(); + add.unlock(); + if(bomStructMap.containsKey(item)) { + Map> map3 = bomStructMap.get(item); + recreateBom2(item, map3, add, bomWindow); + } + + } + } + if(!maxSeq.equals("")) { + Integer valueOf = Integer.valueOf(maxSeq); + for(TCComponentBOMLine bomLine : bomLines) { + bomLine.lock(); + valueOf = valueOf + 10; + bomLine.setStringProperty("bl_sequence_no", String.valueOf(valueOf)); + bomLine.save(); + bomLine.unlock(); + } + } + + topline.save(); + topline.unlock(); + topline.refresh(); + } catch (Exception e) { + // : handle exception + e.printStackTrace(); + } + + } + + /** + * ´BOM + * + * @param item + * @param itemlists + * @throws Exception + + @SuppressWarnings("deprecation") + private void recreateBom(TCComponentItemRevision topItemRev, + boolean isDelete,Map> map2) + throws Exception { + TCComponentBOMWindow bomWindow = null; + try { + TCComponentBOMWindowType bomWindowType = (TCComponentBOMWindowType) session + .getTypeComponent("BOMWindow"); + bomWindow = bomWindowType.create(null); + TCComponentBOMLine topline = bomWindow.setWindowTopLine(topItemRev.getItem(), + topItemRev, null, null); + resultTopline = topline; + bomWindow.lock(); + topline.lock(); + System.out.println("items==>"+items.toString()); + List bomLines = new ArrayList(); + if (isDelete) { + if (topline.hasChildren()) { + System.out.println(topItemRev.getItem()); + if(items.contains(topItemRev.getItem())) { + return; + } + AIFComponentContext[] childrens = topline.getChildren(); + for (AIFComponentContext children : childrens) { + TCComponentBOMLine bLine = (TCComponentBOMLine) children.getComponent(); + if(bLine.getStringProperty("J6_BOM_DTE").equals("DBOMת")) { + bLine.cut(); + }else { + bomLines.add(bLine); + } + } + } + } + String maxSeq = ""; + for(TCComponentItemRevision rev:map2.keySet()) { + List list = map2.get(rev); + for(BomValBean bean:list) { + TCComponentBOMLine add = topline.add(rev.getItem(), rev, null, false, ""); + add.lock(); + add.setStringProperty("bl_quantity", bean.getBl_quantity()); + add.setStringProperty("bl_plmxml_occ_xform", bean.getBl_jdjz()); + add.setStringProperty("bl_sequence_no", bean.getBl_czbh()); + System.out.println("bean.getBl_czbh()==>"+bean.getBl_czbh()); + System.out.println("maxSeq==>"+maxSeq); + if(maxSeq.compareTo(bean.getBl_czbh())<0) { +// System.out.println(maxSeq); + maxSeq = bean.getBl_czbh(); + } + + add.setStringProperty("J6_BOM_DTE","DBOMת"); + add.save(); + add.unlock(); + } + } + if(!maxSeq.equals("")) { + Integer valueOf = Integer.valueOf(maxSeq); + for(TCComponentBOMLine bomLine : bomLines) { + bomLine.lock(); + valueOf = valueOf + 10; + bomLine.setStringProperty("bl_sequence_no", String.valueOf(valueOf)); + bomLine.save(); + bomLine.unlock(); + } + } + + topline.save(); + topline.unlock(); + topline.refresh(); + if(topline.getBOMView() != null) + { + topline.getBOMView().save(); + topline.getBOMView().refresh(); + } + } catch (Exception e) { + // : handle exception + e.printStackTrace(); + } + bomWindow.save(); + bomWindow.unlock(); + bomWindow.refresh(); + }*/ + +} diff --git a/src/com/connor/ml/tcm/outfile/ML_010/DbomTransitionToEbomHandler.java b/src/com/connor/ml/tcm/outfile/ML_010/DbomTransitionToEbomHandler.java new file mode 100644 index 0000000..be5004f --- /dev/null +++ b/src/com/connor/ml/tcm/outfile/ML_010/DbomTransitionToEbomHandler.java @@ -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; + } + + +} diff --git a/src/com/connor/ml/tcm/outfile/ML_010/DbomTransitionToEbomSearchDialog.java b/src/com/connor/ml/tcm/outfile/ML_010/DbomTransitionToEbomSearchDialog.java new file mode 100644 index 0000000..3d86f3a --- /dev/null +++ b/src/com/connor/ml/tcm/outfile/ML_010/DbomTransitionToEbomSearchDialog.java @@ -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 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 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 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 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; + } +} \ No newline at end of file diff --git a/src/com/connor/ml/tcm/outfile/ML_010/JTreeTable.java b/src/com/connor/ml/tcm/outfile/ML_010/JTreeTable.java new file mode 100644 index 0000000..63a0a1b --- /dev/null +++ b/src/com/connor/ml/tcm/outfile/ML_010/JTreeTable.java @@ -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 isNotEditableRow; + //CheckBoxCellEditor checkBoxCellEditor = new CheckBoxCellEditor(this); + private TableCellCheckboxRenderer checkboxRenderer = new TableCellCheckboxRenderer(this); + + public List getIsNotEditableRow() { + return isNotEditableRow; + } + + public void setIsNotEditableRow(List 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); + } + +} diff --git a/src/com/connor/ml/tcm/outfile/ML_010/JTreeTableModel.java b/src/com/connor/ml/tcm/outfile/ML_010/JTreeTableModel.java new file mode 100644 index 0000000..1030184 --- /dev/null +++ b/src/com/connor/ml/tcm/outfile/ML_010/JTreeTableModel.java @@ -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 isNotEditableRow; + + + + public JTreeTableModel(TreeTableNode node, String[] names) { + super(node); + + _names = names; + } + + + public List getIsNotEditableRow() { + return isNotEditableRow; + } + + public void setIsNotEditableRow(List 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; + //} + } + + +} diff --git a/src/com/connor/ml/tcm/outfile/ML_010/ProcessBarDialog.java b/src/com/connor/ml/tcm/outfile/ML_010/ProcessBarDialog.java new file mode 100644 index 0000000..90a26ec --- /dev/null +++ b/src/com/connor/ml/tcm/outfile/ML_010/ProcessBarDialog.java @@ -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(); + } + +} diff --git a/src/com/connor/ml/tcm/outfile/ML_010/TableCellCheckboxRenderer.java b/src/com/connor/ml/tcm/outfile/ML_010/TableCellCheckboxRenderer.java new file mode 100644 index 0000000..9db14bf --- /dev/null +++ b/src/com/connor/ml/tcm/outfile/ML_010/TableCellCheckboxRenderer.java @@ -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 processRows; + protected EventListenerList listenerList = new EventListenerList(); + protected ChangeEvent changeEvent = new ChangeEvent(this); + //private TestTreeTableModel tableModel; + + public List getProcessRows() { + return processRows; + } + + public void setProcessRows(List 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; + } +} \ No newline at end of file diff --git a/src/com/connor/ml/tcm/outfile/ML_010/TableCellComboBoxEditor.java b/src/com/connor/ml/tcm/outfile/ML_010/TableCellComboBoxEditor.java new file mode 100644 index 0000000..314765c --- /dev/null +++ b/src/com/connor/ml/tcm/outfile/ML_010/TableCellComboBoxEditor.java @@ -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 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) 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(); + } +} diff --git a/src/com/connor/ml/tcm/outfile/ML_010/Test.java b/src/com/connor/ml/tcm/outfile/ML_010/Test.java new file mode 100644 index 0000000..ab553f5 --- /dev/null +++ b/src/com/connor/ml/tcm/outfile/ML_010/Test.java @@ -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("-"))); + } +} diff --git a/src/com/connor/ml/tcm/outfile/bean/NodeBean.java b/src/com/connor/ml/tcm/outfile/bean/NodeBean.java new file mode 100644 index 0000000..a3c418e --- /dev/null +++ b/src/com/connor/ml/tcm/outfile/bean/NodeBean.java @@ -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> bomValMap = new HashMap>(); + + 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 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> getBomValMap() { + return bomValMap; + } + public void setBomValMap(Map> 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; + } +} \ No newline at end of file diff --git a/src/com/connor/ml/tcm/outfile/util/Adapter.java b/src/com/connor/ml/tcm/outfile/util/Adapter.java new file mode 100644 index 0000000..c654807 --- /dev/null +++ b/src/com/connor/ml/tcm/outfile/util/Adapter.java @@ -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> selectValue = new ArrayList>(); + + /** + * 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= 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= 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= 0) + { + String[] cellValue = rowstring.split("\t"); + for(int j=0;j= 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= 0) + { + String[] cellValue = rowstring.split("\t"); + for(int j=0;j 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(); + } + + } + } +} \ No newline at end of file diff --git a/src/com/connor/ml/tcm/outfile/util/JAutoCompleteComboBox.java b/src/com/connor/ml/tcm/outfile/util/JAutoCompleteComboBox.java new file mode 100644 index 0000000..3024722 --- /dev/null +++ b/src/com/connor/ml/tcm/outfile/util/JAutoCompleteComboBox.java @@ -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(); + } + } + } + } +} \ No newline at end of file diff --git a/src/com/connor/ml/tcm/outfile/util/MethodUtil.java b/src/com/connor/ml/tcm/outfile/util/MethodUtil.java new file mode 100644 index 0000000..8df1412 --- /dev/null +++ b/src/com/connor/ml/tcm/outfile/util/MethodUtil.java @@ -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; + } + + /** + * ListתString + * + * @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; + } + + /** + * LOVƻȡLOV + * + * @param tcsession + * @param s + * @return + */ + + + /** + * LOV KeyȡLOVֵ + * + * @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); + //ǷQ + 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 صϢ + * @throws IOException + * @throws FileNotFoundException + */ + + + + + /** + * ȡEXCEL + * + * @param File excel_file + * @return List صϢ + * @throws IOException + * @throws FileNotFoundException + */ + + + + + /** + * ȡEXCEL + * + * @param File excel_file + * @return List صϢ + * @throws IOException + * @throws FileNotFoundException + */ + + +}