commit 3ef96a7452a3f1187a2b0e47b7d3fa0768869696 Author: lijh Date: Wed Apr 2 14:36:59 2025 +0800 20250402 commit diff --git a/.classpath b/.classpath new file mode 100644 index 0000000..4fcb083 --- /dev/null +++ b/.classpath @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/.project b/.project new file mode 100644 index 0000000..23670f5 --- /dev/null +++ b/.project @@ -0,0 +1,28 @@ + + + com.connor.lidy + + + + + + 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..0c68a61 --- /dev/null +++ b/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,7 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/META-INF/MANIFEST.MF b/META-INF/MANIFEST.MF new file mode 100644 index 0000000..de87633 --- /dev/null +++ b/META-INF/MANIFEST.MF @@ -0,0 +1,34 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Lidy +Bundle-SymbolicName: com.connor.lidy;singleton:=true +Bundle-Version: 1.0.0 +Bundle-Localization: plugin +Bundle-Activator: com.connor.lidy.Activator +Bundle-Vendor: CONNOR +Require-Bundle: org.eclipse.ui, + org.eclipse.core.runtime, + com.teamcenter.rac.kernel;bundle-version="13000.1.0", + com.teamcenter.rac.aifrcp;bundle-version="13000.1.0", + com.teamcenter.rac.util;bundle-version="13000.1.0", + com.teamcenter.rac.commonclient;bundle-version="13000.1.0", + TcSoaCoreRac;bundle-version="13000.1.0", + com.teamcenter.rac.ui;bundle-version="13000.1.0", + com.teamcenter.rac.schedule;bundle-version="13000.1.0", + org.apache.poi.39;bundle-version="3.9.0", + com.teamcenter.rac.common;bundle-version="13000.1.0", + Fnd0SoaAuditManagerRac;bundle-version="13000.1.0", + TcSoaWorkflowRac;bundle-version="13000.1.0" +Bundle-RequiredExecutionEnvironment: JavaSE-1.8 +Automatic-Module-Name: com.connor.lidy +Bundle-ActivationPolicy: lazy +Import-Package: com.teamcenter.rac.kernel, + com.teamcenter.rac.stylesheet, + org.dom4j, + org.dom4j.io +Export-Package: com.microsoft.sqlserver.jdbc, + org.jdesktop.swingx +Bundle-ClassPath: sqljdbc4.jar, + ., + lib/jxl.jar, + lib/swingx-1.6.1.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..e69a7b5 --- /dev/null +++ b/build.properties @@ -0,0 +1,8 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + plugin.xml,\ + sqljdbc4.jar,\ + lib/jxl.jar,\ + lib/swingx-1.6.1.jar diff --git a/lib/activation-1.1.1.jar b/lib/activation-1.1.1.jar new file mode 100644 index 0000000..1b703ab Binary files /dev/null and b/lib/activation-1.1.1.jar differ diff --git a/lib/commons-codec-1.11.jar b/lib/commons-codec-1.11.jar new file mode 100644 index 0000000..2245120 Binary files /dev/null and b/lib/commons-codec-1.11.jar differ diff --git a/lib/commons-collections4-4.2.jar b/lib/commons-collections4-4.2.jar new file mode 100644 index 0000000..73a4f3f Binary files /dev/null and b/lib/commons-collections4-4.2.jar differ diff --git a/lib/commons-compress-1.18.jar b/lib/commons-compress-1.18.jar new file mode 100644 index 0000000..e401046 Binary files /dev/null and b/lib/commons-compress-1.18.jar differ diff --git a/lib/commons-logging-1.2.jar b/lib/commons-logging-1.2.jar new file mode 100644 index 0000000..93a3b9f Binary files /dev/null and b/lib/commons-logging-1.2.jar differ diff --git a/lib/commons-math3-3.6.1.jar b/lib/commons-math3-3.6.1.jar new file mode 100644 index 0000000..0ff582c Binary files /dev/null and b/lib/commons-math3-3.6.1.jar differ diff --git a/lib/curvesapi-1.05.jar b/lib/curvesapi-1.05.jar new file mode 100644 index 0000000..6ec3119 Binary files /dev/null and b/lib/curvesapi-1.05.jar differ diff --git a/lib/jaxb-api-2.3.0.jar b/lib/jaxb-api-2.3.0.jar new file mode 100644 index 0000000..0817c08 Binary files /dev/null and b/lib/jaxb-api-2.3.0.jar differ diff --git a/lib/jaxb-core-2.3.0.1.jar b/lib/jaxb-core-2.3.0.1.jar new file mode 100644 index 0000000..431e143 Binary files /dev/null and b/lib/jaxb-core-2.3.0.1.jar differ diff --git a/lib/jaxb-impl-2.3.0.1.jar b/lib/jaxb-impl-2.3.0.1.jar new file mode 100644 index 0000000..6ae03f6 Binary files /dev/null and b/lib/jaxb-impl-2.3.0.1.jar differ diff --git a/lib/junit-4.12.jar b/lib/junit-4.12.jar new file mode 100644 index 0000000..3a7fc26 Binary files /dev/null and b/lib/junit-4.12.jar differ diff --git a/lib/jxl.jar b/lib/jxl.jar new file mode 100644 index 0000000..b210c06 Binary files /dev/null and b/lib/jxl.jar differ diff --git a/lib/log4j-1.2.17.jar b/lib/log4j-1.2.17.jar new file mode 100644 index 0000000..1d425cf Binary files /dev/null and b/lib/log4j-1.2.17.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-ooxml-4.0.1.jar b/lib/poi-ooxml-4.0.1.jar new file mode 100644 index 0000000..282a1a5 Binary files /dev/null and b/lib/poi-ooxml-4.0.1.jar differ diff --git a/lib/poi-ooxml-schemas-4.0.1.jar b/lib/poi-ooxml-schemas-4.0.1.jar new file mode 100644 index 0000000..49509b2 Binary files /dev/null and b/lib/poi-ooxml-schemas-4.0.1.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/lib/xmlbeans-3.0.2.jar b/lib/xmlbeans-3.0.2.jar new file mode 100644 index 0000000..f371911 Binary files /dev/null and b/lib/xmlbeans-3.0.2.jar differ diff --git a/plugin - 副本.xml b/plugin - 副本.xml new file mode 100644 index 0000000..0ec25d8 --- /dev/null +++ b/plugin - 副本.xml @@ -0,0 +1,375 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugin.xml b/plugin.xml new file mode 100644 index 0000000..c6c9d96 --- /dev/null +++ b/plugin.xml @@ -0,0 +1,439 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sqljdbc4.jar b/sqljdbc4.jar new file mode 100644 index 0000000..d6b7f6d Binary files /dev/null and b/sqljdbc4.jar differ diff --git a/src/com/connor/lidy/Activator.java b/src/com/connor/lidy/Activator.java new file mode 100644 index 0000000..d956e58 --- /dev/null +++ b/src/com/connor/lidy/Activator.java @@ -0,0 +1,44 @@ +package com.connor.lidy; + +import org.eclipse.ui.plugin.AbstractUIPlugin; +import org.osgi.framework.BundleContext; + +/** + * The activator class controls the plug-in life cycle + */ +public class Activator extends AbstractUIPlugin { + + // The plug-in ID + public static final String PLUGIN_ID = "com.connor.lidy"; //$NON-NLS-1$ + + // The shared instance + private static Activator plugin; + + /** + * The constructor + */ + public Activator() { + } + + @Override + public void start(BundleContext context) throws Exception { + super.start(context); + plugin = this; + } + + @Override + public void stop(BundleContext context) throws Exception { + plugin = null; + super.stop(context); + } + + /** + * Returns the shared instance + * + * @return the shared instance + */ + public static Activator getDefault() { + return plugin; + } + +} diff --git a/src/com/connor/lidy/create/DbPool.java b/src/com/connor/lidy/create/DbPool.java new file mode 100644 index 0000000..a6edc0b --- /dev/null +++ b/src/com/connor/lidy/create/DbPool.java @@ -0,0 +1,233 @@ +package com.connor.lidy.create; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import com.teamcenter.rac.aif.AbstractAIFUIApplication; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCPreferenceService; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +public class DbPool { + + public static Connection connection = null; + public static PreparedStatement ps = null; + public static ResultSet rs = null; + + private static DbPool instance = null; + + public static synchronized Connection getConnection() { + if (instance == null) { + instance = new DbPool(); + } + return instance._getConnection(); + } + + private Connection _getConnection() { + try { + String sDBDriver = null; + String sConnection = null; + String sUser = null; + String sPassword = null; +// Properties p = new Properties(); +// InputStream is = getClass().getResourceAsStream( +// "/sqlconn.properties"); +// p.load(is); +// sDBDriver = p.getProperty("DBDriver", "1"); +// sConnection = p.getProperty("Connection", "2"); +// sUser = p.getProperty("User", ""); +// sPassword = p.getProperty("Password", ""); + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + TCSession session = (TCSession) app.getSession(); + TCPreferenceService service = session.getPreferenceService(); + String[] array = service.getStringValues("TC13_SqlServer_Link"); + //TCPreferenceService.TC_preference_site, "TC13_SqlServer_Link"); + + if (array != null) + { + for (String str : array) { +// System.out.println(" ORACLE = " + str); + if (str != null && str.startsWith("DBDriver=")) { + sDBDriver = str.substring(str.indexOf("=") + 1, + str.length()); + } else if (str != null && str.startsWith("Connection=")) { + sConnection = str.substring(str.indexOf("=") + 1, str.length()); + } else if (str != null && str.startsWith("User=")) { + sUser = str.substring(str.indexOf("=") + 1, + str.length()); + } else if (str != null + && str.startsWith("Password=")) { + sPassword = str.substring(str.indexOf("=") + 1, + str.length()); + } + } + } + // String driver_temp = reg.getString("ORACEL_DRIVER"); + // String url = reg.getString("ORACEL_URL");// getProperties("URL"); + // String dbName = reg.getString("ORACEL_NAME");// + // Util.getProperties("dbName"); + // String dbPassword = reg.getString("ORACEL_PASSWORD");// + // Util.getProperties("dbPassword"); + + if (sDBDriver == null || sConnection == null || sUser == null + || sPassword == null) { + + MessageBox.post("ݿѡǷȷ", "ʾ", MessageBox.ERROR); + + } + + Class.forName(sDBDriver); + connection = DriverManager.getConnection(sConnection, sUser, + sPassword); + return connection; + } catch (Exception se) { + System.out.println(se); + } + return null; + } + + public static void executeUpdateSql(String sql) throws SQLException { + Statement st = connection.createStatement(); + try { + connection.setAutoCommit(false); + System.out.println("sql===" + sql); + st.executeUpdate(sql); + } catch (SQLException e) { +// System.out.println(e.getMessage()); + e.printStackTrace(); + if (st != null) + st.close(); + connection.rollback(); + connection.close(); + } finally { + if (st != null) + st.close(); + // connection.close(); + } + + } + + public static void executeDeleteSql(String sql) throws SQLException { + Statement st = connection.createStatement(); + try { + connection.setAutoCommit(false); + System.out.println("sql===" + sql); + st.executeUpdate(sql); + connection.commit(); + } catch (SQLException e) { + if (st != null) + st.close(); + connection.rollback(); + connection.close(); + } finally { + if (st != null) + st.close(); + connection.close(); + } + + } + + public static ResultSet executeSelectSql(String sql) throws SQLException { + Statement st = connection.createStatement(); + try { + connection.setAutoCommit(false); + System.out.println("sql===" + sql); + rs = st.executeQuery(sql); + // conn.commit(); + } catch (SQLException e) { + if (st != null) + st.close(); + connection.rollback(); + connection.close(); + } + return rs; + + } + + /** + * ͷԴ + */ + 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(DbPool.rs, DbPool.ps); + } + + /** + * ͷԴ(ȫͷ) + */ + public final static void freeAll() { + free(DbPool.rs, DbPool.ps, DbPool.connection); + } + + /** + * ͷԴ(ҲҪȫͷ) + */ + public final static void free(ResultSet resultSet, Statement statement, + Connection connection) { + try { + if (resultSet != null) { + try { + resultSet.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + } finally { + try { + if (statement != null) { + try { + statement.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + } finally { + if (connection != null) { + try { + connection.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + } + } + } +} diff --git a/src/com/connor/lidy/create/PictureMaterialDialog.java b/src/com/connor/lidy/create/PictureMaterialDialog.java new file mode 100644 index 0000000..a464eb2 --- /dev/null +++ b/src/com/connor/lidy/create/PictureMaterialDialog.java @@ -0,0 +1,285 @@ +package com.connor.lidy.create; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Vector; +import java.util.Map.Entry; + +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.JTextField; +import javax.swing.table.DefaultTableModel; + +import com.connor.lidy.util.TCUtil; +import com.teamcenter.rac.aif.AIFDesktop; +import com.teamcenter.rac.aif.AbstractAIFDialog; +import com.teamcenter.rac.aif.kernel.AIFComponentContext; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCException; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.stylesheet.PropertyDateComponent; +import com.teamcenter.rac.util.MessageBox; + + +public class PictureMaterialDialog extends AbstractAIFDialog { + private static final long serialVersionUID = 1L; + private TCSession session; + private JButton searchBtn; + private JButton exportBtn; + private JButton closeBtn; +// private JButton nextPageBtn; +// private JButton prePageBtn; +// private JButton firstPageBtn; +// private JButton lastPageBtn; + private JTable impTable; + private DefaultTableModel impModel; + private Map compMap; + private Map tableMap; +// private int nowPage = 0; +// private int totalPage = 0; +// private final int rowsEveryPage = 20;//ÿҳ + + + + public PictureMaterialDialog(TCSession session, TCComponentItemRevision target, String search, String[] options) throws Exception { + super(AIFUtility.getActiveDesktop()); + this.session = session; + compMap = new HashMap<>(); + tableMap = new HashMap<>(); + setTitle("Ŀ"); + + JPanel msgPanel = new JPanel(new GridLayout(0,3,2,5)); +// msgPanel.setBorder(new TitledBorder(BorderFactory.createEtchedBorder(), "ʱ")); + + JLabel label1 = new JLabel(""); + label1.setPreferredSize(new Dimension(100, 23)); + JPanel propPanel1 = new JPanel(new BorderLayout()); + propPanel1.add(BorderLayout.WEST, label1); + JTextField field1 = new JTextField(); + field1.setPreferredSize(new Dimension(118, 23)); + propPanel1.add(BorderLayout.CENTER, field1); + msgPanel.add(propPanel1); + compMap.put(label1.getText(), field1); + /*JLabel label2 = new JLabel("Ʒͺ"); + label2.setPreferredSize(new Dimension(100, 23)); + JPanel propPanel2 = new JPanel(new BorderLayout()); + propPanel2.add(BorderLayout.WEST, label2); + JTextField field2 = new JTextField(); + field2.setPreferredSize(new Dimension(118, 23)); + propPanel2.add(BorderLayout.CENTER, field2); + msgPanel.add(propPanel2); + compMap.put(label2.getText(), field2); + JLabel label3 = new JLabel("ͼ"); + label3.setPreferredSize(new Dimension(100, 23)); + JPanel propPanel3 = new JPanel(new BorderLayout()); + propPanel3.add(BorderLayout.WEST, label3); + JTextField field3 = new JTextField(); + field3.setPreferredSize(new Dimension(118, 23)); + propPanel3.add(BorderLayout.CENTER, field3); + msgPanel.add(propPanel3); + compMap.put(label3.getText(), field3);*/ + + searchBtn = new JButton("ѯ"); + exportBtn = new JButton("ȷ"); + closeBtn = new JButton("ر"); +// firstPageBtn = new JButton("ҳ"); +// lastPageBtn = new JButton("βҳ"); +// nextPageBtn = new JButton("һҳ"); +// prePageBtn = new JButton("һҳ"); + JPanel btnPanel = new JPanel(new FlowLayout()); + btnPanel.add(searchBtn); + btnPanel.add(exportBtn); + btnPanel.add(closeBtn); + JPanel topPanel = new JPanel(new BorderLayout()); + topPanel.add(BorderLayout.CENTER, msgPanel); + topPanel.add(BorderLayout.SOUTH, btnPanel); + + String[] tableHeader = new String[] { "", "", "Ŀ", "WBS", "Ʒ", "Ʒͺ" }; + + 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; i0) { + for(int i=impModel.getRowCount(); i>0; i--) + impModel.removeRow(i-1); + } + Vector keyV = new Vector<>(); + Vector valueV = new Vector<>(); + String text = ""; + for(Entry e : compMap.entrySet()) { + JComponent c = e.getValue(); + + if(c instanceof JTextField) + text = ((JTextField)c).getText(); + else if(c instanceof PropertyDateComponent) + text = ((PropertyDateComponent)c).getDateViewModel().getDateString(); + else + text = ((JComboBox)c).getSelectedItem().toString(); + if(text!=null && !text.isEmpty()) { + keyV.add(e.getKey()); + //2022/11/21ȡǰ* +// valueV.add("*"+text+"*"); + valueV.add(text); + } + } + if(text == null || text.isEmpty()) + throw new Exception("ѯ"); + + long time1 = System.nanoTime(); + //TCComponent[] result = TCUtil.query(session, search, keyV, valueV); + + ResultSet rs = null; + try { + text = text.replaceAll("\\*", "%"); + System.out.println("name=="+text); + String selectSql = "SELECT t1.puid,t1.pobject_name,c.pml8_ProjectManagement,c.pml8_WBSNo,c.pml8_ProductCode,c.pml8_ProductType FROM PWORKSPACEOBJECT t1 inner join (select t1.puid,t2.pname from PRELEASE_STATUS_LIST t1 inner join PRELEASESTATUS t2 on t1.pvalu_0=t2.puid)t2 on t1.puid = t2.puid inner join (select b.puid,d.pml8_ProjectManagement,d.pml8_WBSNo,d.pml8_ProductCode,d.pml8_ProductType from PFORM b,PML8_PROJECTFORMSTORAGE d where b.rdata_fileu = d.puid) c on c.puid = t1.puid where t1.pobject_name like '"+text+"' and t1.pobject_type = 'ML8_ProjectForm'"; + DbPool.getConnection(); + rs = DbPool.executeSelectSql(selectSql); + + LinkedHashMap> map =new LinkedHashMap>(); + if(rs != null) + { + while(rs.next()) + { + ArrayList list =new ArrayList(); + + list.add(rs.getString(2)); + list.add(rs.getString(3)); + list.add(rs.getString(4)); + list.add(rs.getString(5)); + list.add(rs.getString(6)); + map.put(rs.getString(1), list); + } + } + System.out.println("list==========="+map.size()); + if (map == null || map.size() == 0) { + MessageBox.post(AIFDesktop.getActiveDesktop(), "ѯΪգ", "", MessageBox.INFORMATION); + return; + } + + //TCComponent[] result = session.stringToComponent(list.toArray(new String[0])); + + long time2 = System.nanoTime(); + System.out.println("ѯʱ(ms) " + (time2 - time1) + / 1000000); +// System.out.println("result:"+result.length); +// if(result.length==0) { +// MessageBox.post("δѯĿ","",MessageBox.INFORMATION); +// return; +// } + long time3 = System.nanoTime(); + + int count = 1; + for (Entry> tempMap : map.entrySet()) { + String key = tempMap.getKey(); + ArrayList value = tempMap.getValue(); + Vector v = new Vector<>(); + v.add(count+"");// + v.add(value.get(0));// + v.add(value.get(1));//Ŀ + v.add(value.get(2));//WBS + v.add(value.get(3));//Ʒ + v.add(value.get(4));//Ʒͺ + + tableMap.put(count, session.stringToComponent(key)); + impModel.addRow(v); + count++; + } + + long time4 = System.nanoTime(); + System.out.println("ʱ(ms) " + (time4 - time3) + / 1000000); + + } catch (Exception e1) { + e1.printStackTrace(); + } + + + } + + private void addActionListener(TCComponentItemRevision target, String search) { + + final AbstractAIFDialog dialog = this; + searchBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + try { + PictureMaterialOperation operation= new PictureMaterialOperation(tableMap,0,target,dialog,search,"ѯ",session); + session.queueOperation(operation); + } catch (Exception e1) { + e1.printStackTrace(); + MessageBox.post(dialog, ""+e1.getMessage(), "ERROR", MessageBox.ERROR); + } + } + + }); + exportBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + try { + int row = impTable.getSelectedRow(); + if(row<0) + throw new Exception("ѡĵ"); + PictureMaterialOperation operation= new PictureMaterialOperation(tableMap,row,target,dialog,"","",session); + session.queueOperation(operation); + } catch (Exception e1) { + e1.printStackTrace(); + MessageBox.post(dialog, ""+e1.getMessage(), "ERROR", MessageBox.ERROR); + } + } + }); + closeBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + dispose(); + } + }); + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/create/PictureMaterialHandler.java b/src/com/connor/lidy/create/PictureMaterialHandler.java new file mode 100644 index 0000000..768fc7c --- /dev/null +++ b/src/com/connor/lidy/create/PictureMaterialHandler.java @@ -0,0 +1,89 @@ +package com.connor.lidy.create; + +import javax.swing.JOptionPane; + +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.AbstractAIFUIApplication; +import com.teamcenter.rac.aif.kernel.AIFComponentContext; +import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +//ļнṹ +public class PictureMaterialHandler extends AbstractHandler implements IHandler{ + + public Object execute(ExecutionEvent arg0) throws ExecutionException { + System.out.println("PictureMaterialHandler"); + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + new Thread() { + public void run(){ + try { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + TCSession session = (TCSession) app.getSession(); + InterfaceAIFComponent target = app.getTargetComponent(); + if(target==null || !(target instanceof TCComponentItemRevision)) { + MessageBox.post(desktop, "ѡԭϰ汾е", "ERROR", MessageBox.ERROR); + return; + } + TCComponentItemRevision rev = (TCComponentItemRevision) target; +// TCComponentItemRevision[] revs = rev.getItem().getWorkingItemRevisions(); +// if(revs.length==0) { +// MessageBox.post(desktop, "ѡδ汾д", "ERROR", MessageBox.ERROR); +// return null; +// } +// System.out.println("Working:"+revs[0]); +// if(!rev.equals(revs[revs.length-1])) { +// MessageBox.post(desktop, "ѡδ汾д", "ERROR", MessageBox.ERROR); +// return null; +// } + if(rev.getReferenceListProperty("release_status_list").length>0) { + MessageBox.post(desktop, "ѡδ汾д", "ERROR", MessageBox.ERROR); + return; + } + if(!rev.getProperty("item_revision_id").equals("A")) { + AIFComponentContext[] forms = rev.getChildren("ML8_ProjectRelation"); + if(forms.length>0) { + MessageBox.post(desktop, "ѡδ汾д", "ERROR", MessageBox.ERROR); + return; + } + } + String pref = "ML8_PictureMaterial"; + String options[] = session.getPreferenceService().getStringValues(pref); + if(options==null || options.length==0) { + MessageBox.post(desktop, "ѡ"+pref+"òȷ", "ERROR", MessageBox.ERROR); + return; + } + String type = rev.getItem().getType(); + boolean props = false; + for(String s : options) { + if(s.equals(type)) + props = true; + } + if(!props) { + MessageBox.post(desktop, "ѡİ汾ͲڷΧ", "ERROR", MessageBox.ERROR); + return; + } + AIFComponentContext[] children = rev.getChildren("ML8_ProjectRelation"); + if(children.length>0) { + int choose = JOptionPane.showOptionDialog(desktop, "ѡжĿǷ滻?", "ʾ", + JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new String[] {"",""}, ""); + if(choose!=0) + return; + } + new PictureMaterialDialog(session, rev, options[0], null); + }catch(Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + } + } + }.start(); + return null; + } +} diff --git a/src/com/connor/lidy/create/PictureMaterialOperation.java b/src/com/connor/lidy/create/PictureMaterialOperation.java new file mode 100644 index 0000000..a92adcb --- /dev/null +++ b/src/com/connor/lidy/create/PictureMaterialOperation.java @@ -0,0 +1,72 @@ +package com.connor.lidy.create; + +import java.util.Map; + +import com.teamcenter.rac.aif.AbstractAIFDialog; +import com.teamcenter.rac.aif.AbstractAIFOperation; +import com.teamcenter.rac.aif.kernel.AIFComponentContext; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCException; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.kernel.TCUserService; +import com.teamcenter.rac.util.MessageBox; + +public class PictureMaterialOperation extends AbstractAIFOperation{ + private Map tableMap; + private int row; + private TCComponentItemRevision target; + private AbstractAIFDialog dialog; + private String exec; + private String search; + private TCSession session; + public PictureMaterialOperation(Map tableMap,int row,TCComponentItemRevision target,AbstractAIFDialog dialog,String search,String exec,TCSession session) { + this.tableMap=tableMap; + this.row=row; + this.target=target; + this.dialog=dialog; + this.exec = exec; + this.search = search; + this.session = session; + } + @Override + public void executeOperation() throws Exception { + switch (exec) { + case "": + export(); + + break; + case "ѯ": + ((PictureMaterialDialog)dialog).search(search); + + break; + + default: + break; + } + } + private void export() throws TCException { + TCComponent comp = tableMap.get(row); + AIFComponentContext[] children = target.getChildren("ML8_ProjectRelation"); + if(children.length>0) { + for(AIFComponentContext c : children) + target.remove("ML8_ProjectRelation", (TCComponent)c.getComponent()); + } + target.add("ML8_ProjectRelation", comp); + + TCUserService userservice = session.getUserService(); + Object[] obj = new Object[1]; + obj[0] = target; + Object res = userservice.call("updateFormChangeDesc", obj); + + +// AIFComponentContext[] forms = comp.getChildren("ML8_ProjectRelation"); +// System.out.println("forms:"+forms.length); +// if(forms.length>0) { +// for(AIFComponentContext c : forms) +// target.add("ML8_ProjectRelation", (TCComponent)c.getComponent()); +// } + MessageBox.post(dialog, "޸", "INFO", MessageBox.INFORMATION); + dialog.dispose(); + } +} diff --git a/src/com/connor/lidy/create/PictureMaterialSaveDialog.java b/src/com/connor/lidy/create/PictureMaterialSaveDialog.java new file mode 100644 index 0000000..b928589 --- /dev/null +++ b/src/com/connor/lidy/create/PictureMaterialSaveDialog.java @@ -0,0 +1,236 @@ +package com.connor.lidy.create; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.HashMap; +import java.util.Map; +import java.util.Vector; +import java.util.Map.Entry; + +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.JTextField; +import javax.swing.table.DefaultTableModel; + +import com.connor.lidy.util.TCUtil; +import com.teamcenter.rac.aif.AbstractAIFDialog; +import com.teamcenter.rac.aif.kernel.AIFComponentContext; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCComponentPseudoFolder; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.stylesheet.PropertyDateComponent; +import com.teamcenter.rac.util.MessageBox; + +public class PictureMaterialSaveDialog extends AbstractAIFDialog { + private static final long serialVersionUID = 1L; + private TCSession session; + private JButton searchBtn; + private JButton exportBtn; + private JButton closeBtn; + private JTable impTable; + private DefaultTableModel impModel; + private Map compMap; + private Map tableMap; + + public PictureMaterialSaveDialog(TCSession session, TCComponentItemRevision target, String search, String[] options) throws Exception { + super(AIFUtility.getActiveDesktop()); + this.session = session; + compMap = new HashMap<>(); + tableMap = new HashMap<>(); + setTitle("ͼ"); + + JPanel msgPanel = new JPanel(new GridLayout(0,3,2,5)); +// msgPanel.setBorder(new TitledBorder(BorderFactory.createEtchedBorder(), "ʱ")); + + JLabel label1 = new JLabel("Ʒ"); + label1.setPreferredSize(new Dimension(100, 23)); + JPanel propPanel1 = new JPanel(new BorderLayout()); + propPanel1.add(BorderLayout.WEST, label1); + JTextField field1 = new JTextField(); + field1.setPreferredSize(new Dimension(118, 23)); + propPanel1.add(BorderLayout.CENTER, field1); + msgPanel.add(propPanel1); + compMap.put(label1.getText(), field1); + JLabel label2 = new JLabel("Ʒͺ"); + label2.setPreferredSize(new Dimension(100, 23)); + JPanel propPanel2 = new JPanel(new BorderLayout()); + propPanel2.add(BorderLayout.WEST, label2); + JTextField field2 = new JTextField(); + field2.setPreferredSize(new Dimension(118, 23)); + propPanel2.add(BorderLayout.CENTER, field2); + msgPanel.add(propPanel2); + compMap.put(label2.getText(), field2); + JLabel label3 = new JLabel("ͼ"); + label3.setPreferredSize(new Dimension(100, 23)); + JPanel propPanel3 = new JPanel(new BorderLayout()); + propPanel3.add(BorderLayout.WEST, label3); + JTextField field3 = new JTextField(); + field3.setPreferredSize(new Dimension(118, 23)); + propPanel3.add(BorderLayout.CENTER, field3); + msgPanel.add(propPanel3); + compMap.put(label3.getText(), field3); + + searchBtn = new JButton("ѯ"); + exportBtn = new JButton("ȷ"); + closeBtn = new JButton("ر"); + JPanel btnPanel = new JPanel(new FlowLayout()); + btnPanel.add(searchBtn); + btnPanel.add(exportBtn); + btnPanel.add(closeBtn); + JPanel topPanel = new JPanel(new BorderLayout()); + topPanel.add(BorderLayout.CENTER, msgPanel); + topPanel.add(BorderLayout.SOUTH, btnPanel); + + String[] tableHeader = new String[] { "", "ĵ", "汾", "ĵ", "Ŀ", "Ʒ", "", "", "ƺ׺" }; + + 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; i0) { + for(int i=impModel.getRowCount(); i>0; i--) + impModel.removeRow(i-1); + } + Vector keyV = new Vector<>(); + Vector valueV = new Vector<>(); + for(Entry e : compMap.entrySet()) { + JComponent c = e.getValue(); + String text = ""; + if(c instanceof JTextField) + text = ((JTextField)c).getText(); + else if(c instanceof PropertyDateComponent) + text = ((PropertyDateComponent)c).getDateViewModel().getDateString(); + else + text = ((JComboBox)c).getSelectedItem().toString(); + if(text!=null && !text.isEmpty()) { + keyV.add(e.getKey()); + valueV.add("*"+text+"*"); + } + } + if(keyV.size()==0) + throw new Exception("ѯ"); + TCComponent[] result = TCUtil.query(session, search, keyV, valueV); + System.out.println("result:"+result.length); + for(int i=0; i v = new Vector<>(); + v.add(i+1+"");// + v.add(result[i].getProperty("item_id"));//ĵ + v.add(result[i].getProperty("item_revision_id"));//汾 + v.add(result[i].getProperty("object_name"));//ĵ + + AIFComponentContext[] children = result[i].getChildren("ML8_ProjectRelation"); + if(children.length>0) { + TCComponent form = (TCComponent)children[0].getComponent(); + v.add(form.getProperty("object_name"));//Ŀ + v.add(form.getProperty("ml8_ProductCode"));//Ʒ + }else { + v.add("");//Ŀ + v.add("");//Ʒ + } + + v.add(result[i].getProperty("ml8_Materials"));// + v.add(result[i].getProperty("ml8_Suttle"));// + v.add(result[i].getProperty("ml8_NameSuffix"));//ƺ׺ + + tableMap.put(i, result[i]); + impModel.addRow(v); + } + } catch (Exception e1) { + e1.printStackTrace(); + MessageBox.post(dialog, ""+e1.getMessage(), "ERROR", MessageBox.ERROR); + } + } + }); + exportBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + try { + int row = impTable.getSelectedRow(); + if(row<0) + throw new Exception("ѡĵ"); + TCComponent comp = tableMap.get(row); + for(String s : options) { + if(!s.contains("=")) + continue; + String[] ss = s.split("="); + target.setProperty(ss[0], comp.getProperty(ss[1])); + } + AIFComponentContext[] children = target.getChildren("ML8_ProjectRelation"); + if(children.length>0) { + for(AIFComponentContext c : children) + target.remove("ML8_ProjectRelation", (TCComponent)c.getComponent()); + } + AIFComponentContext[] forms = comp.getChildren("ML8_ProjectRelation"); + System.out.println("forms:"+forms.length); + if(forms.length>0) { + for(AIFComponentContext c : forms) + target.add("ML8_ProjectRelation", (TCComponent)c.getComponent()); + } + TCComponentPseudoFolder TC_Is_Represented_By = TCUtil.getPseudoFolder(target, "TC_Is_Represented_By"); + AIFComponentContext[] cs = TC_Is_Represented_By.getChildren(); + if(cs.length>0) { + for(AIFComponentContext c : cs) + TC_Is_Represented_By.remove("TC_Is_Represented_By", (TCComponent)c.getComponent()); + } + target.add("TC_Is_Represented_By", comp); + MessageBox.post(dialog, "޸", "INFO", MessageBox.INFORMATION); + dispose(); + } catch (Exception e1) { + e1.printStackTrace(); + MessageBox.post(dialog, ""+e1.getMessage(), "ERROR", MessageBox.ERROR); + } + } + }); + closeBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + dispose(); + } + }); + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/create/PictureMaterialSaveHandler.java b/src/com/connor/lidy/create/PictureMaterialSaveHandler.java new file mode 100644 index 0000000..a236e08 --- /dev/null +++ b/src/com/connor/lidy/create/PictureMaterialSaveHandler.java @@ -0,0 +1,80 @@ +package com.connor.lidy.create; + +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.AbstractAIFUIApplication; +import com.teamcenter.rac.aif.kernel.AIFComponentContext; +import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +//ļнṹ +public class PictureMaterialSaveHandler extends AbstractHandler implements IHandler{ + + public Object execute(ExecutionEvent arg0) throws ExecutionException { + System.out.println("PictureMaterialSaveHandler"); + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + try { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + TCSession session = (TCSession) app.getSession(); + InterfaceAIFComponent target = app.getTargetComponent(); + if(target==null || !(target instanceof TCComponentItemRevision)) { + MessageBox.post(desktop, "ѡԭϰ汾е", "ERROR", MessageBox.ERROR); + return null; + } + TCComponentItemRevision rev = (TCComponentItemRevision) target; +// TCComponentItemRevision[] revs = rev.getItem().getWorkingItemRevisions(); +// if(revs.length==0) { +// MessageBox.post(desktop, "ѡδ汾д", "ERROR", MessageBox.ERROR); +// return null; +// } +// System.out.println("Working:"+revs[0]); +// if(!rev.equals(revs[revs.length-1])) { +// MessageBox.post(desktop, "ѡδ汾д", "ERROR", MessageBox.ERROR); +// return null; +// } + if(rev.getReferenceListProperty("release_status_list").length>0) { + MessageBox.post(desktop, "ѡδ汾д", "ERROR", MessageBox.ERROR); + return null; + } + if(!rev.getProperty("item_revision_id").equals("A")) { + AIFComponentContext[] forms = rev.getChildren("ML8_ProjectRelation"); + if(forms.length>0) { + MessageBox.post(desktop, "ѡδ汾д", "ERROR", MessageBox.ERROR); + return null; + } + } + String pref = "ML8_PictureMaterialSave"; + String options[] = session.getPreferenceService().getStringValues(pref); + if(options==null || options.length==0) { + MessageBox.post(desktop, "ѡ"+pref+"òȷ", "ERROR", MessageBox.ERROR); + return null; + } + String type = rev.getItem().getType()+":"; + String[] props = null; + for(String s : options) { + if(s.startsWith(type)) + props = s.substring(type.length()).split(";"); + } + if(props==null) { + MessageBox.post(desktop, "ѡİ汾ͲڷΧ", "ERROR", MessageBox.ERROR); + return null; + } + if(rev.getProperty("ml8_FigureNum").isEmpty()) { + MessageBox.post(desktop, "ѡİ汾Ϊͼ޷ʹô˹", "ERROR", MessageBox.ERROR); + return null; + } + new PictureMaterialSaveDialog(session, rev, options[0], props); + }catch(Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + } + return null; + } +} diff --git a/src/com/connor/lidy/create/SpectrumStructureDialog.java b/src/com/connor/lidy/create/SpectrumStructureDialog.java new file mode 100644 index 0000000..3adeb18 --- /dev/null +++ b/src/com/connor/lidy/create/SpectrumStructureDialog.java @@ -0,0 +1,325 @@ +package com.connor.lidy.create; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; + +import org.dom4j.Document; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; + +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.common.create.BOCreateDefinition; +import com.teamcenter.rac.common.create.BOCreateDefinitionFactory; +import com.teamcenter.rac.common.create.CreateInstanceInput; +import com.teamcenter.rac.common.create.ICreateInstanceInput; +import com.teamcenter.rac.common.create.SOAGenericCreateHelper; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentFolder; +import com.teamcenter.rac.kernel.TCComponentFolderType; +import com.teamcenter.rac.kernel.TCComponentListOfValues; +import com.teamcenter.rac.kernel.TCComponentListOfValuesType; +import com.teamcenter.rac.kernel.TCComponentTcFile; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.stylesheet.PropertyDateComponent; +import com.teamcenter.rac.util.MessageBox; +import com.teamcenter.rac.util.PropertyLayout; +import com.teamcenter.services.rac.core.LOVService; +import com.teamcenter.services.rac.core._2013_05.LOV.InitialLovData; +import com.teamcenter.services.rac.core._2013_05.LOV.LOVSearchResults; +import com.teamcenter.services.rac.core._2013_05.LOV.LOVValueRow; +import com.teamcenter.services.rac.core._2013_05.LOV.LovFilterData; + +public class SpectrumStructureDialog extends AbstractAIFDialog { + private static final long serialVersionUID = 1L; + private TCSession session; + private JButton exportBtn; + private JButton cancelBtn; + private HashMap searchMap; + private TCComponent target; + private String folderType; + private String where; + private List mustList; + private HashSet checkSet; + + @SuppressWarnings("unchecked") + public SpectrumStructureDialog(TCSession session, TCComponent target, TCComponentDataset model) throws Exception { + super(AIFUtility.getActiveDesktop()); + this.session = session; + this.searchMap = new HashMap<>(); + this.mustList = new ArrayList<>(); + this.checkSet = new HashSet<>(); + this.target = target; + + TCComponentTcFile[] files = model.getTcFiles(); + File xmlFile = files[0].getFile(System.getProperty("java.io.tmpdir")); + Document doc = new SAXReader().read(xmlFile); + Element Mroot = doc.getRootElement(), element = null; + TCComponent parent = null; + List ItemTypes = Mroot.elements("ItemType"); + String name = target.getProperty("object_name"); + for(Object o : ItemTypes) { + Element itemtype = (Element) o; + if(!target.isTypeOf(itemtype.attributeValue("objectType"))) + continue; + String objectName = itemtype.attributeValue("objectName"); + if(!objectName.isEmpty() && !name.equals(objectName)) + continue; + String pname = itemtype.attributeValue("parentName"); + if(!pname.isEmpty()) { + AIFComponentContext[] parents = target.whereReferencedByTypeRelation(null, null); + for(AIFComponentContext c : parents) { +// System.out.println("parents:"+c.getComponent().getProperty("object_name")); + if(c.getComponent().getProperty("object_name").equals(pname)) { + parent = (TCComponent) c.getComponent(); + break; + } + } + if(parent == null) + continue; + } + element = itemtype; + folderType = element.attributeValue("createType"); + where = element.attributeValue("where"); + break; + } + if(element == null) + throw new Exception("ѡͲxml÷Χ"); +// if(parent == null) +// throw new Exception("δҵĸ"); + + setTitle("׽ṹ"); + JPanel propPanel = new JPanel(new PropertyLayout(70, 5, 10, 5, 5, 5)); + int row = 1; + TCComponentListOfValuesType lovType = (TCComponentListOfValuesType)session.getTypeComponent("ListOfValues"); +// TCComponentListOfValues[] lov = lovType.find("ML8_ProjectCategory_LOV"); +// String[] vals = getDynamicLOV(lov[0]); +// System.out.println("ML8_ProjectCategory_LOV:"+lov[0].getType()+"=="+vals.length); + for(Object o : element.elements()) { + Element e = (Element) o; + String defaultValue = e.attributeValue("defaultValue"); + if(defaultValue.startsWith("@")) + defaultValue = target.getProperty(defaultValue.substring(1)); + if(e.attributeValue("isMust").equals("true")) { + JLabel label = new JLabel(""+e.attributeValue("displayName")+"*"); + propPanel.add(row+".1.left.center", label); + mustList.add(e.attributeValue("realName")); + }else { + JLabel label = new JLabel(e.attributeValue("displayName")); + propPanel.add(row+".1.left.center", label); + } + if(e.attributeValue("propertyType").equals("Date")) { + PropertyDateComponent date = new PropertyDateComponent(); + if(e.attributeValue("Enabled").equals("false")) + date.setEnabled(false); + propPanel.add(row+".2.right.center", date); + searchMap.put(e.attributeValue("realName"), date); + }else if(e.attributeValue("propertyType").equals("lov")) { + JComboBox combo = new JComboBox<>(); + combo.setPreferredSize(new Dimension(150, 23)); + combo.addItem(""); + TCComponentListOfValues[] lovs = lovType.find(e.attributeValue("lovName"));//TODO lov + if(lovs==null || lovs.length==0) + throw new Exception("δҵLOV"+e.attributeValue("lovName")); + if(lovs[0].isTypeOf("Fnd0ListOfValuesDynamic")) { + for(String item : getDynamicLOV(lovs[0])) { + combo.addItem(item); + } + } + + combo.setSelectedItem(defaultValue); + if(e.attributeValue("Enabled").equals("false")) + combo.setEnabled(false); + propPanel.add(row+".2.right.center", combo); + searchMap.put(e.attributeValue("realName"), combo); + }else { + JTextField text = new JTextField(); + text.setPreferredSize(new Dimension(150, 23)); + text.setText(defaultValue); + if(e.attributeValue("Enabled").equals("false")) + text.setEnabled(false); + propPanel.add(row+".2.right.center", text); + searchMap.put(e.attributeValue("realName"), text); + } + row++; + } + if(!searchMap.containsKey("object_name")) + throw new Exception("δobject_nameд"); + exportBtn = new JButton(""); + cancelBtn = new JButton("ȡ"); + JPanel btnPanel = new JPanel(new FlowLayout()); + btnPanel.add(exportBtn); + btnPanel.add(cancelBtn); + setLayout(new BorderLayout()); + add(BorderLayout.CENTER, propPanel); + add(BorderLayout.SOUTH, btnPanel); +// add(new JLabel("")); + addActionListener(""); + + if(!where.isEmpty()) { + String[] wheres = where.split("\\+"); + for(AIFComponentContext c : target.getChildren("contents")) { + InterfaceAIFComponent comp = c.getComponent(); + String ck = ""; + for(String s : wheres) { + ck += comp.getProperty(s); + } + checkSet.add(ck); + } + } + + pack(); + if(row>5) + setSize(new Dimension(380, 220+(row-5)*25)); + else + setSize(new Dimension(380, 220)); + 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) { + exportBtn.addActionListener(new ActionListener() { + @SuppressWarnings({ "deprecation" }) + @Override + public void actionPerformed(ActionEvent arg0) { +// AIFDesktop desktop = AIFUtility.getActiveDesktop(); + TCComponentFolder folder = null; + try { + String name = ((JTextField)searchMap.get("object_name")).getText(); + for(String s : mustList) { + JComponent c = searchMap.get(s); + if(c instanceof JTextField) { + if(((JTextField)searchMap.get(s)).getText().isEmpty()) + throw new Exception("бδд"); + }else { + if(((JComboBox)c).getSelectedItem().toString().isEmpty()) + throw new Exception("бδд"); + } + } + if(name.isEmpty()) + throw new Exception("δдƣ޷д"); + if(!where.isEmpty()) { + String[] wheres = where.split("\\+"); + String check = ""; + for(String s : wheres) { + JComponent c = searchMap.get(s); + if(c instanceof JTextField) { + check += ((JTextField)searchMap.get(s)).getText(); + }else if(c instanceof JComboBox){ + check += ((JComboBox)c).getSelectedItem().toString(); + } + } + if(checkSet.contains(check)) + throw new Exception(where+"ͬѴڣ"); + } + + TCComponentFolderType type = (TCComponentFolderType) session.getTypeService().getTypeComponent(folderType); + if(type==null) + throw new Exception("δҵͣ"+folderType); +// TCComponentFolder folder = type.create(name, "", folderType); + List input = new ArrayList(); + BOCreateDefinition itemDef = (BOCreateDefinition) BOCreateDefinitionFactory.getInstance().getCreateDefinition(session, folderType); + CreateInstanceInput createInput = new CreateInstanceInput(itemDef); + createInput.add("object_name", name); + input.add(createInput); + //SOAGenericCreateHelper helper = new SOAGenericCreateHelper(); + List list1 = SOAGenericCreateHelper.create(session, itemDef, input); + if(list1.size()==0) + throw new Exception("ļдʧ"); + folder = (TCComponentFolder) list1.get(0); + for(String s : searchMap.keySet()) { + JComponent c = searchMap.get(s); + if(c instanceof PropertyDateComponent) { + Date date = ((PropertyDateComponent)c).getDate(); + if(date!=null) + folder.setDateProperty(s, date); + }else if(c instanceof JTextField) { + String value = ((JTextField)c).getText(); + folder.setProperty(s, value); + }else { + String value = ((JComboBox)c).getSelectedItem().toString(); + folder.setProperty(s, value); + } + } + target.add("contents", folder); + long time = new Date().getTime(); + System.out.println("time:0"); + MessageBox.post(SpectrumStructureDialog.this, "", "INFO", MessageBox.INFORMATION); + System.out.println("time:"+(new Date().getTime()-time)); + dispose(); + System.out.println("time:"+(new Date().getTime()-time)); + }catch(Exception e1) { + e1.printStackTrace(); + if(folder != null) + try { + folder.delete(); + } catch (Exception e) { + e.printStackTrace(); + } + MessageBox.post(SpectrumStructureDialog.this, ""+e1.getMessage(), "ERROR", MessageBox.ERROR); + } + } + }); + cancelBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + dispose(); + } + }); + } + + public String[] getDynamicLOV(TCComponentListOfValues lov) throws Exception { + Vector lovDisplayValueList = new Vector<>(); +// lovDisplayValueList.add(""); +// Vector lovValueList = new Vector<>(); + LOVService lovService = LOVService.getService(session); + InitialLovData input = new InitialLovData(); + LovFilterData filter = new LovFilterData(); + filter.sortPropertyName = "object_name"; + filter.order = 1; + filter.numberToReturn = 100; + filter.maxResults = 100; + + input.lov = lov; + input.filterData = filter; + LOVSearchResults result = lovService.getInitialLOVValues(input); +// StringBuffer sb = new StringBuffer(); +// sb.append(">>"); + for (LOVValueRow row : result.lovValues) { + Map map = row.propDisplayValues; +// Map realmap = row.propInternalValues; + for (String key : map.keySet()) { +// sb.append("UID:" + row.uid + ",key:" + key + "value:" + map.get(key)[0]); +// sb.append("\n"); + lovDisplayValueList.add(map.get(key)[0]); +// lovValueList.add(realmap.get(key)[0]); + } + } +// System.out.println("StringBuffer:"+sb.toString()); + return lovDisplayValueList.toArray(new String[lovDisplayValueList.size()]); + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/create/SpectrumStructureHandler.java b/src/com/connor/lidy/create/SpectrumStructureHandler.java new file mode 100644 index 0000000..cec94bb --- /dev/null +++ b/src/com/connor/lidy/create/SpectrumStructureHandler.java @@ -0,0 +1,45 @@ +package com.connor.lidy.create; + +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.AbstractAIFUIApplication; +import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +//ļнṹ +public class SpectrumStructureHandler extends AbstractHandler implements IHandler{ + + public Object execute(ExecutionEvent arg0) throws ExecutionException { + System.out.println("SpectrumStructureHandler"); + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + try { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + String pref = "ML8_SpectrumStructure"; + TCSession session = (TCSession) app.getSession(); + String options = session.getPreferenceService().getStringValue(pref); + if(options==null || options.isEmpty()) { + MessageBox.post(desktop, "ѡ"+pref+"òȷ", "ERROR", MessageBox.ERROR); + return null; + } + TCComponent model = session.stringToComponent(options);//AKLAAInU5kSPsC + if(model==null || !model.isTypeOf("XMLRenderingStylesheet")) { + MessageBox.post(desktop, "ѡ"+pref+"ģUIDòȷ", "ERROR", MessageBox.ERROR); + return null; + } + InterfaceAIFComponent target = app.getTargetComponent(); + new SpectrumStructureDialog(session, (TCComponent)target, (TCComponentDataset)model); + }catch(Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + } + return null; + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/dialog/AssignProjectDialog.java b/src/com/connor/lidy/dialog/AssignProjectDialog.java new file mode 100644 index 0000000..e2bbf3a --- /dev/null +++ b/src/com/connor/lidy/dialog/AssignProjectDialog.java @@ -0,0 +1,316 @@ +/* +#============================================================================= +# +# opyright (c) 2009 Origin Enterprise Solution LTD. +# +#============================================================================= +# File name: CopyFolderAndAssginToProjectDialog.java +# File description: +#============================================================================= +# Date Name Action Description of Change +# 2017-5-10 Administrator Ini ʼ +#============================================================================= + */ +package com.connor.lidy.dialog; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.sql.Connection; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Vector; + +import javax.swing.BorderFactory; +import javax.swing.DefaultListModel; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSplitPane; +import javax.swing.JTextField; +import javax.swing.ListSelectionModel; +import javax.swing.border.TitledBorder; + +import com.connor.lidy.util.SqlUtil; +import com.teamcenter.rac.aif.AbstractAIFDialog; +import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentContextList; +import com.teamcenter.rac.kernel.TCComponentProject; +import com.teamcenter.rac.kernel.TCComponentProjectType; +import com.teamcenter.rac.kernel.TCComponentQuery; +import com.teamcenter.rac.kernel.TCComponentQueryType; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.kernel.TCTextService; +import com.teamcenter.rac.util.ButtonLayout; +import com.teamcenter.rac.util.HorizontalLayout; +import com.teamcenter.rac.util.MessageBox; +import com.teamcenter.rac.util.PropertyLayout; +import com.teamcenter.rac.util.VerticalLayout; + +//import cn.com.ebewin.ysr.util.TCUtil; + +/** + * @author Administrator + */ +//@SuppressWarnings({"rawtypes","unchecked"}) +public class AssignProjectDialog extends AbstractAIFDialog { + + private static final long serialVersionUID = 1L; + TCSession session; +// AbstractAIFUIApplication app; + +// private JList projectList; +// private JList targetList; + private DefaultListModel projectM; + private DefaultListModel targetM; + private JTextField jt2; + private InterfaceAIFComponent[] targets; + private String project; + + public AssignProjectDialog(TCSession pSession, InterfaceAIFComponent[] selectTarget) { + super(AIFUtility.getActiveDesktop(), true); // true + try { + this.session = pSession; + this.targets = selectTarget; + this.project = ""; + init(); + }catch (Exception e) { + e.printStackTrace(); + } + } + + private void init() throws Exception { + setTitle("Ŀϼ"); +// final JPanel jptopleft = new JPanel(new PropertyLayout(2,2,2,2,2,2)); + this.projectM = new DefaultListModel<>(); + this.targetM = new DefaultListModel<>(); + final JPanel jptopleft = new JPanel(new BorderLayout()); + final JPanel jptopright = new JPanel(new VerticalLayout()); + + final TCComponentProjectType tccomponentprojecttype = (TCComponentProjectType) session.getTypeComponent("TC_Project"); + final Vector list = new Vector<>();//listPro("*"); + if(targets.length==1) { + TCComponent[] projects = ((TCComponent)targets[0]).getReferenceListProperty("project_list"); + for(TCComponent p : projects) { + String id = p.getProperty("project_id"); + project += id; + list.add(id); + targetM.addElement(id); + } + } + String user = session.getUser().getUserId(); + final Vector projs = new Vector<>(); +// Vector prov = new Vector<>();//listDCProjTemplFolder(); + //TODO + String options[] = session.getPreferenceService().getStringValues("Meling_SqlServer"); + Connection connection = SqlUtil.getSqlserverConnection(options[0], options[1], options[2], options[3]); + List> search = SqlUtil.getDBInfo(connection, "select a0.pproject_id as id " +// Connection connection = TCUtil.getDBConn(session); +// Vector> search = TCUtil.getDBInfo3Sub(connection, "select a0.pproject_id as id " + + "from PTC_PROJECT a0,PPROJECT_MEMBERS a,PPOM_MEMBER b,PPOM_USER c,PPOM_GROUP d " + + "where a0.rproject_teamu=a.puid and a.pvalu_0=b.puid and b.ruseru=c.puid and b.rgroupu=d.puid " + + "and d.pprivilege=1 and a0.pis_visible=1 and c.puser_id='"+user+"'"); + for(HashMap t : search) { + String id = t.get("id").toString(); + projs.add(id); + if(!list.contains(id)) + projectM.addElement(id); + } + JList projectList = new JList(projectM); + projectList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + jptopleft.setBorder(BorderFactory.createTitledBorder(null, "ѡĿ", TitledBorder.DEFAULT_JUSTIFICATION, + TitledBorder.DEFAULT_POSITION, new Font("", 0, 12))); // NOI18N + JScrollPane folderscrollPane = new JScrollPane(); + folderscrollPane.setPreferredSize(new Dimension(210,310)); + folderscrollPane.getViewport().add(projectList); + jptopleft.add(BorderLayout.CENTER, folderscrollPane); + + JList targetList = new JList(targetM); + jptopright.setBorder(BorderFactory.createTitledBorder(null, "ѡĿ", TitledBorder.DEFAULT_JUSTIFICATION, + TitledBorder.DEFAULT_POSITION, new Font("", 0, 12))); // NOI18N + + targetList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + JScrollPane proscrollPane = new JScrollPane(targetList); + proscrollPane.setPreferredSize(new Dimension(210,310)); + + JButton addbtn = new JButton(">"); + JButton removebtn = new JButton("<"); + addbtn.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent actionevent) { + String select = projectList.getSelectedValue(); + if(select==null) + return; + targetM.addElement(select); + projectM.removeElement(select); + addbtn.setEnabled(false); + } + }); + removebtn.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent actionevent) { + String select = targetList.getSelectedValue(); + if(select==null || select.equals(project)) + return; + projectM.addElement(select); + targetM.removeElement(select); + if(targetM.isEmpty()) + addbtn.setEnabled(true); + else + addbtn.setEnabled(false); + } + }); + if(list.size()>0) + addbtn.setEnabled(false); + JPanel bpane = new JPanel(new PropertyLayout()); + bpane.add("1.1.center.center", addbtn); + bpane.add("2.1.center.center", removebtn); + jptopleft.add(BorderLayout.EAST, bpane); + +// final JTextField jt = new JTextField(30); +// +// jt.addKeyListener(new KeyAdapter() { +// public void keyReleased(KeyEvent ke) { +// char code = ke.getKeyChar(); +// if (code == KeyEvent.VK_ENTER) { +// System.out.println("ceshi س" + code + "=====" + KeyEvent.VK_ENTER); +// Vector pronewVector = listPro(jt.getText()); +// proList.setListData(pronewVector); +// } +// } +// +// }); +// jptopright.add("top.bind.center.top", jt); + jptopright.add("top.bind.center.top", proscrollPane); + + JSplitPane splitPane = new JSplitPane(); + splitPane.setOneTouchExpandable(true);// ÷ָʾͷ + splitPane.setContinuousLayout(true);// ͷػͼ + splitPane.setLeftComponent(jptopleft); + splitPane.setRightComponent(jptopright); + + JPanel jp1 = new JPanel(new HorizontalLayout()); + jt2 = new JTextField(20); + JButton screenbtn = new JButton("ɸѡ"); + screenbtn.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent actionevent) { + String text = jt2.getText(); + Enumeration e = targetM.elements(); + Vector v = new Vector<>(); + while(e.hasMoreElements()) { + v.add(e.nextElement()); + } + projectM.removeAllElements(); + for(String t : projs) { + if(t.contains(text) && !v.contains(t)) + projectM.addElement(t); + } + } + }); + + jp1.add("left.bind.center.center", new JLabel("Ŀɸѡ")); + jp1.add("unbound.bind.center.center", jt2); + jp1.add("right.bind.center.center", screenbtn); + + JPanel butPanel = new JPanel(new ButtonLayout()); + JButton okbtn = new JButton("ʼ"); + JButton canceltn = new JButton("ȡ"); + butPanel.add(okbtn); + butPanel.add(canceltn); + canceltn.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent actionevent) { + dispose(); + } + }); + + JPanel jpx = new JPanel(new VerticalLayout()); + jpx.add("top.bind.center.top", jp1); + jpx.add("top.bind.center.top", splitPane);//jptop + jpx.add("top.bind.center.top", butPanel); + okbtn.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent actionevent) { + try { + Enumeration e = targetM.elements(); + Vector v = new Vector<>(); + while(e.hasMoreElements()) { + v.add(e.nextElement()); + } +// for(String s : list) { +// if(!v.contains(s)) { +// TCComponentProject ps = listPro(s).get(0); +// tccomponentprojecttype.removeFromProject(ps, new TCComponent[] { targets }); +// } +// } + TCComponentProject ps = listPro(v.get(0)).get(0); + for(InterfaceAIFComponent c : targets) { + TCComponent[] projects = ((TCComponent)c).getReferenceListProperty("project_list"); + for(TCComponent p : projects) { + if(!v.contains(p.getProperty(""))) { + tccomponentprojecttype.removeFromProject((TCComponentProject) p, new TCComponent[] { (TCComponent) c }); + } + } + tccomponentprojecttype.assignToProject(ps, (TCComponent) c); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + }); + + add(jpx); +// setResizable(false); + pack(); + centerToScreen(); + setVisible(true); + } + + /** + * listPro:ȡϵͳеĿ + */ + private Vector listPro(String str_value) { + Vector result = new Vector(); + try { + String str_key = "project_id"; + TCTextService textService = session.getTextService(); + TCComponentQueryType querytype = (TCComponentQueryType) session.getTypeComponent("ImanQuery"); + TCComponentQuery query = (TCComponentQuery) querytype.find("Ŀ..."); + if (null == query) { + MessageBox.post(AIFUtility.getActiveDesktop(), "ȴѯ Ŀ... ", "", MessageBox.ERROR); + return null; + } + + querytype.clearCache(); + String as[] = { textService.getTextValue(str_key), textService.getTextValue("is_active")}; + // String as[] = { "project_name" }; + System.out.println("getTextValue===========" + textService.getTextValue(str_key)); + String as1[] = new String[2]; + as1[0] = str_value; + as1[1] = "true"; + query.clearCache(); + TCComponentContextList list = query.getExecuteResultsList(as, as1); // as + // =ѯkey + // ; + // as1 + // =ѯvalue + TCComponentProject tcpro = null; + + if (list != null) { + int count = list.getListCount(); + System.out.println(" pro coutn " + count); + for (int i = 0; i < count; i++) { + tcpro = (TCComponentProject) list.get(i).getComponent(); + result.add(tcpro); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return result; + } + +} diff --git a/src/com/connor/lidy/dialog/AssignProjectHandler.java b/src/com/connor/lidy/dialog/AssignProjectHandler.java new file mode 100644 index 0000000..0647e58 --- /dev/null +++ b/src/com/connor/lidy/dialog/AssignProjectHandler.java @@ -0,0 +1,37 @@ +package com.connor.lidy.dialog; + +import javax.swing.SwingUtilities; + +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.commands.ExecutionException; + +import com.teamcenter.rac.aif.AbstractAIFUIApplication; +import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +public class AssignProjectHandler extends AbstractHandler +{ + + public Object execute(ExecutionEvent arg0) throws ExecutionException + { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + try { + TCSession session = (TCSession) app.getSession(); + final InterfaceAIFComponent[] pasteTargets = app.getTargetComponents(); + SwingUtilities.invokeLater(new Runnable() { + public void run() { + new AssignProjectDialog(session, pasteTargets); + } + }); + } + catch (Exception exception) + { + MessageBox.post(exception, true); + } + + return null; + } +} diff --git a/src/com/connor/lidy/dialog/FindDesignBean.java b/src/com/connor/lidy/dialog/FindDesignBean.java new file mode 100644 index 0000000..91c41bb --- /dev/null +++ b/src/com/connor/lidy/dialog/FindDesignBean.java @@ -0,0 +1,22 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package com.connor.lidy.dialog; + +/** + * + * @author vearn + */ +public class FindDesignBean { + + private Object[] values; + + public Object[] getValues() { + return values; + } + public void setValues(Object[] values) { + this.values = values; + } + +} \ No newline at end of file diff --git a/src/com/connor/lidy/dialog/FindDesignDialog.java b/src/com/connor/lidy/dialog/FindDesignDialog.java new file mode 100644 index 0000000..b0714a8 --- /dev/null +++ b/src/com/connor/lidy/dialog/FindDesignDialog.java @@ -0,0 +1,346 @@ +package com.connor.lidy.dialog; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; + +import javax.swing.JButton; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.ListSelectionModel; + +import org.apache.poi.xssf.usermodel.XSSFCell; +import org.apache.poi.xssf.usermodel.XSSFRow; +import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.jdesktop.swingx.decorator.HighlighterFactory; +import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode; + +import com.connor.lidy.util.ProgressReporterDialog; +import com.connor.lidy.util.TCUtil; +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.TCComponent; +import com.teamcenter.rac.kernel.TCComponentBOMLine; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentItem; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCComponentTcFile; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +public class FindDesignDialog extends AbstractAIFDialog { + private static final long serialVersionUID = 1L; + private TCSession session; + private JButton exportBtn; + private JButton closeBtn; + private FindDesignTable impTable; + private FindDesignModel impModel; + + public FindDesignDialog(TCSession session, InterfaceAIFComponent[] targets, String[] options, ProgressReporterDialog reporter) throws Exception { + super(AIFUtility.getActiveDesktop()); + this.session = session; + setTitle("鿴ĵ"); + + exportBtn = new JButton(""); + closeBtn = new JButton("ر"); + JPanel btnPanel = new JPanel(new FlowLayout()); + btnPanel.add(exportBtn); + btnPanel.add(closeBtn); + + ArrayList list = new ArrayList<>(); + String[] tableHeader = new String[options.length-1];// { "ϰ汾", "ĵ汾" }; + for(int i=1; i isNotEditableRow = new ArrayList(); + isNotEditableRow.add(0); + isNotEditableRow.add(1); + + this.impModel = new FindDesignModel(node, titleNames); + this.impModel.setIsNotEditableRow(isNotEditableRow); + //map.setColumnIdentifiers(titleNames); + + FindDesignTable partsTable = new FindDesignTable(impModel); + partsTable.setIsNotEditableRow(isNotEditableRow); + partsTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); + // partsTable.setRowHeight(1, 50); + // partsTable.setRowHeight(2, 100); + partsTable.setRowHeight(30); + partsTable.expandAll(); // չȫڵ + // +// partsTable.HiddenCell(0); + + partsTable.getColumnModel().getColumn(0).setPreferredWidth(188); // õһп + partsTable.getColumnModel().getColumn(1).setPreferredWidth(150); // õڶп + + partsTable.setHighlighters(HighlighterFactory.createSimpleStriping()); + + if (simpleLen * titleNames.length >= totleLen) { + for (int i = 0; i < titleNames.length; i++) { + partsTable.getColumnModel().getColumn(i).setPreferredWidth(simpleLen); + } + partsTable.setAutoResizeMode(0); + } else { + partsTable.setAutoResizeMode(1); + } + + return partsTable; + } + + private void getNode(InterfaceAIFComponent[] targets, DefaultMutableTreeTableNode pnode, ArrayList list) { + try { + for(InterfaceAIFComponent c : targets) { + FindDesignBean bean = new FindDesignBean(); + + TCComponentItemRevision rev = (TCComponentItemRevision) c; + TCComponentItem item = rev.getItem(); + TCComponentItemRevision drev = null; + TCComponentItem ditem = null; + AIFComponentContext[] ds = TCUtil.getPseudoFolder(rev, "TC_Is_Represented_By").getChildren(); + System.out.println("rev:"+rev+"=="+ds.length); + + if(ds!=null && ds.length>0) { + long time = 0; + for(AIFComponentContext d : ds) { + TCComponentItemRevision dr = (TCComponentItemRevision) d.getComponent(); + TCComponent[] status = dr.getReferenceListProperty("release_status_list"); + if(status==null || status.length==0) + continue; + System.out.println("status:"+status[0]); + if(!status[0].getProperty("name").equals("TCM ѷ"))//TCM_Released + continue; + long t = dr.getDateProperty("creation_date").getTime(); + if(t < time) + continue; +// value = dr.toString(); + drev = dr; + ditem = drev.getItem(); + time = t; + } + } + Object[] v = new Object[list.size()]; + for(int i=0; i list) { + try { + FindDesignBean bean = new FindDesignBean(); + + TCComponentItemRevision rev = line.getItemRevision(); + TCComponentItem item = line.getItem(); + TCComponentItemRevision drev = null; + TCComponentItem ditem = null; + AIFComponentContext[] ds = TCUtil.getPseudoFolder(rev, "TC_Is_Represented_By").getChildren(); + System.out.println("line:"+line+"=="+ds.length); + + if(ds!=null && ds.length>0) { + long time = 0; + for(AIFComponentContext d : ds) { + TCComponentItemRevision dr = (TCComponentItemRevision) d.getComponent(); + TCComponent[] status = dr.getReferenceListProperty("release_status_list"); + if(status==null || status.length==0) + continue; + System.out.println("status:"+status[0]); + if(!status[0].getProperty("name").equals("TCM ѷ"))//TCM_Released + continue; + long t = dr.getDateProperty("creation_date").getTime(); + if(t < time) + continue; +// value = dr.toString(); + drev = dr; + ditem = drev.getItem(); + time = t; + } + } + Object[] v = new Object[list.size()]; + for(int i=0; i1) +// cell.setCellStyle(getCell(sourceRow, col).getCellStyle()); + return cell; + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/dialog/FindDesignHandler.java b/src/com/connor/lidy/dialog/FindDesignHandler.java new file mode 100644 index 0000000..889fb8e --- /dev/null +++ b/src/com/connor/lidy/dialog/FindDesignHandler.java @@ -0,0 +1,72 @@ +package com.connor.lidy.dialog; + +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.connor.lidy.util.ProgressReporterDialog; +import com.teamcenter.rac.aif.AIFDesktop; +import com.teamcenter.rac.aif.AbstractAIFUIApplication; +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 FindDesignHandler extends AbstractHandler implements IHandler{ + + public Object execute(ExecutionEvent arg0) throws ExecutionException { + System.out.println("FindDesignHandler"); + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + try { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + InterfaceAIFComponent[] targets = app.getTargetComponents(); + if(targets==null || targets.length==0) { + MessageBox.post(desktop, "δѡв鿴ѡ", "ERROR", MessageBox.ERROR); + return null; + } + if(targets[0] instanceof TCComponentBOMLine) { + if(((TCComponentBOMLine)targets[0]).parent() != null) { + MessageBox.post(desktop, "ѡBOMв鿴", "ERROR", MessageBox.ERROR); + return null; + } + }else { + for(InterfaceAIFComponent c : targets) { + if(!(c instanceof TCComponentItemRevision)) { + MessageBox.post(desktop, "ѡ汾в鿴", "ERROR", MessageBox.ERROR); + return null; + } + } + } + TCSession session = (TCSession) app.getSession(); + String[] options = session.getPreferenceService().getStringValues("ML_LatestDesign"); + if(options==null || options.length<2) { + MessageBox.post(desktop, "ѡML_LatestDesignòȷ", "ERROR", MessageBox.ERROR); + return null; + } + ProgressReporterDialog reporter = new ProgressReporterDialog("ʾ"); + reporter.reportProgressMessage("ڵԺ..."); + new Thread(reporter).start(); + new Thread() { + public void run(){ + try { + new FindDesignDialog(session, targets, options, reporter); + }catch(Exception e) { + e.printStackTrace(); + reporter.requestCanceling(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + return; + } + } + }.start(); + }catch(Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + return null; + } + return null; + } +} diff --git a/src/com/connor/lidy/dialog/FindDesignModel.java b/src/com/connor/lidy/dialog/FindDesignModel.java new file mode 100644 index 0000000..aaf4302 --- /dev/null +++ b/src/com/connor/lidy/dialog/FindDesignModel.java @@ -0,0 +1,125 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package com.connor.lidy.dialog; + +import java.util.List; + +import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode; +import org.jdesktop.swingx.treetable.DefaultTreeTableModel; +import org.jdesktop.swingx.treetable.TreeTableNode; + +/** + * + * @author vearn + */ +public class FindDesignModel extends DefaultTreeTableModel { + + private String[] _names; + + + private List isNotEditableRow; + + + + public FindDesignModel(TreeTableNode node) { + super(node); + _names = new String[] { "DBOM", "EBOM","ѡ", "EBOMID", "","","״̬","Ӧڵ"}; + } + + public FindDesignModel(TreeTableNode node, String[] _names) { + super(node); + this._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 FindDesignBean) { + FindDesignBean bean = (FindDesignBean) o; + if(bean.getValues() != null) + value = bean.getValues()[column]; + /*switch (column) { + case 0: + value = bean.getDbom(); + break; + case 1: + value = bean.getEbom(); + break; + case 2: + value = bean.getLabel(); + 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/lidy/dialog/FindDesignTable.java b/src/com/connor/lidy/dialog/FindDesignTable.java new file mode 100644 index 0000000..1d724ce --- /dev/null +++ b/src/com/connor/lidy/dialog/FindDesignTable.java @@ -0,0 +1,80 @@ +package com.connor.lidy.dialog; + +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; + +public class FindDesignTable extends JXTreeTable { + + + /** + * + */ + private static final long serialVersionUID = 1L; + private List isNotEditableRow; + //CheckBoxCellEditor checkBoxCellEditor = new CheckBoxCellEditor(this); +// TableCellCheckboxRenderer checkboxRenderer = new TableCellCheckboxRenderer(this); + + public List getIsNotEditableRow() { + return isNotEditableRow; + } + + public void setIsNotEditableRow(List isNotEditableRow) { + this.isNotEditableRow = isNotEditableRow; + } + + public FindDesignTable(FindDesignModel 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) { + 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/lidy/dialog/StandardDialog.java b/src/com/connor/lidy/dialog/StandardDialog.java new file mode 100644 index 0000000..404f717 --- /dev/null +++ b/src/com/connor/lidy/dialog/StandardDialog.java @@ -0,0 +1,354 @@ +package com.connor.lidy.dialog; + +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.MouseAdapter; +import java.awt.event.MouseEvent; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; + +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.JTextArea; +import javax.swing.table.DefaultTableModel; +import javax.swing.table.TableColumnModel; + +import org.apache.poi.xssf.usermodel.XSSFCell; +import org.apache.poi.xssf.usermodel.XSSFRow; +import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.dom4j.Document; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; + +import com.connor.lidy.util.TCUtil; +//import com.connor.ml.tcm.outfile.util.MethodUtil; +import com.teamcenter.rac.aif.kernel.AIFComponentContext; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentItem; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCComponentTask; +import com.teamcenter.rac.kernel.TCComponentTcFile; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +public class StandardDialog extends JFrame { + private static final long serialVersionUID = 1L; + + private TCSession session; + private JTextArea remark; + private JButton remarkBtn; + private JButton exportBtn; + private JButton closeBtn; + private JTable impTable; + private DefaultTableModel impModel; + private ArrayList 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) 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++) + impTable.getColumnModel().getColumn(i).setPreferredWidth(150); + + setDatas(task, (TCComponentDataset) models[0], ruleOpsMap); + addActionListener(models); + + 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("object_type").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(!val.equals(text) || text.equals("null") && !val.isEmpty()) + 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) { + 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(); + 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); + } + } + }); + //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(""); + 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, 0); + TableColumnModel cm = impTable.getColumnModel(); + for(int i=0; i1) +// cell.setCellStyle(getCell(sourceRow, col).getCellStyle()); + return cell; + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/dialog/StandardHandler.java b/src/com/connor/lidy/dialog/StandardHandler.java new file mode 100644 index 0000000..aadc76a --- /dev/null +++ b/src/com/connor/lidy/dialog/StandardHandler.java @@ -0,0 +1,73 @@ +package com.connor.lidy.dialog; + +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("StadioExamineHandler"); + 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.RULE, TCComponentTaskTemplate.COMPLETE_ACTION, "Connor_check_process_member");//j6_Standard + 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; + } + for(String s : options) { + 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[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); + }catch(Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + return null; + } + return null; + } +} diff --git a/src/com/connor/lidy/report/CompetitiveReportDialog.java b/src/com/connor/lidy/report/CompetitiveReportDialog.java new file mode 100644 index 0000000..283809e --- /dev/null +++ b/src/com/connor/lidy/report/CompetitiveReportDialog.java @@ -0,0 +1,339 @@ +package com.connor.lidy.report; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Vector; + +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; + +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.lidy.util.TCUtil; +import com.teamcenter.rac.aif.AIFDesktop; +import com.teamcenter.rac.aif.AbstractAIFDialog; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.ListOfValuesInfo; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentItem; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCComponentListOfValues; +import com.teamcenter.rac.kernel.TCComponentListOfValuesType; +import com.teamcenter.rac.kernel.TCComponentTcFile; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.stylesheet.PropertyDateComponent; +import com.teamcenter.rac.util.MessageBox; +import com.teamcenter.rac.util.PropertyLayout; +import com.teamcenter.services.rac.core.LOVService; +import com.teamcenter.services.rac.core._2013_05.LOV.InitialLovData; +import com.teamcenter.services.rac.core._2013_05.LOV.LOVSearchResults; +import com.teamcenter.services.rac.core._2013_05.LOV.LOVValueRow; +import com.teamcenter.services.rac.core._2013_05.LOV.LovFilterData; + +public class CompetitiveReportDialog extends AbstractAIFDialog { + private static final long serialVersionUID = 1L; + private TCSession session; + private TCComponentDataset model; + private JButton exportBtn; + private JButton cancelBtn; + private HashMap searchMap; + private HashMap exportMap; + private HashMap objectMap; + + public CompetitiveReportDialog(TCSession session, String title, String[] options, TCComponentDataset model) throws Exception { + super(AIFUtility.getActiveDesktop()); + this.session = session; + this.model = model; + this.searchMap = new HashMap<>(); + this.exportMap = new HashMap<>(); + this.objectMap = new HashMap<>(); + LinkedHashMap searchMap = new LinkedHashMap<>(); + for(String s : options) { + if(s.contains(":")) { + String[] ss = s.split(":"); + searchMap.put(ss[0], ss); + }else if(s.contains("=")) { + String[] ss = s.split("="); + exportMap.put(ss[0], ss); + } + } + setTitle(title); + JPanel propPanel = new JPanel(new PropertyLayout(70, 5, 10, 5, 5, 5)); + int row = 1; + TCComponentListOfValuesType lovType = (TCComponentListOfValuesType)session.getTypeComponent("ListOfValues"); +// TCComponentListOfValues[] lov = lovType.find("ML8_ProjectCategory_LOV"); +// String[] vals = getDynamicLOV(lov[0]); +// System.out.println("ML8_ProjectCategory_LOV:"+lov[0].getType()+"=="+vals.length); + for(String s : searchMap.keySet()) { + JLabel label = new JLabel(s); + propPanel.add(row+".1.left.center", label); + String[] ss = searchMap.get(s); + switch(ss[1]){ + case "0": + JTextField text = new JTextField(); + text.setPreferredSize(new Dimension(150, 23)); + propPanel.add(row+".2.right.center", text); + this.searchMap.put(s, text); + break; + case "1": + JComboBox combo = new JComboBox<>(); + combo.setPreferredSize(new Dimension(150, 23)); + combo.addItem(""); + if(ss[2].contains(";")) { + String[] items = ss[2].split(";"); + for(String item : items) { + combo.addItem(item); + } + }else { + TCComponentListOfValues[] lovs = lovType.find(ss[2]);//TODO lov + if(lovs==null || lovs.length==0) + throw new Exception("δҵLOV"+ss[2]); + if(lovs[0].isTypeOf("Fnd0ListOfValuesDynamic")) { + for(String item : getDynamicLOV(lovs[0])) { + combo.addItem(item); + } + }else { + ListOfValuesInfo vs = lovs[0].getListOfValues(); + String[] dVals = vs.getLOVDisplayValues(); + String[] sVals = vs.getStringListOfValues(); + HashMap map = new HashMap<>(); + for(int i=0; i5) + setSize(new Dimension(380, 220+(row-5)*25)); + else + setSize(new Dimension(380, 220)); + 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 title, String options) { + exportBtn.addActionListener(new ActionListener() { + @SuppressWarnings({ "unchecked", "deprecation" }) + @Override + public void actionPerformed(ActionEvent arg0) { + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + FileInputStream input = null; + FileOutputStream output = null; + try { + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); + File directory = TCUtil.saveExcelChooser(title+sdf.format(new Date())); + if(directory==null) + return; + if(directory.exists()) + directory.delete(); + + new Vector<>(); + Vector keyV = new Vector<>(); + Vector valueV = new Vector<>(); +// sdf = new SimpleDateFormat("yyyy-M-d HH:mm"); + sdf = new SimpleDateFormat("d-MMM-yyyy hh:mm"); + for(String s : searchMap.keySet()) { + JComponent c = searchMap.get(s); + if(c instanceof JTextField) { + String text = ((JTextField)c).getText(); + if(!text.isEmpty()) { + keyV.add(s); + valueV.add(text); + } + }else if(c instanceof JComboBox) { + String text = ((JComboBox)c).getSelectedItem().toString(); + if(!text.isEmpty()) { + keyV.add(s); + if(objectMap.containsKey(s)) { + valueV.add(((HashMap)objectMap.get(s)).get(text)); + }else { + valueV.add(text); + } + } + }else if(c instanceof PropertyDateComponent) { + Date date = ((PropertyDateComponent)c).getDate(); + if(date==null) + continue; + if(objectMap.containsKey(s)) { + date.setHours(23); + date.setMinutes(59); + } + if(date != null) { + keyV.add(s); + valueV.add(sdf.format(date)); + } + } + } + if(keyV.size()==0) { + throw new Exception("дѯ"); + } + TCComponent[] results = TCUtil.query(session, options, keyV, valueV); + 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; + for(int i=0; i lovDisplayValueList = new Vector<>(); +// lovDisplayValueList.add(""); + Vector lovValueList = new Vector<>(); + LOVService lovService = LOVService.getService(session); + InitialLovData input = new InitialLovData(); + LovFilterData filter = new LovFilterData(); + filter.sortPropertyName = "object_name"; + filter.order = 1; + filter.numberToReturn = 100; + filter.maxResults = 100; + + input.lov = lov; + input.filterData = filter; + LOVSearchResults result = lovService.getInitialLOVValues(input); +// StringBuffer sb = new StringBuffer(); +// sb.append(">>"); + for (LOVValueRow row : result.lovValues) { + Map map = row.propDisplayValues; + Map realmap = row.propInternalValues; + for (String key : map.keySet()) { +// sb.append("UID:" + row.uid + ",key:" + key + "value:" + map.get(key)[0]); +// sb.append("\n"); + lovDisplayValueList.add(map.get(key)[0]); + lovValueList.add(realmap.get(key)[0]); + } + } +// System.out.println("StringBuffer:"+sb.toString()); + return lovDisplayValueList.toArray(new String[lovDisplayValueList.size()]); + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/report/CompetitiveReportHandler.java b/src/com/connor/lidy/report/CompetitiveReportHandler.java new file mode 100644 index 0000000..5e8bb73 --- /dev/null +++ b/src/com/connor/lidy/report/CompetitiveReportHandler.java @@ -0,0 +1,50 @@ +package com.connor.lidy.report; + +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.AbstractAIFUIApplication; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +//ļнṹ +public class CompetitiveReportHandler extends AbstractHandler implements IHandler{ + + public Object execute(ExecutionEvent arg0) throws ExecutionException { + System.out.println("CompetitiveReportHandler"); + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + try { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + String pref, title; + if(arg0.getCommand().getId().equals("CompetitiveReportHandler")) { + pref = "ML8_CompetitiveReport"; + title = "Ʒ"; + }else{ + pref = "ML8_PatentApplyReport"; + title = "רάϸ"; + } + TCSession session = (TCSession) app.getSession(); + String options[] = session.getPreferenceService().getStringValues(pref); + if(options==null || options.length<2) { + MessageBox.post(desktop, "ѡ"+pref+"òȷ", "ERROR", MessageBox.ERROR); + return null; + } + TCComponent model = session.stringToComponent(options[0]);//wONAAIWd5kSPsC + if(model==null || !model.isTypeOf("MSExcelX")) { + MessageBox.post(desktop, "ѡ"+pref+"ģUIDòȷ", "ERROR", MessageBox.ERROR); + return null; + } + new CompetitiveReportDialog(session, title, options, (TCComponentDataset)model); + }catch(Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + } + return null; + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/report/ParentListReportHandler.java b/src/com/connor/lidy/report/ParentListReportHandler.java new file mode 100644 index 0000000..0b8a4af --- /dev/null +++ b/src/com/connor/lidy/report/ParentListReportHandler.java @@ -0,0 +1,56 @@ +package com.connor.lidy.report; + +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.AbstractAIFUIApplication; +import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +//ļнṹ +public class ParentListReportHandler extends AbstractHandler implements IHandler{ + + public Object execute(ExecutionEvent arg0) throws ExecutionException { + System.out.println("ParentListReportHandler"); + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + try { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + TCSession session = (TCSession) app.getSession(); + InterfaceAIFComponent target = app.getTargetComponent(); + if(target==null) { + MessageBox.post(desktop, "ѡԭϰ汾е", "ERROR", MessageBox.ERROR); + return null; + } + String type = target.getType(); + if(!type.equals("ML8_PartRevision") && !type.equals("ML8_RawMaterialRevision")) { + MessageBox.post(desktop, "ѡԭϰ汾е", "ERROR", MessageBox.ERROR); + return null; + } + String option = session.getPreferenceService().getStringValue("ML8_ParentListReport"); + if(option==null || option.isEmpty()) { + MessageBox.post(desktop, "ѡML8_ParentListReportòȷ", "ERROR", MessageBox.ERROR); + return null; + } + TCComponent model = session.stringToComponent(option);//AODAAInI5kSPsC + if(model==null || !model.isTypeOf("MSExcelX")) { + MessageBox.post(desktop, "ѡML8_ParentListReportģUIDòȷ", "ERROR", MessageBox.ERROR); + return null; + } + ParentListReportOperation operation = new ParentListReportOperation(session, (TCComponentItemRevision)target, (TCComponentDataset)model); + session.queueOperation(operation); +// MessageBox.post(desktop, "ݽ", "ʾ", MessageBox.INFORMATION); + }catch(Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + } + return null; + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/report/ParentListReportOperation.java b/src/com/connor/lidy/report/ParentListReportOperation.java new file mode 100644 index 0000000..607a34b --- /dev/null +++ b/src/com/connor/lidy/report/ParentListReportOperation.java @@ -0,0 +1,172 @@ +package com.connor.lidy.report; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Date; +import java.util.List; + +import javax.swing.JOptionPane; + +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.lidy.util.TCUtil; +import com.teamcenter.rac.aif.AIFDesktop; +import com.teamcenter.rac.aif.AbstractAIFOperation; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentItem; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCComponentTcFile; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +public class ParentListReportOperation extends AbstractAIFOperation { + +// private TCSession session; + private TCComponentItemRevision target; + private TCComponentDataset model; + private XSSFRow sourceRow; + private final static String [] REV_TYPES = { "ML8_UnProductRevision", "ML8_RefrigeratorRevision", "ML8_WashingRevision", "ML8_ColdRevision", + "ML8_OthersRevision", "ML8_PartRevision", "ML8_RawMaterialRevision" }; + public ParentListReportOperation(TCSession session, TCComponentItemRevision target, TCComponentDataset model) { +// this.session = session; + this.target = target; + this.model = model; + } + + @Override + public void executeOperation() throws Exception { + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + FileInputStream input = null; + FileOutputStream output = null; + try { + TCComponentItemRevision newRev = target.getItem().getLatestItemRevision(); +// getParents(target); + Date now = new Date(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); + File directory = TCUtil.saveExcelChooser(newRev.getProperty("item_id")+"ϸʹ嵥"+sdf.format(now)); + if(directory==null) + return; + if(directory.exists()) + directory.delete(); + String path = directory.getPath(); + + TCComponentTcFile[] files = model.getTcFiles(); + File file = files[0].getFile(System.getProperty("java.io.tmpdir")); + input = new FileInputStream(file); + XSSFWorkbook wb = new XSSFWorkbook(input); + + int i = 1; + XSSFSheet sheet = wb.getSheetAt(0); + XSSFRow row; + XSSFCell cell; + sourceRow = getRow(sheet, i); + System.out.println("ǰϣ"+newRev); + TCComponent[] ps = newRev.whereUsed(TCComponent.WHERE_USED_ALL); + if(ps!=null) + System.out.println("ҵʹõ:"+ps.length); + else + System.out.println("δҵʹ"); + for(TCComponent c : ps) { + TCComponentItem item = ((TCComponentItemRevision)c).getItem(); + System.out.println("ҵ"+item); + if(!c.equals(item.getLatestItemRevision())) { + System.out.println("°汾"); + continue; + } + String type = c.getType(); + System.out.println("ǰͣ"+type); + List asList = Arrays.asList(REV_TYPES); + if(!asList.contains(type)) { + System.out.println(""); + continue; + } + String id = c.getProperty("item_id"); + if(id.indexOf("-")>-1) + continue; +// if(!id.startsWith("89") && !id.startsWith("ML")&& !id.startsWith("80")) +// continue; + row = getRow(sheet, i); + cell = getCell(row, 0); + cell.setCellValue(i);// + cell = getCell(row, 1); + cell.setCellValue(id);//ϴ + cell = getCell(row, 2); + cell.setCellValue(c.getProperty("object_desc"));// + cell = getCell(row, 3); + cell.setCellValue(c.getProperty("ml8_StdDesc"));//׼ + cell = getCell(row, 4); + cell.setCellValue(c.getProperty("ml8_FigureNum"));//ͼ + cell = getCell(row, 5); + cell.setCellValue(c.getProperty("ml8_Colour"));//ɫ + cell = getCell(row, 6); + cell.setCellValue(c.getProperty("ml8_Materials"));// + cell = getCell(row, 7); + cell.setCellValue(c.getProperty("ml8_Specifications"));// + cell = getCell(row, 8); + cell.setCellValue(item.getProperty("ml8_Status"));//ѡʽ + cell = getCell(row, 9); + TCComponent[] released = c.getReferenceListProperty("release_status_list"); + if(released!=null && released.length>0) { +// System.out.println("released:"+released[0].getProperty("object_name")); + String status = released[0].getProperty("object_name"); + if(status.equals("ML8_Freeze") || status.equals("ML8_Abolish")) + cell.setCellValue("");//Ƿȡ + else + cell.setCellValue("");//Ƿȡ + }else + cell.setCellValue("");//Ƿȡ + + i++; + } + + output = new FileOutputStream(file.getPath()); + wb.write(output); + input.close(); + output.close(); +// System.out.println("file:"+file.getPath()); + String newPath = System.getProperty("java.io.tmpdir")+path.substring(path.lastIndexOf("\\")); + File reFile = new File(newPath); + file.renameTo(reFile); +// System.out.println("new directory:"+reFile.getPath()); + reFile.renameTo(directory); + +// MessageBox.post(desktop, "", "INFO", MessageBox.INFORMATION); + int choose = JOptionPane.showOptionDialog(desktop, "ѵ"+directory.getPath()+"Ƿ?", "ʾ", + JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new String[] {"",""}, ""); + if(choose==0) { + Runtime runtime = Runtime.getRuntime(); + runtime.exec("cmd /c start exit &&\"" + directory + "\" "); + } + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + }finally { + if(input!=null) + input.close(); + if(output!=null) + output.close(); + } + } + 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()>2) + cell.setCellStyle(getCell(sourceRow, col).getCellStyle()); + return cell; + } +} diff --git a/src/com/connor/lidy/report/ProductListReportHandler.java b/src/com/connor/lidy/report/ProductListReportHandler.java new file mode 100644 index 0000000..acff2b4 --- /dev/null +++ b/src/com/connor/lidy/report/ProductListReportHandler.java @@ -0,0 +1,86 @@ +package com.connor.lidy.report; + +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.connor.lidy.util.TCUtil; +import com.teamcenter.rac.aif.AIFDesktop; +import com.teamcenter.rac.aif.AbstractAIFUIApplication; +import com.teamcenter.rac.aif.kernel.AIFComponentContext; +import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentBOMLine; +import com.teamcenter.rac.kernel.TCComponentBOMWindow; +import com.teamcenter.rac.kernel.TCComponentDataset; +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 ProductListReportHandler extends AbstractHandler implements IHandler{ + + public Object execute(ExecutionEvent arg0) throws ExecutionException { + System.out.println("ProductListReportHandler"); + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + try { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + TCSession session = (TCSession) app.getSession(); + InterfaceAIFComponent target = app.getTargetComponent(); + if(target==null) { + MessageBox.post(desktop, "ѡ汾BOMе", "ERROR", MessageBox.ERROR); + return null; + } + TCComponentItemRevision topRev; + TCComponentBOMLine topLine; + if(target instanceof TCComponentBOMLine) { + topLine = (TCComponentBOMLine) target; + topRev = topLine.getItemRevision(); + }else if(target instanceof TCComponentItemRevision) { + topRev = (TCComponentItemRevision) target; + TCComponentBOMWindow window = TCUtil.getWindow(session); + topLine = TCUtil.getBOMLine(session, window, topRev); + }else { + MessageBox.post(desktop, "ѡ汾BOMне", "ERROR", MessageBox.ERROR); + return null; + } + //+++ +// for(AIFComponentContext c : topLine.getChildren()) { +// TCComponentBOMLine child = (TCComponentBOMLine) c.getComponent(); +// TCComponentItem item = child.getItem(); +// TCComponentItemRevision[] revs = item.getReleasedItemRevisions(); +// if(revs.length==0) { +// MessageBox.post(desktop, item+"δñ׼ܵ", "ERROR", MessageBox.ERROR); +// return null; +// } +// } +// String releaseStatuses=((TCComponentBOMLine) target).getStringProperty("bl_rev_release_statuses"); + +// if(releaseStatuses.indexOf("ML8_JGFB")<0&&releaseStatuses.indexOf("ṹ")<0) { +// MessageBox.post(desktop, "BOMδȫʹϵͳ׼ܵ", "ERROR", MessageBox.ERROR); +// return null; +// } + //+++ + String option = session.getPreferenceService().getStringValue("ML8_ProductListReport"); + if(option==null || option.isEmpty()) { + MessageBox.post(desktop, "ѡML8_ProductListReportòȷ", "ERROR", MessageBox.ERROR); + return null; + } + TCComponent model = session.stringToComponent(option);//AKLAAIHx5kSPsC + if(model==null || !model.isTypeOf("MSExcelX")) { + MessageBox.post(desktop, "ѡML8_ProductListReportģUIDòȷ", "ERROR", MessageBox.ERROR); + return null; + } + ProductListReportOperation operation = new ProductListReportOperation(session, topRev, (TCComponentDataset)model); + session.queueOperation(operation); +// MessageBox.post(desktop, "ݽ", "ʾ", MessageBox.INFORMATION); + }catch(Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + } + return null; + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/report/ProductListReportOperation.java b/src/com/connor/lidy/report/ProductListReportOperation.java new file mode 100644 index 0000000..e222831 --- /dev/null +++ b/src/com/connor/lidy/report/ProductListReportOperation.java @@ -0,0 +1,267 @@ +package com.connor.lidy.report; + +import java.io.File; +import com.connor.lidy.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.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentDatasetType; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.kernel.TCUserService; +import com.teamcenter.rac.util.MessageBox; + +@SuppressWarnings("deprecation") +public class ProductListReportOperation extends AbstractAIFOperation { + + private TCSession session; + private TCComponentItemRevision target; + private TCComponentDataset model; +// private XSSFRow sourceRow; +// private int row; +// private BigDecimal zero; +// private HashMap quantityMap; + + public ProductListReportOperation(TCSession session, TCComponentItemRevision target, TCComponentDataset model) { + this.session = session; + this.target = target; + this.model = model; + } + + @Override + public void executeOperation() throws Exception { + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + try { +// zero = new BigDecimal(0); +// quantityMap = new HashMap<>(); +// Date now = new Date(); +// SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); + String item_id = target.getProperty("item_id"); + String object_name = target.getProperty("object_name"); + String item_revision_id = target.getProperty("item_revision_id"); + String ml8_ProductCode = "", ml8_ProductType = ""; +// + AIFComponentContext[] forms = target.getChildren("ML8_ProjectRelation"); +// System.out.println("forms:"+forms.length); + if(forms.length>0) { + ml8_ProductCode = forms[0].getComponent().getProperty("ml8_ProductCode"); + ml8_ProductType = forms[0].getComponent().getProperty("ml8_ProductType"); + }else { + ml8_ProductCode = target.getProperty("ml8_ProductCode"); + ml8_ProductType = target.getProperty("ml8_ProductType"); + } + //2022/9/7޸ģתΪ_ + String pattern = "[/:*?\"<>|]"; + item_id = item_id.replaceAll(pattern, "_").replace("\\", "_").replace("\n", "_").trim(); + object_name = object_name.replaceAll(pattern, "_").replace("\\", "_").replace("\n", "_").trim(); + item_revision_id = item_revision_id.replaceAll(pattern, "_").replace("\\", "_").replace("\n", "_").trim(); + ml8_ProductCode = ml8_ProductCode.replaceAll(pattern, "_").replace("\\", "_").replace("\n", "_").trim(); + ml8_ProductType = ml8_ProductType.replaceAll(pattern, "_").replace("\\", "_").replace("\n", "_").trim(); + StringBuilder name = new StringBuilder(ml8_ProductCode); + name.append("(").append(ml8_ProductType).append(")").append(object_name).append("(").append(item_id).append(")_").append(item_revision_id); +// File directory = TCUtil.saveExcelChooser(object_name+"("+ml8_ProductCode+"("+ml8_ProductType+"))Ʒϸ"); + File directory = TCUtil.saveExcelChooser(name.toString()); + if(directory==null) + return; + if(directory.exists()) + directory.delete(); + System.out.println("directory:"+directory.getPath()+" == "+name.toString().contains("\n")); +// String path = directory.getPath(); + +// TCComponentTcFile[] files = model.getTcFiles(); +// File file00 = files[0].getFile(System.getProperty("java.io.tmpdir")); + +// String[] fileNames = model.getFileNames("excel"); +//// if (fileNames.length == 0) { +//// } else { +// File file = model.getFile("excel", fileNames[0], System.getProperty("java.io.tmpdir")); +//// } + +// input = new FileInputStream(file); +// XSSFWorkbook wb = new XSSFWorkbook(input); +// output = new FileOutputStream(file.getPath()); +// wb.write(output); +// input.close(); +// output.close(); + TCComponentDatasetType dsType = (TCComponentDatasetType) session.getTypeComponent("MSExcelX"); + TCComponentDataset ds = dsType.create("outexcel", "", "MSExcelX"); + + System.out.println("file path ʼC++"+model.getUid()); + + TCUserService userService =(TCUserService) session.getUserService(); + Object[] params = { target, model.getUid(),ds.getUid()}; + userService.call("outputBomExcel", params); + File file=null; + String[] fileNames = ds.getFileNames("excel"); + if (fileNames.length == 0) { + System.out.println("ϴʧ"); + } else { +// file = ds.getFile("excel", fileNames[0], System.getProperty("java.io.tmpdir")); + file = ds.getTcFiles()[0].getFile(System.getProperty("java.io.tmpdir")); + } +// ds.refresh(); + ds.delete(); + System.out.println("file:"+file.getPath()); +// String path1 = System.getProperty("java.io.tmpdir")+"\\"+directory.getName(); + File file2 = new File(directory.getParent()+"\\"+file.getName()); + file.renameTo(file2); + file2.renameTo(directory); +// System.out.println("file2:"+path2+" == "+result); + +// input = new FileInputStream(file); +// XSSFWorkbook wb = new XSSFWorkbook(input); +// +// XSSFSheet sheet = wb.getSheetAt(0); +// sourceRow = getRow(sheet, 1); +// XSSFRow row; +//// XSSFCell cell; +// this.row = 1; +// +// TCComponentBOMWindow window = TCUtil.getWindow(session); +// TCComponentBOMLine line = TCUtil.getBOMLine(session, window, target); +// row = getRow(sheet, this.row); +// getCell(row, 0).setCellValue(0);// +// getCell(row, 1).setCellValue("0");//㼶 +// getCell(row, 2).setCellValue(item_id);//ϱ +// getCell(row, 3).setCellValue(item_revision_id);//汾 +// getCell(row, 4).setCellValue(target.getProperty("ml8_FigureNum"));//ͼ +// getCell(row, 5).setCellValue(object_name);// +// getCell(row, 6).setCellValue("");//ͺ +// getCell(row, 7).setCellValue(1);// +// getCell(row, 8).setCellValue(line.getItem().getProperty("uom_tag"));//λ +// getCell(row, 9).setCellValue(target.getProperty("ml8_Suttle"));// +// getCell(row, 10).setCellValue("");// +// getCell(row, 11).setCellValue(target.getProperty("ml8_Colour"));//ɫ +// getCell(row, 12).setCellValue(target.getProperty("ml8_AfterSale"));//Ƿۺ󱸼 +// getCell(row, 13).setCellValue("");//ѡʽ +// getCell(row, 14).setCellValue("");//ͨû״̬ +// getCell(row, 15).setCellValue(target.getProperty("ml8_ProcessingMode"));//ӹʽ +// getCell(row, 16).setCellValue("");//Ŀ +// getCell(row, 17).setCellValue(target.getProperty("ml8_Remark"));//ע +// getCell(row, 18).setCellValue("");// +// this.row++; +// +//// System.out.println("rule:"+window.getRevisionRule()); +//// TCComponentRevisionRuleType type = (TCComponentRevisionRuleType) session.getTypeComponent("RevisionRule"); +//// System.out.println("type:"+type.create("Any Status; Working", "")); +// TCComponentRevisionRule[] list = TCComponentRevisionRule.listAllRules(session); +// for(TCComponentRevisionRule rule : list) { +// if(rule.toString().equals("Ʒϸ")) { +// window.setRevisionRule(rule); +// break; +// } +// } +// System.out.println("rule:"+window.getRevisionRule()); +// recycelBom(line.getChildren(), sheet, new BigDecimal(1)); + /*for(int i=2; i<=sheet.getLastRowNum(); i++) { + row = getRow(sheet, i); + cell = getCell(row, 2); + String id = cell.getStringCellValue(); +// System.out.println("id:"+id); + if(id.isEmpty()) + continue; + cell = getCell(row, 7); + cell.setCellValue(quantityMap.get(id).doubleValue()); + }*/ +// window.close(); +// +// output = new FileOutputStream(file.getPath()); +// wb.write(output); +// input.close(); +// output.close(); +//// System.out.println("file:"+file.getPath()); +// String newPath = System.getProperty("java.io.tmpdir")+path.substring(path.lastIndexOf("\\")); +// File reFile = new File(newPath); +// System.out.println("reFile:"+reFile.getPath()); +// file.renameTo(reFile); +// System.out.println("file2:"+file.getPath()); +// reFile.renameTo(directory); +// System.out.println("reFile2:"+reFile.getPath()); + + MessageBox.post(desktop, "", "INFO", MessageBox.INFORMATION); + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + } + } + /*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; + } + private void recycelBom(AIFComponentContext[] context, XSSFSheet sheet, BigDecimal parent) throws Exception { + HashSet idSet = new HashSet<>(); + for(AIFComponentContext c : context) { + TCComponentBOMLine line = (TCComponentBOMLine)c.getComponent(); + String id = line.getProperty("bl_item_item_id"); + if(idSet.contains(id)||id.indexOf("-")>-1) + continue; + idSet.add(id); + TCComponentItemRevision rev = line.getItemRevision(); + if(rev==null) + continue; +// System.out.println("bom:"+id); + BigDecimal count = getQuantity(context, id).multiply(parent); + if(quantityMap.containsKey(id)) + quantityMap.put(id, quantityMap.get(id).add(count)); + else + quantityMap.put(id, count); + TCComponentItem item = line.getItem(); + XSSFRow row = getRow(sheet, this.row); + getCell(row, 0).setCellValue(this.row-1);// + getCell(row, 1).setCellValue(line.getProperty("bl_level_starting_0"));//㼶 + getCell(row, 2).setCellValue(id);//ϱ + getCell(row, 3).setCellValue(rev.getProperty("item_revision_id"));//汾 + getCell(row, 4).setCellValue(rev.getProperty("ml8_FigureNum"));//ͼ + getCell(row, 5).setCellValue(rev.getProperty("object_name"));// + getCell(row, 6).setCellValue(rev.getProperty("ml8_Specifications"));//ͺ + getCell(row, 7).setCellValue(count.doubleValue());// + getCell(row, 8).setCellValue(line.getProperty("bl_uom"));//λ + if(item.getType().equals("ML8_Part")) { + getCell(row, 9).setCellValue(rev.getProperty("ml8_Suttle"));// + getCell(row, 14).setCellValue(rev.getProperty("ml8_GeneralIdentify"));//ͨû״̬ + getCell(row, 16).setCellValue(line.getProperty("ML8_ProjectTeam"));//Ŀ + }else { + getCell(row, 9).setCellValue("");// + getCell(row, 14).setCellValue("");//ͨû״̬ + getCell(row, 16).setCellValue("");//Ŀ + } + getCell(row, 10).setCellValue(rev.getProperty("ml8_Materials"));// + getCell(row, 11).setCellValue(rev.getProperty("ml8_Colour"));//ɫ + getCell(row, 12).setCellValue(rev.getProperty("ml8_AfterSale"));//Ƿۺ󱸼 + getCell(row, 13).setCellValue(item.getProperty("ml8_Status"));//ѡʽ +// getCell(row, 14).setCellValue("");//ͨû״̬ + getCell(row, 15).setCellValue(rev.getProperty("ml8_ProcessingMode"));//ӹʽ +// getCell(row, 16).setCellValue("");//Ŀ + getCell(row, 17).setCellValue(rev.getProperty("ml8_Remark"));//ע + getCell(row, 18).setCellValue(line.getProperty("bl_formatted_parent_name"));// + + this.row++; + AIFComponentContext[] child = line.getChildren(); + if(child!=null && child.length>0) + recycelBom(line.getChildren(), sheet, count); + } + } + private BigDecimal getQuantity(AIFComponentContext[] children, String id) throws Exception { + BigDecimal q = zero; + for(AIFComponentContext c : children) { + TCComponentBOMLine bom = (TCComponentBOMLine) c.getComponent(); + if(bom.getProperty("bl_item_item_id").equals(id)) { + String bl_quantity = bom.getProperty("bl_quantity"); + q = q.add(new BigDecimal(bl_quantity.isEmpty() ? "1":bl_quantity)); + } + } + return q; + }*/ +} diff --git a/src/com/connor/lidy/report/ProjectBoardDialog.java b/src/com/connor/lidy/report/ProjectBoardDialog.java new file mode 100644 index 0000000..502d357 --- /dev/null +++ b/src/com/connor/lidy/report/ProjectBoardDialog.java @@ -0,0 +1,293 @@ +package com.connor.lidy.report; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Map; +import java.util.Vector; + +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; + +import com.connor.lidy.util.MultiCombo; +import com.connor.lidy.util.ProgressReporterDialog; +import com.connor.lidy.util.SelectUserDialog; +import com.connor.lidy.util.TCUtil; +import com.teamcenter.rac.aif.AbstractAIFDialog; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentListOfValues; +import com.teamcenter.rac.kernel.TCComponentListOfValuesType; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.stylesheet.PropertyDateComponent; +import com.teamcenter.rac.util.MessageBox; +import com.teamcenter.rac.util.PropertyLayout; +import com.teamcenter.services.rac.core.LOVService; +import com.teamcenter.services.rac.core._2013_05.LOV.InitialLovData; +import com.teamcenter.services.rac.core._2013_05.LOV.LOVSearchResults; +import com.teamcenter.services.rac.core._2013_05.LOV.LOVValueRow; +import com.teamcenter.services.rac.core._2013_05.LOV.LovFilterData; + +public class ProjectBoardDialog extends AbstractAIFDialog { + private static final long serialVersionUID = 1L; + private TCSession session; + private TCComponentDataset model; + private JButton exportBtn; + private JButton cancelBtn; + private JComponent[] comps; + + public ProjectBoardDialog(TCSession session, String[] options, TCComponentDataset model, String[] departments) throws Exception { + super(AIFUtility.getActiveDesktop()); + this.session = session; + this.model = model; + this.comps = new JComponent[8]; + + System.out.println("group:"+session.getGroup()+">>"+session.getGroup().getGroupName()); + String group = session.getGroup().toString().trim(); + String depart = ""; + for(String s : departments) { + String[] ss = s.split(":"); + if(group.equals(ss[0])) { + depart = ss[1]; + } + } + if(depart.isEmpty()) + throw new Exception("ǰ޷ѯϵϵͳԱ"); + + setTitle("Ŀиٱ-Ʒ"); + JPanel propPanel = new JPanel(new PropertyLayout(70, 5, 10, 5, 5, 5)); + TCComponentListOfValuesType lovType = (TCComponentListOfValuesType)session.getTypeComponent("ListOfValues"); +// TCComponentListOfValues[] lov = lovType.find("ML8_ProjectCategory_LOV"); +// String[] vals = getDynamicLOV(lov[0]); +// System.out.println("ML8_ProjectCategory_LOV:"+lov[0].getType()+"=="+vals.length); + JLabel label1 = new JLabel("Ʒ"); + propPanel.add("1.1.left.center", label1); + JTextField text1 = new JTextField(); + text1.setPreferredSize(new Dimension(155, 23)); + propPanel.add("1.2.right.center", text1); + comps[0] = text1; + + JLabel label2 = new JLabel("Ŀ"); + propPanel.add("2.1.left.center", label2); + JComboBox combo2 = new JComboBox<>(); + combo2.setPreferredSize(new Dimension(155, 23)); + combo2.addItem(""); + TCComponentListOfValues[] lovs2 = lovType.find("ML8_ProjectLevel_LOV"); + for(String item : getDynamicLOV(lovs2[0])) { + combo2.addItem(item); + } + propPanel.add("2.2.right.center", combo2); + comps[1] = combo2; + + JLabel label3 = new JLabel("Ŀʱ"); + propPanel.add("3.1.left.center", label3); + PropertyDateComponent date3 = new PropertyDateComponent(); + propPanel.add("3.2.right.center", date3); + comps[2] = date3; + + JLabel label4 = new JLabel("ĿʱС"); + propPanel.add("4.1.left.center", label4); + PropertyDateComponent date4 = new PropertyDateComponent(); + propPanel.add("4.2.right.center", date4); + comps[3] = date4; + + JLabel label5 = new JLabel("Ŀ"); + propPanel.add("5.1.left.center", label5); + JPanel personPanel = new JPanel(new PropertyLayout(5, 5, 0, 5, 5, 5)); + JTextField text5 = new JTextField(); + text5.setPreferredSize(new Dimension(105, 23)); + text5.setEditable(false); + personPanel.add("1.1.center.center", text5); + JButton personBtn = new JButton("..."); + personBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + try { + new SelectUserDialog(text5, false).showDialog(); + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(ProjectBoardDialog.this, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + } + } + }); + personBtn.setPreferredSize(new Dimension(45, 23)); + personPanel.add("1.2.center.center", personBtn); + propPanel.add("5.2.center.center", personPanel); + comps[4] = text5; + + JLabel label6 = new JLabel("Ŀе"); + propPanel.add("6.1.left.center", label6); +// JComboBox combo6 = new JComboBox<>(); +// combo6.setPreferredSize(new Dimension(155, 23)); +// combo6.addItem(""); +//// TCComponentListOfValues[] lovs6 = lovType.find("ML8_PrjDepartment_LOV"); +//// for(String item : getDynamicLOV(lovs6[0])) { +// for(String item : depart.split(";")) { +// combo6.addItem(item); +// } + MultiCombo combo6 = new MultiCombo(depart.split(";")); + combo6.setEditable(true); + propPanel.add("6.2.right.center", combo6); + combo6.setPreferredSize(new Dimension(155, 23)); + comps[5] = combo6; + + JLabel label7 = new JLabel("Ŀ״̬"); + propPanel.add("7.1.left.center", label7); + JComboBox combo7 = new JComboBox<>(); + combo7.setPreferredSize(new Dimension(155, 23)); + combo7.addItem(""); + TCComponentListOfValues[] lovs7 = lovType.find("ML8_MissionPhase_LOV"); + for(String item : getDynamicLOV(lovs7[0])) { + combo7.addItem(item); +// System.out.println("item:"+item); + } + propPanel.add("7.2.right.center", combo7); + comps[6] = combo7; + + JCheckBox showEarly = new JCheckBox("ʾѽ"); + comps[7] = showEarly; + exportBtn = new JButton(""); + cancelBtn = new JButton("ȡ"); + JPanel btnPanel = new JPanel(new FlowLayout()); + btnPanel.add(showEarly); + btnPanel.add(exportBtn); + btnPanel.add(cancelBtn); + setLayout(new BorderLayout()); + add(BorderLayout.CENTER, propPanel); + add(BorderLayout.SOUTH, btnPanel); +// add(new JLabel("")); + addActionListener(depart, options); + + pack(); + setSize(new Dimension(380, 300)); + 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 depart, String[] options) { + exportBtn.addActionListener(new ActionListener() { + @SuppressWarnings("deprecation") + @Override + public void actionPerformed(ActionEvent arg0) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); + File directory = TCUtil.saveExcelChooserAsk("Ŀиٱ-Ʒ"+sdf.format(new Date())); + if(directory==null) + return; + ProgressReporterDialog reporter = new ProgressReporterDialog("ʾ"); + reporter.reportProgressMessage("ڵԺ..."); + new Thread(reporter).start(); + new Thread() { + public void run(){ + try { + SimpleDateFormat sdf = new SimpleDateFormat("d-MMM-yyyy hh:mm"); + Vector keyV = new Vector<>(); + Vector valV = new Vector<>(); + String text1 = ((JTextField) comps[0]).getText(); + if(!text1.isEmpty()) { + keyV.add("Ʒ"); + valV.add(text1); + } + String text2 = ((JComboBox) comps[1]).getSelectedItem().toString(); + if(!text2.isEmpty()) { + keyV.add("Ŀ"); + valV.add(text2); + } +// System.out.println("Ŀʱ:"+((PropertyDateComponent) comps[2]).getDateString()); + Date date3 = ((PropertyDateComponent) comps[2]).getDate(); + if(date3 != null) { + keyV.add("Ŀʱ"); + valV.add(sdf.format(date3)); + } +// System.out.println("ĿʱС:"+((PropertyDateComponent) comps[3]).getDateString()); + Date date4 = ((PropertyDateComponent) comps[3]).getDate(); + if(date4 != null) { + keyV.add("ĿʱС"); + valV.add(sdf.format(date4)); + } + String text5 = ((JTextField) comps[4]).getText(); + if(!text5.isEmpty()) { + keyV.add("Ŀ"); + valV.add(text5); + } +// String text6 = ((JComboBox) comps[5]).getSelectedItem().toString(); + String text6 = ((MultiCombo) comps[5]).getText().trim(); + if(!text6.isEmpty()) { + keyV.add("Ŀе"); + valV.add(text6); + }else { + keyV.add("Ŀе"); + valV.add(depart); + } + String text7 = ((JComboBox) comps[6]).getSelectedItem().toString(); + if(!text7.isEmpty()) { + keyV.add("Ŀ״̬"); + valV.add(text7); + } + boolean oldyear = ((JCheckBox) comps[7]).isSelected(); + + new ProjectBoardOperation(session, options, model, directory, reporter, keyV, valV, oldyear).executeOperation(); + }catch(Exception e1) { + reporter.requestCanceling(); + e1.printStackTrace(); + MessageBox.post(ProjectBoardDialog.this, ""+e1.getMessage(), "ERROR", MessageBox.ERROR); + } + } + }.start(); + } + }); + cancelBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + dispose(); + } + }); + } + + public String[] getDynamicLOV(TCComponentListOfValues lov) throws Exception { + Vector lovDisplayValueList = new Vector<>(); +// lovDisplayValueList.add(""); +// Vector lovValueList = new Vector<>(); + LOVService lovService = LOVService.getService(session); + InitialLovData input = new InitialLovData(); + LovFilterData filter = new LovFilterData(); + filter.sortPropertyName = "object_name"; + filter.order = 1; + filter.numberToReturn = 100; + filter.maxResults = 100; + + input.lov = lov; + input.filterData = filter; + LOVSearchResults result = lovService.getInitialLOVValues(input); +// StringBuffer sb = new StringBuffer(); +// sb.append(">>"); + for (LOVValueRow row : result.lovValues) { + Map map = row.propDisplayValues; +// Map realmap = row.propInternalValues; + for (String key : map.keySet()) { + if(!key.equals("object_name")) + continue; +// sb.append("UID:" + row.uid + ",key:" + key + "value:" + map.get(key)[0]); +// sb.append("\n"); + String[] v = map.get(key); + lovDisplayValueList.add(v[0]); +// lovValueList.add(realmap.get(key)[0]); +// System.out.println("key:"+key+"=="+v.length+">>"+v[0]); + } + } +// System.out.println("StringBuffer:"+sb.toString()); + return lovDisplayValueList.toArray(new String[lovDisplayValueList.size()]); + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/report/ProjectBoardHandler.java b/src/com/connor/lidy/report/ProjectBoardHandler.java new file mode 100644 index 0000000..d93e560 --- /dev/null +++ b/src/com/connor/lidy/report/ProjectBoardHandler.java @@ -0,0 +1,93 @@ +package com.connor.lidy.report; + + +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.connor.lidy.util.ProgressReporterDialog; +//import com.connor.lidy.util.TCUtil; +import com.teamcenter.rac.aif.AIFDesktop; +import com.teamcenter.rac.aif.AbstractAIFUIApplication; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +//ļнṹ +public class ProjectBoardHandler extends AbstractHandler implements IHandler{ + + public Object execute(ExecutionEvent arg0) throws ExecutionException { + System.out.println("ProjectBoardHandler"); + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + try { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + TCSession session = (TCSession) app.getSession(); +// ProjectBoardDialog.getComps(session.stringToComponent("AyJAAIWu5kSPsC")); + String options[] = session.getPreferenceService().getStringValues("ML8_ProjectReport"); + if(options==null || options.length<2) { + MessageBox.post(desktop, "ѡML8_ProjectReportòȷ", "ERROR", MessageBox.ERROR); + return null; + } + TCComponent model = session.stringToComponent(options[0]);//wtGAAIma5kSPsC SearchProjectSchedule + if(model==null || !model.isTypeOf("MSExcelX")) { + MessageBox.post(desktop, "ѡML8_ProjectReportģUIDòȷ", "ERROR", MessageBox.ERROR); + return null; + } + String departments[] = session.getPreferenceService().getStringValues("ML8_ProjectDepart"); + if(departments==null || departments.length==0) { + MessageBox.post(desktop, "ѡML8_ProjectDepartòȷ", "ERROR", MessageBox.ERROR); + return null; + } +// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); +// System.out.println((sdf.parse("2022-01-10").getTime()-sdf.parse("2021-12-11").getTime())/(1000*60*60*24)); + new ProjectBoardDialog(session, options, (TCComponentDataset)model, departments); + }catch(Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + } + /*new Thread() { + public void run(){ + try { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + TCSession session = (TCSession) app.getSession(); +// ProjectBoardDialog.getComps(session.stringToComponent("AyJAAIWu5kSPsC")); + String options[] = session.getPreferenceService().getStringValues("ML8_ProjectReport"); + if(options==null || options.length<2) { + MessageBox.post(desktop, "ѡML8_ProjectReportòȷ", "ERROR", MessageBox.ERROR); + return; + } + TCComponent model = session.stringToComponent(options[0]);//wtGAAIma5kSPsC SearchProjectSchedule + if(model==null || !model.isTypeOf("MSExcelX")) { + MessageBox.post(desktop, "ѡML8_ProjectReportģUIDòȷ", "ERROR", MessageBox.ERROR); + return; + } + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); + File directory = TCUtil.saveExcelChooserAsk("Ŀиٱ-Ʒ"+ sdf.format(new Date())); + if(directory==null) + return; + ProgressReporterDialog reporter = new ProgressReporterDialog("ʾ"); + reporter.reportProgressMessage("ڵԺ..."); + new Thread(reporter).start(); + new Thread() { + public void run(){ + try { + new ProjectBoardOperation(session, options, (TCComponentDataset)model, directory, reporter).executeOperation(); + } catch (Exception e) { + reporter.requestCanceling(); + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + } + } + }.start(); + }catch(Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + } + } + }.start();*/ + return null; + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/report/ProjectBoardOperation.java b/src/com/connor/lidy/report/ProjectBoardOperation.java new file mode 100644 index 0000000..42b595d --- /dev/null +++ b/src/com/connor/lidy/report/ProjectBoardOperation.java @@ -0,0 +1,368 @@ +package com.connor.lidy.report; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Vector; + +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.lidy.util.ProgressReporterDialog; +import com.connor.lidy.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.aif.kernel.InterfaceAIFComponent; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentItem; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCComponentSchedule; +import com.teamcenter.rac.kernel.TCComponentScheduleTask; +import com.teamcenter.rac.kernel.TCComponentTcFile; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.schedule.scheduler.componentutils.ScheduleHelper; +import com.teamcenter.rac.util.MessageBox; + +public class ProjectBoardOperation extends AbstractAIFOperation { + + private TCSession session; + private String options[]; + private TCComponentDataset model; + private File directory; + private ProgressReporterDialog reporter; + private Vector keyV; + private Vector valV; + private boolean oldyear; + + public ProjectBoardOperation(TCSession session, String options[], TCComponentDataset model, File directory, ProgressReporterDialog reporter, + Vector keyV, Vector valV, boolean oldyear) { + this.session = session; + this.options = options; + this.model = model; + this.directory = directory; + this.reporter = reporter; + this.keyV = keyV; + this.valV = valV; + this.oldyear = oldyear; + } + + @Override + public void executeOperation() throws Exception { + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + FileInputStream input = null; + FileOutputStream output = null; + XSSFWorkbook wb = null; + try { + HashMap exportMap = new HashMap<>(); + for(String s : options) { + if(s.contains("=")) { + String[] ss = s.split("="); + try { + exportMap.put(Integer.parseInt(ss[0])-1, ss); + }catch(NumberFormatException e) { + char[] cs = ss[0].toCharArray(); + int col = 0; + for(int i=0; i nodes = getTasks((TCComponentScheduleTask)comp[2]); +// System.out.println("nodes"+ nodes.size()); + if(nodes.size()==0) + continue; + String stage, status = result.getProperty("fnd0status"); + if(status.equals("ѽ") || status.equals("ֹ")) { + stage = status; + }else { +// stage = getStage(nodes);//TODO + stage = result.getProperty("ml8_ProjectState"); + } + Date finish = result.getDateProperty("fnd0SSTActualFinish"); + if(!oldyear && finish!=null && !sdf.format(finish).equals(sdf.format(now))) { + if(stage.equals("") || stage.equals("ֹ")) + continue; + } +// HashSet states = new HashSet<>(); +// for(String s : nodes.keySet()) { +// String state = nodes.get(s).getProperty("fnd0state"); +// if(state.equals("")) { +// states.add(s); +// } +// } +// if(states.size()==0) +// states.add(assessments[0]); + + cell = getCell(row, 0); + cell.setCellValue(noProj ? "":comp[1].getProperty("ml8_PrjDepartment"));//Ӫ + cell = getCell(row, 1); + cell.setCellValue(noProj ? "":comp[1].getProperty("ml8_PrjType"));//Ʒ + cell = getCell(row, 2); + cell.setCellValue(stage);//Ŀ״̬ + cell = getCell(row, 3); + cell.setCellValue(noProj ? "":comp[1].getProperty("ml8_ProductCode"));// + cell = getCell(row, 4); + cell.setCellValue(noProj ? "":comp[1].getProperty("ml8_ProductType"));//Ʒͺ + cell = getCell(row, 5); + cell.setCellValue(noProj ? "":comp[1].getProperty("ml8_PrjLevel"));//Ŀ + cell = getCell(row, 6); +// cell.setCellValue(noProj ? "":comp[1].getReferenceProperty("owning_user").getProperty("user_name"));//Ŀ + cell.setCellValue(noForm ? "":comp[3].getProperty("ml8_ProjectManagement1"));//Ŀ + cell = getCell(row, 7); + if(!noProj) + setDateValue(cell, comp[1], "ml8_ItemTime");//ʱ + if(!noForm) { + cell = getCell(row, 8); + setDateValue(cell, comp[3], "ml8_PDCP");//PDCPͬ + cell = getCell(row, 9); + setDateValue(cell, comp[3], "ml8_CPDCP");//PDCP + } + if(nodes.containsKey(assessments[0])) { + TCComponentScheduleTask task = nodes.get(assessments[0]); + cell = getCell(row, 10); + setDateValue(cell, task, "actual_finish_date");//ʱ + cell = getCell(row, 11); + Date cdate = noForm? null:comp[3].getDateProperty("ml8_CPDCP"); + Date date = noForm? null:(cdate==null ? comp[3].getDateProperty("ml8_PDCP"):cdate); + cell.setCellValue(getDateD(task.getDateProperty("actual_finish_date"), date));//ƫ + } + if(!noForm) { + cell = getCell(row, 12); + setDateValue(cell, comp[3], "ml8_Prototype");//ͬ + cell = getCell(row, 13); + setDateValue(cell, comp[3], "ml8_Cprototype");// + } + if(nodes.containsKey(assessments[1])) { + TCComponentScheduleTask task = nodes.get(assessments[1]); + cell = getCell(row, 14); + setDateValue(cell, task, "actual_finish_date");//ʱ + cell = getCell(row, 15); + Date cdate = noForm? null:comp[3].getDateProperty("ml8_Cprototype"); + Date date = noForm? null:(cdate==null ? comp[3].getDateProperty("ml8_Prototype"):cdate); + cell.setCellValue(getDateD(task.getDateProperty("actual_finish_date"), date));//ƫ + } + if(!noForm) { + cell = getCell(row, 16); + setDateValue(cell, comp[3], "ml8_SmallBatch");//Сͬ + cell = getCell(row, 17); + setDateValue(cell, comp[3], "ml8_CSmallBatch");//С + } + if(nodes.containsKey(assessments[2])) { + TCComponentScheduleTask task = nodes.get(assessments[2]); + cell = getCell(row, 18); + setDateValue(cell, task, "actual_finish_date");//ʱ + cell = getCell(row, 19); + Date cdate = noForm? null:comp[3].getDateProperty("ml8_CSmallBatch"); + Date date = noForm? null:(cdate==null ? comp[3].getDateProperty("ml8_SmallBatch"):cdate); + cell.setCellValue(getDateD(task.getDateProperty("actual_finish_date"), date));//ƫ + } + if(!noForm) { + cell = getCell(row, 20); + setDateValue(cell, comp[3], "ml8_ADCP");//ͬ + cell = getCell(row, 21); + setDateValue(cell, comp[3], "ml8_CADCP");// + } + if(nodes.containsKey(assessments[3])) { + TCComponentScheduleTask task = nodes.get(assessments[3]); + cell = getCell(row, 22); + setDateValue(cell, task, "actual_finish_date");//ʱ + cell = getCell(row, 23); + Date cdate = noForm? null:comp[3].getDateProperty("ml8_CADCP"); + Date date = noForm? null:(cdate==null ? comp[3].getDateProperty("ml8_ADCP"):cdate); + cell.setCellValue(getDateD(task.getDateProperty("actual_finish_date"), date));//ƫ + } +// System.out.println("date"+getDateD(comp[3].getDateProperty("ml8_PDCP"), comp[3].getDateProperty("ml8_Prototype"))); + AIFComponentContext[] contexts = TCUtil.getPseudoFolder(comp[0], "ML8_ECRProductQCD_rel").getChildren(); + int changeCount = 0; + StringBuilder change = new StringBuilder(""); + for(AIFComponentContext c : contexts) { + InterfaceAIFComponent compo = c.getComponent(); + if(!(compo instanceof TCComponentItem)) + continue; + TCComponentItem item = (TCComponentItem)compo; + TCComponentItemRevision[] revs = item.getReleasedItemRevisions(); + if(revs==null || revs.length==0) + continue; + change.append(revs[0].getProperty("ml8_OAProcessNo")).append("-").append(revs[0].getProperty("ml8_CReason")).append("\n"); + changeCount++; + } + cell = getCell(row, 24); + cell.setCellValue(changeCount);// + cell = getCell(row, 25); + cell.setCellValue(change.toString());//ԭ + + for(int r : exportMap.keySet()) { + cell = getCell(row, r); + String[] ss = exportMap.get(r); + switch(ss[1]) { + case "1": + cell.setCellValue(comp[0].getProperty(ss[2])); + break; + case "2": + cell.setCellValue(noProj ? "":comp[1].getProperty(ss[2])); + break; + case "3": + cell.setCellValue(noForm? "":comp[3].getProperty(ss[2])); + break; + default: + break; + } + } + i++; + } + + output = new FileOutputStream(file.getPath()); + wb.write(output); + input.close(); + output.close(); + file.renameTo(directory); + reporter.requestCanceling(); + MessageBox.post(desktop, "", "INFO", MessageBox.INFORMATION); +// dispose(); + }catch(Exception e1) { + reporter.requestCanceling(); + e1.printStackTrace(); + MessageBox.post(desktop, ""+e1.getMessage(), "ERROR", MessageBox.ERROR); + }finally { + TCUtil.setByPass(session, false); + if(input!=null) + try { + input.close(); + } catch (Exception e) { + e.printStackTrace(); + } + if(output!=null) + try { + output.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + 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; + } + private TCComponent[] getComps(TCComponent comp) throws Exception { + TCComponent[] comps = new TCComponent[4]; + if(comp instanceof TCComponentSchedule) { + comps[0] = comp; + TCComponent[] ps = comp.getReferenceListProperty("project_list"); + if(ps==null || ps.length==0) + comps[1] = null; + else + comps[1] = ps[0]; + comps[2] = ScheduleHelper.getScheduleSummaryTask((TCComponentSchedule)comp); + TCComponent[] refs = comp.getReferenceListProperty("IMAN_reference"); + comps[3] = null; + if(refs!=null && refs.length>0) { + for(TCComponent c : refs) { + if(c.isTypeOf("ML8_ProductQCDForm1")) { + Date states = c.getDateProperty("date_released"); + if(states!=null) { + comps[3] = c; + break; + } + } + } + } +// AIFComponentContext[] children = task.getChildren(); +// if(children!=null && children.length>0) { +// System.out.println("child:"+children[0].getComponent()); +// } + } + return comps; + } + private HashMap getTasks(TCComponentScheduleTask parent) throws Exception { + AIFComponentContext[] children = parent.getChildren(); + HashMap nodes = new HashMap<>(); + for(AIFComponentContext c : children) { + InterfaceAIFComponent comp = c.getComponent(); + if(!(comp instanceof TCComponentScheduleTask)) + continue; + TCComponentScheduleTask task = (TCComponentScheduleTask) comp; + String node = task.getProperty("ml8_AssessmentNode"); +// System.out.println(task+"=="+ node); + if(!node.isEmpty() && !nodes.containsKey(node)) { + nodes.put(node, task); + } + HashMap map = getTasks(task); + if(map.size()>0) { + for(String s : map.keySet()) { + nodes.put(s, map.get(s)); + } + } + } + return nodes; + } + /*private String getStage(HashMap nodes) throws Exception { + String[] stages = new String[] { "(PDCP", "", "С", "(׵)" }; + if(!nodes.containsKey(stages[0])) + return ""; + for(int i=0; i searchMap; + private HashMap objectMap; + private HashMap nodes; + + public ProjectDocReportDialog(TCSession session, String title, String[] options, TCComponentDataset model) throws Exception { + super(AIFUtility.getActiveDesktop()); + this.session = session; + this.model = model; + this.searchMap = new HashMap<>(); + this.objectMap = new HashMap<>(); + + String departments[] = session.getPreferenceService().getStringValues("ML8_ProjectDepart"); + if(departments==null || departments.length==0) + throw new Exception("ѡML8_ProjectDepartòȷ"); + String group = session.getGroup().toString().trim(); + String depart = ""; + for(String s : departments) { + String[] ss = s.split(":"); + if(group.equals(ss[0])) { + depart = ss[1]; + } + } + if(depart.isEmpty()) + throw new Exception("ǰ޷ѯϵϵͳԱ"); + + LinkedHashMap searchMap = new LinkedHashMap<>(); + for(String s : options) { + if(s.contains(":")) { + String[] ss = s.split(":"); + searchMap.put(ss[0], ss); + } + } + setTitle(title); + JPanel propPanel = new JPanel(new PropertyLayout(70, 5, 10, 5, 5, 5)); + int row = 1; + TCComponentListOfValuesType lovType = (TCComponentListOfValuesType)session.getTypeComponent("ListOfValues"); +// TCComponentListOfValues[] lov = lovType.find("ML8_ProjectCategory_LOV"); +// String[] vals = getDynamicLOV(lov[0]); +// System.out.println("ML8_ProjectCategory_LOV:"+lov[0].getType()+"=="+vals.length); + for(String s : searchMap.keySet()) { + JLabel label = new JLabel(s); + propPanel.add(row+".1.left.center", label); + String[] ss = searchMap.get(s); + switch(ss[1]){ + case "0": + JTextField text = new JTextField(); + text.setPreferredSize(new Dimension(150, 23)); + if(ss.length==3) + text.setText(ss[2]); + propPanel.add(row+".2.right.center", text); + this.searchMap.put(s, text); + break; + case "1": + JComboBox combo = new JComboBox<>(); + combo.setPreferredSize(new Dimension(150, 23)); + combo.addItem(""); + if(ss[2].contains(";")) { + String[] items = ss[2].split(";"); + for(String item : items) { + combo.addItem(item); + } + }else { + TCComponentListOfValues[] lovs = lovType.find(ss[2]);// lov + if(lovs==null || lovs.length==0) + throw new Exception("δҵLOV"+ss[2]); + if(lovs[0].isTypeOf("Fnd0ListOfValuesDynamic")) { + for(String item : getDynamicLOV(lovs[0])) { + combo.addItem(item); + } + }else { + ListOfValuesInfo vs = lovs[0].getListOfValues(); + String[] dVals = vs.getLOVDisplayValues(); + String[] sVals = vs.getStringListOfValues(); + HashMap map = new HashMap<>(); + for(int i=0; i4) + setSize(new Dimension(380, 240+(row-4)*25)); + else + setSize(new Dimension(380, 240)); + 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 title, String options, String depart) { + exportBtn.addActionListener(new ActionListener() { + @SuppressWarnings({ "unchecked", "deprecation" }) + @Override + public void actionPerformed(ActionEvent arg0) { + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); + File directory = TCUtil.saveExcelChooserAsk(title+sdf.format(new Date())); + if(directory==null) + return; + ProgressReporterDialog reporter = new ProgressReporterDialog("ʾ"); + reporter.reportProgressMessage("ڵԺ..."); + new Thread(reporter).start(); + new Thread() { + public void run(){ + FileInputStream input = null; + FileOutputStream output = null; + try { + if(directory.exists()) + directory.delete(); + + Vector keyV = new Vector<>(); + Vector valueV = new Vector<>(); +// sdf = new SimpleDateFormat("yyyy-M-d HH:mm"); + SimpleDateFormat sdf = new SimpleDateFormat("d-MMM-yyyy hh:mm"); + for(String s : searchMap.keySet()) { + JComponent c = searchMap.get(s); + if(c instanceof JTextField) { + String text = ((JTextField)c).getText(); + if(!text.isEmpty()) { + keyV.add(s); + valueV.add(text); + } + }else if(c instanceof MultiCombo) { + String text = ((MultiCombo) c).getText().trim(); + keyV.add(s); + if(!text.isEmpty()) { + valueV.add(text); + }else { + valueV.add(depart); + } + }else if(c instanceof JComboBox) { + String text = ((JComboBox)c).getSelectedItem().toString(); + if(!text.isEmpty()) { + keyV.add(s); + if(objectMap.containsKey(s)) { + valueV.add(((HashMap)objectMap.get(s)).get(text)); + }else { + valueV.add(text); + } + } + }else if(c instanceof PropertyDateComponent) { + Date date = ((PropertyDateComponent)c).getDate(); + if(date==null) + continue; + if(objectMap.containsKey(s)) { + date.setHours(23); + date.setMinutes(59); + } + if(date != null) { + keyV.add(s); + valueV.add(sdf.format(date)); + } + } + } +// if(keyV.size()==0) { +// throw new Exception("дѯ"); +// } + TCUtil.setByPass(session, true); + TCComponent[] results = TCUtil.query(session, options, keyV, valueV); + 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; + int rowCount = sheet.getLastRowNum(); + int col = 7; + StringBuilder fileErrors = new StringBuilder(""); + for(TCComponent result : results) { + nodes = new HashMap<>(); + TCComponentSchedule schedule = (TCComponentSchedule)result; + reporter.reportProgressMessage("ڵ"+schedule); + TCComponent project = schedule.getReferenceListProperty("project_list")[0]; + TCComponentScheduleTask summary = ScheduleHelper.getScheduleSummaryTask(schedule); + HashMap map = getTasks(summary.getChildren()); + row = getRow(sheet, 0); + cell = getCell(row, col); + cell.setCellValue(project.getProperty("ml8_ProductCode")); + row = getRow(sheet, 1); + cell = getCell(row, col); + cell.setCellValue(project.getProperty("ml8_ProductType")); + row = getRow(sheet, 2); + cell = getCell(row, col); + cell.setCellValue(schedule.getProperty("ml8_ProjectState"));// ˽׶ + row = getRow(sheet, 3); + cell = getCell(row, col); + cell.setCellValue(project.getReferenceProperty("owning_user").getProperty("user_name")); + row = getRow(sheet, 4); + cell = getCell(row, col); + String ml8_PrjLevel = project.getProperty("ml8_PrjLevel"); + int level = ml8_PrjLevel.equals("A")? 4 : (ml8_PrjLevel.equals("B")? 5 : 6); + cell.setCellValue(ml8_PrjLevel); + row = getRow(sheet, 5); + cell = getCell(row, col); + cell.setCellValue(schedule.getProperty("object_name")); + + boolean all = true; + Vector downs = new Vector<>();//TODO ĵ鵵ȫ + + for(int j=9; j0) + MessageBox.post(desktop, fileErrors.toString(), "ERROR", MessageBox.ERROR); + else + MessageBox.post(desktop, "", "INFO", MessageBox.INFORMATION); + dispose(); + }catch(Exception e1) { + reporter.requestCanceling(); + e1.printStackTrace(); + MessageBox.post(ProjectDocReportDialog.this, ""+e1.getMessage(), "ERROR", MessageBox.ERROR); + }finally { + if(input!=null) + try { + input.close(); + } catch (Exception e) { + e.printStackTrace(); + } + if(output!=null) + try { + output.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + }.start(); + } + }); + cancelBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + dispose(); + } + }); + } + + private XSSFRow getRow(XSSFSheet sheet, int i) throws Exception { + XSSFRow row = sheet.getRow(i); + if(row==null) + row = sheet.createRow(i); + return row; + } + private XSSFCell getCell(XSSFRow row, int col) throws Exception { + XSSFCell cell = row.getCell(col); + if(cell==null) + cell = row.createCell(col); + if(col>7) + cell.setCellStyle(getCell(row, 7).getCellStyle()); + return cell; + } + private HashMap getTasks(AIFComponentContext[] parent) throws Exception { +// AIFComponentContext[] children = parent.getChildren(); + HashMap tasks = new HashMap<>(); + for(AIFComponentContext c : parent) { + InterfaceAIFComponent comp = c.getComponent(); + if(!(comp instanceof TCComponentScheduleTask)) + continue; + TCComponentScheduleTask task = (TCComponentScheduleTask) comp; + System.out.println(task+"=="+task.getProperty("fnd0status")); + if(task.getProperty("fnd0status").equals("ֹ") && task.getProperty("ml8_FilingRequirements").equals("N")) + //task.getStringProperty("fnd0status").equals("aborted") || + continue; + if(!task.getProperty("ml8_CutOrNot").isEmpty()) + continue; + if(!task.getProperty("ml8_AssessmentNode").isEmpty()) { + nodes.put(task.getProperty("object_name"), task); + } + AIFComponentContext[] children = task.getChildren("child_task_taglist"); + if(children.length==0) { + String name = task.getProperty("object_name"); + if(!tasks.containsKey(name)) { + tasks.put(name, task); + }else if(tasks.get(name).getProperty("fnd0status").equals("ֹ")) { + tasks.put(name, task); + } + }else { + HashMap map = getTasks(children); + if(map.size()>0) { + for(String s : map.keySet()) { + tasks.put(s, map.get(s)); + } + } + } + } + return tasks; + } + /*private String getStage(HashMap nodes) throws Exception { + String[] stages = new String[] { "(PDCP", "", "С", "(׵)" }; + if(!nodes.containsKey(stages[0])) + return ""; + for(int i=0; i lovDisplayValueList = new Vector<>(); +// lovDisplayValueList.add(""); + Vector lovValueList = new Vector<>(); + LOVService lovService = LOVService.getService(session); + InitialLovData input = new InitialLovData(); + LovFilterData filter = new LovFilterData(); + filter.sortPropertyName = "object_name"; + filter.order = 1; + filter.numberToReturn = 100; + filter.maxResults = 100; + + input.lov = lov; + input.filterData = filter; + LOVSearchResults result = lovService.getInitialLOVValues(input); +// StringBuffer sb = new StringBuffer(); +// sb.append(">>"); + for (LOVValueRow row : result.lovValues) { + Map map = row.propDisplayValues; + Map realmap = row.propInternalValues; + for (String key : map.keySet()) { +// sb.append("UID:" + row.uid + ",key:" + key + "value:" + map.get(key)[0]); +// sb.append("\n"); + lovDisplayValueList.add(map.get(key)[0]); + lovValueList.add(realmap.get(key)[0]); + } + } +// System.out.println("StringBuffer:"+sb.toString()); + return lovDisplayValueList.toArray(new String[lovDisplayValueList.size()]); + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/report/ProjectDocReportHandler.java b/src/com/connor/lidy/report/ProjectDocReportHandler.java new file mode 100644 index 0000000..6d18d3f --- /dev/null +++ b/src/com/connor/lidy/report/ProjectDocReportHandler.java @@ -0,0 +1,43 @@ +package com.connor.lidy.report; + +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.AbstractAIFUIApplication; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +//ļнṹ +public class ProjectDocReportHandler extends AbstractHandler implements IHandler{ + + public Object execute(ExecutionEvent arg0) throws ExecutionException { + System.out.println("ProjectDocReportHandler"); + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + try { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + String pref = "ML8_ProjectDocReport", title = "Ŀĵ鵵ϸ-Ʒ"; + TCSession session = (TCSession) app.getSession(); + String options[] = session.getPreferenceService().getStringValues(pref); + if(options==null || options.length<2) { + MessageBox.post(desktop, "ѡ"+pref+"òȷ", "ERROR", MessageBox.ERROR); + return null; + } + TCComponent model = session.stringToComponent(options[0]);//A_OAAIm_5kSPsC + if(model==null || !model.isTypeOf("MSExcelX")) { + MessageBox.post(desktop, "ѡ"+pref+"ģUIDòȷ", "ERROR", MessageBox.ERROR); + return null; + } + new ProjectDocReportDialog(session, title, options, (TCComponentDataset)model); + }catch(Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + } + return null; + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/report/StandardRateReportHandler.java b/src/com/connor/lidy/report/StandardRateReportHandler.java new file mode 100644 index 0000000..eec85d3 --- /dev/null +++ b/src/com/connor/lidy/report/StandardRateReportHandler.java @@ -0,0 +1,56 @@ +package com.connor.lidy.report; + +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.AbstractAIFUIApplication; +import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +//ļнṹ +public class StandardRateReportHandler extends AbstractHandler implements IHandler{ + + public Object execute(ExecutionEvent arg0) throws ExecutionException { + System.out.println("StandardRateReportHandler"); + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + try { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + TCSession session = (TCSession) app.getSession(); + InterfaceAIFComponent target = app.getTargetComponent(); + if(target==null) { + MessageBox.post(desktop, "ѡԭϰ汾е", "ERROR", MessageBox.ERROR); + return null; + } + TCComponent comp = (TCComponent)target; + if(!comp.isTypeOf(new String[] { "ML8_WashingRevision", "ML8_ColdRevision", "ML8_RefrigeratorRevision", "ML8_OthersRevision" })) { + MessageBox.post(desktop, "ѡԭϰ汾е", "ERROR", MessageBox.ERROR); + return null; + } + String option = session.getPreferenceService().getStringValue("ML8_StandardRateReport"); + if(option==null || option.isEmpty()) { + MessageBox.post(desktop, "ѡML8_StandardRateReportòȷ", "ERROR", MessageBox.ERROR); + return null; + } + TCComponent model = session.stringToComponent(option);//ASFAAInA5kSPsC + if(model==null || !model.isTypeOf("MSExcelX")) { + MessageBox.post(desktop, "ѡML8_StandardRateReportģUIDòȷ", "ERROR", MessageBox.ERROR); + return null; + } + StandardRateReportOperation operation = new StandardRateReportOperation(session, (TCComponentItemRevision)target, (TCComponentDataset)model); + session.queueOperation(operation); +// MessageBox.post(desktop, "ݽ", "ʾ", MessageBox.INFORMATION); + }catch(Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + } + return null; + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/report/StandardRateReportOperation.java b/src/com/connor/lidy/report/StandardRateReportOperation.java new file mode 100644 index 0000000..37fa916 --- /dev/null +++ b/src/com/connor/lidy/report/StandardRateReportOperation.java @@ -0,0 +1,212 @@ +package com.connor.lidy.report; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashSet; +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.lidy.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.TCComponentBOMWindow; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentItem; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCComponentRevisionRule; +import com.teamcenter.rac.kernel.TCComponentTcFile; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +public class StandardRateReportOperation extends AbstractAIFOperation { + + private TCSession session; + private TCComponentItemRevision target; + private TCComponentDataset model; +// private XSSFRow sourceRow; + private HashSet idSet; + private String ProductCode; + private double[] count; + + public StandardRateReportOperation(TCSession session, TCComponentItemRevision target, TCComponentDataset model) { + this.session = session; + this.target = target; + this.model = model; + } + + @Override + public void executeOperation() throws Exception { + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + FileInputStream input = null; + FileOutputStream output = null; + try { + idSet = new HashSet<>(); + count = new double[] { 0, 0, 0 }; + Date now = new Date(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); + File directory = TCUtil.saveExcelChooser("׼ϵ"+sdf.format(now)); + if(directory==null) + return; + if(directory.exists()) + directory.delete(); + String path = directory.getPath(); + + TCComponentRevisionRule[] rules = TCComponentRevisionRule.listAllRules(session); + TCComponentRevisionRule taskRule = null; + for(TCComponentRevisionRule rule : rules) { + System.out.println("rule:"+rule); + if(rule.toString().equals("Ʒϸ")) { + taskRule = rule; + break; + } + } + TCComponentBOMWindow window = TCUtil.getWindow(session, taskRule); + TCComponentBOMLine line = TCUtil.getBOMLine(session, window, target); + AIFComponentContext[] pfs = target.getChildren("ML8_ProjectRelation"); + String ProductType; + if(pfs!=null && pfs.length>0) { + TCComponent pf = (TCComponent) pfs[0].getComponent(); + ProductCode = pf.getProperty("ml8_ProductCode");//Ʒ + ProductType = pf.getProperty("ml8_ProductType");//Ʒͺ + }else { + ProductCode = target.getProperty("ml8_ProductCode"); + ProductType = ""; + } + System.out.println("target:"+target+"=="+ProductCode); +// TCComponentItem item = line.getItem(); +// if(!(item.isTypeOf("ML8_RawMaterial")) && !(line.getProperty("ML8_MBOM").equals("MBOM"))) { +// count[0]++; +// } + recycelBom(line.getChildren()); + window.close(); + + 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; + System.out.println(count[0]+"=="+count[1]+"=="+count[2]); + + cell = getCell(getRow(sheet, 1), 1); + cell.setCellValue(ProductCode);//Ʒ + cell = getCell(getRow(sheet, 6), 1); + cell.setCellValue(ProductType);//Ʒͺ + +// cell = getCell(getRow(sheet, 1), 1); +// cell.setCellValue(target.getProperty("ml8_ProductCode"));//Ʒ + cell = getCell(getRow(sheet, 2), 1); + cell.setCellValue(count[0]); //ܼ + cell = getCell(getRow(sheet, 3), 1); + cell.setCellValue(count[0]==0 ? 0:(count[0]-count[1])/count[0]);//׼ + cell = getCell(getRow(sheet, 4), 1); + cell.setCellValue(count[0]==0 ? 0:count[2]/count[0]); //ͨû + cell = getCell(getRow(sheet, 5), 1); + cell.setCellValue(count[1]); //רü +// cell = getCell(getRow(sheet, 6), 1); +// cell.setCellValue(target.getProperty("ml8_ProductType"));//Ʒͺ + + output = new FileOutputStream(file.getPath()); + wb.write(output); + input.close(); + output.close(); +// System.out.println("file:"+file.getPath()); + String newPath = System.getProperty("java.io.tmpdir")+path.substring(path.lastIndexOf("\\")); + File reFile = new File(newPath); + file.renameTo(reFile); +// System.out.println("new directory:"+reFile.getPath()); + reFile.renameTo(directory); + + MessageBox.post(desktop, "", "INFO", MessageBox.INFORMATION); + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + }finally { + if(input!=null) + input.close(); + if(output!=null) + output.close(); + } + } + 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()>2) +// cell.setCellStyle(getCell(sourceRow, col).getCellStyle()); + return cell; + } + private void recycelBom(AIFComponentContext[] context) throws Exception { + for(AIFComponentContext c : context) { + TCComponentBOMLine line = (TCComponentBOMLine)c.getComponent(); + String id = line.getProperty("bl_item_item_id"); + if(idSet.contains(id)) + continue; + idSet.add(id); + System.out.println("line:"+line); +// System.out.println(line+":"+count[0]+"=="+count[1]+"=="+count[2]); + TCComponentItem item = line.getItem(); + if(item.isTypeOf("ML8_RawMaterial") || line.getProperty("ML8_MBOM").equals("MBOM")) + continue; + System.out.println(" "+id); + count[0]++;// +// if(line.getItemRevision().getProperty("ml8_FigureNum").equals(target.getProperty("item_id"))) { + TCComponentItemRevision rev = line.getItemRevision(); + String figureNum = rev.getProperty("ml8_FigureNum"); + if(figureNum.contains(".")) { + figureNum = figureNum.substring(0, figureNum.indexOf(".")); + } + System.out.println("ml8_ProductCode:"+figureNum); +// if(rev.getProperty("ml8_ProductCode").equals(ProductCode)) { + if(figureNum.equals(ProductCode)) { + System.out.println("ר "+id); + count[1]++;//ר + } +// AIFComponentContext[] ML8_ProjectRelation = rev.getChildren("ML8_ProjectRelation"); +// if(ML8_ProjectRelation==null || ML8_ProjectRelation.length==0) { +//// throw new Exception(line+"汾δҵĿƱ"); +//// System.out.println("ml8_ProductCode:"+rev.getProperty("ml8_ProductCode")); +// System.out.println("ml8_ProductCode:"+rev.getProperty("ml8_FigureNum")); +//// if(rev.getProperty("ml8_ProductCode").equals(ProductCode)) { +// if(rev.getProperty("ml8_FigureNum").equals(ProductCode)) { +// System.out.println("ר "+id); +// count[1]++;//ר +// } +// }else { +// String s = ML8_ProjectRelation[0].getComponent().getProperty("ml8_FigureNum"); +//// String s = ML8_ProjectRelation[0].getComponent().getProperty("ml8_ProductCode"); +// System.out.println("ml8_ProductCode:"+s); +// if(s.equals(ProductCode)) { +// System.out.println("ר "+id); +// count[1]++;//ר +// } +// } + System.out.println("ml8_Status:"+item.getProperty("ml8_Status")); + if(item.getProperty("ml8_Status").contains("ѡ")) { + System.out.println("ѡ "+id); + count[2]++;//ѡ + } + + AIFComponentContext[] child = line.getChildren(); + if(child!=null && child.length>0) + recycelBom(line.getChildren()); + } + } +} diff --git a/src/com/connor/lidy/report/TechProjectBoardDialog.java b/src/com/connor/lidy/report/TechProjectBoardDialog.java new file mode 100644 index 0000000..28f35ac --- /dev/null +++ b/src/com/connor/lidy/report/TechProjectBoardDialog.java @@ -0,0 +1,293 @@ +package com.connor.lidy.report; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Map; +import java.util.Vector; + +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; + +import com.connor.lidy.util.MultiCombo; +import com.connor.lidy.util.ProgressReporterDialog; +import com.connor.lidy.util.SelectUserDialog; +import com.connor.lidy.util.TCUtil; +import com.teamcenter.rac.aif.AbstractAIFDialog; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentListOfValues; +import com.teamcenter.rac.kernel.TCComponentListOfValuesType; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.stylesheet.PropertyDateComponent; +import com.teamcenter.rac.util.MessageBox; +import com.teamcenter.rac.util.PropertyLayout; +import com.teamcenter.services.rac.core.LOVService; +import com.teamcenter.services.rac.core._2013_05.LOV.InitialLovData; +import com.teamcenter.services.rac.core._2013_05.LOV.LOVSearchResults; +import com.teamcenter.services.rac.core._2013_05.LOV.LOVValueRow; +import com.teamcenter.services.rac.core._2013_05.LOV.LovFilterData; + +public class TechProjectBoardDialog extends AbstractAIFDialog { + private static final long serialVersionUID = 1L; + private TCSession session; + private TCComponentDataset model; + private JButton exportBtn; + private JButton cancelBtn; + private JComponent[] comps; + + public TechProjectBoardDialog(TCSession session, String[] options, TCComponentDataset model, String[] departments) throws Exception { + super(AIFUtility.getActiveDesktop()); + this.session = session; + this.model = model; + this.comps = new JComponent[8]; + + System.out.println("group:"+session.getGroup()+">>"+session.getGroup().getGroupName()); + String group = session.getGroup().toString().trim(); + String depart = ""; + for(String s : departments) { + String[] ss = s.split(":"); + if(group.equals(ss[0])) { + depart = ss[1]; + } + } + if(depart.isEmpty()) + throw new Exception("ǰ޷ѯϵϵͳԱ"); + + setTitle("Ŀиٱ-"); + JPanel propPanel = new JPanel(new PropertyLayout(70, 5, 10, 5, 5, 5)); + TCComponentListOfValuesType lovType = (TCComponentListOfValuesType)session.getTypeComponent("ListOfValues"); +// TCComponentListOfValues[] lov = lovType.find("ML8_ProjectCategory_LOV"); +// String[] vals = getDynamicLOV(lov[0]); +// System.out.println("ML8_ProjectCategory_LOV:"+lov[0].getType()+"=="+vals.length); + JLabel label1 = new JLabel("Ʒ"); + propPanel.add("1.1.left.center", label1); + JTextField text1 = new JTextField(); + text1.setPreferredSize(new Dimension(155, 23)); + propPanel.add("1.2.right.center", text1); + comps[0] = text1; + + JLabel label2 = new JLabel("Ŀ"); + propPanel.add("2.1.left.center", label2); + JComboBox combo2 = new JComboBox<>(); + combo2.setPreferredSize(new Dimension(155, 23)); + combo2.addItem(""); + TCComponentListOfValues[] lovs2 = lovType.find("ML8_ProjectLevel_LOV"); + for(String item : getDynamicLOV(lovs2[0])) { + combo2.addItem(item); + } + propPanel.add("2.2.right.center", combo2); + comps[1] = combo2; + + JLabel label3 = new JLabel("Ŀʱ"); + propPanel.add("3.1.left.center", label3); + PropertyDateComponent date3 = new PropertyDateComponent(); + propPanel.add("3.2.right.center", date3); + comps[2] = date3; + + JLabel label4 = new JLabel("ĿʱС"); + propPanel.add("4.1.left.center", label4); + PropertyDateComponent date4 = new PropertyDateComponent(); + propPanel.add("4.2.right.center", date4); + comps[3] = date4; + + JLabel label5 = new JLabel("Ŀ"); + propPanel.add("5.1.left.center", label5); + JPanel personPanel = new JPanel(new PropertyLayout(5, 5, 0, 5, 5, 5)); + JTextField text5 = new JTextField(); + text5.setPreferredSize(new Dimension(105, 23)); + text5.setEditable(false); + personPanel.add("1.1.center.center", text5); + JButton personBtn = new JButton("..."); + personBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + try { + new SelectUserDialog(text5, false).showDialog(); + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(TechProjectBoardDialog.this, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + } + } + }); + personBtn.setPreferredSize(new Dimension(45, 23)); + personPanel.add("1.2.center.center", personBtn); + propPanel.add("5.2.center.center", personPanel); + comps[4] = text5; + + JLabel label6 = new JLabel("Ŀе"); + propPanel.add("6.1.left.center", label6); +// JComboBox combo6 = new JComboBox<>(); +// combo6.setPreferredSize(new Dimension(155, 23)); +// combo6.addItem(""); +//// TCComponentListOfValues[] lovs6 = lovType.find("ML8_PrjDepartment_LOV"); +//// for(String item : getDynamicLOV(lovs6[0])) { +// for(String item : depart.split(";")) { +// combo6.addItem(item); +// } + MultiCombo combo6 = new MultiCombo(depart.split(";")); + combo6.setEditable(true); + propPanel.add("6.2.right.center", combo6); + combo6.setPreferredSize(new Dimension(155, 23)); + comps[5] = combo6; + + JLabel label7 = new JLabel("Ŀ״̬"); + propPanel.add("7.1.left.center", label7); + JComboBox combo7 = new JComboBox<>(); + combo7.setPreferredSize(new Dimension(155, 23)); + combo7.addItem(""); + TCComponentListOfValues[] lovs7 = lovType.find("ML8_MissionPhase_LOV"); + for(String item : getDynamicLOV(lovs7[0])) { + combo7.addItem(item); +// System.out.println("item:"+item); + } + propPanel.add("7.2.right.center", combo7); + comps[6] = combo7; + + JCheckBox showEarly = new JCheckBox("ʾѽ"); + comps[7] = showEarly; + exportBtn = new JButton(""); + cancelBtn = new JButton("ȡ"); + JPanel btnPanel = new JPanel(new FlowLayout()); + btnPanel.add(showEarly); + btnPanel.add(exportBtn); + btnPanel.add(cancelBtn); + setLayout(new BorderLayout()); + add(BorderLayout.CENTER, propPanel); + add(BorderLayout.SOUTH, btnPanel); +// add(new JLabel("")); + addActionListener(depart, options); + + pack(); + setSize(new Dimension(380, 300)); + 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 depart, String[] options) { + exportBtn.addActionListener(new ActionListener() { + @SuppressWarnings("deprecation") + @Override + public void actionPerformed(ActionEvent arg0) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); + File directory = TCUtil.saveExcelChooserAsk("Ŀиٱ-"+sdf.format(new Date())); + if(directory==null) + return; + ProgressReporterDialog reporter = new ProgressReporterDialog("ʾ"); + reporter.reportProgressMessage("ڵԺ..."); + new Thread(reporter).start(); + new Thread() { + public void run(){ + try { + SimpleDateFormat sdf = new SimpleDateFormat("d-MMM-yyyy hh:mm"); + Vector keyV = new Vector<>(); + Vector valV = new Vector<>(); + String text1 = ((JTextField) comps[0]).getText(); + if(!text1.isEmpty()) { + keyV.add("Ʒ"); + valV.add(text1); + } + String text2 = ((JComboBox) comps[1]).getSelectedItem().toString(); + if(!text2.isEmpty()) { + keyV.add("Ŀ"); + valV.add(text2); + } +// System.out.println("Ŀʱ:"+((PropertyDateComponent) comps[2]).getDateString()); + Date date3 = ((PropertyDateComponent) comps[2]).getDate(); + if(date3 != null) { + keyV.add("Ŀʱ"); + valV.add(sdf.format(date3)); + } +// System.out.println("ĿʱС:"+((PropertyDateComponent) comps[3]).getDateString()); + Date date4 = ((PropertyDateComponent) comps[3]).getDate(); + if(date4 != null) { + keyV.add("ĿʱС"); + valV.add(sdf.format(date4)); + } + String text5 = ((JTextField) comps[4]).getText(); + if(!text5.isEmpty()) { + keyV.add("Ŀ"); + valV.add(text5); + } +// String text6 = ((JComboBox) comps[5]).getSelectedItem().toString(); + String text6 = ((MultiCombo) comps[5]).getText().trim(); + if(!text6.isEmpty()) { + keyV.add("Ŀе"); + valV.add(text6); + }else { + keyV.add("Ŀе"); + valV.add(depart); + } + String text7 = ((JComboBox) comps[6]).getSelectedItem().toString(); + if(!text7.isEmpty()) { + keyV.add("Ŀ״̬"); + valV.add(text7); + } + boolean oldyear = ((JCheckBox) comps[7]).isSelected(); + + new TechProjectBoardOperation(session, options, model, directory, reporter, keyV, valV, oldyear).executeOperation(); + }catch(Exception e1) { + reporter.requestCanceling(); + e1.printStackTrace(); + MessageBox.post(TechProjectBoardDialog.this, ""+e1.getMessage(), "ERROR", MessageBox.ERROR); + } + } + }.start(); + } + }); + cancelBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + dispose(); + } + }); + } + + public String[] getDynamicLOV(TCComponentListOfValues lov) throws Exception { + Vector lovDisplayValueList = new Vector<>(); +// lovDisplayValueList.add(""); +// Vector lovValueList = new Vector<>(); + LOVService lovService = LOVService.getService(session); + InitialLovData input = new InitialLovData(); + LovFilterData filter = new LovFilterData(); + filter.sortPropertyName = "object_name"; + filter.order = 1; + filter.numberToReturn = 100; + filter.maxResults = 100; + + input.lov = lov; + input.filterData = filter; + LOVSearchResults result = lovService.getInitialLOVValues(input); +// StringBuffer sb = new StringBuffer(); +// sb.append(">>"); + for (LOVValueRow row : result.lovValues) { + Map map = row.propDisplayValues; +// Map realmap = row.propInternalValues; + for (String key : map.keySet()) { + if(!key.equals("object_name")) + continue; +// sb.append("UID:" + row.uid + ",key:" + key + "value:" + map.get(key)[0]); +// sb.append("\n"); + String[] v = map.get(key); + lovDisplayValueList.add(v[0]); +// lovValueList.add(realmap.get(key)[0]); +// System.out.println("key:"+key+"=="+v.length+">>"+v[0]); + } + } +// System.out.println("StringBuffer:"+sb.toString()); + return lovDisplayValueList.toArray(new String[lovDisplayValueList.size()]); + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/report/TechProjectBoardHandler.java b/src/com/connor/lidy/report/TechProjectBoardHandler.java new file mode 100644 index 0000000..3a69d60 --- /dev/null +++ b/src/com/connor/lidy/report/TechProjectBoardHandler.java @@ -0,0 +1,48 @@ +package com.connor.lidy.report; + +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.AbstractAIFUIApplication; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +//ļнṹ +public class TechProjectBoardHandler extends AbstractHandler implements IHandler{ + + public Object execute(ExecutionEvent arg0) throws ExecutionException { + System.out.println("TechProjectBoardHandler"); + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + try { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + TCSession session = (TCSession) app.getSession(); +// ProjectBoardDialog.getComps(session.stringToComponent("AyJAAIWu5kSPsC")); + String options[] = session.getPreferenceService().getStringValues("ML8_TechProjectReport"); + if(options==null || options.length<2) { + MessageBox.post(desktop, "ѡML8_TechProjectReportòȷ", "ERROR", MessageBox.ERROR); + return null; + } + TCComponent model = session.stringToComponent(options[0]);//wtGAAIma5kSPsC SearchProjectSchedule + if(model==null || !model.isTypeOf("MSExcelX")) { + MessageBox.post(desktop, "ѡML8_TechProjectReportģUIDòȷ", "ERROR", MessageBox.ERROR); + return null; + } + String departments[] = session.getPreferenceService().getStringValues("ML8_TechProjectDepart"); + if(departments==null || departments.length==0) { + MessageBox.post(desktop, "ѡML8_TechProjectDepartòȷ", "ERROR", MessageBox.ERROR); + return null; + } + new TechProjectBoardDialog(session, options, (TCComponentDataset)model, departments); + }catch(Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + } + return null; + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/report/TechProjectBoardOperation.java b/src/com/connor/lidy/report/TechProjectBoardOperation.java new file mode 100644 index 0000000..e593f81 --- /dev/null +++ b/src/com/connor/lidy/report/TechProjectBoardOperation.java @@ -0,0 +1,346 @@ +package com.connor.lidy.report; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Vector; + +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.lidy.util.ProgressReporterDialog; +import com.connor.lidy.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.aif.kernel.InterfaceAIFComponent; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentItem; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCComponentSchedule; +import com.teamcenter.rac.kernel.TCComponentScheduleTask; +import com.teamcenter.rac.kernel.TCComponentTcFile; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.schedule.scheduler.componentutils.ScheduleHelper; +import com.teamcenter.rac.util.MessageBox; + +public class TechProjectBoardOperation extends AbstractAIFOperation { + + private TCSession session; + private String options[]; + private TCComponentDataset model; + private File directory; + private ProgressReporterDialog reporter; + private Vector keyV; + private Vector valV; + private boolean oldyear; + + public TechProjectBoardOperation(TCSession session, String options[], TCComponentDataset model, File directory, ProgressReporterDialog reporter, + Vector keyV, Vector valV, boolean oldyear) { + this.session = session; + this.options = options; + this.model = model; + this.directory = directory; + this.reporter = reporter; + this.keyV = keyV; + this.valV = valV; + this.oldyear = oldyear; + } + + @Override + public void executeOperation() throws Exception { + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + FileInputStream input = null; + FileOutputStream output = null; + XSSFWorkbook wb = null; + try { + HashMap exportMap = new HashMap<>(); + for(String s : options) { + if(s.contains("=")) { + String[] ss = s.split("="); + try { + exportMap.put(Integer.parseInt(ss[0])-1, ss); + }catch(NumberFormatException e) { + char[] cs = ss[0].toCharArray(); + int col = 0; + for(int i=0; i nodes = getTasks((TCComponentScheduleTask)comp[2]); +// System.out.println("nodes"+ nodes.size()); + if(nodes.size()==0) + continue; + String stage, status = result.getProperty("fnd0status"); + if(status.equals("ѽ") || status.equals("ֹ")) { + stage = status; + }else { +// stage = getStage(nodes);//TODO + stage = result.getProperty("ml8_ProjectState"); + } + Date finish = result.getDateProperty("fnd0SSTActualFinish"); + if(!oldyear && finish!=null && !sdf.format(finish).equals(sdf.format(now))) { + if(stage.equals("") || stage.equals("ֹ")) + continue; + } + + cell = getCell(row, 0); + cell.setCellValue(i-1);// + cell = getCell(row, 1); + cell.setCellValue(noProj ? "":comp[1].getProperty("ml8_PrjDepartment"));//ĿԪ + cell = getCell(row, 2); + cell.setCellValue(noProj ? "":comp[1].getProperty("ml8_PrjType"));//Ŀ + cell = getCell(row, 3); + cell.setCellValue(stage);//Ŀн׶ + cell = getCell(row, 4); + cell.setCellValue(noProj ? "":comp[1].getProperty("project_id"));//Ŀ + cell = getCell(row, 5); + cell.setCellValue(noProj ? "":comp[1].getProperty("project_name"));//Ŀ + cell = getCell(row, 6); + cell.setCellValue(noProj ? "":comp[1].getProperty("ml8_PrjLevel"));//Ŀ + cell = getCell(row, 7); +// cell.setCellValue(noProj ? "":comp[1].getReferenceProperty("owning_user").getProperty("user_name"));//Ŀ + cell.setCellValue(noForm ? "":comp[3].getProperty("ml8_ProjectManagement1"));//Ŀ + cell = getCell(row, 8); + if(!noProj) + setDateValue(cell, comp[1], "ml8_ItemTime");//ʱ + if(!noForm) { + cell = getCell(row, 9); + setDateValue(cell, comp[3], "ml8_PDCP");//PDCPͬ + cell = getCell(row, 10); + setDateValue(cell, comp[3], "ml8_CPDCP");//PDCP + } + if(nodes.containsKey(assessments[0])) { + TCComponentScheduleTask task = nodes.get(assessments[0]); + cell = getCell(row, 11); + setDateValue(cell, task, "actual_finish_date");//ʱ + cell = getCell(row, 12); + Date cdate = noForm? null:comp[3].getDateProperty("ml8_CPDCP"); + Date date = noForm? null:(cdate==null ? comp[3].getDateProperty("ml8_PDCP"):cdate); + cell.setCellValue(getDateD(task.getDateProperty("actual_finish_date"), date)); + } + if(!noForm) { + cell = getCell(row, 13); + setDateValue(cell, comp[3], "ml8_ADCP");//ADCPͬ + cell = getCell(row, 14); + setDateValue(cell, comp[3], "ml8_CADCP");//ADCP + } + if(nodes.containsKey(assessments[1])) { + TCComponentScheduleTask task = nodes.get(assessments[1]); + cell = getCell(row, 15); + setDateValue(cell, task, "actual_finish_date");//ʱ + cell = getCell(row, 16); + Date cdate = noForm? null:comp[3].getDateProperty("ml8_CADCP"); + Date date = noForm? null:(cdate==null ? comp[3].getDateProperty("ml8_ADCP"):cdate); + cell.setCellValue(getDateD(task.getDateProperty("actual_finish_date"), date)); + } + if(!noForm) { + cell = getCell(row, 17); + setDateValue(cell, comp[3], "ml8_Transfer");//תƺͬ + cell = getCell(row, 18); + setDateValue(cell, comp[3], "ml8_Ctransfer");//תƱ + } + if(nodes.containsKey(assessments[2])) { + TCComponentScheduleTask task = nodes.get(assessments[2]); + cell = getCell(row, 19); + setDateValue(cell, task, "actual_finish_date");//ʱ + cell = getCell(row, 20); + Date cdate = noForm? null:comp[3].getDateProperty("ml8_Ctransfer"); + Date date = noForm? null:(cdate==null ? comp[3].getDateProperty("ml8_Transfer"):cdate); + cell.setCellValue(getDateD(task.getDateProperty("actual_finish_date"), date)); + } +// System.out.println("date"+getDateD(comp[3].getDateProperty("ml8_PDCP"), comp[3].getDateProperty("ml8_Prototype"))); + AIFComponentContext[] contexts = TCUtil.getPseudoFolder(comp[0], "ML8_ECRProductQCD_rel").getChildren(); + int changeCount = 0; + StringBuilder change = new StringBuilder(""); + for(AIFComponentContext c : contexts) { + InterfaceAIFComponent compo = c.getComponent(); + if(!(compo instanceof TCComponentItem)) + continue; + TCComponentItem item = (TCComponentItem)compo; + TCComponentItemRevision[] revs = item.getReleasedItemRevisions(); + if(revs==null || revs.length==0) + continue; + change.append(revs[0].getProperty("ml8_OAProcessNo")).append("-").append(revs[0].getProperty("ml8_CReason")).append("\n"); + changeCount++; + } + cell = getCell(row, 21); + cell.setCellValue(changeCount);// + cell = getCell(row, 22); + cell.setCellValue(change.toString());//ԭ + + for(Integer col : exportMap.keySet()) { + cell = getCell(row, col); + String[] ss = exportMap.get(col); + switch(ss[1]) { + case "1": + cell.setCellValue(comp[0].getProperty(ss[2])); + break; + case "2": + cell.setCellValue(noProj ? "":comp[1].getProperty(ss[2])); + break; + case "3": + cell.setCellValue(noForm? "":comp[3].getProperty(ss[2])); + break; + default: + break; + } + } + i++; + } + + output = new FileOutputStream(file.getPath()); + wb.write(output); + input.close(); + output.close(); + file.renameTo(directory); + reporter.requestCanceling(); + MessageBox.post(desktop, "", "INFO", MessageBox.INFORMATION); +// dispose(); + }catch(Exception e1) { + reporter.requestCanceling(); + e1.printStackTrace(); + MessageBox.post(desktop, ""+e1.getMessage(), "ERROR", MessageBox.ERROR); + }finally { + TCUtil.setByPass(session, false); + if(input!=null) + try { + input.close(); + } catch (Exception e) { + e.printStackTrace(); + } + if(output!=null) + try { + output.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + 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; + } + private TCComponent[] getComps(TCComponent comp) throws Exception { + TCComponent[] comps = new TCComponent[4]; + if(comp instanceof TCComponentSchedule) { + comps[0] = comp; + TCComponent[] ps = comp.getReferenceListProperty("project_list"); + if(ps==null || ps.length==0) + comps[1] = null; + else + comps[1] = ps[0]; + comps[2] = ScheduleHelper.getScheduleSummaryTask((TCComponentSchedule)comp); + TCComponent[] refs = comp.getReferenceListProperty("IMAN_reference"); + comps[3] = null; + if(refs!=null && refs.length>0) { + for(TCComponent c : refs) { + if(c.isTypeOf("ML8_TechQCDForm1")) { + Date states = c.getDateProperty("date_released"); + if(states!=null) { + comps[3] = c; + break; + } + } + } + } +// AIFComponentContext[] children = task.getChildren(); +// if(children!=null && children.length>0) { +// System.out.println("child:"+children[0].getComponent()); +// } + } + return comps; + } + private HashMap getTasks(TCComponentScheduleTask parent) throws Exception { + AIFComponentContext[] children = parent.getChildren(); + HashMap nodes = new HashMap<>(); + for(AIFComponentContext c : children) { + InterfaceAIFComponent comp = c.getComponent(); + if(!(comp instanceof TCComponentScheduleTask)) + continue; + TCComponentScheduleTask task = (TCComponentScheduleTask) comp; + String node = task.getProperty("ml8_AssessmentNode"); +// System.out.println(task+"=="+ node); + if(!node.isEmpty() && !nodes.containsKey(node)) { + nodes.put(node, task); + } + HashMap map = getTasks(task); + if(map.size()>0) { + for(String s : map.keySet()) { + nodes.put(s, map.get(s)); + } + } + } + return nodes; + } + /*private String getStage(HashMap nodes) throws Exception { + String[] stages = new String[] { "(PDCP", "ADCP", "ת" }; + if(!nodes.containsKey(stages[0])) + return ""; + for(int i=0; i searchMap; + private HashMap exportMap; + private HashMap objectMap; + private HashMap nodes; + + public TechProjectDocReportDialog(TCSession session, String title, String[] options, TCComponentDataset model) throws Exception { + super(AIFUtility.getActiveDesktop()); + this.session = session; + this.model = model; + this.searchMap = new HashMap<>(); + this.exportMap = new HashMap<>(); + this.objectMap = new HashMap<>(); + + String departments[] = session.getPreferenceService().getStringValues("ML8_ProjectDepart"); + if(departments==null || departments.length==0) + throw new Exception("ѡML8_ProjectDepartòȷ"); + String group = session.getGroup().toString().trim(); + String depart = ""; + for(String s : departments) { + String[] ss = s.split(":"); + if(group.equals(ss[0])) { + depart = ss[1]; + } + } + if(depart.isEmpty()) + throw new Exception("ǰ޷ѯϵϵͳԱ"); + + LinkedHashMap searchMap = new LinkedHashMap<>(); + for(String s : options) { + if(s.contains(":")) { + String[] ss = s.split(":"); + searchMap.put(ss[0], ss); + }else if(s.contains("=")) { + String[] ss = s.split("="); + exportMap.put(ss[0], ss); + } + } + setTitle(title); + JPanel propPanel = new JPanel(new PropertyLayout(70, 5, 10, 5, 5, 5)); + int row = 1; + TCComponentListOfValuesType lovType = (TCComponentListOfValuesType)session.getTypeComponent("ListOfValues"); +// TCComponentListOfValues[] lov = lovType.find("ML8_ProjectCategory_LOV"); +// String[] vals = getDynamicLOV(lov[0]); +// System.out.println("ML8_ProjectCategory_LOV:"+lov[0].getType()+"=="+vals.length); + for(String s : searchMap.keySet()) { + JLabel label = new JLabel(s); + propPanel.add(row+".1.left.center", label); + String[] ss = searchMap.get(s); + switch(ss[1]){ + case "0": + JTextField text = new JTextField(); + text.setPreferredSize(new Dimension(150, 23)); + propPanel.add(row+".2.right.center", text); + this.searchMap.put(s, text); + break; + case "1": + JComboBox combo = new JComboBox<>(); + combo.setPreferredSize(new Dimension(150, 23)); + combo.addItem(""); + if(ss[2].contains(";")) { + String[] items = ss[2].split(";"); + for(String item : items) { + combo.addItem(item); + } + }else { + TCComponentListOfValues[] lovs = lovType.find(ss[2]);//TODO lov + if(lovs==null || lovs.length==0) + throw new Exception("δҵLOV"+ss[2]); + if(lovs[0].isTypeOf("Fnd0ListOfValuesDynamic")) { + for(String item : getDynamicLOV(lovs[0])) { + combo.addItem(item); + } + }else { + ListOfValuesInfo vs = lovs[0].getListOfValues(); + String[] dVals = vs.getLOVDisplayValues(); + String[] sVals = vs.getStringListOfValues(); + HashMap map = new HashMap<>(); + for(int i=0; i4) + setSize(new Dimension(380, 240+(row-4)*25)); + else + setSize(new Dimension(380, 240)); + 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 title, String options, String depart) { + exportBtn.addActionListener(new ActionListener() { + @SuppressWarnings({ "unchecked", "deprecation" }) + @Override + public void actionPerformed(ActionEvent arg0) { + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); + File directory = TCUtil.saveExcelChooserAsk(title+sdf.format(new Date())); + if(directory==null) + return; + ProgressReporterDialog reporter = new ProgressReporterDialog("ʾ"); + reporter.reportProgressMessage("ڵԺ..."); + new Thread(reporter).start(); + new Thread() { + public void run(){ + FileInputStream input = null; + FileOutputStream output = null; + try { + if(directory.exists()) + directory.delete(); + Vector keyV = new Vector<>(); + Vector valueV = new Vector<>(); +// sdf = new SimpleDateFormat("yyyy-M-d HH:mm"); + SimpleDateFormat sdf = new SimpleDateFormat("d-MMM-yyyy hh:mm"); + for(String s : searchMap.keySet()) { + JComponent c = searchMap.get(s); + if(c instanceof JTextField) { + String text = ((JTextField)c).getText(); + if(!text.isEmpty()) { + keyV.add(s); + valueV.add(text); + } + }else if(c instanceof MultiCombo) { + String text = ((MultiCombo) c).getText().trim(); + keyV.add(s); + if(!text.isEmpty()) { + valueV.add(text); + }else { + valueV.add(depart); + } + }else if(c instanceof JComboBox) { + String text = ((JComboBox)c).getSelectedItem().toString(); + if(!text.isEmpty()) { + keyV.add(s); + if(objectMap.containsKey(s)) { + valueV.add(((HashMap)objectMap.get(s)).get(text)); + }else { + valueV.add(text); + } + } + }else if(c instanceof PropertyDateComponent) { + Date date = ((PropertyDateComponent)c).getDate(); + if(date==null) + continue; + if(objectMap.containsKey(s)) { + date.setHours(23); + date.setMinutes(59); + } + if(date != null) { + keyV.add(s); + valueV.add(sdf.format(date)); + } + } + } +// if(keyV.size()==0) { +// throw new Exception("дѯ"); +// } + TCUtil.setByPass(session, true); + TCComponent[] results = TCUtil.query(session, options, keyV, valueV); + 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; + int rowCount = sheet.getLastRowNum(); + int col = 7; + StringBuilder fileErrors = new StringBuilder(""); + for(TCComponent result : results) { + nodes = new HashMap<>(); + TCComponentSchedule schedule = (TCComponentSchedule)result; + reporter.reportProgressMessage("ڵ"+schedule); + TCComponent project = schedule.getReferenceListProperty("project_list")[0]; + TCComponentScheduleTask summary = ScheduleHelper.getScheduleSummaryTask(schedule); + HashMap map = getTasks(summary.getChildren()); +// String[] stage = getStage(nodes); + row = getRow(sheet, 0); + cell = getCell(row, col); + cell.setCellValue(project.getProperty("project_id")); + row = getRow(sheet, 1); + cell = getCell(row, col); + cell.setCellValue(schedule.getProperty("ml8_ProjectState"));//˽׶ + row = getRow(sheet, 2); + cell = getCell(row, col); + cell.setCellValue(project.getProperty("project_name")); + row = getRow(sheet, 3); + cell = getCell(row, col); + cell.setCellValue(project.getReferenceProperty("owning_user").getProperty("user_name")); + row = getRow(sheet, 4); + cell = getCell(row, col); + String ml8_PrjLevel = project.getProperty("ml8_PrjLevel"); + int level = ml8_PrjLevel.equals("A")? 4 : (ml8_PrjLevel.equals("B")? 5 : 6); + cell.setCellValue(ml8_PrjLevel); + row = getRow(sheet, 5); + cell = getCell(row, col); + cell.setCellValue(schedule.getProperty("fnd0status"));//Ŀ״̬ + row = getRow(sheet, 6); + cell = getCell(row, col); + cell.setCellValue(schedule.getProperty("object_name")); + + boolean all = true; + Vector downs = new Vector<>();//TODO ĵ鵵ȫ + + for(int j=8; j<=rowCount; j++) { + row = getRow(sheet, j); + cell = getCell(row, col); + String name = getCell(row, 2).getStringCellValue(); + if(!map.containsKey(name)) { + String check = getCell(row, level).getStringCellValue(); + if(check.equals("Y")) { + cell.setCellValue("鵵Ҫ޸ΪN");// 20230227޸ +// all = false; + } + continue; + } + if(map.get(name).getProperty("ml8_FilingRequirements").equals("N")) { + cell.setCellValue("鵵Ҫ޸ΪN"); + continue; + } + if(map.get(name).getProperty("fnd0status").equals("ֹ")) { + cell.setCellValue(""); + all = false; + continue; + } + TCComponent[] deliveries = map.get(name).getReferenceListProperty("sch_task_deliverable_list"); + if(deliveries==null || deliveries.length==0) { + cell.setCellValue(""); + all = false; + continue; + } + TCComponent delivery = deliveries[0].getReferenceProperty("schedule_deliverable") + .getReferenceProperty("deliverable_inst"); +// TCComponent[] sch_task_deliverable_list = map.get(name).getReferenceListProperty("sch_task_deliverable_list"); +// for(TCComponent son : sch_task_deliverable_list) { +// TCComponent schedule_deliverable = son.getReferenceProperty("schedule_deliverable"); +// TCComponent taskDelivery = schedule_deliverable.getReferenceProperty("deliverable_inst"); +// if(taskDelivery == null) +// continue; +// TCComponent[] contents = taskDelivery.getReferenceListProperty("contents"); +// } +// System.out.println(name+""+delivery); + if(delivery==null) { + cell.setCellValue(""); + all = false; + }else { + Date released = delivery.getDateProperty("date_released"); + if(released==null) { + cell.setCellValue(""); + all = false; + }else { + cell.setCellValue(""); + downs.add(delivery); + } + } + } + if(document.isSelected() && all) { + for(int j=0; j<6; j++) { + row = getRow(sheet, j); + cell = getCell(row, col); + cell.setCellValue(""); + } + for(int j=9; j0) + MessageBox.post(desktop, fileErrors.toString(), "ERROR", MessageBox.ERROR); + else + MessageBox.post(desktop, "", "INFO", MessageBox.INFORMATION); + dispose(); + }catch(Exception e1) { + reporter.requestCanceling(); + e1.printStackTrace(); + MessageBox.post(TechProjectDocReportDialog.this, ""+e1.getMessage(), "ERROR", MessageBox.ERROR); + }finally { + if(input!=null) + try { + input.close(); + } catch (Exception e) { + e.printStackTrace(); + } + if(output!=null) + try { + output.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + }.start(); + } + }); + cancelBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + dispose(); + } + }); + } + + private XSSFRow getRow(XSSFSheet sheet, int i) throws Exception { + XSSFRow row = sheet.getRow(i); + if(row==null) + row = sheet.createRow(i); + return row; + } + private XSSFCell getCell(XSSFRow row, int col) throws Exception { + XSSFCell cell = row.getCell(col); + if(cell==null) + cell = row.createCell(col); + if(col>7) + cell.setCellStyle(getCell(row, 7).getCellStyle()); + return cell; + } + private HashMap getTasks(AIFComponentContext[] parent) throws Exception { +// AIFComponentContext[] children = parent.getChildren(); + HashMap tasks = new HashMap<>(); + for(AIFComponentContext c : parent) { + InterfaceAIFComponent comp = c.getComponent(); + if(!(comp instanceof TCComponentScheduleTask)) + continue; + TCComponentScheduleTask task = (TCComponentScheduleTask) comp; + if(task.getProperty("fnd0status").equals("ֹ") && task.getProperty("ml8_FilingRequirements").equals("N")) + //task.getStringProperty("fnd0status").equals("aborted") || + continue; + if(!task.getProperty("ml8_CutOrNot").isEmpty()) + continue; + AIFComponentContext[] children = task.getChildren("child_task_taglist"); + if(!task.getProperty("ml8_AssessmentNode").isEmpty()) { + nodes.put(task.getProperty("object_name"), task); + } + if(children.length==0) { + String name = task.getProperty("object_name"); + if(!tasks.containsKey(name)) { + tasks.put(name, task); + }else if(tasks.get(name).getProperty("fnd0status").equals("ֹ")) { + tasks.put(name, task); + } + }else { + HashMap map = getTasks(children); + if(map.size()>0) { + for(String s : map.keySet()) { + tasks.put(s, map.get(s)); + } + } + } + } + return tasks; + } + /*private String[] getStage(HashMap nodes) throws Exception { + String[] stages = new String[] { "(PDCP", "ADCP", "ת" }; + if(!nodes.containsKey(stages[0])) + return new String[] { "", "" }; + for(int i=0; i lovDisplayValueList = new Vector<>(); +// lovDisplayValueList.add(""); + Vector lovValueList = new Vector<>(); + LOVService lovService = LOVService.getService(session); + InitialLovData input = new InitialLovData(); + LovFilterData filter = new LovFilterData(); + filter.sortPropertyName = "object_name"; + filter.order = 1; + filter.numberToReturn = 100; + filter.maxResults = 100; + + input.lov = lov; + input.filterData = filter; + LOVSearchResults result = lovService.getInitialLOVValues(input); +// StringBuffer sb = new StringBuffer(); +// sb.append(">>"); + for (LOVValueRow row : result.lovValues) { + Map map = row.propDisplayValues; + Map realmap = row.propInternalValues; + for (String key : map.keySet()) { +// sb.append("UID:" + row.uid + ",key:" + key + "value:" + map.get(key)[0]); +// sb.append("\n"); + lovDisplayValueList.add(map.get(key)[0]); + lovValueList.add(realmap.get(key)[0]); + } + } +// System.out.println("StringBuffer:"+sb.toString()); + return lovDisplayValueList.toArray(new String[lovDisplayValueList.size()]); + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/report/TechProjectDocReportHandler.java b/src/com/connor/lidy/report/TechProjectDocReportHandler.java new file mode 100644 index 0000000..533ad19 --- /dev/null +++ b/src/com/connor/lidy/report/TechProjectDocReportHandler.java @@ -0,0 +1,43 @@ +package com.connor.lidy.report; + +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.AbstractAIFUIApplication; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +//ļнṹ +public class TechProjectDocReportHandler extends AbstractHandler implements IHandler{ + + public Object execute(ExecutionEvent arg0) throws ExecutionException { + System.out.println("TechProjectDocReportHandler"); + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + try { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + String pref = "ML8_TechProjectDocReport", title = "Ŀĵ鵵ϸ-"; + TCSession session = (TCSession) app.getSession(); + String options[] = session.getPreferenceService().getStringValues(pref); + if(options==null || options.length<2) { + MessageBox.post(desktop, "ѡ"+pref+"òȷ", "ERROR", MessageBox.ERROR); + return null; + } + TCComponent model = session.stringToComponent(options[0]);//A_OAAIm_5kSPsC + if(model==null || !model.isTypeOf("MSExcelX")) { + MessageBox.post(desktop, "ѡ"+pref+"ģUIDòȷ", "ERROR", MessageBox.ERROR); + return null; + } + new TechProjectDocReportDialog(session, title, options, (TCComponentDataset)model); + }catch(Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + } + return null; + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/report/UsedbyProductReportHandler.java b/src/com/connor/lidy/report/UsedbyProductReportHandler.java new file mode 100644 index 0000000..c6ccc2d --- /dev/null +++ b/src/com/connor/lidy/report/UsedbyProductReportHandler.java @@ -0,0 +1,56 @@ +package com.connor.lidy.report; + +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.AbstractAIFUIApplication; +import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +//ļнṹ +public class UsedbyProductReportHandler extends AbstractHandler implements IHandler{ + + public Object execute(ExecutionEvent arg0) throws ExecutionException { + System.out.println("UsedbyProductReportHandler"); + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + try { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + TCSession session = (TCSession) app.getSession(); + InterfaceAIFComponent target = app.getTargetComponent(); + if(target==null) { + MessageBox.post(desktop, "ѡԭϰ汾е", "ERROR", MessageBox.ERROR); + return null; + } + String type = target.getType(); + if(!type.equals("ML8_PartRevision") && !type.equals("ML8_RawMaterialRevision")) { + MessageBox.post(desktop, "ѡԭϰ汾е", "ERROR", MessageBox.ERROR); + return null; + } + String option = session.getPreferenceService().getStringValue("ML8_UsedbyProductReport"); + if(option==null || option.isEmpty()) { + MessageBox.post(desktop, "ѡML8_UsedbyProductReportòȷ", "ERROR", MessageBox.ERROR); + return null; + } + TCComponent model = session.stringToComponent(option);//AGFAAIXI5kSPsC + if(model==null || !model.isTypeOf("MSExcelX")) { + MessageBox.post(desktop, "ѡML8_UsedbyProductReportģUIDòȷ", "ERROR", MessageBox.ERROR); + return null; + } + UsedbyProductReportOperation operation = new UsedbyProductReportOperation(session, (TCComponentItemRevision)target, (TCComponentDataset)model); + session.queueOperation(operation); +// MessageBox.post(desktop, "ݽ", "ʾ", MessageBox.INFORMATION); + }catch(Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + } + return null; + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/report/UsedbyProductReportOperation.java b/src/com/connor/lidy/report/UsedbyProductReportOperation.java new file mode 100644 index 0000000..4c45823 --- /dev/null +++ b/src/com/connor/lidy/report/UsedbyProductReportOperation.java @@ -0,0 +1,191 @@ +package com.connor.lidy.report; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +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.lidy.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.TCComponentBOMWindow; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCComponentTcFile; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +public class UsedbyProductReportOperation extends AbstractAIFOperation { + + private TCSession session; + private TCComponentItemRevision target; + private List parents; + private TCComponentDataset model; + private XSSFRow sourceRow; + + public UsedbyProductReportOperation(TCSession session, TCComponentItemRevision target, TCComponentDataset model) { + this.session = session; + this.target = target; + this.model = model; + } + + @Override + public void executeOperation() throws Exception { + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + FileInputStream input = null; + FileOutputStream output = null; + try { + parents = new ArrayList<>(); + TCComponentItemRevision newRev = target.getItem().getLatestItemRevision(); + getParents(target); + Date now = new Date(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); + File directory = TCUtil.saveExcelChooser("ʹڻ嵥"+sdf.format(now)); + if(directory==null) + return; + if(directory.exists()) + directory.delete(); + String path = directory.getPath(); + + TCComponentTcFile[] files = model.getTcFiles(); + File file = files[0].getFile(System.getProperty("java.io.tmpdir")); + input = new FileInputStream(file); + XSSFWorkbook wb = new XSSFWorkbook(input); + + int i = 2; + XSSFSheet sheet = wb.getSheetAt(0); + XSSFRow row; + XSSFCell cell; + sourceRow = getRow(sheet, i); + for(TCComponent c : parents) { + String ID=String.valueOf(c.getProperty("item_id")); + if(ID.indexOf("-")>-1) { + System.out.println("ѹID=======>"+ID); + continue; + } + row = getRow(sheet, i); + cell = getCell(row, 0); + cell.setCellValue(i-1);// + cell = getCell(row, 1); + cell.setCellValue(c.getProperty("item_id"));//ϴ + cell = getCell(row, 2); + cell.setCellValue(c.getProperty("object_name"));//Ʒ + cell = getCell(row, 3); + cell.setCellValue(c.getProperty("object_desc"));// + cell = getCell(row, 4); + cell.setCellValue(c.getProperty("ML8_SalesMode"));//Ƿڶ + cell = getCell(row, 5); + cell.setCellValue(c.getProperty("item_revision_id"));//汾 + cell = getCell(row, 6); + TCComponentItemRevision parent = (TCComponentItemRevision)c; +// System.out.println(newRev+"=="+c.equals(newRev)+"=="+parents.contains(newRev)); + AIFComponentContext[] pfs = parent.getChildren("ML8_ProjectRelation"); + TCComponentBOMWindow window = TCUtil.getWindow(session); + TCComponentBOMLine line = TCUtil.getBOMLine(session, window, parent); + if(!target.equals(newRev)) { + cell.setCellValue("");//Ƿȡ + }else if(isUsed(line.getChildren(), target.getProperty("item_id"))) { + cell.setCellValue("");//Ƿȡ + }else { + cell.setCellValue("");//Ƿȡ + } + window.close(); + if(pfs!=null && pfs.length>0) { + TCComponent pf = (TCComponent) pfs[0].getComponent(); + cell = getCell(row, 7); + cell.setCellValue(pf.getProperty("ml8_ProductCode"));//Ʒ + cell = getCell(row, 8); + cell.setCellValue(pf.getProperty("ml8_ProductType"));//Ʒͺ + }else { + cell = getCell(row, 7); + cell.setCellValue("");//Ʒ + cell = getCell(row, 8); + cell.setCellValue("");//Ʒͺ + } + cell = getCell(row, 9); + cell.setCellValue(c.getProperty("ml8_NativeProducts"));//ԭƷ + cell = getCell(row, 10); + cell.setCellValue(c.getProperty("ml8_ProductCode"));//ʷƷ + cell = getCell(row, 11); + cell.setCellValue(c.getProperty("ml8_ProductType"));//ʷƷͺ + cell = getCell(row, 12); + cell.setCellValue(c.getProperty("release_status_list"));//Ʒ״̬ + + i++; + } + + output = new FileOutputStream(file.getPath()); + wb.write(output); + input.close(); + output.close(); +// System.out.println("file:"+file.getPath()); + String newPath = System.getProperty("java.io.tmpdir")+path.substring(path.lastIndexOf("\\")); + File reFile = new File(newPath); + file.renameTo(reFile); +// System.out.println("new directory:"+reFile.getPath()); + reFile.renameTo(directory); + + MessageBox.post(desktop, "", "INFO", MessageBox.INFORMATION); + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + }finally { + if(input!=null) + input.close(); + if(output!=null) + output.close(); + } + } + 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()>2) + cell.setCellStyle(getCell(sourceRow, col).getCellStyle()); + return cell; + } + private void getParents(TCComponent rev) throws Exception { + TCComponent[] ps = rev.whereUsed(TCComponent.WHERE_USED_ALL); + if(ps==null || ps.length==0){ + TCComponentItemRevision newRev = ((TCComponentItemRevision)rev).getItem().getLatestItemRevision(); + if(!rev.equals(target) && !parents.contains(newRev) && newRev.getProperty("item_id").startsWith("ML")) { + parents.add(newRev); + } + return; + } + for(TCComponent parent : ps) { + System.out.println(rev+">>"+parent); + getParents(parent); + } + } + private boolean isUsed(AIFComponentContext[] context, String id) throws Exception { + for(AIFComponentContext c : context) { + TCComponentBOMLine line = (TCComponentBOMLine)c.getComponent(); + if(line.getProperty("bl_item_item_id").equals(id)) + return true; + AIFComponentContext[] children = line.getChildren(); + if(children!=null && children.length>0) { + if(isUsed(children, id)) + return true; + } + } + return false; + } +} diff --git a/src/com/connor/lidy/task/ComparatorTask.java b/src/com/connor/lidy/task/ComparatorTask.java new file mode 100644 index 0000000..82d8ed4 --- /dev/null +++ b/src/com/connor/lidy/task/ComparatorTask.java @@ -0,0 +1,139 @@ +/* +#======================================================================================================= +# +# Copyright (c) 2007 Origin Enterprise Solution LTD. +# +#======================================================================================================= +# File description: ComparatorTask.java +#======================================================================================================= +# Date time Name Action Description of Change +# 2011-1-17 03:42:41 tyl Ini ʼļ +#======================================================================================================= + */ +package com.connor.lidy.task; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Comparator; +import java.util.Date; + +public class ComparatorTask implements Comparator { + private int count = 0; + + public int compare(Object obj1, Object obj2) { + // Object : id$$$processDate1$$$taskDate1$$$taskFinishDate1 + // id$$$processDate1$$$processName$$$previousTaskFinishDate1 + int returnvalue = 0; + if (obj1 instanceof String) { + String str1 = (String) obj1; + String str2 = (String) obj2; + if (str1.indexOf("$$$") > 0) { + count = 0; + getNum(str1); + if (count == 3) { + // String id1 = str1.substring(0, str1.indexOf("$$$")); + String sep1 = str1.substring(str1.indexOf("$$$") + 3); + String processDate1 = sep1.substring(0, sep1.indexOf("$$$")).trim(); + String processName1 = sep1.substring(sep1.indexOf("$$$") + 3, sep1.lastIndexOf("$$$")).trim(); + String taskCreateDate1 = sep1.substring(sep1.lastIndexOf("$$$") + 3).trim(); + + // String id2 = str2.substring(0, str2.indexOf("$$$")); + String sep2 = str2.substring(str2.indexOf("$$$") + 3); + String processDate2 = sep2.substring(0, sep2.indexOf("$$$")).trim(); + String processName2 = sep2.substring(sep2.indexOf("$$$") + 3, sep2.lastIndexOf("$$$")).trim(); + String taskCreateDate2 = sep2.substring(sep2.lastIndexOf("$$$") + 3).trim(); + + // ̴ʱ併ţϲʱ併 + returnvalue = (compareDate(processDate1, processDate2) == 0 ? (compareStr(processName1, processName2) == 0 ? (compareDate(taskCreateDate1, taskCreateDate2)) : compareStr(processName1, processName2)) : compareDate(processDate2, processDate1)); + } + } + } + return returnvalue; + } + + /** + * compareStrString + * @param @return 趨ļ + * @return String + * @throws + * @since CodingExampleVer 1.1 + */ + public int compareStr(String o1, String o2) { + String s1 = (String) o1; + String s2 = (String) o2; + if ((s1 == null) || (s1.length() == 0) || (s2 == null) || (s2.length() == 0)) { return 0; } + int len1 = s1.length(); + int len2 = s2.length(); + int n = Math.min(len1, len2); + char v1[] = s1.toCharArray(); + char v2[] = s2.toCharArray(); + int pos = 0; + while (n-- != 0) { + char c1 = v1[pos]; + char c2 = v2[pos]; + + if (c1 != c2) { return c1 - c2; } + pos++; + } + return len1 - len2; + } + + public int compareDate(String strDate1, String strDate2) { + SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date date1; + try { + date1 = simpleDate.parse(strDate1); + Date date2 = simpleDate.parse(strDate2); + if (date1.getTime() > date2.getTime()) { + return 1; + } else { + if (date1.getTime() == date2.getTime()) { + return 0; + } else { + return -1; + } + } + } + catch (ParseException e) { + e.printStackTrace(); + return 0; + } + } + + public static void main(String[] args) { + new ComparatorTask().compareDate("01-3-2011 11:17", "02-3-2011 11:17"); + } + + /** + * compareIntint + * @param @return 趨ļ + * @return String + * @throws + * @since CodingExampleVer 1.1 + */ + public int compareInt(Integer o1, Integer o2) { + int val1 = o1.intValue(); + int val2 = o2.intValue(); + return (val1 < val2 ? -1 : (val1 == val2 ? 0 : 1)); + } + + /** + * compareBooleanBoolean + * @param @return 趨ļ + * @return String + * @throws + * @since CodingExampleVer 1.1 + */ + public int compareBoolean(Boolean o1, Boolean o2) { + return (o1.equals(o2) ? 0 : (o1.booleanValue() == true ? 1 : -1)); + } + + private void getNum(String name) { + if (name.contains("$$$")) { + count++; + getNum(name.substring(name.indexOf("$$$") + 3)); + } else { + return; + } + } +} diff --git a/src/com/connor/lidy/task/CustAddReleaseHandler.java b/src/com/connor/lidy/task/CustAddReleaseHandler.java new file mode 100644 index 0000000..04d7bbf --- /dev/null +++ b/src/com/connor/lidy/task/CustAddReleaseHandler.java @@ -0,0 +1,73 @@ +/* +#======================================================================================================= +# +# Copyright (c) 2007 Origin Enterprise Solution LTD. +# +#======================================================================================================= +# File description: QueryTaskOpinionHandler.java +#======================================================================================================= +# Date time Name Action Description of Change +# +#======================================================================================================= +*/ +package com.connor.lidy.task; + +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.AbstractAIFUIApplication; +import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCAttachmentType; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentProcessType; +import com.teamcenter.rac.kernel.TCComponentTaskTemplate; +import com.teamcenter.rac.kernel.TCComponentTaskTemplateType; +import com.teamcenter.rac.kernel.TCPreferenceService; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +public class CustAddReleaseHandler extends AbstractHandler implements IHandler{ + + /* + * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent) + */ + @SuppressWarnings("deprecation") + public Object execute(ExecutionEvent arg0) throws ExecutionException { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + TCSession session = (TCSession) app.getSession(); + try { + TCPreferenceService preSer = session.getPreferenceService(); + String[] value = preSer.getStringArray(4, "Cust_Release_Templates"); + + if(value == null || value.length < 1){ + MessageBox.post("Cust_Release_Templatesòȷ,ϵԱ", "WARNING", 1); + return null; + } + + TCComponentProcessType procType = (TCComponentProcessType) session.getTypeComponent("Job"); + TCComponentTaskTemplateType taskTempType = (TCComponentTaskTemplateType) session.getTypeComponent("EPMTaskTemplate"); + TCComponentTaskTemplate taskTemp = taskTempType.find(value[0], TCComponentTaskTemplate.PROCESS_TEMPLATE_TYPE); + + InterfaceAIFComponent[] selectComps = app.getTargetComponents(); + if(selectComps.length > 0){ + int[] intArr = new int[selectComps.length]; + TCComponent[] comps = new TCComponent[selectComps.length]; + for (int i = 0; i < intArr.length; i++) { + intArr[i] = TCAttachmentType.TARGET; + comps[i] = (TCComponent) selectComps[i]; + } + procType.create("Զ", "״̬", taskTemp, comps, intArr, null); + MessageBox.post("״̬ɹ", "Info", 0); + }else{ + MessageBox.post("ѡִд˹,лл", "WARNING", 1); + } + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + +} diff --git a/src/com/connor/lidy/task/CustRemoveReleaseHandler.java b/src/com/connor/lidy/task/CustRemoveReleaseHandler.java new file mode 100644 index 0000000..2f51056 --- /dev/null +++ b/src/com/connor/lidy/task/CustRemoveReleaseHandler.java @@ -0,0 +1,73 @@ +/* +#======================================================================================================= +# +# Copyright (c) 2007 Origin Enterprise Solution LTD. +# +#======================================================================================================= +# File description: QueryTaskOpinionHandler.java +#======================================================================================================= +# Date time Name Action Description of Change +# 2011-1-17 10:18:54 tyl Ini ʼļ +#======================================================================================================= +*/ +package com.connor.lidy.task; + +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.AbstractAIFUIApplication; +import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCAttachmentType; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentProcessType; +import com.teamcenter.rac.kernel.TCComponentTaskTemplate; +import com.teamcenter.rac.kernel.TCComponentTaskTemplateType; +import com.teamcenter.rac.kernel.TCPreferenceService; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +public class CustRemoveReleaseHandler extends AbstractHandler implements IHandler{ + + /* + * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent) + */ + @SuppressWarnings("deprecation") + public Object execute(ExecutionEvent arg0) throws ExecutionException { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + TCSession session = (TCSession) app.getSession(); + try { + TCPreferenceService preSer = session.getPreferenceService(); + String[] value = preSer.getStringArray(4, "Cust_Release_Templates"); + + if(value == null || value.length < 2){ + MessageBox.post("Cust_Release_Templatesòȷ,ϵԱ", "WARNING", 1); + return null; + } + + TCComponentProcessType procType = (TCComponentProcessType) session.getTypeComponent("Job"); + TCComponentTaskTemplateType taskTempType = (TCComponentTaskTemplateType) session.getTypeComponent("EPMTaskTemplate"); + TCComponentTaskTemplate taskTemp = taskTempType.find(value[1], TCComponentTaskTemplate.PROCESS_TEMPLATE_TYPE); + + InterfaceAIFComponent[] selectComps = app.getTargetComponents(); + if(selectComps.length > 0){ + int[] intArr = new int[selectComps.length]; + TCComponent[] comps = new TCComponent[selectComps.length]; + for (int i = 0; i < intArr.length; i++) { + intArr[i] = TCAttachmentType.TARGET; + comps[i] = (TCComponent) selectComps[i]; + } + procType.create("Զ", "Ƴ״̬", taskTemp, comps, intArr, null); + MessageBox.post("Ƴ״̬ɹ", "Info", 0); + }else{ + MessageBox.post("ѡִд˹,лл", "WARNING", 1); + } + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + +} diff --git a/src/com/connor/lidy/task/ExportSearchResult.java b/src/com/connor/lidy/task/ExportSearchResult.java new file mode 100644 index 0000000..e73398c --- /dev/null +++ b/src/com/connor/lidy/task/ExportSearchResult.java @@ -0,0 +1,148 @@ +/* +#======================================================================================================= +# +# Copyright (c) 2007 Origin Enterprise Solution LTD. +# +#======================================================================================================= +# File description: ExportSearchResult.java +#======================================================================================================= +# Date time Name Action Description of Change +# 2011-1-17 03:43:41 tyl Ini ʼļ +#======================================================================================================= +*/ +package com.connor.lidy.task; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import jxl.Workbook; +import jxl.write.Label; +import jxl.write.WritableSheet; +import jxl.write.WritableWorkbook; +import com.connor.lidy.task.SearchResultDialog.SearchResults; +import com.teamcenter.rac.util.MessageBox; + +public class ExportSearchResult { + public ExportSearchResult(List tableInfos, PackExcelInfo excelInfo) { + createExcel(tableInfos, excelInfo); + } + + protected void createExcel(List tableInfos, PackExcelInfo excelInfo) { + Workbook workbook = null; + WritableSheet sourceSheet; + WritableWorkbook writeWorkbook; + File file = new File(excelInfo.getTemplateFileName()); + int listsize = tableInfos.size(); + int pageSize = excelInfo.getPageSize(); + List listTemp = new ArrayList(); + try { + workbook = Workbook.getWorkbook(file); + writeWorkbook = Workbook.createWorkbook(new File(excelInfo.getTargetFileName()), workbook); + sourceSheet = writeWorkbook.getSheet(0); + WritableSheet sheet = writeWorkbook.getSheet(0); + + String sourceSheetName = sourceSheet.getName(); + int page = listsize / pageSize; + if (((listsize % pageSize) > 0)) { + page = page + 1; + } + for (int i = 1; i <= page; i++) { + sheet = null; + listTemp = new ArrayList(); + writeWorkbook.copySheet(sourceSheetName, "" + i + "ҳ", i); + sheet = writeWorkbook.getSheet("" + i + "ҳ"); + for (int j = (i - 1) * pageSize; (j < pageSize * (i)) && ((j < listsize)); j++) { + listTemp.add(tableInfos.get(j)); + } + addDataToExcel(sourceSheet, sheet, listTemp, i, excelInfo); + } + writeWorkbook.removeSheet(0); + writeWorkbook.write(); + writeWorkbook.close(); + } catch (Exception e1) { + MessageBox.post(":ļǷʹ,ر", "Ϣʾ", MessageBox.INFORMATION); + e1.printStackTrace(); + } + } + + private void addDataToExcel(WritableSheet sourceSheet, WritableSheet sheet, List listTemp, int currentpage, PackExcelInfo excelInfo) { + int row = excelInfo.getInitRow(); + try { + for (row = 0; row < 34; row++) { + for (int col = 0; col < 15; col++) { + if (row >= 4) { + SearchResults result = (SearchResults) listTemp.get(row - 4); + if (result != null) { + if (col == 0) { + insertCell(sourceSheet, sheet, col, row, result.getIndex()); + } else if (col == 1) { + insertCell(sourceSheet, sheet, col, row, result.getTask_name()); + } else if (col == 2) { + insertCell(sourceSheet, sheet, col, row, result.getTask_executor()); + } else if (col == 3) { + insertCell(sourceSheet, sheet, col, row, result.getTask_createDate()); + } else if (col == 4) { + insertCell(sourceSheet, sheet, col, row, result.getTask_finishDate()); + } else if (col == 5) { + insertCell(sourceSheet, sheet, col, row, result.getTask_status()); + } else if (col == 6) { + insertCell(sourceSheet, sheet, col, row, result.getTask_note()); + } else if (col == 7) { + insertCell(sourceSheet, sheet, col, row, result.getTask_type()); + } else if (col == 8) { + insertCell(sourceSheet, sheet, col, row, result.getProcess_executor()); + } else if (col == 9) { + insertCell(sourceSheet, sheet, col, row, result.getProcess_name()); + } else if (col == 10) { + insertCell(sourceSheet, sheet, col, row, result.getProcess_createDate()); + } else if (col == 11) { + insertCell(sourceSheet, sheet, col, row, result.getProcess_finishDate()); + } else if (col == 12) { + insertCell(sourceSheet, sheet, col, row, result.getProcess_lastModeUser()); + } else if (col == 13) { + insertCell(sourceSheet, sheet, col, row, result.getProcess_status()); + } else if (col == 14) { + insertCell(sourceSheet, sheet, col, row, result.getProcess_templateName()); + } + } + } else { + if ((row == 0) && (col == 0)) { + insertCell(sourceSheet, sheet, col, row, excelInfo.getTitle()); + } else + insertCell(sourceSheet, sheet, col, row, ""); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + private void insertCell(WritableSheet sourceSheet, WritableSheet sheet, int col, int row, String value) { + try { + if ((value.trim().length() == 0) || (value == null)) { + Label lab = new Label(col, row, sourceSheet.getCell(col, row).getContents()); + if (lab != null) { + if (sourceSheet.getCell(col, row) != null) { + if (sourceSheet.getCell(col, row).getCellFormat() != null) { + lab.setCellFormat(sourceSheet.getCell(col, row).getCellFormat()); + } + } + sheet.addCell(lab); + } + } else { + Label lab = new Label(col, row, value); + if (lab != null) { + if (sourceSheet.getCell(col, row) != null) { + if (sourceSheet.getCell(col, row).getCellFormat() != null) { + lab.setCellFormat(sourceSheet.getCell(col, row).getCellFormat()); + } + } + sheet.addCell(lab); + } + } + } catch (Exception e) { + e.printStackTrace(); + } } + } \ No newline at end of file diff --git a/src/com/connor/lidy/task/PackExcelInfo.java b/src/com/connor/lidy/task/PackExcelInfo.java new file mode 100644 index 0000000..6e40e6c --- /dev/null +++ b/src/com/connor/lidy/task/PackExcelInfo.java @@ -0,0 +1,122 @@ +/* +#======================================================================================================= +# +# Copyright (c) 2007 Origin Enterprise Solution LTD. +# +#======================================================================================================= +# File description: PackExcelInfo.java +#======================================================================================================= +# Date time Name Action Description of Change +# 2011-1-17 03:45:50 tyl Ini ʼļ +#======================================================================================================= +*/ +package com.connor.lidy.task; + +public class PackExcelInfo { + private String templateFileName = "c:\\viewTaskTemplate.xls"; + private int pageSize = 30; + private String targetFileName = "c:\\report.xls"; + private int initRow = 0; + private int initColumn = 0; + private int secondePageSize = 0; + private String title = ""; + + /** + * @return the initRow + */ + public int getInitRow() { + return initRow; + } + + /** + * @param initRow the initRow to set + */ + public void setInitRow(int initRow) { + this.initRow = initRow; + } + + /** + * @return the title + */ + public String getTitle() { + return title; + } + + /** + * @param title the title to set + */ + public void setTitle(String title) { + this.title = title; + } + + /** + * @return the initColumn + */ + public int getInitColumn() { + return initColumn; + } + + /** + * @param initColumn the initColumn to set + */ + public void setInitColumn(int initColumn) { + this.initColumn = initColumn; + } + + /** + * @return the pageSize + */ + public int getPageSize() { + return pageSize; + } + + /** + * @param pageSize the pageSize to set + */ + public void setPageSize(int pageSize) { + this.pageSize = pageSize; + } + + /** + * @return the targetFileName + */ + public String getTargetFileName() { + return targetFileName; + } + + /** + * @param targetFileName the targetFileName to set + */ + public void setTargetFileName(String targetFileName) { + this.targetFileName = targetFileName; + } + + /** + * @return the templateFileName + */ + public String getTemplateFileName() { + return templateFileName; + } + + /** + * @param templateFileName the templateFileName to set + */ + public void setTemplateFileName(String templateFileName) { + this.templateFileName = templateFileName; + } + + /** + * @return the secondePageSize + */ + public int getSecondePageSize() { + return secondePageSize; + } + + /** + * @param secondePageSize the secondePageSize to set + */ + public void setSecondePageSize(int secondePageSize) { + this.secondePageSize = secondePageSize; + } + +} diff --git a/src/com/connor/lidy/task/QueryTaskOpinionCommand.java b/src/com/connor/lidy/task/QueryTaskOpinionCommand.java new file mode 100644 index 0000000..ab5b05f --- /dev/null +++ b/src/com/connor/lidy/task/QueryTaskOpinionCommand.java @@ -0,0 +1,40 @@ +/* +#======================================================================================================= +# +# Copyright (c) 2007 Origin Enterprise Solution LTD. +# +#======================================================================================================= +# File description: QueryTaskOpinionCommand.java +#======================================================================================================= +# Date time Name Action Description of Change +# 2011-1-17 10:19:09 tyl Ini ʼļ +#======================================================================================================= +*/ +package com.connor.lidy.task; + +import com.connor.lidy.util.ProgressReporterDialog; +import com.teamcenter.rac.aif.AbstractAIFCommand; +import com.teamcenter.rac.aif.AbstractAIFUIApplication; +import com.teamcenter.rac.kernel.TCException; + + +public class QueryTaskOpinionCommand extends AbstractAIFCommand { + + public AbstractAIFUIApplication application; + public QueryTaskOpinionCommand(AbstractAIFUIApplication abstractaifapplication) throws TCException { + application = abstractaifapplication; + execute(); + } + + private void execute() throws TCException { + ProgressReporterDialog reporter = new ProgressReporterDialog("ʾ"); + reporter.reportProgressMessage("ڵԺ..."); + new Thread(reporter).start(); + new Thread() { + public void run(){ + new QueryTaskOpinionOperation(application, reporter); + } + }.start(); + } + +} diff --git a/src/com/connor/lidy/task/QueryTaskOpinionHandler.java b/src/com/connor/lidy/task/QueryTaskOpinionHandler.java new file mode 100644 index 0000000..80a5d6e --- /dev/null +++ b/src/com/connor/lidy/task/QueryTaskOpinionHandler.java @@ -0,0 +1,41 @@ +/* +#======================================================================================================= +# +# Copyright (c) 2007 Origin Enterprise Solution LTD. +# +#======================================================================================================= +# File description: QueryTaskOpinionHandler.java +#======================================================================================================= +# Date time Name Action Description of Change +# 2011-1-17 10:18:54 tyl Ini ʼļ +#======================================================================================================= +*/ +package com.connor.lidy.task; + +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.AbstractAIFUIApplication; +import com.teamcenter.rac.aifrcp.AIFUtility; + +public class QueryTaskOpinionHandler extends AbstractHandler implements IHandler{ + + /* + * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent) + */ + public Object execute(ExecutionEvent arg0) throws ExecutionException { + System.out.println("QueryTaskOpinionHandler"); + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + try { + QueryTaskOpinionCommand command = new QueryTaskOpinionCommand(app); + command.executeModal(); + } + catch (Exception e) { + e.printStackTrace(); + } + return null; + } + +} diff --git a/src/com/connor/lidy/task/QueryTaskOpinionOperation.java b/src/com/connor/lidy/task/QueryTaskOpinionOperation.java new file mode 100644 index 0000000..c3b9a3d --- /dev/null +++ b/src/com/connor/lidy/task/QueryTaskOpinionOperation.java @@ -0,0 +1,1222 @@ +/* +#======================================================================================================= +# +# Copyright (c) 2007 Origin Enterprise Solution LTD. +# +#======================================================================================================= +# File description: QueryTaskOpinion.java +#======================================================================================================= +# Date time Name Action Description of Change +# 2011-1-17 10:29:16 tyl Ini ʼļ +# 2011-4-25 10:38:00 zyn ޸ ʾģʽ޸Ϊʾģʽ +# 2011-5-24 12:02:00 zyn add +#======================================================================================================= + */ +package com.connor.lidy.task; + +import java.io.BufferedReader; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.List; +import java.util.Vector; + +import javax.swing.JFrame; +import javax.swing.JScrollPane; + +import com.connor.lidy.task.util.QueryTaskOpinionTableHead; +import com.connor.lidy.util.ProgressReporterDialog; +import com.fnd0.services.internal.rac.auditmanager.ProcessHistoryManagementService; +import com.fnd0.services.internal.rac.auditmanager._2012_09.ProcessHistoryManagement.GetProcessHistoryAuditRecordsResponse; +import com.fnd0.services.internal.rac.auditmanager._2012_09.ProcessHistoryManagement.ProcessHistoryAuditRecordStruct; +import com.teamcenter.rac.aif.AIFDesktop; +import com.teamcenter.rac.aif.AbstractAIFUIApplication; +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.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentFnd0AuditLog; +import com.teamcenter.rac.kernel.TCComponentFolder; +import com.teamcenter.rac.kernel.TCComponentForm; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCComponentTask; +import com.teamcenter.rac.kernel.TCComponentUser; +import com.teamcenter.rac.kernel.TCException; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.kernel.UserList; +import com.teamcenter.rac.util.MessageBox; + +public class QueryTaskOpinionOperation { + private Vector taskNameVector; + private Vector vector_infor; + private String firstTaskName = ""; + private List RouteTaskList = new ArrayList(); + private List AcknowladgeTaskList = new ArrayList(); + private List reviewTaskList = new ArrayList(); + private List doTaskList = new ArrayList(); + private List conditionTaskList = new ArrayList(); + private List addStatusTaskList = new ArrayList(); + private List smallTitleList = new ArrayList(); + private Vector tableTitleVector; + private String[] doAndConditionTaskTitle = { "ִ", "ʱ", "ע" }; + private String[] firstTaskTitle = { "ִ", "ύʱ", "ע" }; + private String[] auditingTitle = { "ǩ", "ʱ", "ע" }; + private String[] notifyTitle = { "ǩ", "Ͽʱ", "ע" }; + +// private List rootProcessHistory; + private List processNames; + private ProgressReporterDialog reporter; + + public QueryTaskOpinionOperation(AbstractAIFUIApplication abstractaifuiapplication, ProgressReporterDialog reporter) { + this.myuiapp = abstractaifuiapplication; + session = (TCSession) this.myuiapp.getSession(); + this.reporter = reporter; + run(); + } + + //-----------------------------------------------------*-*- + public void readInfo(InterfaceAIFComponent ainterfaceaifcomponent) { + //InterfaceAIFComponent ainterfaceaifcomponent = myuiapp.getTargetComponent(); + if (ainterfaceaifcomponent != null) { + + ProcessHistoryManagementService processhistorymanagementservice = ProcessHistoryManagementService.getService(session); + GetProcessHistoryAuditRecordsResponse getprocesshistoryauditrecordsresponse = + processhistorymanagementservice.getProcssHistoryAuditRecords((TCComponent) ainterfaceaifcomponent); + ProcessHistoryAuditRecordStruct aprocesshistoryauditrecordstruct[] = getprocesshistoryauditrecordsresponse.rootProcessHistoryAuditRecords; + //----------------------------------------------------- +// rootProcessHistory = new ArrayList<>(); + processNames = new ArrayList<>(); + String as1[]; + int j = (as1 = getprocesshistoryauditrecordsresponse.processNames).length; + for(int i = 0; i < j; i++) + { + String s = as1[i]; + //System.out.println("s================"+s); + processNames.add(s); + } + loadProcessHistoryData(aprocesshistoryauditrecordstruct); +// loadProcessHistoryData(aprocesshistoryauditrecordstruct, rootProcessHistory); +// +// System.out.println("rootProcessHistory.size()="+rootProcessHistory.size()); +// TCComponent comp = ((BaseProcessHistoryEntry)rootProcessHistory.get(0)).getComponent(); +// String[] strNames = comp.getPropertyNames(); +// for(int i = 0; i < strNames.length; i++){ +// System.out.println("strNames["+i+"]="+strNames[i]); +// try { +// System.out.println(comp.getProperty(strNames[i])); +// } catch (TCException e) { +// // Auto-generated catch block +// e.printStackTrace(); +// } +// } + } + } + + private void loadProcessHistoryData(ProcessHistoryAuditRecordStruct aprocesshistoryauditrecordstruct[]) + { + ProcessHistoryAuditRecordStruct recordstruct[] = aprocesshistoryauditrecordstruct; +// int j = (aprocesshistoryauditrecordstruct1 = aprocesshistoryauditrecordstruct).length; + //System.out.println("j="+j); + String templateName = ""; + String taskType = ""; + String taskName = ""; + String startTime = ""; + String finishTime = ""; + String result = ""; + String pzUser = ""; + String comment = ""; + String eventType = ""; + boolean isNotFirstGobak = false; + + for(int i = 0; i < recordstruct.length; i++) + { +// BaseProcessHistoryEntry baseprocesshistoryentry = new BaseProcessHistoryEntry(); + if(recordstruct[i].auditRecord == null) + continue; + try { + if(recordstruct[i].auditRecord.getProperty("fnd0EventTypeName").equals("ɾ")){ + continue; + } + } catch (Exception e1) { + // Auto-generated catch block + e1.printStackTrace(); + } + ProcessHistoryAuditRecordStruct processhistoryauditrecordstruct = recordstruct[i]; + ProcessHistoryAuditRecordStruct aprocesshistoryauditrecordstruct2[] = processhistoryauditrecordstruct.childrenAuditRecords; + for(int k = 0; k < aprocesshistoryauditrecordstruct2.length; k++ ){ + int num = 1; + String taskevent = ""; + try { +// System.out.println("templateName:"+aprocesshistoryauditrecordstruct2[k].auditRecord.getProperty("fnd0EventTypeName")); + String s = aprocesshistoryauditrecordstruct2[k].auditRecord.getProperty("fnd0EventTypeName"); + if(s.equals("ֹ")) + taskevent = "ֹ"; + } catch (Exception e1) { + // Auto-generated catch block + e1.printStackTrace(); + } + ProcessHistoryAuditRecordStruct aprocesshistoryauditrecordstruct3[] = aprocesshistoryauditrecordstruct2[k].childrenAuditRecords; + for(int m = 0; m < aprocesshistoryauditrecordstruct3.length; m++){ + try { + result = aprocesshistoryauditrecordstruct3[m].auditRecord.getProperty("fnd0SignoffDecision"); + if(result.isEmpty()) + result = aprocesshistoryauditrecordstruct3[m].auditRecord.getProperty("task_result"); + taskName = aprocesshistoryauditrecordstruct3[m].auditRecord.getProperty("object_name"); + taskType = aprocesshistoryauditrecordstruct3[m].auditRecord.getProperty("object_type"); + eventType = aprocesshistoryauditrecordstruct3[m].auditRecord.getProperty("fnd0EventTypeName"); + if(taskType.equals("EPMOrTask") || eventType.equals("ָ")){//result.equals("Unset") + continue; + } + System.out.println("taskName:"+taskName+" eventType:"+eventType+" isNotFirstGobak:"+isNotFirstGobak); + //aprocesshistoryauditrecordstruct3[m].auditRecord.getUid() + if(num!=1){ + templateName = ""; +// System.out.println("templateName:"+templateName+" num:"+num); + }else{ + templateName = taskevent + aprocesshistoryauditrecordstruct2[k].auditRecord.getProperty("object_name"); +// System.out.println("templateName:"+templateName+" num:"+num); + num++; + } + if(eventType.equals("˻")){ + if(isNotFirstGobak){ + continue; + }else{ + isNotFirstGobak = true; + if(taskType.equals("EPMDoTask")){ + startTime = aprocesshistoryauditrecordstruct3[m].auditRecord.getProperty("fnd0StartDate"); + finishTime = aprocesshistoryauditrecordstruct3[m].auditRecord.getProperty("fnd0EndDate"); + //result = aprocesshistoryauditrecordstruct3[m].auditRecord.getProperty("task_result"); + comment = aprocesshistoryauditrecordstruct3[m].auditRecord.getProperty("fnd0Comments"); + SignInfo oneSignInfo = new SignInfo(); + oneSignInfo.processName = templateName; + oneSignInfo.num = num++; + oneSignInfo.taskName = taskName; + oneSignInfo.startTime = startTime; + oneSignInfo.finishTime = finishTime; + oneSignInfo.userAction = "Rejected"; + oneSignInfo.userComments = comment; + pzUser = aprocesshistoryauditrecordstruct3[m].auditRecord.getProperty("fnd0UserId"); + TCComponentUser tccomponentuser = UserList.getUser(session, "(" + pzUser + ")"); + if (tccomponentuser != null) { + pzUser = tccomponentuser.toString(); + oneSignInfo.userName = pzUser; + } + vector_infor.add(oneSignInfo); + }else{ + taskName = aprocesshistoryauditrecordstruct3[m].auditRecord.getProperty("object_name"); + getComment( aprocesshistoryauditrecordstruct3[m], templateName, taskName ); + } + } + }else{//else if(!eventType.equals("ʼ")) + isNotFirstGobak = false; + System.out.println("loadProcessHistoryData:taskName="+taskName+";taskType="+taskType);//TODO || taskType.equals("EPMConditionTask") + + if(taskType.equals("EPMDoTask") || taskType.equals("EPMAddStatusTask") || taskType.equals("EPMTask")){ + startTime = aprocesshistoryauditrecordstruct3[m].auditRecord.getProperty("fnd0StartDate"); + finishTime = aprocesshistoryauditrecordstruct3[m].auditRecord.getProperty("fnd0EndDate"); + comment = aprocesshistoryauditrecordstruct3[m].auditRecord.getProperty("fnd0Comments"); + SignInfo oneSignInfo = new SignInfo(); + oneSignInfo.processName = templateName; + oneSignInfo.num = num++; + oneSignInfo.taskName = taskName; + oneSignInfo.startTime = startTime; + oneSignInfo.finishTime = finishTime; + oneSignInfo.userAction = result; + oneSignInfo.userComments = comment; + pzUser = aprocesshistoryauditrecordstruct3[m].auditRecord.getProperty("fnd0UserId"); + TCComponentUser tccomponentuser = UserList.getUser(session, "(" + pzUser + ")"); + if (tccomponentuser != null) { + pzUser = tccomponentuser.toString(); + oneSignInfo.userName = pzUser; + } + vector_infor.add(oneSignInfo); + } +// else if(taskType.equals("EPMRouteTask")){ +// ProcessHistoryAuditRecordStruct aprocesshistoryauditrecordstruct4[] = aprocesshistoryauditrecordstruct3[m].childrenAuditRecords; +// if(aprocesshistoryauditrecordstruct4.length > 0){ +// taskName = aprocesshistoryauditrecordstruct3[m].auditRecord.getProperty("object_name"); +// getComment( aprocesshistoryauditrecordstruct4[aprocesshistoryauditrecordstruct4.length-1], templateName, taskName ); +// } +// } + else{ +// taskName = aprocesshistoryauditrecordstruct3[m].auditRecord.getProperty("object_name"); + getComment( aprocesshistoryauditrecordstruct3[m], templateName, taskName ); +// vector_infor.add(oneSignInfo); + } + } +// System.out.println("loadProcessHistoryData:taskName="+taskName+";user="+pzUser+";endTime="+startTime+";result="+result); + System.out.println("loadDatatemplateName="+templateName+";taskName="+taskName+";result="+result); + } catch (Exception e) { + // Auto-generated catch block + e.printStackTrace(); + } + } + } + } +// System.out.println("--------------------------------------------------------------"); + for (int i = 0; i < vector_infor.size(); i++) { + String taskName1 = ((SignInfo) vector_infor.elementAt(i)).taskName.trim(); + String userAction = ((SignInfo) vector_infor.elementAt(i)).userAction; + System.out.println("loadProcessHistoryData:taskName="+taskName1+";userAction="+userAction); + } +// System.out.println("--------------------------------------------------------------"); + } + + private String getComment( ProcessHistoryAuditRecordStruct aprocesshistoryauditrecordstruct, String templateName, String taskName ){ + + String pzUser = ""; + int cnt = 0; +// String taskName = ""; +// try { +// taskName = aprocesshistoryauditrecordstruct.auditRecord.getProperty("object_name"); +// } catch (TCException e1) { +// // Auto-generated catch block +// e1.printStackTrace(); +// } + ProcessHistoryAuditRecordStruct auditrecordstruct1[] = aprocesshistoryauditrecordstruct.childrenAuditRecords; + System.out.println("getComment:"+auditrecordstruct1.length); + if(auditrecordstruct1!=null && auditrecordstruct1.length>1){ + try { + TCComponentFnd0AuditLog auditRecord = auditrecordstruct1[auditrecordstruct1.length - 1].auditRecord; + if(auditRecord.getProperty("fnd0EventTypeName").equals("")){ +// SignInfo oneSignInfo = new SignInfo(); +// oneSignInfo.actionTime = auditRecord.getProperty("fnd0StartDate"); +// oneSignInfo.userAction = auditRecord.getProperty("fnd0EventTypeName"); +// oneSignInfo.userComments = auditRecord.getProperty("fnd0Comments"); +// oneSignInfo.processName = templateName; +// oneSignInfo.taskName = taskName; +// pzUser = auditRecord.getProperty("fnd0UserId"); +// TCComponentUser tccomponentuser = UserList.getUser(session, "(" + pzUser + ")"); +// if (tccomponentuser != null) { +// pzUser = tccomponentuser.toString(); +// oneSignInfo.userName = pzUser; +// } +// System.out.println("getCommenttaskName="+taskName+";user="+pzUser+";endTime="+oneSignInfo.actionTime+";result="+oneSignInfo.userAction ); +// vector_infor.add(oneSignInfo); + auditRecord = aprocesshistoryauditrecordstruct.auditRecord; + TCComponent[] valid_signoffs = auditRecord.getReferenceProperty("fnd0Object").getReferenceListProperty("valid_signoffs"); + for(int ix = 0; ix < valid_signoffs.length; ix++ ){ + SignInfo oneSignInfo = new SignInfo(); + oneSignInfo.startTime = valid_signoffs[ix].getProperty("decision_date"); + oneSignInfo.finishTime = oneSignInfo.startTime; + oneSignInfo.userAction = valid_signoffs[ix].getProperty("decision"); + if(oneSignInfo.userAction.endsWith("89")){ + oneSignInfo.userAction = "Ͽ"; + } + oneSignInfo.userComments = valid_signoffs[ix].getProperty("comments"); + oneSignInfo.processName = templateName; + oneSignInfo.taskName = taskName; + oneSignInfo.userName = valid_signoffs[ix].getProperty("fnd0Assignee"); + System.out.println("getCommenttaskName="+taskName+";user="+pzUser+";endTime="+oneSignInfo.finishTime+";result="+oneSignInfo.userAction ); + vector_infor.add(oneSignInfo); + } + }else{ + ProcessHistoryAuditRecordStruct[] auditrecordstruct2 = auditrecordstruct1[auditrecordstruct1.length - 1].childrenAuditRecords; + if(auditrecordstruct2==null || auditrecordstruct2.length==0) + auditrecordstruct2 = auditrecordstruct1[auditrecordstruct1.length - 2].childrenAuditRecords; + for(cnt = 0; cnt < auditrecordstruct2.length; cnt++){ + SignInfo oneSignInfo = new SignInfo(); + + oneSignInfo.startTime = auditrecordstruct2[cnt].auditRecord.getProperty("fnd0StartDate"); +// oneSignInfo.finishTime = aprocesshistoryauditrecordstruct2[cnt].auditRecord.getProperty("fnd0EndDate"); + oneSignInfo.finishTime = auditRecord.getProperty("fnd0LoggedDate");//fnd0EndDate + oneSignInfo.userAction = auditrecordstruct2[cnt].auditRecord.getProperty("fnd0EventTypeName"); + oneSignInfo.userComments = auditrecordstruct2[cnt].auditRecord.getProperty("fnd0Comments"); + oneSignInfo.processName = templateName; + oneSignInfo.taskName = taskName; + pzUser = auditrecordstruct2[cnt].auditRecord.getProperty("fnd0UserId"); + TCComponentUser tccomponentuser = UserList.getUser(session, "(" + pzUser + ")"); + if (tccomponentuser != null) { + pzUser = tccomponentuser.toString(); + oneSignInfo.userName = pzUser; + } + System.out.println("getCommenttaskName="+taskName+";user="+pzUser+";endTime="+oneSignInfo.finishTime+";result="+oneSignInfo.userAction ); + vector_infor.add(oneSignInfo); + } + } + } catch (Exception e) { + // Auto-generated catch block + e.printStackTrace(); + } + } +// else{ +// try { +// comment = aprocesshistoryauditrecordstruct.auditRecord.getProperty("fnd0Comments"); +// } catch (TCException e) { +// // Auto-generated catch block +// e.printStackTrace(); +// } +// } + return ""; + } +// private void loadProcessHistoryData(ProcessHistoryAuditRecordStruct aprocesshistoryauditrecordstruct[], List list) +// { +// com.fnd0.services.internal.rac.auditmanager._2012_09.ProcessHistoryManagement.ProcessHistoryAuditRecordStruct aprocesshistoryauditrecordstruct1[]; +// int j = (aprocesshistoryauditrecordstruct1 = aprocesshistoryauditrecordstruct).length; +// System.out.println("j="+j); +// for(int i = 0; i < j; i++) +// { +// ProcessHistoryAuditRecordStruct processhistoryauditrecordstruct = aprocesshistoryauditrecordstruct1[i]; +// BaseProcessHistoryEntry baseprocesshistoryentry = new BaseProcessHistoryEntry(); +// if(processhistoryauditrecordstruct.auditRecord != null) +// { +// try { +// System.out.println("1----"+processhistoryauditrecordstruct.auditRecord.getProperty("object_name")); +// } catch (TCException e) { +// // Auto-generated catch block +// e.printStackTrace(); +// } +// baseprocesshistoryentry.setComponent(processhistoryauditrecordstruct.auditRecord); +// list.add(baseprocesshistoryentry); +// ArrayList arraylist = new ArrayList(); +// com.teamcenter.rac.kernel.TCComponentFnd0SecondaryAudit atccomponentfnd0secondaryaudit[] = processhistoryauditrecordstruct.secondaryAuditRecords; +// com.teamcenter.rac.kernel.TCComponentFnd0SecondaryAudit atccomponentfnd0secondaryaudit1[]; +// int l = (atccomponentfnd0secondaryaudit1 = atccomponentfnd0secondaryaudit).length; +// for(int k = 0; k < l; k++) +// { +// com.teamcenter.rac.kernel.TCComponentFnd0SecondaryAudit tccomponentfnd0secondaryaudit = atccomponentfnd0secondaryaudit1[k]; +// baseprocesshistoryentry = new BaseProcessHistoryEntry(); +// baseprocesshistoryentry.setComponent(tccomponentfnd0secondaryaudit); +// arraylist.add(baseprocesshistoryentry); +// try { +// System.out.println("2----"+tccomponentfnd0secondaryaudit.getProperty("object_name")); +// } catch (TCException e) { +// // Auto-generated catch block +// e.printStackTrace(); +// } +// } +// +// ProcessHistoryAuditRecordStruct aprocesshistoryauditrecordstruct2[] = processhistoryauditrecordstruct.childrenAuditRecords; +// loadProcessHistoryData(aprocesshistoryauditrecordstruct2, ((List) (arraylist))); +// baseprocesshistoryentry.setChildEntries(arraylist); +// } +// } +// +// } + + public void run() { + AIFDesktop desktop = myuiapp.getDesktop(); + try { + InterfaceAIFComponent ainterfaceaifcomponent[] = myuiapp.getTargetComponents(); + if (ainterfaceaifcomponent==null || ainterfaceaifcomponent.length==0) { + reporter.requestCanceling(); + MessageBox.post(desktop, "ѡҪ鿴̼¼Ķ", "ʾ", MessageBox.WARNING); + return; + } + if (ainterfaceaifcomponent.length > 1) { + reporter.requestCanceling(); + MessageBox.post(desktop, "ֻѡһв鿴", "ʾ", MessageBox.WARNING); + return; + } + if ((ainterfaceaifcomponent[0] instanceof TCComponentItemRevision) || (ainterfaceaifcomponent[0] instanceof TCComponentTask) || + (ainterfaceaifcomponent[0] instanceof TCComponentDataset) || (ainterfaceaifcomponent[0] instanceof TCComponentForm) + || (ainterfaceaifcomponent[0] instanceof TCComponentFolder)) { + // ֻԣ TCComponentItemRevision, TCComponentTask, + // TCComponentDataset, TCComponentForm ⼸ + } else { + reporter.requestCanceling(); + MessageBox.post(desktop, "ѡȷ͵Ķ", "ʾ", MessageBox.WARNING); + return; + } + if (ainterfaceaifcomponent[0] instanceof TCComponentTask) { + viewWfInfo(ainterfaceaifcomponent[0]); + } else { + TCComponent com = (TCComponent) ainterfaceaifcomponent[0]; + AIFComponentContext[] aif = com.whereReferenced(); + if (aif==null || aif.length == 0) { + reporter.requestCanceling(); + MessageBox.post(desktop, "ǰ", "ʾ", MessageBox.WARNING); + } + List listProcess = new ArrayList(); + for (int j = 0; j < aif.length; j++) { + TCComponent tccomponent = (TCComponent) aif[j].getComponent(); + if (tccomponent instanceof TCComponentTask) { +// System.out.println("----"); + System.out.println("listProcessobject_name="+((TCComponentTask) tccomponent).getProperty("object_name")); + listProcess.add((TCComponentTask) tccomponent); + } + } + if(listProcess.size()>0){ + viewWfInfo(listProcess, ainterfaceaifcomponent[0]); + }else{ + reporter.requestCanceling(); + MessageBox.post(desktop, "ǰ", "ʾ", MessageBox.WARNING); + } + } + } catch (Exception exception) { + reporter.requestCanceling(); + MessageBox.post(desktop, ""+exception.getMessage(), "ʾ", MessageBox.WARNING); + exception.printStackTrace(); + } + } + + public void viewWfInfo(List listProcess, InterfaceAIFComponent ainterfaceaifcomponent) { + System.out.println("viewWfInfo(List listProcess)...........viewWfInfo"); + taskNameVector = new Vector(); + smallTitleList = new ArrayList(); + tableTitleVector = new Vector(); + Vector fileNameVector = new Vector(); + for(int j=0; j vector_infor = readerFromText(fileNameVector); + vector_infor = new Vector(); + vector_infor = readerFromText(fileNameVector); + readInfo( ainterfaceaifcomponent ); +// System.out.println("--------------------------------------------------------------"); + for (int i = 0; i < vector_infor.size(); i++) { + String taskName = ((SignInfo) vector_infor.elementAt(i)).taskName.trim(); + String userAction = ((SignInfo) vector_infor.elementAt(i)).userAction; + System.out.println("viewWfInfo:taskName="+taskName+";userAction="+userAction); + } +// System.out.println("--------------------------------------------------------------"); + Object[][] objData = null; + objData = getDataAuditing(vector_infor, taskNameVector); + QueryTaskOpinionTableHead tableHeadTestPanel = new QueryTaskOpinionTableHead(); + tableHeadTestPanel.setAutoscrolls(true); + //tableHeadTestPanel.settitleArray(smallTitleList); + //ʾģʽ 2011.4.22 + tableHeadTestPanel.setobjArray(objData); + tableHeadTestPanel.setTableHeadTestModel(tableTitleVector); + tableHeadTestPanel.initColumnSizes(); + String processName = null, processCreator = null, processCreateDate = null; + try { + processName = listProcess.get(0).getRoot().getProperty("job_name"); + processCreator = listProcess.get(0).getRoot().getProperty("owning_user"); + processCreateDate = listProcess.get(0).getRoot().getProperty("creation_date"); + } catch (Exception e) { + e.printStackTrace(); + }// ̴ʱ + JFrame frame = new JFrame("" + processName + " ̴:" + processCreator + " ̴ʱ:" + processCreateDate); + tableHeadTestPanel.setOpaque(true); // content panes + JScrollPane scrollPane = new JScrollPane(tableHeadTestPanel); + scrollPane.setAutoscrolls(true); + frame.setContentPane(scrollPane); + frame.pack(); + frame.setLocation(200, 100); + + reporter.requestCanceling(); + frame.setVisible(true); + } + + public void viewWfInfo(InterfaceAIFComponent interfaceaifcomponent_top) { + System.out.println("viewWfInfo(InterfaceAIFComponent interfaceaifcomponent_top)...........viewWfInfo"); +// if (interfaceaifcomponent_top instanceof TCComponentTask) { +// } else { +// MessageBox.post("ѡĶ󲻶ԣѡ", "ʾ", MessageBox.INFORMATION); +// } + TCComponentTask tccomponenttask = (TCComponentTask) interfaceaifcomponent_top; + taskNameVector = new Vector(); + smallTitleList = new ArrayList(); + tableTitleVector = new Vector(); + try { + TCComponentTask tccomponent_root_task = tccomponenttask.getRoot(); +// AIFComponentContext[] aif = tccomponent_root_task.getChildren();//remove by -*-*- + AIFComponentContext[] aif = tccomponent_root_task.getChildren("child_tasks"); + for (int i = 0; i < aif.length; i++) { + if (aif[i].getComponent() instanceof TCComponentTask) { + TCComponentTask task = (TCComponentTask) aif[i].getComponent(); + if (task.getPrevious() == null) { + firstTaskName = task.toString(); + taskNameVector.add(firstTaskName); + break; + } + } + } + getNextTask(aif); + + String stringInformation = tccomponenttask.getAuditInfo(true);// ˺ֵϵͳúõֵ + + String fileName = System.getenv("temp")+"\\.txt"; + // ѻõϢдһıļ + writeToText(fileName, stringInformation); + // ȡijһıļϢ +// Vector vector_infor = readerFromText(fileName); + vector_infor = new Vector(); + vector_infor = readerFromText(fileName); + readInfo( tccomponenttask ); + Object[][] objData = null; + objData = getDataAuditing(vector_infor, taskNameVector); + QueryTaskOpinionTableHead tableHeadTestPanel = new QueryTaskOpinionTableHead(); + tableHeadTestPanel.setAutoscrolls(true); + //tableHeadTestPanel.settitleArray(smallTitleList); + //ʾģʽ 2011.4.22 + tableHeadTestPanel.setobjArray(objData); + tableHeadTestPanel.setTableHeadTestModel(tableTitleVector); + tableHeadTestPanel.initColumnSizes(); + String processName = tccomponenttask.getProperty("job_name");// + String processCreator = tccomponenttask.getProperty("owning_user");// ̴ + String processCreateDate = tccomponenttask.getProperty("creation_date");// ̴ʱ + JFrame frame = new JFrame("" + processName + " ̴:" + processCreator + " ̴ʱ:" + processCreateDate); + tableHeadTestPanel.setOpaque(true); // content panes + JScrollPane scrollPane = new JScrollPane(tableHeadTestPanel); + scrollPane.setAutoscrolls(true); + frame.setContentPane(scrollPane); + frame.pack(); + frame.setLocation(200, 100); + + reporter.requestCanceling(); + frame.setVisible(true); + } catch (Exception e2) { + reporter.requestCanceling(); + MessageBox.post(myuiapp.getDesktop(), ""+e2.getMessage(), "ʾ", MessageBox.WARNING); + e2.printStackTrace(); + } + } + + /* + * ˳αӦ"" + */ + public void getNextTask(AIFComponentContext[] aif) { + for (int i = 0; i < aif.length; i++) { + InterfaceAIFComponent interfaceaifcomponent = aif[i].getComponent(); + //System.out.println("interfaceaifcomponent.getType()"+interfaceaifcomponent.getType()); + if (interfaceaifcomponent instanceof TCComponentTask) { + //System.out.println("---------------getNextTask------------------"); + if (interfaceaifcomponent.getType().equals("EPMAcknowledgeTask")) { + AcknowladgeTaskList.add(interfaceaifcomponent.toString()); + if (!taskNameVector.contains(interfaceaifcomponent.toString())) { + taskNameVector.addElement(interfaceaifcomponent.toString()); + } + } + if (interfaceaifcomponent.getType().equals("EPMReviewTask")) { + reviewTaskList.add(interfaceaifcomponent.toString()); + if (!taskNameVector.contains(interfaceaifcomponent.toString())) { + taskNameVector.addElement(interfaceaifcomponent.toString()); + } + } + if (interfaceaifcomponent.getType().equals("EPMDoTask")) { + doTaskList.add(interfaceaifcomponent.toString()); + if (!taskNameVector.contains(interfaceaifcomponent.toString())) { + taskNameVector.addElement(interfaceaifcomponent.toString()); + } + } + if (interfaceaifcomponent.getType().equals("EPMConditionTask")) { + conditionTaskList.add(interfaceaifcomponent.toString()); + if (!taskNameVector.contains(interfaceaifcomponent.toString())) { + taskNameVector.addElement(interfaceaifcomponent.toString()); + } + } + if (interfaceaifcomponent.getType().equals("EPMAddStatusTask")) { + addStatusTaskList.add(interfaceaifcomponent.toString()); + if (!taskNameVector.contains(interfaceaifcomponent.toString())) { + taskNameVector.addElement(interfaceaifcomponent.toString()); + } + } + if (interfaceaifcomponent.getType().equals("EPMRouteTask")) { + RouteTaskList.add(interfaceaifcomponent.toString()); + if (!taskNameVector.contains(interfaceaifcomponent.toString())) { + taskNameVector.addElement(interfaceaifcomponent.toString()); + } + } + if (interfaceaifcomponent.getType().equals("EPMTask")) { + conditionTaskList.add(interfaceaifcomponent.toString()); + if (!taskNameVector.contains(interfaceaifcomponent.toString())) { + taskNameVector.addElement(interfaceaifcomponent.toString()); + } + } + } + } + } + + /* + * TODO + */ + public Object[][] getDataAuditing(Vector vector_infor, Vector taskNameVector1) { + // System.out.println("taskNameVector.............." + taskNameVector); + // System.out.println("vector_infor.............." + + // vector_infor.size()); + int columWidth = 0; + if (vector_infor != null) { + columWidth = 6 + 1; + } + + Object[][] objData = new Object[vector_infor.size() + 1][columWidth]; + if (vector_infor.size() == 0) { + objData = new Object[vector_infor.size() + 1][columWidth]; + tableTitleVector.add(firstTaskName + "()"); + for (int j = 0; j < firstTaskTitle.length; j++) { + smallTitleList.add(firstTaskTitle[j]); + } + } + // +// int countNum = 0; + if (vector_infor==null || vector_infor.size()==0) + return objData; + + boolean isRefused = false; + String taskName = ""; + String userAction = ""; + for (int i = 0; i < vector_infor.size(); i++) { + SignInfo info = (SignInfo) vector_infor.elementAt(i); + taskName = info.taskName.trim(); + userAction = info.userAction; + System.out.println("getDataAuditing:taskName="+taskName+";userAction="+userAction); + //if (taskNameVector.contains(taskName)) { + if (userAction.equals("Completed") || userAction.equalsIgnoreCase("true") || userAction.equalsIgnoreCase("false")||userAction.equals("")) { + //userAction.equals("") + if (taskName.equals(firstTaskName.trim())) { + if (!tableTitleVector.contains(firstTaskName + "()")) { + tableTitleVector.add(firstTaskName + "()"); + for (int j = 0; j < firstTaskTitle.length; j++) { + smallTitleList.add(firstTaskTitle[j]); + } + } + isRefused = false; + objData[i][0] = info.processName; + objData[i][1] = info.taskName; + if(userAction.equals("Completed")) + objData[i][2] = ""; + else if(userAction.equalsIgnoreCase("true")) + objData[i][2] = ""; + else if(userAction.equalsIgnoreCase("false")) + objData[i][2] = ""; + objData[i][3] = info.userName; + objData[i][4] = info.startTime; + objData[i][5] = info.finishTime; + objData[i][6] = info.userComments; + } else { + if (doTaskList.contains(taskName) || conditionTaskList.contains(taskName) || addStatusTaskList.contains(taskName)) { + int col = 0; + if (doTaskList.contains(taskName)) { + if (!tableTitleVector.contains("DOTask" + taskName)) { + tableTitleVector.add("DOTask" + taskName); + for (int j = 0; j < doAndConditionTaskTitle.length; j++) { + smallTitleList.add(doAndConditionTaskTitle[j]); + } + } + col = tableTitleVector.indexOf("DOTask" + taskName); + } else if (conditionTaskList.contains(taskName)) { + if (!tableTitleVector.contains("ConditionTask" + taskName)) { + tableTitleVector.add("ConditionTask"+ taskName); + for (int j = 0; j < doAndConditionTaskTitle.length; j++) { + smallTitleList.add(doAndConditionTaskTitle[j]); + } + } + col = tableTitleVector.indexOf("ConditionTask" + taskName); + } else if (addStatusTaskList.contains(taskName)) { + if (!tableTitleVector.contains("AddStatusTask" + taskName)) { + tableTitleVector.add("AddStatusTask"+ taskName); + for (int j = 0; j < doAndConditionTaskTitle.length; j++) { + smallTitleList.add(doAndConditionTaskTitle[j]); + } + } + col = tableTitleVector.indexOf("AddStatusTask" + taskName); + } + if (isRefused) { + for (int m = col + 1; m < columWidth; m++) { + objData[i][m] = ""; + } + } + + isRefused = false; + objData[i][0] = info.processName; + objData[i][1] = info.taskName; + if(userAction.equals("Completed")) + objData[i][2] = ""; + else if(userAction.equalsIgnoreCase("true")) + objData[i][2] = ""; + else if(userAction.equalsIgnoreCase("false")) + objData[i][2] = ""; + objData[i][3] = info.userName; + objData[i][4] = info.startTime; + objData[i][5] = info.finishTime; + objData[i][6] = info.userComments; + } + } + } else if (userAction.equals("Rejected") || userAction.equals("ܾ")) {//userAction.equals("ܾ") + if (reviewTaskList.contains(taskName) || AcknowladgeTaskList.contains(taskName)) { + if (!tableTitleVector.contains(taskName)) { + tableTitleVector.add(taskName); + for (int j = 0; j < auditingTitle.length; j++) { + smallTitleList.add(auditingTitle[j]); + } + } else { + if (AcknowladgeTaskList.contains(taskName)) { + tableTitleVector.add(taskName); + for (int j = 0; j < notifyTitle.length; j++) { + smallTitleList.add(notifyTitle[j]); + } + } + } +// int col = tableTitleVector.indexOf(taskName); + objData[i][0] = info.processName; + objData[i][1] = info.taskName; + //objData[i][2] = info.userAction; + objData[i][2] = "ܾ"; + objData[i][3] = info.userName; + objData[i][4] = info.startTime; + objData[i][5] = info.finishTime; + objData[i][6] = info.userComments; +// ++countNum; + isRefused = true; + } + } else if (userAction.equals("Approved") || userAction.equals("׼") || userAction.equals("Ͽ")) { + //(userAction.equals("׼")) || (userAction.equals("Ͽ")) + if (reviewTaskList.contains(taskName) || AcknowladgeTaskList.contains(taskName) || RouteTaskList.contains(taskName)) { + if (!tableTitleVector.contains(taskName)) { + if (reviewTaskList.contains(taskName)) { + tableTitleVector.add(taskName); + for (int j = 0; j < auditingTitle.length; j++) { + smallTitleList.add(auditingTitle[j]); + } + } else { + if (AcknowladgeTaskList.contains(taskName)) { + tableTitleVector.add(taskName); + for (int j = 0; j < notifyTitle.length; j++) { + smallTitleList.add(notifyTitle[j]); + } + } + } + } + int col = tableTitleVector.indexOf(taskName); + // ĿģǾܾģк + if (isRefused) { + // ĿģǾܾģк + for (int m = col + 1; m < columWidth; m++) { + objData[i][m] = ""; + } + } + isRefused = false; + objData[i][0] = info.processName; + objData[i][1] = info.taskName; + //objData[i][2] = info.userAction; + objData[i][2] = "׼"; + objData[i][3] = info.userName; + objData[i][4] = info.startTime; + objData[i][5] = info.finishTime; + objData[i][6] = info.userComments; + } + }else if(userAction.equals("") || userAction.equals("skipped")){ + if (AcknowladgeTaskList.contains(taskName)) { + if (!tableTitleVector.contains(taskName)) { + if (reviewTaskList.contains(taskName)) { + tableTitleVector.add(taskName); + for (int j = 0; j < auditingTitle.length; j++) { + smallTitleList.add(auditingTitle[j]); + } + } else { + if (AcknowladgeTaskList.contains(taskName)) { + tableTitleVector.add(taskName); + for (int j = 0; j < notifyTitle.length; j++) { + smallTitleList.add(notifyTitle[j]); + } + } + } + } + int col = tableTitleVector.indexOf(taskName); + // ĿģǾܾģк + if (isRefused) { + // ĿģǾܾģк + for (int m = col + 1; m < columWidth; m++) { + objData[i][m] = ""; + } + } + isRefused = false; + objData[i][0] = info.processName; + objData[i][1] = info.taskName; + //objData[i][2] = info.userAction; + objData[i][2] = ""; + objData[i][3] = info.userName; + objData[i][4] = info.startTime; + objData[i][5] = info.finishTime; + objData[i][6] = info.userComments; + } + }else{//add by -*-*- + if (!tableTitleVector.contains(taskName)) { + if (reviewTaskList.contains(taskName)) { + tableTitleVector.add(taskName); + for (int j = 0; j < auditingTitle.length; j++) { + smallTitleList.add(auditingTitle[j]); + } + } else { + if (AcknowladgeTaskList.contains(taskName)) { + tableTitleVector.add(taskName); + for (int j = 0; j < notifyTitle.length; j++) { + smallTitleList.add(notifyTitle[j]); + } + } + } + } + int col = tableTitleVector.indexOf(taskName); + // ĿģǾܾģк + if (isRefused) { + // ĿģǾܾģк + for (int m = col + 1; m < columWidth; m++) { + objData[i][m] = ""; + } + } + isRefused = false; + objData[i][0] = info.processName; + objData[i][1] = info.taskName; + objData[i][2] = info.userAction; + //objData[i][2] = "ʼ"; + objData[i][3] = info.userName; + objData[i][4] = info.startTime; + objData[i][5] = info.finishTime; + objData[i][6] = info.userComments; + } + //} + } + + return objData; + } + + /** + * ַдһıļ(writeToText) *************̴ + */ + public void writeToText(String fileName, String stringInformation) { + PrintWriter pw; + try { + pw = new PrintWriter(new FileWriter(fileName)); + pw.println(stringInformation); + pw.close(); + } + catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * һıļȡϢ(readerFromText) *************̴ + */ + public Vector readerFromText(String fileName) { + System.out.println("readerFromText(String) - start"); //$NON-NLS-1$ + BufferedReader br = null; + Vector vs = new Vector(); + try { + int num = 1; + br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName))); + String strLine = null; + String processName = ""; + while ((strLine = br.readLine()) != null) { + if((strLine.startsWith("ģ"))){ + System.out.println("strLine=="+strLine); + String [] temps = strLine.split(" "); + int y=0; + System.out.println(" temps.length=="+ temps.length); + for (int i = 0; i < temps.length; i++) { + if (temps[i].trim().length() != 0) { + ++y; + if (y == 2) { + processName = temps[i].trim();// + } + } + } + System.out.println("processName=="+processName); + }else if ((strLine.startsWith("")) || (strLine.startsWith("ܾ")) || (strLine.startsWith("׼")) ) {//|| (strLine.startsWith("")) + String[] temp = strLine.split(" "); + int k = 0; + String taskName = ""; + String pzUser = ""; + String pzTime = ""; + + for (int i = 0; i < temp.length; i++) { + if (temp[i].trim().length() != 0) { + ++k; + if (k == 2) { + taskName = temp[i].trim(); + } + if (k == 3) { + pzTime = temp[i].trim(); + } + if (k == 4) { + pzTime = pzTime + " " + temp[i].trim(); + } + if (k == 5) { + pzUser = temp[i].trim(); + break; + } + } + } + + try { + TCComponentUser tccomponentuser1 = UserList.getUser(session, "(" + pzUser + ")"); + if (tccomponentuser1 != null) { + pzUser = tccomponentuser1.toString(); + } + } + catch (TCException e) { + e.printStackTrace(); + } + + SignInfo oneSignInfo = new SignInfo(); + + oneSignInfo.userName = pzUser; + oneSignInfo.startTime = pzTime; + if(num==1){ + oneSignInfo.processName = processName; + }else{ + oneSignInfo.processName = ""; + } + + if ((strLine.startsWith(""))) { + oneSignInfo.taskName = taskName; + if (taskNameVector.contains(taskName)) { + if (strLine.startsWith("")) { + oneSignInfo.userAction = ""; + if ((!reviewTaskList.contains(taskName)) && (!AcknowladgeTaskList.contains(taskName))) { + br.readLine(); + br.mark(400); + strLine = br.readLine(); + if (!(strLine.startsWith(" ") || strLine.startsWith("\t"))) { + br.reset(); + } else { + String Comments = strLine.trim(); + while((strLine = br.readLine()) != null){ + if(strLine.equals("")){ + break; + }else{ + Comments = Comments + "\t"+strLine.trim(); + } + } + oneSignInfo.userComments = Comments; + } + oneSignInfo.num = num++; + vs.add(oneSignInfo); + } + } + } + } else { + if ((strLine.startsWith("׼"))) { + oneSignInfo.userAction = "׼"; + } else { + oneSignInfo.userAction = "ܾ"; + } + strLine = br.readLine(); + temp = strLine.split(":"); + taskName = temp[1].trim(); + if (taskNameVector.contains(taskName)) { + oneSignInfo.taskName = taskName; + if (AcknowladgeTaskList.contains(taskName)) { + oneSignInfo.userAction = "Ͽ"; + } + br.mark(400); + strLine = br.readLine(); + if (!(strLine.startsWith(" ") || strLine.startsWith("\t"))) { + br.reset(); + } else { + String Comments = strLine.trim(); + while((strLine = br.readLine()) != null){ + if(strLine.equals("")){ + break; + }else{ + Comments = Comments + "\t"+strLine.trim(); + } + } + oneSignInfo.userComments = Comments; + } + oneSignInfo.num = num++; + vs.add(oneSignInfo); + } + } + } + } + br.close(); + } + catch (FileNotFoundException e1) { + e1.printStackTrace(); + } + catch (IOException e2) { + e2.printStackTrace(); + } + System.out.println("readerFromText(String) - end" + vs.size()); //$NON-NLS-1$ + return vs; + } + + + /** + * һıļȡϢ(readerFromText) *************̴ + */ + public Vector readerFromText(Vector fileNameVector) { + System.out.println("readerFromText(String) - start"); //$NON-NLS-1$ + BufferedReader br = null; + Vector vs = new Vector(); + for(int n = 0; n < fileNameVector.size(); n++){ + int num = 1; + try { + br = new BufferedReader(new InputStreamReader(new FileInputStream(fileNameVector.get(n)))); + String strLine = null; + String processName = ""; + while ((strLine = br.readLine()) != null) { + System.out.println("strLine=="+strLine); + if(strLine.startsWith("ģ")){ + String [] temps = strLine.split(" "); + int y=0; + System.out.println(" temps.length=="+ temps.length); + for (int i = 0; i < temps.length; i++) { + if (temps[i].trim().length() != 0) { + ++y; + if (y == 2) { + processName = temps[i].trim();// + } + } + } + System.out.println("processName=="+processName); + }else if (strLine.startsWith("") || strLine.startsWith("ܾ") || strLine.startsWith("׼")) { + String[] temp = strLine.split(" "); + int k = 0; + String taskName = ""; + String pzUser = ""; + String pzTime = ""; + + for (int i = 0; i < temp.length; i++) { + if (temp[i].trim().length() != 0) { + ++k; + if (k == 2) { + taskName = temp[i].trim(); + } + if (k == 3) { + pzTime = temp[i].trim(); + } + if (k == 4) { + pzTime = pzTime + " " + temp[i].trim(); + } + if (k == 5) { + pzUser = temp[i].trim(); + break; + } + } + } + + try { + TCComponentUser tccomponentuser1 = UserList.getUser(session, "(" + pzUser + ")"); + if (tccomponentuser1 != null) { + pzUser = tccomponentuser1.toString(); + } + } catch (Exception e) { + e.printStackTrace(); + } + + SignInfo oneSignInfo = new SignInfo(); + + oneSignInfo.userName = pzUser; + oneSignInfo.startTime = pzTime; + if(num==1){ + oneSignInfo.processName = processName; + }else{ + oneSignInfo.processName = ""; + } + + if (strLine.startsWith("")) { + oneSignInfo.taskName = taskName; + if (taskNameVector.contains(taskName)) { + if (strLine.startsWith("")) { + oneSignInfo.userAction = ""; + if (!reviewTaskList.contains(taskName) && !AcknowladgeTaskList.contains(taskName)) { + br.readLine(); + br.mark(400); + strLine = br.readLine(); + if (!(strLine.startsWith(" ") || strLine.startsWith("\t"))) { + br.reset(); + } else { + String Comments = strLine.trim(); + while((strLine = br.readLine()) != null){ + if(strLine.equals("")){ + break; + }else{ + Comments = Comments + "\t"+strLine.trim(); + } + } + oneSignInfo.userComments = Comments; + } + oneSignInfo.num = num++; + vs.add(oneSignInfo); + } + } + } + } else { + if (strLine.startsWith("׼")) { + oneSignInfo.userAction = "׼"; + } else { + oneSignInfo.userAction = "ܾ"; + } + strLine = br.readLine(); + temp = strLine.split(":"); + taskName = temp[1].trim(); + if (taskNameVector.contains(taskName)) { + oneSignInfo.taskName = taskName; + if (AcknowladgeTaskList.contains(taskName)) { + oneSignInfo.userAction = "Ͽ"; + } + br.mark(400); + strLine = br.readLine(); + if (!(strLine.startsWith(" ") || strLine.startsWith("\t"))) { + br.reset(); + } else { + String Comments = strLine.trim(); + while((strLine = br.readLine()) != null){ + if(strLine.equals("")){ + break; + }else{ + Comments = Comments + "\t"+strLine.trim(); + } + } + oneSignInfo.userComments = Comments; + } + oneSignInfo.num = num++; + vs.add(oneSignInfo); + } + } + } + } + br.close(); + } catch (Exception e2) { + e2.printStackTrace(); + } + } + + System.out.println("readerFromText(String) - end" + vs.size()); //$NON-NLS-1$ + return vs; + } + + // ȡһıļҪһ̬ + static class SignInfo { + public String processName = ""; + public int num = 0; + public String taskName = ""; + public String userName = ""; + public String userAction = ""; + public String startTime = ""; + public String finishTime = ""; + public String userComments = ""; + } + + private TCSession session = null; + private AbstractAIFUIApplication myuiapp; +} diff --git a/src/com/connor/lidy/task/QueryTaskProcessCommand.java b/src/com/connor/lidy/task/QueryTaskProcessCommand.java new file mode 100644 index 0000000..3fbb8f4 --- /dev/null +++ b/src/com/connor/lidy/task/QueryTaskProcessCommand.java @@ -0,0 +1,55 @@ +/* +#======================================================================================================= +# +# Copyright (c) 2007 Origin Enterprise Solution LTD. +# +#======================================================================================================= +# File description: QueryTaskProcessCommand.java +#======================================================================================================= +# Date time Name Action Description of Change +# 2011-1-17 10:19:35 tyl Ini ʼļ +#======================================================================================================= + */ +package com.connor.lidy.task; + +import java.util.List; + +import com.connor.lidy.task.util.GetAllUserIds; + +import com.teamcenter.rac.aif.AbstractAIFCommand; +import com.teamcenter.rac.aif.AbstractAIFUIApplication; +import com.teamcenter.rac.kernel.TCException; + +public class QueryTaskProcessCommand extends AbstractAIFCommand { + + public AbstractAIFUIApplication application; + + public QueryTaskProcessCommand(AbstractAIFUIApplication abstractaifapplication) throws TCException { + application = abstractaifapplication; + execute(); + } + + private void execute() throws TCException { + System.out.println(" QueryTaskProcessCommand "); + GetAllUserIds.setUsers(new GetAllUserIds(application).getAllUsers()); + new Thread() { + public void run() { + while (true) { + try { + List users = GetAllUserIds.getUsers(); + if ((users == null) || (users.size() == 0)) { + System.out.println("--------------1000"); + sleep(20000); + } else { + new SearchTaskDialog(application, "ѯ", false); + break; + } + } + catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + }.start(); + } +} diff --git a/src/com/connor/lidy/task/QueryTaskProcessHandler.java b/src/com/connor/lidy/task/QueryTaskProcessHandler.java new file mode 100644 index 0000000..b9e26d7 --- /dev/null +++ b/src/com/connor/lidy/task/QueryTaskProcessHandler.java @@ -0,0 +1,41 @@ +/* +#======================================================================================================= +# +# Copyright (c) 2007 Origin Enterprise Solution LTD. +# +#======================================================================================================= +# File description: QueryTaskProcessHandler.java +#======================================================================================================= +# Date time Name Action Description of Change +# 2011-1-17 10:19:51 tyl Ini ʼļ +#======================================================================================================= + */ +package com.connor.lidy.task; + +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.AbstractAIFUIApplication; +import com.teamcenter.rac.aifrcp.AIFUtility; + +public class QueryTaskProcessHandler extends AbstractHandler implements IHandler { + + /* + * @see + * org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands. + * ExecutionEvent) + */ + public Object execute(ExecutionEvent arg0) throws ExecutionException { + final AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + try { + QueryTaskProcessCommand command = new QueryTaskProcessCommand(app); + command.executeModal(); + + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + +} diff --git a/src/com/connor/lidy/task/SearchResultDialog.java b/src/com/connor/lidy/task/SearchResultDialog.java new file mode 100644 index 0000000..dacbc90 --- /dev/null +++ b/src/com/connor/lidy/task/SearchResultDialog.java @@ -0,0 +1,708 @@ +/* +#======================================================================================================= +# +# Copyright (c) 2007 Origin Enterprise Solution LTD. +# +#======================================================================================================= +# File description: SearchResultDialog.java +#======================================================================================================= +# Date time Name Action Description of Change +# 2011-1-17 03:46:01 tyl Ini ʼļ +#======================================================================================================= + */ +package com.connor.lidy.task; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.swing.ImageIcon; +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.border.TitledBorder; +import javax.swing.table.JTableHeader; + +import com.connor.lidy.task.SearchTaskDialog.SearchCondition; +import com.connor.lidy.task.util.ColumnGroup; +import com.connor.lidy.task.util.DataSetFinder; +import com.connor.lidy.task.util.GetChoosePath; +import com.connor.lidy.task.util.GetMessageDialog; +import com.connor.lidy.task.util.GroupableTableHeader; +import com.connor.lidy.task.util.TableColorRender; +import com.connor.lidy.task.util.TableColumnRender; +import com.connor.lidy.task.util.UtilApi; + +import com.teamcenter.rac.aif.AIFDesktop; +import com.teamcenter.rac.aif.AbstractAIFCommand; +import com.teamcenter.rac.aif.AbstractAIFUIApplication; +import com.teamcenter.rac.aif.kernel.AIFComponentContext; +import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.commands.open.OpenCommand; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentSignoff; +import com.teamcenter.rac.kernel.TCComponentTask; +import com.teamcenter.rac.kernel.TCComponentUserType; +import com.teamcenter.rac.kernel.TCException; +import com.teamcenter.rac.kernel.TCPreferenceService; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.kernel.TCTypeService; +import com.teamcenter.rac.util.MessageBox; +import com.teamcenter.rac.util.PropertyLayout; +import com.teamcenter.rac.util.Registry; + +//public class SearchResultDialog extends AbstractAIFDialog { +public class SearchResultDialog extends JFrame { + private static final long serialVersionUID = 1L; + private List results = new ArrayList(); + private JTable table1; + private SearchResultTableModel dtm1; + private String title = ""; + private TCSession session; + private SearchCondition searchCondition; + private String[] names1 = { "*", "", "ִ", "ϲʱ", "ʱ", "״̬", "ǩע", "", + "", "", "ʱ", "һ޸ʱ", "һ޸", "״̬", "ģ" }; + private String[] names2 = { "*", "", "", "", "ʱ", "һ޸ʱ", "һ޸", "״̬" }; + private Map taskMap = new HashMap(); + + private String reportOption = "origin_viewTask_report"; + private String reportPath = "c:"; + private PackExcelInfo excelInfo = new PackExcelInfo(); + private boolean isExceptionSearch; + + public SearchResultDialog(AbstractAIFUIApplication app, List components, SearchCondition searchCondition, boolean isExceptionSearch) { + this.session = (TCSession) app.getSession(); + this.searchCondition = searchCondition; + this.isExceptionSearch = isExceptionSearch; + getResultValue(components); + initUI(); + File file = new File(excelInfo.getTemplateFileName()); + if (file.exists()) { + file.delete(); + } + } + + @SuppressWarnings("deprecation") + private void getResultValue(List components) { + try { + title = (new Date().toLocaleString()) + "_" + session.getUser() + "_ִѯִߣ" + searchCondition.getUsername() + "ʱΣ[" + searchCondition.getCreateDate() + "]_[" + searchCondition.getFinishDate() + "]"; + if (components != null) { + List taskList = new ArrayList(); + List taskIndexList = new ArrayList(); + for (int i = 0; i < components.size(); i++) { + TCComponentTask task = (TCComponentTask) components.get(i); + + if (task != null) { + SearchResults result = new SearchResults(); + if (!isExceptionSearch) { + if (((task.getTaskType()).equalsIgnoreCase("EPMSelectSignoffTask")) || ((task.getTaskType()).equalsIgnoreCase("EPMPerformSignoffTask"))) { + TCComponentSignoff[] sigoffs = task.getValidSignoffs(); + for (int m = 0; m < sigoffs.length; m++) { + String comment = sigoffs[m].getComments(); + result.setTask_note(comment); + result.setTask_executor(sigoffs[m].getProperty("signoff_member")); + result.setTask_finishDate(sigoffs[m].getProperty("decision_date")); + } + } else { + result.setTask_executor(task.getProperty("owning_user")); + result.setTask_finishDate(task.getProperty("last_mod_date")); + result.setTask_note(""); + } + } + + if (((task.getTaskType()).equalsIgnoreCase("EPMSelectSignoffTask")) || ((task.getTaskType()).equalsIgnoreCase("EPMPerformSignoffTask"))) { + task = task.getParent(); + } + if (taskList.contains(task)) { + int taskIndex = taskList.indexOf(task); + taskList.remove(task); + taskIndexList.remove(taskIndex); + } + + result.setTask_name(task.getProperty("object_name")); + if (result.getTask_type().equals("EPMTask")) { + if (result.getTask_status().equals("ѿʼ")) { + result.setTask_name("" + result.getTask_name()); + result.setTask_finishDate(""); + } + } + + Date taskCreateDate = null; + SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + result.setTask(task); + taskCreateDate = task.getDateProperty("creation_date"); + + result.setTask_createDate(task.getProperty("creation_date")); + TCComponentTask previousTask = task.getPrevious(); + if (previousTask != null) { + result.setTask_createDate(previousTask.getProperty("last_mod_date")); + taskCreateDate = previousTask.getDateProperty("last_mod_date"); + } + result.setTask_type(task.getProperty("object_type")); + result.setTask_status(task.getProperty("real_state")); + + if (!result.getTask_status().equals("")) { + result.setTask_finishDate(""); + } + + TCComponentTask rootTask = task.getRoot(); + result.setProcess_name(rootTask.getProperty("job_name")); + result.setProcess_createDate(rootTask.getProperty("creation_date")); + result.setProcess_finishDate(rootTask.getProperty("last_mod_date")); + result.setProcess_lastModeUser(rootTask.getProperty("last_mod_user")); + result.setProcess_executor(rootTask.getProperty("owning_user")); + result.setProcess_status(rootTask.getProperty("real_state")); + result.setProcess_templateName(rootTask.getProperty("task_template")); + // String index = String.valueOf(i + 1) + "$$$" + + // result.getProcess_createDate() + "$$$" + + // result.getTask_createDate() + "$$$" + + // result.getTask_finishDate(); + String index = String.valueOf(i + 1) + "$$$" + simpleDate.format(rootTask.getDateProperty("creation_date")) + "$$$" + result.getProcess_name() + "$$$" + simpleDate.format(taskCreateDate); + taskIndexList.add(index); + taskMap.put(index, result); + } + taskList.add(task); + } + + Collections.sort(taskIndexList, new ComparatorTask()); + for (int i = 0; i < taskIndexList.size(); i++) { + SearchResults result = taskMap.get(taskIndexList.get(i)); + result.setIndex(String.valueOf(i + 1)); + results.add(result); + } + } + } + catch (TCException e) { + e.printStackTrace(); + } + } + + public String getUserByID(String userID) { + try { + TCTypeService service = session.getTypeService(); + TCComponentUserType userType = (TCComponentUserType) service.getTypeComponent("User"); + if (userType.find(userID) != null) { + String user = userType.find(userID).toString(); + return user; + } + } + catch (TCException e1) { + e1.printStackTrace(); + } + return ""; + } + + public void initUI() { + this.setTitle("ѯ"); + ImageIcon image = Registry.getImageIconFromPath("/com/teamcenter/rac/ecmanagement/images/processviewer_16.png"); + this.setIconImage(image.getImage()); + JPanel panel = new JPanel(new BorderLayout()); + panel.add(BorderLayout.NORTH, setTopPanel()); + panel.add(BorderLayout.CENTER, setCenterPanel()); + panel.add(BorderLayout.SOUTH, setBottomPanel()); + getContentPane().add(panel); + // this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); + // this.addWindowListener(new WindowAdapter() { + // public void windowClosing(WindowEvent e) { + // dispose(); + // } + // }); + // showDialog(); + pack(); + Dimension screen = getToolkit().getScreenSize(); + setLocation((screen.width - getSize().width) / 2, (screen.height - getSize().height) / 2); + this.setVisible(true); + } + + private JPanel setTopPanel() { + JPanel panel = new JPanel(new BorderLayout()); + panel.add(new JLabel(" "), BorderLayout.NORTH); + if (!isExceptionSearch) { + panel.add(new JLabel(" " + title), BorderLayout.CENTER); + } + panel.add(new JLabel(" "), BorderLayout.SOUTH); + return panel; + } + + private JPanel setCenterPanel() { + JPanel panel1 = new JPanel(new PropertyLayout()); + panel1.setBorder(new TitledBorder("")); + if (!isExceptionSearch) { + dtm1 = new SearchResultTableModel(names1, results, 0); + table1 = new JTable(dtm1) { + private static final long serialVersionUID = 1L; + + protected JTableHeader createDefaultTableHeader() { + return new GroupableTableHeader(columnModel); + } + }; + GroupableTableHeader header = new GroupableTableHeader(table1.getColumnModel()); + javax.swing.table.TableColumnModel cm = table1.getColumnModel(); + // + ColumnGroup taskCol = new ColumnGroup("Ϣ"); + taskCol.add(cm.getColumn(1)); + taskCol.add(cm.getColumn(2)); + taskCol.add(cm.getColumn(3)); + taskCol.add(cm.getColumn(4)); + taskCol.add(cm.getColumn(5)); + taskCol.add(cm.getColumn(6)); + taskCol.add(cm.getColumn(7)); + header.addColumnGroup(taskCol); + + ColumnGroup processCol = new ColumnGroup("Ϣ"); + processCol.add(cm.getColumn(8)); + processCol.add(cm.getColumn(9)); + processCol.add(cm.getColumn(10)); + processCol.add(cm.getColumn(11)); + processCol.add(cm.getColumn(12)); + processCol.add(cm.getColumn(13)); + processCol.add(cm.getColumn(14)); + header.addColumnGroup(processCol); + table1.setTableHeader(header); + table1.setDefaultRenderer(Object.class, new TableColorRender()); + dtm1.setTableColumnsWidth(table1, 0); + } else { + dtm1 = new SearchResultTableModel(names2, results, 1); + table1 = new JTable(dtm1); + dtm1.setTableColumnsWidth(table1, 1); + } + table1.setRowHeight(20); + table1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); + + // нȾ + table1.getColumnModel().getColumn(0).setCellRenderer(new TableColumnRender()); + Dimension screen = getToolkit().getScreenSize(); + JScrollPane scrollPane1 = new JScrollPane(table1, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); + if (!isExceptionSearch) { + scrollPane1.setPreferredSize(new Dimension((int) (screen.getWidth() * (0.75)), (int) (screen.getHeight() * (0.6)))); + } else { + scrollPane1.setPreferredSize(new Dimension((int) (screen.getWidth() * (0.62)), (int) (screen.getHeight() * (0.5)))); + } + JPanel panel = new JPanel(new BorderLayout()); + panel.setBorder(new TitledBorder("")); + panel.add(scrollPane1); + return panel; + } + + private JPanel setBottomPanel() { + JPanel southPanel = new JPanel(new FlowLayout()); + // southPanel.setSize(100, 15); + JButton confirmButton = new JButton("鿴"); + JButton exitButton = new JButton(" "); + JButton exportButton = new JButton("Excel"); + confirmButton.addActionListener(new buttonListener()); + exitButton.addActionListener(new buttonListener()); + exportButton.addActionListener(new buttonListener()); + southPanel.add(new JLabel(" ")); + southPanel.add(new JLabel(" ")); + southPanel.add(new JLabel(" ")); + southPanel.add(new JLabel(" ")); + southPanel.add(new JLabel(" ")); + southPanel.add(confirmButton); + if (!isExceptionSearch) { + southPanel.add(exportButton); + } + southPanel.add(exitButton); + return southPanel; + } + + class buttonListener implements ActionListener { + public void actionPerformed(ActionEvent event) { + String name = ((JButton) event.getSource()).getText(); + if (name.equals("鿴")) { + showProcess(); + } else if (name.equals("Excel")) { + exportResult(); + } else if (name.equals(" ")) { + dispose(); + } + } + } + + private void exportResult() { + String dir = new GetChoosePath().getPath("\\viewTask.txt"); + if ((dir != "") || (dir.trim().length() > 0)) { + excelInfo.setTitle(title); + excelInfo.setTemplateFileName(getTemplateFile()); + String times = String.valueOf(new SimpleDateFormat("yyyyMMddhhmmss").format(new Date(System.currentTimeMillis()))); + excelInfo.setTargetFileName(dir + "\\ѯ_" + times + ".xls"); + new ExportSearchResult(results, excelInfo); + openFile(excelInfo.getTargetFileName(), false); + this.setVisible(true); + } + } + + public String getTemplateFile() { + HashMap cfghm = UtilApi.getPreferenceHashMap(session, TCPreferenceService.TC_preference_site, reportOption); + if (cfghm == null) { + MessageBox.post("ûѡ" + reportOption + "!", "INFO", MessageBox.INFORMATION); + return ""; + } + String DatasetOwningUser = (cfghm.get("DatasetOwningUser") + "").trim(); + String DatasetOwningGroup = (cfghm.get("DatasetOwningGroup") + "").trim(); + String DatasetName = (cfghm.get("DatasetName") + "").trim(); + DataSetFinder dataset_finder = new DataSetFinder(session); + TCComponentDataset imancomponentdataset = dataset_finder.FindDatasetByName(DatasetName, DatasetOwningUser, DatasetOwningGroup, "MSExcel"); + System.out.println("imancomponentdataset=========" + imancomponentdataset); + if (imancomponentdataset != null) { + try { + File file1 = new File(reportPath); + if (!file1.exists()) { + file1.createNewFile(); + } + File file = dataset_finder.ExportFileToDir(imancomponentdataset, reportPath); + if (file != null) { + System.out.println("file=========" + file.getAbsolutePath()); + return file.getAbsolutePath(); + } + } + catch (Exception e) { + MessageBox.post("ݼʱ!", "INFO", MessageBox.INFORMATION); + e.printStackTrace(); + } + } else { + MessageBox.post("õġ" + DatasetName + "ݼģ岻!", "INFO", MessageBox.INFORMATION); + } + return ""; + } + + public void openFile(String targetFile, boolean isDir) { + File file = new File(targetFile); + if (file.exists()) { + int value = 0; + if (isDir) { + value = new GetMessageDialog("INFO", "ļѾɣǷĿ¼").getValue(); + // value = + // MessageDialog.openConfirm(Display.getCurrent().getActiveShell(), + // "INFO", "ļѾɣǷĿ¼"); + } else { + // value = + // MessageDialog.openConfirm(Display.getCurrent().getActiveShell(), + // "INFO", "ļѾɣǷ򿪣"); + value = new GetMessageDialog("INFO", "ļѾɣǷ򿪣").getValue(); + } + if (value == 0) { + try { + Runtime runtime = Runtime.getRuntime(); + runtime.exec("cmd /c start exit &&\"" + targetFile + "\" "); + } + catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + private void showProcess() { + int row = table1.getSelectedRow(); + if (row >= 0) { + final SearchResults result = results.get(row); + AIFDesktop localAIFDesktop = AIFUtility.getActiveDesktop(); + + // try { + // ExplorerService exploreService = new ExplorerService(); + // // exploreService.expand(); + // // exploreService.refresh(); + // } + // catch (Exception e1) { + // e1.printStackTrace(); + // } + // String str = "com.teamcenter.rac.explorer.ExplorerApplication"; + // localAIFDesktop.sendToApplication(result.getTask(), str); + + TCComponentTask task = result.getTask(); + try { + AIFComponentContext[] context = task.getChildren(); + InterfaceAIFComponent[] contexts = new InterfaceAIFComponent[] { (InterfaceAIFComponent) context[0].getComponent() }; + try { + System.out.println("task.getName()==" + task.getName()); + } + catch (TCException e1) { + e1.printStackTrace(); + } + AbstractAIFCommand abstractaifcommand = new OpenCommand(localAIFDesktop, contexts); + try { + abstractaifcommand.executeModal(); + } + catch (Exception e1) { + e1.printStackTrace(); + } + } + catch (TCException e1) { + e1.printStackTrace(); + } + + try { + Thread.sleep(500); + } + catch (InterruptedException e) { + e.printStackTrace(); + } + SearchResultDialog.this.setExtendedState(JFrame.ICONIFIED); + } else { + MessageBox.post("ѡҪ鿴̣", "INFO", MessageBox.INFORMATION); + this.setVisible(true); + } + } + + class SearchResults { + private String index = ""; + private String task_name = ""; + private String task_createDate = ""; + private String task_finishDate = ""; + private String task_status = ""; + private String task_executor = ""; + private String task_note = ""; + private String task_type = ""; + + /** + * @return the task_type + */ + public String getTask_type() { + return task_type; + } + + /** + * @param task_type the task_type to set + */ + public void setTask_type(String task_type) { + this.task_type = task_type; + } + + private TCComponentTask task; + + private String process_name; + private String process_createDate; + private String process_finishDate; + private String process_status; + private String process_executor; + private String process_lastModeUser; + private String process_templateName; + + /** + * @return the task + */ + public TCComponentTask getTask() { + return task; + } + + /** + * @return the process_lastModeUser + */ + public String getProcess_lastModeUser() { + return process_lastModeUser; + } + + /** + * @param process_lastModeUser the process_lastModeUser to set + */ + public void setProcess_lastModeUser(String process_lastModeUser) { + this.process_lastModeUser = process_lastModeUser; + } + + /** + * @param task the task to set + */ + public void setTask(TCComponentTask task) { + this.task = task; + } + + /** + * @return the index + */ + public String getIndex() { + return index; + } + + /** + * @param index the index to set + */ + public void setIndex(String index) { + this.index = index; + } + + /** + * @return the task_name + */ + public String getTask_name() { + return task_name; + } + + /** + * @param task_name the task_name to set + */ + public void setTask_name(String task_name) { + this.task_name = task_name; + } + + /** + * @return the task_createDate + */ + public String getTask_createDate() { + return task_createDate; + } + + /** + * @param task_createDate the task_createDate to set + */ + public void setTask_createDate(String task_createDate) { + this.task_createDate = task_createDate; + } + + /** + * @return the task_finishDate + */ + public String getTask_finishDate() { + return task_finishDate; + } + + /** + * @param task_finishDate the task_finishDate to set + */ + public void setTask_finishDate(String task_finishDate) { + this.task_finishDate = task_finishDate; + } + + /** + * @return the task_status + */ + public String getTask_status() { + return task_status; + } + + /** + * @param task_status the task_status to set + */ + public void setTask_status(String task_status) { + this.task_status = task_status; + } + + /** + * @return the task_executor + */ + public String getTask_executor() { + return task_executor; + } + + /** + * @param task_executor the task_executor to set + */ + public void setTask_executor(String task_executor) { + this.task_executor = task_executor; + } + + /** + * @return the task_note + */ + public String getTask_note() { + return task_note; + } + + /** + * @param task_note the task_note to set + */ + public void setTask_note(String task_note) { + this.task_note = task_note; + } + + /** + * @return the process_name + */ + public String getProcess_name() { + return process_name; + } + + /** + * @param process_name the process_name to set + */ + public void setProcess_name(String process_name) { + this.process_name = process_name; + } + + /** + * @return the process_createDate + */ + public String getProcess_createDate() { + return process_createDate; + } + + /** + * @param process_createDate the process_createDate to set + */ + public void setProcess_createDate(String process_createDate) { + this.process_createDate = process_createDate; + } + + /** + * @return the process_finishDate + */ + public String getProcess_finishDate() { + return process_finishDate; + } + + /** + * @param process_finishDate the process_finishDate to set + */ + public void setProcess_finishDate(String process_finishDate) { + this.process_finishDate = process_finishDate; + } + + /** + * @return the process_status + */ + public String getProcess_status() { + return process_status; + } + + /** + * @param process_status the process_status to set + */ + public void setProcess_status(String process_status) { + this.process_status = process_status; + } + + /** + * @return the process_executor + */ + public String getProcess_executor() { + return process_executor; + } + + /** + * @param process_executor the process_executor to set + */ + public void setProcess_executor(String process_executor) { + this.process_executor = process_executor; + } + + /** + * @return the process_templateName + */ + public String getProcess_templateName() { + return process_templateName; + } + + /** + * @param process_templateName the process_templateName to set + */ + public void setProcess_templateName(String process_templateName) { + this.process_templateName = process_templateName; + } + + } +} diff --git a/src/com/connor/lidy/task/SearchResultTableModel.java b/src/com/connor/lidy/task/SearchResultTableModel.java new file mode 100644 index 0000000..322d7d4 --- /dev/null +++ b/src/com/connor/lidy/task/SearchResultTableModel.java @@ -0,0 +1,135 @@ +/* +#======================================================================================================= +# +# Copyright (c) 2007 Origin Enterprise Solution LTD. +# +#======================================================================================================= +# File description: SearchResultTableModel.java +#======================================================================================================= +# Date time Name Action Description of Change +# 2011-1-17 03:46:12 tyl Ini ʼļ +#======================================================================================================= +*/ +package com.connor.lidy.task; + +import java.util.Enumeration; +import java.util.List; + +import javax.swing.JTable; +import javax.swing.table.DefaultTableModel; +import javax.swing.table.JTableHeader; +import javax.swing.table.TableColumn; + +import com.connor.lidy.task.SearchResultDialog.SearchResults; + +public class SearchResultTableModel extends DefaultTableModel { + + private static final long serialVersionUID = 1L; + + /** + * Creates a new instance of EditBatchProcessLineTableModel. + * @param data + */ + public SearchResultTableModel(String[] names, List data, int index) { + super(getData(data, index), names); + } + + public static Object[][] getData(List data, int index) { + Object[][] datas = new Object[data.size()][]; + for (int i = 0; i < data.size(); i++) { + if (index == 0) { + String[] info = new String[15]; + info[0] = String.valueOf(i + 1); + info[1] = data.get(i).getTask_name(); + info[2] = data.get(i).getTask_executor(); + info[3] = data.get(i).getTask_createDate(); + info[4] = data.get(i).getTask_finishDate(); + info[5] = data.get(i).getTask_status(); + info[6] = data.get(i).getTask_note(); + info[7] = data.get(i).getTask_type(); + info[8] = data.get(i).getProcess_executor(); + info[9] = data.get(i).getProcess_name(); + info[10] = data.get(i).getProcess_createDate(); + info[11] = data.get(i).getProcess_finishDate(); + info[12] = data.get(i).getProcess_lastModeUser(); + info[13] = data.get(i).getProcess_status(); + info[14] = data.get(i).getProcess_templateName(); + datas[i] = info; + } else { + if (index == 1) { + String[] info = new String[8]; + info[0] = String.valueOf(i + 1); + info[1] = data.get(i).getProcess_executor(); + info[2] = data.get(i).getProcess_name(); + info[3] = data.get(i).getTask_name(); + info[4] = data.get(i).getProcess_createDate(); + info[5] = data.get(i).getProcess_finishDate(); + info[6] = data.get(i).getProcess_lastModeUser(); + info[7] = data.get(i).getProcess_status(); + datas[i] = info; + } + } + } + return datas; + } + + @Override + public boolean isCellEditable(int row, int column) { + if (column == 0) { + return false; + } else { + return true; + } + } + + // п + public void setTableColumnsWidth(JTable myTable, int index) { + if (index == 0) { + myTable.getColumnModel().getColumn(0).setPreferredWidth(30); + myTable.getColumnModel().getColumn(1).setPreferredWidth(80); + myTable.getColumnModel().getColumn(2).setPreferredWidth(80); + myTable.getColumnModel().getColumn(3).setPreferredWidth(80); + myTable.getColumnModel().getColumn(4).setPreferredWidth(80); + myTable.getColumnModel().getColumn(5).setPreferredWidth(60); + myTable.getColumnModel().getColumn(6).setPreferredWidth(60); + myTable.getColumnModel().getColumn(7).setPreferredWidth(60); + myTable.getColumnModel().getColumn(8).setPreferredWidth(80); + myTable.getColumnModel().getColumn(9).setPreferredWidth(80); + myTable.getColumnModel().getColumn(10).setPreferredWidth(80); + myTable.getColumnModel().getColumn(11).setPreferredWidth(80); + myTable.getColumnModel().getColumn(12).setPreferredWidth(80); + myTable.getColumnModel().getColumn(13).setPreferredWidth(50); + myTable.getColumnModel().getColumn(14).setPreferredWidth(80); + } else { + if (index == 1) { + myTable.getColumnModel().getColumn(0).setPreferredWidth(30); + myTable.getColumnModel().getColumn(1).setPreferredWidth(100); + myTable.getColumnModel().getColumn(2).setPreferredWidth(120); + myTable.getColumnModel().getColumn(3).setPreferredWidth(100); + myTable.getColumnModel().getColumn(4).setPreferredWidth(120); + myTable.getColumnModel().getColumn(5).setPreferredWidth(120); + myTable.getColumnModel().getColumn(6).setPreferredWidth(100); + myTable.getColumnModel().getColumn(7).setPreferredWidth(80); + } + } + } + + // п + public void FitTableColumns(JTable myTable) { + JTableHeader header = myTable.getTableHeader(); + // header.getColumnModel().getColumn(0) + int rowCount = myTable.getRowCount(); + Enumeration columns = myTable.getColumnModel().getColumns(); + while (columns.hasMoreElements()) { + TableColumn column = (TableColumn) columns.nextElement(); + int col = header.getColumnModel().getColumnIndex(column.getIdentifier()); + int width = (int) myTable.getTableHeader().getDefaultRenderer().getTableCellRendererComponent(myTable, column.getIdentifier(), false, false, -1, col).getPreferredSize().getWidth(); + for (int row = 0; row < rowCount; row++) { + int preferedWidth = (int) myTable.getCellRenderer(row, col).getTableCellRendererComponent(myTable, myTable.getValueAt(row, col), false, false, row, col).getPreferredSize().getWidth(); + width = Math.max(width, preferedWidth); + } + header.setResizingColumn(column); + column.setWidth(width + myTable.getIntercellSpacing().width); + } + } +} diff --git a/src/com/connor/lidy/task/SearchTaskDialog.java b/src/com/connor/lidy/task/SearchTaskDialog.java new file mode 100644 index 0000000..c801c6b --- /dev/null +++ b/src/com/connor/lidy/task/SearchTaskDialog.java @@ -0,0 +1,450 @@ +/* +#======================================================================================================= +# +# Copyright (c) 2007 Origin Enterprise Solution LTD. +# +#======================================================================================================= +# File description: SearchTaskDialog.java +#======================================================================================================= +# Date time Name Action Description of Change +# 2011-1-17 03:46:21 tyl Ini ʼļ +#======================================================================================================= + */ +package com.connor.lidy.task; + +import java.awt.Dimension; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.List; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JPanel; + +import com.connor.lidy.task.util.GetAllUserIds; +import com.connor.lidy.task.util.UtilApi; + +import com.teamcenter.rac.aif.AbstractAIFDialog; +import com.teamcenter.rac.aif.AbstractAIFUIApplication; +import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; //import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponentTask; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.DateButton; +import com.teamcenter.rac.util.MessageBox; +import com.teamcenter.rac.util.PropertyLayout; + +@SuppressWarnings("deprecation") +public class SearchTaskDialog extends AbstractAIFDialog { + // public class SearchTaskDialog extends JDialog { + // public class SearchTaskDialog extends JFrame { + private static final long serialVersionUID = 1L; + private JComboBox user_cmb; + private DateButton startTime_jtb; + private DateButton endTime_jtb; + private JCheckBox EPMTask_ck; + private JCheckBox EPMDoTask_ck; + private JCheckBox EPMReviewTask_ck; + private JCheckBox EPMAcknowledgeTask_ck; + private JCheckBox EPMAddStatusTask_ck; + private JCheckBox EPMConditionTask_ck; + private String title; + private AbstractAIFUIApplication app; + private String queryName = "__SearachViewTask"; + private String querySelectSigoff = "__SearchEPMReviewTask"; + private TCSession session; + private boolean isExceptionSearch = false; + // private String serverInfoOption = "origin_serverinfo"; + + public SearchTaskDialog(AbstractAIFUIApplication app, String title, boolean isExceptionSearch) { + super(true); + this.title = title; + this.isExceptionSearch = isExceptionSearch; + this.app = app; + session = (TCSession) app.getSession(); + initUI(); + } + + public void initUI() { + // setPersistentDisplay(false); + // setOptimalDisplay(false); + setTitle(title); + this.setResizable(false); + // this.setAlwaysOnTop(true); + // ImageIcon image = + // Registry.getImageIconFromPath("/com/teamcenter/rac/ecmanagement/images/processviewer_16.png"); + // this.setIconImage(image.getImage()); + JPanel panel = new JPanel(new PropertyLayout()); + panel.add("1.1.left.center", new JLabel(" ")); + if (isExceptionSearch) { + panel.add("1.2.left.center", setSearchExceptionPanel()); + } else { + panel.add("1.2.left.center", setSearchPanel()); + } + panel.add("2.1.left.center", new JLabel(" ")); + this.getContentPane().add(panel); + pack(); + validate(); + Dimension screen = getToolkit().getScreenSize(); + setLocation((screen.width - getSize().width) / 2, (screen.height - getSize().height) / 2); + this.setVisible(true); + + // showDialog(); + // Dimension screen = getToolkit().getScreenSize(); + // setLocation((screen.width - getSize().width) / 2, (screen.height - + // getSize().height) / 2); + } + + private JPanel setSearchExceptionPanel() { + startTime_jtb = new DateButton(); + endTime_jtb = new DateButton(); + JPanel panel1 = new JPanel(new PropertyLayout()); + panel1.setBorder(BorderFactory.createTitledBorder("ѯ")); + panel1.add("1.1.left.center", new JLabel(" ")); + panel1.add("2.1.left.center", new JLabel(" ִʱ_ ")); + panel1.add("2.2.left.center", startTime_jtb); + panel1.add("2.3.left.center", new JLabel(" ")); + panel1.add("3.1.left.center", new JLabel(" ִʱ_ֹ ")); + panel1.add("3.2.left.center", endTime_jtb); + panel1.add("4.1.left.center", new JLabel(" ")); + + JPanel panel = new JPanel(new PropertyLayout()); + panel.add("1.1.left.center", panel1); + panel.add("1.2.left.center", setButtonPanel()); + return panel; + } + + private JPanel setSearchPanel() { + user_cmb = new JComboBox<>(); + user_cmb.setPreferredSize(new Dimension(156, 27)); + startTime_jtb = new DateButton(); + endTime_jtb = new DateButton(); + + java.util.Date myDate = new java.util.Date(); + long myTime = (myDate.getTime() / 1000) - 60 * 60 * 24 * 7; + myDate.setTime(myTime * 1000); + startTime_jtb.setDate(myDate); + new Thread() { + public void run() { + while (true) { + try { + String userRole = session.getPreferenceService().getString(4, "Cust_search_task_role"); + if(session.getCurrentRole().getRoleName().equals(userRole)){ + List users = GetAllUserIds.getUsers(); + Collections.sort(users); + if (users != null) { + for (int i = 0; i < users.size(); i++) { + user_cmb.addItem(users.get(i)); + if (users.get(i).equalsIgnoreCase(session.getUser().getUserId())) { + user_cmb.setSelectedIndex(i); + } + } + user_cmb.setEnabled(true); + break; + } + }else{ + user_cmb.addItem(session.getUser().toString()); + break; + } + } + catch (Exception e) { + e.printStackTrace(); + } + } + } + }.start(); + + JPanel panel1 = new JPanel(new PropertyLayout()); + panel1.setBorder(BorderFactory.createTitledBorder("ѯ")); + panel1.add("1.1.left.center", new JLabel(" ִ ")); + panel1.add("1.2.left.center", user_cmb); + panel1.add("1.3.left.center", new JLabel(" ")); + panel1.add("2.1.left.center", new JLabel(" ִʱ_ ")); + panel1.add("2.2.left.center", startTime_jtb); + panel1.add("2.3.left.center", new JLabel(" ")); + panel1.add("3.1.left.center", new JLabel(" ִʱ_ֹ ")); + panel1.add("3.2.left.center", endTime_jtb); + panel1.add("3.3.left.center", new JLabel(" ")); + + JPanel panel2 = new JPanel(new PropertyLayout()); + panel2.setBorder(BorderFactory.createTitledBorder("ѡѯ")); + EPMTask_ck = new JCheckBox("EPMTask"); + EPMDoTask_ck = new JCheckBox("EPMDoTask"); + EPMReviewTask_ck = new JCheckBox("EPMReviewTask"); + EPMAcknowledgeTask_ck = new JCheckBox("EPMAcknowledgeTask"); + EPMAddStatusTask_ck = new JCheckBox("EPMAddStatusTask"); + EPMConditionTask_ck = new JCheckBox("EPMConditionTask"); + + EPMTask_ck.setSelected(true); + EPMDoTask_ck.setSelected(true); + EPMReviewTask_ck.setSelected(true); + EPMAcknowledgeTask_ck.setSelected(true); + + panel2.add("1.1.left.center", EPMTask_ck); + panel2.add("1.2.left.center", EPMDoTask_ck); + panel2.add("1.3.left.center", new JLabel(" ")); + panel2.add("2.1.left.center", EPMReviewTask_ck); + panel2.add("2.2.left.center", EPMConditionTask_ck); + panel2.add("2.3.left.center", new JLabel(" ")); + panel2.add("3.1.left.center", EPMAcknowledgeTask_ck); + panel2.add("3.2.left.center", EPMAddStatusTask_ck); + + JPanel panel = new JPanel(new PropertyLayout()); + panel.add("1.1.left.center", panel1); + panel.add("2.1.left.center", panel2); + panel.add("2.2.left.center", setButtonPanel()); + return panel; + } + + private JPanel setButtonPanel() { + JPanel panel = new JPanel(new PropertyLayout()); + JButton confirmBtn = new JButton("ȷ"); + JButton cancelBtn = new JButton("ȡ"); + confirmBtn.addActionListener(new buttonListener()); + cancelBtn.addActionListener(new buttonListener()); + + panel.add("1.1.left.center", new JLabel(" ")); + panel.add("2.1.left.center", confirmBtn); + panel.add("3.1.left.center", new JLabel(" ")); + panel.add("4.1.left.center", cancelBtn); + panel.add("5.1.left.center", new JLabel(" ")); + return panel; + } + + class buttonListener implements ActionListener { + public void actionPerformed(ActionEvent actionevent) { + session.setStatus("ڲѯԵ..."); + JButton obj = ((JButton) actionevent.getSource()); + if (obj.getText().equals("ȷ")) { + try { + if (startTime_jtb.getDate() == null) { + MessageBox.post("ִʱ_ԡΪգ", "INFO", MessageBox.INFORMATION); + return; + } + Date endDate = new Date(); + if (endTime_jtb.getDate() != null) { + endDate = endTime_jtb.getDate(); + } + if (startTime_jtb.getDate().compareTo(endDate) >= 0) { + MessageBox.post("ִʱ_ֹӦȡִʱ_ԡ", "INFO", MessageBox.INFORMATION); + return; + } + List components = new ArrayList(); + SearchCondition searchCondition = new SearchCondition(); + String as[] = { "޸ʱ", "޸ʱ", "ID", "", "ModUserID"}; + + SimpleDateFormat fomat = new SimpleDateFormat("dd-M-yyyy HH:ss"); + // fomat = new SimpleDateFormat("dd-M-yyyy HH:ss:mm"); + + String startTime = fomat.format(startTime_jtb.getDate()); + String endTime = fomat.format(endDate); + /* + * windows HashMap cfghm = + * UtilApi.getPreferenceHashMap(session, + * TCPreferenceService.TC_preference_site, + * serverInfoOption); if (cfghm == null) { + * MessageBox.post("ûѡ" + serverInfoOption + "!", + * "INFO", MessageBox.INFORMATION); return; } String + * isWindows = (cfghm.get("isWindowsServer") + "").trim(); + * if (isWindows.equalsIgnoreCase("true")) { startTime = + * startTime_jtb.getDate().toLocaleString(); endTime = + * endDate.toLocaleString(); + * System.out.println("Windows:startTime=========" + + * startTime); System.out.println("Windows:endTime=========" + * + endTime); } + */ +// System.out.println("Windows:startTime=========" + startTime); +// System.out.println("Windows:endTime=========" + endTime); + searchCondition.setCreateDate(startTime); + searchCondition.setFinishDate(endTime); + + if (!isExceptionSearch) { + String user = (user_cmb.getSelectedItem().toString()); + if ((user.length() == 0) || (user == null)) { + MessageBox.post("ûΪգ", "INFO", MessageBox.INFORMATION); + return; + } + if ((!(EPMTask_ck.isSelected())) && (!(EPMDoTask_ck.isSelected())) && (!(EPMReviewTask_ck.isSelected())) && (!(EPMAcknowledgeTask_ck.isSelected())) && (!(EPMAddStatusTask_ck.isSelected()))) { + MessageBox.post("ѡѯͣ", "INFO", MessageBox.INFORMATION); + return; + } + searchCondition.setUsername(user); + user = user.substring(0, user.indexOf("(")).trim(); + List taskList = new ArrayList(); + if (EPMTask_ck.isSelected()) { + taskList.add("EPMTask"); + } + if (EPMDoTask_ck.isSelected()) { + taskList.add("EPMDoTask"); + } + if (EPMReviewTask_ck.isSelected()) { + taskList.add("EPMReviewTask"); + } + if (EPMAcknowledgeTask_ck.isSelected()) { + taskList.add("EPMAcknowledgeTask"); + } + if (EPMAddStatusTask_ck.isSelected()) { + taskList.add("EPMAddStatusTask"); + } + if (EPMConditionTask_ck.isSelected()) { + taskList.add("EPMConditionTask"); + } + + for (int i = 0; i < taskList.size(); i++) { + if (taskList.get(i).equals("EPMTask")) { + String as1[] = { startTime, endTime, user, taskList.get(i).trim(), "*" }; + InterfaceAIFComponent[] components1 = UtilApi.getQueryList((TCSession) app.getSession(), queryName, as, as1); + if (components1 != null) { + for (int m = 0; m < components1.length; m++) { + components.add(components1[m]); + } + } + } else { + if (taskList.get(i).equals("EPMReviewTask")) { + String strID[] = { "memberUser" }; + String as1[] = { user }; + InterfaceAIFComponent[] components1 = UtilApi.getQueryList((TCSession) app.getSession(), querySelectSigoff,strID, as1); + if (components1 != null) { + for (int m = 0; m < components1.length; m++) { + components.add(components1[m]); + } + } + } else { + String as1[] = { startTime, endTime, user, taskList.get(i).trim(), "*"}; + InterfaceAIFComponent[] components1 = UtilApi.getQueryList((TCSession) app.getSession(), queryName, as, as1); + if (components1 != null) { + for (int m = 0; m < components1.length; m++) { + components.add(components1[m]); + } + } + } + } + } + } else { + String as1[] = { startTime, endTime, "*", "EPMTask", "*" }; + InterfaceAIFComponent[] components1 = UtilApi.getQueryList((TCSession) app.getSession(), queryName, as, as1); + if (components1 != null) { + for (int m = 0; m < components1.length; m++) { + TCComponentTask task = (TCComponentTask) components1[m]; + isValidTask(task, components); + } + } + } + if ((components == null) || (components.size() == 0)) { + MessageBox.post("ûзҪļ¼", "INFO", MessageBox.INFORMATION); + } else { + SearchTaskDialog.this.dispose(); + new SearchResultDialog(app, components, searchCondition, isExceptionSearch); + } + } + catch (Exception e) { + e.printStackTrace(); + } + } else { + SearchTaskDialog.this.dispose(); + } + session.setReadyStatus(); + } + } + + private boolean isValidTask(TCComponentTask task, List components) { + try { + TCComponentTask[] children = task.getSubtasks(); + for (int i = 0; i < children.length; i++) { + TCComponentTask childrenTask = children[i]; + String childState = childrenTask.getProperty("real_state"); + if (childState.equals("")) { + TCComponentTask previousTask = childrenTask.getPrevious(); + if (previousTask != null) { + String previousType = previousTask.getProperty("object_type"); + String previousState = previousTask.getProperty("real_state"); + if ((previousState.equals("")) && (!previousType.equals("EPMConditionTask"))) { + components.add(childrenTask); + return false; + } else { + if (!isValidTask(childrenTask, components)) { + components.add(childrenTask); + return false; + } + } + } + } + } + String taskState = task.getProperty("real_state"); + if (taskState.equals("ѿʼ")) { + if ((children != null) && (children.length >= 3)) { + int count = 0; + for (int i = 0; i < children.length; i++) { + TCComponentTask childrenTask = children[i]; + String childState = childrenTask.getProperty("real_state"); + if (childState.equals("ѿʼ")) { + count++; + } + } + if (count == 0) { + components.add(task); + return false; + } + } + } + } + catch (Exception e) { + e.printStackTrace(); + } + return true; + } + + class SearchCondition { + private String username; + private String createDate; + private String finishDate; + + /** + * @return the username + */ + public String getUsername() { + return username; + } + + /** + * @param username the username to set + */ + public void setUsername(String username) { + this.username = username; + } + + /** + * @return the createDate + */ + public String getCreateDate() { + return createDate; + } + + /** + * @param createDate the createDate to set + */ + public void setCreateDate(String createDate) { + this.createDate = createDate; + } + + /** + * @return the finishDate + */ + public String getFinishDate() { + return finishDate; + } + + /** + * @param finishDate the finishDate to set + */ + public void setFinishDate(String finishDate) { + this.finishDate = finishDate; + } + } +} diff --git a/src/com/connor/lidy/task/util/CheckBoxColumnRender.java b/src/com/connor/lidy/task/util/CheckBoxColumnRender.java new file mode 100644 index 0000000..6a4908b --- /dev/null +++ b/src/com/connor/lidy/task/util/CheckBoxColumnRender.java @@ -0,0 +1,52 @@ +/* +#============================================================================= +# +# Copyright (c) 2009 Origin Enterprise Solution LTD. +# +#============================================================================= +# File name: CheckBoxColumnRender.java +# File description: +#============================================================================= +# Date Name Action Description of Change +# 2011-4-20 liqz Ini ʼ(From Shaangu) +#============================================================================= +*/ +package com.connor.lidy.task.util; + +import java.awt.Component; + +import javax.swing.JCheckBox; +import javax.swing.JLabel; +import javax.swing.JTable; +import javax.swing.UIManager; +import javax.swing.table.DefaultTableCellRenderer; + +public class CheckBoxColumnRender extends DefaultTableCellRenderer { + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * + */ + public CheckBoxColumnRender() { + super(); + } + public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { + //õͷ + JCheckBox checkBox=new JCheckBox(); +// JTableHeader header = table.getTableHeader(); +// if (header != null) { +// setForeground(header.getForeground()); +// setBackground(header.getBackground()); +// setFont(header.getFont()); +// } + setHorizontalAlignment(JLabel.CENTER); + checkBox.setSelected(Boolean.valueOf(value.toString())); +// (value == null) ? "" : value.toString() + setBorder(UIManager.getBorder("TableHeader.cellBorder")); + return checkBox; + } +} diff --git a/src/com/connor/lidy/task/util/ColumnGroup.java b/src/com/connor/lidy/task/util/ColumnGroup.java new file mode 100644 index 0000000..01b7de8 --- /dev/null +++ b/src/com/connor/lidy/task/util/ColumnGroup.java @@ -0,0 +1,205 @@ +package com.connor.lidy.task.util; + +import java.awt.Component; +import java.awt.Dimension; +import java.util.Enumeration; +import java.util.Vector; + +import javax.swing.JLabel; +import javax.swing.JTable; +import javax.swing.UIManager; +import javax.swing.table.DefaultTableCellRenderer; +import javax.swing.table.JTableHeader; +import javax.swing.table.TableCellRenderer; +import javax.swing.table.TableColumn; + +public class ColumnGroup { + protected TableCellRenderer renderer; + + protected Vector v; + + protected String text; + + protected int margin = 0; + + public ColumnGroup(String text) { + this(null, text); + } + + public ColumnGroup(TableCellRenderer renderer, String text) { + if (renderer == null) { + this.renderer = new DefaultTableCellRenderer() { + /** + * + */ + private static final long serialVersionUID = 1L; + + public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { + JTableHeader header = table.getTableHeader(); + if (header != null) { + setForeground(header.getForeground()); + setBackground(header.getBackground()); + setFont(header.getFont()); + } + setHorizontalAlignment(JLabel.CENTER); + this.setText((value == null) ? "" : value.toString()); + setBorder(UIManager.getBorder("TableHeader.cellBorder")); + return this; + } + }; + } else { + this.renderer = renderer; + } + this.text = text; + v = new Vector<>(); + } + + /** + * @param obj TableColumn or ColumnGroup + */ + public void add(Object obj) { + if (obj == null) { + return; + } + v.addElement(obj); + } + + /** + * @param c TableColumn + * @param v ColumnGroups + */ + @SuppressWarnings("unchecked") + public Vector getColumnGroups(TableColumn c, Vector g) { + g.addElement(this); + if (v.contains(c)) + return g; + Enumeration enumeration = v.elements(); + while (enumeration.hasMoreElements()) { + Object obj = enumeration.nextElement(); + if (obj instanceof ColumnGroup) { + Vector groups = (Vector) ((ColumnGroup) obj).getColumnGroups(c, (Vector) g.clone()); + if (groups != null) + return groups; + } + } + return null; + } + + public TableCellRenderer getHeaderRenderer() { + return renderer; + } + + public Object getHeaderValue() { + return text; + } + + public int getSize() { + return v == null ? 0 : v.size(); + } + + public Dimension getSize(JTable table) { + Component comp = renderer.getTableCellRendererComponent(table, getHeaderValue(), false, false, -1, -1); + int height = comp.getPreferredSize().height; + int width = 0; + Enumeration enumeration = v.elements(); + while (enumeration.hasMoreElements()) { + Object obj = enumeration.nextElement(); + if (obj instanceof TableColumn) { + TableColumn aColumn = (TableColumn) obj; + width += aColumn.getWidth(); + width += margin; + } else { + width += ((ColumnGroup) obj).getSize(table).width; + } + } + return new Dimension(width, height); + } + + /** + * :(2003-7-14 10:53:26) + * @return java.lang.String + */ + public java.lang.String getText() { + return text; + } + + /** + * бͷɾColumn :(2002-9-25 15:49:00) + */ + public boolean removeColumn(ColumnGroup ptg, TableColumn tc) { + boolean retFlag = false; + if (tc != null) { + for (int i = 0; i < ptg.v.size(); i++) { + Object tmpObj = ptg.v.get(i); + if (tmpObj instanceof ColumnGroup) { + retFlag = removeColumn((ColumnGroup) tmpObj, tc); + // ҵ + if (retFlag) + break; + } else if (tmpObj instanceof TableColumn) { + // жǷҵĶ + if (tmpObj == tc) { + ptg.v.remove(i); + retFlag = true; + break; + } + } + } + } + return retFlag; + } + + /** + * бͷɾColumnGrp ɾtrue,򷵻false; :(2002-9-25 15:49:00) + */ + public boolean removeColumnGrp(ColumnGroup ptg, ColumnGroup tg) { + boolean retFlag = false; + if (tg != null) { + for (int i = 0; i < ptg.v.size(); i++) { + Object tmpObj = ptg.v.get(i); + if (tmpObj instanceof ColumnGroup) { + // жǷҵĶ + if (tmpObj == tg) { + ptg.v.remove(i); + retFlag = true; + break; + } else { + retFlag = removeColumnGrp((ColumnGroup) tmpObj, tg); + // ҵ + if (retFlag) + break; + + } + } else if (tmpObj instanceof TableColumn) { + break; + } + } + } + return retFlag; + } + + public void setColumnMargin(int margin) { + this.margin = margin; + Enumeration enumeration = v.elements(); + while (enumeration.hasMoreElements()) { + Object obj = enumeration.nextElement(); + if (obj instanceof ColumnGroup) { + ((ColumnGroup) obj).setColumnMargin(margin); + } + } + } + + public void setHeaderRenderer(TableCellRenderer renderer) { + if (renderer != null) { + this.renderer = renderer; + } + } + + /** + * :(2003-7-14 10:53:26) + * @param newText java.lang.String + */ + public void setText(java.lang.String newText) { + text = newText; + } +} diff --git a/src/com/connor/lidy/task/util/DataSetFinder.java b/src/com/connor/lidy/task/util/DataSetFinder.java new file mode 100644 index 0000000..eb7a580 --- /dev/null +++ b/src/com/connor/lidy/task/util/DataSetFinder.java @@ -0,0 +1,251 @@ +/* + #======================================================================================================= + # + # Copyright (c) 2007 Origin Enterprise Solution LTD. + # + #======================================================================================================= + # File description: ݼ + #======================================================================================================= + # Date Name Action Description of Change + # 20090301 Matt Shan Ini ݼ + #======================================================================================================= + */ +package com.connor.lidy.task.util; + +import java.io.File; + +import com.teamcenter.rac.kernel.TCAccessControlService; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentItem; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCComponentItemType; +import com.teamcenter.rac.kernel.TCComponentQuery; +import com.teamcenter.rac.kernel.TCComponentQueryType; +import com.teamcenter.rac.kernel.TCComponentTcFile; +import com.teamcenter.rac.kernel.TCComponentUser; +import com.teamcenter.rac.kernel.TCException; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.kernel.TCTextService; +import com.teamcenter.rac.util.MessageBox; + +public class DataSetFinder { + + private TCSession session = null; + + /** + * ݼ + * @param session ϵͳsession + */ + public DataSetFinder(TCSession pSession) { + queryType = null; + datasetQuery = null; + boolean flag = false; + try { + session = pSession; + its = session.getTextService(); + queryType = (TCComponentQueryType) session.getTypeComponent("ImanQuery"); + } + catch (TCException imane) { + imane.printStackTrace(); + imane.dump(); + } + try { + datasetQuery = (TCComponentQuery) queryType.find("ݼ..."); + } + catch (TCException imane) { + imane.printStackTrace(); + imane.dump(); + flag = true; + } + if (datasetQuery == null || flag) { + try { + datasetQuery = (TCComponentQuery) queryType.find(its.getTextValue("DataSet...")); + } + catch (TCException imane) { + imane.printStackTrace(); + imane.dump(); + } + } + } + + /** + * ѯݼ + * @param datasetname ݼ + * @return ݼƲѯݼ + */ + public TCComponentDataset FindDatasetByName(String datasetname, String pOwningUser, String pOwningGroup, String pDatasetType) { + System.out.println("-----------FindDatasetByName"); + try { + //String f_dataset_name[] = { its.getTextValue("Name"), its.getTextValue("OwningUser"), its.getTextValue("OwningGroup"), its.getTextValue("DatasetType") }; + String f_dataset_name[] = new String[4]; + f_dataset_name[0] = its.getTextValue("Name"); + if(f_dataset_name[0] == null){ + f_dataset_name[0] = "Name"; + } + f_dataset_name[1] = its.getTextValue("OwningUser"); + if(f_dataset_name[1] == null){ + f_dataset_name[1] = "Owning User"; + } + f_dataset_name[2] = its.getTextValue("OwningGroup"); + if(f_dataset_name[2] == null){ + f_dataset_name[2] = "Owning Group"; + } + f_dataset_name[3] = its.getTextValue("DatasetType"); + if(f_dataset_name[3] == null){ + f_dataset_name[3] = "Dataset Type"; + } + f_dataset_name_value = new String[4]; + f_dataset_name_value[0] = datasetname; + f_dataset_name_value[1] = pOwningUser; + f_dataset_name_value[2] = pOwningGroup; + f_dataset_name_value[3] = pDatasetType; + com.teamcenter.rac.kernel.TCComponent dataset[] = datasetQuery.execute(f_dataset_name, f_dataset_name_value); + if (dataset == null || dataset.length == 0) { + return null; + } else { + TCComponentDataset dataset0 = (TCComponentDataset) dataset[0]; + TCComponentDataset dataset1 = dataset0.latest(); + return dataset1; + } + } + catch (TCException imane) { + imane.printStackTrace(); + imane.dump(); + return null; + } + } + + /** + * ȡģݼ + * @param datasetname ݼ + * @return ݼƲѯݼ + */ + public TCComponentDataset FindDatasetByName(String datasetname) { + TCComponent[] components = null; + try { + TCComponentItemRevision revision =null; + TCComponentItemType tccomItemType = (TCComponentItemType) session.getTypeComponent("Item"); + TCComponentItem[]items =tccomItemType.findItems(datasetname); + if(items.length >0){ + revision=items[0].getLatestItemRevision() ; + } + components = revision.getRelatedComponents("IMAN_specification");// ͨϵҶ + for (TCComponent component : components) { + if (component instanceof TCComponentDataset) { + TCComponentDataset dataset = (TCComponentDataset) component; + return dataset; + } + } + } catch (TCException e) { + e.printStackTrace(); + return null; + } + return null; + } + + /** + * ݼļָ· + * @param dataset ݼ + * @param nameRef ݼ + * @param filename ļ + * @param dir · + * @return ļ + */ + public File ExportFileToDir(TCComponentDataset dataset, String nameRef, String filename, String dir) { + File exportFile = null; + try { + String workdir = dir; + File tFile = new File(workdir, filename); + if (tFile.exists()) + tFile.delete(); + if (!checkAccessPrivilige(session.getUser(), dataset, "EXPORT")) { + MessageBox.post("ûȨرģļ", "ʾ", MessageBox.WARNING); + return null; + } + TCComponentTcFile files[] = dataset.getTcFiles(); + if (files.length != 1) { + MessageBox.post("鱨ģļǷȷ", "ʾ", MessageBox.WARNING); + return null; + } + for (int i = 0; i < files.length; i++) { + exportFile = files[i].getFile(workdir, filename); + } + return exportFile; + } + catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + private boolean checkAccessPrivilige(TCComponentUser user, TCComponent comp, String accessName) throws TCException { + TCAccessControlService accessService = ((TCSession) session).getTCAccessControlService(); + boolean returnboolean = accessService.checkUsersPrivilege(user, comp, accessName); + return returnboolean; + } + + /** + * ݼļָ· + * @param dataset ݼ + * @param nameRef ݼ + * @param filename ļ + * @param dir · + * @return ļ + */ + public File ExportFileToDir(TCComponentDataset dataset, String filename, String dir) { + File exportFile = null; + try { + String workdir = dir; + File tFile = new File(workdir, filename); + if (tFile.exists()) + tFile.delete(); + if (!checkAccessPrivilige(session.getUser(), dataset, "EXPORT")) { + MessageBox.post("ûȨرģļ", "ʾ", MessageBox.WARNING); + return null; + } + TCComponentTcFile files[] = dataset.getTcFiles(); + if (files.length != 1) { + MessageBox.post("鱨ģļǷȷ", "ʾ", MessageBox.WARNING); + return null; + } + for (int i = 0; i < files.length; i++) { + exportFile = files[i].getFile(workdir, filename); + } + return exportFile; + } + catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public File ExportFileToDir(TCComponentDataset dataset, String dir) { + File exportFile = null; + try { + String workdir = dir; + if (!checkAccessPrivilige(session.getUser(), dataset, "EXPORT")) { + MessageBox.post("ûȨرģļ", "ʾ", MessageBox.WARNING); + return null; + } + TCComponentTcFile files[] = dataset.getTcFiles(); + if (files.length != 1) { + MessageBox.post("鱨ģļǷȷ", "ʾ", MessageBox.WARNING); + return null; + } + for (int i = 0; i < files.length; i++) { + exportFile = files[i].getFile(workdir); + } + return exportFile; + } + catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + private TCComponentQueryType queryType; + private TCComponentQuery datasetQuery; + private TCTextService its; + private String f_dataset_name_value[]; +} diff --git a/src/com/connor/lidy/task/util/GetAllUserIds.java b/src/com/connor/lidy/task/util/GetAllUserIds.java new file mode 100644 index 0000000..a4eb04a --- /dev/null +++ b/src/com/connor/lidy/task/util/GetAllUserIds.java @@ -0,0 +1,132 @@ +/* +#======================================================================================================= +# +# Copyright (c) 2007 Origin Enterprise Solution LTD. +# +#======================================================================================================= +# File description: GetAllUserIds.java +#======================================================================================================= +# Date time Name Action Description of Change +# 2011-1-17 03:51:32 tyl Ini ʼļ +#======================================================================================================= + */ +package com.connor.lidy.task.util; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.teamcenter.rac.aif.AbstractAIFUIApplication; +import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; +import com.teamcenter.rac.kernel.TCComponentContextList; +import com.teamcenter.rac.kernel.TCComponentQuery; +import com.teamcenter.rac.kernel.TCComponentQueryType; +import com.teamcenter.rac.kernel.TCComponentUser; +import com.teamcenter.rac.kernel.TCException; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.kernel.TCTextService; + +public class GetAllUserIds { + private AbstractAIFUIApplication pseapp; + /** + * TCжQuery + */ + private String findType = "__WEB_find_user"; + /** + * TCжQueryеûػ + */ + private String str_key = "UserId"; + /** + * TCжQueryбػȡֵ + */ + private String str_value = "*"; + /** + * װûϢ + */ + private List allUsers = null; + private Map userMap; + + public GetAllUserIds(AbstractAIFUIApplication app) { + System.out.println("_______________GetAllUserIds________"); + this.pseapp = app; + userMap = new HashMap(); + allUsers = new ArrayList(); + getAllUser(); + } + + /** + * getAllUser:ͨѯõеû + * @param @return 趨ļ + * @return String + * @throws + * @since CodingExampleVer 1.1 + */ + public void getAllUser() { + System.out.println("__________getAllUser__________"); + TCSession session = (TCSession) pseapp.getSession(); + InterfaceAIFComponent components[] = null; + TCComponentUser user = null; + try { + TCTextService textService = session.getTextService(); + TCComponentQueryType querytype = (TCComponentQueryType) session.getTypeComponent("ImanQuery"); + TCComponentQuery query = (TCComponentQuery) querytype.find(findType); + //querytype.clearCache(); + String as[] = { textService.getTextValue(str_key) }; + String as1[] = new String[1]; + as1[0] = str_value; + //query.clearCache(); + TCComponentContextList list = query.getExecuteResultsList(as, as1); + System.out.println("list = "+list); + if (list != null) { + int count = list.getListCount(); + System.out.println("count = " + count); + if(count > 0){ + components = new InterfaceAIFComponent[count]; + for (int i = 0; i < count; i++) { + if(list.get(i) != null){ + components[i] = list.get(i).getComponent(); + } + } + } + } else { + System.out.println("__WEB_find_user==null"); + } + } + catch (TCException e) { + e.printStackTrace(); + } + for (int i = 0; i < components.length; i++) { + if (components[i] instanceof TCComponentUser) { + user = (TCComponentUser) components[i]; + try { + String userid = user.getUserId().toString(); + String userName = user.getProperty("user_name"); + userMap.put(userid + "(" + userName + ")", user.toString()); + allUsers.add(userid + "(" + userName + ")"); + } + catch (TCException e) { + e.printStackTrace(); + } + } + } + } + + private static List userIDs = new ArrayList(); + + public static synchronized void setUsers(List users) { + userIDs = users; + } + + public static synchronized List getUsers() { + return userIDs; + } + + public List getAllUsers() { + return allUsers; + } + + public Map getUserMap() { + return userMap; + } +} diff --git a/src/com/connor/lidy/task/util/GetChoosePath.java b/src/com/connor/lidy/task/util/GetChoosePath.java new file mode 100644 index 0000000..422f629 --- /dev/null +++ b/src/com/connor/lidy/task/util/GetChoosePath.java @@ -0,0 +1,100 @@ +/* +#======================================================================================================= +# +# Copyright (c) 2007 Origin Enterprise Solution LTD. +# +#======================================================================================================= +# File description: GetChoosePath.java +#======================================================================================================= +# Date time Name Action Description of Change +# 2011-1-17 03:45:21 tyl Ini ʼļ +#======================================================================================================= +*/ +package com.connor.lidy.task.util; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStreamReader; + +import javax.swing.JFileChooser; + +public class GetChoosePath { + + public String getPath(String filename) { + String tempPath = System.getProperty("java.io.tmpdir"); + File tempFile = new File(tempPath + filename); + JFileChooser jfc = null; + if (!tempFile.exists()) { + try { + tempFile.createNewFile(); + jfc = new JFileChooser(); + } catch (IOException e) { + e.printStackTrace(); + } + } else { + if (tempFile.exists()) { + BufferedReader in; + try { + in = new BufferedReader(new InputStreamReader(new FileInputStream(tempFile))); + String line; + try { + line = in.readLine(); + if ((line != null) && (line.length() > 0)) { + File file = new File(line); + if (file.exists()) { + jfc = new JFileChooser(file); + } else { + jfc = new JFileChooser(); + } + } else { + jfc = new JFileChooser(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } catch (FileNotFoundException e1) { + e1.printStackTrace(); + } + } + } + jfc.setFileSelectionMode(JFileChooser.SAVE_DIALOG); + jfc.setInheritsPopupMenu(true); +// jfc.setDialogTitle("..."); + jfc.setMultiSelectionEnabled(false); + + jfc.setFileFilter(new javax.swing.filechooser.FileFilter() { + @Override + public boolean accept(File f) { + if (f.isDirectory()) + return true; + else + return false; + } + + @Override + public String getDescription() { + return null;//дļ + } + }); + + int openOrCancel = jfc.showSaveDialog(null); + if (openOrCancel == 0) { + try { + BufferedWriter output; + output = new BufferedWriter(new FileWriter(tempFile)); + output.write(jfc.getSelectedFile().getAbsolutePath()); + output.close(); + } catch (IOException e1) { + e1.printStackTrace(); + } + File file = jfc.getSelectedFile(); + return file.getAbsolutePath(); + } + return ""; + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/task/util/GetCommonInfo.java b/src/com/connor/lidy/task/util/GetCommonInfo.java new file mode 100644 index 0000000..b7fe226 --- /dev/null +++ b/src/com/connor/lidy/task/util/GetCommonInfo.java @@ -0,0 +1,165 @@ +/* +#============================================================================= +# +# copyright (c) 2009 Origin Enterprise Solution LTD. +# +#============================================================================= +# File name: GetCommonInfo.java +# File description: +#============================================================================= +# Date Name Action Description of Change +# 2011-4-20 liqz õһЩͨϢ(From shangu) +#============================================================================= + */ +package com.connor.lidy.task.util; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileWriter; +import java.io.InputStreamReader; + +import javax.swing.JFileChooser; + +import com.teamcenter.rac.kernel.TCAccessControlService; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentUser; +import com.teamcenter.rac.kernel.TCException; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +public class GetCommonInfo { + private TCSession session; + + public GetCommonInfo(TCSession session) { + this.session = session; + + } + + /** + * getChoosePath:õûѡ· + * @param @return 趨ļ + * @return String + * @throws + * @since CodingExampleVer 1.1 + */ + public String getChoosePath() { + String tempPath = System.getProperty("java.io.tmpdir"); + String currentPath = ""; + BufferedReader in = null; + try { + File file1 = new File(tempPath + "\\export.txt"); + JFileChooser jfc = null; + if (file1.exists()) { + in = new BufferedReader(new InputStreamReader(new FileInputStream(file1))); + String line = in.readLine(); + if (line != null) { + jfc = new JFileChooser(new File(line)); + } else { + jfc = new JFileChooser(); + } + } else { + jfc = new JFileChooser(); + } + + jfc.setFileSelectionMode(JFileChooser.SAVE_DIALOG); + int openOrCann = jfc.showSaveDialog(null); + if (openOrCann == 1) { + return currentPath; + } + // 洢ûѡ· + File file2 = new File(tempPath + "\\export.txt"); + if (!file2.exists()) { + file2.createNewFile(); + } + try { + BufferedWriter output = new BufferedWriter(new FileWriter(file2)); + output.write(jfc.getSelectedFile().getAbsolutePath()); + output.close(); + currentPath = jfc.getSelectedFile().getAbsolutePath(); + } catch (Exception e) { + e.printStackTrace(); + } + + } catch (Exception e) { + e.printStackTrace(); + }finally { + if(in != null) + try { + in.close(); + } catch (Exception e) { + // Auto-generated catch block + e.printStackTrace(); + } + } + return currentPath; + } + + public boolean isExistFiles(String path) { + boolean flag = false; + File file = new File(path); + if (file.isDirectory()) { + if (file.listFiles().length > 0) { + flag = true; + } + } + return flag; + } + + /** + * existFile:жļǷ + * @param @return 趨ļ + * @return String + * @throws + * @since CodingExampleVer 1.1 + */ + public boolean existFile(String filePath, String fileName) { + boolean exist = false; + try { + if (fileName.indexOf('/') >= 0) { + fileName = fileName.replace('/', '_'); + } + File file = new File(filePath + "\\" + fileName); + System.out.println("filePath_fileName:" + filePath + "\\" + fileName); + if (file.exists()) { + exist = true; + } + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post("ڼļǷڵʱ򣬳ִ", "ERROR", MessageBox.ERROR); + } + return exist; + } + + /** + * ǷѾ + * @param tccomponent + * @return Ƿ񷢲 + */ + public boolean isReleased(TCComponent tccomponent) { + boolean flag = false; + try { + String s = tccomponent.getProperty("release_status_list"); + if (s != null && s.length() > 0) + flag = true; + } catch (TCException tcexception) { + flag = false; + } + return flag; + } + + /** + * existFile:ǷȨ + * @param @return 趨ļ + * @return String + * @throws + * @since CodingExampleVer 1.1 + */ + public boolean checkAccessPrivilige(TCComponentUser user, TCComponent comp, String accessName) throws TCException { + TCAccessControlService accessService = ((TCSession) session).getTCAccessControlService(); + boolean returnboolean = accessService.checkUsersPrivilege(user, comp, accessName); + return returnboolean; + } + +} diff --git a/src/com/connor/lidy/task/util/GetMessageDialog.java b/src/com/connor/lidy/task/util/GetMessageDialog.java new file mode 100644 index 0000000..7b88670 --- /dev/null +++ b/src/com/connor/lidy/task/util/GetMessageDialog.java @@ -0,0 +1,91 @@ +/* +#======================================================================================================= +# +# Copyright (c) 2007 Origin Enterprise Solution LTD. +# +#======================================================================================================= +# File description: GetMessageDialog.java +#======================================================================================================= +# Date time Name Action Description of Change +# 2011-1-17 04:01:59 tyl Ini ʼļ +#======================================================================================================= +*/ +package com.connor.lidy.task.util; + +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.net.URL; + +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JPanel; + +import com.teamcenter.rac.aif.AbstractAIFDialog; +import com.teamcenter.rac.util.PropertyLayout; +import com.teamcenter.rac.util.Separator; +import com.teamcenter.rac.util.VerticalLayout; + +public class GetMessageDialog extends AbstractAIFDialog { + /** + * serialVersionUID:TODOһ仰ʾʲô + * @since Ver 1.1 + */ + + private static final long serialVersionUID = 1L; + private int value = 0; + private String title = ""; + private String info = ""; + + public GetMessageDialog(String title, String info) { + super(true); + this.title=title; + this.info=info; + this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); + } + + public int getValue() { + setPersistentDisplay(true); + setOptimalDisplay(false); + setTitle(title); + JPanel parentPanel; + JPanel itemInfoPanel; + parentPanel = new JPanel(new VerticalLayout(5, 2, 2, 2, 2)); + itemInfoPanel = new JPanel(new PropertyLayout()); + + URL url=this.getClass().getResource("image/info.png"); + JLabel iconLabel=new JLabel(); + iconLabel.setIcon(new ImageIcon(url)); + + itemInfoPanel.add("1.1.left.center",iconLabel); + itemInfoPanel.add("1.2.left.center",new JLabel(info)); + JButton buttonYes = new JButton(""); + buttonYes.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + value = 0; + GetMessageDialog.this.dispose(); + } + }); + JButton buttonNo = new JButton(""); + buttonNo.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + value = 1; + GetMessageDialog.this.dispose(); + } + }); + JPanel panelButton = new JPanel(new FlowLayout()); + panelButton.add(buttonYes); + panelButton.add(buttonNo); + parentPanel.add("top.bin", new Separator()); + parentPanel.add("top.bind.left.top", itemInfoPanel); + parentPanel.add("bottom.nobind.center.top", panelButton); + getContentPane().add(parentPanel); + pack(); + Dimension screen = getToolkit().getScreenSize(); // õĻߴ + setLocation((screen.width - getSize().width) / 2, (screen.height - getSize().height) / 2); + setVisible(true); + return value; + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/task/util/GetMessagePromptDialog.java b/src/com/connor/lidy/task/util/GetMessagePromptDialog.java new file mode 100644 index 0000000..1baf099 --- /dev/null +++ b/src/com/connor/lidy/task/util/GetMessagePromptDialog.java @@ -0,0 +1,106 @@ +/* +#======================================================================================================= +# +# Copyright (c) 2007 Origin Enterprise Solution LTD. +# +#======================================================================================================= +# File description: GetMessagePromptDialog.java +#======================================================================================================= +# Date Name Action Description of Change +# 2009-11-13 tyl Ϣʾ +#======================================================================================================= + */ +package com.connor.lidy.task.util; + +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.net.URL; + +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JPanel; + +import com.teamcenter.rac.aif.AbstractAIFDialog; +import com.teamcenter.rac.util.PropertyLayout; +import com.teamcenter.rac.util.VerticalLayout; + +public class GetMessagePromptDialog extends AbstractAIFDialog { + + /** + * serialVersionUID:TODOһ仰ʾʲô + * @since Ver 1.1 + */ + + private static final long serialVersionUID = 1L; + private String title; + private String info; + private String info2; + private int value = 1; + + /** + * Creates a new instance of PromptDialog. + */ + + public GetMessagePromptDialog(String title, String info) { + super(true); + this.title = title; + this.info = info; + } + + public GetMessagePromptDialog(String title, String info, String info2) { + super(true); + this.title = title; + this.info = info; + this.info2 = info2; + } + + // ؾ + public int getValue() { + setPersistentDisplay(true); + setOptimalDisplay(false); + setTitle(title); + + JPanel parentPanel; + JPanel itemInfoPanel; + parentPanel = new JPanel(new VerticalLayout(5, 2, 2, 2, 2)); + itemInfoPanel = new JPanel(new PropertyLayout()); + URL url = this.getClass().getResource("image/info.png"); + JLabel iconLabel = new JLabel(); + iconLabel.setIcon(new ImageIcon(url)); + + itemInfoPanel.add("1.1.left.center", iconLabel); + itemInfoPanel.add("1.2.left.center", new JLabel(info)); + itemInfoPanel.add("2.1.left.center", new JLabel(" ")); + itemInfoPanel.add("2.2.left.center", new JLabel(info2)); + JButton buttonYes = new JButton(""); + buttonYes.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + value = 0; + GetMessagePromptDialog.this.dispose(); + } + }); + JButton buttonNo = new JButton(""); + buttonNo.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + value = 1; + GetMessagePromptDialog.this.dispose(); + } + }); + JPanel panelButton = new JPanel(new FlowLayout()); + panelButton.add(buttonYes); + panelButton.add(buttonNo); + parentPanel.add("top.bin", new JLabel(" ")); + parentPanel.add("top.bind.left.top", itemInfoPanel); + parentPanel.add("bottom.nobind.center.top", panelButton); + getContentPane().add(parentPanel); + pack(); + Dimension screen = getToolkit().getScreenSize(); // õĻߴ + setLocation((screen.width - getSize().width) / 2, (screen.height - getSize().height) / 2); + setVisible(true); + return value; + } + +} diff --git a/src/com/connor/lidy/task/util/GroupableTableHeader.java b/src/com/connor/lidy/task/util/GroupableTableHeader.java new file mode 100644 index 0000000..223c979 --- /dev/null +++ b/src/com/connor/lidy/task/util/GroupableTableHeader.java @@ -0,0 +1,90 @@ +package com.connor.lidy.task.util; + + +import java.util.Enumeration; +import java.util.Vector; + +import javax.swing.table.JTableHeader; +import javax.swing.table.TableColumn; +import javax.swing.table.TableColumnModel; + + + +/** + * GroupableTableHeader + * @author flyx + */ + +public class GroupableTableHeader extends JTableHeader { + /** + * + */ + private static final long serialVersionUID = 1L; +// private static final String uiClassID = "GroupableTableHeaderUI"; + protected Vector columnGroups = null; + public GroupableTableHeader(TableColumnModel model) { + super(model); + setUI(new GroupableTableHeaderUI()); + setReorderingAllowed(false); + setRequestFocusEnabled(false); + } +public void addColumnGroup(ColumnGroup g) { + if (columnGroups == null) { + columnGroups = new Vector<>(); + } + columnGroups.addElement(g); +} +/** + * + * :(2001-8-31 15:54:29) + */ +public void clearColumnGroups() { + columnGroups = null; +} +public ColumnGroup[] getColumnGroups() { + ColumnGroup[] retg=null; + if (columnGroups.size()>0) { + retg=new ColumnGroup[columnGroups.size()]; + columnGroups.copyInto(retg); + } + return retg; +} +public Enumeration getColumnGroups(TableColumn col) { + if (columnGroups == null) + return null; + Enumeration enumi = columnGroups.elements(); + while (enumi.hasMoreElements()) { + ColumnGroup cGroup = (ColumnGroup) enumi.nextElement(); + Vector v_ret = (Vector) cGroup.getColumnGroups(col, new Vector<>()); + if (v_ret != null) { + return v_ret.elements(); + } + } + return null; +} +/** + * Identifies whether or not this component can receive the focus. + * A disabled button, for example, would return false. + * + * @return true if this component can receive the focus + */ +@SuppressWarnings("deprecation") +public boolean isFocusTraversable() { + return super.isFocusTraversable() && isRequestFocusEnabled(); +} +public void setColumnMargin() { + if (columnGroups == null) + return; + int columnMargin = getColumnModel().getColumnMargin(); + Enumeration enumi = columnGroups.elements(); + while (enumi.hasMoreElements()) { + ColumnGroup cGroup = (ColumnGroup) enumi.nextElement(); + cGroup.setColumnMargin(columnMargin); + } +} +public void setReorderingAllowed(boolean b) { + reorderingAllowed = b; +} +} + + diff --git a/src/com/connor/lidy/task/util/GroupableTableHeaderUI.java b/src/com/connor/lidy/task/util/GroupableTableHeaderUI.java new file mode 100644 index 0000000..34ae504 --- /dev/null +++ b/src/com/connor/lidy/task/util/GroupableTableHeaderUI.java @@ -0,0 +1,255 @@ +package com.connor.lidy.task.util; + + +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Graphics; +import java.awt.Rectangle; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Vector; + +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JTable; +import javax.swing.UIManager; +import javax.swing.plaf.basic.BasicTableHeaderUI; +import javax.swing.table.*; + +/** + * ͷTableHeaderUI + * + * @author flyx + */ +public class GroupableTableHeaderUI extends BasicTableHeaderUI { + private int m_height; + + private Dimension createHeaderSize(long width) { + TableColumnModel columnModel = header.getColumnModel(); + width += columnModel.getColumnMargin() * columnModel.getColumnCount(); + if (width > Integer.MAX_VALUE) { + width = Integer.MAX_VALUE; + } + return new Dimension((int) width, getHeaderHeight()); + } + + /** + * øöͷµĻ(zjb) ݹ :(02-4-8 18:03:56) + * + * @return int + * @param cg + * nc.ui.pub.beans.table.ColumnGroup + */ + private int getColCountUnderColGroup(ColumnGroup cg, int iCount) { + Vector v = cg.v; + for (int i = 0; i < v.size(); i++) { + Object obj = v.elementAt(i); + if (obj instanceof ColumnGroup) + iCount = getColCountUnderColGroup((ColumnGroup) obj, iCount); + else + iCount++; + } + return iCount; + } + + public int getHeaderHeight() { + int height = 0; + TableColumnModel columnModel = header.getColumnModel(); + for (int column = 0; column < columnModel.getColumnCount(); column++) { + TableColumn aColumn = columnModel.getColumn(column); + TableCellRenderer renderer = aColumn.getHeaderRenderer(); + // + if (renderer == null) { + renderer = new DefaultTableCellRenderer() { + /** + * + */ + private static final long serialVersionUID = 1L; + + public Component getTableCellRendererComponent( + JTable table, Object value, boolean isSelected, + boolean hasFocus, int row, int column) { + JTableHeader header = table.getTableHeader(); + if (header != null) { + setForeground(header.getForeground()); + setBackground(header.getBackground()); + setFont(header.getFont()); + } + setHorizontalAlignment(JLabel.CENTER); + setText((value == null) ? "" : value.toString()); + setBorder(UIManager.getBorder("TableHeader.cellBorder")); + return this; + } + }; + } + // + Component comp = renderer.getTableCellRendererComponent(header + .getTable(), aColumn.getHeaderValue(), false, false, -1, + column); + int cHeight = comp.getPreferredSize().height; + Enumeration enumeration = ((GroupableTableHeader) header).getColumnGroups(aColumn); + if (enumeration != null) { + while (enumeration.hasMoreElements()) { + ColumnGroup cGroup = (ColumnGroup) enumeration + .nextElement(); + cHeight += cGroup.getSize(header.getTable()).height; + } + } + height = Math.max(height, cHeight); + } + height = Math.max(height, m_height); + return height; + } + + public Dimension getPreferredSize(JComponent c) { + long width = 0; + Enumeration enumeration = header.getColumnModel().getColumns(); + while (enumeration.hasMoreElements()) { + TableColumn aColumn = (TableColumn) enumeration.nextElement(); + width = width + aColumn.getWidth(); + } + + return createHeaderSize(width); + } + + public void paint(Graphics g, JComponent c) { + Rectangle clipBounds = g.getClipBounds(); + if (header.getColumnModel() == null) + return; + ((GroupableTableHeader) header).setColumnMargin(); + int column = 0; + Dimension size = header.getSize(); + Rectangle cellRect = new Rectangle(0, 0, size.width, size.height); + Hashtable h = new Hashtable<>(); + int columnMargin = header.getColumnModel().getColumnMargin(); + Enumeration enumeration = header.getColumnModel().getColumns(); + while (enumeration.hasMoreElements()) { + cellRect.height = size.height; + cellRect.y = 0; + TableColumn aColumn = (TableColumn) enumeration.nextElement(); + Enumeration cGroups = ((GroupableTableHeader) header).getColumnGroups(aColumn); + if (cGroups != null) { + int groupHeight = 0; + while (cGroups.hasMoreElements()) { + ColumnGroup cGroup = (ColumnGroup) cGroups.nextElement(); + Rectangle groupRect = (Rectangle) h.get(cGroup); + if (groupRect == null) { + groupRect = new Rectangle(cellRect); + Dimension d = cGroup.getSize(header.getTable()); + if (!System.getProperty("java.vm.version").startsWith( + "1.2")) { + int iColCount = getColCountUnderColGroup(cGroup, 0); // øöͷµĻ(zjb) + // System.out.println(iColCount); + groupRect.width = d.width - iColCount + * columnMargin; + } else + groupRect.width = d.width; + groupRect.height = d.height; + h.put(cGroup, groupRect); + } + paintCell(g, groupRect, cGroup); + groupHeight += groupRect.height; + cellRect.height = size.height - groupHeight; + cellRect.y = groupHeight; + } + } + if (!System.getProperty("java.vm.version").startsWith("1.2")) + cellRect.width = aColumn.getWidth(); + else + cellRect.width = aColumn.getWidth() + columnMargin; + + if (cellRect.intersects(clipBounds)) { + paintCell(g, cellRect, column); + } + cellRect.x += cellRect.width; + column++; + } + } + + private void paintCell(Graphics g, Rectangle cellRect, int columnIndex) { + TableColumn aColumn = header.getColumnModel().getColumn(columnIndex); + TableCellRenderer renderer = aColumn.getHeaderRenderer(); + // + if (renderer == null) { + renderer = new DefaultTableCellRenderer() { + /** + * + */ + private static final long serialVersionUID = 1L; + + public Component getTableCellRendererComponent(JTable table, + Object value, boolean isSelected, boolean hasFocus, + int row, int column) { + JTableHeader header = table.getTableHeader(); + if (header != null) { + setForeground(header.getForeground()); + setBackground(header.getBackground()); + setFont(header.getFont()); + } + setHorizontalAlignment(JLabel.CENTER); + setText((value == null) ? "" : value.toString()); + setBorder(UIManager.getBorder("TableHeader.cellBorder")); + return this; + } + }; + } + // + // Component component = + // renderer.getTableCellRendererComponent(header.getTable(), + // aColumn.getHeaderValue(), false, false, -1, columnIndex); + // + String headerValue = aColumn.getHeaderValue().toString(); + Component component = renderer.getTableCellRendererComponent(header + .getTable(), headerValue, false, false, -1, columnIndex); + + rendererPane.add(component); + rendererPane.paintComponent(g, component, header, cellRect.x, + cellRect.y, cellRect.width, cellRect.height, true); + } + + private void paintCell(Graphics g, Rectangle cellRect, ColumnGroup cGroup) { + TableCellRenderer renderer = cGroup.getHeaderRenderer(); + // + if (renderer == null) { + renderer = new DefaultTableCellRenderer() { + /** + * + */ + private static final long serialVersionUID = 1L; + + public Component getTableCellRendererComponent(JTable table, + Object value, boolean isSelected, boolean hasFocus, + int row, int column) { + JTableHeader header = table.getTableHeader(); + if (header != null) { + setForeground(header.getForeground()); + setBackground(header.getBackground()); + setFont(header.getFont()); + } + setHorizontalAlignment(JLabel.CENTER); + setText((value == null) ? "" : value.toString()); + setBorder(UIManager.getBorder("TableHeader.cellBorder")); + return this; + } + }; + } + // + // Component component = + // renderer.getTableCellRendererComponent(header.getTable(), + // cGroup.getHeaderValue(), false, false, -1, -1); + // + String headerValue = cGroup.getHeaderValue().toString(); + Component component = renderer.getTableCellRendererComponent(header + .getTable(), headerValue, false, false, -1, -1); + + rendererPane.add(component); + rendererPane.paintComponent(g, component, header, cellRect.x, + cellRect.y, cellRect.width, cellRect.height, true); + } + + public void setHeaderHeight(int iHeight) { + m_height = iHeight; + } +} + + diff --git a/src/com/connor/lidy/task/util/PackFailDownInfo.java b/src/com/connor/lidy/task/util/PackFailDownInfo.java new file mode 100644 index 0000000..a5c70cb --- /dev/null +++ b/src/com/connor/lidy/task/util/PackFailDownInfo.java @@ -0,0 +1,151 @@ +/* +#============================================================================= +# +# Copyright (c) 2009 Origin Enterprise Solution LTD. +# +#============================================================================= +# File name: PackFailDownInfo.java +# File description: +#============================================================================= +# Date Name Action Description of Change +# 2011-4-20 liqz Ini ʼ(From Shaangu) +#============================================================================= +*/ +package com.connor.lidy.task.util; + +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentItemRevision; + +public class PackFailDownInfo { + private TCComponentItemRevision itemRev=null; + private String itemId; + private String rev; + private String datasetName; + private String reference_file; + private TCComponentDataset dataSet; + private String filePath=""; + private String reason=""; + private String owner=""; + private String needDown="false"; + /** + * @return the owner + */ + public String getOwner() { + return owner; + } + /** + * @return the itemRev + */ + public TCComponentItemRevision getItemRev() { + return itemRev; + } + /** + * @param itemRev the itemRev to set + */ + public void setItemRev(TCComponentItemRevision itemRev) { + this.itemRev = itemRev; + } + /** + * @param owner the owner to set + */ + public void setOwner(String owner) { + this.owner = owner; + } + /** + * @return the itemId + */ + public String getItemId() { + return itemId; + } + /** + * @param itemId the itemId to set + */ + public void setItemId(String itemId) { + this.itemId = itemId; + } + /** + * @return the rev + */ + public String getRev() { + return rev; + } + /** + * @param rev the rev to set + */ + public void setRev(String rev) { + this.rev = rev; + } + /** + * @return the datasetName + */ + public String getDatasetName() { + return datasetName; + } + /** + * @param datasetName the datasetName to set + */ + public void setDatasetName(String datasetName) { + this.datasetName = datasetName; + } + /** + * @return the reference_file + */ + public String getReference_file() { + return reference_file; + } + /** + * @param reference_file the reference_file to set + */ + public void setReference_file(String reference_file) { + this.reference_file = reference_file; + } + /** + * @return the dataSet + */ + public TCComponentDataset getDataSet() { + return dataSet; + } + /** + * @param dataSet the dataSet to set + */ + public void setDataSet(TCComponentDataset dataSet) { + this.dataSet = dataSet; + } + /** + * @return the filePath + */ + public String getFilePath() { + return filePath; + } + /** + * @param filePath the filePath to set + */ + public void setFilePath(String filePath) { + this.filePath = filePath; + } + /** + * @return the reason + */ + public String getReason() { + return reason; + } + /** + * @param reason the reason to set + */ + public void setReason(String reason) { + this.reason = reason; + } + /** + * @return the needDown + */ + public String getNeedDown() { + return needDown; + } + /** + * @param needDown the needDown to set + */ + public void setNeedDown(String needDown) { + this.needDown = needDown; + } + +} diff --git a/src/com/connor/lidy/task/util/PackResultInfo.java b/src/com/connor/lidy/task/util/PackResultInfo.java new file mode 100644 index 0000000..019fd98 --- /dev/null +++ b/src/com/connor/lidy/task/util/PackResultInfo.java @@ -0,0 +1,203 @@ +/* +#============================================================================= +# +# Copyright (c) 2009 Origin Enterprise Solution LTD. +# +#============================================================================= +# File name: PackResultInfo.java +# File description: +#============================================================================= +# Date Name Action Description of Change +# 2011-4-20 liqz Ini ʼ(From Shaangu) +#============================================================================= + */ +package com.connor.lidy.task.util; + +import java.util.List; + +public class PackResultInfo { + + // ʱ䣺2010-06-15:8890 ˣXXXXXX, ѡ̣Ŀ¼XXXXXXXXXX + + private String time = ""; + private String person = ""; + private String job = ""; + private int needNum = 0; + private int successNum = 0; + private int failNum = 0; + private int noReferenceNum = 0; + private int noPrivilegelNum = 0; + private int equalNameNum = 0; + private int noReleasedNum = 0; + private int existDataSetCount = 0; + private List failDownInfo = null; + + /** + * @return the time + */ + public String getTime() { + return time; + } + + /** + * @param time the time to set + */ + public void setTime(String time) { + this.time = time; + } + + /** + * @return the person + */ + public String getPerson() { + return person; + } + + /** + * @param person the person to set + */ + public void setPerson(String person) { + this.person = person; + } + + /** + * @return the job + */ + public String getJob() { + return job; + } + + /** + * @param job the job to set + */ + public void setJob(String job) { + this.job = job; + } + + /** + * @return the needNum + */ + public int getNeedNum() { + return needNum; + } + + /** + * @param needNum the needNum to set + */ + public void setNeedNum(int needNum) { + this.needNum = needNum; + } + + /** + * @return the successNum + */ + public int getSuccessNum() { + return successNum; + } + + /** + * @param successNum the successNum to set + */ + public void setSuccessNum(int successNum) { + this.successNum = successNum; + } + + /** + * @return the failNum + */ + public int getFailNum() { + return failNum; + } + + /** + * @param failNum the failNum to set + */ + public void setFailNum(int failNum) { + this.failNum = failNum; + } + + /** + * @return the noReferenceNum + */ + public int getNoReferenceNum() { + return noReferenceNum; + } + + /** + * @param noReferenceNum the noReferenceNum to set + */ + public void setNoReferenceNum(int noReferenceNum) { + this.noReferenceNum = noReferenceNum; + } + + /** + * @return the noPrivilegelNum + */ + public int getNoPrivilegelNum() { + return noPrivilegelNum; + } + + /** + * @param noPrivilegelNum the noPrivilegelNum to set + */ + public void setNoPrivilegelNum(int noPrivilegelNum) { + this.noPrivilegelNum = noPrivilegelNum; + } + + /** + * @return the equalNameNum + */ + public int getEqualNameNum() { + return equalNameNum; + } + + /** + * @param equalNameNum the equalNameNum to set + */ + public void setEqualNameNum(int equalNameNum) { + this.equalNameNum = equalNameNum; + } + + /** + * @return the noReleasedNum + */ + public int getNoReleasedNum() { + return noReleasedNum; + } + + /** + * @param noReleasedNum the noReleasedNum to set + */ + public void setNoReleasedNum(int noReleasedNum) { + this.noReleasedNum = noReleasedNum; + } + + /** + * @return the failDownInfo + */ + public List getFailDownInfo() { + return failDownInfo; + } + + /** + * @param failDownInfo the failDownInfo to set + */ + public void setFailDownInfo(List failDownInfo) { + this.failDownInfo = failDownInfo; + } + + /** + * @return the existDataSetCount + */ + public int getExistDataSetCount() { + return existDataSetCount; + } + + /** + * @param existDataSetCount the existDataSetCount to set + */ + public void setExistDataSetCount(int existDataSetCount) { + this.existDataSetCount = existDataSetCount; + } + +} diff --git a/src/com/connor/lidy/task/util/PackSuccessfulInfo.java b/src/com/connor/lidy/task/util/PackSuccessfulInfo.java new file mode 100644 index 0000000..6fa6760 --- /dev/null +++ b/src/com/connor/lidy/task/util/PackSuccessfulInfo.java @@ -0,0 +1,108 @@ +/* +#============================================================================= +# +# opyright (c) 2009 Origin Enterprise Solution LTD. +# +#============================================================================= +# File name: PackSuccessfulInfo.java +# File description: +#============================================================================= +# Date Name Action Description of Change +# 2011-4-20 liqz Ini ʼ(From Shaangu) +#============================================================================= + */ +package com.connor.lidy.task.util; + +public class PackSuccessfulInfo { + private String index = ""; + private String itemID = ""; + private String itemRev = ""; + private String itemOwner = ""; + private String dataset = ""; + private String refFile = ""; + + /** + * @return the index + */ + public String getIndex() { + return index; + } + + /** + * @param index the index to set + */ + public void setIndex(String index) { + this.index = index; + } + + /** + * @return the itemID + */ + public String getItemID() { + return itemID; + } + + /** + * @param itemID the itemID to set + */ + public void setItemID(String itemID) { + this.itemID = itemID; + } + + /** + * @return the itemRev + */ + public String getItemRev() { + return itemRev; + } + + /** + * @param itemRev the itemRev to set + */ + public void setItemRev(String itemRev) { + this.itemRev = itemRev; + } + + /** + * @return the itemOwner + */ + public String getItemOwner() { + return itemOwner; + } + + /** + * @param itemOwner the itemOwner to set + */ + public void setItemOwner(String itemOwner) { + this.itemOwner = itemOwner; + } + + /** + * @return the dataset + */ + public String getDataset() { + return dataset; + } + + /** + * @param dataset the dataset to set + */ + public void setDataset(String dataset) { + this.dataset = dataset; + } + + /** + * @return the refFile + */ + public String getRefFile() { + return refFile; + } + + /** + * @param refFile the refFile to set + */ + public void setRefFile(String refFile) { + this.refFile = refFile; + } + +} diff --git a/src/com/connor/lidy/task/util/QueryTaskOpinionTableHead.java b/src/com/connor/lidy/task/util/QueryTaskOpinionTableHead.java new file mode 100644 index 0000000..ccbf89a --- /dev/null +++ b/src/com/connor/lidy/task/util/QueryTaskOpinionTableHead.java @@ -0,0 +1,214 @@ +/* +#======================================================================================================= +# +# Copyright (c) 2007 Origin Enterprise Solution LTD. +# +#======================================================================================================= +# File description: test.java +#======================================================================================================= +# Date Name Action Description of Change +# 2010-1-6 tyl ޸ +# 2010-4-25 zyn ޸ ʾģʽ޸Ϊʾģʽ +#======================================================================================================= + */ + +package com.connor.lidy.task.util; + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Cursor; +import java.awt.Dimension; +import java.awt.GridLayout; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.util.Vector; + +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSplitPane; +import javax.swing.JTable; +import javax.swing.JTextArea; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; +import javax.swing.plaf.SplitPaneUI; +import javax.swing.plaf.basic.BasicSplitPaneUI; +import javax.swing.table.DefaultTableModel; +import javax.swing.table.TableCellRenderer; +import javax.swing.table.TableColumn; +import javax.swing.table.TableColumnModel; + +//import components.TableDemo; + +public class QueryTaskOpinionTableHead extends JPanel { + /** + * serialVersionUID:Ĺܣ + * @since Ver 1.1 + */ + private static final long serialVersionUID = 1L; + private Object[][] objArray; // е + private DefaultTableModel dm; + private JTable table; + private JTextArea textarea; +// private String[] headers = { "","", "" , "ǩ","ִ","ύʱ","ע"}; + private String[] headers = { "", "", "ǩ", "ִ", "ʼʱ", "ʱ", "ע" }; + + public QueryTaskOpinionTableHead() { + super(new GridLayout(1, 0)); + } + + // ϱ + public void setTableHeadTestModel(Vector titleArrayTemp) { + dm = new DefaultTableModel(objArray, headers); + table = new JTable(dm); + textarea = new JTextArea(15,35); + textarea.setAutoscrolls(true); + textarea.setLineWrap(true); + textarea.setEditable(false); + textarea.addMouseListener(new MouseAdapter() { + public void mouseEntered(MouseEvent mouseEvent) { + textarea.setCursor(new Cursor(Cursor.TEXT_CURSOR)); //TextΪıָ + } + public void mouseExited(MouseEvent mouseEvent) { + textarea.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); //뿪TextָĬ̬ + } + }); + textarea.getCaret().addChangeListener(new ChangeListener() { + public void stateChanged(ChangeEvent e) { + textarea.getCaret().setVisible(true); //ʹtextareaıʾ + } + }); + + GroupableTableHeader header = new GroupableTableHeader(table.getColumnModel()); + + table.setTableHeader(header); + table.setPreferredScrollableViewportSize(new Dimension(820, 150)); + addListener(); + + JScrollPane scrollPane = new JScrollPane(table); + + JPanel jpane = new JPanel(new BorderLayout()); + jpane.add(new JLabel("ע:"), BorderLayout.NORTH); + jpane.add(textarea, BorderLayout.CENTER); + + JSplitPane splitPane = new JSplitPane(); + splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT); + splitPane.setLeftComponent(scrollPane); + splitPane.setRightComponent(jpane); + splitPane.setDividerLocation(0.6); + splitPane.setEnabled(false); + SplitPaneUI ui = splitPane.getUI(); + if (ui instanceof BasicSplitPaneUI) { + ((BasicSplitPaneUI) ui).getDivider().setBorder(null);//طָ + } + + add(splitPane); + } + + public void setobjArray(Object[][] objArrayTemp) { + objArray = objArrayTemp; + } + + /* + * This method picks good column sizes. If all column heads are wider than + * the column's cells' contents, then you can just use + * column.sizeWidthToFit(). + */ + public void initColumnSizes() { + table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); + // DefaultTableModel model = (DefaultTableModel) table.getModel(); + TableColumn column = null; + Component comp = null; + int headerWidth = 0; + int cellWidth = 0; + TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer(); + TableColumnModel colmode = table.getColumnModel(); + int count = colmode.getColumnCount(); + for (int i = 0; i < count; i++) { + column = table.getColumnModel().getColumn(i); + comp = headerRenderer.getTableCellRendererComponent(table, column.getHeaderValue(), false, false, 0, 0); + headerWidth = comp.getPreferredSize().width; +// if (i == 1) { +// cellWidth = 50; +// }else if (i == 2) { +// cellWidth = 50; +// }else if (i == 3) { +// cellWidth = 80; +// }else if (i == 4) { +// cellWidth = 100; +// }else { +// cellWidth = 130; +// } + if (i == 0) { + cellWidth = 180; + }else if (i == 1) { + cellWidth = 75; + }else if (i == 2) { + cellWidth = 75; + }else if (i == 3) { + cellWidth = 100; + }else { + cellWidth = 130; + } + column.setPreferredWidth(Math.max(headerWidth, cellWidth)); + } + } + + public String getUserChoose() { + String cellValue = null; + int selectRows = table.getSelectedRows().length;// ȡûѡе + if (selectRows == 1) { + int selectedRowIndex = table.getSelectedRow(); // ȡûѡ + cellValue = (String) table.getValueAt(selectedRowIndex, 6); + } + return cellValue; + } + + /** + * ӵ¼עϢ + */ + public void addListener(){ + table.addMouseListener(new MouseListener(){ + + public void mouseClicked(MouseEvent e) { + String userComments = getUserChoose(); + String Comments = ""; + if(userComments!=null){ + int len = userComments.split("\t").length; + for(int i = 0;i tableData; + private JButton confirmButton = null; + private String validTypeOption = "origin_batchdown_validtype"; + // origin_showLogFileеֵΪtrue־ļc:\\batchExportDataset.log + private String isShowLogOption = "origin_showLogFile"; + private String logFileName = "c:\\batchExportDataset.log"; + private PackResultInfo resultInfo; + private boolean isDownReleased = false; + private WriteAndCopyFile writeLog; + + private int downDataSetCount = 0; + private int isNotHavePriviligeCount = 0; + private int haveEqualDataSetCount = 0; + private int needDownCount = 0; + private int notReleasedDataSetCount = 0; + private int downCount = 0; + private List haveDownDataSet = new ArrayList(); + private List notExistFiles = new ArrayList(); + private List failDownInfos = new ArrayList(); + + private JLabel existDataSetLb = new JLabel(); + private JLabel needLb = new JLabel(); + private JLabel successLb = new JLabel(); + private JLabel noReleaseLb = new JLabel(); + private JLabel noPrevilegeLb = new JLabel(); + private JLabel noReferenceFileLb = new JLabel(); + private JLabel failLb = new JLabel(); + private List successfulInfos = new ArrayList(); + private String successfulDir = "c:/ugs/log"; + private TCUserService userService = null; + private List logsList = new ArrayList(); + + public ResultDialog(PackResultInfo resultInfo, TCSession session) { + super(true); + this.resultInfo = resultInfo; + this.session = session; + checkcommon = new GetCommonInfo(session); + this.tableData = resultInfo.getFailDownInfo(); + writeLog = new WriteAndCopyFile(); + userService = (TCUserService) session.getUserService(); + + if (isShowLog()) { + File file = new File(logFileName); + if (file.exists()) { + writeLog.writeFile(logFileName, true, "\n"); + } else { + try { + file.createNewFile(); + writeLog.writeFile(logFileName, true, "\n"); + } catch (IOException e) { + e.printStackTrace(); + } + } + } else { + File file = new File(logFileName); + if (file.exists()) { + file.delete(); + } + } + initUI(); + } + + public void initUI() { + // setPersistentDisplay(true); + setOptimalDisplay(false); + this.setTitle("ؽ"); + BorderLayout borderLayout = new BorderLayout(); + JPanel panel = new JPanel(borderLayout); + panel.add(setTopPanel(), BorderLayout.NORTH); +// panel.add(setCenterPanel(), BorderLayout.CENTER); + panel.add(setBottomPanel(), BorderLayout.SOUTH); + getContentPane().add(panel); +// Dimension screen = getToolkit().getScreenSize(); + setPreferredSize(new Dimension(400,300)); +// setLocation((screen.width - getSize().width) / 2, (screen.height - getSize().height) / 2); + centerToScreen(); + this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); + this.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + dispose(); + } + }); + pack(); + this.setVisible(true); + } + + private JPanel setTopPanel() { + JPanel panel1 = new JPanel(new PropertyLayout()); + JLabel infoLb = new JLabel(" ļͳƣ"); + existDataSetLb.setText(" ݼ" + resultInfo.getExistDataSetCount()); + noReleaseLb.setText(" δݼ:" + resultInfo.getNoReleasedNum()); + noPrevilegeLb.setText(" Ȩݼ:" + resultInfo.getNoPrivilegelNum()); + needLb.setText(" Ҫļ:" + resultInfo.getNeedNum()); + successLb.setText(" ɹļ:" + resultInfo.getSuccessNum()); + noReferenceFileLb.setText(" ļݼ:" + resultInfo.getNoReferenceNum()); + failLb.setText(" δɹļ" + resultInfo.getFailNum()); + + panel1.add("1.1.left.center", new JLabel()); + panel1.add("2.1.left.center", existDataSetLb); + panel1.add("3.1.left.center", noReleaseLb); + panel1.add("4.1.left.center", noPrevilegeLb); + panel1.add("5.1.left.center", needLb); + panel1.add("6.1.left.center", successLb); + panel1.add("7.1.left.center", noReferenceFileLb); + + JPanel panel2 = new JPanel(new PropertyLayout()); + panel2.add("1.1.left.center", new JLabel()); + panel2.add("2.1.left.center", failLb); + + JPanel panel = new JPanel(new PropertyLayout()); + panel.add("1.1.left.center", new JLabel()); + panel.add("2.1.left.center", infoLb); + panel.add("3.1.left.center", panel1); + panel.add("4.1.left.center", panel2); + return panel; + } + /* + private JPanel setCenterPanel() { + JPanel panel = new JPanel(new PropertyLayout()); + dtm = new ResultTableModel(tableData); + table = new JTable(dtm); + table.setRowHeight(20); + dtm.setTableColumnsWidth(table); + table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); + // нȾ + table.getColumnModel().getColumn(0).setCellRenderer(new TableColumnRender()); + table.getColumnModel().getColumn(7).setCellRenderer(new CheckBoxColumnRender()); + + JScrollPane scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); + scrollPane.setAutoscrolls(true); + scrollPane.setPreferredSize(new Dimension(690, 200)); + panel.add("1.1.left.center", scrollPane); + panel.add("2.1.left.center", new JLabel(" ")); + panel.setBorder(new TitledBorder("")); + return panel; + } + */ + + private JPanel setBottomPanel() { + JPanel southPanel = new JPanel(new FlowLayout()); + southPanel.setSize(60, 10); + confirmButton = new JButton(""); + confirmButton.addActionListener(new buttonListener()); + JButton exitButton = new JButton("ȡ"); + exitButton.addActionListener(new buttonListener()); + southPanel.add(confirmButton); + southPanel.add(exitButton); + return southPanel; + } + + class buttonListener implements ActionListener { + public void actionPerformed(ActionEvent event) { + String name = ((JButton) event.getSource()).getText(); + if (name.equals("")) { + confirmButtonAction(); + } else { + if (name.equals("ȡ")) { + dispose(); + } + } + } + } + + private void writeSuccessfulLogFile(String fileName, String content) { + content = content + "\n"; + writeLog.writeFile(fileName, true, content); + logsList.add(content); + } + + private void confirmButtonAction() { + System.out.println("tableData.size()......." + tableData.size()); + if (tableData.size() > 0) { + writeLogFile(logFileName, "\n"); + writeLogFile(logFileName, ":\n"); + PackSuccessfulInfo succesfulDataset = new PackSuccessfulInfo(); + succesfulDataset.setIndex(""); + succesfulDataset.setItemID("ID"); + succesfulDataset.setItemRev("汾"); + succesfulDataset.setItemOwner(""); + succesfulDataset.setDataset("ݼ"); + succesfulDataset.setRefFile(""); + successfulInfos.add(succesfulDataset); + + boolean need = false; + for (int i = 0; i < tableData.size(); i++) { + TCComponentDataset dataSet = tableData.get(i).getDataSet(); + String needDown = tableData.get(i).getNeedDown(); + if (needDown.equals("true")) { + need = true; + String filePath = tableData.get(i).getFilePath(); + String itemId = tableData.get(i).getItemId(); + String rev = tableData.get(i).getRev(); + String owner = tableData.get(i).getOwner(); + TCComponentItemRevision itemRevision = tableData.get(i).getItemRev(); + datasetFileDown(itemRevision, dataSet, filePath, itemId, rev, owner); + } + } + + SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd:HHmmss"); + String time = date.format(new Date()); + String logPath = successfulDir + "/¹ļ־_" + (new SimpleDateFormat("yyyyMMdd")).format(new Date()) + ".log"; + writeSuccessfulLogFile(logPath, " "); + writeSuccessfulLogFile(logPath, "==========================================================================================================================="); + writeSuccessfulLogFile(logPath, "ʱ:" + time + " :" + resultInfo.getPerson() + " ѡ(Ŀ¼):" + resultInfo.getJob()); + writeSuccessfulLogFile(logPath, " "); + writeSuccessfulLogFile(logPath, "ݼ:" + haveDownDataSet.size()); + writeSuccessfulLogFile(logPath, "δݼ:" + notReleasedDataSetCount); + writeSuccessfulLogFile(logPath, "Ȩݼ:" + isNotHavePriviligeCount); + writeSuccessfulLogFile(logPath, "ļ:" + needDownCount); + writeSuccessfulLogFile(logPath, "ɹļ:" + downDataSetCount); + writeSuccessfulLogFile(logPath, "ļݼ:" + notExistFiles.size()); + writeSuccessfulLogFile(logPath, " "); + writeSuccessfulLogFile(logPath, "ѳɹļб:"); + writeSuccessfulLogFile(logPath, "---------------------------------------------------------------------------"); + for (int i = 0; i < successfulInfos.size(); i++) { + PackSuccessfulInfo successfulInfo = successfulInfos.get(i); + writeSuccessfulLogFile(logPath, appendSpace(successfulInfo.getIndex().trim(), 5) + appendSpace(successfulInfo.getItemID().trim(), 32) + appendSpace(successfulInfo.getItemRev().trim(), 5) + appendSpace(successfulInfo.getItemOwner().trim(), 25) + appendSpace(successfulInfo.getDataset().trim(), 50) + appendSpace(successfulInfo.getRefFile().trim(), 50)); + } + writeSuccessfulLogFile(logPath, " "); + // ־ + try { + Object objs[] = new Object[1]; + objs[0] = logsList.toArray(); + userService.call("DatasetDownLog", objs); + } catch (TCException e) { + e.printStackTrace(); + } + + if (need) { + writeLogFile(logFileName, " "); + writeLogFile(logFileName, "ܽ᣺"); + writeLogFile(logFileName, "ݼ:" + haveDownDataSet.size() + ""); + writeLogFile(logFileName, "δݼ:" + notReleasedDataSetCount + ""); + writeLogFile(logFileName, "Ȩݼ:" + isNotHavePriviligeCount + ""); + writeLogFile(logFileName, "Ҫļ:" + needDownCount + ""); + writeLogFile(logFileName, "ɹļ:" + downDataSetCount + ""); + writeLogFile(logFileName, "ļݼ:" + notExistFiles.size() + ""); + writeLogFile(logFileName, "δɹļ:" + (needDownCount - downDataSetCount) + ""); + + resultInfo.setExistDataSetCount(haveDownDataSet.size()); + resultInfo.setNeedNum(needDownCount); + resultInfo.setSuccessNum(downDataSetCount); + resultInfo.setNoReleasedNum(notReleasedDataSetCount); + resultInfo.setNoPrivilegelNum(isNotHavePriviligeCount); + resultInfo.setNoReferenceNum(notExistFiles.size()); + resultInfo.setEqualNameNum(haveEqualDataSetCount); + resultInfo.setFailNum(failDownInfos.size()); + resultInfo.setFailDownInfo(failDownInfos); + updateDialog(); + } else { + MessageBox.post("ûҪصݼ!", "INFO", MessageBox.INFORMATION); + } + } else { + MessageBox.post("ûҪصݼ!", "INFO", MessageBox.INFORMATION); + } + } + + private String appendSpace(String str, int num) { + if (str.length() < num) { + for (int i = UtilApi.length(str) + 1; i <= num; i++) { + str += " "; + } + } + return str; + } + + private void updateDialog() { + existDataSetLb.setText(" ݼ" + resultInfo.getExistDataSetCount()); + noReleaseLb.setText(" δݼ:" + resultInfo.getNoReleasedNum()); + noPrevilegeLb.setText(" Ȩݼ:" + resultInfo.getNoPrivilegelNum()); + needLb.setText(" Ҫļ:" + resultInfo.getNeedNum()); + successLb.setText(" ɹļ:" + resultInfo.getSuccessNum()); + noReferenceFileLb.setText(" ļݼ:" + resultInfo.getNoReferenceNum()); + failLb.setText(" أ" + resultInfo.getFailNum()); + + tableData = resultInfo.getFailDownInfo(); + dtm = new ResultTableModel(tableData); + table.setModel(dtm); + table.setRowHeight(20); + dtm.setTableColumnsWidth(table); + table.getColumnModel().getColumn(0).setCellRenderer(new TableColumnRender()); + table.getColumnModel().getColumn(7).setCellRenderer(new CheckBoxColumnRender()); + dtm.setTableColumnsWidth(table); + + downDataSetCount = 0; + isNotHavePriviligeCount = 0; + haveEqualDataSetCount = 0; + needDownCount = 0; + notReleasedDataSetCount = 0; + downCount = 0; + failDownInfos = new ArrayList(); + haveDownDataSet = new ArrayList(); + notExistFiles = new ArrayList(); + } + + /** + * datasetFileDown:ݼļ + * @param @return 趨ļ + * @param dataset + * @param fileCurrentPath + * @return String + * @throws + * @since CodingExampleVer 1.1 + */ + + private void datasetFileDown(TCComponentItemRevision itemRevision, TCComponentDataset dataSet, String currentPath, String itemId, String rev, String owner) { + + try { + dataSet.refresh(); + } catch (TCException e2) { + e2.printStackTrace(); + } + if (haveDownDataSet != null) { + if (haveDownDataSet.contains(dataSet)) { + return; + } + } + String fileCurrentPath = currentPath; + haveDownDataSet.add(dataSet); + writeLogFile(logFileName, "ݼ:" + dataSet.toString()); + System.out.println("dataSet............" + dataSet.toString()); + PackFailDownInfo dataSetInfo = new PackFailDownInfo(); + dataSetInfo.setItemId(itemId); + dataSetInfo.setRev(rev); + dataSetInfo.setDatasetName(dataSet.toString()); + dataSetInfo.setDataSet(dataSet); + dataSetInfo.setOwner(owner); + dataSetInfo.setItemRev(itemRevision); + try { + String release = dataSet.getProperty("release_status_list").trim(); + if (release != null) { + String regex = ".*Released.*"; + Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); + Matcher match = pattern.matcher(release); + boolean find = match.find(); + if (!find) { + notReleasedDataSetCount++; + writeLogFile(logFileName, "δ"); + if (isDownReleased) { + dataSetInfo.setReason("δ"); + failDownInfos.add(dataSetInfo); + writeLogFile(logFileName, ""); + return; + } + } else { + writeLogFile(logFileName, "Ѿ"); + } + } + } catch (TCException e2) { + e2.printStackTrace(); + } + try { + boolean isCanExport = false; + isCanExport = checkAccessPrivilige(session.getUser(), dataSet, "EXPORT"); + if (!isCanExport) { + ++isNotHavePriviligeCount; + dataSetInfo.setReason("ûеȨ"); + failDownInfos.add(dataSetInfo); + writeLogFile(logFileName, "ûеȨ"); + writeLogFile(logFileName, " "); + return; + } else { + writeLogFile(logFileName, "еȨ "); + } + } catch (TCException e1) { + e1.printStackTrace(); + } + TCComponentTcFile tcFile = null; + String fileName = ""; + try { + if ((dataSet.getTcFiles() != null) && (dataSet.getTcFiles().length > 0)) { +// if (itemRevision != null) { +// String revType = itemRevision.getType(); +// if (revType.equals("GGDitem Revision") || revType.equals("HTDitem Revision")) { +// fileCurrentPath = createFile(fileCurrentPath, changePackageName); +// } +// } + + for (int i = 0; i < dataSet.getTcFiles().length; i++) { + tcFile = dataSet.getTcFiles()[i]; + if (tcFile == null) { + return; + } + tcFile.refresh(); + fileName = tcFile.getProperty("original_file_name"); + if (fileName != null) { + needDownCount++; + dataSetInfo.setReference_file(fileName); + dataSetInfo.setFilePath(fileCurrentPath); + dataSetInfo.setNeedDown("true"); + String fileType = ""; + String preFileName = ""; + int index = fileName.lastIndexOf("."); + if (index > 0) { + fileType = fileName.substring(index, fileName.length()); + preFileName = fileName.substring(0, index); + } else { + preFileName = fileName; + } + boolean flag = checkcommon.existFile(fileCurrentPath, fileName); + if (flag) { + haveEqualDataSetCount++; + int pos = fileName.indexOf('.'); + if (pos > 0) { + fileName = preFileName + "_" + UtilApi.getTimeNum() + fileType; + } + } + if (fileName.indexOf('/') >= 0) { + fileName = fileName.replace('/', '_'); + } + downCount = 0; + getTCFile(tcFile, fileCurrentPath, fileName, dataSetInfo); + } + } + } else { + dataSetInfo.setReason("ļ"); + failDownInfos.add(dataSetInfo); + notExistFiles.add(dataSet.toString()); + writeLogFile(logFileName, "ļ"); + } + writeLogFile(logFileName, " "); + } catch (Throwable e) { + writeLogFile(logFileName, "ļʱ쳣"); + writeLogFile(logFileName, e.getMessage()); + writeLogFile(logFileName, " "); + e.printStackTrace(); + } + } + + private File getTCFile(TCComponentTcFile tcFile, String fileCurrentPath, String fileName, PackFailDownInfo dataSetInfo) { + ++downCount; + if (downCount == 2) { + writeLogFile(logFileName, "ڶ"); + } + File file = null; + try { + file = tcFile.getFile(fileCurrentPath, fileName); + if (file != null) { + ++downDataSetCount; + writeLogFile(logFileName, "ļ:" + fileName + " " + getTime()); + writeLogFile(logFileName, " "); + + // successfulInfos + PackSuccessfulInfo succesfulDataset = new PackSuccessfulInfo(); + succesfulDataset.setIndex(String.valueOf(downDataSetCount)); + succesfulDataset.setItemID(dataSetInfo.getItemId()); + succesfulDataset.setItemRev(dataSetInfo.getRev()); + succesfulDataset.setItemOwner(dataSetInfo.getOwner()); + succesfulDataset.setDataset(dataSetInfo.getDatasetName()); + succesfulDataset.setRefFile(file.getName()); + successfulInfos.add(succesfulDataset); + } else { + writeLogFile(logFileName, "ûеļ"); + } + } catch (Throwable e) { + writeLogFile(logFileName, "ļʱ쳣"); + String exceptionMessage = e.getMessage(); + writeLogFile(logFileName, exceptionMessage); + writeLogFile(logFileName, " "); + e.printStackTrace(); + if (downCount < 2) { + file = getTCFile(tcFile, fileCurrentPath, fileName, dataSetInfo); + } else { + dataSetInfo.setReason(exceptionMessage); + failDownInfos.add(dataSetInfo); + } + } + return file; + } + + private void writeLogFile(String fileName, String content) { + if (isShowLog()) { + content = content + "\n"; + writeLog.writeFile(fileName, true, content); + } + } + + public String getTime() { + String strTime = ""; + try { + SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss:SSS"); + strTime = bartDateFormat.format(new Date()); + // System.out.println(strTime); + } catch (Exception e) { + e.printStackTrace(); + } + return strTime; + } + + /** + * checkAccessPrivilige:ûԸComponentǷȨ + * @param @return 趨ļ + * @return String + * @throws + * @since CodingExampleVer 1.1 + */ + private boolean checkAccessPrivilige(TCComponentUser user, TCComponent comp, String accessName) throws TCException { + TCAccessControlService accessService = ((TCSession) session).getTCAccessControlService(); + boolean returnboolean = accessService.checkUsersPrivilege(user, comp, accessName); + return returnboolean; + } + + private boolean isShowLog() { + boolean isShowLog = false; + TCPreferenceService preSer = session.getPreferenceService(); + String value = preSer.getString(4, isShowLogOption).trim(); + if (value.equalsIgnoreCase("true")) { + isShowLog = true; + } + return isShowLog; + } + + public void isDownReleased() { + TCPreferenceService preSer = session.getPreferenceService(); + String type = preSer.getString(4, validTypeOption).trim(); + if (type.equalsIgnoreCase("released")) { + isDownReleased = true; + } + } +} diff --git a/src/com/connor/lidy/task/util/ResultTableModel.java b/src/com/connor/lidy/task/util/ResultTableModel.java new file mode 100644 index 0000000..28aa998 --- /dev/null +++ b/src/com/connor/lidy/task/util/ResultTableModel.java @@ -0,0 +1,97 @@ +/* +#============================================================================= +# +# Copyright (c) 2009 Origin Enterprise Solution LTD. +# +#============================================================================= +# File name: ResultTableModel.java +# File description: +#============================================================================= +# Date Name Action Description of Change +# 2011-4-20 liqz Ini ʼ(From Shaangu) +#============================================================================= + */ +package com.connor.lidy.task.util; + +import java.util.Enumeration; +import java.util.List; + +import javax.swing.JTable; +import javax.swing.table.DefaultTableModel; +import javax.swing.table.JTableHeader; +import javax.swing.table.TableColumn; + + +public class ResultTableModel extends DefaultTableModel { + + /** + * + */ + private static final long serialVersionUID = 1L; + private static String[] names = { "*", "ID", "汾", "","ݼ", "" ,"ԭ",""}; + + /** + * Creates a new instance of EditBatchProcessLineTableModel. + * @param data + */ + public ResultTableModel(List data) { + super(getData(data), names); + } + + public static Object[][] getData(List data) { + Object[][] datas = new Object[data.size()][]; + for (int i = 0; i < data.size(); i++) { + String[] info = new String[8]; + info[0] = String.valueOf(i + 1); + info[1] = data.get(i).getItemId(); + info[2] = data.get(i).getRev(); + info[3] = data.get(i).getOwner(); + info[4] = data.get(i).getDatasetName(); + info[5] = data.get(i).getReference_file(); + info[6] = data.get(i).getReason(); + info[7] = data.get(i).getNeedDown(); + datas[i] = info; + } + return datas; + } + + @Override + public boolean isCellEditable(int row, int column) { + if (column < 7) { + return false; + } else { + return true; + } + } + + // ݱСп + public void FitTableColumns(JTable myTable) { + JTableHeader header = myTable.getTableHeader(); + int rowCount = myTable.getRowCount(); + Enumeration columns = myTable.getColumnModel().getColumns(); + while (columns.hasMoreElements()) { + TableColumn column = (TableColumn) columns.nextElement(); + int col = header.getColumnModel().getColumnIndex(column.getIdentifier()); + int width = (int) myTable.getTableHeader().getDefaultRenderer().getTableCellRendererComponent(myTable, column.getIdentifier(), false, false, -1, col).getPreferredSize().getWidth(); + for (int row = 0; row < rowCount; row++) { + int preferedWidth = (int) myTable.getCellRenderer(row, col).getTableCellRendererComponent(myTable, myTable.getValueAt(row, col), false, false, row, col).getPreferredSize().getWidth(); + width = Math.max(width, preferedWidth); + } + header.setResizingColumn(column); + column.setWidth(width + myTable.getIntercellSpacing().width); + } + } + + // п + public void setTableColumnsWidth(JTable myTable) { + myTable.getColumnModel().getColumn(0).setPreferredWidth(25); + myTable.getColumnModel().getColumn(1).setPreferredWidth(100); + myTable.getColumnModel().getColumn(2).setPreferredWidth(40); + myTable.getColumnModel().getColumn(3).setPreferredWidth(100); + myTable.getColumnModel().getColumn(4).setPreferredWidth(100); + myTable.getColumnModel().getColumn(5).setPreferredWidth(125); + myTable.getColumnModel().getColumn(6).setPreferredWidth(100); + myTable.getColumnModel().getColumn(7).setPreferredWidth(80); + } + +} diff --git a/src/com/connor/lidy/task/util/SelectUserDialog.java b/src/com/connor/lidy/task/util/SelectUserDialog.java new file mode 100644 index 0000000..c10996a --- /dev/null +++ b/src/com/connor/lidy/task/util/SelectUserDialog.java @@ -0,0 +1,426 @@ +package com.connor.lidy.task.util; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Cursor; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.List; +import javax.swing.DefaultListModel; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.JTextField; +import javax.swing.JTree; +import javax.swing.ListCellRenderer; +import javax.swing.ListSelectionModel; +import javax.swing.tree.DefaultMutableTreeNode; + +import com.teamcenter.rac.aif.AbstractAIFDialog; +import com.teamcenter.rac.aif.common.AIFTreeNode; +import com.teamcenter.rac.aifrcp.AIFUtility; +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.TCComponentGroupMember; +import com.teamcenter.rac.kernel.TCComponentProject; +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 SelectUserDialog extends AbstractAIFDialog { + + 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 JTextField editPropMap; + private String group; + private boolean isMulti; + private JTable table; + private int[] colIndex; + private int rowIndex; + private TCComponentProject project; + + public SelectUserDialog(JTextField editPropMap, boolean isMulti) throws Exception { + super(true); + this.editPropMap = editPropMap; + this.isMulti = isMulti; + initUI(); + } + + private String getValue() { + String val = ""; + if (editPropMap != null) { + val = editPropMap.getText(); + } else if (table != null) { + val = (String) table.getValueAt(rowIndex, colIndex[0]); + } + return val; + } + + private void setValue(String text) { + if (editPropMap != null) { + editPropMap.setText(text); + } else if (table != null) { + table.setValueAt(text, rowIndex, colIndex[0]); + if (colIndex.length>1) + table.setValueAt(group, rowIndex, colIndex[1]); + } + } + + public SelectUserDialog(JTable table, boolean isMulti, int[] colIndex, int rowIndex, TCComponentProject projectID) throws Exception { + super(true); + this.table = table; + this.isMulti = isMulti; + this.colIndex = colIndex; + this.rowIndex = rowIndex; + this.project = projectID; + initUI(); + } + + private void initUI() throws Exception { + this.setTitle("ѡԱ"); + 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 = 640; + mweight = 480; + } + if(project != null) { + pheight = 700; + mheight = 700; + } + this.setPreferredSize(new Dimension(pweight, pheight)); + this.setMinimumSize(new Dimension(mweight, mheight)); + OrgTreePanel orgPanel = new OrgTreePanel((TCSession) AIFUtility.getCurrentApplication().getSession()); + this.tree = orgPanel.getOrgTree(); + + 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); + } + this.add(BorderLayout.SOUTH, initBtnPanel()); + if (isMulti) { + JPanel lp = initListPanel(); + this.add(BorderLayout.EAST, lp); + initData(); + } + addListeners(); + } + + 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 panel = new JPanel(new BorderLayout()); + FlowLayout flow = new FlowLayout(); + flow.setVgap(100); + JPanel btnPanel = new JPanel(flow); + btnPanel.add(this.add); +// btnPanel.add("2.1.center.center", this.remove); + this.lm_user = new DefaultListModel<>(); + this.l_user = new JList<>(lm_user); + l_user.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + this.l_user.setCellRenderer(new DeleteListRenderer(l_user)); + JScrollPane scroll = new JScrollPane(l_user); + scroll.setPreferredSize(new Dimension(200, 0)); +// this.add.setPreferredSize(new Dimension(50, 30)); + panel.add(BorderLayout.WEST, btnPanel); + panel.add(BorderLayout.CENTER, scroll); + return panel; + } + + private JPanel initBtnPanel() { + JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 5)); + this.b_ok = new JButton("ȷ"); + 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 {//TODO + 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) { + if(projectTree == null) + return null; + else if(projectTree.getSelectionModel() == null) + return null; + else if(projectTree.getLastSelectedPathComponent() == null) + return null; + DefaultMutableTreeNode selectNode = (DefaultMutableTreeNode) projectTree.getLastSelectedPathComponent(); + Object selectObject = selectNode.getUserObject(); + if(selectObject instanceof TCComponentGroupMember) { + String member = ((TCComponentGroupMember) selectObject).toString(); + if(member.indexOf(".")>0) + group = member.substring(0, member.indexOf(".")); + else + group = member.substring(0, member.indexOf("/")); + TCComponentUser user = ((TCComponentGroupMember) selectObject).getUser(); + if (user != null) { + return user.getProperty("user_name"); + } + }else + 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(); + return user.getProperty("user_name"); + } + } + } + return null; + } + + private void addListeners() { + this.b_cel.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + disposeDialog(); + } + }); + this.b_ok.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + try { + 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(""); + } + } + 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(); + if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) { + String user = getSelectUser(); + System.out.println("user:"+user); + if (user != null) { + if (isMulti) { + if (!lm_user.contains(user.toString())) { + lm_user.addElement(user.toString()); + } + } else { + setValue(user.toString()); + disposeDialog(); + } + } + } + } catch (Exception e1) { + e1.printStackTrace(); + MessageBox.post("Error:"+e1.getMessage(), "ERROR", MessageBox.ERROR); + } + } + }); + 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.toString())) { + lm_user.addElement(user.toString()); + } + } else { + setValue(user.toString()); + disposeDialog(); + } + } + } + } catch (Exception e1) { + e1.printStackTrace(); + MessageBox.post("Error:"+e1.getMessage(), "ERROR", MessageBox.ERROR); + } + } + }); + } + 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); + } + + }); + this.add.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + try { + String user = getSelectUser(); + System.out.println("user:"+user); + if (user != null) { + if (!lm_user.contains(user.toString())) { + lm_user.addElement(user.toString()); + } + } + } catch (Exception e1) { + e1.printStackTrace(); + MessageBox.post("Error:"+e1.getMessage(), "ERROR", MessageBox.ERROR); + } + } + }); + this.remove.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + disposeDialog(); + } + }); + } + private class DeleteListRenderer extends JPanel implements ListCellRenderer { + + JButton btn; + JLabel label; + + public DeleteListRenderer(final JList list) { + this.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 1)); + this.setBackground(Color.WHITE); + btn = getDeletetBtn(); + label = new JLabel(""); + this.add(btn); + this.add(label); + + btn.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + int ind = list.getSelectedIndex(); + System.out.println(ind); + if (ind >= 0) { + list.remove(ind); + } + } + }); + + } + @Override + public Component getListCellRendererComponent(JList list, String value, int index, + boolean isSelected, boolean cellHasFocus) { + label.setText(value); + return this; + } + private JButton getDeletetBtn() { + ImageIcon icon = new ImageIcon(SelectUserDialog.class.getResource("image/delete.png")); + JButton btn = new JButton(icon); + btn.setPreferredSize(new Dimension(23, 23)); + btn.setContentAreaFilled(false); + btn.setFocusPainted(false); + btn.setBorderPainted(false); + btn.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); + return btn; + } + } +} diff --git a/src/com/connor/lidy/task/util/ShowMessageDialog.java b/src/com/connor/lidy/task/util/ShowMessageDialog.java new file mode 100644 index 0000000..235dd88 --- /dev/null +++ b/src/com/connor/lidy/task/util/ShowMessageDialog.java @@ -0,0 +1,93 @@ +/* +#============================================================================= +# +# Copyright (c) 2009 Origin Enterprise Solution LTD. +# +#============================================================================= +# File name: ShowMessageDialog.java +# File description: +#============================================================================= +# Date Name Action Description of Change +# 2009-10-30 tyl ʾϢ +# 2010-02-10 tyl Mod Ϣǰٿո +#============================================================================= + */ + +package com.connor.lidy.task.util; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.net.URL; + +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JPanel; + +import com.teamcenter.rac.aif.AbstractAIFDialog; +import com.teamcenter.rac.util.PropertyLayout; +import com.teamcenter.rac.util.VerticalLayout; + +public class ShowMessageDialog extends AbstractAIFDialog { + + private static final long serialVersionUID = 1L; + private String title = ""; + private String info1 = ""; + private String info2 = ""; + + public ShowMessageDialog(String title, String info1, String info2) { + super(true); + this.title = title; + this.info1 = info1; + this.info2 = info2; + initUI(); + } + + public void initUI() { + setPersistentDisplay(true); + setOptimalDisplay(false); + setTitle(title); + JPanel parentPanel; + JPanel iconPanel = new JPanel(); + JPanel itemInfoPanel1; + JPanel itemInfoPanel2; + parentPanel = new JPanel(new VerticalLayout(5, 2, 2, 2, 2)); + itemInfoPanel2 = new JPanel(new GridLayout(2, 1)); + itemInfoPanel1 = new JPanel(new PropertyLayout()); + + URL url = this.getClass().getResource("image/info.png"); + JLabel iconLabel = new JLabel(); + iconLabel.setIcon(new ImageIcon(url)); + iconPanel.add(iconLabel); + + itemInfoPanel2.add(new JLabel(" " + info1)); + itemInfoPanel2.add(new JLabel(info2)); + + itemInfoPanel1.add("1.1.left.center", iconPanel); + itemInfoPanel1.add("1.2.left.center", itemInfoPanel2); + + JButton buttonYes = new JButton("ȷ"); + buttonYes.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + ShowMessageDialog.this.dispose(); + } + }); + JPanel panelButton = new JPanel(new BorderLayout()); + panelButton.setSize(10, 20); + panelButton.add(buttonYes, BorderLayout.CENTER); + + parentPanel.add("top.bin", new JLabel(" ")); + parentPanel.add("top.bind.left.top", itemInfoPanel1); + parentPanel.add("bottom.nobind.center.top", panelButton); + + getContentPane().add(parentPanel); + + pack(); + Dimension screen = getToolkit().getScreenSize(); // õĻߴ + setLocation((screen.width - getSize().width) / 2, (screen.height - getSize().height) / 2); + setVisible(true); + } +} diff --git a/src/com/connor/lidy/task/util/TableColorRender.java b/src/com/connor/lidy/task/util/TableColorRender.java new file mode 100644 index 0000000..a41de4b --- /dev/null +++ b/src/com/connor/lidy/task/util/TableColorRender.java @@ -0,0 +1,54 @@ +/* +#======================================================================================================= +# +# Copyright (c) 2007 Origin Enterprise Solution LTD. +# +#======================================================================================================= +# File description: TableColorRender.java +#======================================================================================================= +# Date time Name Action Description of Change +# 2011-1-17 03:46:31 tyl Ini ʼļ +#======================================================================================================= + */ +package com.connor.lidy.task.util; + +import java.awt.Color; +import java.awt.Component; + +import javax.swing.JTable; +import javax.swing.table.DefaultTableCellRenderer; +import javax.swing.table.TableCellRenderer; + +public class TableColorRender implements TableCellRenderer { + // + public static final DefaultTableCellRenderer DEFAULT_RENDERER = new DefaultTableCellRenderer(); + + public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { + Component renderer = DEFAULT_RENDERER.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); + + Color foreground = table.getForeground(); + Color background = table.getBackground(); + if (isSelected) { + foreground = Color.WHITE; + background = Color.LIGHT_GRAY; + } else { + if (value != null) { + if (((String) value).startsWith("")) { + foreground = Color.RED; + background = Color.WHITE; + } else { + if (((String) value).startsWith("")) { + System.out.println("value============" + value); + foreground = Color.RED; + background = Color.WHITE; + } + } + } + foreground = table.getForeground(); + background = table.getBackground(); + } + renderer.setForeground(foreground); + renderer.setBackground(background); + return renderer; + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/task/util/TableColumnRender.java b/src/com/connor/lidy/task/util/TableColumnRender.java new file mode 100644 index 0000000..2d3ffca --- /dev/null +++ b/src/com/connor/lidy/task/util/TableColumnRender.java @@ -0,0 +1,51 @@ +/* +#======================================================================================================= +# +# Copyright (c) 2007 Origin Enterprise Solution LTD. +# +#======================================================================================================= +# File description: TableColumnRender.java +#======================================================================================================= +# Date time Name Action Description of Change +# 2011-1-17 03:50:26 tyl Ini ʼļ +#======================================================================================================= +*/ +package com.connor.lidy.task.util; + +import java.awt.Component; + +import javax.swing.JLabel; +import javax.swing.JTable; +import javax.swing.UIManager; +import javax.swing.table.DefaultTableCellRenderer; +import javax.swing.table.JTableHeader; + +public class TableColumnRender extends DefaultTableCellRenderer { + + /** + * serialVersionUID:TODOĹܣ + * @since Ver 1.1 + */ + private static final long serialVersionUID = 1L; + + /** + * + */ + public TableColumnRender() { + super(); + } + + public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { + //õͷ + JTableHeader header = table.getTableHeader(); + if (header != null) { + setForeground(header.getForeground()); + setBackground(header.getBackground()); + setFont(header.getFont()); + } + setHorizontalAlignment(JLabel.CENTER); + this.setText((value == null) ? "" : value.toString()); + setBorder(UIManager.getBorder("TableHeader.cellBorder")); + return this; + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/task/util/UtilApi.java b/src/com/connor/lidy/task/util/UtilApi.java new file mode 100644 index 0000000..d46c8b5 --- /dev/null +++ b/src/com/connor/lidy/task/util/UtilApi.java @@ -0,0 +1,917 @@ +/* +#======================================================================================================= +# +# Copyright (c) 2007 Origin Enterprise Solution LTD. +# +#======================================================================================================= +# File description: UtilApi.java +#======================================================================================================= +# Date time Name Action Description of Change +# 2011-1-17 03:56:51 tyl Ini ʼļ +#======================================================================================================= + */ +package com.connor.lidy.task.util; + +import java.awt.Dimension; +import java.awt.Point; +import java.awt.Toolkit; +import java.io.Serializable; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Vector; + +import javax.swing.JComboBox; + +import com.teamcenter.rac.aif.AbstractAIFUIApplication; +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.TCComponentContextList; +import com.teamcenter.rac.kernel.TCComponentQuery; +import com.teamcenter.rac.kernel.TCComponentQueryType; +import com.teamcenter.rac.kernel.TCException; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.kernel.TCTextService; +import com.teamcenter.rac.util.MessageBox; + +public class UtilApi { + /** + * Logger for this class + */ +// private static HashMap loginUserInfoHm = new HashMap(); + + /** + * ϵͳsession + */ +// private TCSession session; + + /** + * ͨapi + * @param pseapplication Ӧó + */ + public UtilApi(AbstractAIFUIApplication pseapplication) { +// session = (TCSession) pseapplication.getSession(); + } + + /** + * ͨapi + * @param newsession session + */ + public UtilApi(TCSession newsession) { +// session = newsession; + } + /* + private String getDefaultExportDirectory() { + String s = null; + if (s == null || s.length() == 0) { + TCPreferenceService tcpreferenceservice = session.getPreferenceService(); + s = tcpreferenceservice.getString(0, "defaultExportDirectory"); + } + if (s != null) { + s = s.trim(); + if (s.length() == 0) + s = null; + } + return s; + } + */ + public String getEnv(String name) { + String str = ""; + Iterator> it = System.getenv().entrySet().iterator(); + while (it.hasNext()) { + Map.Entry entry = it.next(); + System.out.println("entry-" + entry.getKey() + ":" + entry.getValue()); + if (entry.getKey().toString().equals(name)) { + str = entry.getValue() + ""; + if (!str.endsWith("\\")) { + str = str + "\\"; + } + break; + } + } + return str; + } + + /** + * Enter + */ + @SuppressWarnings("deprecation") + public static String ENTER = new String(new byte[] { 13, 10 }, 0); + + /** + * ָָstringתΪvector + * @param msg Դַ + * @param sepStr ָ + * @return vector + */ + public static Vector getVector(String msg, String sepStr) { + System.out.println("***********getVector()"); + System.out.println("msg===" + msg); + System.out.println("sepStr===" + sepStr); + Vector vt = new Vector<>(); + try { + String tmpStr = null; + boolean flag = false; + int pos = -1; + if (msg == null || msg.trim().length() == 0) { return null; } + if (msg.startsWith(sepStr)) { + msg = msg.substring(1); + } + if (msg.lastIndexOf(sepStr) == msg.length() - 1) { + flag = true; + msg = msg.substring(0, msg.length() - 1); + } + while ((pos = msg.indexOf(sepStr)) > 0) { + try { + tmpStr = msg.substring(0, pos); + vt.addElement(tmpStr); + if (msg.length() > pos + 1) + msg = msg.substring(pos + 1); + } + catch (RuntimeException e) { + break; + } + } + vt.add(msg); + if (flag) + vt.add(""); + } + catch (RuntimeException e) { + e.printStackTrace(); + } + return vt; + } + + /** + * ȡַ + * @param src Դַ + * @return double + */ + public static double getFloatFromStr(String src) { + double d = 0d; + try { + if (src == null || src.length() == 0) { return 0d; } + src = src.trim(); + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < src.length(); i++) { + if (src.charAt(i) == '.' || src.charAt(i) == '+' || src.charAt(i) == '-') { + sb.append(src.charAt(i)); + } else if (src.charAt(i) >= '0' && src.charAt(i) <= '9') { + sb.append(src.charAt(i)); + } + } + d = Double.parseDouble(sb.toString()); + } + catch (NumberFormatException e) { + e.printStackTrace(); + } + return d; + } + + /** + * getMsgboxLocate:趨λ + * @param @return λ + * @return Point + * @throws + * @since CodingExampleVer 1.1 + */ + public static Point getMsgboxLocate() { + Toolkit kit = Toolkit.getDefaultToolkit(); + Dimension screenSize = kit.getScreenSize(); + int frmLocateWidth = screenSize.width * 2 / 5; + int frmLocateHeight = screenSize.height * 4 / 7; + Point p = new Point(frmLocateWidth, frmLocateHeight); + return p; + } + + /** + * Ϣʾλ + * @param formLocHeigh ǰʼλ + * @return λ + */ + public static Point getMsgboxLocate(double formLocHeigh) { + Toolkit kit = Toolkit.getDefaultToolkit(); + Dimension screenSize = kit.getScreenSize(); + String tmp = formLocHeigh + ""; + if (tmp.indexOf(".") >= 0) { + tmp = tmp.substring(0, tmp.indexOf(".")); + } + int t = Integer.parseInt(tmp); + int frmLocateWidth = screenSize.width * 2 / 5; + int frmLocateHeight = t - 120; + if (frmLocateHeight <= 0) + frmLocateHeight = 0; + Point p = new Point(frmLocateWidth, frmLocateHeight); + return p; + } + + /** + * doubleתΪָСȵ + * @param srcdouble ԭ + * @param length + * @return ָȵ + */ + public static double round(double srcdouble, int length) { + double t = 0d; + try { + t = (double) Math.pow(10, length); + } + catch (RuntimeException e) { + e.printStackTrace(); + } + return (Math.round(srcdouble * t)) / t; + } + + /** + * ֤ѡbomlineǷǵǰû + * @param selectedLine ѡbomline + * @param newsession ϵͳsession + * @return ֤ + */ + public static boolean validateOwnringUser(TCComponentBOMLine selectedLine, TCSession newsession) { + String userName = ""; + String ownerName = ""; + try { + userName = newsession.getUserName(); + userName = "(" + userName + ")"; + + ownerName = selectedLine.getProperty("bl_rev_owning_user"); + } + catch (TCException e) { + e.printStackTrace(); + return false; + } + if (ownerName.indexOf(userName) < 0) { + MessageBox messagebox1 = new MessageBox("ǵǰѡжߣܽд˲", "...", MessageBox.ERROR); + messagebox1.setVisible(true); + return false; + } + return true; + } + +// private MessageBox messagebox1; + + /** + * getTimeNum:ʱַ + * @param @return 趨ļ + * @return String + * @throws + * @since CodingExampleVer 1.1 + */ + public static String getTimeNum() { + String strTime = ""; + try { + SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS"); + strTime = bartDateFormat.format(new Date()); + System.out.println(strTime); + } + catch (Exception e) { + e.printStackTrace(); + } + return strTime; + } + + /** + * getTimeNum:ʱַ : formatΪyyyyMMddHHmmssSSS + * @param @param format ʽ + * @param @return 趨ļ + * @return String + * @throws + * @since CodingExampleVer 1.1 + */ + public static String getTimeNum(String format) { + String strTime = ""; + try { + SimpleDateFormat bartDateFormat = new SimpleDateFormat(format); + strTime = bartDateFormat.format(new Date()); + System.out.println(strTime); + } + catch (Exception e) { + e.printStackTrace(); + } + return strTime; + } + + /** + * øʽʱַ + * @param pDate + * @param pFormat ַʽ + * @return ʽʱַ pFormat=yyyyMMddHHmmssSSS + */ + public static String getFormatTimeNum(Date pDate, String pFormat) { + String strTime = ""; + try { + if (pDate == null) { return ""; } + SimpleDateFormat bartDateFormat = new SimpleDateFormat(pFormat); + strTime = bartDateFormat.format(pDate); + System.out.println(strTime); + } + catch (Exception e) { + e.printStackTrace(); + } + return strTime; + } + + /** + * õǰϵͳjavaʱ· + * @return ǰϵͳjavaʱ· + */ + public static String getJavaTmpDir() { + String filepath = System.getProperty("java.io.tmpdir"); + if (!filepath.endsWith("\\")) { + filepath = filepath + "\\"; + } + System.out.println("getJavaTmpDir() - String filepath=" + filepath); //$NON-NLS-1$ + return filepath; + } + + /** + * getLimLenTxtIgnSomeVt:Թ̶Ȳֿܰĵַ(ַָ),ʸ + * @param src ַ + * @param rowLength + * @param repStr ָ + * @param someStr Եַ + * @param @return 趨ļ + * @return Vector + * @throws + * @since CodingExampleVer 1.1 + */ + public static Vector getLimLenTxtIgnSomeVt(String src, int rowLength, String repStr, String someStr) { + String tmpstr = ""; + Vector v; + Vector vt; + Vector vt1 = new Vector<>(); + if (src != null || UtilApi.length(src) > 0) { + v = str2vt(src, someStr); + for (int i = 0; i < v.size(); i++) { + tmpstr = v.get(i).toString(); + tmpstr = UtilApi.getLimRowLenText(tmpstr, rowLength, repStr); + tmpstr = UtilApi.nbsp2space(tmpstr); + if (tmpstr.indexOf(repStr) >= 0) { + vt = str2vt(tmpstr, repStr); + for (int j = 0; j < vt.size(); j++) { + vt1.add(vt.get(j).toString()); + } + } else { + vt1.add(tmpstr); + } + } + } + + // if (logger.isDebugEnabled()) { + // logger.debug("getLimLenTxtIgnSomeVt(String, int, String, String) - end"); //$NON-NLS-1$ + // } + return vt1; + } + + /** + * getLimRowLenText:Թ̶Ȳܰĵַ(ַָ) + * @param src ַ + * @param rowLength + * @param repStr ָ + * @param @return ˷ַָ + * @return String + * @throws + * @since CodingExampleVer 1.1 + */ + public static String getLimRowLenText(String src, int rowLength, String repStr) { + String ret = ""; + try { + if (src != null || UtilApi.length(src) > 0) { + src = UtilApi.nbsp2space(src); + while (UtilApi.length(src) > 0) { + if (UtilApi.length(src) > rowLength) { + ret += UtilApi.substring(src, 0, rowLength) + repStr; + src = UtilApi.substring(src, rowLength); + } else { + ret += src; + src = ""; + } + } + } + } + catch (Exception e) { + + e.printStackTrace(); + } + String returnString = UtilApi.space2nbsp(ret); + return returnString; + } + + /** + * space2nbsp:ոתΪnbsp + * @param pStr ַ + * @param @return תַ + * @return String + * @throws + * @since CodingExampleVer 1.1 + */ + public static String space2nbsp(String pStr) { + if (pStr == null || pStr.length() < 1) + return pStr; + String s1 = ""; + for (int i = 0; i < pStr.length(); i++) + if (pStr.charAt(i) == ' ') + s1 = s1 + " "; + else s1 = s1 + pStr.charAt(i); + return s1; + } + + /** + * substring: ַ + * @param source ַ + * @param iniPos ʼλ + * @param endPos Ϊֹ + * @param @return ַ + * @return String + * @throws + * @since CodingExampleVer 1.1 + */ + public static String substring(String source, int iniPos, int endPos) { + String tmpStr = ""; + String tmpStr1 = ""; + String retStr = ""; + int tmpLen = 0; + int len = 0; + try { + len = endPos - iniPos; + if (iniPos >= UtilApi.length(source)) + return ""; + tmpStr = UtilApi.substr(source, iniPos); + tmpLen = tmpStr.length(); + tmpStr1 = source.substring(tmpLen); + if (UtilApi.length(tmpStr1) <= len) + retStr = tmpStr1; + else retStr = UtilApi.substr(tmpStr1, len); + } + catch (Exception e) {} + return retStr; + } + + /* + * ȡһַij,Ӣ,ֲãȡһַλ + * @author patriotlml @param String origin, ԭʼַ @param int len, + * ȡ(һֳȰ2) @return String, صַ(0λõlenλ) + */ + public static String substr(String source, int len) { + String retStr = ""; + if (source == null || source.equals("")) + return ""; + byte[] strByte = new byte[len]; + if (len > UtilApi.length(source)) + return source; + System.arraycopy(source.getBytes(), 0, strByte, 0, len); + int count = 0; + for (int i = 0; i < len; i++) { + int value = (int) strByte[i]; + if (value < 0) { + count++; + } + } + if (count % 2 != 0) { + len = (len == 1) ? ++len : --len; + } + + try { + retStr = new String(strByte, 0, len); + } + catch (Exception e) { + + try { + System.arraycopy(source.getBytes(), 0, strByte, 0, len); + retStr = new String(strByte, 0, len); + } + catch (Exception ex) {} + } + return retStr; + } + + /* + * ȡһַij,Ӣ,ֲãȡһַλ + * @author patriotlml @param String origin, ԭʼַ @param int iniPos, + * ȡַijʼλ @param int len, ȡ(һֳȰ2) @return String, + * صַ(0λõlenλ) + */ + public static String substring(String source, int iniPos) { + String tmpStr = ""; + int endPos = 0; + try { + endPos = UtilApi.length(source); + tmpStr = UtilApi.substring(source, iniPos, endPos + 1); + } + catch (Exception e) {} + return tmpStr; + } + + /** + * õһַij,ʾij,һֻպijΪ2,ӢַΪ1 + * @param String s ,Ҫõȵַ + * @return int, õַ + */ + public static int length(String s) { + if (s == null) + return 0; + char[] c = s.toCharArray(); + int len = 0; + for (int i = 0; i < c.length; i++) { + len++; + if (!isLetter(c[i])) { + len++; + } + } + return len; + } + + /** + * getLimRowLenTextWithSplitstr: ַ,ù̶ȵַ,滻ַָ + * @param src ַ + * @param rowLength ÿг + * @param repStr 滻ַ + * @param splitStr ָ + * @param @return ַ + * @return String + * @throws + * @since CodingExampleVer 1.1 + */ + public static String getLimRowLenTextWithSplitstr(String src, int rowLength, String repStr, String splitStr) { + Vector v; + String retStr = ""; + try { + src = UtilApi.nbsp2space(src); + v = UtilApi.getLimLenTxtIgnSomeVt(src, rowLength, repStr, splitStr); + for (int i = 0; i < v.size(); i++) { + retStr += v.get(i).toString(); + if (i != v.size() - 1) + retStr += repStr; + } + } + catch (Exception e) {} + return retStr; + } + + /** + * nbsp2space:() + * @param s + * @param @return 趨ļ + * @return String + * @throws + * @since CodingExampleVer 1.1 + */ + public static String nbsp2space(String s) { + if (s == null || s.length() < 1) + return s; + String s1 = ""; + if (s.indexOf(" ") >= 0) + s1 = UtilApi.ReplaceAll(s, " ", " "); + else s1 = s; + return s1; + } + + /** + * жһַAscillַַ纺գַ + * @param char c, Ҫжϵַ + * @return boolean, true,Ascillַ + */ + public static boolean isLetter(char c) { + int k = 0x80; + return c / k == 0 ? true : false; + } + + /** + * ReplaceAll:滻ַеضַ + * @param source ַ + * @param regex 滻ַ + * @param replacement 滻ַ + * @param @return 滻ַ + * @return String + * @throws + * @since CodingExampleVer 1.1 + */ + public static String ReplaceAll(String source, String regex, String replacement) { + if (source == null) + return ""; + String stmp1 = source; + String stmp2 = ""; + String stmp3 = ""; + int posRegex = stmp1.indexOf(regex); + int regexLen = regex.length(); + while (posRegex >= 0) { + stmp2 = stmp1.substring(0, posRegex); + stmp3 += stmp2 + replacement; + stmp1 = stmp1.substring(posRegex + regexLen); + posRegex = stmp1.indexOf(regex); + } + return stmp3 += stmp1; + } + + /** + * str2vt:ַָָָ,ʸ + * @param source ַ + * @param sepStr ָ + * @param @return ʸ + * @return Vector + * @throws + * @since CodingExampleVer 1.1 + */ + public static Vector str2vt(String source, String sepStr) { + String stmp1 = source; + String stmp2 = ""; +// String stmp3 = ""; + Vector vt = new Vector<>(); + int sepPos = 0; + int sepLen = sepStr.length(); + try { + do { + sepPos = stmp1.indexOf(sepStr); + if (sepPos < 0 || sepLen == 0) { + vt.add(stmp1); + return vt; + } + stmp2 = stmp1.substring(0, sepPos); + vt.add(stmp2); + stmp1 = stmp1.substring(sepPos + sepLen); + } while (stmp1.indexOf(sepStr) >= 0); + vt.add(stmp1); + } + catch (Exception e) {} + return vt; + } + + /** + * str2vt:ַָָָ,ɶάʸ + * @param source ַ + * @param sepStr1 ָһ + * @param sepStr2 ָ + * @param @return ʸ + * @return Vector + * @throws + * @since CodingExampleVer 1.1 + */ + public static Vector str2vt(String source, String sepStr1, String sepStr2) { + + if (source.indexOf(sepStr1) < 0) { return str2vt(source, sepStr2); } + Vector vector = str2vt(source, sepStr1); + Vector vector1 = new Vector<>(); + for (int i = 0; i < vector.size(); i++) + vector1.addElement(str2vt((String) vector.get(i), sepStr2)); + return vector1; + } + + /** + * str2vt:ַָָָ,άʸ + * @param source ַ + * @param sepStr1 ָһ + * @param sepStr2 ָ + * @param sepStr3 ָ + * @param @return ʸ + * @return Vector + * @throws + * @since CodingExampleVer 1.1 + */ + public static Vector str2vt(String source, String sepStr1, String sepStr2, String sepStr3) { + if (source.indexOf(sepStr1) < 0) { return str2vt(source, sepStr2, sepStr3); } + Vector vector = str2vt(source, sepStr1); + Vector vector1 = new Vector<>(); + for (int i = 0; i < vector.size(); i++) { + vector1.addElement(str2vt((String) vector.get(i), sepStr2, sepStr3)); + } + return vector1; + } + + /** + * str2vt:ַָָָ,άʸ + * @param source ַ + * @param sepStr1 ָһ + * @param sepStr2 ָ + * @param sepStr3 ָ + * @param sepStr4 ָ + * @param @return ʸ + * @return Vector + * @throws + * @since CodingExampleVer 1.1 + + public static Vector str2vt(String source, String sepStr1, String sepStr2, String sepStr3, String sepStr4) { + if (source.indexOf(sepStr1) < 0) { return str2vt(source, sepStr2, sepStr3, sepStr4); } + Vector vector = str2vt(source, sepStr1); + Vector vector1 = new Vector(); + for (int i = 0; i < vector.size(); i++) + vector1.addElement(str2vt((String) vector.get(i), sepStr2, sepStr3, sepStr4)); + return vector1; + } + */ + + /** + * getPreferenceHashMap:ϵͳֵ + * @param session tcsession + * @param scope + * @param pid ѡ + * @param @return 趨ļ + * @return HashMap + * @throws + * @since CodingExampleVer 1.1 + */ + @SuppressWarnings("deprecation") + public static String[] getPreference(TCSession session, int scope, String pid) { + try { + String options[] = session.getPreferenceService().getStringArray(scope, pid); + return options; + } + catch (Exception e) { + System.out.println("ûҵѡ:" + pid); + e.printStackTrace(); + return null; + } + + } + + /** + * getPreferenceHashMap:ϵͳֵ + * @param session tcsession + * @param scope + * @param pid ѡ + * @param @return 趨ļ + * @return HashMap + * @throws + * @since CodingExampleVer 1.1 + */ + public static HashMap getPreferenceHashMap(TCSession pSession, int pScope, String pid) { + HashMap hm = new HashMap(); + try { + String[] options = getPreference(pSession, pScope, pid); + if (options == null || options.length == 0) { + System.out.println("processRows(Vector, HashMap) - ************ û" + pid + "ѡ!"); + } + String key = ""; + String value = ""; + for (int i = 0; i < options.length; i++) { + if (options[i].indexOf("=") > 0) { + key = options[i].substring(0, options[i].indexOf("=")); + value = options[i].substring(options[i].indexOf("=") + 1); + hm.put(key, value); + } else { + hm.put("" + i, options[i]); + } + } + } + catch (Exception e) { + e.printStackTrace(); + return null; + } + return hm; + } + + public static InterfaceAIFComponent[] getQueryList(TCSession session, String queryName, String as[], String as1[]) { + System.out.println("begin=====query" + queryName + ""); + InterfaceAIFComponent[] components = null; + // ʹòѯ + try { + components = session.search(queryName, as, as1); + } + catch (Exception e) { + e.printStackTrace(); + MessageBox.post("querying " + queryName + " error" + e.getMessage(), "INFO", MessageBox.INFORMATION); + } + System.out.println("end=====query" + queryName + ""); + return components; + } + + // ======ϵͳѯѯݼ======= + public static TCComponent[] searchComponentCollection(TCSession session, String queryName, String as[], String as1[]) { + TCComponent returnaimancomponent[] = null; + try { + TCTextService textService = session.getTextService(); + TCComponentQueryType querytype = (TCComponentQueryType) session.getTypeComponent("ImanQuery"); + TCComponentQuery query = (TCComponentQuery) querytype.find(queryName); + querytype.clearCache(); + if(query == null){ + System.out.println("δҵѯ:" + queryName); + return null; + } + int asLen = as.length; + String tValue = ""; + for(int ix = 0; ix < asLen; ix++){ + tValue = textService.getTextValue(as[ix]); + if(tValue != null && !tValue.equals("")){ + as[ix] = tValue; + } + } + TCComponentContextList list = query.getExecuteResultsList(as, as1); + if (list != null && list.getListCount() > 0) { + int count = list.getListCount(); + returnaimancomponent = new TCComponent[count]; + for (int i = 0; i < count; i++) { + AIFComponentContext context = list.get(i); + returnaimancomponent[i] = (TCComponent) context.getComponent(); + } + return returnaimancomponent; + } else { + return null; + } + } + catch (TCException e) { + e.printStackTrace(); + } + return null; + } + + /** + * ضʽַת + * @param str ַ + * @param pattern ַģʽ磺yyyyMdգyyyy-MM-dd + * @return ڶ + * @throws java.text.ParseException + */ + public static Date convertStringToDate(String pattern, String str) { + Date date = null; + try { + if (str.equals("") || str == null) + return date; + + SimpleDateFormat formatter = new SimpleDateFormat(pattern); + date = formatter.parse(str); + } + catch (Exception e) { + e.printStackTrace(); + } + + return date; + } + + private static HashMap msghm = new HashMap<>(); + + public static synchronized void setMsg(String key, String msg) { + msghm.put(key, msg); + } + + public static synchronized String getMsg(String key) { + String msg = ""; + try { + if (msghm.get(key) == null) { + msg = ""; + } else { + msg = "" + msghm.get(key); + } + } + catch (Exception e) { + e.printStackTrace(); + } + return msg; + } + + /** + * getOptionValues:: ȡѡֵ䵽comboBox + * @param JComboBox + * @param String + * @author liqz + * @since 20111215 + * */ + public static void getOptionValues(TCSession pSession,JComboBox cbo,String strOptionName){ + @SuppressWarnings("deprecation") + String[] arrValue= pSession.getPreferenceService().getStringArray(4, strOptionName); + cbo.addItem(""); + for (int i = 0; i < arrValue.length; i++) { + cbo.addItem(arrValue[i]); + } + } + + /** + * getDaysBetween: + * + * @param Date + * + * @param Date + * + * @return int + */ + public static int getDaysBetween(Date dtFormer, Date dtLater) { + GregorianCalendar vFormer = (GregorianCalendar) GregorianCalendar.getInstance(); + GregorianCalendar vLatter = (GregorianCalendar) GregorianCalendar.getInstance(); + + vFormer.setTime(dtFormer); + vLatter.setTime(dtLater); + + vFormer.set(Calendar.MILLISECOND, 0); + vFormer.set(Calendar.SECOND, 0); + vFormer.set(Calendar.MINUTE, 0); + vFormer.set(Calendar.HOUR_OF_DAY, 0); + vLatter.set(Calendar.MILLISECOND, 0); + vLatter.set(Calendar.SECOND, 0); + vLatter.set(Calendar.MINUTE, 0); + vLatter.set(Calendar.HOUR_OF_DAY, 0); + + int iCounter = 0; + while (vFormer.before(vLatter)) { + vFormer.add(Calendar.DATE, 1); + iCounter++; + } + // iCounter = iCounter + 1; + return iCounter; + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/task/util/WriteAndCopyFile.java b/src/com/connor/lidy/task/util/WriteAndCopyFile.java new file mode 100644 index 0000000..e7107a9 --- /dev/null +++ b/src/com/connor/lidy/task/util/WriteAndCopyFile.java @@ -0,0 +1,75 @@ +/* +#============================================================================= +# +# copyright (c) 2009 Origin Enterprise Solution LTD. +# +#============================================================================= +# File name: WriteAndCopyFile.java +# File description: +#============================================================================= +# Date Name Action Description of Change +# 2011-4-20 liqz ʵֶļIJ(From Shaangu) +#============================================================================= +*/ +package com.connor.lidy.task.util; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.FileInputStream; + + +public class WriteAndCopyFile { + + /** + * Creates a new instance of WriteAndCopyFile. + */ + public WriteAndCopyFile() { + + } + + /** + * writeFile:дϢıļ + * @param @param fileName ļȫ· trueӡ + * @param @param append Ƿ񸽼ӵļβ + * @param @param content ļ + * @since CodingExampleVer 1.1 + */ + public void writeFile(String fileName, boolean append, String content) { + FileOutputStream fos; + try { + fos = new FileOutputStream(fileName, append); + fos.write(content.getBytes()); + fos.close(); + } catch (final FileNotFoundException e) { + e.printStackTrace(); + } catch (final IOException e) { + e.printStackTrace(); + } + } + /** + * copyFile:ʵļCopy + * + * @param @return 趨ļ + * @return String + * @throws + * @since CodingExampleVer 1.1 + */ + public static void copyFile(String src, String dest) throws IOException { + FileInputStream in = new FileInputStream(src); + File file = new File(dest); + if (!file.exists()) + file.createNewFile(); + FileOutputStream out = new FileOutputStream(file); + int c; + byte buffer[] = new byte[1024]; + while ((c = in.read(buffer)) != -1) { + for (int i = 0; i < c; i++) + out.write(buffer[i]); + } + in.close(); + out.close(); + } + +} diff --git a/src/com/connor/lidy/task/util/image/delete.png b/src/com/connor/lidy/task/util/image/delete.png new file mode 100644 index 0000000..1000b86 Binary files /dev/null and b/src/com/connor/lidy/task/util/image/delete.png differ diff --git a/src/com/connor/lidy/task/util/image/info.png b/src/com/connor/lidy/task/util/image/info.png new file mode 100644 index 0000000..48dd7d0 Binary files /dev/null and b/src/com/connor/lidy/task/util/image/info.png differ diff --git a/src/com/connor/lidy/util/LCombobox.java b/src/com/connor/lidy/util/LCombobox.java new file mode 100644 index 0000000..85ff67a --- /dev/null +++ b/src/com/connor/lidy/util/LCombobox.java @@ -0,0 +1,228 @@ +package com.connor.lidy.util; + +import java.awt.Component; +import java.awt.Dimension; +import java.awt.event.FocusEvent; +import java.awt.event.FocusListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; + +import javax.swing.DefaultComboBoxModel; +import javax.swing.DefaultListSelectionModel; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.JList; +import javax.swing.JTextField; +import javax.swing.ListCellRenderer; +import javax.swing.ListSelectionModel; +import javax.swing.plaf.basic.BasicComboPopup; +import javax.swing.plaf.basic.ComboPopup; +import javax.swing.plaf.metal.MetalComboBoxUI; + +public class LCombobox { + + public static void main(String[] args) { + String str[][] = new String[10][3]; + for (int i = 0; i < str.length; i++) { + str[i][0] = i + 6 + ""; + } + RwJComboBox jComboBox = new RwJComboBox(str); + jComboBox.setEditable(true); + jComboBox.setPreferredSize(new Dimension(400, 60)); + + // Խ¼ + + JFrame frame = new JFrame(); +// frame.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 20, 20)); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setSize(500, 500); + frame.setLocationRelativeTo(null); + frame.add(jComboBox); + frame.setVisible(true); + } + + public static class RwJComboBox extends JComboBox implements FocusListener { + /** + * + */ + private static final long serialVersionUID = 1L; + protected HashSet set = new HashSet(); + + public RwJComboBox(String str[][]) { + setModel(new RwDefaultComboBoxModel(str)); + setUI(new RwMetalComboBoxUI(this)); + setRenderer(new RwJCheckBox()); + setSelectedIndex(-1); +// ((javax.swing.JTextField)getEditor().getEditorComponent()).setEditable(false); +// ֹ༭Ĵ + } + + public void focusGained(FocusEvent e) { + } + + public void focusLost(FocusEvent e) { +// һµʹ÷ +// java.awt.Container container=(java.awt.Container)getEditor().getEditorComponent(); +// while(container!=null&&!(container instanceof javax.swing.JLabel)) +// { +// container=container.getParent(); +// } +// ((cLabel)container).setValue(((javax.swing.JTextField)getEditor().getEditorComponent()).getText()); + } + } + + private static class RwMetalComboBoxUI extends MetalComboBoxUI { + private RwMetalComboBoxUI(RwJComboBox rwJComboBox) { + this.comboBox = rwJComboBox; + } + + protected ComboPopup createPopup() { + return new RwBasicComboPopup(comboBox); + } + } + + private static class RwBasicComboPopup extends BasicComboPopup { + public RwBasicComboPopup(JComboBox combo) { + super(combo); + } + + protected void configureList() { + super.configureList(); + list.setSelectionModel(new RwDefaultListSelectionModel(comboBox)); + } + + protected MouseListener createListMouseListener() { + return new RwMouseAdapter(list, comboBox); + } + } + + private static class RwDefaultListSelectionModel extends DefaultListSelectionModel { + protected RwJComboBox rwJComboBox; + + public RwDefaultListSelectionModel(JComboBox comboBox) { + this.rwJComboBox = (RwJComboBox) comboBox; + } + + public boolean isSelectedIndex(int index) { + return rwJComboBox.set.contains(index); + } + } + + private static class RwMouseAdapter extends MouseAdapter { + protected JList list; + protected RwJComboBox rwJComboBox; + + private RwMouseAdapter(JList list, JComboBox comboBox) { + this.list = list; + this.rwJComboBox = (RwJComboBox) comboBox; + } + + public void mousePressed(MouseEvent anEvent) { + StringBuilder sb, sb1, sb2, sb3; + int k, index; + index = list.getSelectedIndex(); + JTextField jTextField = (JTextField) rwJComboBox.getEditor().getEditorComponent(); + sb = new StringBuilder(jTextField.getText()); + + if (sb.length() > 0 && ',' != sb.charAt(0)) + sb.insert(0, ","); + if (sb.length() > 0 && ',' != sb.charAt(sb.length() - 1)) + sb.append(","); + if (sb.length() > 0 && ",".equals(sb.toString())) + sb = new StringBuilder(); + if (list.getSelectionMode() == ListSelectionModel.MULTIPLE_INTERVAL_SELECTION) { + if (rwJComboBox.set.contains(index)) { + rwJComboBox.set.remove(index); + sb1 = new StringBuilder(); + sb1.append(",").append(rwJComboBox.getModel().getElementAt(index)).append(","); + k = sb.indexOf(sb1.toString()); + while (k != -1) { + sb.replace(k, k + sb1.length(), ","); + k = sb.indexOf(sb1.toString()); + } + } else { + rwJComboBox.set.add(index); + if (sb.length() == 0) + sb.append(",").append(rwJComboBox.getModel().getElementAt(index)).append(","); + else + sb.append(rwJComboBox.getModel().getElementAt(index)).append(","); + } + } else { + if (!rwJComboBox.set.contains(index)) { + rwJComboBox.set.clear(); + rwJComboBox.set.add(index); + } + } + Object obj; + sb2 = new StringBuilder(sb); + // 滻Ŀѡֵ + for (int i = 0; i < list.getModel().getSize(); i++) { + obj = list.getModel().getElementAt(i); + sb1 = new StringBuilder(); + sb1.append(",").append(obj).append(","); + k = sb2.indexOf(sb1.toString()); + while (k != -1) { + sb2.replace(k, k + sb1.length(), ","); + k = sb2.indexOf(sb1.toString()); + } + } + ArrayList list1 = new ArrayList(rwJComboBox.set); + Collections.sort(list1); + for (int i = 0; i < list1.size(); i++) { + obj = rwJComboBox.getModel().getElementAt(Integer.parseInt(list1.get(i).toString())); + sb1 = new StringBuilder(); + sb1.append(",").append(obj).append(","); + k = sb.indexOf(sb1.toString()); + if (k != -1 && sb2.indexOf(sb1.toString()) == -1) { + sb2.append(obj).append(","); + } + } + sb = new StringBuilder(sb2); + if (sb.length() > 0 && ',' == sb.charAt(0)) + sb.deleteCharAt(0); + if (sb.length() > 0 && ',' == sb.charAt(sb.length() - 1)) + sb.deleteCharAt(sb.length() - 1); + if (sb.length() > 0 && ",".equals(sb.toString())) + sb = new StringBuilder(); + jTextField.setText(sb.toString()); + // java.awt.Container container =jTextField; + // while(container!=null&&!(container instanceof javax.swing.JLabel)) + // { + // container=container.getParent(); + // } + // ((cLabel)container).setValue(sb.toString()); + rwJComboBox.repaint(); + list.repaint(); + } + } + + private static class RwDefaultComboBoxModel extends DefaultComboBoxModel { + private RwDefaultComboBoxModel(String[][] str) { + for (int i = 0; i < str.length; i++) + addElement(str[i][0]); + } + } + + private static class RwJCheckBox extends JCheckBox implements ListCellRenderer { + public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + setComponentOrientation(list.getComponentOrientation()); + if (isSelected) { + setBackground(list.getSelectionBackground()); + setForeground(list.getSelectionForeground()); + } else { + setBackground(list.getBackground()); + setForeground(list.getForeground()); + } + setEnabled(list.isEnabled()); + setSelected(isSelected); + setText(value == null ? "" : value.toString()); + setFont(list.getFont()); + return this; + } + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/util/MultiCombo.java b/src/com/connor/lidy/util/MultiCombo.java new file mode 100644 index 0000000..2927c50 --- /dev/null +++ b/src/com/connor/lidy/util/MultiCombo.java @@ -0,0 +1,236 @@ +package com.connor.lidy.util; + +import java.awt.Component; +import java.awt.event.FocusEvent; +import java.awt.event.FocusListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; + +import javax.swing.DefaultComboBoxModel; +import javax.swing.DefaultListSelectionModel; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JList; +import javax.swing.JTextField; +import javax.swing.ListCellRenderer; +import javax.swing.ListSelectionModel; +import javax.swing.plaf.basic.BasicComboPopup; +import javax.swing.plaf.basic.ComboPopup; +import javax.swing.plaf.metal.MetalComboBoxUI; + +@SuppressWarnings({ "rawtypes", "unchecked"}) +public class MultiCombo extends JComboBox implements FocusListener { + + /** + * + */ + private static final long serialVersionUID = 1L; + protected HashSet set = new HashSet(); + + public MultiCombo(String str[]) { + setModel(new RwDefaultComboBoxModel(str)); + setUI(new RwMetalComboBoxUI(this)); + setRenderer(new RwJCheckBox()); + setSelectedIndex(-1); +// ((JTextField)getEditor().getEditorComponent()).setEditable(true); +// ֹ༭Ĵ + } + + public void focusGained(FocusEvent e) { + + } + + public void focusLost(FocusEvent e) { +// һµʹ÷ +// java.awt.Container container=(java.awt.Container)getEditor().getEditorComponent(); +// while(container!=null&&!(container instanceof javax.swing.JLabel)) +// { +// container=container.getParent(); +// } +// ((cLabel)container).setValue(((javax.swing.JTextField)getEditor().getEditorComponent()).getText()); + } + + public void setEditable(boolean b) { + super.setEditable(b); + ((JTextField)getEditor().getEditorComponent()).setEditable(false); + } + + public String getText() { + return ((JTextField) this.getEditor().getEditorComponent()).getText(); + } + + private static class RwMetalComboBoxUI extends MetalComboBoxUI { + private RwMetalComboBoxUI(MultiCombo MultiCombo) { + this.comboBox = MultiCombo; + } + + protected ComboPopup createPopup() { + return new RwBasicComboPopup(comboBox); + } + } + + private static class RwBasicComboPopup extends BasicComboPopup { + /** + * + */ + private static final long serialVersionUID = 1L; + + public RwBasicComboPopup(JComboBox combo) { + super(combo); + } + + protected void configureList() { + super.configureList(); + list.setSelectionModel(new RwDefaultListSelectionModel(comboBox)); + } + + protected MouseListener createListMouseListener() { + return new RwMouseAdapter(list, comboBox); + } + } + + private static class RwDefaultListSelectionModel extends DefaultListSelectionModel { + /** + * + */ + private static final long serialVersionUID = 1L; + protected MultiCombo MultiCombo; + + public RwDefaultListSelectionModel(JComboBox comboBox) { + this.MultiCombo = (MultiCombo) comboBox; + } + + public boolean isSelectedIndex(int index) { + return MultiCombo.set.contains(index); + } + } + + private static class RwMouseAdapter extends MouseAdapter { + protected JList list; + protected MultiCombo MultiCombo; + + private RwMouseAdapter(JList list, JComboBox comboBox) { + this.list = list; + this.MultiCombo = (MultiCombo) comboBox; + } + + public void mousePressed(MouseEvent anEvent) { +// System.out.println("RwMouseAdapter"); + StringBuilder sb, sb1, sb2; + int k, index; + index = list.getSelectedIndex(); + JTextField jTextField = (JTextField) MultiCombo.getEditor().getEditorComponent(); + sb = new StringBuilder(jTextField.getText()); + + if (sb.length() > 0 && ';' != sb.charAt(0)) + sb.insert(0, ";"); + if (sb.length() > 0 && ';' != sb.charAt(sb.length() - 1)) + sb.append(";"); + if (sb.length() > 0 && ";".equals(sb.toString())) + sb = new StringBuilder(); + if (list.getSelectionMode() == ListSelectionModel.MULTIPLE_INTERVAL_SELECTION) { + if (MultiCombo.set.contains(index)) { + MultiCombo.set.remove(index); + sb1 = new StringBuilder(); + sb1.append(";").append(MultiCombo.getModel().getElementAt(index)).append(","); + k = sb.indexOf(sb1.toString()); + while (k != -1) { + sb.replace(k, k + sb1.length(), ";"); + k = sb.indexOf(sb1.toString()); + } + } else { + MultiCombo.set.add(index); + if (sb.length() == 0) + sb.append(";").append(MultiCombo.getModel().getElementAt(index)).append(";"); + else + sb.append(MultiCombo.getModel().getElementAt(index)).append(";"); + } + } else { + if (!MultiCombo.set.contains(index)) { + MultiCombo.set.clear(); + MultiCombo.set.add(index); + } + } + Object obj; + sb2 = new StringBuilder(sb); + // 滻Ŀѡֵ + for (int i = 0; i < list.getModel().getSize(); i++) { + obj = list.getModel().getElementAt(i); + sb1 = new StringBuilder(); + sb1.append(";").append(obj).append(";"); + k = sb2.indexOf(sb1.toString()); + while (k != -1) { + sb2.replace(k, k + sb1.length(), ";"); + k = sb2.indexOf(sb1.toString()); + } + } + ArrayList list1 = new ArrayList(MultiCombo.set); + Collections.sort(list1); + for (int i = 0; i < list1.size(); i++) { + obj = MultiCombo.getModel().getElementAt(Integer.parseInt(list1.get(i).toString())); + sb1 = new StringBuilder(); + sb1.append(";").append(obj).append(";"); + k = sb.indexOf(sb1.toString()); + if (k != -1 && sb2.indexOf(sb1.toString()) == -1) { + sb2.append(obj).append(";"); + } + } + sb = new StringBuilder(sb2); + if (sb.length() > 0 && ';' == sb.charAt(0)) + sb.deleteCharAt(0); + if (sb.length() > 0 && ';' == sb.charAt(sb.length() - 1)) + sb.deleteCharAt(sb.length() - 1); + if (sb.length() > 0 && ";".equals(sb.toString())) + sb = new StringBuilder(); + jTextField.setText(sb.toString()); + // java.awt.Container container =jTextField; + // while(container!=null&&!(container instanceof javax.swing.JLabel)) + // { + // container=container.getParent(); + // } + // ((cLabel)container).setValue(sb.toString()); + MultiCombo.repaint(); + list.repaint(); +// System.out.println("text:"+((JTextField) MultiCombo.getEditor().getEditorComponent()).getText()); + } + } + + private static class RwDefaultComboBoxModel extends DefaultComboBoxModel { + /** + * + */ + private static final long serialVersionUID = 1L; + + private RwDefaultComboBoxModel(String[] str) { + for (int i = 0; i < str.length; i++) + addElement(str[i]); + } + } + + private static class RwJCheckBox extends JCheckBox implements ListCellRenderer { + /** + * + */ + private static final long serialVersionUID = 1L; + + public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + setComponentOrientation(list.getComponentOrientation()); + if (isSelected) { + setBackground(list.getSelectionBackground()); + setForeground(list.getSelectionForeground()); + } else { + setBackground(list.getBackground()); + setForeground(list.getForeground()); + } + setEnabled(list.isEnabled()); + setSelected(isSelected); + setText(value == null ? "" : value.toString()); + setFont(list.getFont()); + return this; + } + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/util/ProgressReporterDialog.java b/src/com/connor/lidy/util/ProgressReporterDialog.java new file mode 100644 index 0000000..4d456ac --- /dev/null +++ b/src/com/connor/lidy/util/ProgressReporterDialog.java @@ -0,0 +1,143 @@ +package com.connor.lidy.util; + +import java.awt.BorderLayout; +import java.awt.Cursor; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.Toolkit; +import javax.swing.JLabel; +import javax.swing.JProgressBar; + +import com.teamcenter.rac.aif.AbstractAIFDialog; + +@SuppressWarnings("serial") +public class ProgressReporterDialog extends AbstractAIFDialog +{ + + private JLabel messageLabel; + + private JProgressBar progressBar; + + private boolean requestCanceling; + + private int percent; + + public ProgressReporterDialog(String title) + { + super(false); + + setLayout(new BorderLayout()); + setAlwaysOnTop(true); + + initializeComponents(); + setTitle(title); + registerComponentsListeners(); + addComponents(); + + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + } + public ProgressReporterDialog(Frame parent, String title) + { + super(parent, false); + + setLayout(new BorderLayout()); + setAlwaysOnTop(true); + + initializeComponents(); + setTitle(title); + registerComponentsListeners(); + addComponents(); + + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + } + + private void initializeComponents() + { + messageLabel = new JLabel(" ", JLabel.LEFT); + progressBar = new JProgressBar(); + } + + private void registerComponentsListeners() + { + } + + private void addComponents() + { + add(messageLabel, BorderLayout.NORTH); + add(progressBar, BorderLayout.SOUTH); + } + + public void centerToClientScreen() + { + Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); + + int x = screen.width - getWidth(); + int y = screen.height - getHeight(); + + setLocation(x / 2, y / 2); + } + + public void reportProgressMessage(String message) + { + messageLabel.setText(message); + } + + public void setProgressPercent(int percent) + { + this.percent = percent; + } + + public void setMaximum(int max){ + progressBar.setMaximum(max); + } + + public void setProgess(int i){ + progressBar.setValue(i); + } + + public void requestCanceling() + { + requestCanceling = true; + } + + public void run() + { + pack(); + setSize(400, getHeight()); + centerToClientScreen(); + setVisible(true); + + while (!requestCanceling) + { + if(percent > progressBar.getMaximum()) + { + percent = 0; + } + + progressBar.setValue(percent); + + percent += 5; + + try + { + Thread.sleep(100); + } + catch (InterruptedException e) + { + continue; + } + } + + dispose(); + } + + public int getProgess() + { + return progressBar.getValue(); + } + + public boolean isRequestCanceling() + { + return requestCanceling; + } +} diff --git a/src/com/connor/lidy/util/SelectUserDialog.java b/src/com/connor/lidy/util/SelectUserDialog.java new file mode 100644 index 0000000..4d79356 --- /dev/null +++ b/src/com/connor/lidy/util/SelectUserDialog.java @@ -0,0 +1,424 @@ +package com.connor.lidy.util; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Cursor; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.List; +import javax.swing.DefaultListModel; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.JTextField; +import javax.swing.JTree; +import javax.swing.ListCellRenderer; +import javax.swing.ListSelectionModel; +import javax.swing.tree.DefaultMutableTreeNode; + +import com.teamcenter.rac.aif.AbstractAIFDialog; +import com.teamcenter.rac.aif.common.AIFTreeNode; +import com.teamcenter.rac.aifrcp.AIFUtility; +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.TCComponentGroupMember; +import com.teamcenter.rac.kernel.TCComponentProject; +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 SelectUserDialog extends AbstractAIFDialog { + + 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 JTextField editPropMap; + private String group; + private boolean isMulti; + private JTable table; + private int[] colIndex; + private int rowIndex; + private TCComponentProject project; + + public SelectUserDialog(JTextField editPropMap, boolean isMulti) throws Exception { + super(true); + this.editPropMap = editPropMap; + this.isMulti = isMulti; + initUI(); + } + + private String getValue() { + String val = ""; + if (editPropMap != null) { + val = editPropMap.getText(); + } else if (table != null) { + val = (String) table.getValueAt(rowIndex, colIndex[0]); + } + return val; + } + + private void setValue(String text) { + if (editPropMap != null) { + editPropMap.setText(text); + } else if (table != null) { + table.setValueAt(text, rowIndex, colIndex[0]); + if (colIndex.length>1) + table.setValueAt(group, rowIndex, colIndex[1]); + } + } + + public SelectUserDialog(JTable table, boolean isMulti, int[] colIndex, int rowIndex, TCComponentProject projectID) throws Exception { + super(true); + this.table = table; + this.isMulti = isMulti; + this.colIndex = colIndex; + this.rowIndex = rowIndex; + this.project = projectID; + initUI(); + } + + private void initUI() throws Exception { + this.setTitle("ѡԱ"); + 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 = 640; + mweight = 480; + } + if(project != null) { + pheight = 700; + mheight = 700; + } + this.setPreferredSize(new Dimension(pweight, pheight)); + this.setMinimumSize(new Dimension(mweight, mheight)); + OrgTreePanel orgPanel = new OrgTreePanel((TCSession) AIFUtility.getCurrentApplication().getSession()); + this.tree = orgPanel.getOrgTree(); + + 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); + } + this.add(BorderLayout.SOUTH, initBtnPanel()); + if (isMulti) { + JPanel lp = initListPanel(); + this.add(BorderLayout.EAST, lp); + initData(); + } + addListeners(); + } + + 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 panel = new JPanel(new BorderLayout()); + FlowLayout flow = new FlowLayout(); + flow.setVgap(100); + JPanel btnPanel = new JPanel(flow); + btnPanel.add(this.add); +// btnPanel.add("2.1.center.center", this.remove); + this.lm_user = new DefaultListModel<>(); + this.l_user = new JList<>(lm_user); + l_user.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + this.l_user.setCellRenderer(new DeleteListRenderer(l_user)); + JScrollPane scroll = new JScrollPane(l_user); + scroll.setPreferredSize(new Dimension(200, 0)); +// this.add.setPreferredSize(new Dimension(50, 30)); + panel.add(BorderLayout.WEST, btnPanel); + panel.add(BorderLayout.CENTER, scroll); + return panel; + } + + private JPanel initBtnPanel() { + JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 5)); + this.b_ok = new JButton("ȷ"); + 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 {//TODO + 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) { + if(projectTree == null) + return null; + else if(projectTree.getSelectionModel() == null) + return null; + else if(projectTree.getLastSelectedPathComponent() == null) + return null; + DefaultMutableTreeNode selectNode = (DefaultMutableTreeNode) projectTree.getLastSelectedPathComponent(); + Object selectObject = selectNode.getUserObject(); + if(selectObject instanceof TCComponentGroupMember) { + String member = ((TCComponentGroupMember) selectObject).toString(); + if(member.indexOf(".")>0) + group = member.substring(0, member.indexOf(".")); + else + group = member.substring(0, member.indexOf("/")); + TCComponentUser user = ((TCComponentGroupMember) selectObject).getUser(); + if (user != null) { + return user.getProperty("user_name"); + } + }else + 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(); + return user.getProperty("user_name"); + } + } + } + return null; + } + + private void addListeners() { + this.b_cel.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + disposeDialog(); + } + }); + this.b_ok.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + try { + 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(""); + } + } + 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(); + if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) { + String user = getSelectUser(); + System.out.println("user:"+user); + if (user != null) { + if (isMulti) { + if (!lm_user.contains(user.toString())) { + lm_user.addElement(user.toString()); + } + } else { + setValue(user.toString()); + disposeDialog(); + } + } + } + } catch (Exception e1) { + e1.printStackTrace(); + MessageBox.post("Error:"+e1.getMessage(), "ERROR", MessageBox.ERROR); + } + } + }); + 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.toString())) { + lm_user.addElement(user.toString()); + } + } else { + setValue(user.toString()); + disposeDialog(); + } + } + } + } catch (Exception e1) { + e1.printStackTrace(); + MessageBox.post("Error:"+e1.getMessage(), "ERROR", MessageBox.ERROR); + } + } + }); + } + if(isMulti) { + 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); + } + }); + } + this.add.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + try { + String user = getSelectUser(); + System.out.println("user:"+user); + if (user != null) { + if (!lm_user.contains(user.toString())) { + lm_user.addElement(user.toString()); + } + } + } catch (Exception e1) { + e1.printStackTrace(); + MessageBox.post("Error:"+e1.getMessage(), "ERROR", MessageBox.ERROR); + } + } + }); + this.remove.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + disposeDialog(); + } + }); + } + private class DeleteListRenderer extends JPanel implements ListCellRenderer { + + JButton btn; + JLabel label; + + public DeleteListRenderer(final JList list) { + this.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 1)); + this.setBackground(Color.WHITE); + btn = getDeletetBtn(); + label = new JLabel(""); + this.add(btn); + this.add(label); + + btn.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + int ind = list.getSelectedIndex(); + System.out.println(ind); + if (ind >= 0) { + list.remove(ind); + } + } + }); + + } + @Override + public Component getListCellRendererComponent(JList list, String value, int index, + boolean isSelected, boolean cellHasFocus) { + label.setText(value); + return this; + } + private JButton getDeletetBtn() { + ImageIcon icon = new ImageIcon(SelectUserDialog.class.getResource("image/delete.png")); + JButton btn = new JButton(icon); + btn.setPreferredSize(new Dimension(23, 23)); + btn.setContentAreaFilled(false); + btn.setFocusPainted(false); + btn.setBorderPainted(false); + btn.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); + return btn; + } + } +} diff --git a/src/com/connor/lidy/util/SqlUtil.java b/src/com/connor/lidy/util/SqlUtil.java new file mode 100644 index 0000000..257d7cb --- /dev/null +++ b/src/com/connor/lidy/util/SqlUtil.java @@ -0,0 +1,685 @@ +package com.connor.lidy.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 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(); + 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()) { + HashMap dataTable = new HashMap(); + + 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]); + } + 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/lidy/util/TCUtil.java b/src/com/connor/lidy/util/TCUtil.java new file mode 100644 index 0000000..9c88ab6 --- /dev/null +++ b/src/com/connor/lidy/util/TCUtil.java @@ -0,0 +1,415 @@ +package com.connor.lidy.util; + +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.Toolkit; +import java.io.BufferedReader; +import java.io.File; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Vector; + +import javax.swing.JFileChooser; +import javax.swing.JOptionPane; +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.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.TCComponentRevisionRule; +import com.teamcenter.rac.kernel.TCException; +import com.teamcenter.rac.kernel.TCQueryClause; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.kernel.TCUserService; +import com.teamcenter.rac.util.MessageBox; +import com.teamcenter.services.rac.workflow.WorkflowService; +import com.teamcenter.services.rac.workflow._2008_06.Workflow.ContextData; +import com.teamcenter.services.rac.workflow._2008_06.Workflow.InstanceInfo; + +@SuppressWarnings("deprecation") +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 TCComponentBOMWindow getWindow(TCSession session) throws Exception{ + TCComponentBOMWindow window = null; + TCComponentBOMWindowType bomWinType = (TCComponentBOMWindowType) session.getTypeComponent("BOMWindow"); + window = bomWinType.create(null); + return window; + } + public static TCComponentBOMWindow getWindow(TCSession session, TCComponentRevisionRule rule) throws Exception{ + TCComponentBOMWindow window = null; + TCComponentBOMWindowType bomWinType = (TCComponentBOMWindowType) session.getTypeComponent("BOMWindow"); + window = bomWinType.create(rule); + return window; + } + + 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(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 Frame()); + 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 File saveExcelChooserAsk(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(null); + 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()) { + int choose = JOptionPane.showOptionDialog(chooser, "ļѴڣǷ滻?", "ʾ", + JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new String[] {"",""}, ""); + if(choose==0) + dir.delete(); + else + dir = saveExcelChooserAsk(dir.getPath()); + } +// System.out.println("saveExcelChooser1:" + dir.getPath()); + } +// new Thread() { +// public void run() { +// +// } +// }; + 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.contains("#") || !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(TCSession session, boolean val) { + try { + TCUserService userservice = session.getUserService(); + userservice.call(val ? "CONNOR_open_bypass" : "CONNOR_close_bypass", new Object[] { "" }); + System.out.println(val ? "Open Bypass" : "Close Bypass"); + } catch (Exception e) { + e.printStackTrace(); + } + } + public static String workflow(TCSession session, String[] uid, String workFlowName, String templateName) { + // String uid = rev.getUid(); + // + System.out.println("workflow:"+workFlowName); + WorkflowService wfService = WorkflowService.getService(session); + ContextData contextData = new ContextData(); + + String observerKey = ""; + String name = workFlowName; + String subject = ""; + String description = ""; + + contextData.processTemplate = templateName; // update with your own ProcessTemplate. + contextData.subscribeToEvents = false; + contextData.subscriptionEventCount = 0; + contextData.attachmentCount = uid.length; + contextData.attachments = uid ; + int [] types = new int[uid.length]; + for(int i = 0;i 0) { + String error = Arrays.toString(info.serviceData.getPartialError(0).getMessages()); + System.out.println("error:"+error); + return error; + } +// System.out.println("info:"+info); +// if(info != null) { +// TCComponent c = info.serviceData.getPlainObject(0); +// System.out.println("info:"+c+"=="+c.getUid()); +// } + return ""; + } +} diff --git a/src/com/connor/lidy/util/TYBKJFilterComboBox.java b/src/com/connor/lidy/util/TYBKJFilterComboBox.java new file mode 100644 index 0000000..2342c28 --- /dev/null +++ b/src/com/connor/lidy/util/TYBKJFilterComboBox.java @@ -0,0 +1,419 @@ +package com.connor.lidy.util; + +import java.awt.Component; +import java.awt.event.FocusEvent; +import java.awt.event.FocusListener; +import java.awt.event.ItemEvent; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.util.Vector; + +import javax.swing.ComboBoxModel; +import javax.swing.DefaultComboBoxModel; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.ListCellRenderer; +import javax.swing.SwingUtilities; +import javax.swing.event.ListDataEvent; +import javax.swing.plaf.basic.BasicComboPopup; +import javax.swing.plaf.basic.ComboPopup; +import javax.swing.plaf.metal.MetalComboBoxUI; + +/** + * Զ + * @author Sun + * + */ +@SuppressWarnings({ "serial", "rawtypes", "unchecked" }) +public class TYBKJFilterComboBox extends JComboBox { + + /** + * ʾģ + */ + protected static DefaultComboBoxModel showModel = new DefaultComboBoxModel<>(); + /** + * ѡ + */ + private boolean selectingItem; + + /** + * һJFilterComboBox + * ȡеComboBoxModel + * ṩComboBoxModel + * ʹô˹췽Ͽ򲻴ĬϿģͣ + * Ӱ롢ƳӷΪʽ + * @param aModel - ṩʾб ComboBoxModel + */ + public TYBKJFilterComboBox(ComboBoxModel aModel) { + super(aModel); + initialize(); + } + + /** + * ָеԪص JFilterComboBox + * Ĭ£ѡеĵһҲѡ˸ģͣ + * @param items - Ҫ뵽ϿĶ + */ + public TYBKJFilterComboBox(final Object items[]) { + super(items); + initialize(); + } + + /** + * ָ Vector еԪص JFilterComboBox + * Ĭ£ѡеĵһҲѡ˸ģͣ + * @param items - Ҫ뵽Ͽ + */ + public TYBKJFilterComboBox(Vector< ?> items) { + super(items); + initialize(); + } + + /** + * Ĭģ͵ JFilterComboBox + * ĬϵģΪնбʹ addItem  + * Ĭ£ѡģеĵһ + */ + public TYBKJFilterComboBox() { + super(); + initialize(); + } + + private void initialize() { + showModel.addListDataListener(this); + } + + @Override + public void updateUI() { + setUI(new MetalFilterComboBoxUI()); + ListCellRenderer renderer = getRenderer(); + if (renderer instanceof Component) { + SwingUtilities.updateComponentTreeUI((Component) renderer); + } + } + + @Override + public Object getSelectedItem() { + return showModel.getSelectedItem(); + } + + @Override + public void setSelectedItem(Object anObject) { + Object oldSelection = selectedItemReminder; + Object objectToSelect = anObject; + if (oldSelection == null || !oldSelection.equals(anObject)) { + + if (anObject != null && !isEditable()) { + boolean found = false; + for (int i = 0; i < showModel.getSize(); i++) { + Object element = showModel.getElementAt(i); + if (anObject.equals(element)) { + found = true; + objectToSelect = element; + break; + } + } + if (!found) { + return; + } + } + + selectingItem = true; + showModel.setSelectedItem(objectToSelect); + selectingItem = false; + + if (selectedItemReminder != showModel.getSelectedItem()) { + selectedItemChanged(); + } + } + fireActionEvent(); + } + + @Override + public void setSelectedIndex(int anIndex) { + int size = showModel.getSize(); + if (anIndex == -1 || size == 0) { + setSelectedItem(null); + } else if (anIndex < -1) { + throw new IllegalArgumentException("setSelectedIndex: " + anIndex + + " out of bounds"); + } else if (anIndex >= size) { + setSelectedItem(showModel.getElementAt(size - 1)); + } else { + setSelectedItem(showModel.getElementAt(anIndex)); + } + } + + @Override + public int getSelectedIndex() { + Object sObject = showModel.getSelectedItem(); + int i, c; + Object obj; + + for (i = 0, c = showModel.getSize(); i < c; i++) { + obj = showModel.getElementAt(i); + if (obj != null && obj.equals(sObject)) + return i; + } + return -1; + } + + @Override + public void contentsChanged(ListDataEvent e) { + Object oldSelection = selectedItemReminder; + Object newSelection = showModel.getSelectedItem(); + if (oldSelection == null || !oldSelection.equals(newSelection)) { + selectedItemChanged(); + if (!selectingItem) { + fireActionEvent(); + } + } + } + + @Override + protected void selectedItemChanged() { + if (selectedItemReminder != null) { + fireItemStateChanged(new ItemEvent(this, ItemEvent.ITEM_STATE_CHANGED, selectedItemReminder, ItemEvent.DESELECTED)); + } + + selectedItemReminder = showModel.getSelectedItem(); + + if (selectedItemReminder != null) { + fireItemStateChanged(new ItemEvent(this, ItemEvent.ITEM_STATE_CHANGED, selectedItemReminder, ItemEvent.SELECTED)); + } + } + + @Override + public void intervalAdded(ListDataEvent e) { + if (selectedItemReminder != showModel.getSelectedItem()) { + selectedItemChanged(); + } + } + + @Override + public void setEditable(boolean aFlag) { + super.setEditable(true); + } + + /** + * ʾģ + * @return + */ + public DefaultComboBoxModel getShowModel() { + return showModel; + } + + /** + * Metal L&F UI + * @author Sun + * + */ + class MetalFilterComboBoxUI extends MetalComboBoxUI { + + /** + * ༭¼ + */ + protected EditorListener editorListener; + /** + * UI ฺƵĿؼ + */ + protected TYBKJFilterComboBox filterComboBox; + + @Override + public void installUI(JComponent c) { + filterComboBox = (TYBKJFilterComboBox) c; + filterComboBox.setEditable(true); + super.installUI(c); + } + + @Override + public void configureEditor() { + super.configureEditor(); + editor.addKeyListener(getEditorListener()); + editor.addMouseListener(getEditorListener()); + editor.addFocusListener(getEditorListener()); + } + + @Override + public void unconfigureEditor() { + super.unconfigureEditor(); + if (editorListener != null) { + editor.removeKeyListener(editorListener); + editor.removeMouseListener(editorListener); + editor.removeFocusListener(editorListener); + editorListener = null; + } + } + + @Override + protected ComboPopup createPopup() { + return new FilterComboPopup(filterComboBox); + } + + /** + * ʼر༭¼ + * @return + */ + protected EditorListener getEditorListener() { + if (editorListener == null) { + editorListener = new EditorListener(); + } + return editorListener; + } + + /** + * ؼֽвѯ÷Умֲѯ㷨 + */ + protected void findMatchs() { + ComboBoxModel model = filterComboBox.getModel(); + DefaultComboBoxModel showModel = filterComboBox.getShowModel(); + showModel.removeAllElements(); + for (int i = 0; i < model.getSize(); i++) { + String name = model.getElementAt(i).toString(); + if (name.toLowerCase().indexOf(getEditorText1()) >= 0) { + showModel.addElement(model.getElementAt(i)); + } + } + ((FilterComboPopup)popup ).repaint(); + } + + /** + * ر༭ı + * @return + */ + private String getEditorText() { + return filterComboBox.getEditor().getItem().toString(); + } + private String getEditorText1() { + return filterComboBox.getEditor().getItem().toString().toLowerCase(); + } + + /** + * + * @author Sun + * + */ + class FilterComboPopup extends BasicComboPopup { + + public FilterComboPopup(JComboBox combo) { + super(combo); + } + + @Override + protected JList createList() { + JList list = super.createList(); + list.setModel(filterComboBox.getShowModel()); + return list; + } + + @Override + public void setVisible(boolean b) { + super.setVisible(b); + if (!b) { + comboBox.getEditor().setItem(comboBox.getSelectedItem()); + } + } + + @Override + public void show() { + findMatchs(); + super.show(); + } + + } + + /** + * ༭¼ + * @author Sun + * + */ + class EditorListener implements KeyListener,MouseListener, FocusListener { + + /** + * ıڼʱıȶ + */ + private String oldText = ""; + + + public void keyReleased(KeyEvent e) { + String newText = getEditorText(); + if (!newText.equals(oldText)) { + findMatchs(); + } + } + + + public void keyPressed(KeyEvent e) { + oldText = getEditorText(); + if (!isPopupVisible(filterComboBox)) { + setPopupVisible(filterComboBox, true); + } + } + + + public void keyTyped(KeyEvent e) { + findMatchs(); + } + + + public void mouseClicked(MouseEvent e) {} + + + public void mousePressed(MouseEvent e) { + if (!isPopupVisible(filterComboBox)) { + setPopupVisible(filterComboBox, true); + } + } + + + public void mouseReleased(MouseEvent e) {} + + + public void mouseEntered(MouseEvent e) {} + + + public void mouseExited(MouseEvent e) {} + + + public void focusGained(FocusEvent e) { + if (!isPopupVisible(filterComboBox)) { + setPopupVisible(filterComboBox, true); + } + } + + + public void focusLost(FocusEvent e) {} + + } + + } + + /** + * ʹʾ + * @param args + */ + public static void main(String... args) { + Vector< String> data = new Vector< String>(0); + data.add("ab"); + data.add("ac"); + data.add("bb"); + data.add("cc"); + JPanel panel = new JPanel(); + TYBKJFilterComboBox combobox=new TYBKJFilterComboBox(data); +// combobox.addItem("abc"); + combobox.setSelectedIndex(-1);//.setSelectedItem(null); + panel.add(combobox); + JFrame frame = new JFrame(); + frame.setSize(400, 300); + frame.setLocationRelativeTo(null); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setContentPane(panel); + frame.setVisible(true); + } + +} \ No newline at end of file diff --git a/src/com/connor/lidy/util/util.properties b/src/com/connor/lidy/util/util.properties new file mode 100644 index 0000000..7120aee --- /dev/null +++ b/src/com/connor/lidy/util/util.properties @@ -0,0 +1,24 @@ +SQL.URL=jdbc:sqlserver://10.128.10.50:1433;DatabaseName=Basedb_2012 +SQL.DRIVER=com.microsoft.sqlserver.jdbc.SQLServerDriver +SQL.USER=PLMUser +SQL.PASSWORD=PLMUser + +SQL.TCDATA.URL=jdbc:oracle:thin:@192.168.0.103:1521:TC +SQL.TCDATA.DRIVER=oracle.jdbc.driver.OracleDriver +SQL.TCDATA.USER=infodba +SQL.TCDATA.PASSWORD=infodba + +SQL.TEMPLATE_TREE=select t.PmpcCode, t.PmpcCompanyCode, t.PmpcName, t.PmpcUpperCode, t.PmpcItem, t.PmpcPrhCode, t.PmpcEnd from CcemVW_Pmpc t; +SQL.TEMPLATE=select t.PrhName,t.PrdLine,t.PrdNo,t.PrdFeatureCode,t.FeatureName,t.PrdCanInput,t.PrdRightSign from CcemVW_Prd t where t.prhcode = ? order by t.PrdNo +SQL.LOV=select t.PrddNo,t.PrddFeatureCode,t.PrddValue from CcemVW_Prdd t where t.PrddDisabled=0 and t.PrddCode = ? and PrddLine = ? order by t.PrddNo + +DATARELEASE.CHECKPROP=s8WSOType +DATARELEASE.RELEASESTATUS=S81Delivered +DATARELEASE.OTHER=����Ʒ�� +DATARELEASE.ROLE=�Ŀ�רԱ +DATARECEIVE.GROUP=���ݽ����� + +SQL.SQLSERVER.DRIVER=com.microsoft.sqlserver.jdbc.SQLServerDriver +SQL.SQLSERVER.URL=jdbc:sqlserver://192.168.220.129:1433;DatabaseName=TC13 +SQL.SQLSERVER.USER=infodba +SQL.SQLSERVER.PASSWORD=infodba \ No newline at end of file diff --git a/src/com/connor/lidy/workflow/BatchTaskCreateDialog.java b/src/com/connor/lidy/workflow/BatchTaskCreateDialog.java new file mode 100644 index 0000000..06eb9ea --- /dev/null +++ b/src/com/connor/lidy/workflow/BatchTaskCreateDialog.java @@ -0,0 +1,131 @@ +package com.connor.lidy.workflow; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.ArrayList; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JPanel; + +import com.connor.lidy.util.TCUtil; +import com.connor.lidy.util.TYBKJFilterComboBox; +import com.teamcenter.rac.aif.AbstractAIFDialog; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCComponentTaskTemplate; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; +import com.teamcenter.rac.util.PropertyLayout; +import com.teamcenter.services.rac.workflow.WorkflowService; +import com.teamcenter.services.rac.workflow._2013_05.Workflow.GetWorkflowTemplatesInputInfo; +import com.teamcenter.services.rac.workflow._2013_05.Workflow.GetWorkflowTemplatesOutput; +import com.teamcenter.services.rac.workflow._2013_05.Workflow.GetWorkflowTemplatesResponse; + +@SuppressWarnings("unchecked") +public class BatchTaskCreateDialog extends AbstractAIFDialog { + private static final long serialVersionUID = 1L; + + private TCSession session; + private JButton exportBtn; + private JButton cancelBtn; + private TYBKJFilterComboBox comps; +// private HashMap map; + private ArrayList alltemps; + private ArrayList filters; + + public BatchTaskCreateDialog(TCSession session, String[] options, ArrayList revs) throws Exception { + super(AIFUtility.getActiveDesktop()); + this.session = session; + this.alltemps = new ArrayList<>(); + this.filters = new ArrayList<>(); + + setTitle(""); + JPanel propPanel = new JPanel(new PropertyLayout(40, 5, 10, 5, 5, 5)); + + JLabel label1 = new JLabel(""); + propPanel.add("1.1.left.center", label1); + comps = new TYBKJFilterComboBox(); + comps.addItem(""); + String[] key = new String[]{ "ģ", "׶" }; + String[] val = new String[]{ "0", "1;2" }; + TCComponent[] results = TCUtil.query(session, "SearchWorkflowTemplate", key, val); + for(TCComponent c : results) { + if(!(c instanceof TCComponentTaskTemplate)) + continue; +// comps.addItem(c.getProperty("object_name")); +// map.put(c.getProperty("object_name"), (TCComponentTaskTemplate) c); + alltemps.add(c.getProperty("object_name")); + } + + GetWorkflowTemplatesInputInfo[] info = new GetWorkflowTemplatesInputInfo[1]; + info[0] = new GetWorkflowTemplatesInputInfo(); + info[0].group = session.getGroup().getFullName(); + info[0].objectTypes = new String[] { revs.get(0).getType() }; + info[0].getFiltered = true; + if(info[0].group.equals("dba")) { + info[0].includeUnderConstruction = true; + }else { + info[0].includeUnderConstruction = false; + } + System.out.println("info:"+info[0].objectTypes[0]+"+++"+info[0].group); +// Templates templates = WorkflowService.getService(session).getWorkflowTemplates(new TCComponentItemRevision[]{ revs.get(0) }, info.group); + GetWorkflowTemplatesResponse outputs = WorkflowService.getService(session).getWorkflowTemplates(info); + if(outputs.templatesOutput!=null && outputs.templatesOutput.length>0) { + GetWorkflowTemplatesOutput templates = outputs.templatesOutput[0]; + System.out.println("templates:"+templates.workflowTemplates.length); + for(TCComponentTaskTemplate t : templates.workflowTemplates) { + comps.addItem(t.getProperty("object_name")); + filters.add(t.getProperty("object_name")); + } + } + + comps.setPreferredSize(new Dimension(200, 23)); + comps.setSelectedItem(""); + comps.setPopupVisible(false); + propPanel.add("1.2.right.center", comps); + + exportBtn = new JButton("ȷ"); + cancelBtn = new JButton("ȡ"); + JPanel btnPanel = new JPanel(new FlowLayout()); + btnPanel.add(exportBtn); + btnPanel.add(cancelBtn); + setLayout(new BorderLayout()); + add(BorderLayout.CENTER, propPanel); + add(BorderLayout.SOUTH, btnPanel); +// add(new JLabel("")); + addActionListener(revs); + + pack(); + setSize(new Dimension(350, 150)); + 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 revs) { + exportBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + try { + new BatchTaskCreateOperation(BatchTaskCreateDialog.this, session, comps, revs).executeOperation(); + dispose(); + }catch(Exception e1) { + e1.printStackTrace(); + MessageBox.post(BatchTaskCreateDialog.this, ""+e1.getMessage(), "ERROR", MessageBox.ERROR); + } + } + }); + cancelBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + dispose(); + } + }); + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/workflow/BatchTaskCreateHandler.java b/src/com/connor/lidy/workflow/BatchTaskCreateHandler.java new file mode 100644 index 0000000..25f22d3 --- /dev/null +++ b/src/com/connor/lidy/workflow/BatchTaskCreateHandler.java @@ -0,0 +1,59 @@ +package com.connor.lidy.workflow; + +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.AbstractAIFUIApplication; +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 BatchTaskCreateHandler extends AbstractHandler implements IHandler{ + + public Object execute(ExecutionEvent arg0) throws ExecutionException { + System.out.println("BatchTaskCreateHandler"); + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + try { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + ArrayList revs = new ArrayList<>(); + InterfaceAIFComponent[] targets = app.getTargetComponents(); + for(InterfaceAIFComponent t : targets) { + if(!(t instanceof TCComponentItemRevision)) { + MessageBox.post(desktop, "ѡ"+t+"ڰ汾", "ERROR", MessageBox.ERROR); + return null; + } + revs.add((TCComponentItemRevision) t); + } + String type = ""; + for(TCComponentItemRevision rev : revs) { + if(type.isEmpty()) { + type = rev.getType(); + continue; + } + if(!type.equals(rev.getType())) { + MessageBox.post(desktop, "ѡͬһͣ", "ERROR", MessageBox.ERROR); + return null; + } + } + TCSession session = (TCSession) app.getSession(); +// String options[] = session.getPreferenceService().getStringValues("Meling_SqlServer"); +// if(options==null || options.length<4) { +// MessageBox.post(desktop, "ѡMeling_SqlServeròȷ", "ERROR", MessageBox.ERROR); +// return null; +// } + new BatchTaskCreateDialog(session, null, revs); + }catch(Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + } + return null; + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/workflow/BatchTaskCreateOperation.java b/src/com/connor/lidy/workflow/BatchTaskCreateOperation.java new file mode 100644 index 0000000..2db1f88 --- /dev/null +++ b/src/com/connor/lidy/workflow/BatchTaskCreateOperation.java @@ -0,0 +1,70 @@ +package com.connor.lidy.workflow; + +import java.util.ArrayList; + +import javax.swing.JComboBox; + +import com.connor.lidy.util.ProgressReporterDialog; +import com.connor.lidy.util.TCUtil; +import com.teamcenter.rac.aif.AIFDesktop; +import com.teamcenter.rac.aif.AbstractAIFDialog; +import com.teamcenter.rac.aif.AbstractAIFOperation; +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 BatchTaskCreateOperation extends AbstractAIFOperation { + + private AbstractAIFDialog dialog; + private TCSession session; + private JComboBox combo; + private ArrayList revs; + + public BatchTaskCreateOperation(AbstractAIFDialog dialog, TCSession session, JComboBox combo, ArrayList revs) { + this.dialog = dialog; + this.session = session; + this.combo = combo; + this.revs = revs; + } + + @Override + public void executeOperation() throws Exception { + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + ProgressReporterDialog reporter = new ProgressReporterDialog("ʾ"); + try { + String temp = combo.getSelectedItem().toString(); + int size = revs.size(); + reporter.reportProgressMessage("ڴ̣0/"+size+""); + reporter.pack(); + reporter.setSize(400, 100); + reporter.centerToClientScreen(); + reporter.setVisible(true); + reporter.setMaximum(size); + new Thread() { + public void run(){ + int i = 0; + StringBuilder sb = new StringBuilder(""); + for(TCComponentItemRevision rev : revs) { + System.out.println("create:"+rev); + String result = TCUtil.workflow(session, new String[] { rev.getUid() }, rev.toString(), temp); + if(!result.isEmpty()) { + sb.append(rev).append(" ⣺").append(result).append("\n"); + } + reporter.setProgess(i++); + reporter.reportProgressMessage("ڴ̣"+i+"/"+size+""); + } + reporter.dispose(); + if(sb.length()==0) + MessageBox.post(dialog, "̴", "INFO", MessageBox.INFORMATION); + else + MessageBox.post(dialog, sb.toString(), "INFO", MessageBox.WARNING); + } + }.start(); + } catch (Exception e) { + reporter.dispose(); + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + } + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/workflow/CodeCreateReportDialog.java b/src/com/connor/lidy/workflow/CodeCreateReportDialog.java new file mode 100644 index 0000000..955fe23 --- /dev/null +++ b/src/com/connor/lidy/workflow/CodeCreateReportDialog.java @@ -0,0 +1,101 @@ +package com.connor.lidy.workflow; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JPanel; +import com.teamcenter.rac.aif.AbstractAIFDialog; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.stylesheet.PropertyDateComponent; +import com.teamcenter.rac.util.MessageBox; +import com.teamcenter.rac.util.PropertyLayout; + +public class CodeCreateReportDialog extends AbstractAIFDialog { + private static final long serialVersionUID = 1L; + private TCSession session; + private TCComponentDataset model; + private JButton exportBtn; + private JButton cancelBtn; + private PropertyDateComponent[] comps; + + public CodeCreateReportDialog(TCSession session, String[] options, TCComponentDataset model) throws Exception { + super(AIFUtility.getActiveDesktop()); + this.session = session; + this.model = model; + this.comps = new PropertyDateComponent[2]; + + setTitle("봴"); + JPanel propPanel = new JPanel(new PropertyLayout(70, 5, 10, 5, 5, 5)); + + JLabel label1 = new JLabel("ʱ"); + propPanel.add("1.1.left.center", label1); + PropertyDateComponent date1 = new PropertyDateComponent(); + date1.setPreferredSize(new Dimension(155, 23)); + propPanel.add("1.2.right.center", date1); + comps[0] = date1; + + JLabel label2 = new JLabel("ʱ"); + propPanel.add("2.1.left.center", label2); + PropertyDateComponent date2 = new PropertyDateComponent(); + date2.setPreferredSize(new Dimension(155, 23)); + propPanel.add("2.2.right.center", date2); + comps[1] = date2; + + exportBtn = new JButton(""); + cancelBtn = new JButton("ȡ"); + JPanel btnPanel = new JPanel(new FlowLayout()); + btnPanel.add(exportBtn); + btnPanel.add(cancelBtn); + setLayout(new BorderLayout()); + add(BorderLayout.CENTER, propPanel); + add(BorderLayout.SOUTH, btnPanel); +// add(new JLabel("")); + addActionListener(options); + + pack(); + setSize(new Dimension(350, 200)); + 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) { + exportBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { +// ProgressReporterDialog reporter = new ProgressReporterDialog("ʾ"); +// reporter.reportProgressMessage("ڵԺ..."); +// new Thread(reporter).start(); +// new Thread() { +// public void run(){ +// } +// }.start(); + try { +// SimpleDateFormat sdf = new SimpleDateFormat("d-MMM-yyyy hh:mm"); + +// new CodeCreateReportOperation(session, options, tasks, comps, model).executeOperation(); + new CodeCreateReportOperation(session, options, comps, model).executeOperation(); + dispose(); + }catch(Exception e1) { +// reporter.requestCanceling(); + e1.printStackTrace(); + MessageBox.post(CodeCreateReportDialog.this, ""+e1.getMessage(), "ERROR", MessageBox.ERROR); + } + } + }); + cancelBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + dispose(); + } + }); + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/workflow/CodeCreateReportHandler.java b/src/com/connor/lidy/workflow/CodeCreateReportHandler.java new file mode 100644 index 0000000..cf92f44 --- /dev/null +++ b/src/com/connor/lidy/workflow/CodeCreateReportHandler.java @@ -0,0 +1,50 @@ +package com.connor.lidy.workflow; + +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.AbstractAIFUIApplication; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +//ļнṹ +public class CodeCreateReportHandler extends AbstractHandler implements IHandler{ + + public Object execute(ExecutionEvent arg0) throws ExecutionException { + System.out.println("CodeCreateReportHandler"); + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + try { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + TCSession session = (TCSession) app.getSession(); + String options[] = session.getPreferenceService().getStringValues("Meling_SqlServer"); + if(options==null || options.length<4) { + MessageBox.post(desktop, "ѡMeling_SqlServeròȷ", "ERROR", MessageBox.ERROR); + return null; + } + String option = session.getPreferenceService().getStringValue("ML8_CodeCreateReport"); + if(option==null || option.isEmpty()) { + MessageBox.post(desktop, "ѡML8_CodeCreateReportòȷ", "ERROR", MessageBox.ERROR); + return null; + } + TCComponent model = session.stringToComponent(option);//w1NAAI2S5kSPsC + if(model==null || !model.isTypeOf("MSExcelX")) { + MessageBox.post(desktop, "ѡML8_CodeCreateReportģUIDòȷ", "ERROR", MessageBox.ERROR); + return null; + } +// CodeCreateReportOperation operation = new CodeCreateReportOperation(session, options, (TCComponentDataset)model); +// session.queueOperation(operation); + new CodeCreateReportDialog(session, options, (TCComponentDataset)model); +// MessageBox.post(desktop, "ݽ", "ʾ", MessageBox.INFORMATION); + }catch(Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + } + return null; + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/workflow/CodeCreateReportOperation.java b/src/com/connor/lidy/workflow/CodeCreateReportOperation.java new file mode 100644 index 0000000..58586bc --- /dev/null +++ b/src/com/connor/lidy/workflow/CodeCreateReportOperation.java @@ -0,0 +1,169 @@ +package com.connor.lidy.workflow; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.sql.Connection; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +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.lidy.util.SqlUtil; +import com.connor.lidy.util.TCUtil; +import com.teamcenter.rac.aif.AIFDesktop; +import com.teamcenter.rac.aif.AbstractAIFOperation; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentTcFile; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.stylesheet.PropertyDateComponent; +import com.teamcenter.rac.util.MessageBox; + +public class CodeCreateReportOperation extends AbstractAIFOperation { + +// private TCSession session; + private TCComponentDataset model; + private String options[]; + private PropertyDateComponent[] comps; + + public CodeCreateReportOperation(TCSession session, String options[], PropertyDateComponent[] comps, TCComponentDataset model) { +// this.session = session; + this.options = options; + this.comps = comps; + this.model = model; + } + + @Override + @SuppressWarnings("deprecation") + public void executeOperation() throws Exception { + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + FileInputStream input = null; + FileOutputStream output = null; + try { + Connection conn = SqlUtil.getSqlserverConnection(options[0], options[1], options[2], options[3]); +// Statement state = conn.createStatement(); + String d1 = "", d2 = ""; + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Date date1 = comps[0].getDate(); + if(date1!=null) { + d1 = " and a.pcreation_date>'"+sdf.format(date1)+" 00:00:00'"; + } + Date date2 = comps[1].getDate(); + if(date2!=null) { + d2 = " and a.pcreation_date<'"+sdf.format(date2)+" 23:59:59'"; + } + Date now = new Date(); +// int yesr = Integer.parseInt(new SimpleDateFormat("yyyy").format(now)); + int month = Integer.parseInt(new SimpleDateFormat("M").format(now)); + //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + if(month == 1) { +// yesr--; + month = 12; + }else { + month--; + } + StringBuilder sql = new StringBuilder("select count(a.puid) as count,a.year,a.month,a.projectname from VL25N_NOTANDOTH as a inner join" + + "(select c.puid from PITEM as b,PITEMREVISION as c where b.puid=c.ritems_tagu and b.pitem_id not like '%[-]%') d " + + "on d.puid=a.puid where 1=1"); + sql.append(d1).append(d2) + //.append(" and year=").append(yesr).append(" and month<=").append(month) + .append(" group by a.year,a.month,a.projectname"); + System.out.println("sql"+sql.toString()); + List> results = SqlUtil.getDBInfo(conn, sql.toString()); + + if(results.size()<1) { + MessageBox.post(desktop, "δҵ", "WARNING", MessageBox.WARNING); + return; + } + sdf = new SimpleDateFormat("yyyyMMdd"); + File directory = TCUtil.saveExcelChooser("봴"+sdf.format(now)); + if(directory==null) + return; + if(directory.exists()) + directory.delete(); + String path = directory.getPath(); + + TCComponentTcFile[] files = model.getTcFiles(); + File file = files[0].getFile(System.getProperty("java.io.tmpdir")); + input = new FileInputStream(file); + int i = 2; + +// Workbook wb = new Workbook(input); +// Worksheet sheet = wb.getWorksheets().get(0); + + XSSFWorkbook wb = new XSSFWorkbook(input); + XSSFSheet sheet = wb.getSheetAt(0); + XSSFRow row = getRow(sheet, 0); + XSSFCell cell = getCell(row, i); + +// int monCol = Integer.parseInt(month)+3; +// while(!cell.getStringCellValue().equals("")){ +// i++; +// cell = getCell(row, i); +// } +// if(i > monCol) { +//// int col = row. +// }else if(i < monCol) { +// +// } + i = 1; + HashMap rowMap = new HashMap<>(); + for(int j=1; j c : results) { +// for(String s : c.keySet()) +// System.out.println("result"+s+"=="+c.get(s)); + int n = Integer.parseInt(c.get("month").toString()); + n++; +// System.out.println("projectname:"+c.get("projectname").toString()); + if(!rowMap.containsKey(c.get("projectname").toString())) + continue; + row = getRow(sheet, rowMap.get(c.get("projectname"))); + cell = getCell(row, n); + cell.setCellValue((int)c.get("count")); +// System.out.println("cell:"+row.getRowNum()+","+cell.getColumnIndex()+"=="+c.get("count")); + } + output = new FileOutputStream(file.getPath()); + wb.write(output); + input.close(); + output.close(); +// System.out.println("file:"+file.getPath()); + String newPath = System.getProperty("java.io.tmpdir")+path.substring(path.lastIndexOf("\\")); + File reFile = new File(newPath); + file.renameTo(reFile); +// System.out.println("new directory:"+reFile.getPath()); + reFile.renameTo(directory); + + MessageBox.post(desktop, "", "INFO", MessageBox.INFORMATION); + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + }finally { + if(input!=null) + input.close(); + if(output!=null) + output.close(); + } + } + private static XSSFRow getRow(XSSFSheet sheet, int num) throws Exception { + XSSFRow row = sheet.getRow(num); + if(row==null) + row = sheet.createRow(num); + return row; + } + private static XSSFCell getCell(XSSFRow row, int col) throws Exception { + XSSFCell cell = row.getCell(col); + if(cell==null) + cell = row.createCell(col); + return cell; + } +} diff --git a/src/com/connor/lidy/workflow/EffectiveDataReportDialog.java b/src/com/connor/lidy/workflow/EffectiveDataReportDialog.java new file mode 100644 index 0000000..145c214 --- /dev/null +++ b/src/com/connor/lidy/workflow/EffectiveDataReportDialog.java @@ -0,0 +1,100 @@ +package com.connor.lidy.workflow; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.text.SimpleDateFormat; +import java.util.Date; + +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JPanel; +import com.teamcenter.rac.aif.AbstractAIFDialog; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; +import com.teamcenter.rac.util.PropertyLayout; + +public class EffectiveDataReportDialog extends AbstractAIFDialog { + private static final long serialVersionUID = 1L; + private TCSession session; + private TCComponentDataset model; + private JButton exportBtn; + private JButton cancelBtn; + private JComboBox comps; + + public EffectiveDataReportDialog(TCSession session, String[] options, TCComponentDataset model) throws Exception { + super(AIFUtility.getActiveDesktop()); + this.session = session; + this.model = model; + + setTitle("Чݱ"); + JPanel propPanel = new JPanel(new PropertyLayout(70, 5, 10, 5, 5, 5)); + + Date now = new Date(); + int year = Integer.parseInt(new SimpleDateFormat("yyyy").format(now)); + + JLabel label1 = new JLabel(""); + propPanel.add("1.1.left.center", label1); + comps = new JComboBox<>(); + for(int y=2020; y<=year; y++) + comps.addItem(""+y); + comps.setSelectedItem(""+year); + comps.setPreferredSize(new Dimension(155, 23)); + propPanel.add("1.2.right.center", comps); + + exportBtn = new JButton(""); + cancelBtn = new JButton("ȡ"); + JPanel btnPanel = new JPanel(new FlowLayout()); + btnPanel.add(exportBtn); + btnPanel.add(cancelBtn); + setLayout(new BorderLayout()); + add(BorderLayout.CENTER, propPanel); + add(BorderLayout.SOUTH, btnPanel); +// add(new JLabel("")); + addActionListener(options); + + pack(); + setSize(new Dimension(350, 200)); + 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) { + exportBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { +// ProgressReporterDialog reporter = new ProgressReporterDialog("ʾ"); +// reporter.reportProgressMessage("ڵԺ..."); +// new Thread(reporter).start(); +// new Thread() { +// public void run(){ +// } +// }.start(); + try { +// SimpleDateFormat sdf = new SimpleDateFormat("d-MMM-yyyy hh:mm"); + + new EffectiveDataReportOperation(session, options, comps.getSelectedItem().toString(), model).executeOperation(); + dispose(); + }catch(Exception e1) { +// reporter.requestCanceling(); + e1.printStackTrace(); + MessageBox.post(EffectiveDataReportDialog.this, ""+e1.getMessage(), "ERROR", MessageBox.ERROR); + } + } + }); + cancelBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + dispose(); + } + }); + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/workflow/EffectiveDataReportHandler.java b/src/com/connor/lidy/workflow/EffectiveDataReportHandler.java new file mode 100644 index 0000000..5b8d415 --- /dev/null +++ b/src/com/connor/lidy/workflow/EffectiveDataReportHandler.java @@ -0,0 +1,47 @@ +package com.connor.lidy.workflow; + +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.AbstractAIFUIApplication; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +//ļнṹ +public class EffectiveDataReportHandler extends AbstractHandler implements IHandler{ + + public Object execute(ExecutionEvent arg0) throws ExecutionException { + System.out.println("EffectiveDataReportHandler"); + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + try { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + TCSession session = (TCSession) app.getSession(); + String options[] = session.getPreferenceService().getStringValues("Meling_SqlServer"); + if(options==null || options.length<4) { + MessageBox.post(desktop, "ѡMeling_SqlServeròȷ", "ERROR", MessageBox.ERROR); + return null; + } + String option = session.getPreferenceService().getStringValue("ML8_EffectiveDataReport"); + if(option==null || option.isEmpty()) { + MessageBox.post(desktop, "ѡML8_EffectiveDataReportòȷ", "ERROR", MessageBox.ERROR); + return null; + } + TCComponent model = session.stringToComponent(option);//wxKAAIWH5kSPsC + if(model==null || !model.isTypeOf("MSExcelX")) { + MessageBox.post(desktop, "ѡML8_EffectiveDataReportģUIDòȷ", "ERROR", MessageBox.ERROR); + return null; + } + new EffectiveDataReportDialog(session, options, (TCComponentDataset)model); + }catch(Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + } + return null; + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/workflow/EffectiveDataReportOperation.java b/src/com/connor/lidy/workflow/EffectiveDataReportOperation.java new file mode 100644 index 0000000..97fa5d0 --- /dev/null +++ b/src/com/connor/lidy/workflow/EffectiveDataReportOperation.java @@ -0,0 +1,150 @@ +package com.connor.lidy.workflow; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.sql.Connection; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +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.lidy.util.SqlUtil; +import com.connor.lidy.util.TCUtil; +import com.teamcenter.rac.aif.AIFDesktop; +import com.teamcenter.rac.aif.AbstractAIFOperation; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentTcFile; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +public class EffectiveDataReportOperation extends AbstractAIFOperation { + +// private TCSession session; + private TCComponentDataset model; + private String options[]; + private String select; + + public EffectiveDataReportOperation(TCSession session, String options[], String select, TCComponentDataset model) { +// this.session = session; + this.options = options; + this.model = model; + this.select = select; + } + + @Override + public void executeOperation() throws Exception { + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + FileInputStream input = null; + FileOutputStream output = null; + try { + Connection conn = SqlUtil.getSqlserverConnection(options[0], options[1], options[2], options[3]); +// Statement state = conn.createStatement(); + Date now = new Date(); + String year = new SimpleDateFormat("yyyy").format(now); + int month = 12; + //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + if(year.equals(select)) { + month = Integer.parseInt(new SimpleDateFormat("M").format(now))-1; + } +// StringBuilder sql = new StringBuilder("select count(distinct itemuid) as count,type,year,month from VL25N_CODECREATE a,VL25N_EFFECTIVESTATUS a0,") +// .append("PWORKSPACEOBJECT a1 where a0.puid=a.itemuid and a.puid=a1.puid and a1.pactive_seq=1 ") +// .append("and (not exists (select b.ritems_tagu from (select n.* from PITEM as m,PITEMREVISION as n where m.puid=n.ritems_tagu and m.pitem_id not like '%[-]%') b where a.itemuid=b.ritems_tagu and b.pitem_revision_id='A') ") +// .append("or exists (select b.ritems_tagu from (select n.* from PITEM as m,PITEMREVISION as n where m.puid=n.ritems_tagu and m.pitem_id not like '%[-]%') b,VL25N_RELEASEDSTATUS c where a.itemuid=b.ritems_tagu and b.puid=c.puid ") +// .append("and c.pseq in(select max(d.pseq) from PRELEASE_STATUS_LIST d where d.puid=c.puid) and c.pname!='ML8_SXFB' and b.pitem_revision_id='A')) ") +// .append("and (year<").append(select).append(" or year=").append(select).append(" and month<=").append(month) +// .append(") and (a0.status is null or a0.status!='') ") +// .append("group by type,year,month order by year,month,type"); + StringBuilder sql = new StringBuilder("select YEAR,MONTH,PRODUCT,PART from ML_ValidData where YEAR<=").append(select).append(" order by YEAR,MONTH"); + System.out.println("sql"+sql.toString()); + List> results = SqlUtil.getDBInfo(conn, sql.toString()); + + if(results.size()<1) { + MessageBox.post(desktop, "δҵ", "WARNING", MessageBox.WARNING); + return; + } + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); + File directory = TCUtil.saveExcelChooser("Чݱ"+sdf.format(now)); + if(directory==null) + return; + if(directory.exists()) + directory.delete(); + String path = directory.getPath(); + + 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; + + int product = 0, part = 0, theyear = Integer.parseInt(select); + for(HashMap c : results) { + //String type = c.get("type").toString(); + int y = (int)c.get("YEAR"); +// int product = (int)c.get("count"); +// int part = (int)c.get("count"); + if(y> results = SqlUtil.getDBInfo(conn, sql.toString()); + + TCComponentTcFile[] files = model.getTcFiles(); + File file = files[0].getFile(System.getProperty("java.io.tmpdir")); + input = new FileInputStream(file); + XSSFWorkbook wb = new XSSFWorkbook(input); + + int i = 1; + XSSFSheet sheet = wb.getSheetAt(0); + XSSFRow row; + XSSFCell cell; + sourceRow = getRow(sheet, i); + for(HashMap c : results) { + row = getRow(sheet, i); + cell = getCell(row, 0); + cell.setCellValue(c.get("pitem_id").toString());//ϴ + cell = getCell(row, 1); + cell.setCellValue(c.get("auser_name").toString());//A洴 + cell = getCell(row, 2); + cell.setCellValue((Date)c.get("acreation_date"));//A洴ʱ + cell = getCell(row, 3); + cell.setCellValue(c.get("pitem_revision_id").toString());//°汾 + cell = getCell(row, 4); + cell.setCellValue(c.get("status").toString());// + cell = getCell(row, 5); + cell.setCellValue((Date)c.get("pcreation_date"));//ʱ + cell = getCell(row, 6); + cell.setCellValue(c.get("pobject_name").toString());// + cell = getCell(row, 7); + cell.setCellValue(c.get("pml8_Status").toString());//״̬ + cell = getCell(row, 8); + cell.setCellValue(c.get("pml8_Specifications").toString());//ͺ + cell = getCell(row, 9); + cell.setCellValue(c.get("pobject_desc").toString());// + cell = getCell(row, 10); + cell.setCellValue(c.get("pml8_ProjectName").toString());//Ŀ + cell = getCell(row, 11); + cell.setCellValue(c.get("pml8_Proposer").toString());// + cell = getCell(row, 12); + cell.setCellValue(c.get("pgroup").toString());// + cell = getCell(row, 13); + cell.setCellValue(c.get("pml8_Remark").toString());//ע2 + + i++; + } + + output = new FileOutputStream(file.getPath()); + wb.write(output); + input.close(); + output.close(); +// System.out.println("file:"+file.getPath()); + String newPath = System.getProperty("java.io.tmpdir")+path.substring(path.lastIndexOf("\\")); + File reFile = new File(newPath); + file.renameTo(reFile); +// System.out.println("new directory:"+reFile.getPath()); + reFile.renameTo(directory); + + MessageBox.post(desktop, "", "INFO", MessageBox.INFORMATION); + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + }finally { + if(input!=null) + input.close(); + if(output!=null) + output.close(); + } + } + 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; + } +} diff --git a/src/com/connor/lidy/workflow/MaterialsListReportHandler.java b/src/com/connor/lidy/workflow/MaterialsListReportHandler.java new file mode 100644 index 0000000..aace4df --- /dev/null +++ b/src/com/connor/lidy/workflow/MaterialsListReportHandler.java @@ -0,0 +1,49 @@ +package com.connor.lidy.workflow; + +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.AbstractAIFUIApplication; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +//ļнṹ +public class MaterialsListReportHandler extends AbstractHandler implements IHandler{ + + public Object execute(ExecutionEvent arg0) throws ExecutionException { + System.out.println("MaterialsListReportHandler"); + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + try { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + TCSession session = (TCSession) app.getSession(); + String options[] = session.getPreferenceService().getStringValues("Meling_SqlServer"); + if(options==null || options.length<4) { + MessageBox.post(desktop, "ѡMeling_SqlServeròȷ", "ERROR", MessageBox.ERROR); + return null; + } + String option = session.getPreferenceService().getStringValue("ML8_MaterialsListReport"); + if(option==null || option.isEmpty()) { + MessageBox.post(desktop, "ѡML8_MaterialsListReportòȷ", "ERROR", MessageBox.ERROR); + return null; + } + TCComponent model = session.stringToComponent(option);//wxHAAIGr5kSPsC + if(model==null || !model.isTypeOf("MSExcelX")) { + MessageBox.post(desktop, "ѡML8_MaterialsListReportģUIDòȷ", "ERROR", MessageBox.ERROR); + return null; + } + MaterialsListReportOperation operation = new MaterialsListReportOperation(session, options, (TCComponentDataset)model); + session.queueOperation(operation); +// MessageBox.post(desktop, "ݽ", "ʾ", MessageBox.INFORMATION); + }catch(Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + } + return null; + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/workflow/MaterialsListReportOperation.java b/src/com/connor/lidy/workflow/MaterialsListReportOperation.java new file mode 100644 index 0000000..5f21ac2 --- /dev/null +++ b/src/com/connor/lidy/workflow/MaterialsListReportOperation.java @@ -0,0 +1,557 @@ +package com.connor.lidy.workflow; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +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 javax.swing.JOptionPane; + +import org.apache.poi.xssf.usermodel.XSSFCell; +import org.apache.poi.xssf.usermodel.XSSFCellStyle; +import org.apache.poi.xssf.usermodel.XSSFCreationHelper; +import org.apache.poi.xssf.usermodel.XSSFRow; +import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + +import com.connor.lidy.util.SqlUtil; +import com.connor.lidy.util.TCUtil; +import com.teamcenter.rac.aif.AIFDesktop; +import com.teamcenter.rac.aif.AbstractAIFOperation; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentGroup; +import com.teamcenter.rac.kernel.TCComponentTcFile; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +public class MaterialsListReportOperation extends AbstractAIFOperation { + + private TCSession session; + private TCComponentDataset model; + private String options[]; + private XSSFRow sourceRow; +// private SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-M-dd hh:mm:ss"); + + public MaterialsListReportOperation(TCSession session, String options[], TCComponentDataset model) { + this.session = session; + this.options = options; + this.model = model; + } + + @Override + public void executeOperation() throws Exception { + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + FileInputStream input = null; + FileOutputStream output = null; + try { + HashMap groupMap = new HashMap<>(); + HashMap colMap = new HashMap<>(); + colMap.put("pitem_id", 0); + colMap.put("pitem_revision_id", 1); + colMap.put("auser", 2); + colMap.put("adate", 3); + colMap.put("pobject_name", 4); + colMap.put("pobject_desc", 5); + colMap.put("puser_name", 6); + colMap.put("groupid", 7); + colMap.put("pcreation_date", 8); + colMap.put("count", 9); + colMap.put("status", 10); + colMap.put("pstate_value", 11); + colMap.put("uom_tag", 12); + colMap.put("pml8_PlatformSeries", 13); + colMap.put("pml8_ProjectName", 14); + colMap.put("pml8_ProductCode", 15); + colMap.put("pml8_ProductType", 16); + colMap.put("pml8_Wide", 17); + colMap.put("pml8_Deep", 18); + colMap.put("pml8_High", 19); + colMap.put("pml8_Colour", 20); + colMap.put("pml8_Voltage", 21); + colMap.put("pml8_Frequency", 22); + colMap.put("pml8_Place", 23); + colMap.put("pml8_ProcessingMode", 24); + colMap.put("pml8_SalesMode", 25); + colMap.put("pml8_DomesticSales", 26); + colMap.put("pml8_ExportLand", 27); + colMap.put("pml8_ExportCode", 28); + colMap.put("pml8_ProductTeam", 29); + colMap.put("pml8_GroupCode", 30); + colMap.put("pml8_StdDesc", 31); + colMap.put("pml8_Proposer", 32); + colMap.put("pml8_Remark", 33); + colMap.put("pml8_Remark2", 34); + colMap.put("pml8_ProductVolume", 35); + colMap.put("pml8_ControlType", 36); + colMap.put("pml8_PortalBody", 37); + colMap.put("object_type", 38); + + + Connection conn = SqlUtil.getSqlserverConnection(options[0], options[1], options[2], options[3]); + if (conn == null) { + throw new Exception("޷ȡݿϢ"); + } +// Statement state = conn.createStatement(); + Date now = new Date(); +// int yesr = Integer.parseInt(new SimpleDateFormat("yyyy").format(now)); +// int month = Integer.parseInt(new SimpleDateFormat("M").format(now)); +// //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); +// if(month == 1) { +// yesr--; +// month = 12; +// }else { +// month--; +// } +// StringBuilder sql = new StringBuilder("select distinct a.pitem_id,b.pitem_revision_id,a2.puser_name as auser,") +// .append("CONVERT(VARCHAR(100), a2.pcreation_date) as adate,"); + StringBuilder sql = new StringBuilder("select distinct a.pitem_id,b.pitem_revision_id,ac.pml8_Proposer as auser,a2.pcreation_date as adate,"); + sql.append("b1.pobject_name,b1.pobject_desc,b1.puser_name,b1.groupid,b1.pcreation_date,")//a2.puser_name +// .append("case when e.count is null then 0 else e.count end as count,f.pname as status,g.pstate_value,") + .append("c.pml8_Child as count,f.pname as status,g.pstate_value,") + .append("case a.ruom_tagu when 'AAAAAAAAAAAAAA' then '' else ") + .append("(select psymbol from PUNITOFMEASURE where puid=a.ruom_tagu) end as uom_tag,c.pml8_PlatformSeries,") + .append("case when k.pml8_ProjectName is null then c.pml8_ProjectName else k.pml8_ProjectName end as pml8_ProjectName,") + .append("case when k.pml8_ProductCode is null then c.pml8_ProductCode else k.pml8_ProductCode end as pml8_ProductCode,") + .append("case when k.pml8_ProductType is null then c.pml8_ProductType else k.pml8_ProductType end as pml8_ProductType,") + .append("c.pml8_Wide,c.pml8_Deep,c.pml8_High,c.pml8_Colour,c.pml8_Voltage,c.pml8_Frequency,c.pml8_Place,c.pml8_ProcessingMode,") + .append("c.pml8_SalesMode,c.pml8_DomesticSales,c.pml8_ExportLand,c.pml8_ExportCode,c.pml8_ProductTeam,c.pml8_GroupCode,") + .append("c.pml8_StdDesc,c.pml8_Proposer,c.pml8_Remark,c.pml8_Remark2,c1.pml8_ProductVolume,c1.pml8_ControlType,") + .append("c1.pml8_PortalBody,c1.object_type ") + .append("from PITEM a,PITEMREVISION a1,PML8_PRODUCTREVISION ac,VL25N_POMPROPERTIES a2,VL25N_POMPROPERTIES b1,PML8_PRODUCTREVISION c,VL25N_PRODUCTSLIT c1,") + .append("PITEMREVISION b left join VL25N_BOMCOUNT e on e.puid=b.puid left join VL25N_RELEASEDSTATUS f on f.puid=b.puid ") + .append("left join VL25N_WORKFLOWTARGET g on g.puid=b.puid and g.creation_date in (select max(creation_date) from VL25N_WORKFLOWTARGET ") + .append("g1 where g1.puid=b.puid group by g1.puid) left join VL25N_PROJECTFORM k on b.puid=k.puid ") + .append("where a1.puid=ac.puid and a1.puid=a2.puid and a2.pcreation_date in ") + .append("(select dateadd(hour,8,min(t2.pcreation_date)) from PITEMREVISION t1,PPOM_APPLICATION_OBJECT t2 ") + .append("where t1.puid=t2.puid and t1.ritems_tagu=a1.ritems_tagu) and a2.pactive_seq=1 and a.puid=a1.ritems_tagu and a.puid=b.ritems_tagu ") + .append("and b.puid=b1.puid and b1.pactive_seq=1 and b1.pcreation_date in (select dateadd(hour,8,max(t2.pcreation_date)) ") + .append("from PITEMREVISION t1,PPOM_APPLICATION_OBJECT t2 where t1.puid=t2.puid and t1.ritems_tagu=b.ritems_tagu) ") + .append("and b.puid=c.puid and c.puid=c1.puid"); + +// if(results.size()<1) { +// MessageBox.post(desktop, "δҵ", "WARNING", MessageBox.WARNING); +// return; +// } + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); + File directory = TCUtil.saveExcelChooser("ϸ"+sdf.format(now)); + if(directory==null) + return; + if(directory.exists()) + directory.delete(); + String path = directory.getPath(); + + TCComponentTcFile[] files = model.getTcFiles(); + File file = files[0].getFile(System.getProperty("java.io.tmpdir")); + input = new FileInputStream(file); + XSSFWorkbook wb = new XSSFWorkbook(input); + + int i = 1; + XSSFSheet sheet = wb.getSheetAt(0); + XSSFRow row2 = getRow(sheet, 1); + XSSFCell cell2 = getCell(row2, 2); + XSSFCellStyle createCellStyle = cell2.getCellStyle(); + if(createCellStyle ==null)createCellStyle = wb.createCellStyle(); + XSSFCreationHelper creationHelper = wb.getCreationHelper(); + createCellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-M-dd")); + SimpleDateFormat format2 = new SimpleDateFormat("yyyy-M-dd"); + sourceRow = getRow(sheet, i); + ArrayList IDlist=new ArrayList(); + + System.out.println("sql"+sql.toString()); + List results = SqlUtil.getArrayDBInfo(conn, sql.toString()); + for(Object[] c : results) { + String ID=String.valueOf(c[colMap.get("pitem_id")]); + if(ID.indexOf("-")>-1||IDlist.contains(ID)) { + continue; + } + IDlist.add(ID); + XSSFRow row = getRow(sheet, i); + XSSFCell cell = getCell(row, 0); + cell.setCellValue(c[colMap.get("pitem_id")].toString());//ϴ + cell = getCell(row, 1); + cell.setCellValue(c[colMap.get("auser")].toString());//A洴 + cell = getCell(row, 2); + cell.setCellValue(format2.parse(format2.format((Date)c[colMap.get("adate")])));//A洴ʱ + cell.setCellStyle(createCellStyle); +// cell.setCellValue(formatDate.parse(c[colMap.get("adate")].toString()));//A洴ʱ + cell = getCell(row, 3); +// cell.setCellValue(((int)c[colMap.get("count")])==0 ? "":"");//BOM + cell.setCellValue(c[colMap.get("count")].toString());//BOM + cell = getCell(row, 4); + cell.setCellValue(c[colMap.get("pitem_revision_id")].toString());//°汾 + cell = getCell(row, 5); + if((c[colMap.get("pstate_value")] instanceof Integer) && (int)c[colMap.get("pstate_value")]==4) + cell.setCellValue("");//״̬ + cell = getCell(row, 6); + cell.setCellValue(c[colMap.get("status")].toString());//״̬ + cell = getCell(row, 7); + cell.setCellValue(format2.parse(format2.format((Date)c[colMap.get("pcreation_date")])));//°洴 + cell.setCellStyle(createCellStyle); + cell = getCell(row, 8); + cell.setCellValue(c[colMap.get("pml8_ProjectName")].toString());//Ŀ + cell = getCell(row, 9); + cell.setCellValue(c[colMap.get("pml8_PlatformSeries")].toString());//ƽ̨ϵ + cell = getCell(row, 10); + cell.setCellValue(c[colMap.get("pobject_name")].toString());//Ʒ + cell = getCell(row, 11); + cell.setCellValue(c[colMap.get("pml8_ProductCode")].toString());//Ʒ + cell = getCell(row, 12); + cell.setCellValue(c[colMap.get("pml8_ProductType")].toString());//Ʒͺ + cell = getCell(row, 13); + cell.setCellValue(c[colMap.get("object_type")].toString());//Ʒ + cell = getCell(row, 14); + cell.setCellValue(c[colMap.get("pml8_PortalBody")].toString());// + cell = getCell(row, 15); + cell.setCellValue(c[colMap.get("pml8_ProductVolume")].toString());//Ʒݻ + cell = getCell(row, 16); + cell.setCellValue(c[colMap.get("pml8_Wide")].toString());//װߴ()mm + cell = getCell(row, 17); + cell.setCellValue(c[colMap.get("pml8_Deep")].toString());//װߴ()mm + cell = getCell(row, 18); + cell.setCellValue(c[colMap.get("pml8_High")].toString());//װߴ()mm + cell = getCell(row, 19); + cell.setCellValue(c[colMap.get("pml8_ControlType")].toString());//¿ + cell = getCell(row, 20); + cell.setCellValue(c[colMap.get("pml8_Colour")].toString());//ɫ + cell = getCell(row, 21); + cell.setCellValue(c[colMap.get("pml8_Voltage")].toString());//ѹ + cell = getCell(row, 22); + cell.setCellValue(c[colMap.get("pml8_Frequency")].toString());//Ƶ + cell = getCell(row, 23); + cell.setCellValue(c[colMap.get("pml8_Place")].toString());// + cell = getCell(row, 24); + cell.setCellValue(c[colMap.get("pml8_ProcessingMode")].toString());//ӹʽ + cell = getCell(row, 25); + cell.setCellValue(c[colMap.get("pml8_SalesMode")].toString());//۷ʽ + cell = getCell(row, 26); + cell.setCellValue(c[colMap.get("pml8_DomesticSales")].toString());//ͻ + cell = getCell(row, 27); + cell.setCellValue(c[colMap.get("pml8_ExportLand")].toString());// + cell = getCell(row, 28); + cell.setCellValue(c[colMap.get("pml8_ExportCode")].toString());//̱ + cell = getCell(row, 29); + cell.setCellValue(c[colMap.get("pml8_ProductTeam")].toString());//Ʒ + cell = getCell(row, 30); + cell.setCellValue(c[colMap.get("pml8_GroupCode")].toString());// + cell = getCell(row, 31); + cell.setCellValue(c[colMap.get("pobject_desc")].toString());// + cell = getCell(row, 32); + cell.setCellValue(c[colMap.get("pml8_StdDesc")].toString());//׼ + cell = getCell(row, 33); + cell.setCellValue(c[colMap.get("status")].toString());//׶ + cell = getCell(row, 34); + cell.setCellValue(c[colMap.get("puser_name")].toString());// + cell = getCell(row, 35); + String groupid = c[colMap.get("groupid")].toString(); + if(groupMap.containsKey(groupid)) { + cell.setCellValue(groupMap.get(groupid));//߲ + }else { + TCComponentGroup g = (TCComponentGroup) session.stringToComponent(groupid); + String group = g.getGroupName(); + cell.setCellValue(group);//߲ + groupMap.put(groupid, group); + } +// cell.setCellValue(c[colMap.get("pname")].toString());//߲ + cell = getCell(row, 36); + cell.setCellValue(c[colMap.get("pml8_Proposer")].toString());//η + cell = getCell(row, 37); + cell.setCellValue(c[colMap.get("pml8_Remark")].toString());//ע + cell = getCell(row, 38); + cell.setCellValue(c[colMap.get("pml8_Remark2")].toString());//ע2 + cell = getCell(row, 39); + cell.setCellValue(c[colMap.get("uom_tag")].toString());//PDMĬϵλ + + i++; + } + IDlist.clear(); + + colMap.put("pml8_Status", 9); + colMap.put("status", 10); + colMap.put("pstate_value", 11); + colMap.put("uom_tag", 12); + colMap.put("pml8_FigureNum", 13); + colMap.put("pml8_ProjectName", 14); + colMap.put("pml8_Materials", 15); + colMap.put("pml8_Specifications", 16); + colMap.put("pml8_Colour", 17); + colMap.put("pml8_Child", 18); + colMap.put("pml8_ProcessingMode", 19); + colMap.put("pml8_ExternalWorking", 20); + colMap.put("pml8_ProductTeam", 21); + colMap.put("pml8_StdDesc", 22); + colMap.put("pml8_Proposer", 23); + colMap.put("pml8_Suttle", 24); + colMap.put("pml8_Remark", 25); + colMap.put("pml8_Remark2", 26); + colMap.put("pml8_GeneralIdentify", 27); + +// sql = new StringBuilder("select distinct a.pitem_id,b.pitem_revision_id,a2.puser_name as auser,CONVERT(VARCHAR(100), a2.pcreation_date) as adate,b1.pobject_name,"); + sql = new StringBuilder("select distinct a.pitem_id,b.pitem_revision_id,ac.pml8_Proposer as auser,a2.pcreation_date as adate,b1.pobject_name,"); + sql.append("b1.pobject_desc,b1.puser_name,b1.groupid,b1.pcreation_date,a0.pml8_Status,f.pname as status,g.pstate_value,case a.ruom_tagu ") + .append("when 'AAAAAAAAAAAAAA' then '' else (select psymbol from PUNITOFMEASURE where puid=a.ruom_tagu) end as uom_tag,") + .append("c.pml8_FigureNum,case when k.pml8_ProjectName is null then c.pml8_ProjectName else k.pml8_ProjectName end as pml8_ProjectName,") + .append("c.pml8_Materials,c.pml8_Specifications,c.pml8_Colour,c.pml8_Child,c.pml8_ProcessingMode,") + .append("c.pml8_ExternalWorking,c.pml8_ProductTeam,c.pml8_StdDesc,c.pml8_Proposer,c.pml8_Suttle,c.pml8_Remark,c.pml8_Remark2,a0.pml8_GeneralIdentify ") + .append("from PITEM a,PML8_PART a0,PITEMREVISION a1,PML8_PARTREVISION ac,VL25N_POMPROPERTIES a2,VL25N_POMPROPERTIES b1,PML8_PARTREVISION c,") + .append("PITEMREVISION b left join VL25N_RELEASEDSTATUS f on f.puid=b.puid ") + .append("left join VL25N_WORKFLOWTARGET g on g.puid=b.puid and g.creation_date in (select max(creation_date) from VL25N_WORKFLOWTARGET g1 ") + .append("where g1.puid=b.puid group by g1.puid) left join VL25N_PROJECTFORM k on b.puid=k.puid where a1.puid=ac.puid and a1.puid=a2.puid ") + .append("and a2.pcreation_date in (select dateadd(hour,8,min(t2.pcreation_date)) from PITEMREVISION t1,PPOM_APPLICATION_OBJECT t2 ") + .append("where t1.puid=t2.puid and t1.ritems_tagu=a1.ritems_tagu) and a2.pactive_seq=1 ") + .append("and a.puid=a0.puid and a.puid=a1.ritems_tagu and a.puid=b.ritems_tagu and b.puid=b1.puid and b1.pactive_seq=1 ") + .append("and b1.pcreation_date in (select dateadd(hour,8,max(t2.pcreation_date)) from PITEMREVISION t1,PPOM_APPLICATION_OBJECT t2 ") + .append("where t1.puid=t2.puid and t1.ritems_tagu=b.ritems_tagu) and b.puid=c.puid");// and c.pml8_ProcessingMode='' + + System.out.println("sql"+sql.toString()); + List results2 = SqlUtil.getArrayDBInfo(conn, sql.toString()); + i = 1; + sheet = wb.getSheetAt(1); + sourceRow = getRow(sheet, i); + ArrayList IDlist2=new ArrayList(); + for(Object[] c : results2) { + String ID=String.valueOf(c[colMap.get("pitem_id")]); + if(ID.indexOf("-")>-1||IDlist2.contains(ID)) { + continue; + } + IDlist2.add(ID); + XSSFRow row = getRow(sheet, i); + XSSFCell cell = getCell(row, 0); + cell.setCellValue(c[colMap.get("pitem_id")].toString());//ϴ + cell = getCell(row, 1); + cell.setCellValue(c[colMap.get("auser")].toString());//A洴 + cell = getCell(row, 2); + cell.setCellValue(format2.parse(format2.format((Date)c[colMap.get("adate")])));//A洴ʱ + cell.setCellStyle(createCellStyle); +// cell.setCellValue(formatDate.parse(c[colMap.get("adate")].toString()));//A洴ʱ + cell = getCell(row, 3); + cell.setCellValue(c[colMap.get("pitem_revision_id")].toString());//°汾 + cell = getCell(row, 4); + if((c[colMap.get("pstate_value")] instanceof Integer) && (int)c[colMap.get("pstate_value")]==4) + cell.setCellValue("");//°湤״̬ + cell = getCell(row, 5); + cell.setCellValue(c[colMap.get("status")].toString());//״̬ + cell = getCell(row, 6); + cell.setCellValue(format2.parse(format2.format((Date)c[colMap.get("pcreation_date")])));//°洴 + cell.setCellStyle(createCellStyle); + cell = getCell(row, 7); + cell.setCellValue(c[colMap.get("pobject_name")].toString());// + cell = getCell(row, 8); + cell.setCellValue(c[colMap.get("pml8_FigureNum")].toString());//ͼ + cell = getCell(row, 9); + cell.setCellValue(c[colMap.get("pml8_ProjectName")].toString());//Ŀ + cell = getCell(row, 10); + cell.setCellValue(c[colMap.get("pml8_Materials")].toString());// + cell = getCell(row, 11); + cell.setCellValue(c[colMap.get("pml8_Specifications")].toString());//ͺ + cell = getCell(row, 12); + cell.setCellValue(c[colMap.get("pml8_Colour")].toString());//ɫ + cell = getCell(row, 13); + cell.setCellValue(c[colMap.get("pml8_Child")].toString());//Ӽ + cell = getCell(row, 14); + cell.setCellValue(c[colMap.get("pml8_ProcessingMode")].toString());//ӹʽ + cell = getCell(row, 15); + cell.setCellValue(c[colMap.get("pml8_ExternalWorking")].toString());//ӹ״̬ + cell = getCell(row, 16); + cell.setCellValue(c[colMap.get("pml8_GeneralIdentify")].toString());//ͨû״̬ + cell = getCell(row, 17); + cell.setCellValue(c[colMap.get("pml8_Status")].toString());//ѡʽ + cell = getCell(row, 18); + cell.setCellValue(c[colMap.get("pml8_ProductTeam")].toString());//Ʒ + cell = getCell(row, 19); + cell.setCellValue(c[colMap.get("pobject_desc")].toString());// + cell = getCell(row, 20); + cell.setCellValue(c[colMap.get("pml8_StdDesc")].toString());//׼ + cell = getCell(row, 21); + cell.setCellValue(c[colMap.get("puser_name")].toString());// + cell = getCell(row, 22); +// cell.setCellValue(c[colMap.get("pname")].toString());//߲ + String groupid = c[colMap.get("groupid")].toString(); + if(groupMap.containsKey(groupid)) { + cell.setCellValue(groupMap.get(groupid));//߲ + }else { + TCComponentGroup g = (TCComponentGroup) session.stringToComponent(groupid); + String group = g.getGroupName(); + cell.setCellValue(group);//߲ + groupMap.put(groupid, group); + } + cell = getCell(row, 23); + cell.setCellValue(c[colMap.get("pml8_Proposer")].toString());//η + cell = getCell(row, 24); + cell.setCellValue(c[colMap.get("pml8_Remark")].toString());//ע + cell = getCell(row, 25); + cell.setCellValue(c[colMap.get("pml8_Remark2")].toString());//ע2 + cell = getCell(row, 26); + cell.setCellValue(c[colMap.get("uom_tag")].toString());//PDMĬϵλ + cell = getCell(row, 27); + cell.setCellValue(c[colMap.get("pml8_Suttle")].toString());// + + i++; + } + IDlist2.clear(); + + colMap.put("pcreation_date", 8); + colMap.put("status", 9); + colMap.put("pstate_value", 10); + colMap.put("uom_tag", 11); + colMap.put("pml8_ProjectName", 12); + colMap.put("pml8_Materials", 13); + colMap.put("pml8_MaterialsType", 14); + colMap.put("pml8_Specifications", 15); + colMap.put("pml8_Colour", 16); + colMap.put("pml8_ProcessingMode", 17); + colMap.put("pml8_ProductTeamCode", 18); + colMap.put("pml8_Proposer", 19); + colMap.put("pml8_Remark", 20); + colMap.put("pml8_Remark2", 21); + colMap.put("pml8_Status", 22); + +// sql = new StringBuilder("select distinct a.pitem_id,b.pitem_revision_id,a2.puser_name as auser,CONVERT(VARCHAR(100), a2.pcreation_date) as adate,b1.pobject_name,"); + sql = new StringBuilder("select distinct a.pitem_id,b.pitem_revision_id,ac.pml8_Proposer as auser,a2.pcreation_date as adate,b1.pobject_name,"); + sql.append("b1.pobject_desc,b1.puser_name,b1.groupid,b1.pcreation_date,f.pname as status,g.pstate_value,case a.ruom_tagu ") + .append("when 'AAAAAAAAAAAAAA' then '' else (select psymbol from PUNITOFMEASURE where puid=a.ruom_tagu) end as uom_tag,") + .append("case when k.pml8_ProjectName is null then c.pml8_ProjectName else k.pml8_ProjectName end as pml8_ProjectName,") + .append("c.pml8_Materials,c.pml8_MaterialsType,c.pml8_Specifications,c.pml8_Colour,c.pml8_ProcessingMode,") + .append("case when c.pml8_ProductTeam is null then c.pml8_ProductTeamCode else c.pml8_ProductTeam end as pml8_ProductTeamCode,") + .append("c.pml8_Proposer,c.pml8_Remark,c.pml8_Remark2,a0.pml8_Status ") + .append("from PITEM a,PML8_RAWMATERIAL a0,PITEMREVISION a1,PML8_RAWMATERIALREVISION ac,VL25N_POMPROPERTIES a2,VL25N_POMPROPERTIES b1,PML8_RAWMATERIALREVISION c,PITEMREVISION b ") + .append("left join VL25N_RELEASEDSTATUS f on f.puid=b.puid left join VL25N_WORKFLOWTARGET g on g.puid=b.puid and g.creation_date in ") + .append("(select max(creation_date) from VL25N_WORKFLOWTARGET g1 where g1.puid=b.puid group by g1.puid) ") + .append("left join VL25N_PROJECTFORM k on b.puid=k.puid ") + .append("where a1.puid=ac.puid and a1.puid=a2.puid and a2.pcreation_date in (select dateadd(hour,8,min(t2.pcreation_date)) ") + .append("from PITEMREVISION t1,PPOM_APPLICATION_OBJECT t2 where t1.puid=t2.puid and t1.ritems_tagu=a1.ritems_tagu) and a2.pactive_seq=1 ") + .append("and a.puid=a0.puid and a.puid=a1.ritems_tagu and a.puid=b.ritems_tagu and b.puid=b1.puid and b1.pactive_seq=1 ") + .append("and b1.pcreation_date in (select dateadd(hour,8,max(t2.pcreation_date)) from PITEMREVISION t1,PPOM_APPLICATION_OBJECT t2 ") + .append("where t1.puid=t2.puid and t1.ritems_tagu=b.ritems_tagu) and b.puid=c.puid"); + + System.out.println("sql"+sql.toString()); + List results3 = SqlUtil.getArrayDBInfo(conn, sql.toString()); + i = 1; + sheet = wb.getSheetAt(2); + sourceRow = getRow(sheet, i); + ArrayList IDlist3=new ArrayList(); + for(Object[] c : results3) { + String ID=String.valueOf(c[colMap.get("pitem_id")]); + if(ID.indexOf("-")>-1||IDlist3.contains(ID)) { + continue; + } + IDlist3.add(ID); + XSSFRow row = getRow(sheet, i); + XSSFCell cell = getCell(row, 0); + cell.setCellValue(c[colMap.get("pitem_id")].toString());//ϴ + cell = getCell(row, 1); + cell.setCellValue(c[colMap.get("auser")].toString());//A洴 + cell = getCell(row, 2); + cell.setCellValue(format2.parse(format2.format((Date)c[colMap.get("adate")])));//A洴ʱ + cell.setCellStyle(createCellStyle); +// cell.setCellValue(formatDate.parse(c[colMap.get("adate")].toString()));//A洴ʱ + cell = getCell(row, 3); + cell.setCellValue(c[colMap.get("pitem_revision_id")].toString());//°汾 + cell = getCell(row, 4); + if((c[colMap.get("pstate_value")] instanceof Integer) && (int)c[colMap.get("pstate_value")]==4) + cell.setCellValue("");//°湤״̬ + cell = getCell(row, 5); + cell.setCellValue(c[colMap.get("status")].toString());//״̬ + cell = getCell(row, 6); + cell.setCellValue(format2.parse(format2.format((Date)c[colMap.get("pcreation_date")])));//°洴 + cell.setCellStyle(createCellStyle); + cell = getCell(row, 7); + cell.setCellValue(c[colMap.get("pobject_name")].toString());// + cell = getCell(row, 8); + cell.setCellValue(c[colMap.get("pml8_ProjectName")].toString());//Ŀ + cell = getCell(row, 9); + cell.setCellValue(c[colMap.get("pml8_Materials")].toString());// + cell = getCell(row, 10); + cell.setCellValue(c[colMap.get("pml8_MaterialsType")].toString());// + cell = getCell(row, 11); + cell.setCellValue(c[colMap.get("pml8_Specifications")].toString());//ͺ + cell = getCell(row, 12); + cell.setCellValue(c[colMap.get("pml8_Colour")].toString());//ɫ + cell = getCell(row, 13); + cell.setCellValue(c[colMap.get("pml8_ProcessingMode")].toString());//ӹʽ + cell = getCell(row, 14); +// cell.setCellValue(c[colMap.get("pml8_ExternalWorking")].toString());//ӹ״̬ + cell = getCell(row, 15); + cell.setCellValue(c[colMap.get("pml8_ProductTeamCode")].toString());//Ʒ + cell = getCell(row, 16); + cell.setCellValue(c[colMap.get("pobject_desc")].toString());// + cell = getCell(row, 17); + cell.setCellValue(c[colMap.get("puser_name")].toString());// + cell = getCell(row, 18); +// cell.setCellValue(c[colMap.get("pname")].toString());//߲ + String groupid = c[colMap.get("groupid")].toString(); + if(groupMap.containsKey(groupid)) { + cell.setCellValue(groupMap.get(groupid));//߲ + }else { + TCComponentGroup g = (TCComponentGroup) session.stringToComponent(groupid); + String group = g.getGroupName(); + cell.setCellValue(group);//߲ + groupMap.put(groupid, group); + } + cell = getCell(row, 19); + cell.setCellValue(c[colMap.get("pml8_Proposer")].toString());//η + cell = getCell(row, 20); + cell.setCellValue(c[colMap.get("pml8_Remark")].toString());//ע + cell = getCell(row, 21); + cell.setCellValue(c[colMap.get("pml8_Remark2")].toString());//ע2 + cell = getCell(row, 22); + cell.setCellValue(c[colMap.get("uom_tag")].toString());//PDMĬϵλ + cell = getCell(row, 23); + cell.setCellValue(c[colMap.get("pml8_Status")].toString());//״̬ + + i++; + } + IDlist3.clear(); + + output = new FileOutputStream(file.getPath()); + wb.write(output); + input.close(); + output.close(); +// System.out.println("file:"+file.getPath()); + String newPath = System.getProperty("java.io.tmpdir")+path.substring(path.lastIndexOf("\\")); + File reFile = new File(newPath); + file.renameTo(reFile); +// System.out.println("new directory:"+reFile.getPath()); + reFile.renameTo(directory); + +// MessageBox.post(desktop, "", "INFO", MessageBox.INFORMATION); +// new Thread() { +// public void run(){ +// } +// }.start(); + int choose = JOptionPane.showOptionDialog(AIFUtility.getActiveDesktop(), "ѵ"+directory.getPath()+"Ƿ?", "ʾ", + JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new String[] {"",""}, ""); + if(choose==0) { + Runtime runtime = Runtime.getRuntime(); + runtime.exec("cmd /c start exit &&\"" + directory + "\" "); + } + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + }finally { + if(input!=null) + input.close(); + if(output!=null) + output.close(); + } + } + 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; + } +} diff --git a/src/com/connor/lidy/workflow/NewAndChangedReportDialog.java b/src/com/connor/lidy/workflow/NewAndChangedReportDialog.java new file mode 100644 index 0000000..15a6380 --- /dev/null +++ b/src/com/connor/lidy/workflow/NewAndChangedReportDialog.java @@ -0,0 +1,100 @@ +package com.connor.lidy.workflow; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.text.SimpleDateFormat; +import java.util.Date; + +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JPanel; +import com.teamcenter.rac.aif.AbstractAIFDialog; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; +import com.teamcenter.rac.util.PropertyLayout; + +public class NewAndChangedReportDialog extends AbstractAIFDialog { + private static final long serialVersionUID = 1L; + private TCSession session; + private TCComponentDataset model; + private JButton exportBtn; + private JButton cancelBtn; + private JComboBox comps; + + public NewAndChangedReportDialog(TCSession session, String[] options, TCComponentDataset model) throws Exception { + super(AIFUtility.getActiveDesktop()); + this.session = session; + this.model = model; + + setTitle("½ͳ"); + JPanel propPanel = new JPanel(new PropertyLayout(70, 5, 10, 5, 5, 5)); + + Date now = new Date(); + int year = Integer.parseInt(new SimpleDateFormat("yyyy").format(now)); + + JLabel label1 = new JLabel(""); + propPanel.add("1.1.left.center", label1); + comps = new JComboBox<>(); + for(int y=2020; y<=year; y++) + comps.addItem(""+y); + comps.setSelectedItem(""+year); + comps.setPreferredSize(new Dimension(155, 23)); + propPanel.add("1.2.right.center", comps); + + exportBtn = new JButton(""); + cancelBtn = new JButton("ȡ"); + JPanel btnPanel = new JPanel(new FlowLayout()); + btnPanel.add(exportBtn); + btnPanel.add(cancelBtn); + setLayout(new BorderLayout()); + add(BorderLayout.CENTER, propPanel); + add(BorderLayout.SOUTH, btnPanel); +// add(new JLabel("")); + addActionListener(options); + + pack(); + setSize(new Dimension(350, 200)); + 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) { + exportBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { +// ProgressReporterDialog reporter = new ProgressReporterDialog("ʾ"); +// reporter.reportProgressMessage("ڵԺ..."); +// new Thread(reporter).start(); +// new Thread() { +// public void run(){ +// } +// }.start(); + try { +// SimpleDateFormat sdf = new SimpleDateFormat("d-MMM-yyyy hh:mm"); + + new NewAndChangedReportOperation(session, options, comps, model).executeOperation(); + dispose(); + }catch(Exception e1) { +// reporter.requestCanceling(); + e1.printStackTrace(); + MessageBox.post(NewAndChangedReportDialog.this, ""+e1.getMessage(), "ERROR", MessageBox.ERROR); + } + } + }); + cancelBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + dispose(); + } + }); + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/workflow/NewAndChangedReportHandler.java b/src/com/connor/lidy/workflow/NewAndChangedReportHandler.java new file mode 100644 index 0000000..9f3d587 --- /dev/null +++ b/src/com/connor/lidy/workflow/NewAndChangedReportHandler.java @@ -0,0 +1,51 @@ +package com.connor.lidy.workflow; + +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.AbstractAIFUIApplication; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +//ļнṹ +public class NewAndChangedReportHandler extends AbstractHandler implements IHandler{ + + public Object execute(ExecutionEvent arg0) throws ExecutionException { + System.out.println("NewAndChangedReportHandler"); + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + try { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + TCSession session = (TCSession) app.getSession(); + String options[] = session.getPreferenceService().getStringValues("Meling_SqlServer"); + if(options==null || options.length<4) { + MessageBox.post(desktop, "ѡMeling_SqlServeròȷ", "ERROR", MessageBox.ERROR); + return null; + } + String option = session.getPreferenceService().getStringValue("ML8_NewAndChangedReport"); +// if(option==null || option.length<1) { + if(option==null || option.isEmpty()) { + MessageBox.post(desktop, "ѡML8_NewAndChangedReportòȷ", "ERROR", MessageBox.ERROR); + return null; + } + TCComponent model = session.stringToComponent(option);//w9EAAI235kSPsC + if(model==null || !model.isTypeOf("MSExcelX")) { + MessageBox.post(desktop, "ѡML8_NewAndChangedReportģUIDòȷ", "ERROR", MessageBox.ERROR); + return null; + } + new NewAndChangedReportDialog(session, options, (TCComponentDataset)model); +// NewAndChangedReportOperation operation = new NewAndChangedReportOperation(session, options, (TCComponentDataset)model); +// session.queueOperation(operation); +// MessageBox.post(desktop, "ݽ", "ʾ", MessageBox.INFORMATION); + }catch(Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + } + return null; + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/workflow/NewAndChangedReportOperation.java b/src/com/connor/lidy/workflow/NewAndChangedReportOperation.java new file mode 100644 index 0000000..2ff060b --- /dev/null +++ b/src/com/connor/lidy/workflow/NewAndChangedReportOperation.java @@ -0,0 +1,142 @@ +package com.connor.lidy.workflow; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.sql.Connection; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.List; + +import javax.swing.JComboBox; + +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.lidy.util.SqlUtil; +import com.connor.lidy.util.TCUtil; +import com.teamcenter.rac.aif.AIFDesktop; +import com.teamcenter.rac.aif.AbstractAIFOperation; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentTcFile; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +public class NewAndChangedReportOperation extends AbstractAIFOperation { + +// private TCSession session; + private TCComponentDataset model; + private String options[]; +// private XSSFRow sourceRow; + private JComboBox comps; + + public NewAndChangedReportOperation(TCSession session, String options[], JComboBox comps, TCComponentDataset model) { +// this.session = session; + this.options = options; + this.model = model; + this.comps = comps; + } + + @Override + public void executeOperation() throws Exception { + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + FileInputStream input = null; + FileOutputStream output = null; + XSSFWorkbook wb = null; + try { + Connection conn = SqlUtil.getSqlserverConnection(options[0], options[1], options[2], options[3]); + String select = comps.getSelectedItem().toString(); + Date now = new Date(); + String year = new SimpleDateFormat("yyyy").format(now); + int month = 12; + //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + if(year.equals(select)) { + month = Integer.parseInt(new SimpleDateFormat("M").format(now))-1; + } + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); + File directory = TCUtil.saveExcelChooser("½ͳ"+sdf.format(now)); + if(directory==null) + return; + StringBuilder sql = new StringBuilder("select a.year,a.month,a.type,case a.bom when 0 then 1 else 0 end as class,count(a.puid) as count "); + sql.append("from VL25N_NewAndChange a,(select n.* from PITEM as m,PITEMREVISION as n where m.puid=n.ritems_tagu and m.pitem_id not like '%[-]%') b,") + .append("PWORKSPACEOBJECT b1,PPOM_APPLICATION_OBJECT c where a.puid=b.puid and b.puid=b1.puid ") + .append("and b.puid=c.puid and b1.pactive_seq=1 and a.year=").append(select).append(" and a.month<=").append(month) + .append(" and c.pcreation_date in (select min(c1.pcreation_date) from (select n.* from PITEM as m,PITEMREVISION as n where m.puid=n.ritems_tagu ") + .append("and m.pitem_id not like '%[-]%') b1,PPOM_APPLICATION_OBJECT c1 ") + .append("where b1.puid=c1.puid and b.ritems_tagu=b1.ritems_tagu) group by a.bom,a.type,a.year,a.month union ") + .append("select d.year,d.month,d.type,d.class,count(d.puid) as count ") + .append("from PML8_CNOTICEREVISION a,PWORKSPACEOBJECT a1,PIMANRELATION b,PIMANTYPE c,VL25N_CHANGEDOCANDPART d,(select n.* from PITEM as m,PITEMREVISION as n ") + .append("where m.puid=n.ritems_tagu and m.pitem_id not like '%[-]%') d0,PWORKSPACEOBJECT d1 where ") + .append("a.puid=a1.puid and a1.pactive_seq=1 and a.puid=b.rprimary_objectu and b.rsecondary_objectu=d.puid and d.puid=d1.puid and d1.pactive_seq=1 ") + .append("and d.puid=d0.puid and b.rrelation_typeu=c.puid and c.ptype_name='ML8_GXBGH' and d.year=") + .append(select).append(" and d.month<=").append(month).append(" and d0.pitem_revision_id!='A' group by d.year,d.month,d.type,d.class"); + + System.out.println("sql"+sql.toString()); + List> results = SqlUtil.getDBInfo(conn, sql.toString()); + +// if(results.size()<1) { +// MessageBox.post(desktop, "δҵ", "WARNING", MessageBox.WARNING); +// return; +// } + if(directory.exists()) + directory.delete(); + String path = directory.getPath(); + + 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; + for(HashMap c : results) { + row = getRow(sheet, (int)c.get("month")+2); + cell = getCell(row, (int)c.get("type") + (int)c.get("class")); + cell.setCellValue((int)c.get("count"));// +// System.out.println(cell.getRowIndex()+","+cell.getColumnIndex()+"=="+cell.getCellType()); +// cell = getCell(row, (int)c.get("type") + 2); +// System.out.println(cell.getRowIndex()+","+cell.getColumnIndex()+"=="+cell.getCellType()); + } + + output = new FileOutputStream(file.getPath()); + wb.setForceFormulaRecalculation(true); + wb.write(output); + input.close(); + output.close(); +// System.out.println("file:"+file.getPath()); + String newPath = System.getProperty("java.io.tmpdir")+path.substring(path.lastIndexOf("\\")); + File reFile = new File(newPath); + file.renameTo(reFile); +// System.out.println("new directory:"+reFile.getPath()); + reFile.renameTo(directory); + + MessageBox.post(desktop, "", "INFO", MessageBox.INFORMATION); + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + }finally { + if(input!=null) + input.close(); + if(output!=null) + output.close(); + } + } + 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; + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/workflow/RejectedCountReportDialog.java b/src/com/connor/lidy/workflow/RejectedCountReportDialog.java new file mode 100644 index 0000000..eabdf81 --- /dev/null +++ b/src/com/connor/lidy/workflow/RejectedCountReportDialog.java @@ -0,0 +1,100 @@ +package com.connor.lidy.workflow; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.text.SimpleDateFormat; +import java.util.Date; + +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JPanel; +import com.teamcenter.rac.aif.AbstractAIFDialog; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; +import com.teamcenter.rac.util.PropertyLayout; + +public class RejectedCountReportDialog extends AbstractAIFDialog { + private static final long serialVersionUID = 1L; + private TCSession session; + private TCComponentDataset model; + private JButton exportBtn; + private JButton cancelBtn; + private JComboBox comps; + + public RejectedCountReportDialog(TCSession session, String[] options, String[] tasks, TCComponentDataset model) throws Exception { + super(AIFUtility.getActiveDesktop()); + this.session = session; + this.model = model; + + setTitle("˴ͳƱ"); + JPanel propPanel = new JPanel(new PropertyLayout(70, 5, 10, 5, 5, 5)); + + Date now = new Date(); + int year = Integer.parseInt(new SimpleDateFormat("yyyy").format(now)); + + JLabel label1 = new JLabel(""); + propPanel.add("1.1.left.center", label1); + comps = new JComboBox<>(); + for(int y=2020; y<=year; y++) + comps.addItem(""+y); + comps.setSelectedItem(""+year); + comps.setPreferredSize(new Dimension(155, 23)); + propPanel.add("1.2.right.center", comps); + + exportBtn = new JButton(""); + cancelBtn = new JButton("ȡ"); + JPanel btnPanel = new JPanel(new FlowLayout()); + btnPanel.add(exportBtn); + btnPanel.add(cancelBtn); + setLayout(new BorderLayout()); + add(BorderLayout.CENTER, propPanel); + add(BorderLayout.SOUTH, btnPanel); +// add(new JLabel("")); + addActionListener(options, tasks); + + pack(); + setSize(new Dimension(350, 200)); + 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[] tasks) { + exportBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { +// ProgressReporterDialog reporter = new ProgressReporterDialog("ʾ"); +// reporter.reportProgressMessage("ڵԺ..."); +// new Thread(reporter).start(); +// new Thread() { +// public void run(){ +// } +// }.start(); + try { +// SimpleDateFormat sdf = new SimpleDateFormat("d-MMM-yyyy hh:mm"); + + new RejectedCountReportOperation(session, options, tasks, comps.getSelectedItem().toString(), model).executeOperation(); + dispose(); + }catch(Exception e1) { +// reporter.requestCanceling(); + e1.printStackTrace(); + MessageBox.post(RejectedCountReportDialog.this, ""+e1.getMessage(), "ERROR", MessageBox.ERROR); + } + } + }); + cancelBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + dispose(); + } + }); + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/workflow/RejectedCountReportHandler.java b/src/com/connor/lidy/workflow/RejectedCountReportHandler.java new file mode 100644 index 0000000..8620e0b --- /dev/null +++ b/src/com/connor/lidy/workflow/RejectedCountReportHandler.java @@ -0,0 +1,54 @@ +package com.connor.lidy.workflow; + +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.AbstractAIFUIApplication; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +//ļнṹ +public class RejectedCountReportHandler extends AbstractHandler implements IHandler{ + + public Object execute(ExecutionEvent arg0) throws ExecutionException { + System.out.println("RejectedCountReportHandler"); + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + try { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + TCSession session = (TCSession) app.getSession(); + String options[] = session.getPreferenceService().getStringValues("Meling_SqlServer"); + if(options==null || options.length<4) { + MessageBox.post(desktop, "ѡMeling_SqlServeròȷ", "ERROR", MessageBox.ERROR); + return null; + } + String[] tasks = session.getPreferenceService().getStringValues("ML8_RejectedListReport"); + if(tasks==null || tasks.length<2) { + MessageBox.post(desktop, "ѡML8_RejectedListReportòȷ", "ERROR", MessageBox.ERROR); + return null; + } + String option = session.getPreferenceService().getStringValue("ML8_RejectedCountReport"); +// if(option==null || option.length<1) { + if(option==null || option.isEmpty()) { + MessageBox.post(desktop, "ѡML8_RejectedCountReportòȷ", "ERROR", MessageBox.ERROR); + return null; + } + TCComponent model = session.stringToComponent(option);//RkBAAImz5kSPsC + if(model==null || !model.isTypeOf("MSExcelX")) { + MessageBox.post(desktop, "ѡML8_RejectedCountReportģUIDòȷ", "ERROR", MessageBox.ERROR); + return null; + } + new RejectedCountReportDialog(session, options, tasks, (TCComponentDataset)model); +// MessageBox.post(desktop, "ݽ", "ʾ", MessageBox.INFORMATION); + }catch(Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + } + return null; + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/workflow/RejectedCountReportOperation.java b/src/com/connor/lidy/workflow/RejectedCountReportOperation.java new file mode 100644 index 0000000..9c26f7f --- /dev/null +++ b/src/com/connor/lidy/workflow/RejectedCountReportOperation.java @@ -0,0 +1,313 @@ +package com.connor.lidy.workflow; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +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 org.apache.poi.ss.util.CellRangeAddress; +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.lidy.util.SqlUtil; +import com.connor.lidy.util.TCUtil; +import com.teamcenter.rac.aif.AIFDesktop; +import com.teamcenter.rac.aif.AbstractAIFOperation; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentGroup; +import com.teamcenter.rac.kernel.TCComponentTcFile; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +public class RejectedCountReportOperation extends AbstractAIFOperation { + + private TCSession session; + private TCComponentDataset model; + private String options[]; + private String tasks[]; +// private XSSFRow sourceRow; + private String select; + + public RejectedCountReportOperation(TCSession session, String options[], String[] tasks, String select, TCComponentDataset model) { + this.session = session; + this.options = options; + this.tasks = tasks; + this.model = model; + this.select = select; + } + + @Override + public void executeOperation() throws Exception { + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + FileInputStream input = null; + FileOutputStream output = null; + XSSFWorkbook wb = null; + try { + Connection conn = SqlUtil.getSqlserverConnection(options[0], options[1], options[2], options[3]); + Date now = new Date(); + String year = new SimpleDateFormat("yyyy").format(now); + int month = 12; + //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + if(year.equals(select)) { + month = Integer.parseInt(new SimpleDateFormat("M").format(now))-1; + } + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); + File directory = TCUtil.saveExcelChooser("˴ͳƱ"+sdf.format(now)); + if(directory==null) + return; + StringBuilder tasksql = new StringBuilder("''"); + for(int i=1; i> results = SqlUtil.getDBInfo(conn, sql.toString()); + +// if(results.size()<1) { +// MessageBox.post(desktop, "δҵ", "WARNING", MessageBox.WARNING); +// return; +// } + if(directory.exists()) + directory.delete(); + String path = directory.getPath(); + + TCComponentTcFile[] files = model.getTcFiles(); + File file = files[0].getFile(System.getProperty("java.io.tmpdir")); + input = new FileInputStream(file); + wb = new XSSFWorkbook(input); + + HashMap groupMap = new HashMap<>(); + HashMap nameMap = new HashMap<>(); + int col = 1; + for(HashMap map : results) { + String group = map.get("groupid").toString(); + if(!nameMap.containsKey(group)) { + String groupname = ((TCComponentGroup) session.stringToComponent(group)).getGroupName(); + nameMap.put(group, groupname); + } + if(!groupMap.containsKey(group)) { + groupMap.put(group, col); + col += 3; + } + } + int groups = groupMap.size(); + XSSFSheet sheet = wb.getSheetAt(0); + XSSFRow row = getRow(sheet, 0); + XSSFCell cell; + if(groups>4) { + cell = getCell(row, 13+3*(groups-4)); + cell.setCellStyle(getCell(row, 13).getCellStyle()); + cell.setCellValue(getCell(row, 13).getStringCellValue()); + cell = getCell(row, 14+3*(groups-4)); + cell.setCellStyle(getCell(row, 14).getCellStyle()); + cell = getCell(row, 15+3*(groups-4)); + cell.setCellStyle(getCell(row, 15).getCellStyle()); + sheet.addMergedRegion(new CellRangeAddress(0, 0, 13+3*(groups-4), 15+3*(groups-4))); + row = getRow(sheet, 1); + cell = getCell(row, 13+3*(groups-4)); + cell.setCellStyle(getCell(row, 13).getCellStyle()); + cell.setCellValue(getCell(row, 13).getStringCellValue()); + cell = getCell(row, 14+3*(groups-4)); + cell.setCellStyle(getCell(row, 14).getCellStyle()); + cell.setCellValue(getCell(row, 14).getStringCellValue()); + cell = getCell(row, 15+3*(groups-4)); + cell.setCellStyle(getCell(row, 15).getCellStyle()); + cell.setCellValue(getCell(row, 15).getStringCellValue()); + for(int i=0; i<13; i++) { + row = getRow(sheet, i+2); + cell = getCell(row, 13+3*(groups-4)); + cell.setCellStyle(getCell(row, 13).getCellStyle()); +// cell.setCellValue(getCell(row, 13).getStringCellValue()); + cell = getCell(row, 14+3*(groups-4)); + cell.setCellStyle(getCell(row, 14).getCellStyle()); +// cell.setCellValue(getCell(row, 14).getStringCellValue()); + cell = getCell(row, 15+3*(groups-4)); + cell.setCellStyle(getCell(row, 15).getCellStyle()); +// cell.setCellValue(getCell(row, 15).getStringCellValue()); + } + for(int i=0; i c : results) { + int m = (int) c.get("month")+2; + int g = groupMap.get(c.get("groupid")); + int t = (int) c.get("type"); + row = getRow(sheet, m-1); + if(t==0) { + cell = getCell(row, g+1); + cell.setCellValue((int)c.get("count"));// + }else { + cell = getCell(row, g); + cell.setCellValue((int)c.get("count"));// + } + cell = getCell(row, g+2); + StringBuilder formula = new StringBuilder(""); + formula.append(numToLetter(g)).append(m).append("/").append(numToLetter(g+1)).append(m); + cell.setCellFormula(formula.toString());// + } + //TODO + /*XSSFDrawing drawingPatriarch = sheet.getDrawingPatriarch(); + List charts = drawingPatriarch.getCharts(); + XSSFChart chart = charts.get(0); +// XDDFChartAxis[] axesCatVal = addAxesToChart(chart, "", ""); + List axis = chart.getAxes(); +// System.out.println("axis:"+axis.size()); +// System.out.println("axis:"+axis.get(0)+" "+axis.get(1)); + + XDDFLineChartData chartData = (XDDFLineChartData) chart.createData(ChartTypes.LINE, axis.get(0), (XDDFValueAxis) axis.get(1)); + System.out.println("chartData:"+chartData); + Series series1 = addLineSeriesToChartData(chartData, sheet, "Sheet1!$A$3:$A$14", "Sheet1!$M$3:$M$14", "Sheet1!$K$1", PresetColor.RED); + System.out.println("added line 1" + series1); +// chart.plot(chartData); + + CTPlotArea plotArea = chart.getCTChart().getPlotArea(); +// System.out.println("getBarChartArray:"+plotArea.array.length); + System.out.println("getLineChartArray:"+plotArea.getLineChartArray(0).sizeOfSerArray()); + + // ȡͼϵ + CTLineChart lines = plotArea.getLineChartArray(0); + CTLineSer line = lines.getSerArray(0); + System.out.println("line0:"+line.getVal().getNumRef().getF()); + line = lines.getSerArray(1); + System.out.println("line1:"+line.getVal().getNumRef().getF()); + + */ + + output = new FileOutputStream(file.getPath()); + wb.write(output); + input.close(); + output.close(); +// System.out.println("file:"+file.getPath()); + String newPath = System.getProperty("java.io.tmpdir")+path.substring(path.lastIndexOf("\\")); + File reFile = new File(newPath); + file.renameTo(reFile); +// System.out.println("new directory:"+reFile.getPath()); + reFile.renameTo(directory); + + MessageBox.post(desktop, "", "INFO", MessageBox.INFORMATION); + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + }finally { + if(input!=null) + input.close(); + if(output!=null) + output.close(); + } + } + 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; + } + private String numToLetter(int num) { + List list = new ArrayList<>(); + if(num<26) + return (char)(num+65) + ""; + int n = num; + while(n>25) { + list.add(n/26); + n = n%26; + } +// list.add(n); + int size = list.size(); + char[] array = new char[size+1]; + for(int i=0; i categoryData = XDDFDataSourcesFactory.fromNumericCellRange(sheet, CellRangeAddress.valueOf(categoryDataRef)); + XDDFNumericalDataSource valueData = XDDFDataSourcesFactory.fromNumericCellRange(sheet, CellRangeAddress.valueOf(valueDataRef)); + + Series series = (Series) chartData.addSeries(categoryData, valueData); + series.setTitle("", new CellReference(seriesTitleRef)); + series.setSmooth(false); + + series.setMarkerStyle(MarkerStyle.CIRCLE); + + XDDFShapeProperties shapeProperties = series.getShapeProperties(); + if (shapeProperties == null) { + shapeProperties = new XDDFShapeProperties(); + } + shapeProperties.setLineProperties(solidLineWithColor(lineColor)); + series.setShapeProperties(shapeProperties); + + return series; + } + private static XDDFLineProperties solidLineWithColor(PresetColor color) { + XDDFSolidFillProperties fill = new XDDFSolidFillProperties(XDDFColor.from(color)); + XDDFLineProperties line = new XDDFLineProperties(); + line.setFillProperties(fill); + return line; + }*/ +} \ No newline at end of file diff --git a/src/com/connor/lidy/workflow/RejectedListReportDialog.java b/src/com/connor/lidy/workflow/RejectedListReportDialog.java new file mode 100644 index 0000000..720c146 --- /dev/null +++ b/src/com/connor/lidy/workflow/RejectedListReportDialog.java @@ -0,0 +1,102 @@ +package com.connor.lidy.workflow; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JPanel; +import com.teamcenter.rac.aif.AbstractAIFDialog; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.stylesheet.PropertyDateComponent; +import com.teamcenter.rac.util.MessageBox; +import com.teamcenter.rac.util.PropertyLayout; + +public class RejectedListReportDialog extends AbstractAIFDialog { + private static final long serialVersionUID = 1L; + private TCSession session; + private TCComponentDataset model; + private JButton exportBtn; + private JButton cancelBtn; + private String tasks[]; + private PropertyDateComponent[] comps; + + public RejectedListReportDialog(TCSession session, String[] options, String[] tasks, TCComponentDataset model) throws Exception { + super(AIFUtility.getActiveDesktop()); + this.session = session; + this.model = model; + this.tasks = tasks; + this.comps = new PropertyDateComponent[2]; + + setTitle("˴ϸ"); + JPanel propPanel = new JPanel(new PropertyLayout(70, 5, 10, 5, 5, 5)); + + JLabel label1 = new JLabel("˻ʱ"); + propPanel.add("1.1.left.center", label1); + PropertyDateComponent date1 = new PropertyDateComponent(); + date1.setPreferredSize(new Dimension(155, 23)); + propPanel.add("1.2.right.center", date1); + comps[0] = date1; + + JLabel label2 = new JLabel("˻ʱ"); + propPanel.add("2.1.left.center", label2); + PropertyDateComponent date2 = new PropertyDateComponent(); + date2.setPreferredSize(new Dimension(155, 23)); + propPanel.add("2.2.right.center", date2); + comps[1] = date2; + + exportBtn = new JButton(""); + cancelBtn = new JButton("ȡ"); + JPanel btnPanel = new JPanel(new FlowLayout()); + btnPanel.add(exportBtn); + btnPanel.add(cancelBtn); + setLayout(new BorderLayout()); + add(BorderLayout.CENTER, propPanel); + add(BorderLayout.SOUTH, btnPanel); +// add(new JLabel("")); + addActionListener(options); + + pack(); + setSize(new Dimension(350, 200)); + 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) { + exportBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { +// ProgressReporterDialog reporter = new ProgressReporterDialog("ʾ"); +// reporter.reportProgressMessage("ڵԺ..."); +// new Thread(reporter).start(); +// new Thread() { +// public void run(){ +// } +// }.start(); + try { +// SimpleDateFormat sdf = new SimpleDateFormat("d-MMM-yyyy hh:mm"); + + new RejectedListReportOperation(session, options, tasks, comps, model).executeOperation(); + dispose(); + }catch(Exception e1) { +// reporter.requestCanceling(); + e1.printStackTrace(); + MessageBox.post(RejectedListReportDialog.this, ""+e1.getMessage(), "ERROR", MessageBox.ERROR); + } + } + }); + cancelBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + dispose(); + } + }); + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/workflow/RejectedListReportHandler.java b/src/com/connor/lidy/workflow/RejectedListReportHandler.java new file mode 100644 index 0000000..c054cd3 --- /dev/null +++ b/src/com/connor/lidy/workflow/RejectedListReportHandler.java @@ -0,0 +1,49 @@ +package com.connor.lidy.workflow; + +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.AbstractAIFUIApplication; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +//ļнṹ +public class RejectedListReportHandler extends AbstractHandler implements IHandler{ + + public Object execute(ExecutionEvent arg0) throws ExecutionException { + System.out.println("RejectedListReportHandler"); + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + try { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + TCSession session = (TCSession) app.getSession(); + String options[] = session.getPreferenceService().getStringValues("Meling_SqlServer"); + if(options==null || options.length<4) { + MessageBox.post(desktop, "ѡMeling_SqlServeròȷ", "ERROR", MessageBox.ERROR); + return null; + } + String[] option = session.getPreferenceService().getStringValues("ML8_RejectedListReport"); + if(option==null || option.length<2) { + MessageBox.post(desktop, "ѡML8_RejectedListReportòȷ", "ERROR", MessageBox.ERROR); + return null; + } + TCComponent model = session.stringToComponent(option[0]);//w1PAAImz5kSPsC + if(model==null || !model.isTypeOf("MSExcelX")) { + MessageBox.post(desktop, "ѡML8_RejectedListReportģUIDòȷ", "ERROR", MessageBox.ERROR); + return null; + } + new RejectedListReportDialog(session, options, option, (TCComponentDataset)model); +// session.queueOperation(operation); +// MessageBox.post(desktop, "ݽ", "ʾ", MessageBox.INFORMATION); + }catch(Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + } + return null; + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/workflow/RejectedListReportOperation.java b/src/com/connor/lidy/workflow/RejectedListReportOperation.java new file mode 100644 index 0000000..8252b66 --- /dev/null +++ b/src/com/connor/lidy/workflow/RejectedListReportOperation.java @@ -0,0 +1,194 @@ +package com.connor.lidy.workflow; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.sql.Connection; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +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.lidy.util.SqlUtil; +import com.connor.lidy.util.TCUtil; +import com.teamcenter.rac.aif.AIFDesktop; +import com.teamcenter.rac.aif.AbstractAIFOperation; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentGroup; +import com.teamcenter.rac.kernel.TCComponentTcFile; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.stylesheet.PropertyDateComponent; +import com.teamcenter.rac.util.MessageBox; + +public class RejectedListReportOperation extends AbstractAIFOperation { + + private TCSession session; + private TCComponentDataset model; + private String options[]; + private String tasks[]; + private XSSFRow sourceRow; + private PropertyDateComponent[] comps; + + public RejectedListReportOperation(TCSession session, String options[], String[] tasks, PropertyDateComponent[] comps, TCComponentDataset model) { + this.session = session; + this.options = options; + this.tasks = tasks; + this.comps = comps; + this.model = model; + } + + @SuppressWarnings("deprecation") + @Override + public void executeOperation() throws Exception { + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + FileInputStream input = null; + FileOutputStream output = null; + try { + Date now = new Date(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); + File directory = TCUtil.saveExcelChooser("˴ϸ"+sdf.format(now)); + if(directory==null) + return; + Connection conn = SqlUtil.getSqlserverConnection(options[0], options[1], options[2], options[3]); +// Statement state = conn.createStatement(); + StringBuilder tasksql = new StringBuilder(""); + for(int i=1; i groupMap = new HashMap<>(); + HashMap uidMap = new HashMap<>(); + + StringBuilder sql = new StringBuilder("select distinct a1.pname,b.puid,b.pfnd0SignoffComments,d1.pitem_id,"); + sql.append("d.pobject_name,d.puser_name,d.groupid as pgroup,b.pfnd0StartDate,dateadd(hour, 8, b.pfnd0LoggedDate) as pdate,f.puser_name as puser ") + .append("from PEPMTASK a,VL25N_TASKRELATION a1,PPOM_APPLICATION_OBJECT a2,PFND0WORKFLOWAUDIT b,PIMANRELATION c,PITEMREVISION d0,PITEM d1,") + .append("VL25N_POMPROPERTIES d,VL25N_JGTCOUNT e,PPOM_USER f where a.rparent_tasku=a1.cuid and a.puid=a2.puid and a.puid=substring(b.pfnd0Object,0,15) ") + .append("and a1.puid=c.rprimary_objectu and c.rsecondary_objectu=d0.puid and d0.ritems_tagu=d1.puid and d.puid=d0.puid ") + .append("and a1.puid=e.puid and b.pfnd0SignoffUserID=f.puser_id and (b.pfnd0SignoffDecision='Reject') ")//b.ptask_result='Rejected' or + .append("and (e.JGT=0 or e.JGT>0 and substring(d1.pitem_id,0,4)='JGT') ") + .append("and a1.pname+'='+a1.cname in (").append(tasksql.substring(1)).append(")").append(d1).append(d2); + + System.out.println("sql"+sql.toString()); + List> results = SqlUtil.getDBInfo(conn, sql.toString()); + +// if(results.size()<1) { +// MessageBox.post(desktop, "δҵ", "WARNING", MessageBox.WARNING); +// return; +// } + if(directory.exists()) + directory.delete(); + String path = directory.getPath(); + + TCComponentTcFile[] files = model.getTcFiles(); + File file = files[0].getFile(System.getProperty("java.io.tmpdir")); + input = new FileInputStream(file); + XSSFWorkbook wb = new XSSFWorkbook(input); + + int i = 1; + XSSFSheet sheet = wb.getSheetAt(0); + XSSFRow row; + XSSFCell cell; + sourceRow = getRow(sheet, i); + for(HashMap c : results) { + String puid = c.get("puid").toString(); + if(uidMap.containsKey(puid)) { + row = getRow(sheet, uidMap.get(puid)); + cell = getCell(row, 2); + cell.setCellValue(cell.getStringCellValue()+""+c.get("pitem_id").toString());//ϴ/ĵ +// i++; + continue; + } + uidMap.put(puid, i); + row = getRow(sheet, i); + cell = getCell(row, 0); + cell.setCellValue((Date)c.get("pdate"));//ʱ + cell = getCell(row, 1); + cell.setCellValue(c.get("pname").toString());// + cell = getCell(row, 2); + cell.setCellValue(c.get("pitem_id").toString());//ϴ/ĵ + cell = getCell(row, 3); + cell.setCellValue(c.get("pobject_name").toString());///ĵ + cell = getCell(row, 4); + cell.setCellValue(c.get("pfnd0SignoffComments").toString());//˻ԭ + cell = getCell(row, 5); + cell.setCellValue(c.get("puser_name").toString());// + cell = getCell(row, 6); +// cell.setCellValue(c.get("pgroup").toString());//߲ + String uid = c.get("pgroup").toString(); + if(groupMap.containsKey(uid)) + cell.setCellValue(groupMap.get(uid));//߲ + else { + TCComponentGroup g = (TCComponentGroup) session.stringToComponent(uid); + String group = g.getGroupName(); + cell.setCellValue(group);//߲ + groupMap.put(uid, group); + } + cell = getCell(row, 7); + cell.setCellValue(c.get("puser").toString());//˻ + + i++; + } + + output = new FileOutputStream(file.getPath()); + wb.write(output); + input.close(); + output.close(); +// System.out.println("file:"+file.getPath()); + String newPath = System.getProperty("java.io.tmpdir")+path.substring(path.lastIndexOf("\\")); + File reFile = new File(newPath); + file.renameTo(reFile); +// System.out.println("new directory:"+reFile.getPath()); + reFile.renameTo(directory); + + MessageBox.post(desktop, "", "INFO", MessageBox.INFORMATION); + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + }finally { + if(input!=null) + input.close(); + if(output!=null) + output.close(); + } + } + 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; + } +} diff --git a/src/com/connor/lidy/workflow/TypeChangedReportHandler.java b/src/com/connor/lidy/workflow/TypeChangedReportHandler.java new file mode 100644 index 0000000..c7b2bc5 --- /dev/null +++ b/src/com/connor/lidy/workflow/TypeChangedReportHandler.java @@ -0,0 +1,49 @@ +package com.connor.lidy.workflow; + +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.AbstractAIFUIApplication; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +//ļнṹ +public class TypeChangedReportHandler extends AbstractHandler implements IHandler{ + + public Object execute(ExecutionEvent arg0) throws ExecutionException { + System.out.println("TypeChangedReportHandler"); + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + try { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + TCSession session = (TCSession) app.getSession(); + String options[] = session.getPreferenceService().getStringValues("Meling_SqlServer"); + if(options==null || options.length<4) { + MessageBox.post(desktop, "ѡMeling_SqlServeròȷ", "ERROR", MessageBox.ERROR); + return null; + } + String option = session.getPreferenceService().getStringValue("ML8_TypeChangedReport"); + if(option==null || option.isEmpty()) { + MessageBox.post(desktop, "ѡML8_TypeChangedReportòȷ", "ERROR", MessageBox.ERROR); + return null; + } + TCComponent model = session.stringToComponent(option);//w9HAAIHg5kSPsC + if(model==null || !model.isTypeOf("MSExcelX")) { + MessageBox.post(desktop, "ѡML8_TypeChangedReportģUIDòȷ", "ERROR", MessageBox.ERROR); + return null; + } + TypeChangedReportOperation operation = new TypeChangedReportOperation(session, options, (TCComponentDataset)model); + session.queueOperation(operation); +// MessageBox.post(desktop, "ݽ", "ʾ", MessageBox.INFORMATION); + }catch(Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + } + return null; + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/workflow/TypeChangedReportOperation.java b/src/com/connor/lidy/workflow/TypeChangedReportOperation.java new file mode 100644 index 0000000..19d4e35 --- /dev/null +++ b/src/com/connor/lidy/workflow/TypeChangedReportOperation.java @@ -0,0 +1,171 @@ +package com.connor.lidy.workflow; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.sql.Connection; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +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.lidy.util.SqlUtil; +import com.connor.lidy.util.TCUtil; +import com.teamcenter.rac.aif.AIFDesktop; +import com.teamcenter.rac.aif.AbstractAIFOperation; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentTcFile; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +public class TypeChangedReportOperation extends AbstractAIFOperation { + +// private TCSession session; + private TCComponentDataset model; + private String options[]; + private XSSFRow sourceRow; + + public TypeChangedReportOperation(TCSession session, String options[], TCComponentDataset model) { +// this.session = session; + this.options = options; + this.model = model; + } + + @Override + public void executeOperation() throws Exception { + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + FileInputStream input = null; + FileOutputStream output = null; + try { + Connection conn = SqlUtil.getSqlserverConnection(options[0], options[1], options[2], options[3]); +// Statement state = conn.createStatement(); + Date now = new Date(); +// int yesr = Integer.parseInt(new SimpleDateFormat("yyyy").format(now)); +// int month = Integer.parseInt(new SimpleDateFormat("M").format(now)); +// //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); +// if(month == 1) { +// yesr--; +// month = 12; +// }else { +// month--; +// } + StringBuilder sql = new StringBuilder("select k.pml8_ProductCode as ml8_ProductCode,k.pml8_ProductType as ml8_ProductType,"); + sql.append("a.pml8_PlatformSeries as ml8_PlatformSeries,a.pml8_ProjectManagement as ml8_ProjectManagement,") + .append("a.pml8_ProjectName as ml8_ProjectName,a.state as status,e.pml8_ProductCode,e.pml8_ProductType,e.pml8_PlatformSeries,") + .append("e.pml8_ProjectManagement,e.pml8_ProjectName,e.state,e.pdate_released,e3.puser_name,e1.pobject_name ") + .append("from VL25N_TYPECHANGED a,PWORKSPACEOBJECT a1,PIMANRELATION b,PIMANTYPE b1,PML8_CNOTICEREVISION c,PWORKSPACEOBJECT c1,") + .append("PIMANRELATION d,PIMANTYPE d1,PPOM_APPLICATION_OBJECT e2,PPOM_USER e3,PWORKSPACEOBJECT e1,VL25N_TYPECHANGED e ") + .append("left join PWORKSPACEOBJECT e1 on e.taskuid=e1.puid left join VL25N_PROJECTFORM k on e.puid=k.puid ") + .append("where a.puid=a1.puid and a1.pactive_seq=1 and a.ritems_tagu=e.ritems_tagu and e.puid=e1.puid and e1.pactive_seq=1 ") + .append("and a.puid=b.rsecondary_objectu and b.rrelation_typeu=b1.puid ") + .append("and b1.ptype_name='ML8_GXBGQ' and b.rprimary_objectu=c.puid and c.puid=c1.puid and c1.pactive_seq=1 and c.puid=d.rprimary_objectu ") + .append("and e.puid=e2.puid and e2.rowning_useru=e3.puid and d.rsecondary_objectu=e.puid and d.rrelation_typeu=d1.puid ") + .append("and d1.ptype_name='ML8_GXBGH'"); + + System.out.println("sql"+sql.toString()); + List> results = SqlUtil.getDBInfo(conn, sql.toString()); + +// if(results.size()<1) { +// MessageBox.post(desktop, "δҵ", "WARNING", MessageBox.WARNING); +// return; +// } + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); + File directory = TCUtil.saveExcelChooser("ƷͺŸı"+sdf.format(now)); + if(directory==null) + return; + if(directory.exists()) + directory.delete(); + String path = directory.getPath(); + + TCComponentTcFile[] files = model.getTcFiles(); + File file = files[0].getFile(System.getProperty("java.io.tmpdir")); + input = new FileInputStream(file); + XSSFWorkbook wb = new XSSFWorkbook(input); + + int i = 2; + XSSFSheet sheet = wb.getSheetAt(0); + XSSFRow row; + XSSFCell cell; + sourceRow = getRow(sheet, i); + for(HashMap c : results) { + row = getRow(sheet, i); + cell = getCell(row, 0); + cell.setCellValue(i-1);// + cell = getCell(row, 1); + cell.setCellValue(c.get("ml8_ProductCode").toString());//ԭƷ + cell = getCell(row, 2); + cell.setCellValue(c.get("ml8_ProductType").toString());//ԭƷͺ + cell = getCell(row, 3); + cell.setCellValue(c.get("ml8_PlatformSeries").toString());//ԭƽ̨ϵ + cell = getCell(row, 4); + cell.setCellValue(c.get("ml8_ProjectManagement").toString());//ԭĿ + cell = getCell(row, 5); + cell.setCellValue(c.get("ml8_ProjectName").toString());//ԭĿ + cell = getCell(row, 6); + cell.setCellValue(c.get("status").toString());//״̬ + cell = getCell(row, 7); + cell.setCellValue(c.get("pml8_ProductCode").toString());//ֲƷ + cell = getCell(row, 8); + cell.setCellValue(c.get("pml8_ProductType").toString());//ͺ + cell = getCell(row, 9); + cell.setCellValue(c.get("pml8_PlatformSeries").toString());//ƽ̨ϵ + cell = getCell(row, 10); + cell.setCellValue(c.get("pml8_ProjectManagement").toString());//Ŀ + cell = getCell(row, 11); + cell.setCellValue(c.get("pml8_ProjectName").toString());//Ŀ + cell = getCell(row, 12); + cell.setCellValue(c.get("puser_name").toString());// + cell = getCell(row, 13); + Object pdate_released = c.get("pdate_released"); + if(pdate_released != null) + cell.setCellValue((Date)pdate_released);//ʱ + cell = getCell(row, 14); + cell.setCellValue(c.get("state").toString());//״̬ + cell = getCell(row, 15); + cell.setCellValue(c.get("pobject_name").toString());//̱ + + i++; + } + + output = new FileOutputStream(file.getPath()); + wb.write(output); + input.close(); + output.close(); +// System.out.println("file:"+file.getPath()); + String newPath = System.getProperty("java.io.tmpdir")+path.substring(path.lastIndexOf("\\")); + File reFile = new File(newPath); + file.renameTo(reFile); +// System.out.println("new directory:"+reFile.getPath()); + reFile.renameTo(directory); + + MessageBox.post(desktop, "", "INFO", MessageBox.INFORMATION); + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + }finally { + if(input!=null) + input.close(); + if(output!=null) + output.close(); + } + } + 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()>2) + cell.setCellStyle(getCell(sourceRow, col).getCellStyle()); + return cell; + } +} diff --git a/src/com/connor/lidy/workflow/WorkMemberReportHandler.java b/src/com/connor/lidy/workflow/WorkMemberReportHandler.java new file mode 100644 index 0000000..3d1925f --- /dev/null +++ b/src/com/connor/lidy/workflow/WorkMemberReportHandler.java @@ -0,0 +1,49 @@ +package com.connor.lidy.workflow; + +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.AbstractAIFUIApplication; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +//ļнṹ +public class WorkMemberReportHandler extends AbstractHandler implements IHandler{ + + public Object execute(ExecutionEvent arg0) throws ExecutionException { + System.out.println("WorkMemberReportHandler"); + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + try { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + TCSession session = (TCSession) app.getSession(); + String options[] = session.getPreferenceService().getStringValues("ML8_WorkflowMemberReport"); + if(options==null || options.length<2) { + MessageBox.post(desktop, "ѡML8_WorkflowMemberReportòȷ", "ERROR", MessageBox.ERROR); + return null; + } + TCComponent model = session.stringToComponent(options[0]);//wlCAAI255kSPsC + if(model==null || !model.isTypeOf("MSExcelX")) { + MessageBox.post(desktop, "ѡML8_WorkflowMemberReportExcelģUIDòȷ", "ERROR", MessageBox.ERROR); + return null; + } + TCComponent xml = session.stringToComponent(options[1]);//gGHAAI2p5kSPsC + if(xml==null || !xml.isTypeOf("XMLRenderingStylesheet")) { + MessageBox.post(desktop, "ѡML8_WorkflowMemberReportָxmlģUIDòȷ", "ERROR", MessageBox.ERROR); + return null; + } + WorkMemberReportOperation operation = new WorkMemberReportOperation(session, (TCComponentDataset)model, xml); + session.queueOperation(operation); +// MessageBox.post(desktop, "ݽ", "ʾ", MessageBox.INFORMATION); + }catch(Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + } + return null; + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/workflow/WorkMemberReportOperation.java b/src/com/connor/lidy/workflow/WorkMemberReportOperation.java new file mode 100644 index 0000000..ece8241 --- /dev/null +++ b/src/com/connor/lidy/workflow/WorkMemberReportOperation.java @@ -0,0 +1,280 @@ +package com.connor.lidy.workflow; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import org.apache.poi.xssf.usermodel.XSSFCell; +import org.apache.poi.xssf.usermodel.XSSFRow; +import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.dom4j.Document; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; + +import com.connor.lidy.util.TCUtil; +import com.teamcenter.rac.aif.AIFDesktop; +import com.teamcenter.rac.aif.AbstractAIFOperation; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentTaskTemplate; +import com.teamcenter.rac.kernel.TCComponentTcFile; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +public class WorkMemberReportOperation extends AbstractAIFOperation { + + private TCSession session; + private TCComponentDataset model; + private TCComponentDataset xml; + + public WorkMemberReportOperation(TCSession session, TCComponentDataset model, TCComponent xml) { + this.session = session; + this.xml = (TCComponentDataset) xml; + this.model = model; + } + + @SuppressWarnings("unchecked") + @Override + public void executeOperation() throws Exception { + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + FileInputStream input = null; + FileOutputStream output = null; + try { + String[] key = new String[]{ "ģ", "׶" }; + String[] val = new String[]{ "0", "1;2" }; + TCComponent[] results = TCUtil.query(session, "SearchWorkflowTemplate", key, val); + if(results.length<1) { + MessageBox.post(desktop, "δҵģ", "WARNING", MessageBox.WARNING); + return; + } + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); + File directory = TCUtil.saveExcelChooser(sdf.format(new Date())); + if(directory==null) + return; + if(directory.exists()) + directory.delete(); + String path = directory.getPath(); + + HashMap> xmlMap = new HashMap<>(); + TCComponentTcFile[] files = xml.getTcFiles(); + File xmlFile = files[0].getFile(System.getProperty("java.io.tmpdir")); + Document doc = new SAXReader().read(xmlFile); + Element Mroot = doc.getRootElement(); + List ItemTypes = Mroot.elements("ItemType"); + for(Object o : ItemTypes) { + Element ItemType = (Element) o; + List Processes = ItemType.elements("Process"); + for(Object o2 : Processes) { + Element Process = (Element) o2; + List ProcessNodes = Process.elements("ProcessNode"); + for(Object o3 : ProcessNodes) { + Element ProcessNode = (Element) o3; + String node = Process.attributeValue("processName") +"::"+ ProcessNode.attributeValue("nodeName"); + HashMap map; + if(xmlMap.containsKey(node)) + map = xmlMap.get(node); + else { + map = new HashMap<>(); + xmlMap.put(node, map); + } + List Propertys = ProcessNode.elements("Property"); + for(Object o4 : Propertys) { + Element Property = (Element) o4; + StringBuilder cond = new StringBuilder("objectType=\""); + cond.append(ItemType.attributeValue("objectType")).append("\""); + if(!Property.attributeValue("referenced").isEmpty()) + cond.append(",referenced=\"").append(Property.attributeValue("referenced")).append("\""); + cond.append(",where=\"").append(Property.attributeValue("where")).append("\""); + StringBuilder users = new StringBuilder(""); + List Users = Property.elements("User"); + for(Object o5 : Users) { + Element User = (Element) o5; + if(!User.attributeValue("referenced").isEmpty()) + users.append("referenced=\"").append(User.attributeValue("referenced")).append("\","); + if(!User.attributeValue("referenced2").isEmpty()) + users.append("referenced2=\"").append(User.attributeValue("referenced2")).append("\","); + if(!User.attributeValue("propertyName").isEmpty()) + users.append("propertyName=\"").append(User.attributeValue("propertyName")).append("\","); + if(!User.attributeValue("group").isEmpty()) + users.append("group=\"").append(User.attributeValue("group")).append("\","); + if(!User.attributeValue("role").isEmpty()) + users.append("role=\"").append(User.attributeValue("role")).append("\","); + if(!User.attributeValue("userID").isEmpty()) + users.append("userID=\"").append(User.attributeValue("userID")).append("\""); + if(users.length()>0) + users.append("\n"); + } + if(users.length()>0) { + String con = cond.toString(); + if(map.containsKey(con)) + map.put(con, map.get(con)+users.toString()); + else + map.put(con, users.toString()); + } + } + } + } + } + for(String s : xmlMap.keySet()) { + HashMap map = xmlMap.get(s); + for(String ss : map.keySet()) { + System.out.println(s+":"+ss+"=="+map.get(ss)); + } + } + + files = model.getTcFiles(); + File file = files[0].getFile(System.getProperty("java.io.tmpdir")); + input = new FileInputStream(file); + int i = 1; + XSSFWorkbook wb = new XSSFWorkbook(input); + XSSFSheet sheet = wb.getSheetAt(0); + XSSFRow row; + XSSFCell cell; + for(TCComponent c : results) { + if(c instanceof TCComponentTaskTemplate) { + TCComponentTaskTemplate temp = (TCComponentTaskTemplate) c; + System.out.println(temp.getProperty("object_name")); + TCComponent[] subtasks = temp.getReferenceListProperty("subtask_template"); + if(subtasks==null || subtasks.length==0) { + row = getRow(sheet, i); + cell = getCell(row, 0); + cell.setCellValue(temp.getProperty("object_name")); + i++; + continue; + } + for(TCComponent sub : subtasks) { + /*row = getRow(sheet, i); + String subName = sub.getProperty("object_name"); + if(temp.getProperty("object_name").equals("EBOM") && subName.equals("")) { + TCComponent[] subtasks2 = sub.getReferenceListProperty("subtask_template"); + for(TCComponent sub2 : subtasks2) { +// System.out.println(sub2.getProperty("object_name")+""+sub2.getProperty("object_type")); + if(sub2.getProperty("object_type").equals("ѡǩСģ")) { + TCComponent[] signoff_profiles = sub2.getReferenceListProperty("signoff_profiles"); + System.out.println(subName+""+signoff_profiles[0]+"=="+signoff_profiles[0].getType()); + }else if(sub2.getProperty("object_type").equals("ִǩģ")) { + System.out.println(subName+""+sub2.getProperty("fnd0Instructions")); + } + } + TCComponent[] undos = sub.getReferenceListProperty("undo_action_handlers"); + for(TCComponent undo : undos) { + System.out.println("undo"+undo.getProperty("object_name")); + if(undo.getProperty("object_name").equals("EPM-demote")) { + System.out.println("EPM-demote"+undo.getTCProperty("arguments").getStringArrayValue()[0]); + } + } + }*/ + String node = temp.getProperty("object_name") +"::"+ sub.getProperty("object_name"); + String type = sub.getProperty("object_type"); + if(xmlMap.containsKey(node)) { + HashMap map = xmlMap.get(node); + for(String s : map.keySet()) { + row = getRow(sheet, i); + cell = getCell(row, 0); + cell.setCellValue(temp.getProperty("object_name")); + cell = getCell(row, 1); + cell.setCellValue(sub.getProperty("object_name")); + cell = getCell(row, 2); + cell.setCellValue(type); + cell = getCell(row, 3); + cell.setCellValue(map.get(s)); + cell = getCell(row, 4); + if(type.equals("ˡģ") || type.equals("Ͽɡģ")) { + TCComponent[] subs = sub.getReferenceListProperty("subtask_template"); + for(TCComponent task : subs) { + if(task.getProperty("object_type").equals("ִǩģ")) { + cell.setCellValue(task.getProperty("fnd0Instructions")); + } + } + }else { + cell.setCellValue(sub.getProperty("fnd0Instructions")); + } + cell = getCell(row, 5); + cell.setCellValue(s); + + i++; + } + }else { + row = getRow(sheet, i); + cell = getCell(row, 0); + cell.setCellValue(temp.getProperty("object_name")); + cell = getCell(row, 1); + cell.setCellValue(sub.getProperty("object_name")); + cell = getCell(row, 2); + cell.setCellValue(type); + if(type.equals("ˡģ") || type.equals("Ͽɡģ")) { + TCComponent[] subs = sub.getReferenceListProperty("subtask_template"); + for(TCComponent task : subs) { + if(task.getProperty("object_type").equals("ѡǩСģ")) { + cell = getCell(row, 3); + TCComponent[] signoff_profiles = task.getReferenceListProperty("signoff_profiles"); + if(signoff_profiles==null || signoff_profiles.length==0) { + TCComponent[] handlers = sub.getReferenceListProperty("action_handlers"); + for(TCComponent handler : handlers) { + if(handler.getProperty("object_name").equals("EPM-adhoc-signoffs")) { + String[] args = handler.getTCProperty("handler_arguments").getStringArrayValue(); + for(String arg : args) { + if(arg.startsWith("-assigne=")) { + cell.setCellValue(arg.replace("-assigne=", "")); + } + } + } + } + }else { + cell.setCellValue(signoff_profiles[0].toString()); + } + }else if(task.getProperty("object_type").equals("ִǩģ")) { + cell = getCell(row, 4); + cell.setCellValue(task.getProperty("fnd0Instructions")); + } + } + }else { + cell = getCell(row, 4); + cell.setCellValue(sub.getProperty("fnd0Instructions")); + } + + i++; + } + } + } + } + output = new FileOutputStream(file.getPath()); + wb.write(output); + input.close(); + output.close(); +// System.out.println("file:"+file.getPath()); + String newPath = System.getProperty("java.io.tmpdir")+path.substring(path.lastIndexOf("\\")); + File reFile = new File(newPath); + file.renameTo(reFile); +// System.out.println("new directory:"+reFile.getPath()); + reFile.renameTo(directory); + + MessageBox.post(desktop, "", "INFO", MessageBox.INFORMATION); + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + }finally { + if(input!=null) + input.close(); + if(output!=null) + output.close(); + } + } + private static XSSFRow getRow(XSSFSheet sheet, int num) throws Exception { + XSSFRow row = sheet.getRow(num); + if(row==null) + row = sheet.createRow(num); + return row; + } + private static XSSFCell getCell(XSSFRow row, int col) throws Exception { + XSSFCell cell = row.getCell(col); + if(cell==null) + cell = row.createCell(col); + return cell; + } +} diff --git a/src/com/connor/lidy/workflow/WorkflowHistoryHandler.java b/src/com/connor/lidy/workflow/WorkflowHistoryHandler.java new file mode 100644 index 0000000..e82dfec --- /dev/null +++ b/src/com/connor/lidy/workflow/WorkflowHistoryHandler.java @@ -0,0 +1,49 @@ +package com.connor.lidy.workflow; + +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.AbstractAIFUIApplication; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +//ļнṹ +public class WorkflowHistoryHandler extends AbstractHandler implements IHandler{ + + public Object execute(ExecutionEvent arg0) throws ExecutionException { + System.out.println("WorkflowHistoryHandler"); + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + try { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + TCSession session = (TCSession) app.getSession(); + String options[] = session.getPreferenceService().getStringValues("Meling_SqlServer"); + if(options==null || options.length<4) { + MessageBox.post(desktop, "ѡMeling_SqlServeròȷ", "ERROR", MessageBox.ERROR); + return null; + } + String option = session.getPreferenceService().getStringValue("ML8_WorkflowHistory"); + if(option==null || option.isEmpty()) { + MessageBox.post(desktop, "ѡML8_WorkflowHistoryòȷ", "ERROR", MessageBox.ERROR); + return null; + } + TCComponent model = session.stringToComponent(option);//AGHAAIH95kSPsC + if(model==null || !model.isTypeOf("MSExcelX")) { + MessageBox.post(desktop, "ѡML8_WorkflowHistoryģUIDòȷ", "ERROR", MessageBox.ERROR); + return null; + } + WorkflowHistoryOperation operation = new WorkflowHistoryOperation(session, options, (TCComponentDataset)model); + session.queueOperation(operation); +// MessageBox.post(desktop, "ݽ", "ʾ", MessageBox.INFORMATION); + }catch(Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + } + return null; + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/workflow/WorkflowHistoryOperation.java b/src/com/connor/lidy/workflow/WorkflowHistoryOperation.java new file mode 100644 index 0000000..e84acac --- /dev/null +++ b/src/com/connor/lidy/workflow/WorkflowHistoryOperation.java @@ -0,0 +1,178 @@ +package com.connor.lidy.workflow; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.sql.Connection; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +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.lidy.util.SqlUtil; +import com.connor.lidy.util.TCUtil; +import com.teamcenter.rac.aif.AIFDesktop; +import com.teamcenter.rac.aif.AbstractAIFOperation; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentTask; +import com.teamcenter.rac.kernel.TCComponentTcFile; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +public class WorkflowHistoryOperation extends AbstractAIFOperation { + + private TCSession session; + private TCComponentDataset model; + private String options[]; + private XSSFRow sourceRow; + + public WorkflowHistoryOperation(TCSession session, String options[], TCComponentDataset model) { + this.session = session; + this.options = options; + this.model = model; + } + + @Override + public void executeOperation() throws Exception { + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + FileInputStream input = null; + FileOutputStream output = null; + try { + Connection conn = SqlUtil.getSqlserverConnection(options[0], options[1], options[2], options[3]); +// Statement state = conn.createStatement(); + Date now = new Date(); +// int yesr = Integer.parseInt(new SimpleDateFormat("yyyy").format(now)); +// int month = Integer.parseInt(new SimpleDateFormat("M").format(now)); +// //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); +// if(month == 1) { +// yesr--; +// month = 12; +// }else { +// month--; +// } + +// if(results.size()<1) { +// MessageBox.post(desktop, "δҵ", "WARNING", MessageBox.WARNING); +// return; +// } + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); + File directory = TCUtil.saveExcelChooser("ִеĹʷ"+sdf.format(now)); + if(directory==null) + return; + if(directory.exists()) + directory.delete(); + String path = directory.getPath(); + String userid = session.getUser().getUserId(); + HashMap map = new HashMap<>(); + map.put("__Complete", ""); + map.put("__Approve", "׼"); + map.put("__Reject", "ܾ"); + map.put("__Perform", ""); + + StringBuilder sql = new StringBuilder("select * from VL25N_WORKFLOWHISTORY where userid='"); + sql.append(userid).append("' order by puid,pfnd0LoggedDate"); + System.out.println("sql"+sql.toString()); + List> results = SqlUtil.getDBInfo(conn, sql.toString()); + + TCComponentTcFile[] files = model.getTcFiles(); + File file = files[0].getFile(System.getProperty("java.io.tmpdir")); + input = new FileInputStream(file); + XSSFWorkbook wb = new XSSFWorkbook(input); + + int i = 1; + XSSFSheet sheet = wb.getSheetAt(0); + XSSFRow row; + XSSFCell cell; + sourceRow = getRow(sheet, i); + String uid = ""; + TCComponentTask task = null; + for(HashMap c : results) { + String puid = c.get("puid").toString(); + if(!puid.equals(uid)) { + uid = puid; + task = (TCComponentTask)session.stringToComponent(puid); +// TCComponent[] st = task.getReferenceListProperty("Fnd0EPMScheduleTask"); +// System.out.println("task"+st.length); + } + if(task==null) + continue; + row = getRow(sheet, i); + cell = getCell(row, 0); + cell.setCellValue(c.get("pjob_name").toString());// + cell = getCell(row, 1); + cell.setCellValue(task.getReferenceProperty("owning_user").toString());//̷ + cell = getCell(row, 2); + cell.setCellValue(task.getTaskState());//ǰ״̬ + cell = getCell(row, 3); + cell.setCellValue(c.get("taskname").toString());//ڵ + cell = getCell(row, 4); + cell.setCellValue((Date)c.get("pfnd0LoggedDate"));//ִʱ + cell = getCell(row, 5); + cell.setCellValue(map.get(c.get("pfnd0EventTypeName").toString()));//ִн + cell = getCell(row, 6); + cell.setCellValue(c.get("pfnd0SignoffComments").toString());//ע + StringBuilder target = new StringBuilder(""); + for(TCComponent r : task.getReferenceListProperty("Fnd0EPMTarget")) { + target.append(r).append("\n"); + } + cell = getCell(row, 7); + cell.setCellValue(target.toString());//Ŀ + target = new StringBuilder(""); + for(TCComponent r : task.getReferenceListProperty("Fnd0EPMReference")) { + target.append(r).append("\n"); + } + cell = getCell(row, 8); + cell.setCellValue(target.toString());// + cell = getCell(row, 9); + TCComponent[] st = task.getReferenceListProperty("Fnd0EPMScheduleTask"); + if(st.length>0) + cell.setCellValue(st[0].toString());//ʱ + else + cell.setCellValue("");//ʱ + + i++; + } + + output = new FileOutputStream(file.getPath()); + wb.write(output); + input.close(); + output.close(); +// System.out.println("file:"+file.getPath()); + String newPath = System.getProperty("java.io.tmpdir")+path.substring(path.lastIndexOf("\\")); + File reFile = new File(newPath); + file.renameTo(reFile); +// System.out.println("new directory:"+reFile.getPath()); + reFile.renameTo(directory); + + MessageBox.post(desktop, "", "INFO", MessageBox.INFORMATION); + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + }finally { + if(input!=null) + input.close(); + if(output!=null) + output.close(); + } + } + 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; + } +} diff --git a/src/com/connor/lidy/workflow/WorkflowReportHandler.java b/src/com/connor/lidy/workflow/WorkflowReportHandler.java new file mode 100644 index 0000000..899103a --- /dev/null +++ b/src/com/connor/lidy/workflow/WorkflowReportHandler.java @@ -0,0 +1,44 @@ +package com.connor.lidy.workflow; + +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.AbstractAIFUIApplication; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +//ļнṹ +public class WorkflowReportHandler extends AbstractHandler implements IHandler{ + + public Object execute(ExecutionEvent arg0) throws ExecutionException { + System.out.println("WorkflowReportHandler"); + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + try { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + TCSession session = (TCSession) app.getSession(); + String options[] = session.getPreferenceService().getStringValues("ML8_WorkflowTemplateReport"); + if(options==null || options.length<2) { + MessageBox.post(desktop, "ѡML8_WorkflowTemplateReportòȷ", "ERROR", MessageBox.ERROR); + return null; + } + TCComponent model = session.stringToComponent(options[0]);//wONAAIWd5kSPsC + if(model==null || !model.isTypeOf("MSExcelX")) { + MessageBox.post(desktop, "ѡML8_WorkflowTemplateReportģUIDòȷ", "ERROR", MessageBox.ERROR); + return null; + } + WorkflowReportOperation operation = new WorkflowReportOperation(session, options, (TCComponentDataset)model); + session.queueOperation(operation); +// MessageBox.post(desktop, "ݽ", "ʾ", MessageBox.INFORMATION); + }catch(Exception e) { + e.printStackTrace(); + MessageBox.post(desktop, ""+e.getMessage(), "ERROR", MessageBox.ERROR); + } + return null; + } +} \ No newline at end of file diff --git a/src/com/connor/lidy/workflow/WorkflowReportOperation.java b/src/com/connor/lidy/workflow/WorkflowReportOperation.java new file mode 100644 index 0000000..2212eda --- /dev/null +++ b/src/com/connor/lidy/workflow/WorkflowReportOperation.java @@ -0,0 +1,176 @@ +package com.connor.lidy.workflow; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Vector; + +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.lidy.util.TCUtil; +import com.teamcenter.rac.aif.AIFDesktop; +import com.teamcenter.rac.aif.AbstractAIFOperation; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentTaskTemplate; +import com.teamcenter.rac.kernel.TCComponentTcFile; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +public class WorkflowReportOperation extends AbstractAIFOperation { + + private TCSession session; + private TCComponentDataset model; + private String options[]; + + public WorkflowReportOperation(TCSession session, String options[], TCComponentDataset model) { + this.session = session; + this.options = options; + this.model = model; + } + + @Override + public void executeOperation() throws Exception { + AIFDesktop desktop = AIFUtility.getActiveDesktop(); + FileInputStream input = null; + FileOutputStream output = null; + try { + Vector vec = new Vector<>(); + for(int i=1; i