BOM装箱单批量填写代码上传

master
李冬阳 1 year ago
commit e85afb0702

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

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

@ -0,0 +1,2 @@
eclipse.preferences.version=1
encoding/<project>=GBK

@ -0,0 +1,9 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=11
org.eclipse.jdt.core.compiler.compliance=11
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning
org.eclipse.jdt.core.compiler.release=enabled
org.eclipse.jdt.core.compiler.source=11

@ -0,0 +1,17 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Cust
Bundle-SymbolicName: com.connor.cust;singleton:=true
Bundle-Version: 1.0.0
Bundle-Activator: com.connor.cust.Activator
Bundle-Vendor: CONNOR
Require-Bundle: org.eclipse.ui,
org.eclipse.core.runtime,
com.teamcenter.rac.kernel;bundle-version="14000.3.0",
com.teamcenter.rac.aifrcp;bundle-version="14000.3.0",
com.teamcenter.rac.util;bundle-version="14000.3.0",
org.apache.poi;bundle-version="5.2.1",
TcSoaCoreRac;bundle-version="14000.3.0"
Bundle-RequiredExecutionEnvironment: JavaSE-11
Automatic-Module-Name: com.connor.cust
Bundle-ActivationPolicy: lazy

@ -0,0 +1,8 @@
preferr=preferences error!
#XYBOM
ok=ok
err=Error:
cel=cancel
notbom= is not BOMLine!
setbox=Set Box
boxfinish=Box set finished!

@ -0,0 +1,10 @@
preferr=\u9996\u9009\u9879\u914D\u7F6E\u4E0D\u6B63\u786E
#XYBOM
ok=\u786E\u5B9A
err=\u9519\u8BEF\uFF1A
cel=\u53D6\u6D88
notbom= \u4E0D\u662FBOM\u884C\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\uFF01
setbox=\u8BBE\u7F6E\u88C5\u7BB1\u5355
boxfinish=\u88C5\u7BB1\u5355\u8BBE\u7F6E\u5B8C\u6210\uFF01
#BoxReport
nottop=\u9009\u4E2D\u5BF9\u8C61\u4E0D\u662FBOM\u9876\u5C42\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\uFF01

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 332 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 526 B

@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<plugin>
<extension
point="org.eclipse.ui.commands">
<command
name="设置装箱单"
id="XYBOMHandler">
</command>
</extension>
<extension
point="org.eclipse.ui.handlers">
<handler
class="com.connor.cust.box.XYBOMHandler"
commandId="XYBOMHandler">
</handler>
</extension>
<extension
point="org.eclipse.ui.menus">
<!-->
<menuContribution
locationURI="menu:org.eclipse.ui.main.menu?after=additions">
<menu
id="com.connor.cust.menus.sampleMenu"
label="Sample Menu"
mnemonic="M">
<command
commandId="com.connor.cust.commands.sampleCommand"
id="com.connor.cust.menus.sampleCommand"
mnemonic="S">
</command>
</menu>
</menuContribution><-->
<menuContribution locationURI="popup:org.eclipse.ui.popup.any?after=additions">
<command commandId="XYBOMHandler" id="XYBOMHandler" label="设置装箱单">
<visibleWhen checkEnabled="true">
<and>
<reference definitionId="com.teamcenter.rac.pse.inMainView"/>
<with variable="rac_command_suppression">
<not>
<iterate operator="or">
<equals value="XYBOMHandler"/>
</iterate>
</not>
</with>
</and>
</visibleWhen>
</command>
</menuContribution>
</extension>
</plugin>

@ -0,0 +1,44 @@
package com.connor.cust;
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.cust"; //$NON-NLS-1$
// The shared instance
private static Activator plugin;
/**
* The constructor
*/
public Activator() {
}
@Override
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
}
@Override
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
}

@ -0,0 +1,53 @@
package com.connor.cust.box;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
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.TCSession;
import com.teamcenter.rac.util.MessageBox;
/**
* :
* :2024-01-05
* @author
*
*
* 2019-01-24 XXXX
*/
public class BoxReportHandler extends AbstractHandler{
@Override
public Object execute(ExecutionEvent arg0) throws ExecutionException {
System.out.println("BoxReportHandler");
AIFDesktop desktop = AIFUtility.getActiveDesktop();
try {
AbstractAIFUIApplication app = AIFUtility.getCurrentApplication();
TCSession session = (TCSession) app.getSession();
InterfaceAIFComponent target = app.getTargetComponent();
if(target == null || !(target instanceof TCComponentBOMLine)) {
MessageBox.post(desktop, PlmLocale.getString("nottop"), "ERROR", MessageBox.ERROR);//选中对象不是BOM顶层请重新选择
return null;
}
TCComponentBOMLine bom = (TCComponentBOMLine) target;
if(bom.parent() != null) {
MessageBox.post(desktop, PlmLocale.getString("nottop"), "ERROR", MessageBox.ERROR);//选中对象不是BOM顶层请重新选择
return null;
}
String[] options = session.getPreferenceService().getStringValues("KWC_ReportTemplate_XYBOX");
if(options == null || options.length < 2) {
MessageBox.post(desktop, "KWC_ReportTemplate_XYBOX" + PlmLocale.getString("preferr"), "ERROR", MessageBox.ERROR);
return null;
}
// new XYBOMDialog(session, targets);
} catch(Exception e) {
e.printStackTrace();
MessageBox.post(desktop, PlmLocale.getString("err") + e.getMessage(), "ERROR", MessageBox.ERROR);
}
return null;
}
}

@ -0,0 +1,29 @@
package com.connor.cust.box;
import com.teamcenter.rac.util.Registry;
/**
* :
* :2019-02-26
* @author
*
*
* 2019-01-24 XXXX
*/
public class PlmLocale {
public static final Registry reg = Registry.getRegistry(PlmLocale.class);
public static String getString(String title) {
if (isEmpty(title)) {
return "";
} else {
String res = reg.getString(title);
return isEmpty(res) ? title : res;
}
}
private static boolean isEmpty(String title) {
return title == null || "".equals(title.trim());
}
}

@ -0,0 +1,105 @@
package com.connor.cust.box;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import com.connor.cust.util.TCUtil;
import com.teamcenter.rac.aif.AbstractAIFDialog;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.kernel.TCComponentBOMLine;
import com.teamcenter.rac.kernel.TCComponentListOfValues;
import com.teamcenter.rac.kernel.TCComponentListOfValuesType;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;
/**
* : BOM
* :2024-01-04
* @author
*
*
* 2019-01-24 XXXX
*/
public class XYBOMDialog extends AbstractAIFDialog {
private static final long serialVersionUID = 1L;
// private TCSession session;
private JButton cancelBtn;
private JButton okBtn;
private JComboBox<String> box;
public XYBOMDialog(TCSession session, InterfaceAIFComponent[] targets) throws Exception {
super(AIFUtility.getActiveDesktop());
// this.session = session;
setTitle(PlmLocale.getString("setbox"));
// JLabel label1 = new JLabel("资源名称");
// add(label1);
// label1.setBounds(20, 20, 90, 23);
box = new JComboBox<>();
box.setEditable(true);
box.addItem("");
TCComponentListOfValuesType lovType = (TCComponentListOfValuesType)session.getTypeComponent("ListOfValues");
TCComponentListOfValues[] lovs = lovType.find("KWC6_DTLOV_ZXBOX");
if(lovs.length > 0) {
for(String s : TCUtil.getDynamicLOV(session, lovs[0])) {
box.addItem(s);
}
}
add(box);
box.setBounds(30, 20, 200, 23);
okBtn = new JButton(PlmLocale.getString("ok"));
add(okBtn);
okBtn.setBounds(30, 100, 80, 23);
cancelBtn = new JButton(PlmLocale.getString("cel"));
add(cancelBtn);
cancelBtn.setBounds(150, 100, 80, 23);
add(new JLabel(""));
addActionListener(session, targets);
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(TCSession session, InterfaceAIFComponent[] targets) {
okBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
String value = box.getSelectedItem().toString();
TCUtil.setByPass(session, true);
for(InterfaceAIFComponent t : targets) {
((TCComponentBOMLine)t).setProperty("XYBOX", value);
}
MessageBox.post(XYBOMDialog.this, PlmLocale.getString("boxfinish"), "INFO", MessageBox.INFORMATION);//装箱单设置完成!
} catch (Exception e1) {
e1.printStackTrace();
MessageBox.post(XYBOMDialog.this, PlmLocale.getString("err") + e1.getMessage(), "ERROR", MessageBox.ERROR);
}finally {
try {
TCUtil.setByPass(session, false);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
});
cancelBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
}
}

@ -0,0 +1,46 @@
package com.connor.cust.box;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
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.TCSession;
import com.teamcenter.rac.util.MessageBox;
/**
* : BOM
* :2024-01-04
* @author
*
*
* 2019-01-24 XXXX
*/
public class XYBOMHandler extends AbstractHandler{
@Override
public Object execute(ExecutionEvent arg0) throws ExecutionException {
System.out.println("XYBOMHandler");
AIFDesktop desktop = AIFUtility.getActiveDesktop();
try {
AbstractAIFUIApplication app = AIFUtility.getCurrentApplication();
TCSession session = (TCSession) app.getSession();
InterfaceAIFComponent[] targets = app.getTargetComponents();
for(InterfaceAIFComponent t : targets) {
if(!(t instanceof TCComponentBOMLine)) {
MessageBox.post(desktop, t + PlmLocale.getString("notbom"), "ERROR", MessageBox.ERROR);// 不是BOM行请重新选择
return null;
}
}
new XYBOMDialog(session, targets);
} catch(Exception e) {
e.printStackTrace();
MessageBox.post(desktop, PlmLocale.getString("err") + e.getMessage(), "ERROR", MessageBox.ERROR);
}
return null;
}
}

@ -0,0 +1,8 @@
preferr=preferences error!
#XYBOM
ok=ok
err=Error:
cel=cancel
notbom= is not BOMLine!
setbox=Set Box
boxfinish=Box set finished!

@ -0,0 +1,10 @@
preferr=\u9996\u9009\u9879\u914D\u7F6E\u4E0D\u6B63\u786E
#XYBOM
ok=\u786E\u5B9A
err=\u9519\u8BEF\uFF1A
cel=\u53D6\u6D88
notbom= \u4E0D\u662FBOM\u884C\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\uFF01
setbox=\u8BBE\u7F6E\u88C5\u7BB1\u5355
boxfinish=\u88C5\u7BB1\u5355\u8BBE\u7F6E\u5B8C\u6210\uFF01
#BoxReport
nottop=\u9009\u4E2D\u5BF9\u8C61\u4E0D\u662FBOM\u9876\u5C42\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\uFF01

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

@ -0,0 +1,490 @@
package com.connor.cust.util;
import java.awt.Frame;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Vector;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JTable;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
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.TCException;
import com.teamcenter.rac.kernel.TCQueryClause;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;
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 TCUtil {
public static final int MINWIDTH = 1280;
public static final int MINHEIGHT = 768;
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 TCComponentBOMLine getBOMLine(TCSession session,TCComponentBOMWindow window, TCComponentItemRevision revision)
throws Exception {
TCComponentBOMLine bomLine = window.setWindowTopLine(null, revision, null, null);
window.save();
return bomLine;
}
public static TCComponentPseudoFolder getPseudoFolder(TCComponent parent, String relation) throws Exception {
TCComponentPseudoFolder pseudoFolder = null;
AIFComponentContext[] comps = parent.getChildren();
if (comps != null && comps.length > 0 && comps[0] != null) {
for (int i = 0; i < comps.length; i++) {
TCComponent comp = (TCComponent) comps[i].getComponent();
if (comp instanceof TCComponentPseudoFolder) {
if (comp.isTypeOf("PseudoFolder")) {
// System.out.println("PseudoFolder type:" + comp.getDefaultPasteRelation());
if (comp.getDefaultPasteRelation().equalsIgnoreCase(relation)) {
pseudoFolder = (TCComponentPseudoFolder) comp;
break;
}
}
}
}
}
return pseudoFolder;
}
public static TCComponentForm getItemRevisionMasterForm(TCComponentItemRevision revision) throws Exception {
if (revision != null) {
AIFComponentContext[] contexts = revision.getChildren("IMAN_master_form_rev");
if (contexts != null && contexts.length > 0) {
InterfaceAIFComponent component = contexts[0].getComponent();
if (component instanceof TCComponentForm) {
return (TCComponentForm) component;
}
}
}
return null;
}
public static LinkedHashMap<String, String> getlovValues(TCSession session, String lovName) throws TCException {
LinkedHashMap<String, String> lovVal = new LinkedHashMap<String, String>();
TCComponentListOfValuesType lovType = (TCComponentListOfValuesType) session.getTypeComponent("ListOfValues");
TCComponentListOfValues[] lovs = lovType.find(lovName);
if (lovs != null && lovs.length > 0) {
TCComponentListOfValues lov = lovs[0];
ListOfValuesInfo lovInfo = lov.getListOfValues();
String[] code = lovInfo.getStringListOfValues();
String[] name = lovInfo.getLOVDisplayValues();
if (code != null && name != null) {
for (int i = 0; i < code.length; i++) {
// System.out.printf("code[%d]=%s name[%d]=%s \n", i, code[i], i, name[i]);
lovVal.put(code[i], name[i]);
}
}
return lovVal;
}
return null;
}
public static String getTableValue(JTable table, int row, int col){
Object val = table.getValueAt(row, col);
if(val==null)
return "";
else
return val.toString();
}
/**
*
* @param session TCSession
* @param queryName
* @param aKey
* @param aVal
* @return
*/
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();
}
/**
*
* @param session TCSession
* @param queryName
* @param Keys
* @param Vals
* @return
*/
public static TCComponent[] query(TCSession session, String queryName, Vector<String> Keys, Vector<String> Vals) throws Exception {
TCComponentQueryType imanQueryType = (TCComponentQueryType) session.getTypeComponent("ImanQuery");
TCComponentQuery imancomponentquery = (TCComponentQuery) imanQueryType.find(queryName);
if (imancomponentquery == null) {
System.out.println("未找到查询构建器" + queryName);
throw new Exception("Query:"+queryName+" cannot find");
}
TCQueryClause[] qc = imancomponentquery.describe();
// Map<String, String> clauseMap = new HashMap<>();
for(TCQueryClause c : qc) {
String key = c.getUserEntryNameDisplay();
String value = c.getDefaultValue();
// System.out.println(key + "==>" + c.getAttributeName());
if(!value.trim().isEmpty() && !Keys.contains(key)) {
if(key.isEmpty())
Keys.add(c.getAttributeName());
else
Keys.add(key);
Vals.add(value);
}
}
int size = Keys.size();
String[] keyA = new String[size];
String[] valueA = new String[size];
for(int i=0; i<size; i++) {
keyA[i] = Keys.get(i);
valueA[i] = Vals.get(i);
System.out.println(keyA[i] + ":" + valueA[i]);
}
TCComponentContextList componentContextList = imancomponentquery.getExecuteResultsList(keyA, valueA);
return componentContextList.toTCComponentArray();
}
public static String getSerialNo(TCSession session, String itemId, String objectType) throws Exception {
TCComponent[] comps = null;
if (objectType.equals("")) {
comps = query(session, "零组件 ID", new String[] { "ItemID" }, new String[] { itemId + "*" });
} else {
comps = query(session, "零组件...", new String[] { "ItemID", "Type" }, new String[] { itemId + "*", objectType });
}
// System.out.println("getSerialNo comps.len:" + (comps == null ? 0 : comps.length));
if (comps.length > 0) {
Integer maxId = 0;
for (TCComponent comp : comps) {
String pid = comp.getProperty("item_id");
System.out.println("pid:" + pid);
String pidSuffix = pid.substring(pid.length() - 3);
if (Integer.parseInt(pidSuffix) > maxId) {
maxId = Integer.parseInt(pidSuffix);
}
}
return String.format("%03d", maxId + 1);
}
return "001";
}
/**
* Excel
* @return Excel
*/
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));
Frame frame = new Frame();
int returnVal = chooser.showSaveDialog(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;
}
/**
* Excel
* @param defaultFile
* @return Excel
*/
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;
}
/**
* Excel
* @param defaultFile
* @return Excel
*/
public static File saveExcelChooser(JDialog parent) {
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(parent);
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 boolean contains(Object[] array, Object str) {
for(Object s : array) {
// System.out.println("contains:"+s+"="+str);
if(s.equals(str))
return true;
}
return false;
}
public static Map<String, String> executeToMap(InputStream in){
System.out.println("Read properties file");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
String line = null;
Map<String, String> resultMap = new LinkedHashMap<>(16);
if (reader.ready()) {
while (null != (line = reader.readLine())) {
if (line.length() <= 0 || line.startsWith("#") || !line.contains("=")) {
continue;
}
resultMap.put(line.substring(0, line.indexOf("=")), line.substring(line.indexOf("=") + 1));
}
}
in.close();
reader.close();
return resultMap;
} catch (Exception e) {
e.printStackTrace();
MessageBox.post("Find properties file failed", "ERROR", MessageBox.ERROR);
}
return null;
}
public static TCComponentDataset createExcelDataset(TCSession session, File file, String datasetName) throws Exception {
String refType = null, objType = null, fileName = null;
fileName = file.getName().toLowerCase();
if (fileName.endsWith("xls")) {
refType = "excel";
objType = "MSExcel";
} else if (fileName.endsWith("xlsx")) {
refType = "excel";
objType = "MSExcelX";
}
TCComponentDatasetType compType = (TCComponentDatasetType) session.getTypeService().getTypeComponent("Dataset");
TCComponentDataset dataset = compType.create(datasetName, "description", objType);
dataset.setFiles(new String[] { file.getAbsolutePath() }, new String[] { refType });
return dataset;
}
public static Vector<TCComponent> getChildren(TCComponent parent, String relation, String name) throws Exception {
Vector<TCComponent> result = new Vector<>();
AIFComponentContext[] children;
if(relation==null || relation.isEmpty())
children = parent.getChildren();
else
children = parent.getChildren(relation);
for(AIFComponentContext c : children) {
TCComponent comp = (TCComponent) c.getComponent();
if(comp.getProperty("object_name").equals(name))
result.add(comp);
}
return result;
}
/**
* null
* @param parent
* @param relation
* @return
*/
public static AIFComponentContext[] getChildren(TCComponent parent, String relation) throws Exception {
AIFComponentContext[] fs = parent.getChildren(relation);
if(fs==null || fs.length==0)
return new AIFComponentContext[] { };
if(fs.length>1)
return fs;
InterfaceAIFComponent fc = fs[0].getComponent();
if(fc instanceof TCComponentPseudoFolder)
return fc.getChildren();
return fs;
}
/**
* TC
* @param TCComponent
* @param property
* @return
*/
public static TCComponent[] TCsort(TCComponent[] TCComponent, String property) {
HashMap<TCComponent,String> map = new HashMap<>();
int count = TCComponent.length;
for(TCComponent Component : TCComponent) {
try {
map.put(Component, Component.getProperty(property));
} catch (Exception e) {
e.printStackTrace();
}
}
// 通过ArrayList构造函数把map.entrySet()转换成list
ArrayList<Map.Entry<TCComponent, String>> list = new ArrayList<Map.Entry<TCComponent, String>>(map.entrySet());
// 通过比较器实现比较排序
Collections.sort(list, new Comparator<Map.Entry<TCComponent, String>>() {
public int compare(Map.Entry<TCComponent, String> mapping1, Map.Entry<TCComponent, String> mapping2) {
return mapping1.getValue().compareTo(mapping2.getValue());
}
});
TCComponent = new TCComponent[count];
int i=0;
for(Map.Entry<TCComponent, String> mapping : list) {
TCComponent[i] = mapping.getKey();
i++;
}
return TCComponent;
}
public static String getStackTrace(Exception e) {
e.printStackTrace();
StringBuilder rError = new StringBuilder(""+e.getMessage());
for(StackTraceElement ste : e.getStackTrace()) {
rError.append("\n\t"+ste.toString());
}
// System.out.println(rError.toString());
return rError.toString();
}
/**
* Excel
* @param sheet sheet
* @param i
* @return Excel
*/
public static XSSFRow getRow(XSSFSheet sheet, int i) throws Exception {
XSSFRow row = sheet.getRow(i);
if(row==null)
row = sheet.createRow(i);
return row;
}
/**
* Excel
* @param row
* @param i
* @return Excel
*/
public static XSSFCell getCell(XSSFRow row, int col) throws Exception {
XSSFCell cell = row.getCell(col);
if(cell==null)
cell = row.createCell(col);
return cell;
}
/**
*
* @param session TCSession
* @param open truefalse
*/
@SuppressWarnings("deprecation")
public static void setByPass(TCSession session, boolean open) throws Exception {
session.getUserService().call("setbypass", new Object[] { open ? "true" : "false" });
}
/**
* LOV
* @param session TCSession
* @param lov LOV
* @return LOV
*/
public static String[] getDynamicLOV(TCSession session, TCComponentListOfValues lov) throws Exception {
Vector<String> lovDisplayValueList = new Vector<>();
// lovDisplayValueList.add("");
Vector<String> 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<String, String[]> map = row.propDisplayValues;
Map<String, String[]> 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()]);
}
}
Loading…
Cancel
Save