diff --git a/.classpath b/.classpath index eca7bdb..bd4f707 100644 --- a/.classpath +++ b/.classpath @@ -3,5 +3,16 @@ + + + + + + + + + + + diff --git a/META-INF/MANIFEST.MF b/META-INF/MANIFEST.MF index 7afe5d5..8ee8dac 100644 --- a/META-INF/MANIFEST.MF +++ b/META-INF/MANIFEST.MF @@ -3,7 +3,6 @@ Bundle-ManifestVersion: 2 Bundle-Name: Performancemanagement Bundle-SymbolicName: com.langtech.plm.performancemanagement;singleton:=true Bundle-Version: 1.0.0 -Bundle-Activator: com.langtech.plm.performancemanagement.Activator Bundle-Vendor: LANGTECH Require-Bundle: org.eclipse.ui, org.eclipse.core.runtime, @@ -15,7 +14,367 @@ Require-Bundle: org.eclipse.ui, com.teamcenter.rac.common;bundle-version="13000.1.0", com.teamcenter.rac.kernel;bundle-version="13000.1.0", com.teamcenter.rac.external;bundle-version="13000.1.0", - org.apache.poi.39;bundle-version="3.9.0" + TcSoaCoreRac;bundle-version="13000.1.0", + k.util;bundle-version="1.0.0", + com.teamcenter.rac.aif.registryeditor;bundle-version="13000.1.0" Bundle-RequiredExecutionEnvironment: JavaSE-1.8 Automatic-Module-Name: com.langtech.plm.performancemanagement -Bundle-ActivationPolicy: lazy +Bundle-ClassPath: sqlServerLib/sqljdbc4.jar, + ., + sqlServerLib/swingx-1.6.1.jar, + sqlServerLib/aspose-words-17.4.0-jdk16.jar, + poi_lib/aspose-words-17.4.0-jdk16.jar, + poi_lib/commons-collections4-4.1.jar, + poi_lib/poi-3.17.jar, + poi_lib/poi-examples-3.17.jar, + poi_lib/poi-excelant-3.17.jar, + poi_lib/poi-ooxml-3.17.jar, + poi_lib/poi-ooxml-schemas-3.17.jar, + poi_lib/poi-scratchpad-3.17.jar, + poi_lib/xmlbeans-2.6.0.jar +Export-Package: asposewobfuscated, + com.aspose.words, + com.aspose.words.net.System, + com.aspose.words.net.System.Data, + com.aspose.words.net.System.Data.Common, + com.langtech.plm.batchRename, + com.langtech.plm.calculateMaterialsAndWork, + com.langtech.plm.createProjectStruct, + com.langtech.plm.mpart, + com.langtech.plm.synchronize, + com.langtech.plm.template, + com.langtech.plm.tqsx, + com.microsoft.schemas.office.excel, + com.microsoft.schemas.office.excel.impl, + com.microsoft.schemas.office.office, + com.microsoft.schemas.office.office.impl, + com.microsoft.schemas.office.visio.x2012.main, + com.microsoft.schemas.office.visio.x2012.main.impl, + com.microsoft.schemas.office.x2006.digsig, + com.microsoft.schemas.office.x2006.digsig.impl, + com.microsoft.schemas.office.x2006.encryption, + com.microsoft.schemas.office.x2006.encryption.impl, + com.microsoft.schemas.office.x2006.keyEncryptor.certificate, + com.microsoft.schemas.office.x2006.keyEncryptor.certificate.impl, + com.microsoft.schemas.office.x2006.keyEncryptor.password, + com.microsoft.schemas.office.x2006.keyEncryptor.password.impl, + com.microsoft.schemas.vml, + com.microsoft.schemas.vml.impl, + com.microsoft.sqlserver.jdbc, + microsoft.sql, + org.apache.commons.collections4, + org.apache.commons.collections4.bag, + org.apache.commons.collections4.bidimap, + org.apache.commons.collections4.collection, + org.apache.commons.collections4.comparators, + org.apache.commons.collections4.functors, + org.apache.commons.collections4.iterators, + org.apache.commons.collections4.keyvalue, + org.apache.commons.collections4.list, + org.apache.commons.collections4.map, + org.apache.commons.collections4.multimap, + org.apache.commons.collections4.multiset, + org.apache.commons.collections4.queue, + org.apache.commons.collections4.sequence, + org.apache.commons.collections4.set, + org.apache.commons.collections4.splitmap, + org.apache.commons.collections4.trie, + org.apache.commons.collections4.trie.analyzer, + org.apache.poi, + org.apache.poi.common.usermodel, + org.apache.poi.common.usermodel.fonts, + org.apache.poi.crypt.examples, + org.apache.poi.ddf, + org.apache.poi.dev, + org.apache.poi.examples.util, + org.apache.poi.extractor, + org.apache.poi.hdgf, + org.apache.poi.hdgf.chunks, + org.apache.poi.hdgf.dev, + org.apache.poi.hdgf.exceptions, + org.apache.poi.hdgf.extractor, + org.apache.poi.hdgf.pointers, + org.apache.poi.hdgf.streams, + org.apache.poi.hemf.extractor, + org.apache.poi.hemf.hemfplus.record, + org.apache.poi.hemf.record, + org.apache.poi.hmef, + org.apache.poi.hmef.attribute, + org.apache.poi.hmef.dev, + org.apache.poi.hmef.extractor, + org.apache.poi.hpbf, + org.apache.poi.hpbf.dev, + org.apache.poi.hpbf.extractor, + org.apache.poi.hpbf.model, + org.apache.poi.hpbf.model.qcbits, + org.apache.poi.hpsf, + org.apache.poi.hpsf.examples, + org.apache.poi.hpsf.extractor, + org.apache.poi.hpsf.wellknown, + org.apache.poi.hslf.blip, + org.apache.poi.hslf.dev, + org.apache.poi.hslf.examples, + org.apache.poi.hslf.exceptions, + org.apache.poi.hslf.extractor, + org.apache.poi.hslf.model, + org.apache.poi.hslf.model.textproperties, + org.apache.poi.hslf.record, + org.apache.poi.hslf.usermodel, + org.apache.poi.hslf.util, + org.apache.poi.hsmf, + org.apache.poi.hsmf.datatypes, + org.apache.poi.hsmf.dev, + org.apache.poi.hsmf.examples, + org.apache.poi.hsmf.exceptions, + org.apache.poi.hsmf.extractor, + org.apache.poi.hsmf.parsers, + org.apache.poi.hssf, + org.apache.poi.hssf.converter, + org.apache.poi.hssf.dev, + org.apache.poi.hssf.eventmodel, + org.apache.poi.hssf.eventusermodel, + org.apache.poi.hssf.eventusermodel.dummyrecord, + org.apache.poi.hssf.eventusermodel.examples, + org.apache.poi.hssf.extractor, + org.apache.poi.hssf.model, + org.apache.poi.hssf.record, + org.apache.poi.hssf.record.aggregates, + org.apache.poi.hssf.record.cf, + org.apache.poi.hssf.record.chart, + org.apache.poi.hssf.record.common, + org.apache.poi.hssf.record.cont, + org.apache.poi.hssf.record.crypto, + org.apache.poi.hssf.record.pivottable, + org.apache.poi.hssf.usermodel, + org.apache.poi.hssf.usermodel.examples, + org.apache.poi.hssf.usermodel.helpers, + org.apache.poi.hssf.util, + org.apache.poi.hssf.view, + org.apache.poi.hssf.view.brush, + org.apache.poi.hwmf.draw, + org.apache.poi.hwmf.record, + org.apache.poi.hwmf.usermodel, + org.apache.poi.hwpf, + org.apache.poi.hwpf.converter, + org.apache.poi.hwpf.dev, + org.apache.poi.hwpf.extractor, + org.apache.poi.hwpf.model, + org.apache.poi.hwpf.model.io, + org.apache.poi.hwpf.model.types, + org.apache.poi.hwpf.sprm, + org.apache.poi.hwpf.usermodel, + org.apache.poi.openxml4j.exceptions, + org.apache.poi.openxml4j.opc, + org.apache.poi.openxml4j.opc.internal, + org.apache.poi.openxml4j.opc.internal.marshallers, + org.apache.poi.openxml4j.opc.internal.unmarshallers, + org.apache.poi.openxml4j.util, + org.apache.poi.poifs.common, + org.apache.poi.poifs.crypt, + org.apache.poi.poifs.crypt.agile, + org.apache.poi.poifs.crypt.binaryrc4, + org.apache.poi.poifs.crypt.cryptoapi, + org.apache.poi.poifs.crypt.dsig, + org.apache.poi.poifs.crypt.dsig.facets, + org.apache.poi.poifs.crypt.dsig.services, + org.apache.poi.poifs.crypt.standard, + org.apache.poi.poifs.crypt.temp, + org.apache.poi.poifs.crypt.xor, + org.apache.poi.poifs.dev, + org.apache.poi.poifs.eventfilesystem, + org.apache.poi.poifs.filesystem, + org.apache.poi.poifs.macros, + org.apache.poi.poifs.nio, + org.apache.poi.poifs.poibrowser, + org.apache.poi.poifs.property, + org.apache.poi.poifs.storage, + org.apache.poi.sl.draw, + org.apache.poi.sl.draw.binding, + org.apache.poi.sl.draw.geom, + org.apache.poi.sl.image, + org.apache.poi.sl.usermodel, + org.apache.poi.ss, + org.apache.poi.ss.examples, + org.apache.poi.ss.examples.formula, + org.apache.poi.ss.examples.html, + org.apache.poi.ss.excelant, + org.apache.poi.ss.excelant.util, + org.apache.poi.ss.extractor, + org.apache.poi.ss.format, + org.apache.poi.ss.formula, + org.apache.poi.ss.formula.atp, + org.apache.poi.ss.formula.constant, + org.apache.poi.ss.formula.eval, + org.apache.poi.ss.formula.eval.forked, + org.apache.poi.ss.formula.function, + org.apache.poi.ss.formula.functions, + org.apache.poi.ss.formula.ptg, + org.apache.poi.ss.formula.udf, + org.apache.poi.ss.usermodel, + org.apache.poi.ss.usermodel.charts, + org.apache.poi.ss.usermodel.helpers, + org.apache.poi.ss.util, + org.apache.poi.ss.util.cellwalk, + org.apache.poi.util, + org.apache.poi.wp.usermodel, + org.apache.poi.xdgf.exceptions, + org.apache.poi.xdgf.extractor, + org.apache.poi.xdgf.geom, + org.apache.poi.xdgf.usermodel, + org.apache.poi.xdgf.usermodel.section, + org.apache.poi.xdgf.usermodel.section.geometry, + org.apache.poi.xdgf.usermodel.shape, + org.apache.poi.xdgf.usermodel.shape.exceptions, + org.apache.poi.xdgf.util, + org.apache.poi.xdgf.xml, + org.apache.poi.xslf.extractor, + org.apache.poi.xslf.model, + org.apache.poi.xslf.usermodel, + org.apache.poi.xslf.usermodel.tutorial, + org.apache.poi.xslf.util, + org.apache.poi.xssf, + org.apache.poi.xssf.binary, + org.apache.poi.xssf.dev, + org.apache.poi.xssf.eventusermodel, + org.apache.poi.xssf.eventusermodel.examples, + org.apache.poi.xssf.extractor, + org.apache.poi.xssf.model, + org.apache.poi.xssf.streaming, + org.apache.poi.xssf.streaming.examples, + org.apache.poi.xssf.usermodel, + org.apache.poi.xssf.usermodel.charts, + org.apache.poi.xssf.usermodel.examples, + org.apache.poi.xssf.usermodel.extensions, + org.apache.poi.xssf.usermodel.helpers, + org.apache.poi.xssf.util, + org.apache.poi.xwpf.extractor, + org.apache.poi.xwpf.model, + org.apache.poi.xwpf.usermodel, + org.apache.poi.xwpf.usermodel.examples, + org.apache.xmlbeans, + org.apache.xmlbeans.impl.common, + org.apache.xmlbeans.impl.config, + org.apache.xmlbeans.impl.inst2xsd, + org.apache.xmlbeans.impl.inst2xsd.util, + org.apache.xmlbeans.impl.jam, + org.apache.xmlbeans.impl.jam.annotation, + org.apache.xmlbeans.impl.jam.internal, + org.apache.xmlbeans.impl.jam.internal.classrefs, + org.apache.xmlbeans.impl.jam.internal.elements, + org.apache.xmlbeans.impl.jam.internal.javadoc, + org.apache.xmlbeans.impl.jam.internal.parser, + org.apache.xmlbeans.impl.jam.internal.reflect, + org.apache.xmlbeans.impl.jam.mutable, + org.apache.xmlbeans.impl.jam.provider, + org.apache.xmlbeans.impl.jam.visitor, + org.apache.xmlbeans.impl.jam.xml, + org.apache.xmlbeans.impl.piccolo.io, + org.apache.xmlbeans.impl.piccolo.util, + org.apache.xmlbeans.impl.piccolo.xml, + org.apache.xmlbeans.impl.regex, + org.apache.xmlbeans.impl.richParser, + org.apache.xmlbeans.impl.schema, + org.apache.xmlbeans.impl.soap, + org.apache.xmlbeans.impl.store, + org.apache.xmlbeans.impl.tool, + org.apache.xmlbeans.impl.util, + org.apache.xmlbeans.impl.validator, + org.apache.xmlbeans.impl.values, + org.apache.xmlbeans.impl.xb.ltgfmt, + org.apache.xmlbeans.impl.xb.ltgfmt.impl, + org.apache.xmlbeans.impl.xb.substwsdl, + org.apache.xmlbeans.impl.xb.substwsdl.impl, + org.apache.xmlbeans.impl.xb.xmlconfig, + org.apache.xmlbeans.impl.xb.xmlconfig.impl, + org.apache.xmlbeans.impl.xb.xmlschema, + org.apache.xmlbeans.impl.xb.xmlschema.impl, + org.apache.xmlbeans.impl.xb.xsdownload, + org.apache.xmlbeans.impl.xb.xsdownload.impl, + org.apache.xmlbeans.impl.xb.xsdschema, + org.apache.xmlbeans.impl.xb.xsdschema.impl, + org.apache.xmlbeans.impl.xpathgen, + org.apache.xmlbeans.impl.xsd2inst, + org.apache.xmlbeans.soap, + org.apache.xmlbeans.xml.stream, + org.apache.xmlbeans.xml.stream.events, + org.apache.xmlbeans.xml.stream.utils, + org.etsi.uri.x01903.v13, + org.etsi.uri.x01903.v13.impl, + org.jdesktop.beans, + org.jdesktop.swingx, + org.jdesktop.swingx.action, + org.jdesktop.swingx.auth, + org.jdesktop.swingx.autocomplete, + org.jdesktop.swingx.autocomplete.workarounds, + org.jdesktop.swingx.border, + org.jdesktop.swingx.calendar, + org.jdesktop.swingx.color, + org.jdesktop.swingx.combobox, + org.jdesktop.swingx.decorator, + org.jdesktop.swingx.error, + org.jdesktop.swingx.event, + org.jdesktop.swingx.geom, + org.jdesktop.swingx.graphics, + org.jdesktop.swingx.hyperlink, + org.jdesktop.swingx.icon, + org.jdesktop.swingx.image, + org.jdesktop.swingx.multislider, + org.jdesktop.swingx.multisplitpane, + org.jdesktop.swingx.painter, + org.jdesktop.swingx.painter.effects, + org.jdesktop.swingx.plaf, + org.jdesktop.swingx.plaf.basic, + org.jdesktop.swingx.plaf.basic.core, + org.jdesktop.swingx.plaf.linux, + org.jdesktop.swingx.plaf.macosx, + org.jdesktop.swingx.plaf.metal, + org.jdesktop.swingx.plaf.misc, + org.jdesktop.swingx.plaf.motif, + org.jdesktop.swingx.plaf.nimbus, + org.jdesktop.swingx.plaf.synth, + org.jdesktop.swingx.plaf.windows, + org.jdesktop.swingx.prompt, + org.jdesktop.swingx.renderer, + org.jdesktop.swingx.rollover, + org.jdesktop.swingx.search, + org.jdesktop.swingx.sort, + org.jdesktop.swingx.table, + org.jdesktop.swingx.tips, + org.jdesktop.swingx.tree, + org.jdesktop.swingx.treetable, + org.jdesktop.swingx.util, + org.openxmlformats.schemas.drawingml.x2006.chart, + org.openxmlformats.schemas.drawingml.x2006.chart.impl, + org.openxmlformats.schemas.drawingml.x2006.main, + org.openxmlformats.schemas.drawingml.x2006.main.impl, + org.openxmlformats.schemas.drawingml.x2006.picture, + org.openxmlformats.schemas.drawingml.x2006.picture.impl, + org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing, + org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.impl, + org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing, + org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.impl, + org.openxmlformats.schemas.officeDocument.x2006.customProperties, + org.openxmlformats.schemas.officeDocument.x2006.customProperties.impl, + org.openxmlformats.schemas.officeDocument.x2006.docPropsVTypes, + org.openxmlformats.schemas.officeDocument.x2006.docPropsVTypes.impl, + org.openxmlformats.schemas.officeDocument.x2006.extendedProperties, + org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.impl, + org.openxmlformats.schemas.officeDocument.x2006.relationships, + org.openxmlformats.schemas.officeDocument.x2006.relationships.impl, + org.openxmlformats.schemas.presentationml.x2006.main, + org.openxmlformats.schemas.presentationml.x2006.main.impl, + org.openxmlformats.schemas.spreadsheetml.x2006.main, + org.openxmlformats.schemas.spreadsheetml.x2006.main.impl, + org.openxmlformats.schemas.wordprocessingml.x2006.main, + org.openxmlformats.schemas.wordprocessingml.x2006.main.impl, + org.openxmlformats.schemas.xpackage.x2006.digitalSignature, + org.openxmlformats.schemas.xpackage.x2006.digitalSignature.impl, + org.w3.x2000.x09.xmldsig, + org.w3.x2000.x09.xmldsig.impl, + repackage, + schemaorg_apache_xmlbeans.system.s8C3F193EE11A2F798ACF65489B9E6078, + schemaorg_apache_xmlbeans.system.sF1327CCA741569E70F9CA8C9AF9B44B2, + schemaorg_apache_xmlbeans.system.sXMLCONFIG, + schemaorg_apache_xmlbeans.system.sXMLLANG, + schemaorg_apache_xmlbeans.system.sXMLSCHEMA, + schemaorg_apache_xmlbeans.system.sXMLTOOLS diff --git a/README.md b/README.md index 55091bd..69ccaa4 100644 --- a/README.md +++ b/README.md @@ -2,10 +2,131 @@ # 操作触发 -选中项目文件夹,点击“绩效报表”菜单,输出改项目的绩效报表(Excel) +选中项目文件夹,点击“绩效报表”菜单,输出该项目的绩效报表(Excel) # 首选项配置 ## ld_billboards_uid -单值:报表模板的puid \ No newline at end of file +```text +单值:报表模板的puid +``` + + + +## ld_postCoefficient + +```text +多值,描述岗位组对应的岗位系数,形式: +岗位组=岗位系数 +绘图组=1 +三维组=1.05 + +``` + + + +## ld_taskNature + +``` +多值,描述任务性质对应的任务系数,形式: +任务性质=任务系数 +全新=10 +可复制修改=5 +临时=2.5 +EC=2.5 + +``` + + + +## ld_taskDifficulty + +``` +多值,描述任务难度对应的难度系数,形式: +任务难度=难度系数 +子项目=0.1 +简单=1 +一般=1.25 +较难=1.5 +很难=2 +``` + + + +## ld_urgency + +``` +多值,描述紧急度对应的紧急系数,形式: +紧急度=紧急系数 +一般=1 +紧急=1.25 +超紧急=1.5 + +``` + + + +## ld_overtime + +``` +多值,超时扣分配置,形式: +严重程度:天数区间:扣分比例,其中"()"代表开区间,"[]"代表闭区间 +如: +一般:(0,1]:0.2 +严重:(1,2]:0.33 +超严重:(2,3]:0.5 +未定义:(3,1000):0.6 +``` + + + +## ld_processReview + +``` +多值,描述流程信息配置,用户获取特定流程节点的分派人和处理人,形式: +新品任务项名称=流程名称:审核节点名称 +铸件资料=001铸件资料流程:铸件资料审核 +``` + + + +## ld_requestTime + +``` +多值,描述任务要求完成时间对应的公式,形式: +新品任务项名称=公式,E和F必须放在运算符前面,例如 +铸件资料=E-10 +PPAP文件=F+1 +其中,E代表流程发起时间,F代表工艺程序结束时间(数据库表维护) + +``` + + + +## ld_sqlserver + +``` +多值,描述sqlserver数据库连接信息 +第一行:数据库用户名 +第二行:数据库密码 +第三行:登录url +第四行:驱动 +第五行:表名 + +infodba +infodba +jdbc:microsoft:sqlserver://10.10.22.39:1433;DatabaseName=TC13 +com.microsoft.jdbc.sqlserver.SQLServerDriver +TASK_REQUIREMENT +``` + + + +## Connor_JXFolder + +``` +多值,描述现有的项目归档文件夹与绩效管理要求的任务包对应,形式: +任务包名称=一级文件夹名称/二级文件夹名称/三级文件夹名称/……. +``` + diff --git a/bin/com/langtech/plm/batchRename/BatchRenameDialog.class b/bin/com/langtech/plm/batchRename/BatchRenameDialog.class new file mode 100644 index 0000000..0801718 Binary files /dev/null and b/bin/com/langtech/plm/batchRename/BatchRenameDialog.class differ diff --git a/bin/com/langtech/plm/batchRename/BatchRenameHandler.class b/bin/com/langtech/plm/batchRename/BatchRenameHandler.class new file mode 100644 index 0000000..f173a17 Binary files /dev/null and b/bin/com/langtech/plm/batchRename/BatchRenameHandler.class differ diff --git a/bin/com/langtech/plm/calculateMaterialsAndWork/CalculateDialog.class b/bin/com/langtech/plm/calculateMaterialsAndWork/CalculateDialog.class new file mode 100644 index 0000000..c60a8be Binary files /dev/null and b/bin/com/langtech/plm/calculateMaterialsAndWork/CalculateDialog.class differ diff --git a/bin/com/langtech/plm/calculateMaterialsAndWork/CalculateHandler.class b/bin/com/langtech/plm/calculateMaterialsAndWork/CalculateHandler.class new file mode 100644 index 0000000..27f135f Binary files /dev/null and b/bin/com/langtech/plm/calculateMaterialsAndWork/CalculateHandler.class differ diff --git a/bin/com/langtech/plm/calculateMaterialsAndWork/TestHandler.class b/bin/com/langtech/plm/calculateMaterialsAndWork/TestHandler.class new file mode 100644 index 0000000..d60b895 Binary files /dev/null and b/bin/com/langtech/plm/calculateMaterialsAndWork/TestHandler.class differ diff --git a/bin/com/langtech/plm/createProjectStruct/CheckBoxTreeCellRenderer.class b/bin/com/langtech/plm/createProjectStruct/CheckBoxTreeCellRenderer.class new file mode 100644 index 0000000..11015a3 Binary files /dev/null and b/bin/com/langtech/plm/createProjectStruct/CheckBoxTreeCellRenderer.class differ diff --git a/bin/com/langtech/plm/createProjectStruct/CheckBoxTreeLabel.class b/bin/com/langtech/plm/createProjectStruct/CheckBoxTreeLabel.class new file mode 100644 index 0000000..42a1b26 Binary files /dev/null and b/bin/com/langtech/plm/createProjectStruct/CheckBoxTreeLabel.class differ diff --git a/bin/com/langtech/plm/createProjectStruct/CheckBoxTreeNode.class b/bin/com/langtech/plm/createProjectStruct/CheckBoxTreeNode.class new file mode 100644 index 0000000..032f306 Binary files /dev/null and b/bin/com/langtech/plm/createProjectStruct/CheckBoxTreeNode.class differ diff --git a/bin/com/langtech/plm/createProjectStruct/CheckBoxTreeNodeSelectionListener.class b/bin/com/langtech/plm/createProjectStruct/CheckBoxTreeNodeSelectionListener.class new file mode 100644 index 0000000..3201eaa Binary files /dev/null and b/bin/com/langtech/plm/createProjectStruct/CheckBoxTreeNodeSelectionListener.class differ diff --git a/bin/com/langtech/plm/createProjectStruct/CreateProjectStructDialog.class b/bin/com/langtech/plm/createProjectStruct/CreateProjectStructDialog.class new file mode 100644 index 0000000..0c1287a Binary files /dev/null and b/bin/com/langtech/plm/createProjectStruct/CreateProjectStructDialog.class differ diff --git a/bin/com/langtech/plm/createProjectStruct/CreateProjectStructHandler.class b/bin/com/langtech/plm/createProjectStruct/CreateProjectStructHandler.class new file mode 100644 index 0000000..a774ccc Binary files /dev/null and b/bin/com/langtech/plm/createProjectStruct/CreateProjectStructHandler.class differ diff --git a/bin/com/langtech/plm/createProjectStruct/KUtil.class b/bin/com/langtech/plm/createProjectStruct/KUtil.class new file mode 100644 index 0000000..08611d5 Binary files /dev/null and b/bin/com/langtech/plm/createProjectStruct/KUtil.class differ diff --git a/bin/com/langtech/plm/mpart/CheckHeaderCellRenderer$1.class b/bin/com/langtech/plm/mpart/CheckHeaderCellRenderer$1.class new file mode 100644 index 0000000..e5d7db3 Binary files /dev/null and b/bin/com/langtech/plm/mpart/CheckHeaderCellRenderer$1.class differ diff --git a/bin/com/langtech/plm/mpart/CheckHeaderCellRenderer.class b/bin/com/langtech/plm/mpart/CheckHeaderCellRenderer.class new file mode 100644 index 0000000..97ffa78 Binary files /dev/null and b/bin/com/langtech/plm/mpart/CheckHeaderCellRenderer.class differ diff --git a/bin/com/langtech/plm/mpart/ChoosePartDialog.class b/bin/com/langtech/plm/mpart/ChoosePartDialog.class new file mode 100644 index 0000000..17b3d3d Binary files /dev/null and b/bin/com/langtech/plm/mpart/ChoosePartDialog.class differ diff --git a/bin/com/langtech/plm/mpart/DialogFrame$1.class b/bin/com/langtech/plm/mpart/DialogFrame$1.class new file mode 100644 index 0000000..6d112cf Binary files /dev/null and b/bin/com/langtech/plm/mpart/DialogFrame$1.class differ diff --git a/bin/com/langtech/plm/mpart/DialogFrame.class b/bin/com/langtech/plm/mpart/DialogFrame.class new file mode 100644 index 0000000..2e14d07 Binary files /dev/null and b/bin/com/langtech/plm/mpart/DialogFrame.class differ diff --git a/bin/com/langtech/plm/mpart/MainFrame$1$1.class b/bin/com/langtech/plm/mpart/MainFrame$1$1.class new file mode 100644 index 0000000..f73af31 Binary files /dev/null and b/bin/com/langtech/plm/mpart/MainFrame$1$1.class differ diff --git a/bin/com/langtech/plm/mpart/MainFrame$1.class b/bin/com/langtech/plm/mpart/MainFrame$1.class new file mode 100644 index 0000000..769e77a Binary files /dev/null and b/bin/com/langtech/plm/mpart/MainFrame$1.class differ diff --git a/bin/com/langtech/plm/mpart/MainFrame.class b/bin/com/langtech/plm/mpart/MainFrame.class new file mode 100644 index 0000000..b7ff4a6 Binary files /dev/null and b/bin/com/langtech/plm/mpart/MainFrame.class differ diff --git a/bin/com/langtech/plm/mpart/MpartDialog.class b/bin/com/langtech/plm/mpart/MpartDialog.class new file mode 100644 index 0000000..3aa140b Binary files /dev/null and b/bin/com/langtech/plm/mpart/MpartDialog.class differ diff --git a/bin/com/langtech/plm/mpart/MpartHandler.class b/bin/com/langtech/plm/mpart/MpartHandler.class new file mode 100644 index 0000000..da082d3 Binary files /dev/null and b/bin/com/langtech/plm/mpart/MpartHandler.class differ diff --git a/bin/com/langtech/plm/mpart/TableCellCheckboxRenderer.class b/bin/com/langtech/plm/mpart/TableCellCheckboxRenderer.class new file mode 100644 index 0000000..fed8a59 Binary files /dev/null and b/bin/com/langtech/plm/mpart/TableCellCheckboxRenderer.class differ diff --git a/bin/com/langtech/plm/performancemanagement/handlers/TaskFolderMatchingHandler.class b/bin/com/langtech/plm/performancemanagement/handlers/TaskFolderMatchingHandler.class deleted file mode 100644 index 994f3bb..0000000 Binary files a/bin/com/langtech/plm/performancemanagement/handlers/TaskFolderMatchingHandler.class and /dev/null differ diff --git a/bin/com/langtech/plm/synchronize/SynchronizeDialog.class b/bin/com/langtech/plm/synchronize/SynchronizeDialog.class new file mode 100644 index 0000000..fd33758 Binary files /dev/null and b/bin/com/langtech/plm/synchronize/SynchronizeDialog.class differ diff --git a/bin/com/langtech/plm/synchronize/SynchronizeHandler.class b/bin/com/langtech/plm/synchronize/SynchronizeHandler.class new file mode 100644 index 0000000..3f37cea Binary files /dev/null and b/bin/com/langtech/plm/synchronize/SynchronizeHandler.class differ diff --git a/bin/com/langtech/plm/template/TemplateDialog.class b/bin/com/langtech/plm/template/TemplateDialog.class new file mode 100644 index 0000000..56a59b2 Binary files /dev/null and b/bin/com/langtech/plm/template/TemplateDialog.class differ diff --git a/bin/com/langtech/plm/template/TemplateHandler.class b/bin/com/langtech/plm/template/TemplateHandler.class new file mode 100644 index 0000000..d920417 Binary files /dev/null and b/bin/com/langtech/plm/template/TemplateHandler.class differ diff --git a/bin/com/langtech/plm/performancemanagement/Activator.class b/bin/com/langtech/plm/tqsx/Activator.class similarity index 62% rename from bin/com/langtech/plm/performancemanagement/Activator.class rename to bin/com/langtech/plm/tqsx/Activator.class index ea46575..e3dd115 100644 Binary files a/bin/com/langtech/plm/performancemanagement/Activator.class and b/bin/com/langtech/plm/tqsx/Activator.class differ diff --git a/bin/com/langtech/plm/tqsx/DateUtil$FormatEnum.class b/bin/com/langtech/plm/tqsx/DateUtil$FormatEnum.class new file mode 100644 index 0000000..571f34a Binary files /dev/null and b/bin/com/langtech/plm/tqsx/DateUtil$FormatEnum.class differ diff --git a/bin/com/langtech/plm/tqsx/DateUtil.class b/bin/com/langtech/plm/tqsx/DateUtil.class new file mode 100644 index 0000000..3488e5c Binary files /dev/null and b/bin/com/langtech/plm/tqsx/DateUtil.class differ diff --git a/bin/com/langtech/plm/tqsx/KAction.class b/bin/com/langtech/plm/tqsx/KAction.class new file mode 100644 index 0000000..f90e8a4 Binary files /dev/null and b/bin/com/langtech/plm/tqsx/KAction.class differ diff --git a/bin/com/langtech/plm/tqsx/KCommand.class b/bin/com/langtech/plm/tqsx/KCommand.class new file mode 100644 index 0000000..c00583f Binary files /dev/null and b/bin/com/langtech/plm/tqsx/KCommand.class differ diff --git a/bin/com/langtech/plm/tqsx/KHandler.class b/bin/com/langtech/plm/tqsx/KHandler.class new file mode 100644 index 0000000..e69ea32 Binary files /dev/null and b/bin/com/langtech/plm/tqsx/KHandler.class differ diff --git a/bin/com/langtech/plm/tqsx/KLocale.class b/bin/com/langtech/plm/tqsx/KLocale.class new file mode 100644 index 0000000..c29816e Binary files /dev/null and b/bin/com/langtech/plm/tqsx/KLocale.class differ diff --git a/bin/com/langtech/plm/tqsx/KOperation.class b/bin/com/langtech/plm/tqsx/KOperation.class new file mode 100644 index 0000000..437ce7b Binary files /dev/null and b/bin/com/langtech/plm/tqsx/KOperation.class differ diff --git a/bin/com/langtech/plm/tqsx/KOperation2.class b/bin/com/langtech/plm/tqsx/KOperation2.class new file mode 100644 index 0000000..9cc7b67 Binary files /dev/null and b/bin/com/langtech/plm/tqsx/KOperation2.class differ diff --git a/bin/com/langtech/plm/tqsx/KUtil.class b/bin/com/langtech/plm/tqsx/KUtil.class new file mode 100644 index 0000000..120611c Binary files /dev/null and b/bin/com/langtech/plm/tqsx/KUtil.class differ diff --git a/bin/com/langtech/plm/tqsx/PropertyToWordOrExcelCommand.class b/bin/com/langtech/plm/tqsx/PropertyToWordOrExcelCommand.class new file mode 100644 index 0000000..60eb1d9 Binary files /dev/null and b/bin/com/langtech/plm/tqsx/PropertyToWordOrExcelCommand.class differ diff --git a/bin/com/langtech/plm/tqsx/PropertyToWordOrExcelOperation.class b/bin/com/langtech/plm/tqsx/PropertyToWordOrExcelOperation.class new file mode 100644 index 0000000..7b9a8d7 Binary files /dev/null and b/bin/com/langtech/plm/tqsx/PropertyToWordOrExcelOperation.class differ diff --git a/bin/com/langtech/plm/tqsx/WordUtils.class b/bin/com/langtech/plm/tqsx/WordUtils.class new file mode 100644 index 0000000..b83e640 Binary files /dev/null and b/bin/com/langtech/plm/tqsx/WordUtils.class differ diff --git a/bin/com/teamcenter/rac/stylesheet/stylesheet_user.properties b/bin/com/teamcenter/rac/stylesheet/stylesheet_user.properties new file mode 100644 index 0000000..93ef268 --- /dev/null +++ b/bin/com/teamcenter/rac/stylesheet/stylesheet_user.properties @@ -0,0 +1 @@ +LD6_NewProdForm.FORMJAVARENDERING=com.langtech.plm.form.LD6_NewProdForm \ No newline at end of file diff --git a/build.properties b/build.properties index 0d3d3a7..2dc014c 100644 --- a/build.properties +++ b/build.properties @@ -3,4 +3,16 @@ output.. = bin/ bin.includes = plugin.xml,\ META-INF/,\ .,\ - icons/ + icons/,\ + sqlServerLib/sqljdbc4.jar,\ + sqlServerLib/swingx-1.6.1.jar,\ + sqlServerLib/aspose-words-17.4.0-jdk16.jar,\ + poi_lib/aspose-words-17.4.0-jdk16.jar,\ + poi_lib/commons-collections4-4.1.jar,\ + poi_lib/poi-3.17.jar,\ + poi_lib/poi-examples-3.17.jar,\ + poi_lib/poi-excelant-3.17.jar,\ + poi_lib/poi-ooxml-3.17.jar,\ + poi_lib/poi-ooxml-schemas-3.17.jar,\ + poi_lib/poi-scratchpad-3.17.jar,\ + poi_lib/xmlbeans-2.6.0.jar diff --git a/plugin.xml b/plugin.xml index 5a25493..90fd3ac 100644 --- a/plugin.xml +++ b/plugin.xml @@ -8,27 +8,78 @@ id="com.langtech.plm.performancemanagement.commands.category" name="Sample Category"> + + categoryId="com.langtech.plm.calculateMaterialsAndWork.CalculateHandler" + name="计算材料定额" + id="com.langtech.plm.calculateMaterialsAndWork.CalculateHandler"> + + + + + + + + + + + + + + + + + class="com.langtech.plm.calculateMaterialsAndWork.CalculateHandler" + commandId="com.langtech.plm.calculateMaterialsAndWork.CalculateHandler"> + + + + + + + + + + + + + - - - - @@ -36,15 +87,60 @@ locationURI="menu:org.eclipse.ui.main.menu?after=additions"> + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/poi_lib/aspose-words-17.4.0-jdk16.jar b/poi_lib/aspose-words-17.4.0-jdk16.jar new file mode 100644 index 0000000..e8bd66c Binary files /dev/null and b/poi_lib/aspose-words-17.4.0-jdk16.jar differ diff --git a/poi_lib/commons-collections4-4.1.jar b/poi_lib/commons-collections4-4.1.jar new file mode 100644 index 0000000..43a9413 Binary files /dev/null and b/poi_lib/commons-collections4-4.1.jar differ diff --git a/poi_lib/poi-3.17.jar b/poi_lib/poi-3.17.jar new file mode 100644 index 0000000..353ce76 Binary files /dev/null and b/poi_lib/poi-3.17.jar differ diff --git a/poi_lib/poi-examples-3.17.jar b/poi_lib/poi-examples-3.17.jar new file mode 100644 index 0000000..a923b04 Binary files /dev/null and b/poi_lib/poi-examples-3.17.jar differ diff --git a/poi_lib/poi-excelant-3.17.jar b/poi_lib/poi-excelant-3.17.jar new file mode 100644 index 0000000..da9f5ed Binary files /dev/null and b/poi_lib/poi-excelant-3.17.jar differ diff --git a/poi_lib/poi-ooxml-3.17.jar b/poi_lib/poi-ooxml-3.17.jar new file mode 100644 index 0000000..68086e8 Binary files /dev/null and b/poi_lib/poi-ooxml-3.17.jar differ diff --git a/poi_lib/poi-ooxml-schemas-3.17.jar b/poi_lib/poi-ooxml-schemas-3.17.jar new file mode 100644 index 0000000..2e9b3e7 Binary files /dev/null and b/poi_lib/poi-ooxml-schemas-3.17.jar differ diff --git a/poi_lib/poi-scratchpad-3.17.jar b/poi_lib/poi-scratchpad-3.17.jar new file mode 100644 index 0000000..12ba1f1 Binary files /dev/null and b/poi_lib/poi-scratchpad-3.17.jar differ diff --git a/poi_lib/xmlbeans-2.6.0.jar b/poi_lib/xmlbeans-2.6.0.jar new file mode 100644 index 0000000..d1b6627 Binary files /dev/null and b/poi_lib/xmlbeans-2.6.0.jar differ diff --git a/sqlServerLib/poi-3.7-20101029.jar b/sqlServerLib/poi-3.7-20101029.jar new file mode 100644 index 0000000..a08d953 Binary files /dev/null and b/sqlServerLib/poi-3.7-20101029.jar differ diff --git a/sqlServerLib/poi-4.1.2.jar b/sqlServerLib/poi-4.1.2.jar new file mode 100644 index 0000000..3803353 Binary files /dev/null and b/sqlServerLib/poi-4.1.2.jar differ diff --git a/sqlServerLib/poi-examples-3.7-20101029.jar b/sqlServerLib/poi-examples-3.7-20101029.jar new file mode 100644 index 0000000..914243d Binary files /dev/null and b/sqlServerLib/poi-examples-3.7-20101029.jar differ diff --git a/sqlServerLib/poi-ooxml-3.7-20101029.jar b/sqlServerLib/poi-ooxml-3.7-20101029.jar new file mode 100644 index 0000000..5f36eb4 Binary files /dev/null and b/sqlServerLib/poi-ooxml-3.7-20101029.jar differ diff --git a/sqlServerLib/poi-ooxml-schemas-3.7-20101029.jar b/sqlServerLib/poi-ooxml-schemas-3.7-20101029.jar new file mode 100644 index 0000000..82282b5 Binary files /dev/null and b/sqlServerLib/poi-ooxml-schemas-3.7-20101029.jar differ diff --git a/sqlServerLib/sqljdbc4.jar b/sqlServerLib/sqljdbc4.jar new file mode 100644 index 0000000..d6b7f6d Binary files /dev/null and b/sqlServerLib/sqljdbc4.jar differ diff --git a/sqlServerLib/swingx-1.6.1.jar b/sqlServerLib/swingx-1.6.1.jar new file mode 100644 index 0000000..b0bcc87 Binary files /dev/null and b/sqlServerLib/swingx-1.6.1.jar differ diff --git a/src/com/langtech/plm/batchRename/BatchRenameDialog.java b/src/com/langtech/plm/batchRename/BatchRenameDialog.java new file mode 100644 index 0000000..e8fc663 --- /dev/null +++ b/src/com/langtech/plm/batchRename/BatchRenameDialog.java @@ -0,0 +1,215 @@ +package com.langtech.plm.batchRename; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.Toolkit; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Map.Entry; + +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.border.EmptyBorder; +import javax.swing.table.DefaultTableModel; + +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.TCComponentForm; +import com.teamcenter.rac.kernel.TCComponentItem; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCComponentScheduleTask; +import com.teamcenter.rac.kernel.TCException; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; +import com.teamcenter.rac.util.PropertyLayout; + +public class BatchRenameDialog extends JFrame implements ActionListener { + + private TCSession session; + protected DefaultTableModel tm_part; + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + private TCComponentScheduleTask task; + private JTextField find = new JTextField(); + private JTextField replace = new JTextField(); + private JButton okButton = new JButton("ȷ"); + private JButton concelButton = new JButton("ȡ"); + + HashMap objectMap = new HashMap(); + + public BatchRenameDialog(TCSession session, TCComponentScheduleTask task) throws TCException { + // TODO Auto-generated constructor stub + this.session = session; + this.task = task; + + initUI(); + } + + private void initUI() { + // TODO Auto-generated method stub + try { + find.setPreferredSize(new Dimension(200,30)); + replace.setPreferredSize(new Dimension(200,30)); + this.setTitle("޸ʱ"); + this.setLayout(new BorderLayout()); + + JPanel topPanel = getTopPanel(); + + JPanel btnPanel = getBtnPanel(); + + this.add(topPanel, BorderLayout.NORTH); + // this.add(pane,BorderLayout.CENTER); + this.add(btnPanel, BorderLayout.SOUTH); + this.setPreferredSize(new Dimension(450, 200)); + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); // ȡĻߴ + int screenWidth = screenSize.width; // ȡĻ + int screenHeight = screenSize.height; // ȡĻ߶ + int x = (screenWidth - 450) / 2; // FrameϽx + int y = (screenHeight - 200) / 2; // FrameϽy + this.setLocation(x, y); // Frameλ + + // this.setLocationRelativeTo(null); + this.createActionEvent(); + this.pack(); + + // this.validate(); + this.setVisible(true); + +// this.setAlwaysOnTop(true); + + + } catch (Exception e) { + e.printStackTrace(); + return; + } + } + + // Ӽ + public void createActionEvent() { + + this.okButton.addActionListener(this); + this.concelButton.addActionListener(this); + } + + @Override + public void actionPerformed(ActionEvent e) { + // TODO Auto-generated method stub + + Object source = e.getSource(); + System.out.println("source==>+" + source); + if (this.okButton.equals(source)) { + String fString = find.getText(); + String rString = replace.getText(); + + if(fString.isEmpty()) { + MessageBox.post("дݣ", "ʾ ", MessageBox.INFORMATION); + return; + } + + if(rString.isEmpty()) { + MessageBox.post("д滻ݣ", "ʾ ", MessageBox.INFORMATION); + return; + } + + //ȡвݵĸ + int childrenCount = 0; + try { + childrenCount = task.getChildrenCount(); + + System.out.println("childrenCount=============="+childrenCount); + //ӸΪ0 + if(childrenCount == 0) { + MessageBox.post("ʱûӶ", "ʾ ", MessageBox.INFORMATION); + return; + } + //ȡ + AIFComponentContext[] children = task.getChildren(); + HashMap map = new HashMap(); + for (int i = 0; i < children.length; i++) { + InterfaceAIFComponent component = children[i].getComponent(); + if(component instanceof TCComponentScheduleTask) { + TCComponentScheduleTask scheduleTask = (TCComponentScheduleTask)component; + String objectName = scheduleTask.getStringProperty("object_name"); + if(objectName.contains(fString)) { + map.put(scheduleTask, objectName.replace(fString, rString)); + } + } + } + + if(map.size() == 0) { + MessageBox.post("δƥ䵽вݵĶ", "ʾ ", MessageBox.INFORMATION); + return; + } + + //޸ + for (Entry tempMap : map.entrySet()) { + TCComponentScheduleTask key = tempMap.getKey(); + String value = tempMap.getValue(); + key.setProperty("object_name", value); + } + //޸Ϣ + MessageBox.post("ɹ޸"+map.size()+"", "ʾ ", MessageBox.INFORMATION); + this.dispose(); + } catch (TCException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + + + + + + + + } else if (this.concelButton.equals(source)) { + this.dispose(); + } + + } + + private JPanel getBtnPanel() { + JPanel topPanel = new JPanel(); + topPanel.setLayout(new PropertyLayout()); + topPanel.add("1.1.center", new JLabel("")); + topPanel.add("2.1.center", new JLabel(" ")); + topPanel.add("2.2.center", okButton); + topPanel.add("2.3.center", new JLabel("")); + topPanel.add("2.4.center", concelButton); + + return topPanel; + } + + // ѯ + private JPanel getTopPanel() { + // TODO Auto-generated method stub + JPanel topPanel = new JPanel(); + topPanel.setLayout(new PropertyLayout()); + topPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); + + topPanel.add("1.1.left.center", new JLabel("")); + topPanel.add("2.1.left.center", new JLabel("")); + topPanel.add("3.1.left.center", new JLabel("")); + topPanel.add("4.1.left.center", new JLabel(" ݣ")); + topPanel.add("4.2.left.center", find); + + topPanel.add("5.1.left.center", new JLabel("")); + topPanel.add("6.1.left.center", new JLabel("")); + topPanel.add("7.1.left.center", new JLabel("")); + topPanel.add("8.1.left.center", new JLabel(" 滻ݣ")); + + topPanel.add("8.2.left.center", replace); + + return topPanel; + } + +} diff --git a/src/com/langtech/plm/batchRename/BatchRenameHandler.java b/src/com/langtech/plm/batchRename/BatchRenameHandler.java new file mode 100644 index 0000000..9827e87 --- /dev/null +++ b/src/com/langtech/plm/batchRename/BatchRenameHandler.java @@ -0,0 +1,57 @@ +package com.langtech.plm.batchRename; + +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.commands.ExecutionException; + +import com.teamcenter.rac.aif.AbstractAIFApplication; +import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCComponentSchedule; +import com.teamcenter.rac.kernel.TCComponentScheduleTask; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +public class BatchRenameHandler extends AbstractHandler{ + + + @Override + public Object execute(ExecutionEvent arg0) throws ExecutionException { + AbstractAIFApplication app = AIFUtility.getCurrentApplication(); + TCSession session = (TCSession) app.getSession(); + try { + + new Thread() { + @Override + public void run() { + InterfaceAIFComponent targetComponent = app.getTargetComponent(); + + if(targetComponent instanceof TCComponentScheduleTask) { + try { + TCComponentScheduleTask task = (TCComponentScheduleTask)targetComponent; + + new BatchRenameDialog(session,task); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else { + MessageBox.post("ʱ","ʾ",2); + return; + } + + + } + }.start(); + + } catch (Exception e) { + // TODO: handle exception + e.printStackTrace(); + } + + return null; + } + + +} diff --git a/src/com/langtech/plm/calculateMaterialsAndWork/CalculateDialog.java b/src/com/langtech/plm/calculateMaterialsAndWork/CalculateDialog.java new file mode 100644 index 0000000..f6e54e5 --- /dev/null +++ b/src/com/langtech/plm/calculateMaterialsAndWork/CalculateDialog.java @@ -0,0 +1,623 @@ +package com.langtech.plm.calculateMaterialsAndWork; + +import java.awt.BorderLayout; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.io.FileInputStream; +import java.util.HashMap; +import java.util.Map; + +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; + +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import com.teamcenter.rac.aif.AbstractAIFApplication; +import com.teamcenter.rac.aif.kernel.AIFComponentContext; +import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentBOMLine; +import com.teamcenter.rac.kernel.TCComponentBOMWindow; +import com.teamcenter.rac.kernel.TCComponentBOMWindowType; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentItem; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCComponentMEOP; +import com.teamcenter.rac.kernel.TCComponentMEOPRevision; +import com.teamcenter.rac.kernel.TCComponentTcFile; +import com.teamcenter.rac.kernel.TCException; +import com.teamcenter.rac.kernel.TCPreferenceService; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; +import com.teamcenter.rac.util.PropertyLayout; +import com.teamcenter.rac.util.UIUtilities; + +public class CalculateDialog extends JFrame implements ActionListener { + /** + * + */ + private static final long serialVersionUID = 1L; + + private AbstractAIFApplication application; + private TCComponentMEOPRevision meop; + private TCSession session; + + TCComponentItemRevision rawMaterialRevision; + + //ӡؼ + //ͼֱֽD + private JLabel zjdLabel; + private JTextField zjdTextField; + //ͼֽ + private JLabel lkcLabel; + private JTextField lkcTextField; + //жó + private JLabel qdycdLabel; + private JTextField qdycdTextField; + //ó + private JLabel cdmycdLabel; + private JTextField cdmycdTextField; + //ͷó + private JLabel jtycdLabel; + private JTextField jtycdTextField; + // + private JLabel kzljsLabel; + private JTextField kzljsTextField; + // + private JLabel ggLabel; + private JTextField ggTextField; + //ƺ + private JLabel clphLabel; + private JTextField clphTextField; + + //ؼ + //ܳ + private JLabel zcLabel; + private JTextField zcTextField; + // + private JLabel djcdLabel; + private JTextField djcdTextField; + // + private JLabel djzlLabel; + private JTextField djzlTextField; + //׼ʱ + private JLabel bzgsLabel; + private JTextField bzgsTextField; + //ʱ + private JLabel fzgsLabel; + private JTextField fzgsTextField; + + //㰴ť + private JButton calculateButton; + //ͬť + private JButton syncButton; + //ȡť + private JButton celButton; + + //ܶ + private String density; + // + private String crossSection; + //ʱ + private String auxiliaryTime; + //̶ʱ + private String fixedTime; + //иʱ + private String cuttingTime; + + + public CalculateDialog(AbstractAIFApplication application,TCComponentMEOPRevision meop) throws TCException { + this.application = application; + this.meop = meop; + this.session = (TCSession) application.getSession(); + initUI(); + getProperties(this.meop); + } + + + private JPanel getTopPanel() { + JPanel centerPanel = new JPanel(new PropertyLayout()); + centerPanel.add("1.1.left.top",this.zjdLabel); + centerPanel.add("1.2.left.top",this.zjdTextField); + centerPanel.add("2.1.left.top",this.lkcLabel); + centerPanel.add("2.2.left.top",this.lkcTextField); + centerPanel.add("3.1.left.top",this.qdycdLabel); + centerPanel.add("3.2.left.top",this.qdycdTextField); + centerPanel.add("4.1.left.top",this.cdmycdLabel); + centerPanel.add("4.2.left.top",this.cdmycdTextField); + centerPanel.add("5.1.left.top",this.jtycdLabel); + centerPanel.add("5.2.left.top",this.jtycdTextField); + centerPanel.add("6.1.left.top",this.kzljsLabel); + centerPanel.add("6.2.left.top",this.kzljsTextField); + centerPanel.add("7.1.left.top",this.ggLabel); + centerPanel.add("7.2.left.top",this.ggTextField); + centerPanel.add("8.1.left.top",this.clphLabel); + centerPanel.add("8.2.left.top",this.clphTextField); + + centerPanel.add("1.3.left.top",this.zcLabel); + centerPanel.add("1.4.left.top",this.zcTextField); + centerPanel.add("2.3.left.top",this.djcdLabel); + centerPanel.add("2.4.left.top",this.djcdTextField); + centerPanel.add("3.3.left.top",this.djzlLabel); + centerPanel.add("3.4.left.top",this.djzlTextField); + centerPanel.add("4.3.left.top",this.bzgsLabel); + centerPanel.add("4.4.left.top",this.bzgsTextField); + centerPanel.add("5.3.left.top",this.fzgsLabel); + centerPanel.add("5.4.left.top",this.fzgsTextField); + centerPanel.add("6.3.left.top",this.calculateButton); + + return centerPanel; + } + + /** + * ýĿ + */ + private void setPanelProperties() { + this.zjdLabel = new JLabel("ͼֱֽD"); + this.lkcLabel = new JLabel("ͼֽ"); + this.qdycdLabel = new JLabel("жó"); + this.cdmycdLabel = new JLabel("ó"); + this.jtycdLabel = new JLabel("ͷó"); + this.kzljsLabel = new JLabel(""); + this.ggLabel = new JLabel(""); + this.clphLabel = new JLabel("ƺ"); + this.zcLabel = new JLabel("ܳ"); + this.djcdLabel = new JLabel(""); + this.djzlLabel = new JLabel(""); + this.bzgsLabel = new JLabel("׼ʱ"); + this.fzgsLabel = new JLabel("ʱ"); + + this.zjdTextField = new JTextField(32); + this.lkcTextField = new JTextField(32); + this.qdycdTextField = new JTextField(32); + this.cdmycdTextField = new JTextField(32); + this.jtycdTextField = new JTextField(32); + this.kzljsTextField = new JTextField(32); + this.ggTextField = new JTextField(32); + this.clphTextField = new JTextField(32); + this.zcTextField = new JTextField(32); + this.djcdTextField = new JTextField(32); + this.djzlTextField = new JTextField(32); + this.bzgsTextField = new JTextField(32); + this.fzgsTextField = new JTextField(32); + + this.calculateButton = new JButton(""); + this.syncButton = new JButton("ͬ"); + this.celButton = new JButton("ȡ"); + } + + /** + * ȡײť + * @return + */ + private JPanel getButtomPanel() { + JPanel bottomPanel = new JPanel(new FlowLayout()); +// bottomPanel.add(this.calculateButton); + bottomPanel.add(this.syncButton); + bottomPanel.add(this.celButton); + + return bottomPanel; + } + + /** + * ʼͼν + */ + private void initUI() { + this.setTitle("϶ʱ"); + this.setSize(500, 500); + this.setLayout(new BorderLayout()); + + setPanelProperties(); + + JPanel centerPanel = getTopPanel(); + + JPanel bottomPanel = getButtomPanel(); + + this.add(centerPanel,BorderLayout.CENTER); + this.add(bottomPanel,BorderLayout.SOUTH); + + //¼ + this.calculateButton.addActionListener(this); + this.syncButton.addActionListener(this); + this.celButton.addActionListener(this); + + //ŵĻ + UIUtilities.centerToScreen(this); + this.setVisible(true); + + } + + /** + * ȡѡMEOPԣֵ + * @param meop + * @throws TCException + */ + private void getProperties(TCComponentMEOPRevision meop) throws TCException { + String outlineDiameter = meop.getStringProperty("ly6_outlineDiameter"); + String outlineLength = meop.getStringProperty("ly6_outlineLength"); + String cuttingLength = meop.getStringProperty("ly6_cuttingLength"); + String transverseLength = meop.getStringProperty("ly6_transverseLength"); + String colletLength = meop.getStringProperty("ly6_colletLength"); + String manufacturingQuantity =meop.getStringProperty("ly6_manufacturableQuantity"); + String specifications = meop.getStringProperty("ly6_specifications"); + String brandNum = meop.getStringProperty("ly6_brandNum"); + + this.zjdTextField.setText(outlineDiameter != null ? outlineDiameter : ""); + this.lkcTextField.setText(outlineLength != null ? outlineLength : ""); + this.qdycdTextField.setText(cuttingLength != null ? cuttingLength : ""); + this.cdmycdTextField.setText(transverseLength != null ? transverseLength : ""); + this.jtycdTextField.setText(colletLength != null ? colletLength : ""); + this.kzljsTextField.setText(manufacturingQuantity != null ? manufacturingQuantity : ""); + this.ggTextField.setText(specifications != null ? specifications : ""); + this.clphTextField.setText(brandNum != null ? brandNum : ""); + } + + + /** + * ܳ + * @return + */ + private String calculateTotalLength() { + // ȡ TextField + String lkcText = this.lkcTextField.getText(); + String qdycdText = this.qdycdTextField.getText(); + String cdmycdText = this.cdmycdTextField.getText(); + String kzljsText = this.kzljsTextField.getText(); + String jtycdText = this.jtycdTextField.getText(); + + // ַתΪֵ + double lkcValue = Double.parseDouble(lkcText); + double qdycdValue = Double.parseDouble(qdycdText); + double cdmycdValue = Double.parseDouble(cdmycdText); + double kzljsValue = Double.parseDouble(kzljsText); + double jtycdValue = Double.parseDouble(jtycdText); + + // + double result = (lkcValue + qdycdValue + cdmycdValue) * kzljsValue + jtycdValue; + System.out.println("ͼֽ"+lkcValue+"жóȣ"+qdycdValue+"óȣ"+cdmycdValue+""+kzljsValue+"ͷóȣ"+jtycdValue); + + return String.valueOf(result); + } + + /** + * 㵥 + * @return + */ + private String calculateSingleLength(){ + String zcText = this.zcTextField.getText(); + String kzljsText = this.kzljsTextField.getText(); + + double zcValue = Double.parseDouble(zcText); + double kzljsValue = Double.parseDouble(kzljsText); + if (kzljsValue == 0){ + System.out.println(" is 0"); + } + double result = zcValue / kzljsValue; + System.out.println("ܳ"+zcValue+""+kzljsValue); + return String.valueOf(result); + } + + /** + * ѡеuidȡݼEXCEL + * uidȡitem󣬻ȡöµ + * ݡֱȡEXCELвıҪĿʱͱ׼ʱ + * @throws Exception + */ + private void getDataset(){ + TCPreferenceService preferenceService = session.getPreferenceService(); + String itemId = preferenceService.getStringValue("LY6_MEOPTypeTime"); + + InterfaceAIFComponent[] resultComponents; + try { + resultComponents = session.search("...", new String[] {" ID"}, new String[] {itemId}); + + InterfaceAIFComponent component = resultComponents[0]; + if (component instanceof TCComponentItem){ + TCComponentItem item = (TCComponentItem) component; + //ȡitemѷ°汾淶ϵµMSEXCELݼ + TCComponentItemRevision[] releasedItemRevisions = item.getReleasedItemRevisions(); + int releaseRevNum = releasedItemRevisions.length; + if (releaseRevNum == 0) { + System.out.println("󣺵ǰ²ڷ汾"); + } + TCComponentItemRevision tcComponentItemRevision = releasedItemRevisions[releaseRevNum - 1]; + + //ȡǰ汾Ĺ淶ϵµݼ + TCComponent[] referenceListProperty = tcComponentItemRevision.getReferenceListProperty("IMAN_specification"); + if(referenceListProperty.length>0) { + //ȡݼ¾ļ + TCComponentTcFile[] tcFiles = ((TCComponentDataset)referenceListProperty[0]).getTcFiles(); + File file = tcFiles[0].getFmsFile(); + // ݺȡݼ-excelУӦĿݣʱ䡢̶ʱ䡢иʱ + FileInputStream fis = new FileInputStream(file); + Workbook workbook = new HSSFWorkbook(fis); + Sheet sheet = workbook.getSheetAt(0); + //ӵ3ʼ(ǰDZ) + for (int i = 2; i < sheet.getPhysicalNumberOfRows(); i++) { + Row row = sheet.getRow(i); + //ȡÿеĵһֱֵ + double diam = row.getCell(0).getNumericCellValue(); + // ݹƥݼеֱ + if (diam == Double.parseDouble(this.ggTextField.getText())){ + System.out.println("=========ֱƥɹʼȡʱͱ׼ʱ"+"=========ǰкţ"+(i+1)+"ǰеֱ"+diam); + //ȡ11еֵ׼ʱ + this.bzgsTextField.setText(row.getCell(10).getStringCellValue()); + //ȡ12еֵʱ + this.fzgsTextField.setText(row.getCell(11).getStringCellValue()); + break; + } + } + } + } + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + + } + + /** + * 㸨ʱ + * @return + */ + private String calculateAssistTime() { + String result = null; + double kzljsNum = Double.parseDouble(this.kzljsTextField.getText()); + if (kzljsNum > 0){ + double auxiliaryTimeNum = Double.parseDouble(this.auxiliaryTime); + double fixedTimeNum = Double.parseDouble(this.fixedTime); + + double resultNum = Math.round((auxiliaryTimeNum + fixedTimeNum) / kzljsNum / 60 * 100.0) / 100.0; + System.out.println("ʱ䣺"+auxiliaryTimeNum+"̶ʱ䣺"+fixedTimeNum+""+kzljsNum); + result = String.valueOf(resultNum); + + } + return result; + + } + + /** + * ׼ʱ + * @return + */ + private String calculateStandardTime() { + String result = null; + double kzljsNum = Double.parseDouble(this.kzljsTextField.getText()); + if (kzljsNum > 0){ + System.out.println("=========>ȡиʱ䣺"+this.cuttingTime); + double cuttingTimeNum = Double.parseDouble(this.cuttingTime); + + double resultNum = Math.round((cuttingTimeNum / kzljsNum / 60) * 100.0) / 100.0; + System.out.println("иʱ䣺"+cuttingTimeNum+""+kzljsNum); + result = String.valueOf(resultNum); + } + return result; + } + + /** + * ȡܶȺͽ + * @throws TCException + */ + private void getDensityAndCrossSection() throws TCException { + System.out.println("=========>ʼȡܶȺͺ棺getDensityAndCrossSection"); + +// 1.ȡǰѡMEOPBOM + TCComponentMEOP meopItem = (TCComponentMEOP) meop.getItem(); + TCComponentBOMWindowType winType = (TCComponentBOMWindowType) this.session.getTypeComponent("BOMWindow"); + TCComponentBOMWindow view = winType.create(null); + TCComponentBOMLine bomLine = view.setWindowTopLine(meopItem, meop, null, null); +// 2.BOMУݡ񡱺͡ϡҪΨһԭ϶ + throughBomline(bomLine); + + view.close(); + } + + /** + * ѭǰbomline¹УȡҪbomӦԭ϶󣬲ȡӦܶȺͺ + * @param topBomLine ǰBOM + */ + private void throughBomline(TCComponentBOMLine topBomLine) throws TCException{ + // 3.ȡԭ϶ܶȺͺ + boolean hasChildren = topBomLine.hasChildren(); + if (hasChildren) { + AIFComponentContext[] childrens = topBomLine.getChildren(); + for (AIFComponentContext children : childrens) { + TCComponentBOMLine bomLine = (TCComponentBOMLine) children.getComponent(); + //ȡǰbomͣͶϣ򵽵ǰbomӦԭ϶ + String propertyValue = bomLine.getProperty("bl_occ_type"); + if ("Ͷ".equals(propertyValue)) { + //ͨԭ϶ȡܶȺͺ + this.rawMaterialRevision = bomLine.getItemRevision(); + String densityString = rawMaterialRevision.getProperty("ly6_density"); + String crossSectionString = rawMaterialRevision.getProperty("ly6_crossSection"); + System.out.println("==========ɹȡõǰԭ϶Ӧܶȣ"+densityString+"棺"+crossSectionString); + + this.density = densityString != null ? densityString : ""; + this.crossSection = crossSectionString != null ? crossSectionString : ""; + + break; + } + throughBomline(bomLine); + } + } + + } + + + /** + * 㵥 + * @return + * @throws TCException + */ + private String calculateWeight(){ + //ͨȡǰѡжbom¹ԭ϶󣬻ȡܶȺͺ + try { + getDensityAndCrossSection(); + } catch (TCException e) { + e.printStackTrace(); + } + //ȡܶȡȣ㵥 + double crossSectionNum = Double.parseDouble(this.crossSection); + double densityNum = Double.parseDouble(this.density); + double siglengthNum = Double.parseDouble(this.djcdTextField.getText()); + + double result = crossSectionNum * densityNum * siglengthNum; + System.out.println("棺"+crossSectionNum+"ܶȣ"+densityNum+"ȣ"+siglengthNum); + return String.valueOf(result); + } + + /** + * дԵӦĶ + * @throws TCException + */ + private void saveProperty() throws TCException { + try { + meop.setProperty("ly6_specifications", this.ggTextField.getText() == null ? "" : this.ggTextField.getText()); + rawMaterialRevision.setProperty("ly6_specifications", this.ggTextField.getText() == null ? "" : this.ggTextField.getText()); + meop.setProperty("ly6_totalLenght", this.zcTextField.getText() == null ? "" : this.zcTextField.getText()); + meop.setProperty("ly6_singleLength", this.djcdTextField.getText() == null ? "" : this.djcdTextField.getText()); + meop.setProperty("ly6_weight", this.djzlTextField.getText() == null ? "" : this.djzlTextField.getText()); + meop.setProperty("ly6_standardTime", this.bzgsTextField.getText() == null ? "" : this.bzgsTextField.getText()); + meop.setProperty("ly6_auxiliaryTime", this.fzgsTextField.getText() == null ? "" : this.fzgsTextField.getText()); + rawMaterialRevision.setProperty("ly6_material", this.clphTextField.getText() == null ? "" : this.clphTextField.getText()); + meop.setProperty("ly6_brandNum", this.clphTextField.getText() == null ? "" : this.clphTextField.getText()); + meop.setProperty("ly6_outlineDiameter", this.zjdTextField.getText() == null ? "" : this.zjdTextField.getText()); + meop.setProperty("ly6_outlineLength", this.lkcTextField.getText() == null ? "" : this.lkcTextField.getText()); + meop.setProperty("ly6_cuttingLength", this.qdycdTextField.getText() == null ? "" : this.qdycdTextField.getText()); + meop.setProperty("ly6_transverseLength", this.cdmycdTextField.getText()== null ? "" : this.cdmycdTextField.getText()); + meop.setProperty("ly6_colletLength", this.jtycdTextField.getText() == null ? "" : this.jtycdTextField.getText()); + meop.setProperty("ly6_manufacturableQuantity", this.kzljsTextField.getText() == null ? "" : this.kzljsTextField.getText()); + }catch (Exception e){ + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } + + /** + * MǷѾԭ + * @throws TCException + */ + private void checkMaterial() throws TCException { + try { + System.out.println("ʼMµĹ"); + boolean isGZ=false; + TCComponent[] whereUsed = meop.whereUsed((short) 0); + for (TCComponent tcComponent : whereUsed) { + //ȡǰĸ-tcComponent + String mepRevisionType = tcComponent.getStringProperty("object_type"); + //ȡѡеĹնͣƥ + TCSession session = (TCSession) this.application.getSession(); + TCPreferenceService preferenceService = session.getPreferenceService(); + //ѡ-C8MyPreference,ȡѡֵ + String value = preferenceService.getStringValue("LY6_MEPType"); + String[] strings = value.split(","); + for (int i = 0; i < whereUsed.length; i++) { + //նƥ䣬Уԭ϶ȶ + if (strings[i].equals(mepRevisionType)) { + System.out.println("========>ƥɹ"); + if (tcComponent instanceof TCComponentItemRevision) { + System.out.println("====>ȡĹն"+tcComponent.getObjectString()); + TCComponentItemRevision mepRevision = (TCComponentItemRevision) tcComponent; + //ȡնµ/:relatedRevision\\relatedItem + TCComponent relatedComponent = mepRevision.getRelatedComponent("IMAN_METarget"); + TCComponentItemRevision relatedRevision = (TCComponentItemRevision) relatedComponent; + TCComponentItem relatedItem = relatedRevision.getItem(); + + //鵱ǰ϶Ƿԭ϶ + TCComponentBOMWindowType winType = (TCComponentBOMWindowType) session.getTypeComponent("BOMWindow"); + TCComponentBOMWindow view = winType.create(null); + //ȡ϶/Ӧbomline + TCComponentBOMLine bomLine = view.setWindowTopLine(relatedItem, relatedRevision, null, null); + //bomlineǷԭ϶ + if (bomLine.hasChildren()) { + AIFComponentContext[] childrens = bomLine.getChildren(); + for(AIFComponentContext children:childrens) { + TCComponentBOMLine childrenBomLine = (TCComponentBOMLine) children.getComponent(); + TCComponentItemRevision itemRevision = childrenBomLine.getItemRevision(); + String uidTag = itemRevision.getUid(); + String materialRevUid = this.rawMaterialRevision.getUid(); + if (uidTag.equals(materialRevUid)) { + System.out.println("M϶Ѿԭ϶󡤡"); + //M϶¹ԭ϶ + isGZ = true; + break; + } + } + } + //M϶ûйԭ϶ + if (!isGZ) { + System.out.println("M϶ûйԭ϶󣬿ʼء"); + view.lock(); + TCComponentItem materialItem = this.rawMaterialRevision.getItem(); + bomLine.add(materialItem,this.rawMaterialRevision,null,false,""); + bomLine.save(); + view.unlock(); + } + // BOMWindowرգ + view.close(); + }else { + System.out.println("ǰ汾쳣"); + } + break; + } + } + } + }catch (Exception e){ + e.printStackTrace(); + System.out.println(e.getMessage()); + } + } + + /** + * ¼ťĵ¼ + */ + @Override + public void actionPerformed(ActionEvent e) { + Object sourceObject = e.getSource(); + //㡱ť + if(sourceObject.equals(this.calculateButton)) { + try { + //ȼ + this.zcTextField.setText(calculateTotalLength()); + this.djcdTextField.setText(calculateSingleLength()); + // + this.djzlTextField.setText(calculateWeight()); + // ʱ + getDataset(); +// this.bzgsTextField.setText(calculateStandardTime()); +// this.fzgsTextField.setText(calculateAssistTime()); + }catch (Exception e1){ + MessageBox.post("ʧܣԻֶά", "ʾ", MessageBox.ERROR); + } + } else if (sourceObject.equals(this.syncButton)) { + //ͬťԷд + try { + saveProperty(); + //M + checkMaterial(); + MessageBox.post("ͬɹ", "", MessageBox.INFORMATION); + + this.setVisible(false); + this.dispose(); + } catch (TCException e1) { + e1.printStackTrace(); + } + }else { + //ȡť + //ر + this.setVisible(false); + //ͷ + this.dispose(); + } + } +} diff --git a/src/com/langtech/plm/calculateMaterialsAndWork/CalculateHandler.java b/src/com/langtech/plm/calculateMaterialsAndWork/CalculateHandler.java new file mode 100644 index 0000000..b5fd406 --- /dev/null +++ b/src/com/langtech/plm/calculateMaterialsAndWork/CalculateHandler.java @@ -0,0 +1,84 @@ +package com.langtech.plm.calculateMaterialsAndWork; + +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.commands.ExecutionException; + +import com.teamcenter.rac.aif.AbstractAIFApplication; +import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCComponentMEOP; +import com.teamcenter.rac.kernel.TCComponentMEOPRevision; +import com.teamcenter.rac.kernel.TCPreferenceService; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +import java.sql.SQLOutput; + +public class CalculateHandler extends AbstractHandler { + + @Override + public Object execute(ExecutionEvent arg0) throws ExecutionException { + AbstractAIFApplication app = AIFUtility.getCurrentApplication(); + TCSession session = (TCSession) app.getSession(); + + try { + new Thread(){ + @Override + public void run() { +// TODO 1.ȡѡжͺ͹ + //ȡѡжƴַ + InterfaceAIFComponent selectComponent = app.getTargetContext().getComponent(); +// ȡѡжͺ + String type = selectComponent.getType(); + String name; + boolean existTag = false; + + try { + name = selectComponent.getProperty("object_name"); +// 2.ȡѡַ飬Ƚϣǰѡж+ƴַ + TCPreferenceService preferenceService = session.getPreferenceService(); + //ѡ-C8MyPreference,ȡѡֵ + String[] preferenceValues = preferenceService.getStringValues("LY6_MEOPType"); + if (preferenceValues == null) { + MessageBox.post("ѡΪգѡ","ʾ",MessageBox.INFORMATION); + } + for (String string : preferenceValues){ + if (type.equals(string)){ + existTag = true; + } + } + + if (!existTag){ + //3.ѡеֵƥ䣬򵯳ʾʾͲȷ + MessageBox.post("Ͳȷ","ʾ",MessageBox.INFORMATION); + }else { + TCComponentMEOPRevision rev = null; + //жѡжitemǰ汾itemȡ°汾 + if (selectComponent instanceof TCComponentMEOP) { +// System.out.println("ǰѡжΪTCComponentMEOP"); + TCComponentMEOP meopType = (TCComponentMEOP) selectComponent; + rev = (TCComponentMEOPRevision) meopType.getLatestItemRevision(); + }else if (selectComponent instanceof TCComponentMEOPRevision) { +// System.out.println("ǰѡжΪTCComponentMEOPRevision"); + rev = (TCComponentMEOPRevision) selectComponent; + } + +// System.out.println("========ѡеĶͣ"+type); + new CalculateDialog(app,rev); + } + + } catch (Exception e) { + e.printStackTrace(); + } + } + }.start(); + } catch (Exception e) { + e.printStackTrace(); + } + + return null; + } + +} diff --git a/src/com/langtech/plm/calculateMaterialsAndWork/TestHandler.java b/src/com/langtech/plm/calculateMaterialsAndWork/TestHandler.java new file mode 100644 index 0000000..d062eb3 --- /dev/null +++ b/src/com/langtech/plm/calculateMaterialsAndWork/TestHandler.java @@ -0,0 +1,41 @@ +package com.langtech.plm.calculateMaterialsAndWork; + +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.commands.ExecutionException; + +import com.teamcenter.rac.aif.AbstractAIFApplication; +import com.teamcenter.rac.aif.kernel.AbstractAIFSession; +import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentMEOPType; +import com.teamcenter.rac.kernel.TCSession; + +public class TestHandler extends AbstractHandler { + + @Override + public Object execute(ExecutionEvent arg0) throws ExecutionException { + // TODO Auto-generated method stub + AbstractAIFApplication application = AIFUtility.getCurrentApplication(); + + TCSession session = (TCSession) application.getSession(); + //ȡѡж + InterfaceAIFComponent selectComponent = application.getTargetContext().getComponent(); + String type = selectComponent.getType(); + try { + String propertyName = selectComponent.getProperty("object_name"); + System.out.println("ѡжͣ"+type); + System.out.println("ѡж1"+propertyName); + System.out.println("ѡж2"+selectComponent.getObjectString()); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + //TCComponentMEOPType + + + return null; + } + +} diff --git a/src/com/langtech/plm/createProjectStruct/CheckBoxTreeCellRenderer.java b/src/com/langtech/plm/createProjectStruct/CheckBoxTreeCellRenderer.java new file mode 100644 index 0000000..ac0862f --- /dev/null +++ b/src/com/langtech/plm/createProjectStruct/CheckBoxTreeCellRenderer.java @@ -0,0 +1,84 @@ +package com.langtech.plm.createProjectStruct; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; + +import javax.swing.JCheckBox; +import javax.swing.JPanel; +import javax.swing.JTree; +import javax.swing.UIManager; +import javax.swing.plaf.ColorUIResource; +import javax.swing.tree.TreeCellRenderer; + +public class CheckBoxTreeCellRenderer extends JPanel implements TreeCellRenderer +{ + protected JCheckBox check; + protected CheckBoxTreeLabel label; + + public CheckBoxTreeCellRenderer() + { + setLayout(null); + add(check = new JCheckBox()); + add(label = new CheckBoxTreeLabel()); + check.setBackground(UIManager.getColor("Tree.textBackground")); + label.setForeground(UIManager.getColor("Tree.textForeground")); + } + + + @Override + public Component getTreeCellRendererComponent(JTree tree, Object value, + boolean selected, boolean expanded, boolean leaf, int row, + boolean hasFocus) + { + String stringValue = tree.convertValueToText(value, selected, expanded, leaf, row, hasFocus); + setEnabled(tree.isEnabled()); + check.setSelected(((CheckBoxTreeNode)value).isSelected()); + label.setFont(tree.getFont()); + label.setText(stringValue); + label.setSelected(selected); + label.setFocus(hasFocus); + if(leaf) + //label.setIcon(UIManager.getIcon("Tree.leafIcon")); + label.setIcon(UIManager.getIcon("Tree.openIcon")); + else if(expanded) + label.setIcon(UIManager.getIcon("Tree.openIcon")); + else + label.setIcon(UIManager.getIcon("Tree.closedIcon")); + + return this; + } + + @Override + public Dimension getPreferredSize() + { + Dimension dCheck = check.getPreferredSize(); + Dimension dLabel = label.getPreferredSize(); + return new Dimension(dCheck.width + dLabel.width, dCheck.height < dLabel.height ? dLabel.height: dCheck.height); + } + + @Override + public void doLayout() + { + Dimension dCheck = check.getPreferredSize(); + Dimension dLabel = label.getPreferredSize(); + int yCheck = 0; + int yLabel = 0; + if(dCheck.height < dLabel.height) + yCheck = (dLabel.height - dCheck.height) / 2; + else + yLabel = (dCheck.height - dLabel.height) / 2; + check.setLocation(0, yCheck); + check.setBounds(0, yCheck, dCheck.width, dCheck.height); + label.setLocation(dCheck.width, yLabel); + label.setBounds(dCheck.width, yLabel, dLabel.width, dLabel.height); + } + + @Override + public void setBackground(Color color) + { + if(color instanceof ColorUIResource) + color = null; + super.setBackground(color); + } +} \ No newline at end of file diff --git a/src/com/langtech/plm/createProjectStruct/CheckBoxTreeLabel.java b/src/com/langtech/plm/createProjectStruct/CheckBoxTreeLabel.java new file mode 100644 index 0000000..e60b2be --- /dev/null +++ b/src/com/langtech/plm/createProjectStruct/CheckBoxTreeLabel.java @@ -0,0 +1,75 @@ +package com.langtech.plm.createProjectStruct; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Graphics; + +import javax.swing.Icon; +import javax.swing.JLabel; +import javax.swing.UIManager; +import javax.swing.plaf.ColorUIResource; + +public class CheckBoxTreeLabel extends JLabel +{ + private boolean isSelected; + private boolean hasFocus; + + public CheckBoxTreeLabel() + { + } + + @Override + public void setBackground(Color color) + { + if(color instanceof ColorUIResource) + color = null; + super.setBackground(color); + } + + @Override + public void paint(Graphics g) + { + String str; + if((str = getText()) != null) + { + if(0 < str.length()) + { + if(isSelected) + g.setColor(UIManager.getColor("Tree.selectionBackground")); + else + g.setColor(UIManager.getColor("Tree.textBackground")); + Dimension d = getPreferredSize(); + int imageOffset = 0; + Icon currentIcon = getIcon(); + if(currentIcon != null) + imageOffset = currentIcon.getIconWidth() + Math.max(0, getIconTextGap() - 1); + g.fillRect(imageOffset, 0, d.width - 1 - imageOffset, d.height); + if(hasFocus) + { + g.setColor(UIManager.getColor("Tree.selectionBorderColor")); + g.drawRect(imageOffset, 0, d.width - 1 - imageOffset, d.height - 1); + } + } + } + super.paint(g); + } + + @Override + public Dimension getPreferredSize() + { + Dimension retDimension = super.getPreferredSize(); + if(retDimension != null) + retDimension = new Dimension(retDimension.width + 3, retDimension.height); + return retDimension; + } + + public void setSelected(boolean isSelected) + { + this.isSelected = isSelected; + } + + public void setFocus(boolean hasFocus) + { + this.hasFocus = hasFocus; + } +} + diff --git a/src/com/langtech/plm/createProjectStruct/CheckBoxTreeNode.java b/src/com/langtech/plm/createProjectStruct/CheckBoxTreeNode.java new file mode 100644 index 0000000..3c8d676 --- /dev/null +++ b/src/com/langtech/plm/createProjectStruct/CheckBoxTreeNode.java @@ -0,0 +1,85 @@ +package com.langtech.plm.createProjectStruct; + +import javax.swing.tree.DefaultMutableTreeNode; + +public class CheckBoxTreeNode extends DefaultMutableTreeNode { + protected boolean isSelected; + + public CheckBoxTreeNode() { + this(null); + } + + public CheckBoxTreeNode(Object userObject) { + this(userObject, true, false); + } + + public CheckBoxTreeNode(Object userObject, boolean allowsChildren, boolean isSelected) { + super(userObject, allowsChildren); + this.isSelected = isSelected; + } + + public boolean isSelected() { + return isSelected; + } + + public void setSelected(boolean _isSelected) { + this.isSelected = _isSelected; + + if (_isSelected) { + // ѡУеӽ㶼ѡ + if (children != null) { + for (Object obj : children) { + CheckBoxTreeNode node = (CheckBoxTreeNode) obj; + if (_isSelected != node.isSelected()) + node.setSelected(_isSelected); + } + } + // ϼ飬ӽ㶼ѡУôҲѡ + CheckBoxTreeNode pNode = (CheckBoxTreeNode) parent; + // ʼpNodeӽڵǷ񶼱ѡ + if (pNode != null) { + int index = 0; + for (; index < pNode.children.size(); ++index) { + CheckBoxTreeNode pChildNode = (CheckBoxTreeNode) pNode.children.get(index); + if (!pChildNode.isSelected()) + break; + } + /* + * pNodeӽ㶼ѾѡУѡи㣬 ÷һݹ鷽ڴ˲ҪеΪ ѡи󣬸㱾ϼġ + */ + if (index == pNode.children.size()) { + if (pNode.isSelected() != _isSelected) + pNode.setSelected(_isSelected); + } + } + } else { + /* + * ȡ㵼ӽȡôʱеӽ㶼Ӧѡϵģ ӽȡ¸ȡȻ󸸽ȡҪȡӽ㣬 + * ʱDzҪȡӽġ + */ + if (children != null) { + int index = 0; + for (; index < children.size(); ++index) { + CheckBoxTreeNode childNode = (CheckBoxTreeNode) children.get(index); + if (!childNode.isSelected()) + break; + } + // ȡʱ + if (index == children.size()) { + for (int i = 0; i < children.size(); ++i) { + CheckBoxTreeNode node = (CheckBoxTreeNode) children.get(i); + if (node.isSelected() != _isSelected) + node.setSelected(_isSelected); + } + } + } + + // ȡֻҪһӽڵ㲻ѡϵģôڵͲӦñѡϡ + CheckBoxTreeNode pNode = (CheckBoxTreeNode) parent; + /* + * if (pNode != null && pNode.isSelected() != _isSelected) + * pNode.setSelected(_isSelected); + */ + } + } +} \ No newline at end of file diff --git a/src/com/langtech/plm/createProjectStruct/CheckBoxTreeNodeSelectionListener.java b/src/com/langtech/plm/createProjectStruct/CheckBoxTreeNodeSelectionListener.java new file mode 100644 index 0000000..2e721c0 --- /dev/null +++ b/src/com/langtech/plm/createProjectStruct/CheckBoxTreeNodeSelectionListener.java @@ -0,0 +1,31 @@ +package com.langtech.plm.createProjectStruct; + +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +import javax.swing.JTree; +import javax.swing.tree.TreePath; +import javax.swing.tree.DefaultTreeModel; + +public class CheckBoxTreeNodeSelectionListener extends MouseAdapter +{ + @Override + public void mouseClicked(MouseEvent event) + { + JTree tree = (JTree)event.getSource(); + int x = event.getX(); + int y = event.getY(); + int row = tree.getRowForLocation(x, y); + TreePath path = tree.getPathForRow(row); + if(path != null) + { + CheckBoxTreeNode node = (CheckBoxTreeNode)path.getLastPathComponent(); + if(node != null) + { + boolean isSelected = !node.isSelected(); + node.setSelected(isSelected); + ((DefaultTreeModel)tree.getModel()).nodeStructureChanged(node); + } + } + } +} \ No newline at end of file diff --git a/src/com/langtech/plm/createProjectStruct/CreateProjectStructDialog.java b/src/com/langtech/plm/createProjectStruct/CreateProjectStructDialog.java new file mode 100644 index 0000000..9c900c7 --- /dev/null +++ b/src/com/langtech/plm/createProjectStruct/CreateProjectStructDialog.java @@ -0,0 +1,250 @@ +package com.langtech.plm.createProjectStruct; + + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.util.HashMap; + +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextField; +import javax.swing.JTree; +import javax.swing.UIManager; +import javax.swing.tree.DefaultTreeModel; + +import com.teamcenter.rac.aif.AbstractAIFApplication; +import com.teamcenter.rac.aif.AbstractAIFDialog; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentFolder; +import com.teamcenter.rac.kernel.TCComponentFolderType; +import com.teamcenter.rac.kernel.TCException; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; +import com.teamcenter.services.rac.core.ReservationService; + + + + +@SuppressWarnings("serial") +public class CreateProjectStructDialog extends AbstractAIFDialog{ + + protected TCSession session; + private TCComponent target; + private JLabel modelLabel; + private JComboBox modelBox; + private JTextField nameField; + private JLabel nameLabel; + private JTree jtree; + private JButton okButton; + private JButton celButton; + private HashMap preMap = new HashMap(); + + public static final String preName = "connor_LY6_FolderTemp"; + + public CreateProjectStructDialog(AbstractAIFApplication app) { + super(false); + this.session = (TCSession) app.getSession(); + this.target = (TCComponent) app.getTargetComponent(); + try { + initUI(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Override + public void run() { + try { + initUI(); + //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); + UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); + } catch (Exception e) { + e.printStackTrace(); + } + } + + private void initUI() throws Exception { + this.setTitle("ģ崴ļ"); + Dimension dim = new Dimension(950, 600); + this.setPreferredSize(new Dimension(1000, 600)); + this.setMinimumSize(dim); + this.setLayout(new BorderLayout()); + modelLabel = new JLabel("ģ壺"); + modelBox = new JComboBox(); + modelBox.setPreferredSize(new Dimension(200,30)); + String[] prefVals = KUtil.getPrefVals(session, preName); + if(prefVals == null) { + MessageBox.post("ѡ " + preName + " ڻֵΪ", "ʾ ", MessageBox.INFORMATION); + return; + } + else { + for(String prefVal : prefVals) { + if(prefVal.contains("=")) { + String[] split = prefVal.split("="); + modelBox.addItem(split[0]); + preMap.put(split[0], split[1]); + } + } + } + nameLabel = new JLabel("Ʒͼţ"); + nameField = new JTextField(); + nameField.setPreferredSize(new Dimension(200,30)); + JPanel topPanel = new JPanel(); + topPanel.add(modelLabel); + topPanel.add(modelBox); + topPanel.add(nameLabel); + topPanel.add(nameField); + + //String lookAndFeel = "com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel"; + //String lookAndFeel = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"; + String lookAndFeel = "javax.swing.plaf.metal.MetalLookAndFeel"; + UIManager.setLookAndFeel(lookAndFeel); + + jtree = new JTree(); + initTree(jtree); + JScrollPane centerPane = new JScrollPane(jtree); + + JPanel buttonPanel = new JPanel(); + okButton = new JButton(""); + celButton = new JButton("ȡ"); + buttonPanel.add(okButton); + buttonPanel.add(celButton); + + this.add(BorderLayout.NORTH,topPanel); + this.add(BorderLayout.CENTER,centerPane); + this.add(BorderLayout.SOUTH,buttonPanel); + + addListeners(); + showDialog(); + } + + /** + * + * @param tree + */ + private void initTree(JTree tree){ + String puid = preMap.get(modelBox.getSelectedItem()); + TCComponent component; + try { + component = session.stringToComponent(puid); + if(component == null || !(component instanceof TCComponentFolder)) { + MessageBox.post(puid + " puidTCвڶ߸puidӦIJǡļС", "쳣", MessageBox.ERROR); + return; + } + else { + CheckBoxTreeNode rootNode = new CheckBoxTreeNode(component.getStringProperty("object_name")); + buildTree(component,rootNode); + DefaultTreeModel model = new DefaultTreeModel(rootNode); + tree.addMouseListener(new CheckBoxTreeNodeSelectionListener()); + tree.setModel(model); + tree.setCellRenderer(new CheckBoxTreeCellRenderer()); + //չнڵ㲢ѡ + for (int i = 0; i < tree.getRowCount(); i++) { + tree.expandRow(i); + } + rootNode.setSelected(true); + } + } catch (TCException e) { + e.printStackTrace(); + } + } + + /** + * ݹ鴴ӽڵ + * @param component + * @param rootNode + * @throws TCException + */ + private void buildTree(TCComponent component, CheckBoxTreeNode rootNode) throws TCException { + TCComponent[] relatedComponent = component.getRelatedComponents("contents"); + if(relatedComponent != null) { + for (TCComponent child : relatedComponent) { + CheckBoxTreeNode childNode = new CheckBoxTreeNode(child.getStringProperty("object_name")); + rootNode.add(childNode); + buildTree(child,childNode); + } + } + + } + + /** + * ݹ½ļнṹ + * @param root ڵ + * @param folder ڵɵļ + * @param folderType + * @throws Exception + */ + private void createFolderStruct(CheckBoxTreeNode root, TCComponentFolder parentFolder, + TCComponentFolderType folderType,boolean ifTop) throws Exception { + if(root.isSelected()) { + if(ifTop) { + for (int i = 0; i < root.getChildCount(); i++) { + CheckBoxTreeNode child = (CheckBoxTreeNode) root.getChildAt(i); + createFolderStruct(child,parentFolder,folderType,false); + } + } + else { + TCComponentFolder folder = KUtil.createFolderBySOA(folderType.getTypeName(), root.toString()); + parentFolder.add("contents", folder); + for (int i = 0; i < root.getChildCount(); i++) { + CheckBoxTreeNode child = (CheckBoxTreeNode) root.getChildAt(i); + createFolderStruct(child,folder,folderType,false); + } + } + } + + } + + private void addListeners() { + this.celButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + disposeDialog(); + } + }); + this.okButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + String name = nameField.getText(); + if (name.isEmpty()) { + MessageBox.post("дƷͼţ", "ʾ ", MessageBox.INFORMATION); + } else { + TCComponentFolderType folderType; + try { + KUtil.setByPass(true); + folderType = (TCComponentFolderType) session.getTypeComponent("LD6_CusProdFolder"); + TCComponentFolder folder = KUtil.createFolderBySOA(folderType.getTypeName(), name); + //TCComponentFolder folder = folderType.create(name, "", "LD6_CusProdFolder"); + target.add("contents", folder); + CheckBoxTreeNode root = (CheckBoxTreeNode) jtree.getModel().getRoot(); + createFolderStruct(root,folder,(TCComponentFolderType) session.getTypeComponent("LD6_ProjMaFolder"),true); + KUtil.setByPass(false); + disposeDialog(); + } catch (Exception e1) { + e1.printStackTrace(); + } + } + } + }); + this.modelBox.addItemListener(new ItemListener() { + public void itemStateChanged(ItemEvent event) { + if(event.getStateChange() == ItemEvent.SELECTED) { + //ˢ + jtree.setModel(null); + initTree(jtree); + }else if(event.getStateChange() == ItemEvent.DESELECTED){ + + } + } + }); + } + +} diff --git a/src/com/langtech/plm/createProjectStruct/CreateProjectStructHandler.java b/src/com/langtech/plm/createProjectStruct/CreateProjectStructHandler.java new file mode 100644 index 0000000..69bf121 --- /dev/null +++ b/src/com/langtech/plm/createProjectStruct/CreateProjectStructHandler.java @@ -0,0 +1,51 @@ +package com.langtech.plm.createProjectStruct; + +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.commands.ExecutionException; + + +import com.teamcenter.rac.aif.AbstractAIFApplication; +import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponentFolder; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +public class CreateProjectStructHandler extends AbstractHandler{ + + + @Override + public Object execute(ExecutionEvent arg0) throws ExecutionException { + AbstractAIFApplication app = AIFUtility.getCurrentApplication(); + TCSession session = (TCSession) app.getSession(); + try { + + new Thread() { + @Override + public void run() { + InterfaceAIFComponent targetComponent = app.getTargetComponent(); + + if(targetComponent instanceof TCComponentFolder) { + new CreateProjectStructDialog(app); + } + else { + MessageBox.post("ѡһͻļУ", "ʾ ", MessageBox.INFORMATION); + } + + + + } + }.start(); + + } catch (Exception e) { + // TODO: handle exception + e.printStackTrace(); + } + + return null; + } + + +} diff --git a/src/com/langtech/plm/createProjectStruct/KUtil.java b/src/com/langtech/plm/createProjectStruct/KUtil.java new file mode 100644 index 0000000..afadcad --- /dev/null +++ b/src/com/langtech/plm/createProjectStruct/KUtil.java @@ -0,0 +1,2238 @@ +package com.langtech.plm.createProjectStruct; + +import java.awt.Component; +import java.awt.Dimension; +import java.awt.GridBagConstraints; +import java.awt.Window; +import java.io.BufferedWriter; +import java.io.EOFException; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileWriter; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.text.DecimalFormat; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JDialog; +import javax.swing.JFileChooser; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.filechooser.FileNameExtensionFilter; +import javax.swing.filechooser.FileSystemView; + +import org.apache.poi.hssf.usermodel.HSSFCell; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellType; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.ss.usermodel.WorkbookFactory; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Shell; + + +import com.teamcenter.rac.aif.commands.open.OpenCommand; +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.lov.view.components.LOVDisplayer; +import com.teamcenter.rac.kernel.ListOfValuesInfo; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentContextList; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentDatasetType; +import com.teamcenter.rac.kernel.TCComponentFolder; +import com.teamcenter.rac.kernel.TCComponentForm; +import com.teamcenter.rac.kernel.TCComponentGroup; +import com.teamcenter.rac.kernel.TCComponentGroupMember; +import com.teamcenter.rac.kernel.TCComponentItem; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCComponentItemRevisionType; +import com.teamcenter.rac.kernel.TCComponentItemType; +import com.teamcenter.rac.kernel.TCComponentListOfValues; +import com.teamcenter.rac.kernel.TCComponentListOfValuesType; +import com.teamcenter.rac.kernel.TCComponentManager; +import com.teamcenter.rac.kernel.TCComponentQuery; +import com.teamcenter.rac.kernel.TCComponentQueryType; +import com.teamcenter.rac.kernel.TCComponentRole; +import com.teamcenter.rac.kernel.TCComponentSchedule; +import com.teamcenter.rac.kernel.TCComponentScheduleDeliverable; +import com.teamcenter.rac.kernel.TCComponentTCCalendar; +import com.teamcenter.rac.kernel.TCComponentTaskDeliverable; +import com.teamcenter.rac.kernel.TCComponentType; +import com.teamcenter.rac.kernel.TCComponentUser; +import com.teamcenter.rac.kernel.TCException; +import com.teamcenter.rac.kernel.TCProperty; +import com.teamcenter.rac.kernel.TCPropertyDescriptor; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.kernel.TCTextService; +import com.teamcenter.rac.kernel.TCUserService; +import com.teamcenter.rac.schedule.calendar.TCCalendar; +import com.teamcenter.rac.schedule.componentutils.CalendarHelper; +import com.teamcenter.rac.ui.common.RACUIUtil; +import com.teamcenter.rac.util.MessageBox; +import com.teamcenter.rac.util.Registry; +import com.teamcenter.rac.util.UIUtilities; +import com.teamcenter.services.rac.core.DataManagementService; +import com.teamcenter.services.rac.core.LOVService; +import com.teamcenter.services.rac.core._2006_03.DataManagement.Relationship; +import com.teamcenter.services.rac.core._2007_01.DataManagement.WhereReferencedInfo; +import com.teamcenter.services.rac.core._2007_01.DataManagement.WhereReferencedOutput; +import com.teamcenter.services.rac.core._2007_01.DataManagement.WhereReferencedResponse; +import com.teamcenter.services.rac.core._2008_06.DataManagement.CreateIn; +import com.teamcenter.services.rac.core._2008_06.DataManagement.CreateInput; +import com.teamcenter.services.rac.core._2008_06.DataManagement.CreateOut; +import com.teamcenter.services.rac.core._2008_06.DataManagement.CreateResponse; +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; +import com.teamcenter.soa.client.model.LovValue; +import com.teamcenter.soa.client.model.ServiceData; + +import k.KLocale; + +@SuppressWarnings("deprecation") +public class KUtil { + + public static final TCSession session; + public static final TCTextService textService; +// public static final Registry REG = Registry.getRegistry(KUtil.class); + public static final ZoneId zoneId = ZoneId.systemDefault(); +// public static final Registry reg = Registry.getRegistry(KUtil.class); + +// public static String getRegString(String title) { +// String res = reg.getString(title); +// if (KUtil.isEmpty(res)) { +// return title; +// } +// return res; +// } + + static { + session = (TCSession) AIFUtility.getCurrentApplication().getSession(); + textService = session.getTextService(); + } + + public static void setTCPropertyValue(TCComponent item, String propertyName, Object value) { + try { + TCProperty tcProperty = item.getTCProperty(propertyName); + switch (tcProperty.getPropertyType()) { + case TCProperty.PROP_double: + if (value instanceof Double) { + tcProperty.setDoubleValue((double) value); + } else { + tcProperty.setDoubleValue(Double.parseDouble(value.toString())); + } + break; + case TCProperty.PROP_int: + if (value instanceof Integer) { + tcProperty.setDoubleValue((int) value); + } else { + tcProperty.setDoubleValue(Integer.parseInt(value.toString())); + } + break; + case TCProperty.PROP_string: + tcProperty.setStringValue(value.toString()); + break; + case TCProperty.PROP_date: + if (value instanceof Date) { + tcProperty.setDateValue((Date) value); + } else { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-dd HH:mm"); + tcProperty.setDateValue(sdf.parse(value.toString())); + } + break; + default: + break; + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static Object getTCPropertyValue(TCComponent item, String propertyName) { + Object result = ""; + try { + TCProperty tcProperty = item.getTCProperty(propertyName); + if (tcProperty == null) { + System.out.println("δȡԣ" + propertyName); + return result; + } + switch (tcProperty.getPropertyType()) { + case TCProperty.PROP_double: + result = tcProperty.getDoubleValue(); + break; + case TCProperty.PROP_int: + result = tcProperty.getIntValue(); + break; + case TCProperty.PROP_string: + result = tcProperty.getStringValue(); + break; + case TCProperty.PROP_date: + result = tcProperty.getDateValue(); + break; + case TCProperty.PROP_logical: + result = tcProperty.getLogicalValue(); + break; + default: + break; + } + } catch (TCException e) { + e.printStackTrace(); + } + return result; + } + + public static String getCellValue(Cell c) { + if (c == null) { + return ""; + } + String value = ""; + if (c.getCellType() == CellType.NUMERIC.getCode()) { + DecimalFormat df = new DecimalFormat("0"); + String whatYourWant = df.format(c.getNumericCellValue()); + return whatYourWant; + } + switch (c.getCellType()) { + case HSSFCell.CELL_TYPE_NUMERIC:// + value = (c.getNumericCellValue() + "").split("\\.")[0]; + break; + case HSSFCell.CELL_TYPE_STRING:// ַ + value = c.getStringCellValue(); + break; + case HSSFCell.CELL_TYPE_BOOLEAN:// boolean + value = c.getBooleanCellValue() + ""; + break; + case HSSFCell.CELL_TYPE_FORMULA:// ʽ + value = c.getCellFormula() + ""; + break; + case HSSFCell.CELL_TYPE_BLANK:// ֵ + value = ""; + break; + case HSSFCell.CELL_TYPE_ERROR: + value = "Ƿַ"; + break; + default: + value = "δ֪"; + break; + } + return value; + } + + /** + * õʵ + * + * @param sheet + * @param flag ҪдݿExcelԪöŸ Excel5еԪ4 + * Ҫ⣬2вҪ⣬flagʹ [0,2,3,4] + * @return + * @throws Exception + * + */ + public static int findRealRows(Sheet sheet, int... flag) throws Exception { + int row_real = 0; + int rows = sheet.getPhysicalNumberOfRows();// ˴ͳд, + try { + + for (int i = 1; i < rows; i++) { + Row row = sheet.getRow(i); + int total = 0; + ArrayList blank = new ArrayList(); + int type = -1; + String s = null; + for (int j : flag) { + if (!(row.getCell(j) == null) && row.getCell(j).getCellType() < 2) { + type = row.getCell(j).getCellType(); + row.getCell(j).setCellType(1); + } + + if (row.getCell(j) == null || row.getCell(j).getStringCellValue().matches("^\\s+$") + || row.getCell(j).getCellType() > 2) { + total++; + + if (!(row.getCell(j) == null) && row.getCell(j).getCellType() < 2) { + row.getCell(j).setCellType(type); + } + blank.add(j); + + } + } + System.out.println(s + ""); + // 4жǿ˵͸÷ + if (total == flag.length) { + + return row_real; + } else if (total == 0) { + row_real++; + + } else { + String h = ""; + for (Integer b : blank) { + + h = h + "" + (b + 1) + "" + " "; + } + throw new Exception("" + (i + 1) + "" + h + "Ϊ"); + } + + } + } catch (NullPointerException e) { + throw new Exception("excelʽ쳣,excelʽȱʧ,Ч!"); + } + return row_real; + } + + public static Workbook getWorkbook(File file) throws Exception { + Workbook workbook = null; + FileInputStream in = new FileInputStream(file); + if (file.getName().endsWith("xlsx")) { + System.out.println("ȡģ:" + file.getName()); + try { + workbook = WorkbookFactory.create(in); + } catch (EOFException e) { + e.printStackTrace(); + } +// workbook = new XSSFWorkbook(in); + } else { + System.out.println("ʽ"); + } + in.close(); + return workbook; + } + + public static void removeEnd(StringBuilder sb, int len) { + if (sb == null || len <= 0) { + return; + } + if (sb.length() >= len) { + sb.setLength(sb.length() - len); + } + } + + public static TCComponent[] getComponentsByItemType(TCComponent comp, String type, String relation) + throws TCException { + TCComponent[] comps1 = comp.getRelatedComponents(relation); + if (comps1 == null || comps1.length < 1) { + return null; + } + ArrayList list = new ArrayList(); + for (TCComponent comp1 : comps1) { + if (comp1.getType().equals(type)) { + list.add(comp1); + } + } + return list.toArray(new TCComponent[] {}); + } + + public static TCComponentContextList objectsInProject(String type, String projId) throws Exception { + if (KUtil.isEmpty(type) || KUtil.isEmpty(projId)) { + return null; + } + String queryName = "Objects in Projects"; + String[] keys = new String[] { KUtil.getText("Type"), KUtil.getText("ProjectID") }; + String[] vals = new String[] { type, projId }; + return KUtil.query(KUtil.session, queryName, keys, vals); + } + + public static TCComponentContextList objectsInProject(String type, String projId, String name) throws Exception { + if (KUtil.isEmpty(type) || KUtil.isEmpty(projId) || KUtil.isEmpty(name)) { + return null; + } + String queryName = "Objects in Projects"; + String[] keys = new String[] { KUtil.getText("Name"), KUtil.getText("Type"), KUtil.getText("ProjectID") }; + String[] vals = new String[] { name, type, projId }; + return KUtil.query(KUtil.session, queryName, keys, vals); + } + + public static boolean checkGMPrivilegeFromPref(String prefName) throws Exception { + boolean validityCanEdit = false; + String validRoles = KUtil.getPrefVal(KUtil.session, prefName); + System.out.println(">> Check GroupMember Priv: " + validRoles); + if (!KUtil.isEmpty(validRoles)) { + List groups = new ArrayList(); + List roles = new ArrayList(); + String[] split = validRoles.split(":"); + for (String string : split) { + if (string.startsWith("G.")) { + groups.add(string.substring(2)); + } else if (string.startsWith("R.")) { + roles.add(string.substring(2)); + } + } + TCComponentUser currentUser = KUtil.session.getUser(); + System.out.println(">> Current User: " + currentUser); + TCComponentGroupMember[] gms = currentUser.getGroupMembers(); + System.out.println(">> Current GroupMembers: " + Arrays.toString(gms)); + int len = KUtil.getLen(gms); + for (int i = 0; i < len; i++) { + TCComponentGroupMember gm = gms[i]; + TCComponentGroup g = gm.getGroup(); + TCComponentRole r = gm.getRole(); + String gName = g.getGroupName(); + String rName = r.getRoleName(); + System.out.println((i + 1) + ". " + gName + " - " + rName); + if (groups.contains(gName) && roles.contains(rName)) { + validityCanEdit = true; + // break; + } + } + } + return validityCanEdit; + } + + public static boolean compare(String str1, String str2) { + if (str1 == null) { + str1 = ""; + } + if (str2 == null) { + str2 = ""; + } + return str1.equals(str2); + } + + public static boolean compare(Object str1, Object str2) { + if (str1 == null) { + return str2 == null; + } + return str1.equals(str2); + } + + public static TCComponentItem createItem(TCComponentItemType itemType, String itemName) throws Exception { + if (itemType == null) { + return null; + } + String id = itemType.getNewID(); + String rev = itemType.getNewRev(null); + return itemType.create(id, rev, itemType.getName(), itemName, "", null); + } + + public static void setByPass(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 TCComponentItem createItemBySOA(String itemTypeName, String revTypeName, String revMasterTypeName, + String itemId, String revId, String name, Map stringProps, Map dateProps) + throws Exception { + if (KUtil.isEmpty(itemTypeName) || KUtil.isEmpty(revTypeName) || KUtil.isEmpty(revMasterTypeName)) { + return null; + } + CreateInput revMasterInput = new CreateInput(); + revMasterInput.boName = revMasterTypeName; + if (stringProps != null) { + revMasterInput.stringProps = stringProps; + } + if (dateProps != null) { + revMasterInput.dateProps = dateProps; + } + CreateInput revInput = new CreateInput(); + revInput.boName = revTypeName; + Map revPropMap = new HashMap<>(); + if (!KUtil.isEmpty(revId)) { + revPropMap.put("item_revision_id", revId); + } + revInput.stringProps = revPropMap; + Map revMasterInfoMap = new HashMap<>(); + revMasterInfoMap.put("IMAN_master_form_rev", new CreateInput[] { revMasterInput }); + revInput.compoundCreateInput = revMasterInfoMap; + // create rev + CreateInput itemInput = new CreateInput(); + itemInput.boName = itemTypeName; + Map itemPropMap = new HashMap<>(); + if (!KUtil.isEmpty(itemId)) { + itemPropMap.put("item_id", itemId); + } + if (!KUtil.isEmpty(name)) { + itemPropMap.put("object_name", name); + } + itemInput.stringProps = itemPropMap; + Map revInfoMap = new HashMap<>(); + revInfoMap.put("revision", new CreateInput[] { revInput }); + itemInput.compoundCreateInput = revInfoMap; + // create info + CreateIn cI = new CreateIn(); + cI.clientId = "CreateItem"; + cI.data = itemInput; + // service + DataManagementService service = DataManagementService.getService(session); + // create + CreateResponse resp = service.createObjects(new CreateIn[] { cI }); + throwServiceDataError(resp.serviceData); + CreateOut[] cOs = resp.output; + if (cOs.length > 0) { + for (TCComponent s : cOs[0].objects) { + if (s instanceof TCComponentItem) { + return (TCComponentItem) s; + } + } + } + return null; + } + + public static TCComponentFolder createFolderBySOA(String folderTypeName, String folderName) throws Exception { + if (KUtil.isEmpty(folderTypeName)) { + return null; + } + CreateInput itemInput = new CreateInput(); + itemInput.boName = folderTypeName; + Map itemPropMap = new HashMap<>(); + itemPropMap.put("object_name", folderName); + itemInput.stringProps = itemPropMap; + // create info + CreateIn cI = new CreateIn(); + cI.clientId = "CreateFolder"; + cI.data = itemInput; + // service + DataManagementService service = DataManagementService.getService(session); + // create + CreateResponse resp = service.createObjects(new CreateIn[] { cI }); + throwServiceDataError(resp.serviceData); + CreateOut[] cOs = resp.output; + if (cOs.length > 0) { + for (TCComponent s : cOs[0].objects) { + if (s instanceof TCComponentFolder) { + return (TCComponentFolder) s; + } + } + } + return null; + } + + public static void throwServiceDataError(ServiceData serviceData) throws Exception { + if (serviceData.sizeOfPartialErrors() > 0) { + StringBuilder errInfo = new StringBuilder(); + for (int i = 0; i < serviceData.sizeOfPartialErrors(); i++) { + for (String msg : serviceData.getPartialError(i).getMessages()) { + errInfo.append(msg + "\n"); + } + } + // System.out.println(errInfo.toString()); + throw new Exception(errInfo.toString()); + } + } + + public static void throwServiceDataError(ServiceData serviceData, String defaultErrorMsg) throws Exception { + if (serviceData.sizeOfPartialErrors() > 0) { + StringBuilder errInfo = new StringBuilder(); + for (int i = 0; i < serviceData.sizeOfPartialErrors(); i++) { + for (String msg : serviceData.getPartialError(i).getMessages()) { + errInfo.append(msg + "\n"); + } + } + // System.out.println(errInfo.toString()); + if (KUtil.isEmpty(errInfo.toString())) { + throw new Exception(defaultErrorMsg); + } + throw new Exception(errInfo.toString()); + } + } + + public static Date localDateToDate(LocalDate localDate) { + if (localDate == null) { + return null; + } + ZonedDateTime zdt = localDate.atStartOfDay(zoneId); + Date date = Date.from(zdt.toInstant()); + return date; + } + + public static LocalDate dateToLocalDate(Date date) { + if (date == null) { + return null; + } + Instant instant = date.toInstant(); + LocalDate localDate = instant.atZone(zoneId).toLocalDate(); + return localDate; + } + + public static TCComponent stringToComponent(String uid) throws Exception { + if (KUtil.isEmpty(uid)) { + return null; + } + return session.stringToComponent(uid); + } + + public static String getText(String str) throws Exception { + if (KUtil.isEmpty(str)) { + return str; + } + String res = textService.getTextValue(str); + if (!KUtil.isEmpty(res)) { + return res; + } + return str; + } + + public static void sendTo(TCComponent comp, String perspectiveId) { + if (comp == null) { + return; + } + if (KUtil.isEmpty(perspectiveId)) { + perspectiveId = "com.teamcenter.rac.ui.perspectives.navigatorPerspective"; + } + com.teamcenter.rac.common.Activator.getDefault().openPerspective(perspectiveId); + com.teamcenter.rac.common.Activator.getDefault().openComponents(perspectiveId, new TCComponent[] { comp }); + } + + public static void open(TCComponent comp) { + if (comp == null) { + return; + } + if (comp instanceof TCComponentScheduleDeliverable) { + System.out.println(">> Open Schedule Deliverable: " + comp); + try { + comp = comp.getReferenceProperty("deliverable_inst"); + System.out.println(">> Open Schedule Deliverable Inst: " + comp); + if (comp == null) { + return; + } + } catch (Exception e) { + e.printStackTrace(); + } + } else if (comp instanceof TCComponentTaskDeliverable) { + System.out.println(">> Open Task Deliverable: " + comp); + try { + comp = comp.getReferenceProperty("fnd0DeliverableInstance"); + System.out.println(">> Open Task Deliverable Inst: " + comp); + if (comp == null) { + return; + } + } catch (Exception e) { + e.printStackTrace(); + } + } + try { + Registry localRegistry = Registry.getRegistry("com.teamcenter.rac.commands.open.open"); + OpenCommand localOpenCommand = (OpenCommand) localRegistry.newInstanceForEx("openCommand", + new Object[] { AIFUtility.getActiveDesktop(), comp }); + localOpenCommand.executeModeless(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static JButton getImageBtn(String iconName) { + ImageIcon icon = new ImageIcon(KUtil.class.getResource("/icons/" + iconName)); + JButton btn = new JButton(icon); + btn.setPreferredSize(new Dimension(26, 26)); + btn.setContentAreaFilled(true); + btn.setFocusPainted(false); + btn.setBorderPainted(true); + // btn.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); + return btn; + } + + public static void info(Window dialog, String msg) { + MessageBox.post(dialog, msg, "", MessageBox.INFORMATION); + } + + public static void warn(Window dialog, String msg) { + MessageBox.post(dialog, msg, "", MessageBox.WARNING); + } + + public static void error(Window dialog, String msg) { + MessageBox.post(dialog, msg, "", MessageBox.ERROR); + } + + public static void error(Window dialog, String msg, String title) { + MessageBox.post(dialog, msg, title, MessageBox.ERROR); + } + + public static void showScrollDialog(Window dialog, String text, String title) { + if (dialog == null) { + dialog = UIUtilities.getCurrentModalDialog(); + } + JTextArea textArea = new JTextArea(text); + textArea.setEditable(false); + JScrollPane scrollPane = new JScrollPane(textArea); + textArea.setLineWrap(true); + textArea.setWrapStyleWord(true); + scrollPane.setPreferredSize(new Dimension(500, 300)); + JOptionPane.showMessageDialog(dialog, scrollPane, title, JOptionPane.INFORMATION_MESSAGE); + } + + public static void showScrollDialogWithExport(Window dialog, String text, String title, String exportFileName) { + if (dialog == null) { + dialog = UIUtilities.getCurrentModalDialog(); + } + JTextArea textArea = new JTextArea(text); + textArea.setEditable(false); + JScrollPane scrollPane = new JScrollPane(textArea); + textArea.setLineWrap(true); + textArea.setWrapStyleWord(true); + scrollPane.setPreferredSize(new Dimension(500, 300)); + String yesOption = KLocale.getString("ok"); + String exportOption = KLocale.getString("export"); + int op = JOptionPane.showOptionDialog(dialog, scrollPane, title, JOptionPane.YES_NO_OPTION, + JOptionPane.INFORMATION_MESSAGE, null, new String[] { yesOption, exportOption }, yesOption); + if (op == 1) { + System.out.println("Export"); + File saveFile = KUtil.chooseSaveFile(dialog, exportFileName, "txt"); + if (saveFile != null) { + try { + BufferedWriter writer = new BufferedWriter(new FileWriter(saveFile, false)); + writer.write(text); + writer.flush(); + writer.close(); + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(dialog, e); + } + } + } + } + + public static void errorSWT(Shell shell, String message, String title) { + showDialog(shell, message, title, SWT.ICON_ERROR); + } + + public static void showDialog(Shell shell, String message, String title, int type) { + org.eclipse.swt.widgets.MessageBox dialog = new org.eclipse.swt.widgets.MessageBox(shell, SWT.OK | type); + dialog.setText(title); + dialog.setMessage(message); + dialog.open(); + } + + public static String[] getPrefVals(TCSession session, String prefName) throws Exception { + if (KUtil.isEmpty(prefName)) { + return null; + } + return session.getPreferenceService().getStringValues(prefName); + } + + public static String getPrefVal(TCSession session, String prefName) throws Exception { + if (KUtil.isEmpty(prefName)) { + return null; + } + return session.getPreferenceService().getStringValue(prefName); + } + + public static String getReg(Registry reg, String name) { + String val = reg.getString(name); + // System.out.println("Read REG: " + name + " = " + val); + return val; + } + +// public static String getReg(String name) { +// return getReg(REG, name); +// } + + public static void newRow(JPanel panel, Component comp, GridBagConstraints s, int width) { + newRow(panel, comp, s, width, 0); + } + + public static void newRow(JPanel panel, Component comp, GridBagConstraints s, int width, double weightx) { + s.weightx = weightx; + s.gridwidth = width; + s.gridx = 0; + s.gridy++; + panel.add(comp, s); + } + + public static void newRow(JDialog panel, Component comp, GridBagConstraints s, int width) { + s.weightx = 0; + s.gridwidth = width; + s.gridx = 0; + s.gridy++; + panel.add(comp, s); + } + + public static void addCol(JPanel panel, Component comp, GridBagConstraints s, int width, double weightx) { + s.gridx++; + s.gridwidth = width; + s.weightx = weightx; + panel.add(comp, s); + } + + public static TCComponentDataset getDataset(TCComponent rev, String dsType, String dsName, String rel) + throws Exception { + if (rev == null || KUtil.isEmpty(dsName)) { + return null; + } + rev.refresh(); + TCComponent[] kids = rev.getRelatedComponents(rel); + for (TCComponent c : kids) { + if (c.getType().equals(dsType) && c.toString().equals(dsName)) { + return (TCComponentDataset) c; + } + } + return null; + } + + public static List getDatasets(TCComponent rev, String dsType, String rel) throws Exception { + if (rev == null) { + return null; + } + rev.refresh(); + List res = new ArrayList(); + TCComponent[] kids = rev.getRelatedComponents(rel); + for (TCComponent c : kids) { + if (c.getType().equals(dsType)) { + res.add((TCComponentDataset) c); + } + } + return res; + } + + public static List getChildComponents(TCComponent rev, String dsType, String rel, String dsNamePrefix) + throws Exception { + if (rev == null) { + return null; + } + rev.refresh(); + List res = new ArrayList(); + TCComponent[] kids = rev.getRelatedComponents(rel); + for (TCComponent c : kids) { + if (c.getType().equals(dsType) && c.getProperty("object_name").startsWith(dsNamePrefix)) { + res.add(c); + } + } + return res; + } + + public static List getChildComponentsContainsStr(TCComponent rev, String dsType, String rel, + String dsNameSubStr) throws Exception { + if (rev == null) { + return null; + } + if (dsNameSubStr == null) { + dsNameSubStr = ""; + } + rev.refresh(); + List res = new ArrayList(); + TCComponent[] kids = rev.getRelatedComponents(rel); + for (TCComponent c : kids) { + if (c.getType().equals(dsType) && c.getProperty("object_name").contains(dsNameSubStr)) { + res.add(c); + } + } + return res; + } + + public static List getChildComponents(TCComponent rev, String dsType, String rel) throws Exception { + if (rev == null) { + return null; + } + rev.refresh(); + List res = new ArrayList(); + TCComponent[] kids = rev.getRelatedComponents(rel); + for (TCComponent c : kids) { + if (c.getType().equals(dsType)) { + res.add(c); + } + } + return res; + } + + public static TCComponentFolder getChildFolder(TCComponentFolder folder, String cFolderName) throws Exception { + if (folder == null || cFolderName == null) { + return null; + } + AIFComponentContext[] cc = folder.getChildren(); + int len = KUtil.getLen(cc); + for (int i = 0; i < len; i++) { + InterfaceAIFComponent c = cc[i].getComponent(); + if ((c instanceof TCComponentFolder) && cFolderName.equals(c.getProperty("object_name"))) { + return (TCComponentFolder) c; + } + } + return null; + } + + public static TCComponentDataset uploadFile(TCSession session, TCComponent rev, File newFile, String dsName, + String dsTypeName, String refName, String rel) throws Exception { + TCComponentDataset ds = getDataset(rev, dsTypeName, dsName, rel); + if (ds == null) { + TCComponentDatasetType dsType = (TCComponentDatasetType) session.getTypeComponent(dsTypeName); + ds = dsType.create(dsName, "", dsTypeName); + if (rev != null) { + rev.add(rel, ds); + rev.refresh(); + } + } + setDsFile(ds, refName, newFile); + return ds; + } + + public static void setDsFile(TCComponentDataset ds, String refName, File newFile) throws Exception { + if (ds.isCheckedOut()) { + throw new Exception(String.format(KLocale.getString("uploadfilewhencheckout.ERROR1"), ds.toString())); + } + String[] refs = new String[] { refName }; + String[] files = new String[] { newFile.getAbsolutePath() }; + ds.setFiles(files, refs); + // ds.save(); + ds.refresh(); + } + + public static void setDsFile2(TCComponentDataset ds, String refName, File newFile) throws Exception { + String[] refs = new String[] { refName }; + String[] files = new String[] { newFile.getAbsolutePath() }; + ds.setFiles(files, refs); + // ds.save(); + ds.refresh(); + } + + public static boolean isEmpty(String str) { + return str == null || "".equals(str.trim()); + } + + public static int inArray(int target, int[] arr) { + int len = arr == null ? 0 : arr.length; + for (int i = 0; i < len; i++) { + if (target == arr[i]) { + return i; + } + } + return -1; + } + + public static boolean inArray(String str, String arr, String splitter) { + if (KUtil.isEmpty(arr) || KUtil.isEmpty(splitter)) { + return false; + } + if (KUtil.isEmpty(str)) { + return true; + } + return inArray(str, arr.split(splitter)) >= 0; + } + + public static int inArray(String target, String[] arr) { + int len = arr == null ? 0 : arr.length; + for (int i = 0; i < len; i++) { + if (target.equals(arr[i])) { + return i; + } + } + return -1; + } + + public static int getNextColNumber(int currentIndex, int[] skipColIndex, int cols) { + int res = currentIndex; + for (int i = 0; i < cols; i++) { + res++; + if (inArray(res, skipColIndex) >= 0) { + i--; + } + } + return res; + } + + public static List> groupList(List originList, int maxCount, int gap, E gapFiller) { + List> res = new ArrayList>(); + int cnt = originList == null ? 0 : originList.size(); + List list = new ArrayList(); + for (int i = 0; i < cnt; i++) { + list.add(originList.get(i)); + if (i != cnt - 1) {// add gap + for (int j = 0; j < gap; j++) { + list.add(gapFiller); + } + } + } + cnt = list == null ? 0 : list.size(); + if (maxCount <= 0) { + maxCount = cnt; + } + int pageCounter = 0; + List cList = new ArrayList(); + res.add(cList); + for (int i = 0; i < cnt; i++) { + if (pageCounter == maxCount) { + cList = new ArrayList<>(); + res.add(cList); + pageCounter = 0; + } + if (cList != null) { + E item = list.get(i); + if (cList.size() == 0 && item == gapFiller) { + continue; + } + cList.add(list.get(i)); + pageCounter++; + } + } + list.clear(); + list = null; + return res; + } + + public static List> groupListWithGapAdded(List list, int maxCount, E gapFiller) { + List> res = new ArrayList>(); + int cnt = list == null ? 0 : list.size(); + if (maxCount <= 0) { + maxCount = cnt; + } + int pageCounter = 0; + List cList = new ArrayList(); + res.add(cList); + for (int i = 0; i < cnt; i++) { + if (pageCounter == maxCount) { + cList = new ArrayList<>(); + res.add(cList); + pageCounter = 0; + } + if (cList != null) { + E item = list.get(i); + if (cList.size() == 0 && item == gapFiller) { + continue; + } + cList.add(list.get(i)); + pageCounter++; + } + } + list.clear(); + list = null; + return res; + } + + public static List>> groupList(List> originList, int maxCount, int gap, + Map gapFiller, String gapKey) { + List>> res = new ArrayList>>(); + int cnt = originList == null ? 0 : originList.size(); + List> list = new ArrayList>(); + boolean addGap = false; + for (int i = 0; i < cnt; i++) { + Map item = originList.get(i); + list.add(item); + if (i != cnt - 1) {// add gap + Map nextItem = originList.get(i + 1); + addGap = KUtil.isEmpty(gapKey) || (nextItem != null && nextItem.containsKey(gapKey)); + for (int j = 0; j < gap; j++) { + if (addGap) { + list.add(gapFiller); + } + } + } + } + cnt = list == null ? 0 : list.size(); + if (maxCount <= 0) { + maxCount = cnt; + } + int pageCounter = 0; + List> cList = new ArrayList>(); + res.add(cList); + for (int i = 0; i < cnt; i++) { + if (pageCounter == maxCount) { + cList = new ArrayList<>(); + res.add(cList); + pageCounter = 0; + } + if (cList != null) { + Map item = list.get(i); + if (cList.size() == 0 && item == gapFiller) { + continue; + } + cList.add(list.get(i)); + pageCounter++; + } + } + list.clear(); + list = null; + return res; + } + + public static File getFileFromDataset(TCSession session, String dsType, String uid, String prefName) + throws Exception { + TCComponent comp = null; + try { + comp = session.stringToComponent(uid); + } catch (Exception e) { + e.printStackTrace(); + } + if (comp == null) { + throw new Exception(String.format(KLocale.getString("dsuidinpref.ERROR1"), prefName)); + } + String type = comp.getType(); + System.out.println("Dataset: " + comp + "|Type: " + type); + if (!dsType.equals(type)) { + throw new Exception(String.format(KLocale.getString("dsuidinpref.ERROR1"), prefName)); + } + TCComponentDataset tDataset = (TCComponentDataset) comp; + return getDatasetFile(tDataset); + } + + public static File getDatasetFile(TCComponentDataset dataset) throws Exception { + File[] files = dataset.getFiles("", System.getenv("TEMP")); + if (files == null || files.length == 0) { + throw new Exception(String.format(KLocale.getString("norefindataset.ERROR1"), dataset.toString())); + } + System.out.println(">> Download file (" + files.length + "): " + files[0].getAbsolutePath()); + return files[0]; + } + + public static File getDatasetFile(File dir, TCComponentDataset dataset) throws Exception { + if (dir == null || !dir.isDirectory()) { + throw new Exception("Directory not found."); + } + File[] files = dataset.getFiles("", dir.getAbsolutePath()); + if (files == null || files.length == 0) { + throw new Exception(String.format(KLocale.getString("norefindataset.ERROR1"), dataset.toString())); + } + System.out.println(">> Download file (" + files.length + "): " + files[0].getAbsolutePath()); + return files[0]; + } + + public static String[] getStringArrayProp(TCComponentForm form, String propName) throws Exception { + if (form == null) { + return null; + } + TCProperty prop = form.getFormTCProperty(propName); + if (prop == null) { + throw new java.lang.Exception( + String.format(KLocale.getString("nopropintype.ERROR2"), form.getDisplayType(), propName)); + } + return prop.getStringArrayValue(); + } + + public static File chooseDirectory(Component parent) { + FileSystemView fsv = FileSystemView.getFileSystemView(); + String deskPath = fsv.getHomeDirectory().getPath(); + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setCurrentDirectory(new File(deskPath)); + fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + int state = fileChooser.showOpenDialog(parent); + if (state == 1) { + return null; + } + return fileChooser.getSelectedFile(); + } + + public static boolean addReleaseStatus(TCSession session, String uid, String status) throws Exception { + TCUserService userservice = session.getUserService(); + Object[] obj = new Object[2]; + obj[0] = uid; + obj[1] = status; + Object res = userservice.call("K_add_release_status", obj); + if (res != null && res.toString().equalsIgnoreCase("true")) { + return true; + } + return false; + } + + /** + * ֻԵֵ + * + * @param session + * @param propName + * @param propValue + * @param comp + * @return + * @throws Exception + */ + public static boolean setPropValue(TCSession session, String propName, String propValue, TCComponent comp) + throws Exception { + TCUserService userservice = session.getUserService(); + Object[] obj = new Object[3]; + obj[0] = propName; + obj[1] = propValue; + obj[2] = comp; + Object res = userservice.call("Connor_Set_Prop_Value", obj); + if (res != null && res.toString().equalsIgnoreCase("true")) { + return true; + } + return false; + } + + public static File chooseFile(Component parent) { + FileSystemView fsv = FileSystemView.getFileSystemView(); + String deskPath = fsv.getHomeDirectory().getPath(); + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setCurrentDirectory(new File(deskPath)); + fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); + FileNameExtensionFilter filter = new FileNameExtensionFilter("*.xlsx", "xlsx"); + fileChooser.setFileFilter(filter); + int state = fileChooser.showOpenDialog(parent); + if (state == 1) { + return null; + } + return fileChooser.getSelectedFile(); + } + + public static File chooseSaveFile(Component parent, String defaultFile) { + FileSystemView fsv = FileSystemView.getFileSystemView(); + String deskPath = fsv.getHomeDirectory().getPath(); + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setCurrentDirectory(new File(deskPath)); + fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); + FileNameExtensionFilter filter = new FileNameExtensionFilter("*.xlsx", "xlsx"); + fileChooser.setFileFilter(filter); + fileChooser.setSelectedFile(new File(defaultFile)); + int state = fileChooser.showSaveDialog(parent); + if (state == 1) { + return null; + } + return fileChooser.getSelectedFile(); + } + + public static File chooseSaveFile(Component parent, String defaultFile, String ext) { + FileSystemView fsv = FileSystemView.getFileSystemView(); + String deskPath = fsv.getHomeDirectory().getPath(); + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setCurrentDirectory(new File(deskPath)); + fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); + if (!KUtil.isEmpty(ext)) { + FileNameExtensionFilter filter = new FileNameExtensionFilter("*." + ext, ext); + fileChooser.setFileFilter(filter); + } + fileChooser.setSelectedFile(new File(defaultFile)); + int state = fileChooser.showSaveDialog(parent); + if (state == 1) { + return null; + } + return fileChooser.getSelectedFile(); + } + + public static File getNewFile(File folder, String fileName, String ext) { + File file = new File(folder.getAbsolutePath() + "\\" + fileName + "." + ext); + int index = 1; + while (file.exists()) { + file = new File(folder.getAbsolutePath() + "\\" + fileName + "(" + (index++) + ")." + ext); + } + return file; + } + + public static String getDateStr(Date date, String format) { + String res = ""; + try { + SimpleDateFormat sdf = new SimpleDateFormat(format); + res = sdf.format(date); + } catch (Exception e) { + e.printStackTrace(); + } + return res; + } + + public static TCComponentContextList query(TCSession session, String queryName, Map fields) + throws Exception { + String[] keys = fields.keySet().toArray(new String[] {}); + String[] vals = fields.values().toArray(new String[] {}); + return query(session, queryName, keys, vals); + } + + public static TCComponentContextList query(TCSession session, String queryName, String[] keys, String[] vals) + throws Exception { + System.out.println("Query: " + queryName); + System.out.println("keys = " + Arrays.toString(keys)); + System.out.println("vals = " + Arrays.toString(vals)); + TCComponentQueryType queryType = (TCComponentQueryType) session.getTypeComponent("ImanQuery"); + TCComponentQuery query = (TCComponentQuery) queryType.find(queryName); + if (query == null) { + throw new Exception(String.format(KLocale.getString("querynotexist.ERROR1"), queryName)); + } + queryType.clearCache(); + query.clearCache(); + query.refresh(); + return query.getExecuteResultsList(keys, vals); + } + + public static TCComponent[] query2(TCSession session, String queryName, String[] keys, String[] vals) + throws Exception { + System.out.println("Query: " + queryName); + System.out.println("keys = " + Arrays.toString(keys)); + System.out.println("vals = " + Arrays.toString(vals)); + TCComponentQueryType queryType = (TCComponentQueryType) session.getTypeComponent("ImanQuery"); + TCComponentQuery query = (TCComponentQuery) queryType.find(queryName); + if (query == null) { + throw new Exception(String.format(KLocale.getString("querynotexist.ERROR1"), queryName)); + } + queryType.clearCache(); + query.clearCache(); + query.refresh(); + return query.execute(keys, vals); + } + + public static TCComponentContextList combineContext(TCSession session, TCComponentQuery query, + TCComponentContextList... contexts) throws Exception { + Class c = TCComponentContextList.class; + Field f1 = c.getDeclaredField("m_compUids"); + f1.setAccessible(true); + List compUids = new ArrayList<>(); + for (TCComponentContextList cc : contexts) { + String[] u1 = (String[]) f1.get(cc); + System.out.println(Arrays.toString(u1)); + compUids.addAll(Arrays.asList(u1)); + } + Constructor constructor = c.getDeclaredConstructor(TCComponentManager.class, TCComponent.class, + String[].class, String[].class, String.class); + constructor.setAccessible(true); + TCComponentContextList res = (TCComponentContextList) constructor.newInstance(new TCComponentManager(session), + query, compUids.toArray(new String[] {}), null, ""); + return res; + } + + public static int getLen(Object[] arr) { + return arr == null ? 0 : arr.length; + } + + public static String getValueInArray(String[] arr, int index) { + int len = arr == null ? 0 : arr.length; + if (index >= len) { + return ""; + } + return arr[index]; + } + + public static String getValueInArray(String arrStr, int index, String splitter) { + if (KUtil.isEmpty(arrStr)) { + return ""; + } + String[] split = arrStr.split(splitter, -1); + int len = getLen(split); + if (len > index && index >= 0) { + return split[index]; + } + return ""; + } + + public static String getTypeNames(TCSession session, Object[] types) { + int len = types == null ? 0 : types.length; + if (len == 0) { + return ""; + } + String[] names = new String[len]; + for (int i = 0; i < len; i++) { + try { + if ("TC_Project".equals(types[i].toString())) { + names[i] = KLocale.getString("project"); + } else { + names[i] = session.getTypeComponent(types[i].toString()).getDisplayTypeName(); + } + } catch (Exception e) { + e.printStackTrace(); + } + if (names[i] == null) { + names[i] = types[i].toString(); + } + } + return Arrays.toString(names); + } + + public static String getTypeName(TCSession session, String type) { + if (KUtil.isEmpty(type)) { + return ""; + } + try { + if ("TC_Project".equals(type)) { + return KLocale.getString("project"); + } else { + return session.getTypeComponent(type).getDisplayTypeName(); + } + } catch (Exception e) { + e.printStackTrace(); + } + return type; + } + + public static boolean isReleased(TCComponent comp) throws Exception { + TCComponent[] status = comp.getReferenceListProperty("release_status_list"); + if (status == null || status.length == 0) { + return false; + } + return true; + } + + public static TCComponentUser getUserFromStr(String str) throws Exception { + System.out.println("Search User: " + str); + if (KUtil.isEmpty(str)) { + return null; + } + int ind1 = str.lastIndexOf('('); + int ind2 = str.lastIndexOf(')'); + TCComponentUser user = null; + if (ind1 > 0 && ind2 > ind1) { + String userId = str.substring(ind1 + 1, ind2); + if (KUtil.isEmpty(userId)) { + System.out.println("No Id between '(' and ')'"); + user = null; + } else { + user = queryUserById(userId); + } + } else { + user = queryUserById(str); + if (user == null) { + user = queryUserByName(str); + } + } + return user; + } + + public static TCComponentUser queryUserById(String userId) throws Exception { + System.out.println("Search User By Id: " + userId); + if (KUtil.isEmpty(userId)) { + return null; + } + String queryName = "Admin - Employee Information"; + String[] keys = new String[] { KUtil.getText("UserId") }; + String[] vals = new String[] { userId }; + TCComponentContextList res = KUtil.query(KUtil.session, queryName, keys, vals); + if (res.getListCount() == 0) { + return null; + } + if (res.getListCount() > 1) { + throw new Exception(String.format(KLocale.getString("multiuserbyid.ERROR1"), userId)); + } + return (TCComponentUser) res.get(0).getComponent(); + } + + public static TCComponentUser queryUserByName(String userName) throws Exception { + System.out.println("Search User By Name: " + userName); + if (KUtil.isEmpty(userName)) { + return null; + } + String queryName = "Admin - Employee Information"; + String[] keys = new String[] { KUtil.getText("PersonName") }; + String[] vals = new String[] { userName }; + TCComponentContextList res = KUtil.query(KUtil.session, queryName, keys, vals); + if (res.getListCount() == 0) { + return null; + } + if (res.getListCount() > 1) { + throw new Exception(String.format(KLocale.getString("multiuserbyname.ERROR1"), userName)); + } + return (TCComponentUser) res.get(0).getComponent(); + } + + public static TCComponent[] getGroupMember(List privMembers) throws Exception { + if (privMembers == null) { + return null; + } + List res = new ArrayList<>(); + for (TCComponentUser user : privMembers) { + TCComponentGroupMember[] gms = user.getGroupMembers(); + int len = KUtil.getLen(gms); + for (int i = 0; i < len; i++) { + TCComponentGroupMember gm = gms[i]; + if (KUtil.isEmpty(gm.toString())) { + continue; + } + /* + * if(!gm.isActive()) { System.out.println("���Ա�ǻ�?"+gm); continue; } + */ + if (!res.contains(gm)) { + System.out.println("Add Group Member: " + gm); + res.add(gm); + } else { + System.out.println("Added: " + gm); + } + } + } + return res.toArray(new TCComponent[] {}); + } + + public static int compareWBS(String wbsCode, String wbsCode2) { + if (KUtil.isEmpty(wbsCode) && KUtil.isEmpty(wbsCode2)) { + return 0; + } + if (KUtil.isEmpty(wbsCode)) { + return -1; + } + if (KUtil.isEmpty(wbsCode2)) { + return 1; + } + String[] a = wbsCode.split("\\."); + String[] b = wbsCode2.split("\\."); + int lenA = a.length; + int lenB = b.length; + for (int i = 0; i < lenA && i < lenB; i++) { + String aa = a[i]; + String bb = b[i]; + int ai = 0; + int bi = 0; + try { + ai = Integer.parseInt(aa); + bi = Integer.parseInt(bb); + } catch (Exception e) { + e.printStackTrace(); + } + if (ai != bi) { + return ai - bi; + } + } + return lenA - lenB; + } + + public static TCComponentListOfValues getLov(String lovName) { + TCComponentListOfValuesType lovType; + try { + lovType = (TCComponentListOfValuesType) session.getTypeComponent("ListOfValues"); + TCComponentListOfValues[] lov = lovType.find(lovName); + if (lov.length > 0) + return lov[0]; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static String[] getDynamicLOV(String s) { + TCComponentListOfValues lov = null; + List lovDisplayValueList = new ArrayList<>(); + lovDisplayValueList.add(""); + List lovValueList = new ArrayList<>(); + lov = TCComponentListOfValuesType.findLOVByName(s); + try { + if ("Fnd0ListOfValuesDynamic".equals(lov.getProperty("lov_type"))) { + LOVService lovService = LOVService.getService(RACUIUtil.getTCSession()); + 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]); + } + } + } + } catch (TCException e) { + e.printStackTrace(); + } + return lovDisplayValueList.toArray(new String[lovDisplayValueList.size()]); + } + + public static String getLovValue(TCComponentListOfValues lov, String str) throws Exception { + return getLovValue(lov, str, true); + } + + public static String getLovValue(TCComponentListOfValues lov, String str, boolean translate) throws Exception { + if (lov == null || KUtil.isEmpty(str)) { + return str; + } + if (translate) { + String prefName = "LOV_TRANS_" + lov.getStringProperty(TCComponentListOfValues.PROP_LOV_NAME); + String[] prefVals = KUtil.getPrefVals(KUtil.session, prefName); + int len = KUtil.getLen(prefVals); + for (int i = 0; i < len; i++) { + String pref = prefVals[i]; + int ind = pref.indexOf('='); + if (ind > 0) { + String realVal = pref.substring(0, ind); + String disVal = pref.substring(ind + 1); + if (str.equals(realVal) || str.equals(disVal)) { + return realVal; + } + } + } + } + ListOfValuesInfo info = lov.getListOfValues(); + if (info == null) { + return str; + } + List v = info.getValues(); + int size = v == null ? 0 : v.size(); + for (int i = 0; i < size; i++) { + LovValue vv = v.get(i); + String realValue = vv.getValue() == null ? "" : vv.getValue().toString(); + if (str.equals(realValue)) { + return str; + } + String disValue = vv.getDisplayValue(); + if (str.equals(disValue)) { + return realValue; + } + } + throw new Exception(String.format(KLocale.getString("valuenotinlov.ERROR2"), lov.toString(), str)); + } + + public static String getLovDisplayableValue(TCComponentListOfValues lov, String str) throws Exception { + if (lov == null || KUtil.isEmpty(str)) { + return str; + } + ListOfValuesInfo info = lov.getListOfValues(); + if (info == null) { + return str; + } + List v = info.getValues(); + int size = v == null ? 0 : v.size(); + for (int i = 0; i < size; i++) { + LovValue vv = v.get(i); + String realValue = vv.getValue() == null ? "" : vv.getValue().toString(); + if (str.equals(realValue)) { + return vv.getDisplayValue(); + } + String disValue = vv.getDisplayValue(); + if (str.equals(disValue)) { + return str; + } + } + throw new Exception(String.format(KLocale.getString("valuenotinlov.ERROR2"), lov.toString(), str)); + } + + public static void openFile(File file) { + try { + if (file != null && file.exists()) { + Runtime.getRuntime().exec("cmd /c start /b call \"" + file.getAbsolutePath() + "\""); + } + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(e); + } + } + + public static void importDataset(TCComponent parent, String rel, File f, String dsType, String refName) + throws Exception { + if (f == null || !f.exists() || KUtil.isEmpty(dsType) || KUtil.isEmpty(refName)) { + return; + } + TCComponentDatasetType datasetType = (TCComponentDatasetType) session.getTypeComponent(dsType); + TCComponentDataset dataset = datasetType.create(f.getName(), "", dsType); + String paths[] = { f.getAbsolutePath() }; + String refs[] = { refName }; + dataset.setFiles(paths, refs); + if (parent != null && !KUtil.isEmpty(rel)) { + parent.add(rel, dataset); + } + } + + public static void initPropMap(String propConfig, String value, Map itemPropMap, + Map itemMasterPropMap, Map revPropMap, Map revMasterPropMap) + throws Exception { + initPropMap(propConfig, value, itemPropMap, itemMasterPropMap, revPropMap, revMasterPropMap, null); + } + + public static void initPropMap(String propConfig, String value, Map itemPropMap, + Map itemMasterPropMap, Map revPropMap, Map revMasterPropMap, + Map bomlinePropMap) throws Exception { + if (KUtil.isEmpty(propConfig)) { + return; + } + String propFrom = null, propName = null; + String[] split = propConfig.split("\\."); + if (KUtil.getLen(split) == 2) { + propFrom = split[0].trim().toUpperCase(); + propName = split[1].trim(); + } + if (KUtil.isEmpty(propFrom) || KUtil.isEmpty(propName)) { + return; + } + Map target; + if ("ITEM".equals(propFrom)) { + target = itemPropMap; + System.out.println(">> ITEM PROP: " + propName + " = " + value); + } else if ("REV".equals(propFrom)) { + System.out.println(">> REV PROP: " + propName + " = " + value); + target = revPropMap; + } else if ("ITEMMASTER".equals(propFrom)) { + System.out.println(">> ITEMMASTER PROP: " + propName + " = " + value); + target = itemMasterPropMap; + } else if ("REVMASTER".equals(propFrom)) { + System.out.println(">> REVMASTER PROP: " + propName + " = " + value); + target = revMasterPropMap; + } else if ("BOMLINE".equals(propFrom)) { + System.out.println(">> BOMLINE PROP: " + propName + " = " + value); + target = bomlinePropMap; + } else { + throw new Exception(String.format(KLocale.getString("proplocationnotdefined.ERROR1"), propFrom)); + } + if (target == null) { + return; + } + target.put(propName, value); + } + + public static String getMarkedPropValue(String config, Map markedComponents) throws Exception { + return getMarkedPropValue(config, markedComponents, null); + } + + public static String getMarkedPropValue(String config, Map markedComponents, + Map> relatedComponents) throws Exception { + if (markedComponents == null || KUtil.isEmpty(config)) { + return ""; + } + StringBuilder res = new StringBuilder(); + String[] propConfigSplit = config.split("\\+"); + int len = KUtil.getLen(propConfigSplit); + for (int i = 0; i < len; i++) { + String propConfig = propConfigSplit[i]; + String propFrom = null, propName = null; + String defaultValue = ""; + String[] split = propConfig.split("\\."); + if (KUtil.getLen(split) >= 2) { + propFrom = split[0].trim().toUpperCase(); + propName = split[1].trim(); + } + if (KUtil.getLen(split) >= 3) { + defaultValue = split[2].trim(); + } + if (KUtil.isEmpty(propFrom) || KUtil.isEmpty(propName)) { + if (propConfig.contains("\\n")) { + propConfig = propConfig.replace("\\n", "\n"); + } + res.append(propConfig); + continue; + } + if (!markedComponents.containsKey(propFrom)) { + if (propFrom.startsWith("T")) { + return ""; + } + continue; + } + TCComponent comp = markedComponents.get(propFrom); + // λ.-[-ӷ] + int ind = propName.indexOf('-'); + if (ind > 0) { + String tableProp = propName.substring(0, ind).trim(); + String tableRowProp = propName.substring(ind + 1).trim(); + if (!KUtil.isEmpty(tableProp) && !KUtil.isEmpty(tableRowProp)) { + TCProperty prop = comp.getTCProperty(tableProp.trim()); + if (prop == null) { + throw new Exception(String.format(KLocale.getString("propnotdefinedintype.ERROR2"), + comp.getType(), propName)); + } + String rowSplitter = "#ROW#"; + ind = tableRowProp.indexOf('-'); + if (ind > 0) { + rowSplitter = tableRowProp.substring(ind + 1); + tableRowProp = tableRowProp.substring(0, ind); + } + TCComponent[] tableRows = prop.getReferenceValueArray(); + int rowCnt = KUtil.getLen(tableRows); + String[] value = new String[rowCnt]; + for (int j = 0; j < rowCnt; j++) { + value[j] = tableRows[j].getPropertyDisplayableValue(tableRowProp); + } + res.append(String.join(rowSplitter, value)); + } + continue; + } + TCProperty prop = comp.getTCProperty(propName.trim()); + if (prop == null) { + throw new Exception( + String.format(KLocale.getString("propnotdefinedintype.ERROR2"), comp.getType(), propName)); + } + String value = prop.getDisplayableValue(); + if ("NAME".equalsIgnoreCase(defaultValue)) { + value = prop.getPropertyDisplayName(); + } else if (value == null || "".equals(value)) { + value = defaultValue; + } + res.append(value); + } + return res.toString(); + } + + public static TCComponent getLatestComponent(List comps) { + int size = comps == null ? 0 : comps.size(); + if (size == 0) { + return null; + } + if (size == 1) { + return comps.get(0); + } + TCComponent res = comps.get(0); + try { + Date maxDate = res.getDateProperty("creation_date"); + for (int i = 1; i < size; i++) { + TCComponent temp = comps.get(i); + Date tempDate = temp.getDateProperty("creation_date"); + if (tempDate.after(maxDate)) { + maxDate = tempDate; + res = temp; + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return res; + } + + public static TCComponentType[] getComponentTypes(String itemTypeName) throws Exception { + TCComponentItemType itemType = null; + try { + itemType = (TCComponentItemType) session.getTypeComponent(itemTypeName); + } catch (Exception e) { + e.printStackTrace(); + } + if (itemType == null) { + throw new Exception(String.format(KLocale.getString("typenotfound.ERROR1"), itemTypeName)); + } + TCComponentItemRevisionType revType = itemType.getItemRevisionType(); + if (revType == null) { + throw new Exception(String.format(KLocale.getString("typenotfound.ERROR1"), itemTypeName + "Revision")); + } + TCComponentType itemMasterType = null; + try { + itemMasterType = session.getTypeComponent(itemTypeName + "Master"); + } catch (Exception e) { + e.printStackTrace(); + } + if (itemMasterType == null) { + try { + itemMasterType = session.getTypeComponent(itemTypeName + " Master"); + } catch (Exception e) { + e.printStackTrace(); + } + } + if (itemMasterType == null) { + throw new Exception(String.format(KLocale.getString("typenotfound.ERROR1"), itemTypeName + "Master")); + } + TCComponentType revMasterType = null; + try { + revMasterType = session.getTypeComponent(revType.getTypeName() + "Master"); + } catch (Exception e) { + e.printStackTrace(); + } + if (revMasterType == null) { + try { + revMasterType = session.getTypeComponent(revType.getTypeName() + " Master"); + } catch (Exception e) { + e.printStackTrace(); + } + } + if (revMasterType == null) { + throw new Exception( + String.format(KLocale.getString("typenotfound.ERROR1"), revType.getTypeName() + "Master")); + } + return new TCComponentType[] { itemType, revType, itemMasterType, revMasterType }; + } + + public static String getPropertyDisplayName(TCComponentType type, String propName) throws Exception { + if (type == null || KUtil.isEmpty(propName)) { + return propName; + } + TCPropertyDescriptor desc = type.getPropDesc(propName); + if (desc == null) { + throw new Exception(String.format(KLocale.getString("propnotdefinedintype.ERROR2"), + type.getDisplayTypeName(), propName)); + } + return desc.getDisplayName(); + } + + public static String getConfigPropValue(TCComponentItemRevision rev, String propConfigStr) throws Exception { + if (rev == null || KUtil.isEmpty(propConfigStr)) { + return ""; + } + StringBuilder res = new StringBuilder(); + String[] propConfigSplit = propConfigStr.split("\\+"); + int len = KUtil.getLen(propConfigSplit); + for (int i = 0; i < len; i++) { + String propConfig = propConfigSplit[i]; + String propFrom = null, propName = null; + String[] split = propConfig.split("\\."); + if (KUtil.getLen(split) == 2) { + propFrom = split[0].trim().toUpperCase(); + propName = split[1].trim(); + } + if (KUtil.isEmpty(propFrom) || KUtil.isEmpty(propName)) { + res.append(propConfig); + continue; + } + TCComponent target; + if ("ITEM".equals(propFrom)) { + target = rev.getItem(); + } else if ("REV".equals(propFrom)) { + target = rev; + } else if ("ITEMMASTER".equals(propFrom)) { + target = rev.getItem().getRelatedComponent("IMAN_master_form"); + } else if ("REVMASTER".equals(propFrom)) { + target = rev.getRelatedComponent("IMAN_master_form_rev"); + } else { + throw new Exception(String.format(KLocale.getString("proplocationnotdefined.ERROR1"), propFrom)); + } + TCProperty prop = target.getTCProperty(propName.trim()); + if (prop == null) { + throw new Exception( + String.format(KLocale.getString("propnotdefinedintype.ERROR2"), target.getType(), propName)); + } + res.append(prop.getStringValue()); + } + return res.toString(); + } + + public static String getConfigPropDisplayableValue(TCComponentItemRevision rev, String propConfigStr) + throws Exception { + if (rev == null || KUtil.isEmpty(propConfigStr)) { + return ""; + } + StringBuilder res = new StringBuilder(); + String[] propConfigSplit = propConfigStr.split("\\+"); + int len = KUtil.getLen(propConfigSplit); + for (int i = 0; i < len; i++) { + String propConfig = propConfigSplit[i]; + String propFrom = null, propName = null; + String[] split = propConfig.split("\\."); + if (KUtil.getLen(split) == 2) { + propFrom = split[0].trim().toUpperCase(); + propName = split[1].trim(); + } + if (KUtil.isEmpty(propFrom) || KUtil.isEmpty(propName)) { + res.append(propConfig); + continue; + } + TCComponent target; + if ("ITEM".equals(propFrom)) { + target = rev.getItem(); + } else if ("REV".equals(propFrom)) { + target = rev; + } else if ("ITEMMASTER".equals(propFrom)) { + target = rev.getItem().getRelatedComponent("IMAN_master_form"); + } else if ("REVMASTER".equals(propFrom)) { + target = rev.getRelatedComponent("IMAN_master_form_rev"); + } else { + throw new Exception(String.format(KLocale.getString("proplocationnotdefined.ERROR1"), propFrom)); + } + TCProperty prop = target.getTCProperty(propName.trim()); + if (prop == null) { + throw new Exception( + String.format(KLocale.getString("propnotdefinedintype.ERROR2"), target.getType(), propName)); + } + res.append(prop.getDisplayableValue()); + } + return res.toString(); + } + + public static void removeAllParents(DataManagementService dm, TCComponent comp) throws Exception { + comp.refresh(); + System.out.println("Remove from parent: " + comp); + WhereReferencedResponse refResp = dm.whereReferenced(new TCComponent[] { comp }, 1); + KUtil.throwServiceDataError(refResp.serviceData); + int len = KUtil.getLen(refResp.output); + List datas = new ArrayList(); + for (int i = 0; i < len; i++) { + WhereReferencedOutput ref = refResp.output[i]; + int cnt = KUtil.getLen(ref.info); + for (int j = 0; j < cnt; j++) { + WhereReferencedInfo info = ref.info[j]; + Relationship data = new Relationship(); + data.primaryObject = info.referencer; + data.secondaryObject = comp; + data.relationType = info.relation; + System.out.println(">> " + info.relation + " | " + info.referencer); + datas.add(data); + } + } + ServiceData resp = dm.deleteRelations(datas.toArray(new Relationship[] {})); + KUtil.throwServiceDataError(resp); + } + + public static TCComponent newTableRow(DataManagementService dmService, String type, + Map rowStringProps, Map rowDateProps) throws Exception { + CreateIn rowIn = new CreateIn(); + CreateInput rowInput = new CreateInput(); + rowInput.boName = type; + if (rowStringProps != null) { + rowInput.stringProps = rowStringProps; + } + if (rowDateProps != null) { + rowInput.dateProps = rowDateProps; + } + rowIn.data = rowInput; + CreateResponse res = dmService.createObjects(new CreateIn[] { rowIn }); + KUtil.throwServiceDataError(res.serviceData); + if (res.serviceData.sizeOfCreatedObjects() > 0) { + return res.serviceData.getCreatedObject(0); + } + return null; + } + + public static Date addDay(Date day, int cnt) { + if (day == null) { + return null; + } + Calendar c = Calendar.getInstance(); + c.setTime(day); + c.add(Calendar.DATE, cnt); + return c.getTime(); + } + + public static Date calTime(TCCalendar calendar, Date date, int minutes) { + if (calendar == null || date == null) { + return null; + } + int diff = minutes > 0 ? 1 : -1; + if (minutes < 0) { + minutes = -minutes; + } + Calendar c = Calendar.getInstance(); + c.setTime(date); + int counter = 0; + while (counter < minutes) { + counter += calendar.getMinutesOnDay(c); + c.add(Calendar.DATE, diff); + } + return c.getTime(); + } + + public static int getMinutesBetween(TCCalendar calendar, Date start, Date end) { + if (calendar == null || start == null || end == null) { + return 0; + } + Calendar c = Calendar.getInstance(); + c.setTime(start); + int res = 0; + while (c.getTime().before(end)) { + res += calendar.getMinutesOnDay(c); + // System.out.println(calendar.getMinutesOnDay(c)+" > "+c.getTime()); + c.add(Calendar.DATE, 1); + } + return res; + } + + public static TCComponentTCCalendar getScheduleCalendar(TCComponentSchedule schedule) throws Exception { + if (schedule == null) { + return null; + } + return CalendarHelper.getScheduleCalendar(schedule, session); + } + + public static void dealSpecialModelValue(ArrayList specialList, String prefName, String prop, int ind) { + int index = 0; + + try { + String[] prefVals = KUtil.getPrefVals(session, prefName); + String puid = prefVals[ind]; + TCComponent component = session.stringToComponent(puid); + if (component instanceof TCComponentForm) { + + TCComponentForm form = (TCComponentForm) component; + + TCComponent[] tables = form.getReferenceListProperty("ld6_ChangeTable"); + for (int j = 0; j < tables.length; j++) { + + String change = tables[j].getStringProperty(prop); + if (change.equals("")) { + specialList.add(j); + } + } + + } + +// +// Set>> entrySet = map.entrySet(); +// for (Entry> entry : entrySet) { +// ArrayList list = entry.getValue(); +// String value = list.get(2); +// System.out.println("ǰֵΪ" + value); +// if(value != null && value.equals("")) { +// specialList.add(index); +// } +// index++; +// } + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + /** + * õģֵ + * + * @param map + * @throws Exception + */ +// public static void getModelVale(LinkedHashMap> map,String prefName,int index) throws Exception { +// AbstractAIFApplication application = AIFUtility.getCurrentApplication(); +// TCSession session = (TCSession) application.getSession(); +// String[] prefVals = KUtil.getPrefVals(session, prefName); +// String puid = prefVals[index]; +// TCComponentDataset component = (TCComponentDataset) session.stringToComponent(puid); +// TCComponentTcFile[] tcFiles = component.getTcFiles(); +// File datasetFile = null; +// String name = ""; +// if (tcFiles != null && tcFiles.length != 0) { +// TCComponentTcFile tcComponentTcFile = tcFiles[0]; +// File fmsFile = tcComponentTcFile.getFmsFile(); +// name = tcComponentTcFile.getStringProperty("original_file_name"); +// datasetFile = new File(System.getenv("TEMP")+"\\"+name); +// FileUtility.copyFile(fmsFile, datasetFile); +// +// } +// XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(datasetFile)); +// XSSFSheet sheet = wb.getSheetAt(0); +// for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) { +// XSSFRow row = sheet.getRow(i); +// for (int j = 0; j < 5; j++) { +// XSSFCell cell = row.getCell(j); +// if(cell != null) { +// String cellValue = KUtil.getCellValue(cell); +// if(j == 0 && cellValue.isEmpty()) { +// break; +// } +// if(j == 0 ) { +// if(map.containsKey(cellValue)) { +// break; +// }else { +// map.put(cellValue, null); +// } +// }else { +// String key = KUtil.getCellValue(row.getCell(0)); +// ArrayList arrayList = map.get(key); +// if(arrayList != null) { +// arrayList.add(cellValue); +// }else { +// ArrayList list = new ArrayList(); +// list.add(cellValue); +// map.put(key, list); +// } +// } +// +// } +// } +// } +// wb.close(); +// datasetFile.delete(); +// } + /** + * õģֵ + * + * @param map + * @throws Exception + */ + public static void getModelVale(LinkedHashMap> map, TCComponent forms, + ArrayList specialList, String[] propNames) throws Exception { +// AbstractAIFApplication application = AIFUtility.getCurrentApplication(); +// TCSession session = (TCSession) application.getSession(); +// String[] prefVals = KUtil.getPrefVals(session, prefName); +// String puid = prefVals[index]; +// TCComponent component = session.stringToComponent(puid); + int t = 1; + if (forms instanceof TCComponentForm) { + + TCComponentForm form = (TCComponentForm) forms; + TCComponent[] tables = form.getReferenceListProperty("ld6_ChangeTable"); + for (int j = 0; j < tables.length; j++) { + ArrayList tableValue = new ArrayList(); + + for (String propName : propNames) { + System.out.println("ǰΪ" + propName); + String prop = tables[j].getTCProperty(propName).getDisplayableValue(); + if (propName.equals("ld6_YNChange") && prop.equals("")) { +// specialList.add(j); + } + tableValue.add(prop == null ? "" : prop.trim()); + } + + map.put(String.valueOf(t), tableValue); +// tableValue + + t = t + 1; + } + + } + + } + + /** + * õlovʵֵʾֵ + * + * @param lovMap + * @param comboBox + * @throws TCException + */ + public static void getLov(HashMap lovMap, String lovName, JComboBox comboBox) + throws TCException { + if (comboBox != null) { + comboBox.addItem(""); + } +// for (LovValue lovV : lovValueList) { +// map.put(lovV.getDisplayValue(), lovV.getStringValue()); +// comboBox.addItem(lovV.getDisplayValue()); +// System.out.println(lovV.getDisplayValue() + "===" + lovV.getStringValue()); +// } + + TCComponentListOfValues lov = TCComponentListOfValuesType.findLOVByName(lovName); + if ("Fnd0ListOfValuesDynamic".equals(lov.getProperty("lov_type"))) { + System.out.println("̬lovName=" + lovName); + LOVService lovService = LOVService.getService(RACUIUtil.getTCSession()); + InitialLovData input = new InitialLovData(); + LovFilterData filter = new LovFilterData(); + if ("LD6_TecDoc_TypeLOV".equals(lovName)) { + filter.sortPropertyName = "fnd0StringValues"; // lovĺֵ̨ + } else { + filter.sortPropertyName = "object_name"; // lovĺֵ̨ + } + + filter.order = 1; + filter.numberToReturn = 2000; + filter.maxResults = 2000; + + input.lov = lov; + input.filterData = filter; + LOVSearchResults result = lovService.getInitialLOVValues(input); + // System.out.println("111==="+result.toString()); + + for (LOVValueRow row : result.lovValues) { + Map map = row.propDisplayValues; + Map realmap = row.propInternalValues; +// for (String key : map.keySet()) { +// System.out.println("key=" + key + ",value=" + map.get(key)[0]); +// } +// for (String key : realmap.keySet()) { +// System.out.println("key2=" + key + ",value2=" + map.get(key)[0]); +// } + String disval = ""; + String val = ""; + String key1 = "object_name";// ʵֵ ʾֵһ + if ("LD6_TecDoc_TypeLOV".equals(lovName)) { + key1 = "fnd0StringValues"; // lovĺֵ̨ + } + // String key2 = "object_desc";// ʾֵڶ + if (map.containsKey(key1)) { + val = realmap.get(key1)[0]; + disval = map.get(key1)[0]; + } + if (!val.equals("")) { + lovMap.put(disval, val); + if (comboBox != null) { + comboBox.addItem(disval); + } + } + + } + + } else { + ListOfValuesInfo info = lov.getListOfValues(); + info.getLOVDisplayValues(); + List lovValueList = info.getValues(); + for (LovValue lovV : lovValueList) { + lovMap.put(lovV.getDisplayValue(), lovV.getStringValue()); + if (comboBox != null) { + comboBox.addItem(lovV.getDisplayValue()); + } + } + } + + } + + + +} diff --git a/src/com/langtech/plm/mpart/CheckHeaderCellRenderer.java b/src/com/langtech/plm/mpart/CheckHeaderCellRenderer.java new file mode 100644 index 0000000..47d7268 --- /dev/null +++ b/src/com/langtech/plm/mpart/CheckHeaderCellRenderer.java @@ -0,0 +1,72 @@ +package com.langtech.plm.mpart; + +import java.awt.Component; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +import javax.swing.JCheckBox; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JTable; +import javax.swing.SwingConstants; +import javax.swing.UIManager; +import javax.swing.table.DefaultTableModel; +import javax.swing.table.JTableHeader; +import javax.swing.table.TableCellRenderer; + +public class CheckHeaderCellRenderer implements TableCellRenderer { + DefaultTableModel tableModel; + JTableHeader tableHeader; + final JCheckBox selectBox; + + public CheckHeaderCellRenderer(final JTable table) { + this.tableModel = (DefaultTableModel) table.getModel(); + this.tableHeader = table.getTableHeader(); + selectBox = new JCheckBox(tableModel.getColumnName(0)); + selectBox.setSelected(false); + tableHeader.addMouseListener(new MouseAdapter() { + public void mouseClicked(MouseEvent e) { + if (e.getClickCount() > 0) { + // ѡ + int selectColumn = tableHeader.columnAtPoint(e.getPoint()); + if (selectColumn == 0) { + boolean value = !selectBox.isSelected(); + selectBox.setSelected(value); +// tableModel.selectAllOrNull(value); + tableHeader.repaint(); + if(value) { + for(int i=0;i objectComboBox; + private JButton okButton = new JButton("ȷ"); + private JButton concelButton = new JButton("ȡ"); + private HashMap fieldMap = new HashMap(); + private String revType = ""; + HashMap objectMap = new HashMap(); + + public ChoosePartDialog(JComboBox objectComboBox,AIFDesktop aifDesktop) { + // TODO Auto-generated constructor stub + this.objectComboBox = objectComboBox; + initUI(); + } + + private void initUI() { + // TODO Auto-generated method stub + try { + this.setTitle("ѡBOM"); + this.setLayout(new BorderLayout()); + + JPanel topPanel = getTopPanel(); + + JPanel btnPanel = getBtnPanel(); + + this.add(topPanel, BorderLayout.NORTH); + // this.add(pane,BorderLayout.CENTER); + this.add(btnPanel, BorderLayout.SOUTH); + this.setPreferredSize(new Dimension(550, 200)); + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); // ȡĻߴ + int screenWidth = screenSize.width; // ȡĻ + int screenHeight = screenSize.height; // ȡĻ߶ + int x = (screenWidth - 550) / 2; // FrameϽx + int y = (screenHeight - 300) / 2; // FrameϽy + this.setLocation(x, y); // Frameλ + + // this.setLocationRelativeTo(null); + this.createActionEvent(); + this.pack(); + + // this.validate(); + this.setVisible(true); + +// this.setAlwaysOnTop(true); + + + + } catch (Exception e) { + e.printStackTrace(); + return; + } + } + + // Ӽ + public void createActionEvent() { + + this.okButton.addActionListener(this); + this.concelButton.addActionListener(this); + } + + @Override + public void actionPerformed(ActionEvent e) { + // TODO Auto-generated method stub + + Object source = e.getSource(); + System.out.println("source==>+" + source); + if (this.okButton.equals(source)) { + this.dispose(); + + } else if (this.concelButton.equals(source)) { + this.dispose(); + } + + } + + private JPanel getBtnPanel() { + JPanel topPanel = new JPanel(); + topPanel.setLayout(new PropertyLayout()); + topPanel.add("1.1.center", new JLabel("")); + topPanel.add("2.1.center", new JLabel(" ")); + topPanel.add("2.2.center", okButton); + topPanel.add("2.3.center", new JLabel("")); + topPanel.add("2.4.center", concelButton); + + return topPanel; + } + + // ѯ + private JPanel getTopPanel() { + // TODO Auto-generated method stub + JPanel topPanel = new JPanel(); + topPanel.setLayout(new PropertyLayout()); + topPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); + + topPanel.add("1.1.left.center", new JLabel("")); + topPanel.add("2.1.left.center", new JLabel("")); + topPanel.add("3.1.left.center", new JLabel("")); + topPanel.add("4.1.left.center", new JLabel("")); + topPanel.add("5.1.left.center", new JLabel("")); + topPanel.add("6.1.left.center", new JLabel("")); + topPanel.add("7.1.left.center", new JLabel("ѡԴ")); + topPanel.add("7.2.left.center", objectComboBox); + + return topPanel; + } + +} diff --git a/src/com/langtech/plm/mpart/DialogFrame.java b/src/com/langtech/plm/mpart/DialogFrame.java new file mode 100644 index 0000000..2140534 --- /dev/null +++ b/src/com/langtech/plm/mpart/DialogFrame.java @@ -0,0 +1,50 @@ +package com.langtech.plm.mpart; +import javax.swing.*; + +import com.sun.scenario.effect.impl.hw.d3d.D3DShaderSource; +import com.teamcenter.rac.util.MessageBox; + +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.ArrayList; +import java.util.LinkedHashMap; + +public class DialogFrame extends JDialog { + + private JComboBox comboBox; + private Object syncObject; + public DialogFrame(JFrame owner,JComboBox comboBox,ArrayList list) { + super(owner, "Dialog Window", true); // ģ̬Ի + this.comboBox = comboBox; + this.syncObject = syncObject; + JButton button = new JButton("ȷ"); + button.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + String selectedItem =(String) comboBox.getSelectedItem(); + if(selectedItem == null || selectedItem.isEmpty()) { + MessageBox.post("ѡݣ", "ʾ ", MessageBox.INFORMATION); + }else { + + System.out.println("Selected Item: " + selectedItem); + list.add(selectedItem); + dispose(); // رնԻ + + } + + } + }); + this.setPreferredSize(new Dimension(300,100)); + JPanel panel = new JPanel(); + panel.setLayout(new FlowLayout()); + panel.add(new JLabel("ѡ")); + panel.add(comboBox); + panel.add(button); + + this.add(panel); + this.pack(); + this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); + this.setLocationRelativeTo(owner); // ʾ + } +} \ No newline at end of file diff --git a/src/com/langtech/plm/mpart/MainFrame.java b/src/com/langtech/plm/mpart/MainFrame.java new file mode 100644 index 0000000..835c141 --- /dev/null +++ b/src/com/langtech/plm/mpart/MainFrame.java @@ -0,0 +1,95 @@ +package com.langtech.plm.mpart; +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.ArrayList; + +public class MainFrame extends JFrame { + + private JTextField textField; + private Object syncObject = new Object(); + public MainFrame() { + super("Main Window"); + + textField = new JTextField(20); + JButton button = new JButton("Open Dialog"); + ArrayList childrenList = new ArrayList(); + button.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + // ʾģ̬Ի + JComboBox a = new JComboBox(); + a.addItem("1"); + System.out.println("0"); + System.out.println(syncObject); + + + + for (int i = 0; i < 5; i++) { + DialogFrame dialog = new DialogFrame(MainFrame.this,a,childrenList); + dialog.setVisible(true); + // ȴԻرպִеIJ + dialog.addWindowListener(new java.awt.event.WindowAdapter() { + @Override + public void windowClosed(java.awt.event.WindowEvent e) { + + System.out.println("21121212"); + } + }); + } + + + System.out.println("2"); + + System.out.println(childrenList.size()); + + + +// DialogFrame dialog = new DialogFrame(MainFrame.this,a,syncObject); +// dialog.setVisible(true); +// // ȴԻرպִеIJ +// dialog.addWindowListener(new java.awt.event.WindowAdapter() { +// @Override +// public void windowClosed(java.awt.event.WindowEvent e) { +// +// System.out.println("1"); +// } +// }); +// System.out.println("2"); +// synchronized (syncObject) { +// +// try { +// // Wait until notified +// System.out.println("4"); +// syncObject.wait(); +// +// } catch (InterruptedException ex) { +// Thread.currentThread().interrupt(); // Restore interrupted status +// System.err.println("Thread was interrupted."); +// } +// System.out.println("2"); +// +// } + System.out.println("3"); + } + }); + + JPanel panel = new JPanel(); + panel.setLayout(new FlowLayout()); + panel.add(textField); + panel.add(button); + + this.add(panel); + this.pack(); + this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + this.setLocationRelativeTo(null); // ʾ + } + + public static void main(String[] args) { + EventQueue.invokeLater(() -> { + MainFrame frame = new MainFrame(); + frame.setVisible(true); + }); + } +} \ No newline at end of file diff --git a/src/com/langtech/plm/mpart/MpartDialog.java b/src/com/langtech/plm/mpart/MpartDialog.java new file mode 100644 index 0000000..6f1cbb6 --- /dev/null +++ b/src/com/langtech/plm/mpart/MpartDialog.java @@ -0,0 +1,931 @@ +package com.langtech.plm.mpart; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Toolkit; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map.Entry; + +import javax.swing.BorderFactory; +import javax.swing.DefaultCellEditor; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.JTextField; +import javax.swing.SwingUtilities; +import javax.swing.border.EmptyBorder; +import javax.swing.table.DefaultTableModel; +import javax.swing.table.TableColumn; +import javax.swing.table.TableColumnModel; + +import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode; + +import com.teamcenter.rac.aif.AIFDesktop; +import com.teamcenter.rac.aif.kernel.AIFComponentContext; +import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentBOMLine; +import com.teamcenter.rac.kernel.TCComponentBOMWindow; +import com.teamcenter.rac.kernel.TCComponentBOMWindowType; +import com.teamcenter.rac.kernel.TCComponentForm; +import com.teamcenter.rac.kernel.TCComponentGroup; +import com.teamcenter.rac.kernel.TCComponentItem; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCComponentItemType; +import com.teamcenter.rac.kernel.TCComponentScheduleTask; +import com.teamcenter.rac.kernel.TCComponentUser; +import com.teamcenter.rac.kernel.TCException; +import com.teamcenter.rac.kernel.TCProperty; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; +import com.teamcenter.rac.util.PropertyLayout; + +import k.util.KOrgDialog; + +public class MpartDialog extends JFrame implements ActionListener { + + private TCSession session; + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + private ArrayList list; + private JTextField find = new JTextField(); + private JTextField replace = new JTextField(); + private JButton xrButton = new JButton("ѡ"); + private JButton createButton = new JButton("Mpartֹ"); + private JButton viewlButton = new JButton("鿴M"); + private JTable t_part; + private JComboBox gsdwComboBox = new JComboBox(); + protected DefaultTableModel tm_part; + public static final String[] HEADER = new String[] { "","", "ID", "", "", "Ƿ", "ǷM", "λ", "С", ""}; + public static final int[] HEADERWIDTH = new int[] { 30,40, 60, 120, 100, 60, 60, 60, 60, 100}; + private JTable t_part2; + protected DefaultTableModel tm_part2; + public static final String[] HEADER2 = new String[] {"", ""}; + public static final int[] HEADERWIDTH2 = new int[] {10, 60}; + private ArrayList> valueList = new ArrayList>(); + private HashMap objectMap = new HashMap(); + private ArrayList table2RevList = new ArrayList(); + TCComponentBOMWindowType viewType; + TCComponentBOMWindow view; + TCComponentItemType type; + private String[] groupSplit; + + public MpartDialog(TCSession session, ArrayList list) throws TCException { + // TODO Auto-generated constructor stub + this.session = session; + this.list = list; + viewType = (TCComponentBOMWindowType) session.getTypeComponent("BOMWindow"); + view = viewType.create(null); + type = (TCComponentItemType) session.getTypeComponent("LY6_ProductM"); + initUI(); + } + + private void initUI() { + // TODO Auto-generated method stub + try { + gsdwComboBox.addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent e) { + if (e.getStateChange() == ItemEvent.SELECTED) { + String selectedItem = (String) gsdwComboBox.getSelectedItem(); + System.out.println("Selected Item: " + selectedItem); + // ִ + int count = 0; + for(int i=0;i tempList = new ArrayList(); + tempList.add(0); + tempList.add(i+1); + TCComponentItemRevision tcComponentItemRevision = list.get(i); + String revId = tcComponentItemRevision.getStringProperty("item_id"); + String object_name = tcComponentItemRevision.getStringProperty("object_name"); + String ly6_partNum = tcComponentItemRevision.getStringProperty("ly6_partNum"); + String ly6_homemadeStatus = tcComponentItemRevision.getStringProperty("ly6_homemadeStatus"); + tempList.add(revId); + tempList.add(object_name); + tempList.add(ly6_partNum); + tempList.add(ly6_homemadeStatus); + if(factory != null && !factory.isEmpty()) { + ArrayList mrevList = new ArrayList(); + + String[] split = factory.split(";"); + + for (int j = 0; j < split.length; j++) { + + TCComponent[] search = session.search("_SearchMFKProperties", new String[] { "ID","" }, new String[] { revId,split[j] }); + if(search.length > 0) { + + for (int k = 0; k < search.length; k++) { + TCComponentItem item = (TCComponentItem)search[k]; + mrevList.add(item.getLatestItemRevision()); + } + } + } + if(mrevList.size() <= 0) { + tempList.add(""); + tempList.add(""); + tempList.add(null); + tempList.add(tcComponentItemRevision); + }else { + tempList.add(""); + tempList.add(""); + tempList.add(mrevList); + tempList.add(tcComponentItemRevision); + } + }else { + tempList.add(""); + tempList.add(""); + tempList.add(null); + tempList.add(tcComponentItemRevision); + } + System.out.println("tempList.size============"+tempList.size()); + valueList.add(tempList); + } + + System.out.println("valueList================"+valueList.size()); + for (int j = 0; j < valueList.size(); j++) { + ArrayList arrayList = valueList.get(j); + + tm_part.addRow(new Object[] {arrayList.get(0),arrayList.get(1),arrayList.get(2), + arrayList.get(3),arrayList.get(4),arrayList.get(5),arrayList.get(6), + arrayList.get(7),"",""}); + } + + + + + + } catch (Exception e) { + e.printStackTrace(); + return; + } + } + + // Ӽ + public void createActionEvent() { + + this.createButton.addActionListener(this); + this.viewlButton.addActionListener(this); + this.xrButton.addActionListener(this); + this.gsdwComboBox.addActionListener(this); + } + + @Override + public void actionPerformed(ActionEvent e) { + // TODO Auto-generated method stub + + Object source = e.getSource(); + System.out.println("source==>+" + source); + if (this.createButton.equals(source)) { + //жǷ //ѭ + int count = 0; + + //ѭһж λ + for(int i=0;i arrayList = valueList.get(i); + TCComponentItemRevision rev = (TCComponentItemRevision)arrayList.get(9); + TCComponentBOMLine topLine = view.setWindowTopLine(rev.getItem(), rev, null, null); + int childrenCount = topLine.getChildrenCount(); + System.out.println("childrenCount========"+childrenCount); + TCComponent[] searchLs = session.search("_SearchMFKProperties", new String[] { "ID","" }, new String[] { (String) arrayList.get(2),(String) tm_part.getValueAt(i, 7) }); + + String ly6_sequenceNum = ""; + //ȥòѯ鿴ùˮ + if(searchLs != null && searchLs.length > 0) { + TCComponentItem mItem = (TCComponentItem)searchLs[0]; + ly6_sequenceNum = mItem.getStringProperty("ly6_sequenceNum"); + System.out.println("ly6_sequenceNum==="+ly6_sequenceNum); + } + + if(childrenCount == 0) { + //ֱӴ + String newID = (String) arrayList.get(2); + String newRev = type.getNewRev(null); + + + TCComponentItem item = type.create(newID, newRev, "LY6_ProductM", "", "", null); + item.setProperty("ly6_company", tm_part.getValueAt(i, 7).toString()); + if(ly6_sequenceNum.isEmpty()) { + item.setProperty("ly6_sequenceNum", "01"); + }else { + item.setProperty("ly6_sequenceNum", incrementNumber(ly6_sequenceNum)); + } + + //Ѷŵļ + rev.add("LY6_relatedMPart",item); + }else { + AIFComponentContext[] children = topLine.getChildren(); + //ֱӴ + String newID = (String) arrayList.get(2); + String newRev = type.getNewRev(null); + + + TCComponentItem item = type.create(newID, newRev, "LY6_ProductM", "", "", null); + item.setProperty("ly6_company", tm_part.getValueAt(i, 7).toString()); + if(ly6_sequenceNum.isEmpty()) { + item.setProperty("ly6_sequenceNum", "01"); + }else { + item.setProperty("ly6_sequenceNum", incrementNumber(ly6_sequenceNum)); + } + //Ѷŵļ + rev.add("LY6_relatedMPart",item); + //mBOM + TCComponentBOMWindowType viewType = (TCComponentBOMWindowType) session.getTypeComponent("BOMWindow"); + TCComponentBOMWindow view = viewType.create(null); + TCComponentBOMLine mTopLine = view.setWindowTopLine(item, item.getLatestItemRevision(), null, null); + ArrayList addList = new ArrayList();//mbom + ArrayList childrenList = new ArrayList();//ѡеֵ + HashMap revMap = new HashMap();//object_String ͶӦ汾 + for (int j = 0; j < children.length; j++) { + + TCComponentBOMLine eLine = (TCComponentBOMLine) children[j].getComponent(); + //жǷ + TCComponentItemRevision eRev = eLine.getItemRevision(); + String tcProperty = eRev.getTCProperty("ly6_homemadeStatus").toString(); + System.out.println("ly6_homemadeStatus======="+tcProperty); + String eId = eRev.getStringProperty("item_id"); + if(tcProperty.equals("")) { + //жemǷΨһ + ArrayList tempMrevList = new ArrayList(); + + for (int k = 0; k < groupSplit.length; k++) { + TCComponent[] search = session.search("_SearchMFKProperties", new String[] { "ID","" }, new String[] { eId,groupSplit[k] }); + + for (int l = 0; l < search.length; l++) { + TCComponentItem tempItem = (TCComponentItem)search[l]; + tempMrevList.add(tempItem.getLatestItemRevision()); + } + } + + if(tempMrevList.size() == 0) { + MessageBox.post(eId+"δMPart", "ʾ ", MessageBox.INFORMATION); + return; + }else if(tempMrevList.size() == 1) { + //Mbom + addList.add(tempMrevList.get(0)); + }else if(tempMrevList.size() > 1) { + //ûѡһMbom + + JComboBox jComboBox = new JComboBox(); + for (int k = 0; k < tempMrevList.size(); k++) { + String stringProperty = tempMrevList.get(k).getStringProperty("object_string"); + revMap.put(stringProperty, tempMrevList.get(k)); + jComboBox.addItem(stringProperty); + } + + + + + // ʾģ̬Ի + DialogFrame dialog = new DialogFrame(MpartDialog.this,jComboBox,childrenList); + dialog.setVisible(true); + + // ȴԻرպִеIJ + dialog.addWindowListener(new java.awt.event.WindowAdapter() { + @Override + public void windowClosed(java.awt.event.WindowEvent e) { + + } + }); + + + + + + } + + + + }else { + //ΪֱӽEPartMBOM + addList.add(eRev); + + } + } + System.out.println("childrenList.size()======="+childrenList.size()); + for (int j = 0; j < childrenList.size(); j++) { + addList.add(revMap.get(childrenList.get(j))); + } + + System.out.println("addList.size()============"+addList.size()); + for (int j = 0; j < addList.size(); j++) { + mTopLine.add(addList.get(j).getItem(), addList.get(j), null, false, ""); + + } + mTopLine.save(); + view.save(); + view.close(); + } + + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + } + + } + + MessageBox.post("ɹ", "ʾ ", MessageBox.INFORMATION); + + + + + } else if (this.viewlButton.equals(source)) { + //򿪶󵽽ṹ + + System.out.println("ѡе==="+t_part2.getSelectedRow()); + if(t_part2.getSelectedRow() == -1) { + MessageBox.post("ұѡҪ򿪵ĶУ", "ʾ ", MessageBox.INFORMATION); + return; + }else { + if(table2RevList != null && table2RevList.size() > 0) { + ArrayList arrayList = valueList.get(t_part.getSelectedRow()); + Object object = arrayList.get(8); + com.teamcenter.rac.common.Activator.getDefault() + .openPerspective("com.teamcenter.rac.pse.PSEPerspective"); + try { + com.teamcenter.rac.common.Activator.getDefault().openComponents( + "com.teamcenter.rac.pse.PSEPerspective", + new InterfaceAIFComponent[] {table2RevList.get(t_part2.getSelectedRow()).getItem() }); + } catch (TCException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + } + } + + + + }else if(this.xrButton.equals(source)) { + TCComponentUser user = new KOrgDialog("").getUser(); + System.out.println("Select User: " + user); + String userName = ""; + try { + userName = user.getUserName(); + } catch (TCException e1) { + // TODO Auto-generated catch block + MessageBox.post("ѡû", "ʾ ", MessageBox.INFORMATION); + return; + } + int count = 0; + for(int i=0;i arrayList = valueList.get(selectedRow); + Object object = arrayList.get(8); + System.out.println("11111111111111111111111111111111"); + if(object != null) { + + ArrayList tempList = (ArrayList)object; + for (int i = 0; i < tempList.size(); i++) { + table2RevList.add(tempList.get(i)); + } + System.out.println("tempList======"+tempList.size()); + for (int i = 0; i < tempList.size(); i++) { + TCComponentItemRevision tcComponentItemRevision = tempList.get(i); + try { + String id = tcComponentItemRevision.getStringProperty("item_id"); + System.out.println("item_id======"+id); + String objectName = tcComponentItemRevision.getStringProperty("object_string"); + tm_part2.addRow(new Object[] {i+1,objectName}); + } catch (TCException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + } + } + }else { + Object valueAt = t_part.getValueAt(selectedRow, selectColumn); + if(valueAt.toString().equals("1")) { + t_part.setValueAt("0", selectedRow, selectColumn); + }else { + t_part.setValueAt("1", selectedRow, selectColumn); + } + } + } + } + }); + } + }); + + + + + +// t_part.addMouseListener(new MouseListener() { +// +// @Override +// public void mouseReleased(MouseEvent e) { +// // TODO Auto-generated method stub +// +// } +// +// @Override +// public void mousePressed(MouseEvent e) { +// // TODO Auto-generated method stub +// +// } +// +// @Override +// public void mouseExited(MouseEvent e) { +// // TODO Auto-generated method stub +// +// } +// +// @Override +// public void mouseEntered(MouseEvent e) { +// // TODO Auto-generated method stub +// +// } +// +// @Override +// public void mouseClicked(MouseEvent e) { +// // TODO Auto-generated method stub +// int selectColumn = t_part.getTableHeader().columnAtPoint(e.getPoint()); +// int selectedRow = t_part.rowAtPoint(e.getPoint()); +// +// if(selectColumn != 0) +// { +// t_part2.removeAll(); +// tm_part2.setRowCount(0); +// table2RevList.clear(); +// ArrayList arrayList = valueList.get(selectedRow); +// Object object = arrayList.get(8); +// System.out.println("11111111111111111111111111111111"); +// if(object != null) { +// +// ArrayList tempList = (ArrayList)object; +// for (int i = 0; i < tempList.size(); i++) { +// table2RevList.add(tempList.get(i)); +// } +// System.out.println("tempList======"+tempList.size()); +// for (int i = 0; i < tempList.size(); i++) { +// TCComponentItemRevision tcComponentItemRevision = tempList.get(i); +// try { +// String id = tcComponentItemRevision.getStringProperty("item_id"); +// System.out.println("item_id======"+id); +// String objectName = tcComponentItemRevision.getStringProperty("object_name"); +// tm_part2.addRow(new Object[] {i+1,id+"_"+objectName}); +// } catch (TCException e1) { +// // TODO Auto-generated catch block +// e1.printStackTrace(); +// } +// } +// } +// }else { +// Object valueAt = t_part.getValueAt(selectedRow, selectColumn); +// if(valueAt.toString().equals("1")) { +// t_part.setValueAt("0", selectedRow, selectColumn); +// }else { +// t_part.setValueAt("1", selectedRow, selectColumn); +// } +// } +// } +// }); + + tm_part.setDataVector(null, HEADER); + t_part.getTableHeader().setReorderingAllowed(false); // вƶᷢת󣨵У + this.t_part.setRowHeight(30); + + TableColumnModel colModel = this.t_part.getColumnModel(); + int colCnt = HEADERWIDTH.length; + for (int i = 0; i < colCnt; i++) { + colModel.getColumn(i).setPreferredWidth(HEADERWIDTH[i]); + } + t_part.getTableHeader().setDefaultRenderer(new CheckHeaderCellRenderer(t_part)); + t_part.getColumnModel().getColumn(0).setCellRenderer(new TableCellCheckboxRenderer(t_part)); + + // ȡѡֵ +// String[] ld_taskNature = session.getPreferenceService().getStringValues("ld_taskNature");// +// String[] ld_taskDifficulty = session.getPreferenceService().getStringValues("ld_taskDifficulty");// ׳̶ +// String[] ld_urgency = session.getPreferenceService().getStringValues("ld_urgency");// ̶ +// +// Map ld_taskNatureMap = new HashMap(); +// Map ld_taskDifficultyMap = new HashMap(); +// Map ld_urgencyMap = new HashMap(); + + // ֵ + +// for (int i = 0; i < ld_taskNature.length; i++) { +// String[] split = ld_taskNature[i].split("="); +// ld_taskNatureMap.put(split[0], Double.parseDouble(split[1])); +// jComboBox1.addItem(split[0]); +// } +// +// for (int i = 0; i < ld_taskDifficulty.length; i++) { +// String[] split = ld_taskDifficulty[i].split("="); +// ld_taskDifficultyMap.put(split[0], Double.parseDouble(split[1])); +// jComboBox2.addItem(split[0]); +// } +// +// for (int i = 0; i < ld_urgency.length; i++) { +// String[] split = ld_urgency[i].split("="); +// ld_urgencyMap.put(split[0], Double.parseDouble(split[1])); +// jComboBox3.addItem(split[0]); +// } + + + + + + + + + +// +// // +// t_part.addMouseListener(new MouseAdapter() { +// @Override +// public void mouseClicked(MouseEvent e) { +// if (e.getClickCount() == 2 && t_part.columnAtPoint(e.getPoint()) == 2) { // жǷ˫ڵڶ +// int row = t_part.rowAtPoint(e.getPoint()); +// int column = t_part.columnAtPoint(e.getPoint()); +// if (column == 2) { +// // ȡ˫ĵԪ +// String value = (String) t_part.getModel().getValueAt(row, column); +// // ﴦ˫¼ +// System.out.println("Double-clicked on cell: Row=" + row + ", Column=" + column + ", Value=" + value); +// // Ӹ߼˫¼ +// +// } +// +// } +// } +// }); + + + + //this.t_part.getTableHeader().setBackground(Color.blue); + + + + + + + + JScrollPane scroll = new JScrollPane(t_part); + panel.add(BorderLayout.CENTER, scroll); + + + panel.setBorder(BorderFactory.createLoweredBevelBorder()); + return panel; + } + + + + + private JPanel getTablePanel2() { + JPanel panel = new JPanel(new BorderLayout()); + panel.setPreferredSize(new Dimension(200, 600)); + tm_part2 = new DefaultTableModel(); + t_part2 = new JTable(tm_part2) { + /** + * + */ + + + @Override + public boolean isCellEditable(int row, int column) { + if (column == 0) {// ɱ༭ + return true; + } + else { + return false; + } + + + + } + + + }; + tm_part2.setDataVector(null, HEADER2); + t_part2.getTableHeader().setReorderingAllowed(false); // вƶᷢת󣨵У + this.t_part2.setRowHeight(23); + + + TableColumnModel colModel = this.t_part2.getColumnModel(); + int colCnt = HEADERWIDTH2.length; + for (int i = 0; i < colCnt; i++) { + colModel.getColumn(i).setPreferredWidth(HEADERWIDTH2[i]); + } + //t_part2.getTableHeader().setDefaultRenderer(new CheckHeaderCellRenderer(t_part2)); + //t_part2.getColumnModel().getColumn(0).setCellRenderer(new TableCellCheckboxRenderer(t_part2)); +// t_part2.addMouseListener(new MouseListener() { +// +// @Override +// public void mouseReleased(MouseEvent e) { +// // TODO Auto-generated method stub +// +// } +// +// @Override +// public void mousePressed(MouseEvent e) { +// // TODO Auto-generated method stub +// +// } +// +// @Override +// public void mouseExited(MouseEvent e) { +// // TODO Auto-generated method stub +// +// } +// +// @Override +// public void mouseEntered(MouseEvent e) { +// // TODO Auto-generated method stub +// +// } +// +// @Override +// public void mouseClicked(MouseEvent e) { +// // TODO Auto-generated method stub +// int selectColumn = t_part2.getTableHeader().columnAtPoint(e.getPoint()); +// int selectedRow = t_part2.rowAtPoint(e.getPoint()); +//// System.out.println("selectColumn==>"+selectColumn); +// if(selectColumn != 0) +// { +// return; +// }else { +// Object valueAt = t_part2.getValueAt(selectedRow, selectColumn); +// if(valueAt.toString().equals("1")) { +// t_part2.setValueAt("0", selectedRow, selectColumn); +// }else { +// t_part2.setValueAt("1", selectedRow, selectColumn); +// } +// } +// } +// }); + // õһеĵԪȾͱ༭ + +// +// // +// t_part.addMouseListener(new MouseAdapter() { +// @Override +// public void mouseClicked(MouseEvent e) { +// if (e.getClickCount() == 2 && t_part.columnAtPoint(e.getPoint()) == 2) { // жǷ˫ڵڶ +// int row = t_part.rowAtPoint(e.getPoint()); +// int column = t_part.columnAtPoint(e.getPoint()); +// if (column == 2) { +// // ȡ˫ĵԪ +// String value = (String) t_part.getModel().getValueAt(row, column); +// // ﴦ˫¼ +// System.out.println("Double-clicked on cell: Row=" + row + ", Column=" + column + ", Value=" + value); +// // Ӹ߼˫¼ +// +// } +// +// } +// } +// }); + + + + // this.t_part2.getTableHeader().setBackground(Color.blue); + + + + + + + + JScrollPane scroll = new JScrollPane(t_part2); + panel.add(BorderLayout.CENTER, scroll); + + + panel.setBorder(BorderFactory.createLoweredBevelBorder()); + return panel; + } + + public String getGroupID() throws TCException { + TCComponentGroup group = session.getCurrentGroup(); + String name = group.getTCProperty("name").getStringValue(); + return name; + } + + + /** + * ַʾ10µּ1ؼ1ַ + * + * @param numberStr ַʽΪ "01", "02", ..., "10" + * @return 1ַʽֲ + */ + public String incrementNumber(String numberStr) { + // ַ֤ǷԤڸʽ + if (!numberStr.matches("^0[1-9]|10$")) { + throw new IllegalArgumentException("Input must be a string representing a number between 01 and 10."); + } + + // ַתΪ + int number = Integer.parseInt(numberStr); + + // 1 + number++; + + // ʽ + String formattedNumber = String.format("%02d", number); + + return formattedNumber; + } +} diff --git a/src/com/langtech/plm/mpart/MpartHandler.java b/src/com/langtech/plm/mpart/MpartHandler.java new file mode 100644 index 0000000..392b846 --- /dev/null +++ b/src/com/langtech/plm/mpart/MpartHandler.java @@ -0,0 +1,67 @@ +package com.langtech.plm.mpart; + +import java.util.ArrayList; + +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.commands.ExecutionException; + +import com.teamcenter.rac.aif.AbstractAIFApplication; +import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCComponentSchedule; +import com.teamcenter.rac.kernel.TCComponentScheduleTask; +import com.teamcenter.rac.kernel.TCException; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +public class MpartHandler extends AbstractHandler{ + + + @Override + public Object execute(ExecutionEvent arg0) throws ExecutionException { + AbstractAIFApplication app = AIFUtility.getCurrentApplication(); + TCSession session = (TCSession) app.getSession(); + try { + + new Thread() { + @Override + public void run() { + InterfaceAIFComponent[] targetComponent = app.getTargetComponents(); + ArrayList arrayList = new ArrayList(); + + for (int i = 0; i < targetComponent.length; i++) { + InterfaceAIFComponent component = targetComponent[i]; + if(component instanceof TCComponentItemRevision) { + arrayList.add((TCComponentItemRevision)component); + } + } + + System.out.println("arrayList.size()==========="+arrayList.size()); + + if(arrayList.size() > 0) { + try { + new MpartDialog(session,arrayList); + } catch (TCException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + + + + } + }.start(); + + } catch (Exception e) { + // TODO: handle exception + e.printStackTrace(); + } + + return null; + } + + +} diff --git a/src/com/langtech/plm/mpart/TableCellCheckboxRenderer.java b/src/com/langtech/plm/mpart/TableCellCheckboxRenderer.java new file mode 100644 index 0000000..ab0f89b --- /dev/null +++ b/src/com/langtech/plm/mpart/TableCellCheckboxRenderer.java @@ -0,0 +1,54 @@ +package com.langtech.plm.mpart; + +import java.awt.Component; +import java.util.List; + +import javax.swing.JCheckBox; +import javax.swing.JRadioButton; +import javax.swing.JTable; +import javax.swing.SwingConstants; +import javax.swing.event.ChangeEvent; +import javax.swing.event.EventListenerList; +import javax.swing.table.TableCellRenderer; + +import com.teamcenter.rac.treetable.JTreeTable; + + +public class TableCellCheckboxRenderer extends JCheckBox implements + TableCellRenderer { + private List processRows; + protected EventListenerList listenerList = new EventListenerList(); + protected ChangeEvent changeEvent = new ChangeEvent(this); + //private TestTreeTableModel tableModel; + + public List getProcessRows() { + return processRows; + } + + public void setProcessRows(List processRows) { + this.processRows = processRows; + + } + public TableCellCheckboxRenderer(final JTable table) { + } + public TableCellCheckboxRenderer(final JTreeTable table) { + } + + @Override + public Component getTableCellRendererComponent(JTable table, Object value, + boolean isSelected, boolean hasFocus, int row, int column) { + // TODO Auto-generated method stub + this.setHorizontalAlignment(SwingConstants.CENTER);// ͷǩ +// this.setBorderPainted(true); + + if(value != null) + { + this.setSelected(value.toString().equals("1")); + } + else + { + this.setSelected(false); + } + return this; + } +} \ No newline at end of file diff --git a/src/com/langtech/plm/performancemanagement/handlers/TaskFolderMatchingHandler.java b/src/com/langtech/plm/performancemanagement/handlers/TaskFolderMatchingHandler.java deleted file mode 100644 index d08dc3d..0000000 --- a/src/com/langtech/plm/performancemanagement/handlers/TaskFolderMatchingHandler.java +++ /dev/null @@ -1,426 +0,0 @@ -package com.langtech.plm.performancemanagement.handlers; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.time.Instant; -import java.time.LocalDate; -import java.time.ZoneId; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; - -import com.teamcenter.rac.aif.AbstractAIFApplication; -import com.teamcenter.rac.aifrcp.AIFUtility; -import com.teamcenter.rac.kernel.TCComponent; -import com.teamcenter.rac.kernel.TCComponentDataset; -import com.teamcenter.rac.kernel.TCComponentTcFile; -import com.teamcenter.rac.kernel.TCException; -import com.teamcenter.rac.kernel.TCProperty; -import com.teamcenter.rac.kernel.TCSession; -import com.teamcenter.rac.util.FileUtility; -import com.teamcenter.rac.util.MessageBox; - -/** - * ѡĿļУЧ ݿάҪ - * - * - */ -public class TaskFolderMatchingHandler extends AbstractHandler { - @Override - public Object execute(ExecutionEvent event) throws ExecutionException { - AbstractAIFApplication app = AIFUtility.getCurrentApplication(); - TCSession session = (TCSession) app.getSession(); - TCComponent target = null; - target = (TCComponent) app.getTargetComponent(); - // ѡĿͣ򱨴 - String type = target.getType(); - if (type.equals("LD6_CusProdFolder") || type.equals("ͻƷļ")) { - // TODO ݿⷽʽά -// TCComponent[] workRequest = null; -// try { -// workRequest = session.search("...", new String[] { "", "" }, new String[] { "Ҫ", "xxxx" }); -// } catch (Exception e) { -// e.printStackTrace(); -// MessageBox.post("ѯ쳣", "", MessageBox.INFORMATION); -// } -// if (workRequest.length == 0) { -// MessageBox.post("ϵͳûҪ뵼", "", MessageBox.INFORMATION); -// } else if (workRequest.length > 1) { -// -// MessageBox.post("ϵͳдڶҪ", "", MessageBox.INFORMATION); -// } - // 鱨ģǷڣѡld_billboards_uid - String ldBillboardsUid = session.getPreferenceService().getStringValue("ld_billboards_uid"); - if (!getMessageboxInfo(ldBillboardsUid, "ld_billboards_uid")) { - return null; - } - TCComponent billboard = null; - try { - billboard = session.stringToComponent(ldBillboardsUid); - } catch (TCException e) { - e.printStackTrace(); - MessageBox.post("֪ͨԱѡld_billboards_uidǷ", "", MessageBox.INFORMATION); - return null; - } - if (billboard == null) { - MessageBox.post("֪ͨԱѡld_billboards_uidǷ", "", MessageBox.INFORMATION); - return null; - } - // ȡλϵ Ѷϵ Ŷϵ Ҫʱ乫ʽѡ - String[] ldPostCoefficient = session.getPreferenceService().getStringValues("ld_postCoefficient"); - String[] ldTaskNature = session.getPreferenceService().getStringValues("ld_taskNature");// ѶϵӦѶϵ - String[] ldUrgency = session.getPreferenceService().getStringValues("ld_urgency"); - // ʱ - String[] ldOvertime = session.getPreferenceService().getStringValues("ld_overtime");// صȼ:䣨[0,0]:۷ϵ;һ:(0,1]:1/5;:(1,2]:1/3;:(2,3]:1/2;δ:[3,1000):0.6 - // Ϣó =:˽ڵ - String[] ldProcessReview = session.getPreferenceService().getStringValues("ld_processReview"); - if (!getMessageInfo(ldPostCoefficient, "ld_processReview")) { - return false; - } - if (!getMessageInfo(ldTaskNature, "ld_taskNature")) { - return false; - } - if (!getMessageInfo(ldUrgency, "ld_urgency")) { - return false; - } - if (!getMessageInfo(ldProcessReview, "ld_processReview")) { - return false; - } - if (!getMessageInfo(ldOvertime, "ld_overtime")) { - return false; - } - Map postCoefficientMap = new HashMap();// λλϵ - Map taskNatureMap = new HashMap();// ʣϵ - Map urgencyMap = new HashMap();// ̶ȣ̶ϵ - Map processReviewMap = new HashMap();// ƣָɵĽڵ - Map severityIntervalMap = new HashMap();// 䣻ֵ۷ϵ - for (int i = 0; i < ldPostCoefficient.length; i++) { - String value = ldPostCoefficient[i]; - postCoefficientMap.put(value.split("=")[0], value.split("=")[0]); - } - for (int i = 0; i < ldTaskNature.length; i++) { - String value = ldTaskNature[i]; - taskNatureMap.put(value.split("=")[0], value.split("=")[0]); - } - for (int i = 0; i < ldUrgency.length; i++) { - String value = ldUrgency[i]; - urgencyMap.put(value.split("=")[0], value.split("=")[0]); - } - for (int i = 0; i < ldProcessReview.length; i++) { - String value = ldProcessReview[i]; - processReviewMap.put(value.split("=")[0], value.split("=")[0]); - } - for (int i = 0; i < ldOvertime.length; i++) { - String dayInterval = ldOvertime[i].split(":")[1]; - String severity = ldOvertime[i].split(":")[0]; - String point = ldOvertime[i].split(":")[2]; - severityIntervalMap.put(dayInterval, point); - } - // رúҪ - String billboardAddress = downLoadFile(billboard); - // TODO ȡսʱ - String targetName = ""; - try { - targetName = target.getProperty("object_name"); - } catch (TCException e) { - e.printStackTrace(); - } - Date processEndTime = getEndTime(targetName); - if (processEndTime == null) { - MessageBox.post("ǷûߵؿͻƷļƺ͹ճʱ", "", MessageBox.INFORMATION); - return null; - } - // ȡ ֯ - // ȱײṹ - String path = ""; - path = targetName; - String link = "/"; - List taskPathList = new ArrayList(); - Map folderMap = new HashMap();// ļв㼶ṹ ֵļж - getAllFolderPath(target, path, link, taskPathList, folderMap); - // ȡѡConnor_JXFolder - Map> packageMap = new HashMap>(); - String connorJXFolderPreference = "Connor_JXFolder"; - String[] ConnorJXFolders = session.getPreferenceService().getStringValues(connorJXFolderPreference); - if (getMessageInfo(ConnorJXFolders, connorJXFolderPreference)) { - return false; - } - for (int i = 0; i < ConnorJXFolders.length; i++) { - String[] values = ConnorJXFolders[i].split("="); - String[] folders = values[1].split(";"); - List folderList = Arrays.asList(folders); - packageMap.put(values[0], folderList); - } - // ȡϢ - File file = new File(billboardAddress); - XSSFWorkbook workbook = null; - try { - FileInputStream fis = new FileInputStream(file); - workbook = new XSSFWorkbook(fis); - } catch (IOException e) { - e.printStackTrace(); - } - XSSFSheet sheet = workbook.getSheet("Ʒ"); - int rowNum = sheet.getLastRowNum(); - for (int i = 1; i < rowNum; i++) { - XSSFRow row = sheet.getRow(i); - String cellBValue = row.getCell(1).getStringCellValue().trim();// - List folderList = packageMap.get(cellBValue); - if (folderList != null && folderList.size() > 0) { - String folderPath = folderList.get(0); - TCComponent folder = folderMap.get(folderPath); - String[] properties = new String[] { "object_desc", "", "׳̶", "̶", "ҵʱ(Сʱ)", - "fnd0AllWorkflows" }; - TCProperty[] tcproperties = null; - try { - tcproperties = folder.getTCProperties(properties); - } catch (TCException e) { - e.printStackTrace(); - } - // ƷҪ - String objectDesc = tcproperties[0].getStringValue(); - String taskNature = tcproperties[1].getDisplayValue(); - String difficulty = tcproperties[2].getDisplayValue(); - String urgency = tcproperties[3].getDisplayValue(); - String ratedBusinessHours = tcproperties[4].getStringValue(); - String taskNatureCoefficient = taskNatureMap.get(difficulty); - String urgencyCoefficient = urgencyMap.get(urgency); - String postCoefficient = "";// - // ȡϢ - String processReview = processReviewMap.get(cellBValue); - String processName = processReview.split(":")[0]; - String reviewName = processReview.split(":")[1]; - String assignee = "";// ָfnd0Assigneeûоתָ߼̽ߣͬη - String assigner = "";// ָfnd0Assignerûоתûֵȡָ - String assigneeGroup = "";// ָߵ - String status = "";// ״̬ - String startData = "";// ̿ʼʱ - String endDateValue = "";// ̽ʱ - String actualHours = "";// ʵҵʱ - String deductPoints = "";// ʱ۷ - TCComponent[] workflows = tcproperties[5].getReferenceValueArray(); - for (int j = 0; j < workflows.length; j++) { - TCComponent workflow = workflows[j]; - try { - String[] workflowProperties = new String[] { "object_name", "fnd0ActuatedInteractiveTsks", - "fnd0EndDate", "fnd0StartDate", "fnd0Status" }; - TCProperty[] workflowTcProperties = workflow.getTCProperties(workflowProperties); - String workflowName = workflowTcProperties[0].getDisplayValue(); - TCComponent[] reviews = workflowTcProperties[1].getReferenceValueArray(); - if (workflowName.equals(processName)) { - for (int k = 0; k < reviews.length; k++) { - TCComponent review = reviews[k]; - String typeName = review.getType(); - if (typeName.equals("ǩ")) {// fnd0AliasTaskName;ִߣfnd0Performer - // fnd0AssigneeGroupRole owning_group - String[] reviewProperties = new String[] { "fnd0AliasTaskName", "fnd0Performer", - "owning_group", "fnd0Assigner", "fnd0Assignee" }; - TCProperty[] reviewTcProperties = review.getTCProperties(reviewProperties); - String aliasTaskName = reviewTcProperties[0].getDisplayValue(); - if (aliasTaskName.contains(":")) { - String reviewNodeName = aliasTaskName.split(":")[0]; - if (reviewNodeName.equals(reviewName)) { - assignee = reviewTcProperties[4].getDisplayValue(); - assigneeGroup = reviewTcProperties[2].getDisplayableValue(); - TCProperty assigneeProperty = reviewTcProperties[3]; - if (assigneeProperty.getDisplayValue().length() > 0) { - assigner = assigneeProperty.getDisplayValue(); - } else { - assigner = assignee; - } - } - } - status = workflowTcProperties[4].getDisplayValue().equals("") ? "" - : "δ"; - endDateValue = workflowTcProperties[2].getDisplayValue(); - Date startDate = workflowTcProperties[2].getDateValue(); - Date endDate = workflowTcProperties[3].getDateValue(); - actualHours = "" + (endDate.getTime() - startDate.getTime()) / 1000 / 3600; - float point = (float) 0.0; - if (status.equals("")) { - ZoneId zoneId = ZoneId.systemDefault(); - Instant instantEnd = endDate.toInstant(); - Instant instantProcessEnd = processEndTime.toInstant(); - LocalDate localEndDate = instantEnd.atZone(zoneId).toLocalDate(); - LocalDate localProcessEndDate = instantProcessEnd.atZone(zoneId) - .toLocalDate(); - long diff = localEndDate.toEpochDay() - localProcessEndDate.toEpochDay(); - String overtimeCoefficient = "";// ۷ϵ - postCoefficient = postCoefficientMap.get(assigneeGroup); - for (Map.Entry me : severityIntervalMap.entrySet()) { - String interval = me.getKey(); - String startDay = interval.split(",")[0]; - String endDay = interval.split(",")[1]; - boolean condition1 = false; - boolean condition2 = false; - if (startDay.startsWith("[")) { - condition1 = diff >= (Integer - .valueOf(startDay.substring(1, startDay.length() - 1))) - ? true - : false; - } else if (startDay.startsWith("(")) { - condition1 = diff > (Integer - .valueOf(startDay.substring(1, startDay.length() - 1))) - ? true - : false; - } - if (endDay.endsWith("]")) { - condition2 = diff <= (Integer - .valueOf(endDay.substring(0, endDay.length() - 2))) ? true - : false; - } else if (startDay.startsWith(")")) { - condition2 = diff < (Integer - .valueOf(endDay.substring(0, endDay.length() - 2))) ? true - : false; - } - if (condition1 == true && condition2 == true) { - overtimeCoefficient = me.getValue(); - } else { - continue; - } - } - if (!overtimeCoefficient.equals("")) { - point = 1 * Float.valueOf(overtimeCoefficient) - * Float.valueOf(taskNatureCoefficient) - * Float.valueOf(urgencyCoefficient);// TODO ʽʱʺѶϵ - } - } - } - } - } - } catch (TCException e) { - e.printStackTrace(); - } - } - } else { - continue; - } - } - } else { - MessageBox.post("ѡͻƷļ", "", MessageBox.INFORMATION); - } - return null; - } - - /** - * ͨݷʽȡսʱ - */ - private Date getEndTime(String targetName) { - // TODO - return null; - } - - /** - * ѡǷ - * - * @param preferenceValue ѡֵ - * @param preferenceName ѡ - * @return ûþͷfalse - */ - private boolean getMessageInfo(String[] preferenceValue, String preferenceName) { - if (preferenceValue == null || preferenceValue.length == 0) { - MessageBox.post("֪ͨԱѡ" + preferenceName + "Ƿ", "", MessageBox.INFORMATION); - return false; - } - return true; - } - - /** - * ѡǷ - * - * @param preferenceValue ѡֵ - * @param preferenceName ѡ - * @return ûþͷfalse - */ - private boolean getMessageboxInfo(String preferenceValue, String preferenceName) { - if (preferenceValue == null || preferenceValue.length() == 0) { - MessageBox.post("֪ͨԱѡ" + preferenceName + "Ƿ", "", MessageBox.INFORMATION); - return false; - } - return true; - } - - /** - * ѭĿļµļУӵϺmap - * - * @param target ļ - * @param path ļ· - * @param link ӷ - * @param taskPathList · - * @param folderMap · - * @return صļ - */ - private void getAllFolderPath(TCComponent target, String path, String link, List taskPathList, - Map folderMap) { - try { - TCComponent[] contents = target.getRelatedComponents("contents"); - for (int i = 0; i < contents.length; i++) { - TCComponent content = contents[i]; - TCComponent[] childContents = content.getRelatedComponents("contents"); - path = path + link + content.getProperty("object_name"); - if (childContents.length > 0) { - getAllFolderPath(content, path, link, taskPathList, folderMap); - } else { - taskPathList.add(path); - folderMap.put(path, content); - } - } - } catch (TCException e) { - e.printStackTrace(); - } - } - - /** - * ļ - * - * @param ݼ - * @return صļ - */ - public String downLoadFile(TCComponent comp) { - if (comp == null) { - return ""; - } - String value = ""; - String tempPath = System.getenv("TEMP"); - if (tempPath == null) { - tempPath = ""; - } else if (!tempPath.endsWith("\\")) { - tempPath = tempPath + "\\"; - } - SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); - try { - if (comp instanceof TCComponentDataset) { - TCComponentTcFile[] tcFiles = ((TCComponentDataset) comp).getTcFiles(); - File file = null; - System.out.println("tcFiles:" + tcFiles.length); - if (tcFiles != null && tcFiles.length != 0) { - file = tcFiles[0].getFmsFile(); - String fileName = file.getName(); - System.out.println("fileName:" + fileName); - String fileDix = fileName.substring(fileName.lastIndexOf("."), fileName.length()); - fileName = tempPath + sdf.format(new Date()) + fileDix; - File dirFile = new File(fileName); - FileUtility.copyFile(file, dirFile); - return fileName; - } - } - } catch (TCException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - return value; - } -} diff --git a/src/com/langtech/plm/synchronize/SynchronizeDialog.java b/src/com/langtech/plm/synchronize/SynchronizeDialog.java new file mode 100644 index 0000000..0b92896 --- /dev/null +++ b/src/com/langtech/plm/synchronize/SynchronizeDialog.java @@ -0,0 +1,720 @@ +package com.langtech.plm.synchronize; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.Toolkit; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Map.Entry; + +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.border.EmptyBorder; +import javax.swing.table.DefaultTableModel; + +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentForm; +import com.teamcenter.rac.kernel.TCComponentItem; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCException; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; +import com.teamcenter.rac.util.PropertyLayout; + +public class SynchronizeDialog extends JFrame implements ActionListener { + + private TCSession session; + protected DefaultTableModel tm_part; + private static ArrayList dateConnList = new ArrayList(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + private TCComponentItemRevision rev; + private JComboBox objectComboBox = new JComboBox(); + private JButton okButton = new JButton("ȷ"); + private JButton concelButton = new JButton("ȡ"); + private HashMap fieldMap = new HashMap(); + private String revType = ""; + HashMap objectMap = new HashMap(); + + public SynchronizeDialog(TCSession session, TCComponentItemRevision rev) { + // TODO Auto-generated constructor stub + this.session = session; + this.rev = rev; + initUI(); + } + + private void initUI() { + // TODO Auto-generated method stub + try { + this.setTitle("ͬ"); + this.setLayout(new BorderLayout()); + + JPanel topPanel = getTopPanel(); + + JPanel btnPanel = getBtnPanel(); + + this.add(topPanel, BorderLayout.NORTH); + // this.add(pane,BorderLayout.CENTER); + this.add(btnPanel, BorderLayout.SOUTH); + this.setPreferredSize(new Dimension(550, 200)); + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); // ȡĻߴ + int screenWidth = screenSize.width; // ȡĻ + int screenHeight = screenSize.height; // ȡĻ߶ + int x = (screenWidth - 550) / 2; // FrameϽx + int y = (screenHeight - 300) / 2; // FrameϽy + this.setLocation(x, y); // Frameλ + + // this.setLocationRelativeTo(null); + this.createActionEvent(); + this.pack(); + + // this.validate(); + this.setVisible(true); + +// this.setAlwaysOnTop(true); + + // ȡѡ + String[] relations = session.getPreferenceService().getStringValues("LY6_CopyAttributeRelation"); + String[] fields = session.getPreferenceService().getStringValues("LY6_CopyAttribute"); + if (relations == null || relations.length <= 0) { + MessageBox.post("LY6_CopyAttributeRelation", "ʾ", 2); + return; + } + + if (fields == null || fields.length <= 0) { + MessageBox.post("LY6_CopyAttribute", "ʾ", 2); + return; + } + + for (int i = 0; i < fields.length; i++) { + String[] split = fields[i].split("="); + fieldMap.put(split[0], split[1]); + } + + HashMap relationsMap = new HashMap(); + for (int i = 0; i < relations.length; i++) { + String[] split = relations[i].split("="); + relationsMap.put(split[0], split[1]); + } + // ȡ汾 + revType = rev.getStringProperty("object_type"); + String relation = relationsMap.get(revType); + if (relation == null || relation.isEmpty()) { + MessageBox.post("ѡδƥ䵽ϵ", "ʾ", 2); + return; + } + // ȡϵµĶ + if (relation.contains(",")) { + String[] split = relation.split(","); + for (int i = 0; i < split.length; i++) { + TCComponent[] components = rev.getRelatedComponents(split[i]); + for (int j = 0; j < components.length; j++) { + if (components[j] instanceof TCComponentItemRevision) { + TCComponentItemRevision relationRev = (TCComponentItemRevision) components[j]; + String object_string = relationRev.getStringProperty("object_string"); + String object_type = relationRev.getStringProperty("object_type"); + objectMap.put(object_string + "-" + object_type, relationRev); + } + } + } + } else { + TCComponent[] components = rev.getRelatedComponents(relation); + for (int j = 0; j < components.length; j++) { + if (components[j] instanceof TCComponentItemRevision) { + TCComponentItemRevision relationRev = (TCComponentItemRevision) components[j]; + String object_string = relationRev.getStringProperty("object_string"); + String object_type = relationRev.getStringProperty("object_type"); + objectMap.put(object_string + "-" + object_type, relationRev); + } + } + } + + // ֵ + for (Entry map : objectMap.entrySet()) { + objectComboBox.addItem(map.getKey()); + } + + } catch (Exception e) { + e.printStackTrace(); + return; + } + } + + // Ӽ + public void createActionEvent() { + + this.okButton.addActionListener(this); + this.concelButton.addActionListener(this); + } + + @Override + public void actionPerformed(ActionEvent e) { + // TODO Auto-generated method stub + + Object source = e.getSource(); + System.out.println("source==>+" + source); + if (this.okButton.equals(source)) { + // ȡѡĶ + + try { + String selectedItem = (String) objectComboBox.getSelectedItem(); + TCComponentItemRevision selectRev = objectMap.get(selectedItem); + String selectRevType = selectRev.getStringProperty("object_type"); + String field = fieldMap.get(revType + ":" + selectRevType); + // ȡ item form + TCComponentItem revItem = rev.getItem(); + TCComponentForm revForm = (TCComponentForm) rev.getReferenceListProperty("IMAN_master_form_rev")[0]; + + TCComponentItem selectRevItem = selectRev.getItem(); + TCComponentForm selectRevForm = (TCComponentForm) selectRev + .getReferenceListProperty("IMAN_master_form_rev")[0]; + + if (field == null || field.isEmpty()) { + field = fieldMap.get("ͨ"); + // + System.out.println("field==="+field); + if (field.contains(",")) {// жǷ + String[] split = field.split(","); + for (int i = 0; i < split.length; i++) { + String[] split2 = split[i].split(":"); + String[] selectSplit = split2[1].split("\\."); + System.out.println("selectSplit[0]==="+selectSplit[0]); + if (selectSplit[0].equals("item")) { + String value = ""; + Date dateValue = null; + if(dateValue != null && value.isEmpty()) { + value = sdf.format(dateValue); + } + + if (selectSplit[2].equals("string") || selectSplit[2].equals("lov")) { + value = selectRevItem.getStringProperty(selectSplit[1]); + System.out.println("value===="+value); + } else if (selectSplit[2].equals("date")) { + dateValue = selectRevItem.getDateProperty(selectSplit[1]); + } + + // ȡĿҪĸ + String[] targetSplit = split2[0].split("\\."); + if (targetSplit[0].equals("item")) { + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + revItem.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + revItem.setDateProperty(targetSplit[1], dateValue); + } + + } else if (targetSplit[0].equals("rev")) { + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + rev.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + rev.setDateProperty(targetSplit[1], dateValue); + } + + } else if (targetSplit[0].equals("rm")) { + + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + revForm.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + revForm.setDateProperty(targetSplit[1], dateValue); + } + } + } else if (selectSplit[0].equals("rev")) { + + String value = ""; + Date dateValue = null; + if(dateValue != null && value.isEmpty()) { + value = sdf.format(dateValue); + } + if (selectSplit[2].equals("string") || selectSplit[2].equals("lov")) { + value = selectRev.getStringProperty(selectSplit[1]); + } else if (selectSplit[2].equals("date")) { + dateValue = selectRev.getDateProperty(selectSplit[1]); + } + + // ȡĿҪĸ + String[] targetSplit = split2[0].split("\\."); + if (targetSplit[0].equals("item")) { + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + revItem.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + revItem.setDateProperty(targetSplit[1], dateValue); + } + + } else if (targetSplit[0].equals("rev")) { + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + rev.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + rev.setDateProperty(targetSplit[1], dateValue); + } + + } else if (targetSplit[0].equals("rm")) { + + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + revForm.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + revForm.setDateProperty(targetSplit[1], dateValue); + } + } + + } else if (selectSplit[0].equals("rm")) { + + String value = ""; + Date dateValue = null; + if(dateValue != null && value.isEmpty()) { + value = sdf.format(dateValue); + } + if (selectSplit[2].equals("string") || selectSplit[2].equals("lov")) { + value = selectRevForm.getStringProperty(selectSplit[1]); + } else if (selectSplit[2].equals("date")) { + dateValue = selectRevForm.getDateProperty(selectSplit[1]); + } + + // ȡĿҪĸ + String[] targetSplit = split2[0].split("\\."); + if (targetSplit[0].equals("item")) { + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + revItem.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + revItem.setDateProperty(targetSplit[1], dateValue); + } + + } else if (targetSplit[0].equals("rev")) { + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + rev.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + rev.setDateProperty(targetSplit[1], dateValue); + } + + } else if (targetSplit[0].equals("rm")) { + + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + revForm.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + revForm.setDateProperty(targetSplit[1], dateValue); + } + } + + } + } + } else { + + String[] split2 = field.split(":"); + String[] selectSplit = split2[1].split("\\."); + System.out.println("selectSplit[0]==="+selectSplit[0]); + if (selectSplit[0].equals("item")) { + String value = ""; + Date dateValue = null; + if(dateValue != null && value.isEmpty()) { + value = sdf.format(dateValue); + } + + if (selectSplit[2].equals("string") || selectSplit[2].equals("lov")) { + value = selectRevItem.getStringProperty(selectSplit[1]); + System.out.println("value===="+value); + } else if (selectSplit[2].equals("date")) { + dateValue = selectRevItem.getDateProperty(selectSplit[1]); + } + + // ȡĿҪĸ + String[] targetSplit = split2[0].split("\\."); + if (targetSplit[0].equals("item")) { + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + revItem.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + revItem.setDateProperty(targetSplit[1], dateValue); + } + + } else if (targetSplit[0].equals("rev")) { + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + rev.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + rev.setDateProperty(targetSplit[1], dateValue); + } + + } else if (targetSplit[0].equals("rm")) { + + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + revForm.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + revForm.setDateProperty(targetSplit[1], dateValue); + } + } + } else if (selectSplit[0].equals("rev")) { + + String value = ""; + Date dateValue = null; + if(dateValue != null && value.isEmpty()) { + value = sdf.format(dateValue); + } + if (selectSplit[2].equals("string") || selectSplit[2].equals("lov")) { + value = selectRev.getStringProperty(selectSplit[1]); + } else if (selectSplit[2].equals("date")) { + dateValue = selectRev.getDateProperty(selectSplit[1]); + } + + // ȡĿҪĸ + String[] targetSplit = split2[0].split("\\."); + if (targetSplit[0].equals("item")) { + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + revItem.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + revItem.setDateProperty(targetSplit[1], dateValue); + } + + } else if (targetSplit[0].equals("rev")) { + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + rev.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + rev.setDateProperty(targetSplit[1], dateValue); + } + + } else if (targetSplit[0].equals("rm")) { + + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + revForm.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + revForm.setDateProperty(targetSplit[1], dateValue); + } + } + + } else if (selectSplit[0].equals("rm")) { + + String value = ""; + Date dateValue = null; + if(dateValue != null && value.isEmpty()) { + value = sdf.format(dateValue); + } + if (selectSplit[2].equals("string") || selectSplit[2].equals("lov")) { + value = selectRevForm.getStringProperty(selectSplit[1]); + } else if (selectSplit[2].equals("date")) { + dateValue = selectRevForm.getDateProperty(selectSplit[1]); + } + + // ȡĿҪĸ + String[] targetSplit = split2[0].split("\\."); + if (targetSplit[0].equals("item")) { + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + revItem.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + revItem.setDateProperty(targetSplit[1], dateValue); + } + + } else if (targetSplit[0].equals("rev")) { + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + rev.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + rev.setDateProperty(targetSplit[1], dateValue); + } + + } else if (targetSplit[0].equals("rm")) { + + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + revForm.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + revForm.setDateProperty(targetSplit[1], dateValue); + } + } + + } + + } + } else { + + // + System.out.println("field==="+field); + if (field.contains(",")) {// жǷ + String[] split = field.split(","); + for (int i = 0; i < split.length; i++) { + String[] split2 = split[i].split(":"); + String[] selectSplit = split2[1].split("\\."); + System.out.println("selectSplit[0]==="+selectSplit[0]); + if (selectSplit[0].equals("item")) { + String value = ""; + Date dateValue = null; + if(dateValue != null && value.isEmpty()) { + value = sdf.format(dateValue); + } + + if (selectSplit[2].equals("string") || selectSplit[2].equals("lov")) { + value = selectRevItem.getStringProperty(selectSplit[1]); + System.out.println("value===="+value); + } else if (selectSplit[2].equals("date")) { + dateValue = selectRevItem.getDateProperty(selectSplit[1]); + } + + // ȡĿҪĸ + String[] targetSplit = split2[0].split("\\."); + if (targetSplit[0].equals("item")) { + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + revItem.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + revItem.setDateProperty(targetSplit[1], dateValue); + } + + } else if (targetSplit[0].equals("rev")) { + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + rev.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + rev.setDateProperty(targetSplit[1], dateValue); + } + + } else if (targetSplit[0].equals("rm")) { + + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + revForm.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + revForm.setDateProperty(targetSplit[1], dateValue); + } + } + } else if (selectSplit[0].equals("rev")) { + + String value = ""; + Date dateValue = null; + if(dateValue != null && value.isEmpty()) { + value = sdf.format(dateValue); + } + if (selectSplit[2].equals("string") || selectSplit[2].equals("lov")) { + value = selectRev.getStringProperty(selectSplit[1]); + } else if (selectSplit[2].equals("date")) { + dateValue = selectRev.getDateProperty(selectSplit[1]); + } + + // ȡĿҪĸ + String[] targetSplit = split2[0].split("\\."); + if (targetSplit[0].equals("item")) { + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + revItem.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + revItem.setDateProperty(targetSplit[1], dateValue); + } + + } else if (targetSplit[0].equals("rev")) { + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + rev.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + rev.setDateProperty(targetSplit[1], dateValue); + } + + } else if (targetSplit[0].equals("rm")) { + + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + revForm.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + revForm.setDateProperty(targetSplit[1], dateValue); + } + } + + } else if (selectSplit[0].equals("rm")) { + + String value = ""; + Date dateValue = null; + if(dateValue != null && value.isEmpty()) { + value = sdf.format(dateValue); + } + if (selectSplit[2].equals("string") || selectSplit[2].equals("lov")) { + value = selectRevForm.getStringProperty(selectSplit[1]); + } else if (selectSplit[2].equals("date")) { + dateValue = selectRevForm.getDateProperty(selectSplit[1]); + } + + // ȡĿҪĸ + String[] targetSplit = split2[0].split("\\."); + if (targetSplit[0].equals("item")) { + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + revItem.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + revItem.setDateProperty(targetSplit[1], dateValue); + } + + } else if (targetSplit[0].equals("rev")) { + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + rev.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + rev.setDateProperty(targetSplit[1], dateValue); + } + + } else if (targetSplit[0].equals("rm")) { + + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + revForm.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + revForm.setDateProperty(targetSplit[1], dateValue); + } + } + + } + } + } else { + + String[] split2 = field.split(":"); + String[] selectSplit = split2[1].split("\\."); + System.out.println("selectSplit[0]==="+selectSplit[0]); + if (selectSplit[0].equals("item")) { + String value = ""; + Date dateValue = null; + if(dateValue != null && value.isEmpty()) { + value = sdf.format(dateValue); + } + + if (selectSplit[2].equals("string") || selectSplit[2].equals("lov")) { + value = selectRevItem.getStringProperty(selectSplit[1]); + System.out.println("value===="+value); + } else if (selectSplit[2].equals("date")) { + dateValue = selectRevItem.getDateProperty(selectSplit[1]); + } + + // ȡĿҪĸ + String[] targetSplit = split2[0].split("\\."); + if (targetSplit[0].equals("item")) { + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + revItem.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + revItem.setDateProperty(targetSplit[1], dateValue); + } + + } else if (targetSplit[0].equals("rev")) { + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + rev.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + rev.setDateProperty(targetSplit[1], dateValue); + } + + } else if (targetSplit[0].equals("rm")) { + + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + revForm.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + revForm.setDateProperty(targetSplit[1], dateValue); + } + } + } else if (selectSplit[0].equals("rev")) { + + String value = ""; + Date dateValue = null; + if(dateValue != null && value.isEmpty()) { + value = sdf.format(dateValue); + } + if (selectSplit[2].equals("string") || selectSplit[2].equals("lov")) { + value = selectRev.getStringProperty(selectSplit[1]); + } else if (selectSplit[2].equals("date")) { + dateValue = selectRev.getDateProperty(selectSplit[1]); + } + + // ȡĿҪĸ + String[] targetSplit = split2[0].split("\\."); + if (targetSplit[0].equals("item")) { + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + revItem.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + revItem.setDateProperty(targetSplit[1], dateValue); + } + + } else if (targetSplit[0].equals("rev")) { + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + rev.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + rev.setDateProperty(targetSplit[1], dateValue); + } + + } else if (targetSplit[0].equals("rm")) { + + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + revForm.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + revForm.setDateProperty(targetSplit[1], dateValue); + } + } + + } else if (selectSplit[0].equals("rm")) { + + String value = ""; + Date dateValue = null; + if(dateValue != null && value.isEmpty()) { + value = sdf.format(dateValue); + } + if (selectSplit[2].equals("string") || selectSplit[2].equals("lov")) { + value = selectRevForm.getStringProperty(selectSplit[1]); + } else if (selectSplit[2].equals("date")) { + dateValue = selectRevForm.getDateProperty(selectSplit[1]); + } + + // ȡĿҪĸ + String[] targetSplit = split2[0].split("\\."); + if (targetSplit[0].equals("item")) { + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + revItem.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + revItem.setDateProperty(targetSplit[1], dateValue); + } + + } else if (targetSplit[0].equals("rev")) { + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + rev.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + rev.setDateProperty(targetSplit[1], dateValue); + } + + } else if (targetSplit[0].equals("rm")) { + + if (targetSplit[2].equals("string") || targetSplit[2].equals("lov")) { + revForm.setProperty(targetSplit[1], value); + } else if (targetSplit[2].equals("date")) { + revForm.setDateProperty(targetSplit[1], dateValue); + } + } + + } + + } + + } + MessageBox.post("޸ijɹ", "ʾ", 2); + this.dispose(); + } catch (TCException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + } else if (this.concelButton.equals(source)) { + this.dispose(); + } + + } + + private JPanel getBtnPanel() { + JPanel topPanel = new JPanel(); + topPanel.setLayout(new PropertyLayout()); + topPanel.add("1.1.center", new JLabel("")); + topPanel.add("2.1.center", new JLabel(" ")); + topPanel.add("2.2.center", okButton); + topPanel.add("2.3.center", new JLabel("")); + topPanel.add("2.4.center", concelButton); + + return topPanel; + } + + // ѯ + private JPanel getTopPanel() { + // TODO Auto-generated method stub + JPanel topPanel = new JPanel(); + topPanel.setLayout(new PropertyLayout()); + topPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); + + topPanel.add("1.1.left.center", new JLabel("")); + topPanel.add("2.1.left.center", new JLabel("")); + topPanel.add("3.1.left.center", new JLabel("")); + topPanel.add("4.1.left.center", new JLabel("")); + topPanel.add("5.1.left.center", new JLabel("")); + topPanel.add("6.1.left.center", new JLabel("")); + topPanel.add("7.1.left.center", new JLabel("ѡԴ")); + topPanel.add("7.2.left.center", objectComboBox); + + return topPanel; + } + +} diff --git a/src/com/langtech/plm/synchronize/SynchronizeHandler.java b/src/com/langtech/plm/synchronize/SynchronizeHandler.java new file mode 100644 index 0000000..475f696 --- /dev/null +++ b/src/com/langtech/plm/synchronize/SynchronizeHandler.java @@ -0,0 +1,53 @@ +package com.langtech.plm.synchronize; + +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.commands.ExecutionException; + +import com.teamcenter.rac.aif.AbstractAIFApplication; +import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +public class SynchronizeHandler extends AbstractHandler{ + + + @Override + public Object execute(ExecutionEvent arg0) throws ExecutionException { + AbstractAIFApplication app = AIFUtility.getCurrentApplication(); + TCSession session = (TCSession) app.getSession(); + try { + + new Thread() { + @Override + public void run() { + InterfaceAIFComponent targetComponent = app.getTargetComponent(); + if(targetComponent instanceof TCComponentItemRevision) { + try { + TCComponentItemRevision rev = (TCComponentItemRevision)targetComponent; + new SynchronizeDialog(session,rev); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else { + MessageBox.post("ѡ汾","ʾ",2); + return; + } + + + } + }.start(); + + } catch (Exception e) { + // TODO: handle exception + e.printStackTrace(); + } + + return null; + } + + +} diff --git a/src/com/langtech/plm/template/TemplateDialog.java b/src/com/langtech/plm/template/TemplateDialog.java new file mode 100644 index 0000000..76db51f --- /dev/null +++ b/src/com/langtech/plm/template/TemplateDialog.java @@ -0,0 +1,222 @@ +package com.langtech.plm.template; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.Toolkit; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Map.Entry; + +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.border.EmptyBorder; +import javax.swing.table.DefaultTableModel; + +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.TCComponentForm; +import com.teamcenter.rac.kernel.TCComponentItem; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCComponentScheduleTask; +import com.teamcenter.rac.kernel.TCException; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; +import com.teamcenter.rac.util.PropertyLayout; + +public class TemplateDialog extends JFrame implements ActionListener { + + private TCSession session; + protected DefaultTableModel tm_part; + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + private TCComponentItemRevision rev; + private JComboBox company = new JComboBox(); + private JComboBox template = new JComboBox(); + private JButton okButton = new JButton("ȷ"); + private JButton concelButton = new JButton("ȡ"); + private HashMap map = new HashMap(); + HashMap objectMap = new HashMap(); + + public TemplateDialog(TCSession session, TCComponentItemRevision rev) throws TCException { + // TODO Auto-generated constructor stub + this.session = session; + this.rev = rev; + + initUI(); + } + + private void initUI() { + // TODO Auto-generated method stub + try { + company.setPreferredSize(new Dimension(200,30)); + template.setPreferredSize(new Dimension(200,30)); + this.setTitle("ģ"); + this.setLayout(new BorderLayout()); + + JPanel topPanel = getTopPanel(); + + JPanel btnPanel = getBtnPanel(); + + this.add(topPanel, BorderLayout.NORTH); + // this.add(pane,BorderLayout.CENTER); + this.add(btnPanel, BorderLayout.SOUTH); + this.setPreferredSize(new Dimension(450, 200)); + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); // ȡĻߴ + int screenWidth = screenSize.width; // ȡĻ + int screenHeight = screenSize.height; // ȡĻ߶ + int x = (screenWidth - 450) / 2; // FrameϽx + int y = (screenHeight - 200) / 2; // FrameϽy + this.setLocation(x, y); // Frameλ + + // this.setLocationRelativeTo(null); + this.createActionEvent(); + this.pack(); + + // this.validate(); + this.setVisible(true); + +// this.setAlwaysOnTop(true); + + + + String[] pref = session.getPreferenceService().getStringValues("LY6_MEOP_TemplateType"); + for (int i = 0; i < pref.length; i++) { + String[] split = pref[i].split(":"); + company.addItem(split[0]); + map.put(split[0], split[1]); + } + + String mrselectitem = (String)company.getSelectedItem(); + String mrValue = map.get(mrselectitem); + String[] split = mrValue.split(","); + for (int i = 0; i < split.length; i++) { + template.addItem(split[i]); + } + + //ֵ + company.addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent e) { + if (e.getStateChange() == ItemEvent.SELECTED) { + template.removeAllItems(); + String selectedItem = (String) company.getSelectedItem(); + System.out.println("Selected Item: " + selectedItem); + // ִ + String value = map.get(selectedItem); + String[] split = value.split(","); + for (int i = 0; i < split.length; i++) { + template.addItem(split[i]); + } + } + } + }); + + } catch (Exception e) { + e.printStackTrace(); + return; + } + } + + // Ӽ + public void createActionEvent() { + + this.okButton.addActionListener(this); + this.concelButton.addActionListener(this); + } + + @Override + public void actionPerformed(ActionEvent e) { + // TODO Auto-generated method stub + + Object source = e.getSource(); + System.out.println("source==>+" + source); + if (this.okButton.equals(source)) { + String templateString = (String)template.getSelectedItem(); + String companyString = (String)company.getSelectedItem(); + System.out.println("templateString==="+templateString); + System.out.println("companyString==="+companyString); + if(companyString.isEmpty()) { + MessageBox.post("ѡ˾", "ʾ ", MessageBox.INFORMATION); + return; + } + + if(templateString.isEmpty()) { + MessageBox.post("ѡģ壡", "ʾ ", MessageBox.INFORMATION); + return; + } + + //òѯȡģdwgݼ + try { + TCComponent[] items = session.search("...", new String[] { " ID" }, new String[] {templateString}); + System.out.println("items.length===="+items.length); + TCComponentItem item = null; + if(items.length > 0) { + item = (TCComponentItem)items[0]; + } + TCComponentItemRevision latestItemRevision = item.getLatestItemRevision(); + TCComponent[] relatedComponent = latestItemRevision.getRelatedComponents("IMAN_specification"); + System.out.println("relatedComponent========"+relatedComponent.length); + for (int i = 0; i < relatedComponent.length; i++) { + rev.add("IMAN_specification",relatedComponent[i]); + } + MessageBox.post("ģɹ", "ʾ ", MessageBox.INFORMATION); + this.dispose(); + return; + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + //ݼ + } else if (this.concelButton.equals(source)) { + this.dispose(); + } + + } + + private JPanel getBtnPanel() { + JPanel topPanel = new JPanel(); + topPanel.setLayout(new PropertyLayout()); + topPanel.add("1.1.center", new JLabel("")); + topPanel.add("2.1.center", new JLabel(" ")); + topPanel.add("2.2.center", okButton); + topPanel.add("2.3.center", new JLabel("")); + topPanel.add("2.4.center", concelButton); + + return topPanel; + } + + // ѯ + private JPanel getTopPanel() { + // TODO Auto-generated method stub + JPanel topPanel = new JPanel(); + topPanel.setLayout(new PropertyLayout()); + topPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); + + topPanel.add("1.1.left.center", new JLabel("")); + topPanel.add("2.1.left.center", new JLabel("")); + topPanel.add("3.1.left.center", new JLabel("")); + topPanel.add("4.1.left.center", new JLabel(" ˾")); + topPanel.add("4.2.left.center", company); + + topPanel.add("5.1.left.center", new JLabel("")); + topPanel.add("6.1.left.center", new JLabel("")); + topPanel.add("7.1.left.center", new JLabel("")); + topPanel.add("8.1.left.center", new JLabel(" ģ壺")); + + topPanel.add("8.2.left.center", template); + + return topPanel; + } + +} diff --git a/src/com/langtech/plm/template/TemplateHandler.java b/src/com/langtech/plm/template/TemplateHandler.java new file mode 100644 index 0000000..4ced53a --- /dev/null +++ b/src/com/langtech/plm/template/TemplateHandler.java @@ -0,0 +1,77 @@ +package com.langtech.plm.template; + +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.commands.ExecutionException; + +import com.teamcenter.rac.aif.AbstractAIFApplication; +import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; +import com.teamcenter.rac.aifrcp.AIFUtility; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCComponentSchedule; +import com.teamcenter.rac.kernel.TCComponentScheduleTask; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.util.MessageBox; + +public class TemplateHandler extends AbstractHandler{ + + + @Override + public Object execute(ExecutionEvent arg0) throws ExecutionException { + AbstractAIFApplication app = AIFUtility.getCurrentApplication(); + TCSession session = (TCSession) app.getSession(); + try { + + + + new Thread() { + @Override + public void run() { + InterfaceAIFComponent targetComponent = app.getTargetComponent(); + + if(targetComponent instanceof TCComponentItemRevision) { + try { + String[] pref = session.getPreferenceService().getStringValues("LY6_MEOP_TemplateObject"); + String types = ""; + if(pref.length > 0) { + types = pref[0]; + }else { + MessageBox.post("ѡLY6_MEOP_TemplateObject","ʾ",2); + return; + } + + TCComponentItemRevision rev = (TCComponentItemRevision)targetComponent; + String object_type = rev.getStringProperty("object_type"); + if(types.contains(object_type)) { + new TemplateDialog(session,rev); + }else { + MessageBox.post("ѡѡLY6_MEOP_TemplateObjectƥĶ","ʾ",2); + return; + } + + + + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else { + MessageBox.post("ѡ汾","ʾ",2); + return; + } + + + } + }.start(); + + } catch (Exception e) { + // TODO: handle exception + e.printStackTrace(); + } + + return null; + } + + +} diff --git a/src/com/langtech/plm/performancemanagement/Activator.java b/src/com/langtech/plm/tqsx/Activator.java similarity index 83% rename from src/com/langtech/plm/performancemanagement/Activator.java rename to src/com/langtech/plm/tqsx/Activator.java index 67636fc..303ada3 100644 --- a/src/com/langtech/plm/performancemanagement/Activator.java +++ b/src/com/langtech/plm/tqsx/Activator.java @@ -1,4 +1,4 @@ -package com.langtech.plm.performancemanagement; +package com.langtech.plm.tqsx; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; @@ -9,7 +9,7 @@ import org.osgi.framework.BundleContext; public class Activator extends AbstractUIPlugin { // The plug-in ID - public static final String PLUGIN_ID = "com.langtech.plm.performancemanagement"; //$NON-NLS-1$ + public static final String PLUGIN_ID = "cn.net.connor.ml.plm"; //$NON-NLS-1$ // The shared instance private static Activator plugin; diff --git a/src/com/langtech/plm/tqsx/DateUtil.java b/src/com/langtech/plm/tqsx/DateUtil.java new file mode 100644 index 0000000..4585c06 --- /dev/null +++ b/src/com/langtech/plm/tqsx/DateUtil.java @@ -0,0 +1,603 @@ +package com.langtech.plm.tqsx; + +import java.time.*; +import java.time.format.DateTimeFormatter; +import java.util.Date; + +public class DateUtil { + private static final String HYPHEN = "-"; + private static final String COLON = ":"; + + /* ʱʽ DateTimeFormatter (Java8) */ + enum FormatEnum { + /** + * DateTimeFormatter "yyyy-MM-dd HH:mm:ss" ʱʽ + */ + FORMAT_DATA_TIME(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)), + + /** + * DateTimeFormatter "yyyyMMddHHmmss"ʱʽ + */ + FORMAT_DATA_TIME_NO_SYMBOL(DateTimeFormatter.ofPattern(DATETIME_FORMAT)), + + /** + * DateTimeFormatter "yyyy-MM-dd"ʱʽ + */ + FORMAT_DATE(DateTimeFormatter.ofPattern(DATE_FORMAT)), + + /** + * DateTimeFormatter "HH:mm:ss"ʱʽ + */ + FORMAT_TIME(DateTimeFormatter.ofPattern(TIME_FORMAT)); + + private DateTimeFormatter value; + + FormatEnum(DateTimeFormatter format) { + this.value = format; + } + } + /* ʱʽ DateTimeFormatter (Java8) */ + + /* ʱʽ ַ */ + + /** + * ʱʽ + *
+ * "yyyy" ַ + */ + public static final String YEAR_FORMAT = "yyyy"; + + /** + * µʱʽ + *
+ * "MM" ַ + */ + public static final String MONTH_FORMAT = "MM"; + + /** + * յʱʽ + *
+ * "dd" ַ + */ + public static final String DAY_FORMAT = "dd"; + + /** + * ʱʱʽ + *
+ * "HH" ַ + */ + public static final String HOUR_FORMAT = "HH"; + + /** + * ֵʱʽ + *
+ * "mm" ַ + */ + public static final String MINUTE_FORMAT = "mm"; + + /** + * ʱʽ + *
+ * "ss" ַ + */ + public static final String SECOND_FORMAT = "ss"; + + /** + * --ʱʽ + *
+ * "yyyy-MM-dd" ַ + */ + public static final String DATE_FORMAT = YEAR_FORMAT + HYPHEN + MONTH_FORMAT + HYPHEN + DAY_FORMAT; + + /** + * ʱ::ʱʽ + *
+ * "HH:mm:ss" ַ + */ + public static final String TIME_FORMAT = HOUR_FORMAT + COLON + MINUTE_FORMAT + COLON + SECOND_FORMAT; + + /** + * -- ʱ::ʱʽ + *
+ * "yyyy-MM-dd HH:mm:ss" ַ + */ + public static final String DATE_TIME_FORMAT = DATE_FORMAT + " " + TIME_FORMAT; + + /** + * ʱʱʽ޷ţ + *
+ * "yyyyMMddHHmmss" ַ + */ + public static final String DATETIME_FORMAT = YEAR_FORMAT + MONTH_FORMAT + DAY_FORMAT + HOUR_FORMAT + MINUTE_FORMAT + SECOND_FORMAT; + + /* ʱʽ ַ */ + + + + /* ʱ */ + + /** + * ȡ뼶ʱ + */ + public static Long epochSecond() { + return localDateTime().toEpochSecond(ZoneOffset.of("+8")); + } + + /** + * ȡ뼶ʱ + */ + public static Long epochMilli() { + return localDateTime().toInstant(ZoneOffset.of("+8")).toEpochMilli(); + } + + /* ʱ */ + + + /* ǰʱ */ + + /** + * ȡǰϸʱ䣬like 2018-08-27 17:20:06 + */ + public static String dateTime() { + return localDateTime().format(FormatEnum.FORMAT_DATA_TIME.value); + } + + /** + * ȡǰϸʱ䣬like 20180827172006 + */ + public static String dateTimeNoSymbol() { + return localDateTime().format(FormatEnum.FORMAT_DATA_TIME_NO_SYMBOL.value); + } + + /** + * ȡǰڣlike 2018-08-27 + */ + public static String date() { + return localDate() + ""; + } + + /** + * ȡǰʱ䣬like 17:20:06 + */ + public static String time() { + return localTime().format(FormatEnum.FORMAT_TIME.value); + } + + /** + * ȡǰ + */ + public static Integer year() { + return localDate().getYear(); + } + + /** + * ȡǰ + */ + public static int month() { + return localDate().getMonthValue(); + } + + /** + * ȡǰе + */ + public static Integer dayOfYear() { + return localDate().getDayOfYear(); + } + + /** + * ȡǰе + */ + public static Integer dayOfMonth() { + return localDate().getDayOfMonth(); + } + + /** + * ȡǰе + */ + public static Integer dayOfWeek() { + return localDate().getDayOfWeek().getValue(); + } + + /** + * ȡǰСʱ + */ + public static Integer hour() { + return localTime().getHour(); + } + + /** + * ȡǰ + */ + public static Integer minute() { + return localTime().getMinute(); + } + + /** + * ȡǰ + */ + public static Integer second() { + return localTime().getSecond(); + } + + /* ǰʱ */ + + + + /* δʷʱ */ + + /** + * ȡǰ ǰ + *

+ * + * @param years ǰ + * @param formatEnum ʽ + * @return ǰ ǰ Ӧ ʽ + */ + public static String minusYears(Long years, FormatEnum formatEnum) { + return minusOrPlusYears(-years, formatEnum); + } + + /** + * ȡǰ + *

+ * + * @param years + * @param formatEnum ʽ + * @return ǰ Ӧ ʽ + */ + public static String plusYears(Long years, FormatEnum formatEnum) { + return minusOrPlusYears(years, formatEnum); + } + + /** + * ȡǰµ ǰ + * + * @param months ǰ + * @param formatEnum ʽ + * @return ǰµ ǰ Ӧ ʽ + */ + public static String minusMonths(Long months, FormatEnum formatEnum) { + return minusOrPlusMonths(-months, formatEnum); + } + + /** + * ȡǰµ + * + * @param months + * @param formatEnum ʽ + * @return ǰµ Ӧ ʽ + */ + public static String plusMonths(Long months, FormatEnum formatEnum) { + return minusOrPlusMonths(months, formatEnum); + } + + /** + * ȡǰյ ǰ + * + * @param days ǰ + * @param formatEnum ʽ + * @return ǰյ ǰ Ӧ ʽ + */ + public static String minusDays(Long days, FormatEnum formatEnum) { + return minusOrPlusDays(-days, formatEnum); + } + + /** + * ȡǰյ + * + * @param days + * @param formatEnum ʽ + * @return ǰյ Ӧ ʽ + */ + public static String plusDays(Long days, FormatEnum formatEnum) { + return minusOrPlusDays(days, formatEnum); + } + + /** + * ȡǰڵ ǰ + * + * @param weeks ǰ + * @param formatEnum ʽ + * @return ǰڵ ǰ Ӧ ʽ + */ + public static String minusWeeks(Long weeks, FormatEnum formatEnum) { + return minusOrPlusWeeks(-weeks, formatEnum); + } + + /** + * ȡǰڵ + * + * @param weeks + * @param formatEnum ʽ + * @return ǰڵ Ӧ ʽ + */ + public static String plusWeeks(Long weeks, FormatEnum formatEnum) { + return minusOrPlusWeeks(weeks, formatEnum); + } + + /** + * ȡǰСʱ ǰСʱ + * + * @param hours ǰСʱ + * @param formatEnum ʽ + * @return ǰСʱ ǰСʱ Ӧ ʽ + */ + public static String minusHours(Long hours, FormatEnum formatEnum) { + return minusOrPlusHours(-hours, formatEnum); + } + + /** + * ȡǰСʱ Сʱ + * + * @param hours Сʱ + * @param formatEnum ʽ + * @return ǰСʱ Сʱ Ӧ ʽ + */ + public static String plusHours(Long hours, FormatEnum formatEnum) { + return minusOrPlusHours(hours, formatEnum); + } + + /** + * ȡǰӵ ǰ + * + * @param minutes ǰ + * @param formatEnum ʽ + * @return ǰӵ ǰ Ӧ ʽ + */ + public static String minusMinutes(Long minutes, FormatEnum formatEnum) { + return minusOrPlusMinutes(-minutes, formatEnum); + } + + /** + * ȡǰӵ 󼸷 + * + * @param minutes 󼸷 + * @param formatEnum ʽ + * @return ǰӵ 󼸷 Ӧ ʽ + */ + public static String plusMinutes(Long minutes, FormatEnum formatEnum) { + return minusOrPlusMinutes(minutes, formatEnum); + } + + /** + * ȡǰ ǰ + * + * @param seconds ǰ + * @param formatEnum ʽ + * @return ǰ ǰ Ӧ ʽ + */ + public static String minusSeconds(Long seconds, FormatEnum formatEnum) { + return minusOrPlusSeconds(-seconds, formatEnum); + } + + /** + * ȡǰ ǰ/ + * + * @param seconds + * @param formatEnum ʽ + * @return ǰ Ӧ ʽ + */ + public static String plusSeconds(Long seconds, FormatEnum formatEnum) { + return minusOrPlusSeconds(seconds, formatEnum); + } + + /* δʷʱ */ + + + /* ʱת */ + + /** + * DateתLocalDateTime + *

+ * + * @param date dateʱ + * @return LocalDateTime + */ + public static LocalDateTime toLocalDateTime(Date date) { + return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); + } + + /** + * DateתLocalDate + *

+ * + * @param date dateʱ + * @return LocalDate + */ + public static LocalDate toLocalDate(Date date) { + return toLocalDateTime(date).toLocalDate(); + } + + /** + * DateתLocalTime + *

+ * + * @param date dateʱ + * @return LocalTime + */ + public static LocalTime toLocalTime(Date date) { + return toLocalDateTime(date).toLocalTime(); + } + + /** + * LocalDateTime ת Date + * + * @param localDateTime localDateTime + * @return תDate + */ + public static Date toDate(LocalDateTime localDateTime) { + return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); + } + + /** + * LocalDateתDate + * + * @param localDate localDate + * @return תDate + */ + public static Date toDate(LocalDate localDate) { + return toDate(localDate.atStartOfDay()); + } + + /** + * LocalTimeתDate + * + * @param localTime localTime + * @return תDate + */ + public static Date toDate(LocalTime localTime) { + return toDate(LocalDateTime.of(localDate(), localTime)); + } + + /* ʱת */ + + + /* ʱ */ + + /** + * ȡ endDate-startDate ʱ + *
ˣ leigq + *
ʱ䣺 2018-11-07 09:55 + *
+ * + * @param startDate ʼʱ + * @param endDate ʱ + * @return ʱ + */ + public static Long daysInterval(LocalDate startDate, LocalDate endDate) { + return endDate.toEpochDay() - startDate.toEpochDay(); + } + + /** + * ȡ endDate-startDate ʱ + *
ˣ leigq + *
ʱ䣺 2018-11-07 09:55 + *
+ * + * @param startDate ʼʱ + * @param endDate ʱ + * @return ʱ + */ + public static Long daysInterval(String startDate, String endDate) { + return daysInterval(LocalDateTime.parse(endDate, FormatEnum.FORMAT_DATA_TIME.value).toLocalDate(), + LocalDateTime.parse(startDate, FormatEnum.FORMAT_DATA_TIME.value).toLocalDate()); + } + + /** + * ȡ endDate-startDate ʱ + *
ˣ leigq + *
ʱ䣺 2018-11-07 09:55 + *
+ * + * @param startDate ʼʱ + * @param endDate ʱ + * @return ʱ + */ + public static Long daysInterval(LocalDateTime startDate, LocalDateTime endDate) { + return daysInterval(startDate.toLocalDate(), endDate.toLocalDate()); + } + + /* ʱ */ + + /*ֻá*/ + + /** + * ȡ ǰ ǰ/ + *

+ * + * @param yearsToAddOrSubtract 괫ǰ괫 + * @param formatEnum ʽ + * @return ǰǰ/ĶӦ ʽ + */ + private static String minusOrPlusYears(Long yearsToAddOrSubtract, FormatEnum formatEnum) { + return localDateTime().plusYears(yearsToAddOrSubtract).format(formatEnum.value); + } + + /** + * ȡ ǰ ǰ/µ + * + * @param monthsToAddOrSubtract ´ǰ´ + * @param formatEnum ʽ + * @return ǰµǰ/µĶӦ ʽ + */ + private static String minusOrPlusMonths(Long monthsToAddOrSubtract, FormatEnum formatEnum) { + return localDateTime().plusMonths(monthsToAddOrSubtract).format(formatEnum.value); + } + + /** + * ȡ ǰ ǰ/յ + * + * @param daysToAddOrSubtract մǰմ + * @param formatEnum ʽ + * @return ǰյǰ/յ Ӧ ʽ + */ + private static String minusOrPlusDays(Long daysToAddOrSubtract, FormatEnum formatEnum) { + return localDateTime().plusDays(daysToAddOrSubtract).format(formatEnum.value); + } + + /** + * ȡǰڵǰ/ڵ + * + * @param weeksToAddOrSubtract ڴǰڴ + * @param formatEnum ʽ + * @return ǰڵǰ/ڵ Ӧ ʽ + */ + private static String minusOrPlusWeeks(Long weeksToAddOrSubtract, FormatEnum formatEnum) { + return localDateTime().plusWeeks(weeksToAddOrSubtract).format(formatEnum.value); + } + + /** + * ȡǰСʱǰСʱ/Сʱ + * + * @param hoursToAddOrSubtract СʱǰСʱ + * @param formatEnum ʽ + * @return ǰСʱǰСʱ/Сʱ Ӧ ʽ + */ + private static String minusOrPlusHours(Long hoursToAddOrSubtract, FormatEnum formatEnum) { + return localDateTime().plusHours(hoursToAddOrSubtract).format(formatEnum.value); + } + + /** + * ȡǰӵǰ/󼸷ӵ + * + * @param minutesToAddOrSubtract 󼸷ӴǰӴ + * @param formatEnum ʽ + * @return ǰӵǰ/󼸷ӵ Ӧ ʽ + */ + private static String minusOrPlusMinutes(Long minutesToAddOrSubtract, FormatEnum formatEnum) { + return localDateTime().plusMinutes(minutesToAddOrSubtract).format(formatEnum.value); + } + + /** + * ȡǰǰ/ + * + * @param secondsToAddOrSubtract 봫ǰ봫 + * @param formatEnum ʽ + * @return ǰǰ/ Ӧ ʽ + */ + private static String minusOrPlusSeconds(Long secondsToAddOrSubtract, FormatEnum formatEnum) { + return localDateTime().plusSeconds(secondsToAddOrSubtract).format(formatEnum.value); + } + + /** + * ȡ LocalDate + */ + private static LocalDate localDate() { + return localDateTime().toLocalDate(); + } + + /** + * ȡ LocalTime + */ + private static LocalTime localTime() { + return localDateTime().toLocalTime(); + } + + /** + * ȡ LocalDateTime + */ + private static LocalDateTime localDateTime() { + return LocalDateTime.now(); + } + +} diff --git a/src/com/langtech/plm/tqsx/KAction.java b/src/com/langtech/plm/tqsx/KAction.java new file mode 100644 index 0000000..b2700d2 --- /dev/null +++ b/src/com/langtech/plm/tqsx/KAction.java @@ -0,0 +1,37 @@ +package com.langtech.plm.tqsx; + +import java.lang.reflect.Constructor; + +import com.teamcenter.rac.aif.AbstractAIFApplication; +import com.teamcenter.rac.aif.AbstractAIFUIApplication; +import com.teamcenter.rac.aif.common.actions.AbstractAIFAction; +import com.teamcenter.rac.util.MessageBox; + + +public class KAction extends AbstractAIFAction { + + + KAction(AbstractAIFUIApplication app, String string) { + super(app,string); + } + + @Override + public void run() { + try { + int ind = actionName.indexOf('#'); + String action=actionName; + String actionData=""; + if(ind>0) { + action=actionName.substring(0,ind); + actionData=actionName.substring(ind+1); + } + Class c = Class.forName(action); + Constructor constructor = c.getConstructor(AbstractAIFApplication.class, String.class,String.class); + KCommand command = (KCommand) constructor.newInstance(this.application, action, actionData); + command.executeModal(); + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(e.toString(),KLocale.getString("error"),MessageBox.ERROR); + } + } +} diff --git a/src/com/langtech/plm/tqsx/KCommand.java b/src/com/langtech/plm/tqsx/KCommand.java new file mode 100644 index 0000000..744f790 --- /dev/null +++ b/src/com/langtech/plm/tqsx/KCommand.java @@ -0,0 +1,16 @@ +package com.langtech.plm.tqsx; + +import com.teamcenter.rac.aif.AbstractAIFApplication; +import com.teamcenter.rac.aif.AbstractAIFCommand; + +public abstract class KCommand extends AbstractAIFCommand { + + protected AbstractAIFApplication app; + protected String actionInfo; + + public KCommand(AbstractAIFApplication app, String commandId, String actionInfo) { + this.app = app; + this.actionInfo = actionInfo; + } + +} diff --git a/src/com/langtech/plm/tqsx/KHandler.java b/src/com/langtech/plm/tqsx/KHandler.java new file mode 100644 index 0000000..0d6563e --- /dev/null +++ b/src/com/langtech/plm/tqsx/KHandler.java @@ -0,0 +1,24 @@ +package com.langtech.plm.tqsx; + +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.core.commands.ExecutionEvent; + +import com.teamcenter.rac.aif.AbstractAIFUIApplication; +import com.teamcenter.rac.aifrcp.AIFUtility; + +/** + * Add following config to MANIFEST.MF + * Eclipse-RegisterBuddy: k.util + * @author Administrator + * + */ +public class KHandler extends AbstractHandler { + + @Override + public Object execute(ExecutionEvent arg0) { + AbstractAIFUIApplication app = AIFUtility.getCurrentApplication(); + new Thread(new KAction(app,arg0.getCommand().getId())).start(); + return null; + } + +} diff --git a/src/com/langtech/plm/tqsx/KLocale.java b/src/com/langtech/plm/tqsx/KLocale.java new file mode 100644 index 0000000..76adff7 --- /dev/null +++ b/src/com/langtech/plm/tqsx/KLocale.java @@ -0,0 +1,22 @@ +package com.langtech.plm.tqsx; + +import com.teamcenter.rac.util.Registry; + + +public class KLocale { + + public static final Registry reg = Registry.getRegistry(KLocale.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()); + } +} diff --git a/src/com/langtech/plm/tqsx/KOperation.java b/src/com/langtech/plm/tqsx/KOperation.java new file mode 100644 index 0000000..704bb53 --- /dev/null +++ b/src/com/langtech/plm/tqsx/KOperation.java @@ -0,0 +1,54 @@ +package com.langtech.plm.tqsx; + +import java.awt.Dimension; + +import com.teamcenter.rac.aif.AbstractAIFApplication; +import com.teamcenter.rac.aif.AbstractAIFOperation; +import com.teamcenter.rac.kernel.TCSession; + +import k.util.ProgressBar; + +/* + * do not call executeOperation yourself + * use session.performOperation + */ +public abstract class KOperation extends AbstractAIFOperation { + + protected AbstractAIFApplication app; + protected TCSession session; + public String messageLabel; + + public KOperation(AbstractAIFApplication app, String opName, String messageLabel) { + super(opName, true); + this.app = app; + this.session = (TCSession) app.getSession(); + this.messageLabel = messageLabel;// Ϣ + setSession(session); + } + + public abstract boolean init() throws Exception; + + public abstract void execute() throws Exception; + + @Override + public void executeOperation() { + ProgressBar pb = new ProgressBar(new Dimension(250, 50), true); + try { + pb.showDialog(); + pb.setText(messageLabel); + setStatus("Checking Data..."); + if (!init()) { + pb.disposeDialog(); + return; + } + setStatus("Execute..."); + pb.setText(messageLabel); + execute(); + pb.disposeDialog(); + } catch (Exception e) { + pb.disposeDialog(); + KUtil.error(getCurrentDesktop(), "쳣\n" + e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/src/com/langtech/plm/tqsx/KOperation2.java b/src/com/langtech/plm/tqsx/KOperation2.java new file mode 100644 index 0000000..f9f3b90 --- /dev/null +++ b/src/com/langtech/plm/tqsx/KOperation2.java @@ -0,0 +1,53 @@ +package com.langtech.plm.tqsx; + +import java.awt.Dimension; + +import com.teamcenter.rac.aif.AbstractAIFApplication; +import com.teamcenter.rac.aif.AbstractAIFOperation; +import com.teamcenter.rac.kernel.TCSession; + +import k.util.ProgressBar; + +/* + * do not call executeOperation yourself + * use session.performOperation + */ +public abstract class KOperation2 extends AbstractAIFOperation { + + protected AbstractAIFApplication app; + protected TCSession session; + protected ProgressBar pb; + + public KOperation2(AbstractAIFApplication app, String opName) { + super(opName, true); + this.app = app; + this.session = (TCSession) app.getSession(); + setSession(session); + } + + public abstract boolean init() throws Exception; + + public abstract void execute() throws Exception; + + @Override + public void executeOperation() { + pb = new ProgressBar(new Dimension(250, 50), true); + try { + pb.showDialog(); + setStatus(KLocale.getString("initop.STATUS")); + if (!init()) { + pb.disposeDialog(); + return; + } + setStatus(KLocale.getString("exeop.STATUS")); + execute(); + KUtil.setByPass(false); + pb.disposeDialog(); + } catch (Exception e) { + pb.disposeDialog(); + KUtil.setByPass(false); + KUtil.error(getCurrentDesktop(), "쳣\n" + e); + e.printStackTrace(); + } + } +} diff --git a/src/com/langtech/plm/tqsx/KUtil.java b/src/com/langtech/plm/tqsx/KUtil.java new file mode 100644 index 0000000..21c5ee5 --- /dev/null +++ b/src/com/langtech/plm/tqsx/KUtil.java @@ -0,0 +1,2348 @@ +package com.langtech.plm.tqsx; + +import java.awt.Component; +import java.awt.Dimension; +import java.awt.GridBagConstraints; +import java.awt.Window; +import java.io.BufferedWriter; +import java.io.EOFException; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileWriter; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.text.DecimalFormat; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JDialog; +import javax.swing.JFileChooser; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.filechooser.FileNameExtensionFilter; +import javax.swing.filechooser.FileSystemView; + +import org.apache.poi.hssf.usermodel.HSSFCell; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellType; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.ss.usermodel.WorkbookFactory; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Shell; + + +import com.teamcenter.rac.aif.commands.open.OpenCommand; +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.lov.view.components.LOVDisplayer; +import com.teamcenter.rac.kernel.ListOfValuesInfo; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentContextList; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentDatasetType; +import com.teamcenter.rac.kernel.TCComponentFolder; +import com.teamcenter.rac.kernel.TCComponentForm; +import com.teamcenter.rac.kernel.TCComponentGroup; +import com.teamcenter.rac.kernel.TCComponentGroupMember; +import com.teamcenter.rac.kernel.TCComponentItem; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCComponentItemRevisionType; +import com.teamcenter.rac.kernel.TCComponentItemType; +import com.teamcenter.rac.kernel.TCComponentListOfValues; +import com.teamcenter.rac.kernel.TCComponentListOfValuesType; +import com.teamcenter.rac.kernel.TCComponentManager; +import com.teamcenter.rac.kernel.TCComponentQuery; +import com.teamcenter.rac.kernel.TCComponentQueryType; +import com.teamcenter.rac.kernel.TCComponentRole; +import com.teamcenter.rac.kernel.TCComponentSchedule; +import com.teamcenter.rac.kernel.TCComponentScheduleDeliverable; +import com.teamcenter.rac.kernel.TCComponentTCCalendar; +import com.teamcenter.rac.kernel.TCComponentTaskDeliverable; +import com.teamcenter.rac.kernel.TCComponentType; +import com.teamcenter.rac.kernel.TCComponentUser; +import com.teamcenter.rac.kernel.TCException; +import com.teamcenter.rac.kernel.TCProperty; +import com.teamcenter.rac.kernel.TCPropertyDescriptor; +import com.teamcenter.rac.kernel.TCSession; +import com.teamcenter.rac.kernel.TCTextService; +import com.teamcenter.rac.kernel.TCUserService; +import com.teamcenter.rac.schedule.calendar.TCCalendar; +import com.teamcenter.rac.schedule.componentutils.CalendarHelper; +import com.teamcenter.rac.ui.common.RACUIUtil; +import com.teamcenter.rac.util.MessageBox; +import com.teamcenter.rac.util.Registry; +import com.teamcenter.rac.util.UIUtilities; +import com.teamcenter.services.rac.core.DataManagementService; +import com.teamcenter.services.rac.core.LOVService; +import com.teamcenter.services.rac.core._2006_03.DataManagement.Relationship; +import com.teamcenter.services.rac.core._2007_01.DataManagement.WhereReferencedInfo; +import com.teamcenter.services.rac.core._2007_01.DataManagement.WhereReferencedOutput; +import com.teamcenter.services.rac.core._2007_01.DataManagement.WhereReferencedResponse; +import com.teamcenter.services.rac.core._2008_06.DataManagement.CreateIn; +import com.teamcenter.services.rac.core._2008_06.DataManagement.CreateInput; +import com.teamcenter.services.rac.core._2008_06.DataManagement.CreateOut; +import com.teamcenter.services.rac.core._2008_06.DataManagement.CreateResponse; +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; +import com.teamcenter.soa.client.model.LovValue; +import com.teamcenter.soa.client.model.ServiceData; + +@SuppressWarnings("deprecation") +public class KUtil { + + public static final TCSession session; + public static final TCTextService textService; +// public static final Registry REG = Registry.getRegistry(KUtil.class); + public static final ZoneId zoneId = ZoneId.systemDefault(); +// public static final Registry reg = Registry.getRegistry(KUtil.class); + +// public static String getRegString(String title) { +// String res = reg.getString(title); +// if (KUtil.isEmpty(res)) { +// return title; +// } +// return res; +// } + + static { + session = (TCSession) AIFUtility.getCurrentApplication().getSession(); + textService = session.getTextService(); + } + + public static void setTCPropertyValue(TCComponent item, String propertyName, Object value) { + try { + TCProperty tcProperty = item.getTCProperty(propertyName); + switch (tcProperty.getPropertyType()) { + case TCProperty.PROP_double: + if (value instanceof Double) { + tcProperty.setDoubleValue((double) value); + } else { + tcProperty.setDoubleValue(Double.parseDouble(value.toString())); + } + break; + case TCProperty.PROP_int: + if (value instanceof Integer) { + tcProperty.setDoubleValue((int) value); + } else { + tcProperty.setDoubleValue(Integer.parseInt(value.toString())); + } + break; + case TCProperty.PROP_string: + tcProperty.setStringValue(value.toString()); + break; + case TCProperty.PROP_date: + if (value instanceof Date) { + tcProperty.setDateValue((Date) value); + } else { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-dd HH:mm"); + tcProperty.setDateValue(sdf.parse(value.toString())); + } + break; + default: + break; + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static Object getTCPropertyValue(TCComponent item, String propertyName) { + Object result = ""; + try { + TCProperty tcProperty = item.getTCProperty(propertyName); + if (tcProperty == null) { + System.out.println("δȡԣ" + propertyName); + return result; + } + switch (tcProperty.getPropertyType()) { + case TCProperty.PROP_double: + result = tcProperty.getDoubleValue(); + break; + case TCProperty.PROP_int: + result = tcProperty.getIntValue(); + break; + case TCProperty.PROP_string: + result = tcProperty.getStringValue(); + break; + case TCProperty.PROP_date: + result = tcProperty.getDateValue(); + break; + case TCProperty.PROP_logical: + result = tcProperty.getLogicalValue(); + break; + default: + break; + } + } catch (TCException e) { + e.printStackTrace(); + } + return result; + } + + public static String getCellValue(Cell c) { + if (c == null) { + return ""; + } + String value = ""; + if (c.getCellType() == CellType.NUMERIC.getCode()) { + DecimalFormat df = new DecimalFormat("0"); + String whatYourWant = df.format(c.getNumericCellValue()); + return whatYourWant; + } + switch (c.getCellType()) { + case HSSFCell.CELL_TYPE_NUMERIC:// + value = (c.getNumericCellValue() + "").split("\\.")[0]; + break; + case HSSFCell.CELL_TYPE_STRING:// ַ + value = c.getStringCellValue(); + break; + case HSSFCell.CELL_TYPE_BOOLEAN:// boolean + value = c.getBooleanCellValue() + ""; + break; + case HSSFCell.CELL_TYPE_FORMULA:// ʽ + value = c.getCellFormula() + ""; + break; + case HSSFCell.CELL_TYPE_BLANK:// ֵ + value = ""; + break; + case HSSFCell.CELL_TYPE_ERROR: + value = "Ƿַ"; + break; + default: + value = "δ֪"; + break; + } + return value; + } + + /** + * õʵ + * + * @param sheet + * @param flag ҪдݿExcelԪöŸ Excel5еԪ4 + * Ҫ⣬2вҪ⣬flagʹ [0,2,3,4] + * @return + * @throws Exception + * + */ + public static int findRealRows(Sheet sheet, int... flag) throws Exception { + int row_real = 0; + int rows = sheet.getPhysicalNumberOfRows();// ˴ͳд, + try { + + for (int i = 1; i < rows; i++) { + Row row = sheet.getRow(i); + int total = 0; + ArrayList blank = new ArrayList(); + int type = -1; + String s = null; + for (int j : flag) { + if (!(row.getCell(j) == null) && row.getCell(j).getCellType() < 2) { + type = row.getCell(j).getCellType(); + row.getCell(j).setCellType(1); + } + + if (row.getCell(j) == null || row.getCell(j).getStringCellValue().matches("^\\s+$") + || row.getCell(j).getCellType() > 2) { + total++; + + if (!(row.getCell(j) == null) && row.getCell(j).getCellType() < 2) { + row.getCell(j).setCellType(type); + } + blank.add(j); + + } + } + System.out.println(s + ""); + // 4жǿ˵͸÷ + if (total == flag.length) { + + return row_real; + } else if (total == 0) { + row_real++; + + } else { + String h = ""; + for (Integer b : blank) { + + h = h + "" + (b + 1) + "" + " "; + } + throw new Exception("" + (i + 1) + "" + h + "Ϊ"); + } + + } + } catch (NullPointerException e) { + throw new Exception("excelʽ쳣,excelʽȱʧ,Ч!"); + } + return row_real; + } + + public static Workbook getWorkbook(File file) throws Exception { + Workbook workbook = null; + FileInputStream in = new FileInputStream(file); + if (file.getName().endsWith("xlsx")) { + System.out.println("ȡģ:" + file.getName()); + try { + workbook = WorkbookFactory.create(in); + } catch (EOFException e) { + e.printStackTrace(); + } +// workbook = new XSSFWorkbook(in); + } else { + System.out.println("ʽ"); + } + in.close(); + return workbook; + } + + public static void removeEnd(StringBuilder sb, int len) { + if (sb == null || len <= 0) { + return; + } + if (sb.length() >= len) { + sb.setLength(sb.length() - len); + } + } + + public static TCComponent[] getComponentsByItemType(TCComponent comp, String type, String relation) + throws TCException { + TCComponent[] comps1 = comp.getRelatedComponents(relation); + if (comps1 == null || comps1.length < 1) { + return null; + } + ArrayList list = new ArrayList(); + for (TCComponent comp1 : comps1) { + if (comp1.getType().equals(type)) { + list.add(comp1); + } + } + return list.toArray(new TCComponent[] {}); + } + + public static TCComponentContextList objectsInProject(String type, String projId) throws Exception { + if (KUtil.isEmpty(type) || KUtil.isEmpty(projId)) { + return null; + } + String queryName = "Objects in Projects"; + String[] keys = new String[] { KUtil.getText("Type"), KUtil.getText("ProjectID") }; + String[] vals = new String[] { type, projId }; + return KUtil.query(KUtil.session, queryName, keys, vals); + } + + public static TCComponentContextList objectsInProject(String type, String projId, String name) throws Exception { + if (KUtil.isEmpty(type) || KUtil.isEmpty(projId) || KUtil.isEmpty(name)) { + return null; + } + String queryName = "Objects in Projects"; + String[] keys = new String[] { KUtil.getText("Name"), KUtil.getText("Type"), KUtil.getText("ProjectID") }; + String[] vals = new String[] { name, type, projId }; + return KUtil.query(KUtil.session, queryName, keys, vals); + } + + public static boolean checkGMPrivilegeFromPref(String prefName) throws Exception { + boolean validityCanEdit = false; + String validRoles = KUtil.getPrefVal(KUtil.session, prefName); + System.out.println(">> Check GroupMember Priv: " + validRoles); + if (!KUtil.isEmpty(validRoles)) { + List groups = new ArrayList(); + List roles = new ArrayList(); + String[] split = validRoles.split(":"); + for (String string : split) { + if (string.startsWith("G.")) { + groups.add(string.substring(2)); + } else if (string.startsWith("R.")) { + roles.add(string.substring(2)); + } + } + TCComponentUser currentUser = KUtil.session.getUser(); + System.out.println(">> Current User: " + currentUser); + TCComponentGroupMember[] gms = currentUser.getGroupMembers(); + System.out.println(">> Current GroupMembers: " + Arrays.toString(gms)); + int len = KUtil.getLen(gms); + for (int i = 0; i < len; i++) { + TCComponentGroupMember gm = gms[i]; + TCComponentGroup g = gm.getGroup(); + TCComponentRole r = gm.getRole(); + String gName = g.getGroupName(); + String rName = r.getRoleName(); + System.out.println((i + 1) + ". " + gName + " - " + rName); + if (groups.contains(gName) && roles.contains(rName)) { + validityCanEdit = true; + // break; + } + } + } + return validityCanEdit; + } + + public static boolean compare(String str1, String str2) { + if (str1 == null) { + str1 = ""; + } + if (str2 == null) { + str2 = ""; + } + return str1.equals(str2); + } + + public static boolean compare(Object str1, Object str2) { + if (str1 == null) { + return str2 == null; + } + return str1.equals(str2); + } + + public static TCComponentItem createItem(TCComponentItemType itemType, String itemName) throws Exception { + if (itemType == null) { + return null; + } + String id = itemType.getNewID(); + String rev = itemType.getNewRev(null); + return itemType.create(id, rev, itemType.getName(), itemName, "", null); + } + + public static void setByPass(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 TCComponentItem createItemBySOA(String itemTypeName, String revTypeName, String revMasterTypeName, + String itemId, String revId, String name, Map stringProps, Map dateProps) + throws Exception { + if (KUtil.isEmpty(itemTypeName) || KUtil.isEmpty(revTypeName) || KUtil.isEmpty(revMasterTypeName)) { + return null; + } + CreateInput revMasterInput = new CreateInput(); + revMasterInput.boName = revMasterTypeName; + if (stringProps != null) { + revMasterInput.stringProps = stringProps; + } + if (dateProps != null) { + revMasterInput.dateProps = dateProps; + } + CreateInput revInput = new CreateInput(); + revInput.boName = revTypeName; + Map revPropMap = new HashMap<>(); + if (!KUtil.isEmpty(revId)) { + revPropMap.put("item_revision_id", revId); + } + revInput.stringProps = revPropMap; + Map revMasterInfoMap = new HashMap<>(); + revMasterInfoMap.put("IMAN_master_form_rev", new CreateInput[] { revMasterInput }); + revInput.compoundCreateInput = revMasterInfoMap; + // create rev + CreateInput itemInput = new CreateInput(); + itemInput.boName = itemTypeName; + Map itemPropMap = new HashMap<>(); + if (!KUtil.isEmpty(itemId)) { + itemPropMap.put("item_id", itemId); + } + if (!KUtil.isEmpty(name)) { + itemPropMap.put("object_name", name); + } + itemInput.stringProps = itemPropMap; + Map revInfoMap = new HashMap<>(); + revInfoMap.put("revision", new CreateInput[] { revInput }); + itemInput.compoundCreateInput = revInfoMap; + // create info + CreateIn cI = new CreateIn(); + cI.clientId = "CreateItem"; + cI.data = itemInput; + // service + DataManagementService service = DataManagementService.getService(session); + // create + CreateResponse resp = service.createObjects(new CreateIn[] { cI }); + throwServiceDataError(resp.serviceData); + CreateOut[] cOs = resp.output; + if (cOs.length > 0) { + for (TCComponent s : cOs[0].objects) { + if (s instanceof TCComponentItem) { + return (TCComponentItem) s; + } + } + } + return null; + } + + public static TCComponentFolder createFolderBySOA(String folderTypeName, String folderName) throws Exception { + if (KUtil.isEmpty(folderTypeName)) { + return null; + } + CreateInput itemInput = new CreateInput(); + itemInput.boName = folderTypeName; + Map itemPropMap = new HashMap<>(); + itemPropMap.put("object_name", folderName); + itemInput.stringProps = itemPropMap; + // create info + CreateIn cI = new CreateIn(); + cI.clientId = "CreateFolder"; + cI.data = itemInput; + // service + DataManagementService service = DataManagementService.getService(session); + // create + CreateResponse resp = service.createObjects(new CreateIn[] { cI }); + throwServiceDataError(resp.serviceData); + CreateOut[] cOs = resp.output; + if (cOs.length > 0) { + for (TCComponent s : cOs[0].objects) { + if (s instanceof TCComponentFolder) { + return (TCComponentFolder) s; + } + } + } + return null; + } + + public static void throwServiceDataError(ServiceData serviceData) throws Exception { + if (serviceData.sizeOfPartialErrors() > 0) { + StringBuilder errInfo = new StringBuilder(); + for (int i = 0; i < serviceData.sizeOfPartialErrors(); i++) { + for (String msg : serviceData.getPartialError(i).getMessages()) { + errInfo.append(msg + "\n"); + } + } + // System.out.println(errInfo.toString()); + throw new Exception(errInfo.toString()); + } + } + + public static void throwServiceDataError(ServiceData serviceData, String defaultErrorMsg) throws Exception { + if (serviceData.sizeOfPartialErrors() > 0) { + StringBuilder errInfo = new StringBuilder(); + for (int i = 0; i < serviceData.sizeOfPartialErrors(); i++) { + for (String msg : serviceData.getPartialError(i).getMessages()) { + errInfo.append(msg + "\n"); + } + } + // System.out.println(errInfo.toString()); + if (KUtil.isEmpty(errInfo.toString())) { + throw new Exception(defaultErrorMsg); + } + throw new Exception(errInfo.toString()); + } + } + + public static Date localDateToDate(LocalDate localDate) { + if (localDate == null) { + return null; + } + ZonedDateTime zdt = localDate.atStartOfDay(zoneId); + Date date = Date.from(zdt.toInstant()); + return date; + } + + public static LocalDate dateToLocalDate(Date date) { + if (date == null) { + return null; + } + Instant instant = date.toInstant(); + LocalDate localDate = instant.atZone(zoneId).toLocalDate(); + return localDate; + } + + public static TCComponent stringToComponent(String uid) throws Exception { + if (KUtil.isEmpty(uid)) { + return null; + } + return session.stringToComponent(uid); + } + + public static String getText(String str) throws Exception { + if (KUtil.isEmpty(str)) { + return str; + } + String res = textService.getTextValue(str); + if (!KUtil.isEmpty(res)) { + return res; + } + return str; + } + + public static void sendTo(TCComponent comp, String perspectiveId) { + if (comp == null) { + return; + } + if (KUtil.isEmpty(perspectiveId)) { + perspectiveId = "com.teamcenter.rac.ui.perspectives.navigatorPerspective"; + } + com.teamcenter.rac.common.Activator.getDefault().openPerspective(perspectiveId); + com.teamcenter.rac.common.Activator.getDefault().openComponents(perspectiveId, new TCComponent[] { comp }); + } + + public static void open(TCComponent comp) { + if (comp == null) { + return; + } + if (comp instanceof TCComponentScheduleDeliverable) { + System.out.println(">> Open Schedule Deliverable: " + comp); + try { + comp = comp.getReferenceProperty("deliverable_inst"); + System.out.println(">> Open Schedule Deliverable Inst: " + comp); + if (comp == null) { + return; + } + } catch (Exception e) { + e.printStackTrace(); + } + } else if (comp instanceof TCComponentTaskDeliverable) { + System.out.println(">> Open Task Deliverable: " + comp); + try { + comp = comp.getReferenceProperty("fnd0DeliverableInstance"); + System.out.println(">> Open Task Deliverable Inst: " + comp); + if (comp == null) { + return; + } + } catch (Exception e) { + e.printStackTrace(); + } + } + try { + Registry localRegistry = Registry.getRegistry("com.teamcenter.rac.commands.open.open"); + OpenCommand localOpenCommand = (OpenCommand) localRegistry.newInstanceForEx("openCommand", + new Object[] { AIFUtility.getActiveDesktop(), comp }); + localOpenCommand.executeModeless(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static JButton getImageBtn(String iconName) { + ImageIcon icon = new ImageIcon(KUtil.class.getResource("/icons/" + iconName)); + JButton btn = new JButton(icon); + btn.setPreferredSize(new Dimension(26, 26)); + btn.setContentAreaFilled(true); + btn.setFocusPainted(false); + btn.setBorderPainted(true); + // btn.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); + return btn; + } + + public static void info(Window dialog, String msg) { + MessageBox.post(dialog, msg, "", MessageBox.INFORMATION); + } + + public static void warn(Window dialog, String msg) { + MessageBox.post(dialog, msg, "", MessageBox.WARNING); + } + + public static void error(Window dialog, String msg) { + MessageBox.post(dialog, msg, "", MessageBox.ERROR); + } + + public static void error(Window dialog, String msg, String title) { + MessageBox.post(dialog, msg, title, MessageBox.ERROR); + } + + public static void showScrollDialog(Window dialog, String text, String title) { + if (dialog == null) { + dialog = UIUtilities.getCurrentModalDialog(); + } + JTextArea textArea = new JTextArea(text); + textArea.setEditable(false); + JScrollPane scrollPane = new JScrollPane(textArea); + textArea.setLineWrap(true); + textArea.setWrapStyleWord(true); + scrollPane.setPreferredSize(new Dimension(500, 300)); + JOptionPane.showMessageDialog(dialog, scrollPane, title, JOptionPane.INFORMATION_MESSAGE); + } + + public static void showScrollDialogWithExport(Window dialog, String text, String title, String exportFileName) { + if (dialog == null) { + dialog = UIUtilities.getCurrentModalDialog(); + } + JTextArea textArea = new JTextArea(text); + textArea.setEditable(false); + JScrollPane scrollPane = new JScrollPane(textArea); + textArea.setLineWrap(true); + textArea.setWrapStyleWord(true); + scrollPane.setPreferredSize(new Dimension(500, 300)); + String yesOption = KLocale.getString("ok"); + String exportOption = KLocale.getString("export"); + int op = JOptionPane.showOptionDialog(dialog, scrollPane, title, JOptionPane.YES_NO_OPTION, + JOptionPane.INFORMATION_MESSAGE, null, new String[] { yesOption, exportOption }, yesOption); + if (op == 1) { + System.out.println("Export"); + File saveFile = KUtil.chooseSaveFile(dialog, exportFileName, "txt"); + if (saveFile != null) { + try { + BufferedWriter writer = new BufferedWriter(new FileWriter(saveFile, false)); + writer.write(text); + writer.flush(); + writer.close(); + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(dialog, e); + } + } + } + } + + public static void errorSWT(Shell shell, String message, String title) { + showDialog(shell, message, title, SWT.ICON_ERROR); + } + + public static void showDialog(Shell shell, String message, String title, int type) { + org.eclipse.swt.widgets.MessageBox dialog = new org.eclipse.swt.widgets.MessageBox(shell, SWT.OK | type); + dialog.setText(title); + dialog.setMessage(message); + dialog.open(); + } + + public static String[] getPrefVals(TCSession session, String prefName) throws Exception { + if (KUtil.isEmpty(prefName)) { + return null; + } + return session.getPreferenceService().getStringValues(prefName); + } + + public static String getPrefVal(TCSession session, String prefName) throws Exception { + if (KUtil.isEmpty(prefName)) { + return null; + } + return session.getPreferenceService().getStringValue(prefName); + } + + public static String getReg(Registry reg, String name) { + String val = reg.getString(name); + // System.out.println("Read REG: " + name + " = " + val); + return val; + } + +// public static String getReg(String name) { +// return getReg(REG, name); +// } + + public static void newRow(JPanel panel, Component comp, GridBagConstraints s, int width) { + newRow(panel, comp, s, width, 0); + } + + public static void newRow(JPanel panel, Component comp, GridBagConstraints s, int width, double weightx) { + s.weightx = weightx; + s.gridwidth = width; + s.gridx = 0; + s.gridy++; + panel.add(comp, s); + } + + public static void newRow(JDialog panel, Component comp, GridBagConstraints s, int width) { + s.weightx = 0; + s.gridwidth = width; + s.gridx = 0; + s.gridy++; + panel.add(comp, s); + } + + public static void addCol(JPanel panel, Component comp, GridBagConstraints s, int width, double weightx) { + s.gridx++; + s.gridwidth = width; + s.weightx = weightx; + panel.add(comp, s); + } + + public static TCComponentDataset getDataset(TCComponent rev, String dsType, String dsName, String rel) + throws Exception { + if (rev == null || KUtil.isEmpty(dsName)) { + return null; + } + rev.refresh(); + TCComponent[] kids = rev.getRelatedComponents(rel); + for (TCComponent c : kids) { + if (c.getType().equals(dsType) && c.toString().equals(dsName)) { + return (TCComponentDataset) c; + } + } + return null; + } + + public static List getDatasets(TCComponent rev, String dsType, String rel) throws Exception { + if (rev == null) { + return null; + } + rev.refresh(); + List res = new ArrayList(); + TCComponent[] kids = rev.getRelatedComponents(rel); + for (TCComponent c : kids) { + if (c.getType().equals(dsType)) { + res.add((TCComponentDataset) c); + } + } + return res; + } + + public static List getChildComponents(TCComponent rev, String dsType, String rel, String dsNamePrefix) + throws Exception { + if (rev == null) { + return null; + } + rev.refresh(); + List res = new ArrayList(); + TCComponent[] kids = rev.getRelatedComponents(rel); + for (TCComponent c : kids) { + if (c.getType().equals(dsType) && c.getProperty("object_name").startsWith(dsNamePrefix)) { + res.add(c); + } + } + return res; + } + + public static List getChildComponentsContainsStr(TCComponent rev, String dsType, String rel, + String dsNameSubStr) throws Exception { + if (rev == null) { + return null; + } + if (dsNameSubStr == null) { + dsNameSubStr = ""; + } + rev.refresh(); + List res = new ArrayList(); + TCComponent[] kids = rev.getRelatedComponents(rel); + for (TCComponent c : kids) { + if (c.getType().equals(dsType) && c.getProperty("object_name").contains(dsNameSubStr)) { + res.add(c); + } + } + return res; + } + + public static List getChildComponents(TCComponent rev, String dsType, String rel) throws Exception { + if (rev == null) { + return null; + } + rev.refresh(); + List res = new ArrayList(); + TCComponent[] kids = rev.getRelatedComponents(rel); + for (TCComponent c : kids) { + if (c.getType().equals(dsType)) { + res.add(c); + } + } + return res; + } + + public static TCComponentFolder getChildFolder(TCComponentFolder folder, String cFolderName) throws Exception { + if (folder == null || cFolderName == null) { + return null; + } + AIFComponentContext[] cc = folder.getChildren(); + int len = KUtil.getLen(cc); + for (int i = 0; i < len; i++) { + InterfaceAIFComponent c = cc[i].getComponent(); + if ((c instanceof TCComponentFolder) && cFolderName.equals(c.getProperty("object_name"))) { + return (TCComponentFolder) c; + } + } + return null; + } + + public static TCComponentDataset uploadFile(TCSession session, TCComponent rev, File newFile, String dsName, + String dsTypeName, String refName, String rel) throws Exception { + TCComponentDataset ds = getDataset(rev, dsTypeName, dsName, rel); + if (ds == null) { + TCComponentDatasetType dsType = (TCComponentDatasetType) session.getTypeComponent(dsTypeName); + ds = dsType.create(dsName, "", dsTypeName); + if (rev != null) { + rev.add(rel, ds); + rev.refresh(); + } + } + setDsFile(ds, refName, newFile); + return ds; + } + + public static void setDsFile(TCComponentDataset ds, String refName, File newFile) throws Exception { + if (ds.isCheckedOut()) { + throw new Exception(String.format(KLocale.getString("uploadfilewhencheckout.ERROR1"), ds.toString())); + } + String[] refs = new String[] { refName }; + String[] files = new String[] { newFile.getAbsolutePath() }; + ds.setFiles(files, refs); + // ds.save(); + ds.refresh(); + } + + public static void setDsFile2(TCComponentDataset ds, String refName, File newFile) throws Exception { + String[] refs = new String[] { refName }; + String[] files = new String[] { newFile.getAbsolutePath() }; + ds.setFiles(files, refs); + // ds.save(); + ds.refresh(); + } + + public static boolean isEmpty(String str) { + return str == null || "".equals(str.trim()); + } + + public static int inArray(int target, int[] arr) { + int len = arr == null ? 0 : arr.length; + for (int i = 0; i < len; i++) { + if (target == arr[i]) { + return i; + } + } + return -1; + } + + public static boolean inArray(String str, String arr, String splitter) { + if (KUtil.isEmpty(arr) || KUtil.isEmpty(splitter)) { + return false; + } + if (KUtil.isEmpty(str)) { + return true; + } + return inArray(str, arr.split(splitter)) >= 0; + } + + public static int inArray(String target, String[] arr) { + int len = arr == null ? 0 : arr.length; + for (int i = 0; i < len; i++) { + if (target.equals(arr[i])) { + return i; + } + } + return -1; + } + + public static int getNextColNumber(int currentIndex, int[] skipColIndex, int cols) { + int res = currentIndex; + for (int i = 0; i < cols; i++) { + res++; + if (inArray(res, skipColIndex) >= 0) { + i--; + } + } + return res; + } + + public static List> groupList(List originList, int maxCount, int gap, E gapFiller) { + List> res = new ArrayList>(); + int cnt = originList == null ? 0 : originList.size(); + List list = new ArrayList(); + for (int i = 0; i < cnt; i++) { + list.add(originList.get(i)); + if (i != cnt - 1) {// add gap + for (int j = 0; j < gap; j++) { + list.add(gapFiller); + } + } + } + cnt = list == null ? 0 : list.size(); + if (maxCount <= 0) { + maxCount = cnt; + } + int pageCounter = 0; + List cList = new ArrayList(); + res.add(cList); + for (int i = 0; i < cnt; i++) { + if (pageCounter == maxCount) { + cList = new ArrayList<>(); + res.add(cList); + pageCounter = 0; + } + if (cList != null) { + E item = list.get(i); + if (cList.size() == 0 && item == gapFiller) { + continue; + } + cList.add(list.get(i)); + pageCounter++; + } + } + list.clear(); + list = null; + return res; + } + + public static List> groupListWithGapAdded(List list, int maxCount, E gapFiller) { + List> res = new ArrayList>(); + int cnt = list == null ? 0 : list.size(); + if (maxCount <= 0) { + maxCount = cnt; + } + int pageCounter = 0; + List cList = new ArrayList(); + res.add(cList); + for (int i = 0; i < cnt; i++) { + if (pageCounter == maxCount) { + cList = new ArrayList<>(); + res.add(cList); + pageCounter = 0; + } + if (cList != null) { + E item = list.get(i); + if (cList.size() == 0 && item == gapFiller) { + continue; + } + cList.add(list.get(i)); + pageCounter++; + } + } + list.clear(); + list = null; + return res; + } + + public static List>> groupList(List> originList, int maxCount, int gap, + Map gapFiller, String gapKey) { + List>> res = new ArrayList>>(); + int cnt = originList == null ? 0 : originList.size(); + List> list = new ArrayList>(); + boolean addGap = false; + for (int i = 0; i < cnt; i++) { + Map item = originList.get(i); + list.add(item); + if (i != cnt - 1) {// add gap + Map nextItem = originList.get(i + 1); + addGap = KUtil.isEmpty(gapKey) || (nextItem != null && nextItem.containsKey(gapKey)); + for (int j = 0; j < gap; j++) { + if (addGap) { + list.add(gapFiller); + } + } + } + } + cnt = list == null ? 0 : list.size(); + if (maxCount <= 0) { + maxCount = cnt; + } + int pageCounter = 0; + List> cList = new ArrayList>(); + res.add(cList); + for (int i = 0; i < cnt; i++) { + if (pageCounter == maxCount) { + cList = new ArrayList<>(); + res.add(cList); + pageCounter = 0; + } + if (cList != null) { + Map item = list.get(i); + if (cList.size() == 0 && item == gapFiller) { + continue; + } + cList.add(list.get(i)); + pageCounter++; + } + } + list.clear(); + list = null; + return res; + } + + public static File getFileFromDataset(TCSession session, String dsType, String uid, String prefName) + throws Exception { + TCComponent comp = null; + try { + comp = session.stringToComponent(uid); + } catch (Exception e) { + e.printStackTrace(); + } + if (comp == null) { + throw new Exception(String.format(KLocale.getString("dsuidinpref.ERROR1"), prefName)); + } + String type = comp.getType(); + System.out.println("Dataset: " + comp + "|Type: " + type); + if (!dsType.equals(type)) { + throw new Exception(String.format(KLocale.getString("dsuidinpref.ERROR1"), prefName)); + } + TCComponentDataset tDataset = (TCComponentDataset) comp; + return getDatasetFile(tDataset); + } + + public static File getDatasetFile(TCComponentDataset dataset) throws Exception { + File[] files = dataset.getFiles("", System.getenv("TEMP")); + if (files == null || files.length == 0) { + throw new Exception(String.format(KLocale.getString("norefindataset.ERROR1"), dataset.toString())); + } + System.out.println(">> Download file (" + files.length + "): " + files[0].getAbsolutePath()); + return files[0]; + } + + public static File getDatasetFile(File dir, TCComponentDataset dataset) throws Exception { + if (dir == null || !dir.isDirectory()) { + throw new Exception("Directory not found."); + } + File[] files = dataset.getFiles("", dir.getAbsolutePath()); + if (files == null || files.length == 0) { + throw new Exception(String.format(KLocale.getString("norefindataset.ERROR1"), dataset.toString())); + } + System.out.println(">> Download file (" + files.length + "): " + files[0].getAbsolutePath()); + return files[0]; + } + + public static String[] getStringArrayProp(TCComponentForm form, String propName) throws Exception { + if (form == null) { + return null; + } + TCProperty prop = form.getFormTCProperty(propName); + if (prop == null) { + throw new java.lang.Exception( + String.format(KLocale.getString("nopropintype.ERROR2"), form.getDisplayType(), propName)); + } + return prop.getStringArrayValue(); + } + + public static File chooseDirectory(Component parent) { + FileSystemView fsv = FileSystemView.getFileSystemView(); + String deskPath = fsv.getHomeDirectory().getPath(); + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setCurrentDirectory(new File(deskPath)); + fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + int state = fileChooser.showOpenDialog(parent); + if (state == 1) { + return null; + } + return fileChooser.getSelectedFile(); + } + + public static boolean addReleaseStatus(TCSession session, String uid, String status) throws Exception { + TCUserService userservice = session.getUserService(); + Object[] obj = new Object[2]; + obj[0] = uid; + obj[1] = status; + Object res = userservice.call("K_add_release_status", obj); + if (res != null && res.toString().equalsIgnoreCase("true")) { + return true; + } + return false; + } + + /** + * ֻԵֵ + * + * @param session + * @param propName + * @param propValue + * @param comp + * @return + * @throws Exception + */ + public static boolean setPropValue(TCSession session, String propName, String propValue, TCComponent comp) + throws Exception { + TCUserService userservice = session.getUserService(); + Object[] obj = new Object[3]; + obj[0] = propName; + obj[1] = propValue; + obj[2] = comp; + Object res = userservice.call("Connor_Set_Prop_Value", obj); + if (res != null && res.toString().equalsIgnoreCase("true")) { + return true; + } + return false; + } + + public static File chooseFile(Component parent) { + FileSystemView fsv = FileSystemView.getFileSystemView(); + String deskPath = fsv.getHomeDirectory().getPath(); + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setCurrentDirectory(new File(deskPath)); + fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); + FileNameExtensionFilter filter = new FileNameExtensionFilter("*.xlsx", "xlsx"); + fileChooser.setFileFilter(filter); + int state = fileChooser.showOpenDialog(parent); + if (state == 1) { + return null; + } + return fileChooser.getSelectedFile(); + } + + public static File chooseSaveFile(Component parent, String defaultFile) { + FileSystemView fsv = FileSystemView.getFileSystemView(); + String deskPath = fsv.getHomeDirectory().getPath(); + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setCurrentDirectory(new File(deskPath)); + fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); + FileNameExtensionFilter filter = new FileNameExtensionFilter("*.xlsx", "xlsx"); + fileChooser.setFileFilter(filter); + fileChooser.setSelectedFile(new File(defaultFile)); + int state = fileChooser.showSaveDialog(parent); + if (state == 1) { + return null; + } + return fileChooser.getSelectedFile(); + } + + public static File chooseSaveFile(Component parent, String defaultFile, String ext) { + FileSystemView fsv = FileSystemView.getFileSystemView(); + String deskPath = fsv.getHomeDirectory().getPath(); + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setCurrentDirectory(new File(deskPath)); + fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); + if (!KUtil.isEmpty(ext)) { + FileNameExtensionFilter filter = new FileNameExtensionFilter("*." + ext, ext); + fileChooser.setFileFilter(filter); + } + fileChooser.setSelectedFile(new File(defaultFile)); + int state = fileChooser.showSaveDialog(parent); + if (state == 1) { + return null; + } + return fileChooser.getSelectedFile(); + } + + public static File getNewFile(File folder, String fileName, String ext) { + File file = new File(folder.getAbsolutePath() + "\\" + fileName + "." + ext); + int index = 1; + while (file.exists()) { + file = new File(folder.getAbsolutePath() + "\\" + fileName + "(" + (index++) + ")." + ext); + } + return file; + } + + public static String getDateStr(Date date, String format) { + String res = ""; + try { + SimpleDateFormat sdf = new SimpleDateFormat(format); + res = sdf.format(date); + } catch (Exception e) { + e.printStackTrace(); + } + return res; + } + + public static TCComponentContextList query(TCSession session, String queryName, Map fields) + throws Exception { + String[] keys = fields.keySet().toArray(new String[] {}); + String[] vals = fields.values().toArray(new String[] {}); + return query(session, queryName, keys, vals); + } + + public static TCComponentContextList query(TCSession session, String queryName, String[] keys, String[] vals) + throws Exception { + System.out.println("Query: " + queryName); + System.out.println("keys = " + Arrays.toString(keys)); + System.out.println("vals = " + Arrays.toString(vals)); + TCComponentQueryType queryType = (TCComponentQueryType) session.getTypeComponent("ImanQuery"); + TCComponentQuery query = (TCComponentQuery) queryType.find(queryName); + if (query == null) { + throw new Exception(String.format(KLocale.getString("querynotexist.ERROR1"), queryName)); + } + queryType.clearCache(); + query.clearCache(); + query.refresh(); + return query.getExecuteResultsList(keys, vals); + } + + public static TCComponent[] query2(TCSession session, String queryName, String[] keys, String[] vals) + throws Exception { + System.out.println("Query: " + queryName); + System.out.println("keys = " + Arrays.toString(keys)); + System.out.println("vals = " + Arrays.toString(vals)); + TCComponentQueryType queryType = (TCComponentQueryType) session.getTypeComponent("ImanQuery"); + TCComponentQuery query = (TCComponentQuery) queryType.find(queryName); + if (query == null) { + throw new Exception(String.format(KLocale.getString("querynotexist.ERROR1"), queryName)); + } + queryType.clearCache(); + query.clearCache(); + query.refresh(); + return query.execute(keys, vals); + } + + public static TCComponentContextList combineContext(TCSession session, TCComponentQuery query, + TCComponentContextList... contexts) throws Exception { + Class c = TCComponentContextList.class; + Field f1 = c.getDeclaredField("m_compUids"); + f1.setAccessible(true); + List compUids = new ArrayList<>(); + for (TCComponentContextList cc : contexts) { + String[] u1 = (String[]) f1.get(cc); + System.out.println(Arrays.toString(u1)); + compUids.addAll(Arrays.asList(u1)); + } + Constructor constructor = c.getDeclaredConstructor(TCComponentManager.class, TCComponent.class, + String[].class, String[].class, String.class); + constructor.setAccessible(true); + TCComponentContextList res = (TCComponentContextList) constructor.newInstance(new TCComponentManager(session), + query, compUids.toArray(new String[] {}), null, ""); + return res; + } + + public static int getLen(Object[] arr) { + return arr == null ? 0 : arr.length; + } + + public static String getValueInArray(String[] arr, int index) { + int len = arr == null ? 0 : arr.length; + if (index >= len) { + return ""; + } + return arr[index]; + } + + public static String getValueInArray(String arrStr, int index, String splitter) { + if (KUtil.isEmpty(arrStr)) { + return ""; + } + String[] split = arrStr.split(splitter, -1); + int len = getLen(split); + if (len > index && index >= 0) { + return split[index]; + } + return ""; + } + + public static String getTypeNames(TCSession session, Object[] types) { + int len = types == null ? 0 : types.length; + if (len == 0) { + return ""; + } + String[] names = new String[len]; + for (int i = 0; i < len; i++) { + try { + if ("TC_Project".equals(types[i].toString())) { + names[i] = KLocale.getString("project"); + } else { + names[i] = session.getTypeComponent(types[i].toString()).getDisplayTypeName(); + } + } catch (Exception e) { + e.printStackTrace(); + } + if (names[i] == null) { + names[i] = types[i].toString(); + } + } + return Arrays.toString(names); + } + + public static String getTypeName(TCSession session, String type) { + if (KUtil.isEmpty(type)) { + return ""; + } + try { + if ("TC_Project".equals(type)) { + return KLocale.getString("project"); + } else { + return session.getTypeComponent(type).getDisplayTypeName(); + } + } catch (Exception e) { + e.printStackTrace(); + } + return type; + } + + public static boolean isReleased(TCComponent comp) throws Exception { + TCComponent[] status = comp.getReferenceListProperty("release_status_list"); + if (status == null || status.length == 0) { + return false; + } + return true; + } + + public static TCComponentUser getUserFromStr(String str) throws Exception { + System.out.println("Search User: " + str); + if (KUtil.isEmpty(str)) { + return null; + } + int ind1 = str.lastIndexOf('('); + int ind2 = str.lastIndexOf(')'); + TCComponentUser user = null; + if (ind1 > 0 && ind2 > ind1) { + String userId = str.substring(ind1 + 1, ind2); + if (KUtil.isEmpty(userId)) { + System.out.println("No Id between '(' and ')'"); + user = null; + } else { + user = queryUserById(userId); + } + } else { + user = queryUserById(str); + if (user == null) { + user = queryUserByName(str); + } + } + return user; + } + + public static TCComponentUser queryUserById(String userId) throws Exception { + System.out.println("Search User By Id: " + userId); + if (KUtil.isEmpty(userId)) { + return null; + } + String queryName = "Admin - Employee Information"; + String[] keys = new String[] { KUtil.getText("UserId") }; + String[] vals = new String[] { userId }; + TCComponentContextList res = KUtil.query(KUtil.session, queryName, keys, vals); + if (res.getListCount() == 0) { + return null; + } + if (res.getListCount() > 1) { + throw new Exception(String.format(KLocale.getString("multiuserbyid.ERROR1"), userId)); + } + return (TCComponentUser) res.get(0).getComponent(); + } + + public static TCComponentUser queryUserByName(String userName) throws Exception { + System.out.println("Search User By Name: " + userName); + if (KUtil.isEmpty(userName)) { + return null; + } + String queryName = "Admin - Employee Information"; + String[] keys = new String[] { KUtil.getText("PersonName") }; + String[] vals = new String[] { userName }; + TCComponentContextList res = KUtil.query(KUtil.session, queryName, keys, vals); + if (res.getListCount() == 0) { + return null; + } + if (res.getListCount() > 1) { + throw new Exception(String.format(KLocale.getString("multiuserbyname.ERROR1"), userName)); + } + return (TCComponentUser) res.get(0).getComponent(); + } + + public static TCComponent[] getGroupMember(List privMembers) throws Exception { + if (privMembers == null) { + return null; + } + List res = new ArrayList<>(); + for (TCComponentUser user : privMembers) { + TCComponentGroupMember[] gms = user.getGroupMembers(); + int len = KUtil.getLen(gms); + for (int i = 0; i < len; i++) { + TCComponentGroupMember gm = gms[i]; + if (KUtil.isEmpty(gm.toString())) { + continue; + } + /* + * if(!gm.isActive()) { System.out.println("���Ա�ǻ�?"+gm); continue; } + */ + if (!res.contains(gm)) { + System.out.println("Add Group Member: " + gm); + res.add(gm); + } else { + System.out.println("Added: " + gm); + } + } + } + return res.toArray(new TCComponent[] {}); + } + + public static int compareWBS(String wbsCode, String wbsCode2) { + if (KUtil.isEmpty(wbsCode) && KUtil.isEmpty(wbsCode2)) { + return 0; + } + if (KUtil.isEmpty(wbsCode)) { + return -1; + } + if (KUtil.isEmpty(wbsCode2)) { + return 1; + } + String[] a = wbsCode.split("\\."); + String[] b = wbsCode2.split("\\."); + int lenA = a.length; + int lenB = b.length; + for (int i = 0; i < lenA && i < lenB; i++) { + String aa = a[i]; + String bb = b[i]; + int ai = 0; + int bi = 0; + try { + ai = Integer.parseInt(aa); + bi = Integer.parseInt(bb); + } catch (Exception e) { + e.printStackTrace(); + } + if (ai != bi) { + return ai - bi; + } + } + return lenA - lenB; + } + + public static TCComponentListOfValues getLov(String lovName) { + TCComponentListOfValuesType lovType; + try { + lovType = (TCComponentListOfValuesType) session.getTypeComponent("ListOfValues"); + TCComponentListOfValues[] lov = lovType.find(lovName); + if (lov.length > 0) + return lov[0]; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static String[] getDynamicLOV(String s) { + TCComponentListOfValues lov = null; + List lovDisplayValueList = new ArrayList<>(); + lovDisplayValueList.add(""); + List lovValueList = new ArrayList<>(); + lov = TCComponentListOfValuesType.findLOVByName(s); + try { + if ("Fnd0ListOfValuesDynamic".equals(lov.getProperty("lov_type"))) { + LOVService lovService = LOVService.getService(RACUIUtil.getTCSession()); + 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]); + } + } + } + } catch (TCException e) { + e.printStackTrace(); + } + return lovDisplayValueList.toArray(new String[lovDisplayValueList.size()]); + } + + public static String getLovValue(TCComponentListOfValues lov, String str) throws Exception { + return getLovValue(lov, str, true); + } + + public static String getLovValue(TCComponentListOfValues lov, String str, boolean translate) throws Exception { + if (lov == null || KUtil.isEmpty(str)) { + return str; + } + if (translate) { + String prefName = "LOV_TRANS_" + lov.getStringProperty(TCComponentListOfValues.PROP_LOV_NAME); + String[] prefVals = KUtil.getPrefVals(KUtil.session, prefName); + int len = KUtil.getLen(prefVals); + for (int i = 0; i < len; i++) { + String pref = prefVals[i]; + int ind = pref.indexOf('='); + if (ind > 0) { + String realVal = pref.substring(0, ind); + String disVal = pref.substring(ind + 1); + if (str.equals(realVal) || str.equals(disVal)) { + return realVal; + } + } + } + } + ListOfValuesInfo info = lov.getListOfValues(); + if (info == null) { + return str; + } + List v = info.getValues(); + int size = v == null ? 0 : v.size(); + for (int i = 0; i < size; i++) { + LovValue vv = v.get(i); + String realValue = vv.getValue() == null ? "" : vv.getValue().toString(); + if (str.equals(realValue)) { + return str; + } + String disValue = vv.getDisplayValue(); + if (str.equals(disValue)) { + return realValue; + } + } + throw new Exception(String.format(KLocale.getString("valuenotinlov.ERROR2"), lov.toString(), str)); + } + + public static String getLovDisplayableValue(TCComponentListOfValues lov, String str) throws Exception { + if (lov == null || KUtil.isEmpty(str)) { + return str; + } + ListOfValuesInfo info = lov.getListOfValues(); + if (info == null) { + return str; + } + List v = info.getValues(); + int size = v == null ? 0 : v.size(); + for (int i = 0; i < size; i++) { + LovValue vv = v.get(i); + String realValue = vv.getValue() == null ? "" : vv.getValue().toString(); + if (str.equals(realValue)) { + return vv.getDisplayValue(); + } + String disValue = vv.getDisplayValue(); + if (str.equals(disValue)) { + return str; + } + } + throw new Exception(String.format(KLocale.getString("valuenotinlov.ERROR2"), lov.toString(), str)); + } + + public static void openFile(File file) { + try { + if (file != null && file.exists()) { + Runtime.getRuntime().exec("cmd /c start /b call \"" + file.getAbsolutePath() + "\""); + } + } catch (Exception e) { + e.printStackTrace(); + MessageBox.post(e); + } + } + + public static void importDataset(TCComponent parent, String rel, File f, String dsType, String refName) + throws Exception { + if (f == null || !f.exists() || KUtil.isEmpty(dsType) || KUtil.isEmpty(refName)) { + return; + } + TCComponentDatasetType datasetType = (TCComponentDatasetType) session.getTypeComponent(dsType); + TCComponentDataset dataset = datasetType.create(f.getName(), "", dsType); + String paths[] = { f.getAbsolutePath() }; + String refs[] = { refName }; + dataset.setFiles(paths, refs); + if (parent != null && !KUtil.isEmpty(rel)) { + parent.add(rel, dataset); + } + } + + public static void initPropMap(String propConfig, String value, Map itemPropMap, + Map itemMasterPropMap, Map revPropMap, Map revMasterPropMap) + throws Exception { + initPropMap(propConfig, value, itemPropMap, itemMasterPropMap, revPropMap, revMasterPropMap, null); + } + + public static void initPropMap(String propConfig, String value, Map itemPropMap, + Map itemMasterPropMap, Map revPropMap, Map revMasterPropMap, + Map bomlinePropMap) throws Exception { + if (KUtil.isEmpty(propConfig)) { + return; + } + String propFrom = null, propName = null; + String[] split = propConfig.split("\\."); + if (KUtil.getLen(split) == 2) { + propFrom = split[0].trim().toUpperCase(); + propName = split[1].trim(); + } + if (KUtil.isEmpty(propFrom) || KUtil.isEmpty(propName)) { + return; + } + Map target; + if ("ITEM".equals(propFrom)) { + target = itemPropMap; + System.out.println(">> ITEM PROP: " + propName + " = " + value); + } else if ("REV".equals(propFrom)) { + System.out.println(">> REV PROP: " + propName + " = " + value); + target = revPropMap; + } else if ("ITEMMASTER".equals(propFrom)) { + System.out.println(">> ITEMMASTER PROP: " + propName + " = " + value); + target = itemMasterPropMap; + } else if ("REVMASTER".equals(propFrom)) { + System.out.println(">> REVMASTER PROP: " + propName + " = " + value); + target = revMasterPropMap; + } else if ("BOMLINE".equals(propFrom)) { + System.out.println(">> BOMLINE PROP: " + propName + " = " + value); + target = bomlinePropMap; + } else { + throw new Exception(String.format(KLocale.getString("proplocationnotdefined.ERROR1"), propFrom)); + } + if (target == null) { + return; + } + target.put(propName, value); + } + + public static String getMarkedPropValue(String config, Map markedComponents) throws Exception { + return getMarkedPropValue(config, markedComponents, null); + } + + public static String getMarkedPropValue(String config, Map markedComponents, + Map> relatedComponents) throws Exception { + if (markedComponents == null || KUtil.isEmpty(config)) { + return ""; + } + StringBuilder res = new StringBuilder(); + String[] propConfigSplit = config.split("\\+"); + int len = KUtil.getLen(propConfigSplit); + for (int i = 0; i < len; i++) { + String propConfig = propConfigSplit[i]; + String propFrom = null, propName = null; + String defaultValue = ""; + String[] split = propConfig.split("\\."); + if (KUtil.getLen(split) >= 2) { + propFrom = split[0].trim().toUpperCase(); + propName = split[1].trim(); + } + if (KUtil.getLen(split) >= 3) { + defaultValue = split[2].trim(); + } + if (KUtil.isEmpty(propFrom) || KUtil.isEmpty(propName)) { + if (propConfig.contains("\\n")) { + propConfig = propConfig.replace("\\n", "\n"); + } + res.append(propConfig); + continue; + } + if (!markedComponents.containsKey(propFrom)) { + if (propFrom.startsWith("T")) { + return ""; + } + continue; + } + TCComponent comp = markedComponents.get(propFrom); + // λ.-[-ӷ] + int ind = propName.indexOf('-'); + if (ind > 0) { + String tableProp = propName.substring(0, ind).trim(); + String tableRowProp = propName.substring(ind + 1).trim(); + if (!KUtil.isEmpty(tableProp) && !KUtil.isEmpty(tableRowProp)) { + TCProperty prop = comp.getTCProperty(tableProp.trim()); + if (prop == null) { + throw new Exception(String.format(KLocale.getString("propnotdefinedintype.ERROR2"), + comp.getType(), propName)); + } + String rowSplitter = "#ROW#"; + ind = tableRowProp.indexOf('-'); + if (ind > 0) { + rowSplitter = tableRowProp.substring(ind + 1); + tableRowProp = tableRowProp.substring(0, ind); + } + TCComponent[] tableRows = prop.getReferenceValueArray(); + int rowCnt = KUtil.getLen(tableRows); + String[] value = new String[rowCnt]; + for (int j = 0; j < rowCnt; j++) { + value[j] = tableRows[j].getPropertyDisplayableValue(tableRowProp); + } + res.append(String.join(rowSplitter, value)); + } + continue; + } + TCProperty prop = comp.getTCProperty(propName.trim()); + if (prop == null) { + throw new Exception( + String.format(KLocale.getString("propnotdefinedintype.ERROR2"), comp.getType(), propName)); + } + String value = prop.getDisplayableValue(); + if ("NAME".equalsIgnoreCase(defaultValue)) { + value = prop.getPropertyDisplayName(); + } else if (value == null || "".equals(value)) { + value = defaultValue; + } + res.append(value); + } + return res.toString(); + } + + public static TCComponent getLatestComponent(List comps) { + int size = comps == null ? 0 : comps.size(); + if (size == 0) { + return null; + } + if (size == 1) { + return comps.get(0); + } + TCComponent res = comps.get(0); + try { + Date maxDate = res.getDateProperty("creation_date"); + for (int i = 1; i < size; i++) { + TCComponent temp = comps.get(i); + Date tempDate = temp.getDateProperty("creation_date"); + if (tempDate.after(maxDate)) { + maxDate = tempDate; + res = temp; + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return res; + } + + public static TCComponentType[] getComponentTypes(String itemTypeName) throws Exception { + TCComponentItemType itemType = null; + try { + itemType = (TCComponentItemType) session.getTypeComponent(itemTypeName); + } catch (Exception e) { + e.printStackTrace(); + } + if (itemType == null) { + throw new Exception(String.format(KLocale.getString("typenotfound.ERROR1"), itemTypeName)); + } + TCComponentItemRevisionType revType = itemType.getItemRevisionType(); + if (revType == null) { + throw new Exception(String.format(KLocale.getString("typenotfound.ERROR1"), itemTypeName + "Revision")); + } + TCComponentType itemMasterType = null; + try { + itemMasterType = session.getTypeComponent(itemTypeName + "Master"); + } catch (Exception e) { + e.printStackTrace(); + } + if (itemMasterType == null) { + try { + itemMasterType = session.getTypeComponent(itemTypeName + " Master"); + } catch (Exception e) { + e.printStackTrace(); + } + } + if (itemMasterType == null) { + throw new Exception(String.format(KLocale.getString("typenotfound.ERROR1"), itemTypeName + "Master")); + } + TCComponentType revMasterType = null; + try { + revMasterType = session.getTypeComponent(revType.getTypeName() + "Master"); + } catch (Exception e) { + e.printStackTrace(); + } + if (revMasterType == null) { + try { + revMasterType = session.getTypeComponent(revType.getTypeName() + " Master"); + } catch (Exception e) { + e.printStackTrace(); + } + } + if (revMasterType == null) { + throw new Exception( + String.format(KLocale.getString("typenotfound.ERROR1"), revType.getTypeName() + "Master")); + } + return new TCComponentType[] { itemType, revType, itemMasterType, revMasterType }; + } + + public static String getPropertyDisplayName(TCComponentType type, String propName) throws Exception { + if (type == null || KUtil.isEmpty(propName)) { + return propName; + } + TCPropertyDescriptor desc = type.getPropDesc(propName); + if (desc == null) { + throw new Exception(String.format(KLocale.getString("propnotdefinedintype.ERROR2"), + type.getDisplayTypeName(), propName)); + } + return desc.getDisplayName(); + } + + public static String getConfigPropValue(TCComponentItemRevision rev, String propConfigStr) throws Exception { + if (rev == null || KUtil.isEmpty(propConfigStr)) { + return ""; + } + StringBuilder res = new StringBuilder(); + String[] propConfigSplit = propConfigStr.split("\\+"); + int len = KUtil.getLen(propConfigSplit); + for (int i = 0; i < len; i++) { + String propConfig = propConfigSplit[i]; + String propFrom = null, propName = null; + String[] split = propConfig.split("\\."); + if (KUtil.getLen(split) == 2) { + propFrom = split[0].trim().toUpperCase(); + propName = split[1].trim(); + } + if (KUtil.isEmpty(propFrom) || KUtil.isEmpty(propName)) { + res.append(propConfig); + continue; + } + TCComponent target; + if ("ITEM".equals(propFrom)) { + target = rev.getItem(); + } else if ("REV".equals(propFrom)) { + target = rev; + } else if ("ITEMMASTER".equals(propFrom)) { + target = rev.getItem().getRelatedComponent("IMAN_master_form"); + } else if ("REVMASTER".equals(propFrom)) { + target = rev.getRelatedComponent("IMAN_master_form_rev"); + } else { + throw new Exception(String.format(KLocale.getString("proplocationnotdefined.ERROR1"), propFrom)); + } + TCProperty prop = target.getTCProperty(propName.trim()); + if (prop == null) { + throw new Exception( + String.format(KLocale.getString("propnotdefinedintype.ERROR2"), target.getType(), propName)); + } + res.append(prop.getStringValue()); + } + return res.toString(); + } + + public static String getConfigPropDisplayableValue(TCComponentItemRevision rev, String propConfigStr) + throws Exception { + if (rev == null || KUtil.isEmpty(propConfigStr)) { + return ""; + } + StringBuilder res = new StringBuilder(); + String[] propConfigSplit = propConfigStr.split("\\+"); + int len = KUtil.getLen(propConfigSplit); + for (int i = 0; i < len; i++) { + String propConfig = propConfigSplit[i]; + String propFrom = null, propName = null; + String[] split = propConfig.split("\\."); + if (KUtil.getLen(split) == 2) { + propFrom = split[0].trim().toUpperCase(); + propName = split[1].trim(); + } + if (KUtil.isEmpty(propFrom) || KUtil.isEmpty(propName)) { + res.append(propConfig); + continue; + } + TCComponent target; + if ("ITEM".equals(propFrom)) { + target = rev.getItem(); + } else if ("REV".equals(propFrom)) { + target = rev; + } else if ("ITEMMASTER".equals(propFrom)) { + target = rev.getItem().getRelatedComponent("IMAN_master_form"); + } else if ("REVMASTER".equals(propFrom)) { + target = rev.getRelatedComponent("IMAN_master_form_rev"); + } else { + throw new Exception(String.format(KLocale.getString("proplocationnotdefined.ERROR1"), propFrom)); + } + TCProperty prop = target.getTCProperty(propName.trim()); + if (prop == null) { + throw new Exception( + String.format(KLocale.getString("propnotdefinedintype.ERROR2"), target.getType(), propName)); + } + res.append(prop.getDisplayableValue()); + } + return res.toString(); + } + + public static void removeAllParents(DataManagementService dm, TCComponent comp) throws Exception { + comp.refresh(); + System.out.println("Remove from parent: " + comp); + WhereReferencedResponse refResp = dm.whereReferenced(new TCComponent[] { comp }, 1); + KUtil.throwServiceDataError(refResp.serviceData); + int len = KUtil.getLen(refResp.output); + List datas = new ArrayList(); + for (int i = 0; i < len; i++) { + WhereReferencedOutput ref = refResp.output[i]; + int cnt = KUtil.getLen(ref.info); + for (int j = 0; j < cnt; j++) { + WhereReferencedInfo info = ref.info[j]; + Relationship data = new Relationship(); + data.primaryObject = info.referencer; + data.secondaryObject = comp; + data.relationType = info.relation; + System.out.println(">> " + info.relation + " | " + info.referencer); + datas.add(data); + } + } + ServiceData resp = dm.deleteRelations(datas.toArray(new Relationship[] {})); + KUtil.throwServiceDataError(resp); + } + + public static TCComponent newTableRow(DataManagementService dmService, String type, + Map rowStringProps, Map rowDateProps) throws Exception { + CreateIn rowIn = new CreateIn(); + CreateInput rowInput = new CreateInput(); + rowInput.boName = type; + if (rowStringProps != null) { + rowInput.stringProps = rowStringProps; + } + if (rowDateProps != null) { + rowInput.dateProps = rowDateProps; + } + rowIn.data = rowInput; + CreateResponse res = dmService.createObjects(new CreateIn[] { rowIn }); + KUtil.throwServiceDataError(res.serviceData); + if (res.serviceData.sizeOfCreatedObjects() > 0) { + return res.serviceData.getCreatedObject(0); + } + return null; + } + + public static Date addDay(Date day, int cnt) { + if (day == null) { + return null; + } + Calendar c = Calendar.getInstance(); + c.setTime(day); + c.add(Calendar.DATE, cnt); + return c.getTime(); + } + + public static Date calTime(TCCalendar calendar, Date date, int minutes) { + if (calendar == null || date == null) { + return null; + } + int diff = minutes > 0 ? 1 : -1; + if (minutes < 0) { + minutes = -minutes; + } + Calendar c = Calendar.getInstance(); + c.setTime(date); + int counter = 0; + while (counter < minutes) { + counter += calendar.getMinutesOnDay(c); + c.add(Calendar.DATE, diff); + } + return c.getTime(); + } + + public static int getMinutesBetween(TCCalendar calendar, Date start, Date end) { + if (calendar == null || start == null || end == null) { + return 0; + } + Calendar c = Calendar.getInstance(); + c.setTime(start); + int res = 0; + while (c.getTime().before(end)) { + res += calendar.getMinutesOnDay(c); + // System.out.println(calendar.getMinutesOnDay(c)+" > "+c.getTime()); + c.add(Calendar.DATE, 1); + } + return res; + } + + public static TCComponentTCCalendar getScheduleCalendar(TCComponentSchedule schedule) throws Exception { + if (schedule == null) { + return null; + } + return CalendarHelper.getScheduleCalendar(schedule, session); + } + + public static void dealSpecialModelValue(ArrayList specialList, String prefName, String prop, int ind) { + int index = 0; + + try { + String[] prefVals = KUtil.getPrefVals(session, prefName); + String puid = prefVals[ind]; + TCComponent component = session.stringToComponent(puid); + if (component instanceof TCComponentForm) { + + TCComponentForm form = (TCComponentForm) component; + + TCComponent[] tables = form.getReferenceListProperty("ld6_ChangeTable"); + for (int j = 0; j < tables.length; j++) { + + String change = tables[j].getStringProperty(prop); + if (change.equals("")) { + specialList.add(j); + } + } + + } + +// +// Set>> entrySet = map.entrySet(); +// for (Entry> entry : entrySet) { +// ArrayList list = entry.getValue(); +// String value = list.get(2); +// System.out.println("ǰֵΪ" + value); +// if(value != null && value.equals("")) { +// specialList.add(index); +// } +// index++; +// } + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + /** + * õģֵ + * + * @param map + * @throws Exception + */ +// public static void getModelVale(LinkedHashMap> map,String prefName,int index) throws Exception { +// AbstractAIFApplication application = AIFUtility.getCurrentApplication(); +// TCSession session = (TCSession) application.getSession(); +// String[] prefVals = KUtil.getPrefVals(session, prefName); +// String puid = prefVals[index]; +// TCComponentDataset component = (TCComponentDataset) session.stringToComponent(puid); +// TCComponentTcFile[] tcFiles = component.getTcFiles(); +// File datasetFile = null; +// String name = ""; +// if (tcFiles != null && tcFiles.length != 0) { +// TCComponentTcFile tcComponentTcFile = tcFiles[0]; +// File fmsFile = tcComponentTcFile.getFmsFile(); +// name = tcComponentTcFile.getStringProperty("original_file_name"); +// datasetFile = new File(System.getenv("TEMP")+"\\"+name); +// FileUtility.copyFile(fmsFile, datasetFile); +// +// } +// XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(datasetFile)); +// XSSFSheet sheet = wb.getSheetAt(0); +// for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) { +// XSSFRow row = sheet.getRow(i); +// for (int j = 0; j < 5; j++) { +// XSSFCell cell = row.getCell(j); +// if(cell != null) { +// String cellValue = KUtil.getCellValue(cell); +// if(j == 0 && cellValue.isEmpty()) { +// break; +// } +// if(j == 0 ) { +// if(map.containsKey(cellValue)) { +// break; +// }else { +// map.put(cellValue, null); +// } +// }else { +// String key = KUtil.getCellValue(row.getCell(0)); +// ArrayList arrayList = map.get(key); +// if(arrayList != null) { +// arrayList.add(cellValue); +// }else { +// ArrayList list = new ArrayList(); +// list.add(cellValue); +// map.put(key, list); +// } +// } +// +// } +// } +// } +// wb.close(); +// datasetFile.delete(); +// } + /** + * õģֵ + * + * @param map + * @throws Exception + */ + public static void getModelVale(LinkedHashMap> map, TCComponent forms, + ArrayList specialList, String[] propNames) throws Exception { +// AbstractAIFApplication application = AIFUtility.getCurrentApplication(); +// TCSession session = (TCSession) application.getSession(); +// String[] prefVals = KUtil.getPrefVals(session, prefName); +// String puid = prefVals[index]; +// TCComponent component = session.stringToComponent(puid); + int t = 1; + if (forms instanceof TCComponentForm) { + + TCComponentForm form = (TCComponentForm) forms; + TCComponent[] tables = form.getReferenceListProperty("ld6_ChangeTable"); + for (int j = 0; j < tables.length; j++) { + ArrayList tableValue = new ArrayList(); + + for (String propName : propNames) { + System.out.println("ǰΪ" + propName); + String prop = tables[j].getTCProperty(propName).getDisplayableValue(); + if (propName.equals("ld6_YNChange") && prop.equals("")) { +// specialList.add(j); + } + tableValue.add(prop == null ? "" : prop.trim()); + } + + map.put(String.valueOf(t), tableValue); +// tableValue + + t = t + 1; + } + + } + + } + + /** + * õlovʵֵʾֵ + * + * @param lovMap + * @param comboBox + * @throws TCException + */ + public static void getLov(HashMap lovMap, String lovName, JComboBox comboBox) + throws TCException { + if (comboBox != null) { + comboBox.addItem(""); + } +// for (LovValue lovV : lovValueList) { +// map.put(lovV.getDisplayValue(), lovV.getStringValue()); +// comboBox.addItem(lovV.getDisplayValue()); +// System.out.println(lovV.getDisplayValue() + "===" + lovV.getStringValue()); +// } + + TCComponentListOfValues lov = TCComponentListOfValuesType.findLOVByName(lovName); + if ("Fnd0ListOfValuesDynamic".equals(lov.getProperty("lov_type"))) { + System.out.println("̬lovName=" + lovName); + LOVService lovService = LOVService.getService(RACUIUtil.getTCSession()); + InitialLovData input = new InitialLovData(); + LovFilterData filter = new LovFilterData(); + if ("LD6_TecDoc_TypeLOV".equals(lovName)) { + filter.sortPropertyName = "fnd0StringValues"; // lovĺֵ̨ + } else { + filter.sortPropertyName = "object_name"; // lovĺֵ̨ + } + + filter.order = 1; + filter.numberToReturn = 2000; + filter.maxResults = 2000; + + input.lov = lov; + input.filterData = filter; + LOVSearchResults result = lovService.getInitialLOVValues(input); + // System.out.println("111==="+result.toString()); + + for (LOVValueRow row : result.lovValues) { + Map map = row.propDisplayValues; + Map realmap = row.propInternalValues; +// for (String key : map.keySet()) { +// System.out.println("key=" + key + ",value=" + map.get(key)[0]); +// } +// for (String key : realmap.keySet()) { +// System.out.println("key2=" + key + ",value2=" + map.get(key)[0]); +// } + String disval = ""; + String val = ""; + String key1 = "object_name";// ʵֵ ʾֵһ + if ("LD6_TecDoc_TypeLOV".equals(lovName)) { + key1 = "fnd0StringValues"; // lovĺֵ̨ + } + // String key2 = "object_desc";// ʾֵڶ + if (map.containsKey(key1)) { + val = realmap.get(key1)[0]; + disval = map.get(key1)[0]; + } + if (!val.equals("")) { + lovMap.put(disval, val); + if (comboBox != null) { + comboBox.addItem(disval); + } + } + + } + + } else { + ListOfValuesInfo info = lov.getListOfValues(); + info.getLOVDisplayValues(); + List lovValueList = info.getValues(); + for (LovValue lovV : lovValueList) { + lovMap.put(lovV.getDisplayValue(), lovV.getStringValue()); + if (comboBox != null) { + comboBox.addItem(lovV.getDisplayValue()); + } + } + } + + } + +// public static void dealPref(String[] prefVals, InterfaceAIFComponent targetComponent, +// ArrayList beanList, StringBuffer newTypeBuffer) throws Exception { +// /** +// * LD6_PRRevision/LD6_CR|*[string]Item.item_id=; +// * *[string]Item.object_name=;*[string]Rev.ld6_processNum=;*[string]Rev.ld6_productNum=Rev.ld6_proNum +// */ +// String type = targetComponent.getType(); +// TCComponentItemRevision rev = (TCComponentItemRevision) targetComponent; +// for (String string : prefVals) { +// String[] split = string.split("\\|"); +// if (split.length == 2) { +// String[] split2 = split[0].split("/"); +// if (split2.length == 2 && type.equals(split2[0])) { +// // õ +// newTypeBuffer.append(split2[1]); +// // õĿؼ +// String[] split3 = split[1].split(";"); +// for (int i = 0; i < split3.length; i++) { +// ControlBean bean = new ControlBean(); +// if (split3[i].contains("*[")) { +// bean.setIfMust(true); +// } +// String[] split4 = split3[i].split("="); +// // жʲô͵ +// if (split4[0].contains("boolean")) { +// bean.setPropType("boolean"); +// } else if (split4[0].contains("date")) { +// bean.setPropType("date"); +// } else if (split4[0].contains("string:")) { +// bean.setPropType("lov"); +// } else if (split4[0].contains("string") && !split4[0].contains("string:")) { +// bean.setPropType("string"); +// } +// if (split4.length == 2) { +// bean.setDefaultValue(getTCPropertyValue(rev, split4[1], bean)); +// } +// String[] split5 = split4[0].split("]"); +// if (split5.length == 2) { +// String[] split6 = split5[1].split("\\."); +// bean.setPropTo(split6[0]); +// bean.setPropRelName(split6[1]); +// bean.setPropName(split6[2]); +// if ("lov".equals(bean.getPropType())) { +// // õlovlovMap +// String[] split7 = split5[0].split(":"); +// String lovName = split7[1]; +// HashMap lovMap = new LinkedHashMap(); +// // JComboBox combox = new JComboBox(); +// try { +// String desType = newTypeBuffer.toString(); +// if ("Rev".equals(bean.getPropTo())) { +// desType = desType + "Revision"; +// } else if ("Form".equals(bean.getPropTo())) { +// desType = desType + "RevisionMaster"; +// } +// TCComponentType localTCComponentType = session.getTypeComponent(desType); +// TCPropertyDescriptor descriptor = localTCComponentType +// .getPropertyDescriptor(bean.getPropRelName()); +// LOVDisplayer combo = new LOVDisplayer(descriptor); +// getLov(lovMap, lovName, null); +// bean.setCombox(combo); +// } catch (TCException e) { +// e.printStackTrace(); +// } +// bean.setLovMap(lovMap); +// // bean.setCombox(combox); +// } +// } +// beanList.add(bean); +// } +// break; +// } +// } +// } +// } + +// public static String getTCPropertyValue(TCComponentItemRevision rev, String specialValue, ControlBean bean) { +// try { +// String[] split = specialValue.split("\\."); +// TCComponent center = null; +// if (split.length == 2 || split.length == 3) { +// switch (split[0]) { +// case "Rev": +// center = rev; +// break; +// case "Item": +// center = rev.getItem(); +// break; +// case "Form": +// center = rev.getRelatedComponent("IMAN_master_form_rev"); +// break; +// default: +// break; +// } +// String value = ""; +// if ("date".equals(bean.getPropType())) { +// System.out.println("ǰʵΪ" + split[1]); +// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-dd HH:mm"); +// if (center.getDateProperty(split[1]) != null) { +// value = sdf.format(center.getDateProperty(split[1])); +// } +// } else { +// value = center.getStringProperty(split[1]); +// } +// if (split.length == 3) { +// bean.setPropName(split[2]); +// } +// return value; +// } +// } catch (Exception e) { +// e.printStackTrace(); +// } +// return ""; +// } +} diff --git a/src/com/langtech/plm/tqsx/PropertyToWordOrExcelCommand.java b/src/com/langtech/plm/tqsx/PropertyToWordOrExcelCommand.java new file mode 100644 index 0000000..7d7e7d6 --- /dev/null +++ b/src/com/langtech/plm/tqsx/PropertyToWordOrExcelCommand.java @@ -0,0 +1,66 @@ +package com.langtech.plm.tqsx; + +import java.io.File; + +import com.teamcenter.rac.aif.AIFDesktop; +import com.teamcenter.rac.aif.AbstractAIFApplication; +import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; +import com.teamcenter.rac.kernel.TCComponent; +import com.teamcenter.rac.kernel.TCComponentDataset; +import com.teamcenter.rac.kernel.TCComponentItemRevision; +import com.teamcenter.rac.kernel.TCSession; + + + +public class PropertyToWordOrExcelCommand extends KCommand{ + + final String preName = "Connor_LY6_WordExcel_Report_ItemType"; + + public PropertyToWordOrExcelCommand(AbstractAIFApplication app, String commandId, String actionInfo) { + super(app, commandId, actionInfo); + TCSession session = (TCSession) app.getSession(); + this.setRunnable(new PropertyToWordOrExcelOperation(app, "ȡ汾ԵWord Excel")); +// InterfaceAIFComponent targetComponent = app.getTargetComponent(); +// TCComponentItemRevision revision = (TCComponentItemRevision) targetComponent; +// try { +// String[] prefVals = KUtil.getPrefVals(session, preName); +// if(prefVals == null || prefVals.length == 0) { +// KUtil.info(AIFDesktop.getActiveDesktop(), preName + "ѡδãϵԱ"); +// return ; +// } +// String relatioin = prefVals[0]; +// TCComponent[] relatedComponents = revision.getRelatedComponents(relatioin); +// if(relatedComponents == null || relatedComponents.length == 0) { +// KUtil.info(AIFDesktop.getActiveDesktop(), "ѡж " + relatioin + " ϵûݼ"); +// return ; +// } +// for (TCComponent tcComponent : relatedComponents) { +// if (tcComponent instanceof TCComponentDataset) { +// TCComponentDataset dataset = (TCComponentDataset) tcComponent; +// File datasetFile = KUtil.getDatasetFile(dataset); +// System.out.println(); +// String type = tcComponent.getType(); +// switch (type) { +// case "MSExcel": +// +// break; +// case "MSExcelX": +// +// break; +// case "MSWord": +// +// break; +// case "MSWordX": +// +// break; +// } +// } +// } +// } catch (Exception e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } + + } + +} diff --git a/src/com/langtech/plm/tqsx/PropertyToWordOrExcelOperation.java b/src/com/langtech/plm/tqsx/PropertyToWordOrExcelOperation.java new file mode 100644 index 0000000..feb3d8f --- /dev/null +++ b/src/com/langtech/plm/tqsx/PropertyToWordOrExcelOperation.java @@ -0,0 +1,288 @@ +package com.langtech.plm.tqsx; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.poi.hssf.usermodel.HSSFCell; +import org.apache.poi.hssf.usermodel.HSSFName; +import org.apache.poi.hssf.usermodel.HSSFRow; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.util.CellReference; +import org.apache.poi.xssf.usermodel.XSSFCell; +import org.apache.poi.xssf.usermodel.XSSFName; +import org.apache.poi.xssf.usermodel.XSSFRow; +import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + +import com.aspose.words.Bookmark; +import com.aspose.words.Document; +import com.aspose.words.SaveFormat; +import com.teamcenter.rac.aif.AIFDesktop; +import com.teamcenter.rac.aif.AbstractAIFApplication; +import com.teamcenter.rac.aif.kernel.AbstractAIFSession; +import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; +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.TCException; +import com.teamcenter.rac.kernel.TCProperty; +import com.teamcenter.rac.util.FileUtility; + + + +public class PropertyToWordOrExcelOperation extends KOperation { + + public PropertyToWordOrExcelOperation(AbstractAIFApplication app, String opName) { + super(app, opName, "ִС"); + } + + final String preName = "Connor_LY6_WordExcel_Report_ItemType"; + + @Override + public boolean init() throws Exception { + new Thread().sleep(1000); + InterfaceAIFComponent targetComponent = app.getTargetComponent(); + TCComponentItemRevision revision = (TCComponentItemRevision) targetComponent; + String[] prefVals = KUtil.getPrefVals(session, preName); + if(prefVals == null || prefVals.length == 0) { + KUtil.info(AIFDesktop.getActiveDesktop(), preName + "ѡδãϵԱ"); + return false; + } + String relatioin = prefVals[0]; + TCComponent[] relatedComponents = revision.getRelatedComponents(relatioin); + if(relatedComponents == null || relatedComponents.length == 0) { + KUtil.info(AIFDesktop.getActiveDesktop(), "ѡж " + relatioin + " ϵûݼ"); + return false; + } + //ѡ + HashMap nameMap = new HashMap();//ݼƺͶ(item,rev,revMaster) + if(prefVals.length >= 2) { + for (int i = 1; i < prefVals.length; i++) { + //Item.object_name=object_name + String[] split = prefVals[i].split("="); + nameMap.put(split[1],split[0]); + } + } + for (TCComponent tcComponent : relatedComponents) { + if (tcComponent instanceof TCComponentDataset) { + TCComponentDataset dataset = (TCComponentDataset) tcComponent; + File datasetFile = KUtil.getDatasetFile(dataset); + String type = tcComponent.getType(); + String datasetType = ""; + String newPath = ""; + if("MSExcel".equals(type) || "MSExcelX".equals(type) || "MSWord".equals(type) || "MSWordX".equals(type)) { + switch (type) { + case "MSExcel": + datasetType = "excel"; + newPath = dealExcel(datasetFile,revision,nameMap); + break; + case "MSExcelX": + datasetType = "excel"; + newPath = dealExcelX(datasetFile,revision,nameMap); + break; + case "MSWord": + datasetType = "word"; + newPath = dealWord2(datasetFile,revision,nameMap,"doc"); + break; + case "MSWordX": + datasetType = "word"; + newPath = dealWord2(datasetFile,revision,nameMap,"docx"); + break; + } + //ݼµ + dataset.setFiles(new String[] {newPath}, new String[] {datasetType}); + } + } + } + KUtil.info(AIFDesktop.getActiveDesktop(), "ȡ汾ԵWord Excelִ"); + return true; + } + + @Override + public void execute() throws Exception { + + } + + private String dealExcel(File datasetFile, TCComponentItemRevision revision, HashMap nameMap) throws IOException, TCException { + FileInputStream is = new FileInputStream(datasetFile); + HSSFWorkbook workbook = new HSSFWorkbook(is); + List allNames = workbook.getAllNames(); + for (HSSFName hssfName : allNames) { + String name = hssfName.getNameName(); + //ƹѡ + if (nameMap.containsKey(name)) { + CellReference cellReference = new CellReference(hssfName.getRefersToFormula()); + HSSFSheet sheet = workbook.getSheet(cellReference.getSheetName()); + HSSFRow row = sheet.getRow(cellReference.getRow()); + HSSFCell cell = row.getCell(cellReference.getCol()); + String preConfigValue = getPreConfigValue(revision,nameMap,nameMap.get(name)); + System.out.println("Ϊ" + cellReference.getRow() + "====" + "Ϊ" + cellReference.getCol() + "====" + + "ֵΪ " + preConfigValue); + if(cell == null) { + cell = row.createCell(cellReference.getCol()); + } + cell.setCellValue(preConfigValue); + + } + } + is.close(); + FileOutputStream os = new FileOutputStream(datasetFile); + workbook.write(os); + workbook.close(); + return datasetFile.getAbsolutePath(); + } + + private String dealExcelX(File datasetFile, TCComponentItemRevision revision, HashMap nameMap) throws IOException, TCException { + FileInputStream is = new FileInputStream(datasetFile); + XSSFWorkbook workbook = new XSSFWorkbook(is); + List allNames = workbook.getAllNames(); + for (XSSFName xssfName : allNames) { + String name = xssfName.getNameName(); + //ƹѡ + if (nameMap.containsKey(name)) { + CellReference cellReference = new CellReference(xssfName.getRefersToFormula()); + XSSFSheet sheet = workbook.getSheet(cellReference.getSheetName()); + XSSFRow row = sheet.getRow(cellReference.getRow()); + XSSFCell cell = row.getCell(cellReference.getCol()); + String preConfigValue = getPreConfigValue(revision,nameMap,nameMap.get(name)); + System.out.println("Ϊ" + cellReference.getRow() + "====" + "Ϊ" + cellReference.getCol() + "====" + + "ֵΪ " + preConfigValue); + if(cell == null) { + cell = row.createCell(cellReference.getCol()); + cell.setCellValue(preConfigValue); + } + else { + cell.setCellValue(preConfigValue); + } + } + } + is.close(); + FileOutputStream os = new FileOutputStream(datasetFile); + workbook.write(os); + workbook.close(); + return datasetFile.getAbsolutePath(); + } + + private String dealWord(File datasetFile, TCComponentItemRevision revision, HashMap nameMap,String type) throws IOException, TCException { + String path = datasetFile.getAbsolutePath(); + InputStream inputStream = Files.newInputStream(Paths.get(path)); + Map dataMap = new HashMap<>(); + for(String key : nameMap.keySet()) { + String preConfigValue = getPreConfigValue(revision,nameMap,nameMap.get(key)); + dataMap.put(key, preConfigValue); + } + String newPath = ""; + if(type.equals("doc")) { + newPath = path.replace(".doc", "temp.doc"); + WordUtils.replaceBookmarksByDoc(inputStream, Files.newOutputStream(Paths.get(newPath)), dataMap); + } + else if(type.equals("docx")) { + newPath = path.replace(".docx", "temp.docx"); + WordUtils.replaceBookmarksByDocx(inputStream, Files.newOutputStream(Paths.get(newPath)), dataMap); + } + return newPath; + } + + private String dealWord2(File datasetFile, TCComponentItemRevision revision, HashMap nameMap,String type) throws FileNotFoundException, Exception { + String path = datasetFile.getAbsolutePath(); + Document document2 = new Document(new FileInputStream(path)); + OutputStream outputStream = null; + String newPath = path.replace(".doc", "temp.doc"); + outputStream = new FileOutputStream(newPath); + Map dataMap = new HashMap<>(); + for(String key : nameMap.keySet()) { + String preConfigValue = getPreConfigValue(revision,nameMap,nameMap.get(key)); + dataMap.put(key, preConfigValue); + } + for (Bookmark bookmark : document2.getRange().getBookmarks()) { + String bookmarkName = bookmark.getName(); + System.out.println("ǩ"+bookmarkName); + if(dataMap.containsKey(bookmarkName)) + { + System.out.println(""); + bookmark.setText(dataMap.get(bookmarkName)); + } + } + if(type.equals("doc")) { + document2.save(outputStream, SaveFormat.DOC); + }else if(type.equals("docx")) { + document2.save(outputStream, SaveFormat.DOCX); + } + return newPath; + } + + /** + * õѡС=߶Ӧֵ + * @param revision + * @param nameMap + * @param value + * @return + * @throws TCException + */ + private String getPreConfigValue(TCComponentItemRevision revision, HashMap nameMap,String value) throws TCException { + String[] split = value.split("\\."); + String cellValue = ""; + TCProperty property = null; + if(split.length == 2) { + switch (split[0]) { + case "Item": + property = revision.getItem().getTCProperty(split[1]); + break; + case "Rev": + property = revision.getTCProperty(split[1]); + break; + case "RevMaster": + property = revision.getRelatedComponent("IMAN_master_form_rev").getTCProperty(split[1]); + break; + default: + break; + } + } + //ȡϵļµ + else if(split.length == 3) { + String relation = split[0]; + TCComponent relatedComponent = revision.getRelatedComponent(relation); + TCComponentItemRevision centerRev = null; + if(relatedComponent instanceof TCComponentItemRevision) { + centerRev = (TCComponentItemRevision) relatedComponent; + }else if(relatedComponent instanceof TCComponentItem) { + centerRev = ((TCComponentItem) relatedComponent).getLatestItemRevision(); + } + if(centerRev != null) { + switch (split[1]) { + case "Item": + property = centerRev.getItem().getTCProperty(split[2]); + break; + case "Rev": + property = centerRev.getTCProperty(split[2]); + break; + case "RevMaster": + property = centerRev.getRelatedComponent("IMAN_master_form_rev").getTCProperty(split[2]); + break; + default: + break; + } + } + } + if(property == null) { + return ""; + } + else { + cellValue = property.getDisplayValue(); + return cellValue; + } + } +} diff --git a/src/com/langtech/plm/tqsx/WordUtils.java b/src/com/langtech/plm/tqsx/WordUtils.java new file mode 100644 index 0000000..c8b7f82 --- /dev/null +++ b/src/com/langtech/plm/tqsx/WordUtils.java @@ -0,0 +1,167 @@ +package com.langtech.plm.tqsx; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.poi.hwpf.HWPFDocument; +import org.apache.poi.hwpf.usermodel.Bookmark; +import org.apache.poi.hwpf.usermodel.Bookmarks; +import org.apache.poi.hwpf.usermodel.Range; +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.apache.poi.xwpf.usermodel.XWPFParagraph; +import org.apache.poi.xwpf.usermodel.XWPFRun; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBookmark; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; +import org.w3c.dom.Node; + +public class WordUtils { + + public static final String RUN_NODE_NAME = "w:r"; + public static final String TEXT_NODE_NAME = "w:t"; + public static final String BOOKMARK_START_TAG = "w:bookmarkStart"; + public static final String BOOKMARK_END_TAG = "w:bookmarkEnd"; + public static final String BOOKMARK_ID_ATTR_NAME = "w:id"; + public static final String STYLE_NODE_NAME = "w:rPr"; + + public static void main(String[] args) throws IOException { + // 滻ļе bookmark + InputStream inputStream3 = Files.newInputStream(Paths.get("C:\\Users\\Administrator\\Desktop\\ļ\\22.doc")); + Map dataMap = new HashMap<>(); + dataMap.put("one", "oneoneoneoneone"); + dataMap.put("two", "twotwotwotwo"); + dataMap.put("three", "ceshi"); + replaceBookmarksByDoc(inputStream3, Files.newOutputStream(Paths.get("C:\\Users\\Administrator\\Desktop\\ļ\\33.doc")), dataMap); + } + + /** + * ȡ doc ļеǩ + * + * @param inputStream + * @throws IOException + */ + public static void getBookmarksByDoc(InputStream inputStream) throws IOException { + HWPFDocument wordDoc = new HWPFDocument(inputStream); + + Bookmarks bookmarks = wordDoc.getBookmarks(); + + for (int b = 0; b < bookmarks.getBookmarksCount(); b++) { + Bookmark bookmark = bookmarks.getBookmark(b); + String bookMarkText = new Range(bookmark.getStart(), bookmark.getEnd(), wordDoc).text(); + + System.out.println("[" + bookmark.getStart() + "; " + + bookmark.getEnd() + "]: " + bookmark.getName() + " = " + bookMarkText); + } + + } + + /** + * ȡ docx ļеǩ + * + * @param inputStream + * @throws IOException + */ + public static void getBookmarksByDocx(InputStream inputStream) throws IOException { + XWPFDocument docx = new XWPFDocument(inputStream); + + List paragraphList = docx.getParagraphs(); + for (XWPFParagraph xwpfParagraph : paragraphList) { + CTP ctp = xwpfParagraph.getCTP(); + + for (int dwI = 0; dwI < ctp.sizeOfBookmarkStartArray(); dwI++) { + CTBookmark bookmark = ctp.getBookmarkStartArray(dwI); + String bookmarkName = bookmark.getName(); + + // Ϊ docx Ľṹxmlʽ doc ĵоstartendֵλһbookmarkֵΧ + // Ҫȡ docx ĵbookmarkݣҪ bookmarkStart ڵ㿪ʼνxml + // nodeValue ֵƴӣֱȡһΪ bookmarkEnd ĽڵΪֹ + // getBookmarkTextContent() һûʵֵķҪʵ + // String bookmarkTextContent = getBookmarkTextContent(bookmark); + + System.out.println(bookmarkName); + } + } + } + + + /** + * docx ļǩ滻 + * + * @param inputStream + * @param outputStream + * @param dataMap + * @throws IOException + */ + public static void replaceBookmarksByDocx(InputStream inputStream, OutputStream outputStream, Map dataMap) throws IOException { + XWPFDocument document = new XWPFDocument(inputStream).getXWPFDocument(); + List paragraphList = document.getParagraphs(); + for (XWPFParagraph xwpfParagraph : paragraphList) { + CTP ctp = xwpfParagraph.getCTP(); + + for (int dwI = 0; dwI < ctp.sizeOfBookmarkStartArray(); dwI++) { + CTBookmark bookmark = ctp.getBookmarkStartArray(dwI); + if (dataMap.containsKey(bookmark.getName())) { + + XWPFRun run = xwpfParagraph.createRun(); + run.setText(dataMap.get(bookmark.getName())); + + Node firstNode = bookmark.getDomNode(); + Node nextNode = firstNode.getNextSibling(); + while (nextNode != null) { + // ѭҽ + String nodeName = nextNode.getNodeName(); + if (nodeName.equals(BOOKMARK_END_TAG)) { + break; + } + + // ɾмķǽڵ㣬ɾԭǩ + Node delNode = nextNode; + nextNode = nextNode.getNextSibling(); + ctp.getDomNode().removeChild(delNode); + } + + if (nextNode == null) { + // ʼҲʶģǩǰ + ctp.getDomNode().insertBefore(run.getCTR().getDomNode(), firstNode); + } else { + // ҵӵ֮ǰдbookmarkм + ctp.getDomNode().insertBefore(run.getCTR().getDomNode(), nextNode); + } + } + } + } + + document.write(outputStream); + document.close(); + } + + + /** + * doc ļǩ滻 + * + * @param inputStream + * @param outputStream + * @param dataMap + * @throws IOException + */ + public static void replaceBookmarksByDoc(InputStream inputStream, OutputStream outputStream, + Map dataMap) throws IOException { + HWPFDocument document = new HWPFDocument(inputStream); + Bookmarks bookmarks = document.getBookmarks(); + for (int dwI = 0; dwI < bookmarks.getBookmarksCount(); dwI++) { + Bookmark bookmark = bookmarks.getBookmark(dwI); + if (dataMap.containsKey(bookmark.getName())) { + Range range = new Range(bookmark.getStart(), bookmark.getEnd(), document); + range.replaceText(dataMap.get(bookmark.getName()), false); + } + } + document.write(outputStream); + } +} + + diff --git a/src/com/teamcenter/rac/stylesheet/stylesheet_user.properties b/src/com/teamcenter/rac/stylesheet/stylesheet_user.properties new file mode 100644 index 0000000..93ef268 --- /dev/null +++ b/src/com/teamcenter/rac/stylesheet/stylesheet_user.properties @@ -0,0 +1 @@ +LD6_NewProdForm.FORMJAVARENDERING=com.langtech.plm.form.LD6_NewProdForm \ No newline at end of file