commit 859f15c2d56c66bcd7cb9daa507e0dcc05b53f8c Author: qiyh Date: Thu Nov 9 14:01:13 2023 +0800 提交代码 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..82eca33 --- /dev/null +++ b/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/44b29832062a1a8f25c637c9897adbac1b3d608c346301551123fd383bcd0566.png b/44b29832062a1a8f25c637c9897adbac1b3d608c346301551123fd383bcd0566.png new file mode 100644 index 0000000..f1f2c8f Binary files /dev/null and b/44b29832062a1a8f25c637c9897adbac1b3d608c346301551123fd383bcd0566.png differ diff --git a/README.md b/README.md new file mode 100644 index 0000000..fe06b4a --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +SpringBoot集成JWT实现token验证 \ No newline at end of file diff --git a/mvnw b/mvnw new file mode 100644 index 0000000..5bf251c --- /dev/null +++ b/mvnw @@ -0,0 +1,225 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Migwn, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +echo $MAVEN_PROJECTBASEDIR +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..019bd74 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,143 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" + +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/out/artifacts/java_git_jar/java_git.jar b/out/artifacts/java_git_jar/java_git.jar new file mode 100644 index 0000000..c4d67c5 Binary files /dev/null and b/out/artifacts/java_git_jar/java_git.jar differ diff --git a/out/artifacts/tcoaserver/tcoaserver.war b/out/artifacts/tcoaserver/tcoaserver.war new file mode 100644 index 0000000..720dd19 Binary files /dev/null and b/out/artifacts/tcoaserver/tcoaserver.war differ diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..3cf5638 --- /dev/null +++ b/pom.xml @@ -0,0 +1,310 @@ + + + 4.0.0 + + com.pjb + springboot-jjwt + 0.0.1-SNAPSHOT + jar + + springboot-jjwt + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 2.0.3.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + + io.springfox + springfox-swagger2 + 2.9.2 + + + + io.springfox + springfox-swagger-ui + 2.9.2 + + + + org.springframework.boot + spring-boot-starter-web + + + org.mybatis.spring.boot + mybatis-spring-boot-starter + 1.3.2 + + + com.alibaba + fastjson + 1.2.47 + + + io.jsonwebtoken + jjwt + 0.9.1 + + + com.auth0 + java-jwt + 3.4.0 + + + + mysql + mysql-connector-java + runtime + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + com.oracle + ojdbc8 + 12.2.0.1 + + + teamcenter + commons-io + 2.5 + + + teamcenter + commons-logging + 2.5 + + + teamcenter + fccclient + 12.3.0 + + + + teamcenter + fscclient + 12.3.0 + + + + teamcenter + httpclient + 12.3.0 + + + + teamcenter + httpcore + 12.3.0 + + + + teamcenter + httpmime + 12.3.0 + + + + teamcenter + log4j + 12.3.0 + + + + teamcenter + TcSoaAdministrationStrong + 12.3.0 + + + + teamcenter + TcSoaAiStrong + 12.3.0 + + + + teamcenter + TcSoaAllocationsStrong + 12.3.0 + + + + teamcenter + TcSoaBomStrong + 12.3.0 + + + + teamcenter + TcSoaBusinessModelerStrong + 12.3.0 + + + + teamcenter + TcSoaCadBomAlignmentStrong + 12.3.0 + + + + teamcenter + TcSoaCadStrong + 12.3.0 + + + + teamcenter + TcSoaCaeStrong + 12.3.0 + + + + teamcenter + TcSoaCalendarManagementStrong + 12.3.0 + + + + teamcenter + TcSoaChangeManagementStrong + 12.3.0 + + + + teamcenter + TcSoaClassificationStrong + 12.3.0 + + + + teamcenter + TcSoaClient + 12.3.0 + + + + teamcenter + TcSoaCommon + 12.3.0 + + + + teamcenter + TcSoaConfigurationStrong + 12.3.0 + + + + teamcenter + TcSoaCoreLoose + 12.3.0 + + + + teamcenter + TcSoaCoreStrong + 12.3.0 + + + + teamcenter + TcSoaDocumentManagementStrong + 12.3.0 + + + + teamcenter + TcSoaImportExportStrong + 12.3.0 + + + + teamcenter + TcSoaQueryStrong + 12.3.0 + + + + teamcenter + TcSoaStrongModel + 12.3.0 + + + + teamcenter + xercesImpl + 12.3.0 + + + + teamcenter + xml-apis + 12.3.0 + + + teamcenter + TcSoaWorkflowStrong + 12.3.0 + + + + com.squareup.okhttp3 + okhttp + 4.8.0 + + + + org.jetbrains.kotlin + kotlin-stdlib + 1.3.50 + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + 2.3.4.RELEASE + + + org.apache.maven.plugins + maven-jar-plugin + 2.6 + + + + true + lib/ + com.pjb.springbootjjwt.SpringbootJjwtApplication + + + + + + + + + + diff --git a/src/main/java/com/pjb/springbootjjwt/Classification/ClassificationMain.java b/src/main/java/com/pjb/springbootjjwt/Classification/ClassificationMain.java new file mode 100644 index 0000000..d5c9c2e --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/Classification/ClassificationMain.java @@ -0,0 +1,99 @@ +// Copyright 2017 Siemens Product Lifecycle Management Software Inc. All Rights Reserved. +// ================================================== +// Copyright 2011. +// Siemens Product Lifecycle Management Software Inc. +// All Rights Reserved. +// ================================================== +// Copyright 2017 Siemens Product Lifecycle Management Software Inc. All Rights Reserved. + +package com.pjb.springbootjjwt.Classification; + +import com.teamcenter.clientx.AppXSession; + + +/** + * This sample client application demonstrates some of the basic features of the + * Teamcenter classification services. + * + * An instance of the Connection object is created with implementations of the + * ExceptionHandler, PartialErrorListener, ChangeListener, and DeleteListeners + * interfaces. This client application performs the following functions: + * 1. Establishes a session with the Teamcenter server + * 2. Perform the following tasks. + * Create or Update ICO objects. + * Create or Update keyLOV definitions. + * Get class attributes from the class ID. + * Get the class descriptions from the class ID. + * Get the KeyLOV definitions from the key LOV Id. + * + */ +public class ClassificationMain +{ + + /** + * @param args -help or -h will print out a Usage statement + */ + public static void main(String[] args) + { + if (args.length > 0) + { + if (args[0].equals("-help") || args[0].equals("-h")) + { + System.out.println("usage: java [-Dhost=http://server:port/tc] com.teamcenter.clientX.AppX"); + System.exit(0); + } + } + + // Get optional host information + String serverHost = "http://10.10.172.37:7001/tc"; + String host = System.getProperty("host"); + if (host != null && host.length() > 0) + { + serverHost = host; + } + + AppXSession session = new AppXSession(serverHost); + + try + { + // Establish a session with the Teamcenter Server + session.login(); + // testCreateAndUpdateICO demonstrate creating and updating stand alone ICO objects + CreateOrUpdateICOSample creOrUpdateICO = new CreateOrUpdateICOSample(); + creOrUpdateICO.testCreateAndUpdateICO(); + + // CreateOrUpdateKeyLOVSample demonstrate creating , obtaining , + CreateOrUpdateKeyLOVSample creOrUpdateKeyLov = new CreateOrUpdateKeyLOVSample(); + creOrUpdateKeyLov.testCreateKeyLOVs(); + creOrUpdateKeyLov.testGetKeyLOVs2(); + creOrUpdateKeyLov.testInsertKeyLOVEntry(); + creOrUpdateKeyLov.testRemoveKeyLOVEntry(); + creOrUpdateKeyLov.testUpdateKeyLOV(); + + // Get Attributes from a class ID + GetAttributesForClasses2Sample getAttrForClasses2 = new GetAttributesForClasses2Sample(); + getAttrForClasses2.testgetGetAttributesForClasses(); + + // Get class descriptions from a class ID + GetClassDescriptionsSample getClassDesc =new GetClassDescriptionsSample() ; + getClassDesc.testGetClassDescription(); + + //Get KeyLov definitions from KeyLOV id. + GetKeyLOVs2Sample getKeyLovs2 = new GetKeyLOVs2Sample() ; + getKeyLovs2.testGetKeyLOVs2(); + + // Get KeyLOV definitions from KeyLOV id. + GetKeyLOVsSample getKeyLovs = new GetKeyLOVsSample (); + getKeyLovs.testGetKeyLOVs1(); + + }catch (Exception ex) + { + System.out.println( ex.getMessage()); + return ; + + } + // Terminate the session with the Teamcenter server + session.logout(); + + } +} diff --git a/src/main/java/com/pjb/springbootjjwt/Classification/CreateOrUpdateICOSample.java b/src/main/java/com/pjb/springbootjjwt/Classification/CreateOrUpdateICOSample.java new file mode 100644 index 0000000..a85671f --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/Classification/CreateOrUpdateICOSample.java @@ -0,0 +1,120 @@ +// Copyright 2017 Siemens Product Lifecycle Management Software Inc. All Rights Reserved. +// ================================================== +// Copyright 2011. +// Siemens Product Lifecycle Management Software Inc. +// All Rights Reserved. +// ================================================== +// Copyright 2017 Siemens Product Lifecycle Management Software Inc. All Rights Reserved. + +package com.pjb.springbootjjwt.Classification; + + +import com.teamcenter.services.strong.classification._2007_01.Classification.ClassificationObject; +import com.teamcenter.services.strong.classification._2007_01.Classification.ClassificationProperty; +import com.teamcenter.services.strong.classification._2007_01.Classification.ClassificationPropertyValue; +import com.teamcenter.services.strong.classification._2007_01.Classification.CreateClassificationObjectsResponse; +import com.teamcenter.services.strong.classification._2007_01.Classification.UpdateClassificationObjectsResponse; +import com.teamcenter.services.strong.classification.ClassificationService; + +import com.teamcenter.clientx.AppXSession; +import com.teamcenter.schemas.soa._2006_03.exceptions.ServiceException; + + +/** + * This sample program create and update the standalone ICO. + * + * The following data must be created before executing the test. + * Create a string attribute with ID=4001 + * Create Class with ID=ICM4001 + * Add the attribute 4001 to the class ICM4001. + * + * Refer TDoc for creating classification data. + */ +public class CreateOrUpdateICOSample + +{ + ClassificationObject[] newICOs = new ClassificationObject[1]; + CreateClassificationObjectsResponse createICOResponse; + UpdateClassificationObjectsResponse updateICOResponse; + + /** + * This API create and update the standalone ICO object. + * @throws ServiceException + */ + public void testCreateAndUpdateICO()throws ServiceException + { + ClassificationService clsService = ClassificationService.getService(AppXSession.getConnection()); + System.out.println("Calling Classification::createClassificationObjects() ..."); + + ClassificationPropertyValue[] ico_prop_values1 = new ClassificationPropertyValue[1]; + ClassificationProperty[] ico_props = new ClassificationProperty[1]; + ClassificationObject[] icos = new ClassificationObject[1]; + + ico_prop_values1[0] = new ClassificationPropertyValue(); + ico_prop_values1[0].dbValue = "abc"; + + ico_props[0] = new ClassificationProperty(); + ico_props[0].attributeId = 4001; + ico_props[0].values = ico_prop_values1; + + icos[0] = new ClassificationObject(); + icos[0].classId = "ICM4001"; + icos[0].clsObjTag = null; + icos[0].instanceId = "ICO4007"; + icos[0].properties = ico_props; + icos[0].unitBase = "METRIC"; + // wsoId is null for standalone ICO. + icos[0].wsoId = null; + + // Create the ICO object + createICOResponse = clsService.createClassificationObjects( icos ); + + if ( createICOResponse.data.sizeOfPartialErrors() > 0) + throw new ServiceException( "ClassificationService.createClassificationObjects returned a partial Error."); + + System.out.println("... completed Classification::createClassificationObjects()"); + + if ( createICOResponse.clsObjs.length > 0 ) + { + // Set the data on classification property value for updating on ICO + icos[0].properties[0].values[0].dbValue = "defgh" ; + // Set the classification object tag to be updated. + icos[0].clsObjTag = createICOResponse.clsObjs[0].clsObjTag; + + updateICOResponse = clsService.updateClassificationObjects( icos ); + System.out.println("... completed Classification::updateClassificationObjects()"); + + if ( updateICOResponse.data.sizeOfPartialErrors() > 0) + throw new ServiceException( "ClassificationService.updateClassificationObjects returned a partial Error."); + + + int objCount = updateICOResponse.clsObjs.length ; + if ( objCount <= 0 ) + { + System.out.println("Nothing was done"); + } + else + { + ClassificationObject[] updatedICOs = new ClassificationObject[objCount]; + for ( int jnx = 0 ;jnx < objCount ; jnx++ ) + { + updatedICOs[jnx] = updateICOResponse.clsObjs[jnx]; + + System.out.println( "Class ID: " + updatedICOs[jnx].classId ); + System.out.println( "ICO ID: " + updatedICOs[jnx].instanceId ); + System.out.println( "Unit Base: " + updatedICOs[jnx].unitBase ); + System.out.println( "WSO Id: " + updatedICOs[jnx].wsoId ); + for( int attrIndex=0; attrIndex < updatedICOs[jnx].properties.length; attrIndex++) + { + if( updatedICOs[jnx].properties[attrIndex].attributeId == ico_props[0].attributeId ) + { + System.out.println( " Updated Attr ID: " + ico_props[0].attributeId ); + System.out.println( " Attr value: " + updatedICOs[jnx].properties[attrIndex].values[0].dbValue ); + } + } + } + } + + } + } +} diff --git a/src/main/java/com/pjb/springbootjjwt/Classification/CreateOrUpdateKeyLOVSample.java b/src/main/java/com/pjb/springbootjjwt/Classification/CreateOrUpdateKeyLOVSample.java new file mode 100644 index 0000000..7ff818d --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/Classification/CreateOrUpdateKeyLOVSample.java @@ -0,0 +1,303 @@ +// Copyright 2017 Siemens Product Lifecycle Management Software Inc. All Rights Reserved. +// ================================================== +// Copyright 2011. +// Siemens Product Lifecycle Management Software Inc. +// All Rights Reserved. +// ================================================== +// Copyright 2017 Siemens Product Lifecycle Management Software Inc. All Rights Reserved. + +package com.pjb.springbootjjwt.Classification; + +import com.teamcenter.services.strong.classification._2009_10.Classification.KeyLOVDefinition2; +import com.teamcenter.services.strong.classification._2009_10.Classification.KeyLOVEntry; +import com.teamcenter.services.strong.classification.ClassificationService; +import com.teamcenter.soa.client.model.ServiceData; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + + +import com.teamcenter.clientx.AppXSession; +import com.teamcenter.schemas.soa._2006_03.exceptions.ServiceException; + + +/** + * This class contain API's that create or update the KeyLov definitions. + * + */ +public class CreateOrUpdateKeyLOVSample +{ + + ClassificationService clsService = ClassificationService.getService(AppXSession.getConnection()); + + /** + * This test create specified keyLov definitions. + * + * @throws ServiceException + */ + + public void testCreateKeyLOVs()throws ServiceException + { + System.out.println("Calling the SOA createOrUpdateKeyLOVs"); + KeyLOVDefinition2[] lovDefnitions = new KeyLOVDefinition2[3]; + KeyLOVEntry[] keyLOVEntries = new KeyLOVEntry[3]; + + keyLOVEntries[0] =new KeyLOVEntry(); + keyLOVEntries[0].lovKey="6"; + keyLOVEntries[0].lovValue="600"; + keyLOVEntries[0].deprecatedSatus=true; + + keyLOVEntries[1] =new KeyLOVEntry(); + keyLOVEntries[1].lovKey="7"; + keyLOVEntries[1].lovValue="700"; + keyLOVEntries[1].deprecatedSatus=false; + + keyLOVEntries[2] =new KeyLOVEntry(); + keyLOVEntries[2].lovKey="8"; + keyLOVEntries[2].lovValue="800"; + keyLOVEntries[2].deprecatedSatus=false; + + lovDefnitions[0] = new KeyLOVDefinition2(); + lovDefnitions[0].id = "-2894"; + lovDefnitions[0].name = "Test2894"; + lovDefnitions[0].options = 0; + lovDefnitions[0].keyLovEntries = keyLOVEntries; + + lovDefnitions[1] = new KeyLOVDefinition2(); + lovDefnitions[1].id = "-1000"; + lovDefnitions[1].name = "Test1000"; + lovDefnitions[1].options = 0; + lovDefnitions[1].keyLovEntries = keyLOVEntries; + + lovDefnitions[2] = new KeyLOVDefinition2(); + lovDefnitions[2].id = "-1234"; + lovDefnitions[2].name = "Test1234"; + lovDefnitions[2].options = 0; + lovDefnitions[2].keyLovEntries = keyLOVEntries; + + ServiceData data = clsService.createOrUpdateKeyLOVs( lovDefnitions ); + if ( data.sizeOfPartialErrors() > 0 ) + throw new ServiceException( "ClassificationService.createOrUpdateKeyLOVs returned a partial Error."); + + System.out.println("***************************************************"); + System.out.println("********************Key Lov Created****************"); + System.out.println("***************************************************"); + + } + + /** + * This test insert keyLOV entries for the specified KeyLOV definition + * + * @throws ServiceException + */ + + public void testInsertKeyLOVEntry()throws ServiceException + { + System.out.println("Calling the SOA createOrUpdateKeyLOVs"); + KeyLOVDefinition2[] lovDefnitions = new KeyLOVDefinition2[3]; + KeyLOVEntry[] keyLOVEntries = new KeyLOVEntry[4]; + + keyLOVEntries[0] =new KeyLOVEntry(); + keyLOVEntries[0].lovKey="6"; + keyLOVEntries[0].lovValue="600"; + keyLOVEntries[0].deprecatedSatus=true; + + keyLOVEntries[1] =new KeyLOVEntry(); + keyLOVEntries[1].lovKey="7"; + keyLOVEntries[1].lovValue="700"; + keyLOVEntries[1].deprecatedSatus=false; + + keyLOVEntries[2] =new KeyLOVEntry(); + keyLOVEntries[2].lovKey="8"; + keyLOVEntries[2].lovValue="800"; + keyLOVEntries[2].deprecatedSatus=false; + + keyLOVEntries[3] =new KeyLOVEntry(); + keyLOVEntries[3].lovKey="9"; + keyLOVEntries[3].lovValue="900"; + keyLOVEntries[3].deprecatedSatus=false; + + lovDefnitions[0] = new KeyLOVDefinition2(); + lovDefnitions[0].id = "-2894"; + lovDefnitions[0].name = "Test2894"; + lovDefnitions[0].options = 0; + lovDefnitions[0].keyLovEntries = keyLOVEntries; + + lovDefnitions[1] = new KeyLOVDefinition2(); + lovDefnitions[1].id = "-1000"; + lovDefnitions[1].name = "Test1000"; + lovDefnitions[1].options = 0; + lovDefnitions[1].keyLovEntries = keyLOVEntries; + + lovDefnitions[2] = new KeyLOVDefinition2(); + lovDefnitions[2].id = "-1234"; + lovDefnitions[2].name = "Test1234"; + lovDefnitions[2].options = 0; + lovDefnitions[2].keyLovEntries = keyLOVEntries; + + ServiceData data = clsService.createOrUpdateKeyLOVs( lovDefnitions ); + if ( data.sizeOfPartialErrors() > 0 ) + throw new ServiceException( "ClassificationService.createOrUpdateKeyLOVs returned a partial Error."); + + System.out.println("***************************************************"); + System.out.println("********************Key Entry Inserted****************"); + System.out.println("***************************************************"); + + } + + /** + * This test remove the keyLOV entries for the specified KeyLOV definition + * + * @throws ServiceException + */ + public void testRemoveKeyLOVEntry()throws ServiceException + { + System.out.println("Calling the SOA createOrUpdateKeyLOVs"); + KeyLOVDefinition2[] lovDefnitions = new KeyLOVDefinition2[3]; + KeyLOVEntry[] keyLOVEntries = new KeyLOVEntry[3]; + + keyLOVEntries[0] =new KeyLOVEntry(); + keyLOVEntries[0].lovKey="6"; + keyLOVEntries[0].lovValue="600"; + keyLOVEntries[0].deprecatedSatus=true; + + keyLOVEntries[1] =new KeyLOVEntry(); + keyLOVEntries[1].lovKey="7"; + keyLOVEntries[1].lovValue="700"; + keyLOVEntries[1].deprecatedSatus=false; + + keyLOVEntries[2] =new KeyLOVEntry(); + keyLOVEntries[2].lovKey="9"; + keyLOVEntries[2].lovValue="900"; + keyLOVEntries[2].deprecatedSatus=false; + + lovDefnitions[0] = new KeyLOVDefinition2(); + lovDefnitions[0].id = "-2894"; + lovDefnitions[0].name = "Test2894"; + lovDefnitions[0].options = 0; + lovDefnitions[0].keyLovEntries = keyLOVEntries; + + lovDefnitions[1] = new KeyLOVDefinition2(); + lovDefnitions[1].id = "-1000"; + lovDefnitions[1].name = "Test1000"; + lovDefnitions[1].options = 0; + lovDefnitions[1].keyLovEntries = keyLOVEntries; + + lovDefnitions[2] = new KeyLOVDefinition2(); + lovDefnitions[2].id = "-1234"; + lovDefnitions[2].name = "Test1234"; + lovDefnitions[2].options = 0; + lovDefnitions[2].keyLovEntries = keyLOVEntries; + + ServiceData data = clsService.createOrUpdateKeyLOVs( lovDefnitions ); + if ( data.sizeOfPartialErrors() > 0 ) + throw new ServiceException( "ClassificationService.createOrUpdateKeyLOVs returned a partial Error."); + + System.out.println("***************************************************"); + System.out.println("********************Key Lov Entry Removed****************"); + System.out.println("***************************************************"); + + } + /** + * This test update keyLOV entries for the specified KeyLOV definition + * + * @throws ServiceException + */ + public void testUpdateKeyLOV()throws ServiceException + { + System.out.println("Calling the SOA createOrUpdateKeyLOVs"); + KeyLOVDefinition2[] lovDefnitions = new KeyLOVDefinition2[3]; + KeyLOVEntry[] keyLOVEntries = new KeyLOVEntry[3]; + + keyLOVEntries[0] =new KeyLOVEntry(); + keyLOVEntries[0].lovKey="6"; + keyLOVEntries[0].lovValue="60"; + keyLOVEntries[0].deprecatedSatus=true; + + keyLOVEntries[1] =new KeyLOVEntry(); + keyLOVEntries[1].lovKey="7"; + keyLOVEntries[1].lovValue="70"; + keyLOVEntries[1].deprecatedSatus=false; + + keyLOVEntries[2] =new KeyLOVEntry(); + keyLOVEntries[2].lovKey="9"; + keyLOVEntries[2].lovValue="90"; + keyLOVEntries[2].deprecatedSatus=false; + + lovDefnitions[0] = new KeyLOVDefinition2(); + lovDefnitions[0].id = "-2894"; + lovDefnitions[0].name = "Test2894"; + lovDefnitions[0].options = 0; + lovDefnitions[0].keyLovEntries = keyLOVEntries; + + lovDefnitions[1] = new KeyLOVDefinition2(); + lovDefnitions[1].id = "-1000"; + lovDefnitions[1].name = "Test1000"; + lovDefnitions[1].options = 0; + lovDefnitions[1].keyLovEntries = keyLOVEntries; + + lovDefnitions[2] = new KeyLOVDefinition2(); + lovDefnitions[2].id = "-1234"; + lovDefnitions[2].name = "Test1234"; + lovDefnitions[2].options = 0; + lovDefnitions[2].keyLovEntries = keyLOVEntries; + + ServiceData data = clsService.createOrUpdateKeyLOVs( lovDefnitions ); + if ( data.sizeOfPartialErrors() > 0 ) + throw new ServiceException( "ClassificationService.createOrUpdateKeyLOVs returned a partial Error."); + + System.out.println("***************************************************"); + System.out.println("********************Key Lov Updated****************"); + System.out.println("***************************************************"); + + } + + +/** + * This test get the keyLOV definitions for the specified KeyLOV id's + * + * @throws ServiceException + */ + public void testGetKeyLOVs2()throws ServiceException + { + String[] keyLOVIds = new String[1]; + keyLOVIds[0] = "-2894"; + System.out.println("Calling the SOA getKeyLOVs1"); + com.teamcenter.services.strong.classification._2009_10.Classification.GetKeyLOVsResponse2 response = clsService.getKeyLOVs2( keyLOVIds ); + if ( response.data.sizeOfPartialErrors() > 0 ) + throw new ServiceException( "ClassificationService.getKeyLOVs2 returned a partial Error."); + + Map keyLOVs = response.keyLOVs; + System.out.println("*****Lov Details*******"+keyLOVs.size()); + Set keys = keyLOVs.keySet(); + for(Iterator itr = keys.iterator();itr.hasNext();) + { + String id = itr.next(); + KeyLOVDefinition2 lovDef = keyLOVs.get( id ); + System.out.println("LOV Id : "+lovDef.id); + System.out.println("LOV Name : "+lovDef.name); + System.out.println("LOV Options : "+lovDef.options ); + System.out.println("LOV Owning Site : "+lovDef.owningSite.getUid()); + System.out.println("keyLOV Tag : "+lovDef.keyLovtag.getUid() ); + System.out.println("keyLOV Share Sites : "+lovDef.sharedSites.length); + KeyLOVEntry[] keyLOVEntries =lovDef.keyLovEntries; + + System.out.println("Size "+keyLOVEntries.length); + for(int i=0;i 0) + throw new ServiceException( "ClassificationService.getAttributesForClasses returned a partial Error."); + + ClassAttribute[] clsattr = new ClassAttribute[1]; + + Map attributes = response.attributes; + System.out.println( "After Call SOA " ); + + Set keys = attributes.keySet(); + for( Iterator itr = keys.iterator(); itr.hasNext(); ) + { + String id = itr.next(); + clsattr = attributes.get(id ); + + System.out.println (clsattr); + for( int i = 0; i < clsattr.length; i++ ) + { + + ClassAttribute clsattrs = clsattr[i]; + + System.out.println( "Attr Id: " + clsattrs.id ); + System.out.println( "Name: " + clsattrs.name ); + System.out.println( "shortname: " + clsattrs.shortName ); + System.out.println( "description: " + clsattrs.description ); + System.out.println( "annotation: " + clsattrs.annotation ); + System.out.println( "arraysize: " + clsattrs.arraySize ); + System.out.println( "options: " + clsattrs.options ); + System.out.println( "Attribute Length: " + clsattrs.altFormat.formatLength ); + System.out.println( "Attribute Modifier1: " + clsattrs.altFormat.formatModifier1 ); + System.out.println( "Attribute Modifier2: " + clsattrs.altFormat.formatModifier2 ); + System.out.println( "Attribute Type: " + clsattrs.altFormat.formatType ); + System.out.println( "Annotation: " + clsattrs.annotation ); + System.out.println( "Default Value: " + clsattrs.defaultValue ); + System.out.println( "Config: " + clsattrs.config ); + System.out.println( "Maximum Value: " + clsattrs.maxValue ); + System.out.println( "Minimum Value: " + clsattrs.minValue ); + System.out.println( "Post Config: " + clsattrs.postConfig ); + System.out.println( "Pre Config: " + clsattrs.preConfig ); + System.out.println( "Unit Name: " + clsattrs.unitName ); + System.out.println( "****************************************************" ); + + } + System.out.println( "****************************************************" ); + + } + + } +} diff --git a/src/main/java/com/pjb/springbootjjwt/Classification/GetClassDescriptionsSample.java b/src/main/java/com/pjb/springbootjjwt/Classification/GetClassDescriptionsSample.java new file mode 100644 index 0000000..5fc0edf --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/Classification/GetClassDescriptionsSample.java @@ -0,0 +1,97 @@ +// Copyright 2017 Siemens Product Lifecycle Management Software Inc. All Rights Reserved. +// ================================================== +// Copyright 2011. +// Siemens Product Lifecycle Management Software Inc. +// All Rights Reserved. +// ================================================== +// Copyright 2017 Siemens Product Lifecycle Management Software Inc. All Rights Reserved. + +package com.pjb.springbootjjwt.Classification; + +import com.teamcenter.services.strong.classification._2007_01.Classification.ClassDef; +import com.teamcenter.services.strong.classification._2007_01.Classification.ClassificationObject; +import com.teamcenter.services.strong.classification._2007_01.Classification.GetClassDescriptionsResponse; +import com.teamcenter.services.strong.classification._2007_01.Classification.SearchForClassesResponse; + + + +import java.util.Map; + +import com.teamcenter.clientx.AppXSession; +import com.teamcenter.services.strong.classification.ClassificationService; +import com.teamcenter.schemas.soa._2006_03.exceptions.ServiceException; + +/** + * This Class get the classification class descriptions from the class ID's + * + * The following data should exist before running this test. + * Create a class with ID=ICM4001 + * Add attributes to ICM4001 from data dictionary. + * + * Refer TDoc for creating classification data. + * + */ +public class GetClassDescriptionsSample + +{ + + ClassificationObject[] newICOs = new ClassificationObject[1]; + ClassificationObject[] foundICOs = new ClassificationObject[1]; + SearchForClassesResponse searchClassResponse; + GetClassDescriptionsResponse classDescResponse; + ClassDef classDescription; + + + + + /** + * @throws java.lang.ServiceException + * + */ + public void testGetClassDescription()throws ServiceException + { + // Get Class Descriptions ------------------------------------------------------------------- + String [] classIDs = new String[2]; + classIDs[0] = "ICM"; + classIDs[1] = "ICM4001"; + + ClassificationService clsService = ClassificationService.getService(AppXSession.getConnection()); + System.out.println("\t Calling Classification::getClassDescriptions() ..."); + classDescResponse = clsService.getClassDescriptions( classIDs ); + if ( classDescResponse.data.sizeOfPartialErrors() > 0) + throw new ServiceException( "ClassificationService.getClassDescriptions returned a partial Error."); + + System.out.println("\t ... completed Classification::getClassDescriptions()"); + + + Map classDescriptionsMap = classDescResponse.descriptions; + + + System.out.println("\t Class Details -"); + for( String key : classDescriptionsMap.keySet()) + { + ClassDef clsattr = classDescriptionsMap.get(key); + + System.out.println("****** Details for " + key + " ******"); + System.out.println( "Attr Id : " + clsattr.id ); + System.out.println( "Name : " + clsattr.name ); + System.out.println( "Short Name : " + clsattr.shortName ); + System.out.println( "Description : " + clsattr.description ); + + System.out.println( "Is Abstract? : " + clsattr.options.isAbstract ); + System.out.println( "Is Assembly? : " + clsattr.options.isAssembly ); + System.out.println( "Is Group? : " + clsattr.options.isGroup ); + System.out.println( "Is Valid? : " + clsattr.options.isValid ); + System.out.println( "Attr Format : " + clsattr.unitBase ); + System.out.println( "User Data : " + clsattr.userData1 ); + System.out.println( "User Data : " + clsattr.userData2 ); + System.out.println( "Child Count : " + clsattr.childCount ); + System.out.println( "Instance Count: " + clsattr.instanceCount ); + System.out.println( "Parent : " + clsattr.parent ); + System.out.println( "View Count : " + clsattr.viewCount ); + } + + System.out.println("\t ... completed testGetClassDescription()"); + } + +} diff --git a/src/main/java/com/pjb/springbootjjwt/Classification/GetKeyLOVs2Sample.java b/src/main/java/com/pjb/springbootjjwt/Classification/GetKeyLOVs2Sample.java new file mode 100644 index 0000000..9d7b3fb --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/Classification/GetKeyLOVs2Sample.java @@ -0,0 +1,80 @@ +// Copyright 2017 Siemens Product Lifecycle Management Software Inc. All Rights Reserved. +// ================================================== +// Copyright 2011. +// Siemens Product Lifecycle Management Software Inc. +// All Rights Reserved. +// ================================================== +// Copyright 2017 Siemens Product Lifecycle Management Software Inc. All Rights Reserved. + +package com.pjb.springbootjjwt.Classification; + +import com.teamcenter.services.strong.classification._2009_10.Classification.KeyLOVDefinition2; +import com.teamcenter.services.strong.classification._2009_10.Classification.KeyLOVEntry; + + +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import com.teamcenter.clientx.AppXSession; +import com.teamcenter.services.strong.classification.ClassificationService; +import com.teamcenter.schemas.soa._2006_03.exceptions.ServiceException; + +/** + * This sample program get the keyLOV definitions for the specified key LOV id's. + * + * The following data must be created before executing this test. + * Create KeyLov with ID=-2894 + * Add set of key value entries to -2894 + * + * Refer TDoc for classification data creation + * + */ + +public class GetKeyLOVs2Sample +{ + + /** + * get the KeyLOV definitions from keyLOV ID's. + * + * @throws ServiceException + */ + public void testGetKeyLOVs2()throws ServiceException + { + ClassificationService clsService = ClassificationService.getService(AppXSession.getConnection()); + String[] keyLOVIds = new String[1]; + keyLOVIds[0] = "-2894"; + System.out.println("Calling the SOA getKeyLOVs2"); + com.teamcenter.services.strong.classification._2009_10.Classification.GetKeyLOVsResponse2 response = clsService.getKeyLOVs2( keyLOVIds ); + if ( response.data.sizeOfPartialErrors() > 0) + throw new ServiceException( "ClassificationService.getKeyLOVs2 returned a partial Error."); + + Map keyLOVs = response.keyLOVs; + System.out.println("*****Lov Details******* "+keyLOVs.size()); + Set keys = keyLOVs.keySet(); + for(Iterator itr = keys.iterator();itr.hasNext();) + { + String id = itr.next(); + KeyLOVDefinition2 lovDef = keyLOVs.get( id ); + System.out.println("KeyLOV Id : "+lovDef.id); + System.out.println("KeyLOV Name : "+lovDef.name); + System.out.println("KeyLOV Options : "+lovDef.options); + System.out.println("KeyLOV Owning Site : "+lovDef.owningSite.getUid()); + System.out.println("KeyLOV tag : "+lovDef.keyLovtag.getUid()); + System.out.println("KeyLOV Share Sites : "+lovDef.sharedSites); + KeyLOVEntry[] keyLOVEntries =lovDef.keyLovEntries; + + System.out.println("Number of KeyLOV's : "+keyLOVEntries.length); + System.out.println("*************************************************************"); + for(int i=0;i 0) + throw new ServiceException( "ClassificationService.getKeyLOVs returned a partial Error."); + + + Map keyLOVs = response.keyLOVs; + System.out.println("*****LOV Details******* "); + Set keys = keyLOVs.keySet(); + for(Iterator itr = keys.iterator();itr.hasNext();) + { + String id = itr.next(); + KeyLOVDefinition lovDef = keyLOVs.get( id ); + System.out.println("KeyLOV ID: " + id.toString()); + System.out.println("KeyLOV Name: "+lovDef.name); + System.out.println("*************************************************************"); + + Map keyLovEntries= lovDef.keyValuePairs; + Set keySet = keyLovEntries.keySet(); + for ( Iterator iter = keySet.iterator();iter.hasNext();) + { + String key = iter.next(); + System.out.println("KeyLOV Entry Key : "+key ); + System.out.println("KeyLOV Entry Value : "+keyLovEntries.get(key)); + System.out.println("*************************************************************"); + } + + } + } +} diff --git a/src/main/java/com/pjb/springbootjjwt/SpringbootJjwtApplication.java b/src/main/java/com/pjb/springbootjjwt/SpringbootJjwtApplication.java new file mode 100644 index 0000000..376856c --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/SpringbootJjwtApplication.java @@ -0,0 +1,36 @@ +package com.pjb.springbootjjwt; + +import com.teamcenter.clientx.AppXSession; +import com.teamcenter.soa.client.model.strong.User; +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; + +@SpringBootApplication +@MapperScan("com.pjb.springbootjjwt.mapper") +public class SpringbootJjwtApplication { + public static String TC_URL; + public static String TC_USER; + public static String TC_PWD; + public static String TC_FMSURL; + public static String TC_FCCCACH; + public static String TC_WORKFLOWTEMPLATE; + public static String TC_TASKPACKAGE; + public static String TC_PAIPROJECTID; + public static String TC_PAIPROJECTNAME; + + + public static void main(String[] args) { + ConfigurableApplicationContext contenxt = SpringApplication.run(SpringbootJjwtApplication.class, args); + TC_URL = contenxt.getEnvironment().getProperty("teamcenter.url"); + TC_USER = contenxt.getEnvironment().getProperty("teamcenter.user"); + TC_PWD = contenxt.getEnvironment().getProperty("teamcenter.pwd"); + TC_FMSURL = contenxt.getEnvironment().getProperty("teamcenter.fmsurl"); + TC_FCCCACH = contenxt.getEnvironment().getProperty("teamcenter.fcccash"); + TC_WORKFLOWTEMPLATE = contenxt.getEnvironment().getProperty("teamcenter.workflowtemplate"); + TC_TASKPACKAGE = contenxt.getEnvironment().getProperty("teamcenter.taskPackage"); + TC_PAIPROJECTID = contenxt.getEnvironment().getProperty("teamcenter.paiProjectId"); + TC_PAIPROJECTNAME = contenxt.getEnvironment().getProperty("teamcenter.paiProjectName"); + } +} diff --git a/src/main/java/com/pjb/springbootjjwt/annotation/PassToken.java b/src/main/java/com/pjb/springbootjjwt/annotation/PassToken.java new file mode 100644 index 0000000..4ab52b1 --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/annotation/PassToken.java @@ -0,0 +1,13 @@ +package com.pjb.springbootjjwt.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + + +@Target({ElementType.METHOD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +public @interface PassToken { + boolean required() default true; +} diff --git a/src/main/java/com/pjb/springbootjjwt/annotation/UserLoginToken.java b/src/main/java/com/pjb/springbootjjwt/annotation/UserLoginToken.java new file mode 100644 index 0000000..612f366 --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/annotation/UserLoginToken.java @@ -0,0 +1,13 @@ +package com.pjb.springbootjjwt.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + + +@Target({ElementType.METHOD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +public @interface UserLoginToken { + boolean required() default true; +} diff --git a/src/main/java/com/pjb/springbootjjwt/api/IgtcoaApi.java b/src/main/java/com/pjb/springbootjjwt/api/IgtcoaApi.java new file mode 100644 index 0000000..cef2526 --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/api/IgtcoaApi.java @@ -0,0 +1,672 @@ +package com.pjb.springbootjjwt.api; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.pjb.springbootjjwt.SpringbootJjwtApplication; +import com.pjb.springbootjjwt.entity.*; +import com.pjb.springbootjjwt.service.IgtcoaServer; +import com.pjb.springbootjjwt.service.TcsoaService; +import com.teamcenter.clientx.AppXSession; +// import com.teamcenter.services.loose.core._2006_03.FileManagement; +import com.teamcenter.clientx.Utils; +import com.teamcenter.services.strong.administration.PreferenceManagementRestBindingStub; +import com.teamcenter.services.strong.administration.PreferenceManagementService; +import com.teamcenter.services.strong.administration._2012_09.PreferenceManagement; +import com.teamcenter.soa.client.model.ServiceData; +import com.teamcenter.soa.client.model.strong.User; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.Part; +import java.io.*; +import java.net.URLEncoder; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.*; + +@RestController +// @RequestMapping("igtcoa") +public class IgtcoaApi { + @Autowired IgtcoaServer igtcoaServer; + + private static AppXSession tcSession; + private static User tcUser; + private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS"); + private static SimpleDateFormat dateFormatLog = new SimpleDateFormat("yyyyMMddHHmmss"); + + // @UserLoginToken + @PostMapping(value = "/oaCreateWorkFlow") + public JsonResult createWorkFlow(@RequestBody JSONObject jsonObject) { + // "type": "Project" + String logFileName = dateFormatLog.format(new Date()); + // 添加日志记录传递的参数及报错信息 + Utils.setLog(logFileName, "oaCreateWorkFlow", jsonObject.toString()); + + HashMap + itemObjectPropMap = + new HashMap< + String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>(); + HashMap + revObjectPropMap = + new HashMap< + String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>(); + HashMap + revMasterObjectPropMap = + new HashMap< + String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>(); + Map fileMap = new HashMap(); + Map propertyMap = new HashMap(); + + // Map postValueMap = jsonObject.getInnerMap(); + // for (String key : postValueMap.keySet()) { + // Object value = postValueMap.get(key); + // if (value != null) { + // System.out.println("key:" + key + " value:" + value.toString()); + // // 获取属性及位置 + // if (key.indexOf(".") > 0) { + // String itemWhere = key.split(".")[0]; + // String itemName = key.split(".")[1]; + // com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct valueVecStruct + // = + // new com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct(); + // valueVecStruct.stringVec = new String[] {value.toString()}; + // switch (itemWhere) { + // case "item": + // itemObjectPropMap.put(itemName, valueVecStruct); + // break; + // case "rev": + // revObjectPropMap.put(itemName, valueVecStruct); + // break; + // case "revMaster": + // revMasterObjectPropMap.put(itemName, valueVecStruct); + // break; + // } + // } + // } + // } + + Utils.getData( + jsonObject.toString(), + itemObjectPropMap, + revObjectPropMap, + revMasterObjectPropMap, + fileMap, + propertyMap, + logFileName); + // Utils.getData(); + + // 获取必要的属性 + String task_Uid = + propertyMap.containsKey("task_uid") ? propertyMap.get("task_uid").toString() : ""; +// String taskWorkFlowUID = +// propertyMap.containsKey("TaskWorkFlowUID") ? propertyMap.get("TaskWorkFlowUID").toString() : ""; +// String taskPackageUID = +// propertyMap.containsKey("TaskPackageUID") ? propertyMap.get("TaskPackageUID").toString() : ""; + String task_name = + propertyMap.containsKey("task_name") ? propertyMap.get("task_name").toString() : ""; + String task_CustomerNameBilingUnit = + propertyMap.containsKey("project_CustomerNameBilingUnit") + ? propertyMap.get("project_CustomerNameBilingUnit").toString() + : ""; + String project_Projectname = + propertyMap.containsKey("project_Projectname") + ? propertyMap.get("project_Projectname").toString() + : ""; + String project_ProjectCode = + propertyMap.containsKey("project_ProjectCode") + ? propertyMap.get("project_ProjectCode").toString() + : ""; + String project_ProjectLevel = + propertyMap.containsKey("project_ProjectLevel") + ? propertyMap.get("project_ProjectLevel").toString() + : ""; + String task_product = + propertyMap.containsKey("task_product") ? propertyMap.get("task_product").toString() : ""; + String project_id = + propertyMap.containsKey("project_id") ? propertyMap.get("project_id").toString() : ""; + String project_uid = + propertyMap.containsKey("project_uid") ? propertyMap.get("project_uid").toString() : ""; + // String project_name = request.getParameter("project_name"); + // "type": "Task" + // String task_delivery = request.getParameter("task_delivery"); + // String task_uid = request.getParameter("task_uid"); + // String task_type = request.getParameter("task_type"); + // String task_priority = request.getParameter("task_priority"); + // String task_progress = request.getParameter("task_progress"); + // String task_duration = request.getParameter("task_duration"); + // String task_actualStartTime = request.getParameter("task_actualStartTime"); + // String task_actualEndTime = request.getParameter("task_actualEndTime"); + // String task_startTime = request.getParameter("task_startTime"); + // String task_endTime = request.getParameter("task_endTime"); + // String task_planWorkTime = request.getParameter("task_planWorkTime"); + // String task_description = + // request.getParameter("task_description")!=null?request.getParameter("task_description"):""; + // String task_Dstype = request.getParameter("task_Dstype"); + // String task_Dsigner = request.getParameter("task_Dsigner"); + // String task_YPdata = request.getParameter("task_YPdata"); + String user_id = + propertyMap.containsKey("user_id") ? propertyMap.get("user_id").toString() : ""; + Object userIdObject = propertyMap.get("user_id"); + if (userIdObject instanceof JSONArray) { + JSONArray jsonArray = JSONArray.parseArray(userIdObject.toString()); + user_id = jsonArray.getString(0); + } + + // 获取产品信息 + String productJson = + propertyMap.containsKey("product") ? propertyMap.get("product").toString() : null; + List productList = new ArrayList(); + if (productJson != null) { + JSONArray jsonArray = JSONArray.parseArray(productJson); + for (Object o : jsonArray) { + if (o instanceof JSONObject) { + JSONObject productJsonObject = JSONObject.parseObject(o.toString()); + String cUproductModel = + productJsonObject.containsKey("cUproductModel") + ? productJsonObject.getString("cUproductModel") + : "产品型号"; + String bearingCategory = + productJsonObject.containsKey("bearingCategory") + ? productJsonObject.getString("bearingCategory") + : "轴承类别"; + String plant = + productJsonObject.containsKey("plant") + ? productJsonObject.getString("plant") + : "工厂全称"; + String productApplicationFieldOrIndustry = + productJsonObject.containsKey("productApplicationFieldOrIndustry") + ? productJsonObject.getString("productApplicationFieldOrIndustry") + : "产品应用领域/行业"; + String productApplicationPart = + productJsonObject.containsKey("productApplicationPart") + ? productJsonObject.getString("productApplicationPart") + : "产品应用部位"; + String productType = + productJsonObject.containsKey("productType") + ? productJsonObject.getString("productType") + : "产品类型"; + // 拼接产品属性的值 + String productValue = + String.format( + "[%s][%s][%s][%s][%s][%s]", + cUproductModel, + bearingCategory, + plant, + productApplicationFieldOrIndustry, + productApplicationPart, + productType); + if(productValue.length() > 256) + { + return JsonResult.error("产品属性值超长"); + } + productList.add(productValue); + } + } + } + com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct valueVecStruct = + new com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct(); + valueVecStruct.stringVec = productList.toArray(new String[productList.size()]); + revObjectPropMap.put("rb3_aryProductInfo", valueVecStruct); + + // String user_id = + // user_id = user_id.substring(1,user_id.length()-1); + // user_id = user_id.split(",")[0]; + + // 任务说明拼接 云派+任务名称+客户名+项目名称+项目编号+项目等级+产品型号+设计类型+设计人+样品交期 fnd0Instructions + String taskInstruction = + "云派" + + ((task_name != null && task_name != "") ? "+" + task_name : "任务名称") + + ((project_Projectname != null && project_Projectname != "") + ? "+" + project_Projectname + : "项目名称"); + System.out.println(taskInstruction); + if (taskInstruction.length() > 128) { + taskInstruction = taskInstruction.substring(0,124) + "..."; + //Utils.setLog(logFileName, "oaCreateWorkFlow", "流程名称过长"); + //return JsonResult.error("流程名称过长"); + } + // 获取附件 + List fileList = new ArrayList(); + try { + + // MultiValueMap fileMap = ((StandardMultipartHttpServletRequest) + // request).getMultiFileMap(); + // + // System.out.println("fileMap.size();:"+fileMap.size()); + // Collection files = fileMap.values(); + // for(MultipartFile file :files){ + // String fileName = file.getName(); + // System.out.println("fileName:"+fileName); + // } + for (String key : fileMap.keySet()) { + String fileName = fileMap.get(key); + String fileUrl = key; + byte[] buffer = Utils.getFile(fileUrl); + Date date = new Date(); + String filePath = + System.getProperty("java.io.tmpdir") + dateFormat.format(date) + "\\"; + File file = new File(filePath); + if (!file.exists()) { + file.mkdir(); + } + File targetFile = new File(filePath + fileName); + System.out.println("==================AddPath:" + filePath + fileName); + OutputStream outStream = new FileOutputStream(targetFile); + outStream.write(buffer); + outStream.close(); + fileList.add(targetFile); + } + // if (jsonObject.containsKey("fileList")) { + // // 获取文件 + // JSONArray fileArray = jsonObject.getJSONArray("fileList"); + // if (fileArray != null && fileArray.size() > 0) { + // List files = fileArray.toJavaList(JSONObject.class); + // for (JSONObject file : files) { + // String fileName = file.get("fileName").toString(); + // String fileUrl = file.get("fileUrl").toString(); + // byte[] buffer = Utils.getFile(fileUrl); + // + // File targetFile = new File("C://temp//" + fileName); + // System.out.println("==================AddPath:C://temp//" + fileName); + // OutputStream outStream = new FileOutputStream(targetFile); + // outStream.write(buffer); + // outStream.close(); + // fileList.add(targetFile); + // } + // } + // } + // jsonObject.getString("fileList"); + // Collection parts = request.getParts(); + // for (Part part1 : parts) { + // String fileName = part1.getSubmittedFileName(); + // if (fileName != null) { + // InputStream initialStream = part1.getInputStream(); + // byte[] buffer = new byte[initialStream.available()]; + // initialStream.read(buffer); + // + // File targetFile = new File("C://temp//" + fileName); + // System.out.println("==================AddPath:C://temp//" + fileName); + // OutputStream outStream = new FileOutputStream(targetFile); + // outStream.write(buffer); + // outStream.close(); + // fileList.add(targetFile); + // } + // } + } catch (Exception e) { + Utils.setLog(logFileName, "oaCreateWorkFlow", "获取文件出错" + e.getMessage()); + return JsonResult.error("获取文件出错" + e.getMessage()); + } + // catch (ServletException e) { + // e.printStackTrace(); + // } + System.out.println("fileList.size():" + fileList.size()); + System.out.println("=========================================="); + System.out.println("task_uid:" + task_Uid); + // System.out.println("task_id:" + task_id); + System.out.println("task_name:" + task_name); + System.out.println("user_id:" + user_id); + System.out.println("project_uid:" + project_uid); + System.out.println("project_id:" + project_id); + // System.out.println("project_name:" + project_name); + System.out.println("task_CustomerNameBilingUnit:" + task_CustomerNameBilingUnit); + System.out.println("task_product:" + task_CustomerNameBilingUnit); + System.out.println("project_Projectname:" + project_Projectname); + System.out.println("project_ProjectCode:" + project_ProjectCode); + System.out.println("project_ProjectLevel:" + project_ProjectLevel); + // System.out.println("task_Dstype:" + task_Dstype); + // System.out.println("task_Dsigner:" + task_Dsigner); + // System.out.println("task_YPdata:" + task_YPdata); + System.out.println("=========================================="); + // System.out.println("userId:" + request.getParameter("userId")); + // System.out.println("projectUID:" + request.getParameter("projectUID")); + // System.out.println( + // "CustomerNameBillingUnit:" + request.getParameter("customerNameBillingUnit")); + // System.out.println("CustomerLevel:" + request.getParameter("customerLevel")); + // System.out.println("objectName:" + request.getParameter("objectName")); + // System.out.println("ProjectCode:" + request.getParameter("projectCode")); + // System.out.println("type:" + request.getParameter("type")); + // System.out.println("ProjectLevel:" + request.getParameter("projectLevel")); + // System.out.println("objectDesc:" + request.getParameter("objectDesc")); + // System.out.println("fields:" + request.getParameter("fields")); + // System.out.println("PartWhereUse:" + request.getParameter("partWhereUse")); + // System.out.println("ComponentVehicle:" + request.getParameter("componentVehicle")); + // System.out.println("product:" + request.getParameter("product")); + // String + + try { + if (tcSession == null) { + tcSession = new AppXSession(SpringbootJjwtApplication.TC_URL); + } + if (tcUser == null) { + tcUser = + tcSession.login(SpringbootJjwtApplication.TC_USER, SpringbootJjwtApplication.TC_PWD); + } + } catch (Exception ex) { + Utils.setLog(logFileName, "oaCreateWorkFlow", "TC服务器出错" + ex.getMessage()); + ex.printStackTrace(); + return JsonResult.error("TC服务器登录出错" + ex.getMessage()); + } + try { + JsonResult jsonResult = + TcsoaService.osCreateWorkFlow( + task_Uid, + task_name, + user_id, + taskInstruction, + fileList, + project_uid, + itemObjectPropMap, + revObjectPropMap, + revMasterObjectPropMap, + logFileName); + Utils.setLog(logFileName, "oaCreateWorkFlow", "任务包返回信息:" + jsonResult.toString()); + return jsonResult; + } catch (Exception e) { + Utils.setLog(logFileName, "oaCreateWorkFlow", "TC服务器出错" + e.getMessage()); + e.printStackTrace(); + return JsonResult.error("TC服务器出错" + e.getMessage()); + } + } + + protected boolean ServiceDataError(final ServiceData data) { + if (data.sizeOfPartialErrors() > 0) { + for (int i = 0; i < data.sizeOfPartialErrors(); i++) { + for (String msg : data.getPartialError(i).getMessages()) System.out.println(msg); + } + + return true; + } + + return false; + } + + // @UserLoginToken + @PostMapping(value = "/oaGetDeliveryInfo") + public Object getDeliveryInfo(@RequestBody List itemIdList) { + //String deliveryId = request.getParameter("deliveryId"); + if (tcSession == null) { + tcSession = new AppXSession(SpringbootJjwtApplication.TC_URL); + } + try { + if (tcUser == null) { + tcUser = + tcSession.login(SpringbootJjwtApplication.TC_USER, SpringbootJjwtApplication.TC_PWD); + } + + } catch (Exception ex) { + ex.printStackTrace(); + } + + Object object = TcsoaService.osGetDeliveryInfo(itemIdList); + return object; + } + // @UserLoginToken + @PostMapping(value = "/oaGetHistoryDelivery") + public Object getHistoryDelivery(HttpServletRequest request) { + String deliveryId = request.getParameter("deliveryId"); + if (tcSession == null) { + tcSession = new AppXSession(SpringbootJjwtApplication.TC_URL); + } + try { + if (tcUser == null) { + tcUser = + tcSession.login(SpringbootJjwtApplication.TC_USER, SpringbootJjwtApplication.TC_PWD); + } + + } catch (Exception ex) { + ex.printStackTrace(); + } + + Object Object = TcsoaService.oaGetHistoryDelivery(deliveryId); + return Object; + } + // @UserLoginToken + @GetMapping(value = "/oaGetDeliveryFile") + public void getGetDeliveryFile(HttpServletRequest request, HttpServletResponse response) { + String deliveryId = request.getParameter("deliveryId"); + String deliberyRevision = request.getParameter("deliberyRevision"); + + System.out.println("oaGetDeliveryFile" + deliveryId); + + if (tcSession == null) { + tcSession = new AppXSession(SpringbootJjwtApplication.TC_URL); + } + try { + if (tcUser == null) { + tcUser = + tcSession.login(SpringbootJjwtApplication.TC_USER, SpringbootJjwtApplication.TC_PWD); + } + + } catch (Exception ex) { + ex.printStackTrace(); + } + File file = TcsoaService.getGetDeliveryFile(deliveryId, deliberyRevision); + // 1.获取要下载的文件的绝对路径 + if (file == null) { + response.setStatus(400); + return; + } + String realPath = file.getAbsolutePath(); + // 2.获取要下载的文件名 + String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1); + // 3.设置content-disposition响应头控制浏览器以下载的形式打开文件 + // try { + try { + fileName = URLEncoder.encode(fileName, "UTF-8"); + response.setHeader( + "content-disposition", "attachment;filename=" + fileName.replaceAll("\\+", "%20")); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + // } catch (UnsupportedEncodingException e) { + // e.printStackTrace(); + // } + // 4.获取要下载的文件输入流 + InputStream in = null; + try { + in = new FileInputStream(realPath); + int len = 0; + // 5.创建数据缓冲区 + byte[] buffer = new byte[1024]; + // 6.通过response对象获取OutputStream流 + OutputStream out = response.getOutputStream(); + // 7.将FileInputStream流写入到buffer缓冲区 + while ((len = in.read(buffer)) > 0) { + // 8.使用OutputStream将缓冲区的数据输出到客户端浏览器 + out.write(buffer, 0, len); + } + in.close(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @PostMapping(value = "/oaCreateOrUpdateProject") + // public Object createOrUpdateProject(@RequestBody ProjectData data) { + public Object createOrUpdateProject(@RequestBody JSONObject jsonObject) { + // String json = + // "{\"productMaterialNumber\":\"1231\",\"productApplicationFieldOrIndustry\":\"A11底盘系统\",\"sampleType\":\"8888\",\"bearingCategory\":\"调心球轴承\",\"customerPoductCode\":\"15155\",\"cUproductModel\":\"DAC2F90F3543\",\"plant\":\"杭州人本-轨道交通\",\"objectName\":\"DAC2F90F3543\",\"productApplicationPart\":\"22200\",\"cycleStatus\":\"6226ce3ae4b09a8828b1cda9\",\"customerProjectName\":\"158494894\",\"productType\":\"全新新产品\",\"objectDesc\":\"55555\"},{\"productMaterialNumber\":\"22\",\"productApplicationFieldOrIndustry\":\"A45航空\",\"sampleType\":\"222\",\"bearingCategory\":\"调心球轴承\",\"customerPoductCode\":\"55\",\"cUproductModel\":\"122\",\"plant\":\"黄石人本-轨道交通\",\"objectName\":\"45\",\"productApplicationPart\":\"4541\",\"cycleStatus\":\"6226ce3ae4b09a8828b1cda9\",\"customerProjectName\":\"1532\",\"productType\":\"全新新产品\",\"objectDesc\":\"123\"},{\"productMaterialNumber\":\"22\",\"productApplicationFieldOrIndustry\":\"A45航空\",\"sampleType\":\"222\",\"bearingCategory\":\"调心球轴承\",\"customerPoductCode\":\"55\",\"cUproductModel\":\"122\",\"plant\":\"黄石人本-轨道交通\",\"objectName\":\"45\",\"productApplicationPart\":\"4541\",\"cycleStatus\":\"6226ce3ae4b09a8828b1cda9\",\"customerProjectName\":\"1532\",\"productType\":\"全新新产品\",\"objectDesc\":\"123\"}"; + String logFileName = dateFormatLog.format(new Date()); + // 添加日志记录传递的参数及报错信息 + Utils.setLog(logFileName, "oaCreateOrUpdateProject", jsonObject.toString()); + HashMap + itemObjectPropMap = + new HashMap< + String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>(); + HashMap + revObjectPropMap = + new HashMap< + String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>(); + HashMap + revMasterObjectPropMap = + new HashMap< + String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>(); + Map fileMap = new HashMap(); + Map propertyMap = new HashMap(); + + Utils.getData( + jsonObject.toString(), + itemObjectPropMap, + revObjectPropMap, + revMasterObjectPropMap, + fileMap, + propertyMap, + logFileName); + + if (tcSession == null) { + tcSession = new AppXSession(SpringbootJjwtApplication.TC_URL); + } + try { + if (tcUser == null) { + tcUser = + tcSession.login(SpringbootJjwtApplication.TC_USER, SpringbootJjwtApplication.TC_PWD); + } + + } catch (Exception ex) { + Utils.setLog(logFileName, "oaCreateOrUpdateProject", "TC服务器登录出错" + ex.getMessage()); + ex.printStackTrace(); + } + + // 获取必须的属性 + String userId = propertyMap.containsKey("designTeam") ? propertyMap.get("designTeam").toString() : "admin"; + String objectName = + propertyMap.containsKey("objectName") ? propertyMap.get("objectName").toString() : ""; + String projectUID = + propertyMap.containsKey("projectUID") ? propertyMap.get("projectUID").toString() : ""; + + System.out.println("userId:" + userId); + System.out.println("objectName:" + objectName); + System.out.println("projectUID:" + projectUID); + + ProjectData data = new ProjectData(); + data.setUserId(userId); + data.setProjectUID(projectUID); + // data.setCustomerNameBillingUnit(request.getParameter("customerNameBillingUnit")); + // data.setCustomerLevel(request.getParameter("customerLevel")); + data.setObjectName(objectName); + // data.setProjectCode(request.getParameter("projectCode")); + // data.setType(request.getParameter("type")); + // data.setProjectLevel(request.getParameter("projectLevel")); + // data.setObjectDesc(request.getParameter("objectDesc")); + // data.setFields(request.getParameter("fields")); + // data.setPartWhereUse(request.getParameter("partWhereUse")); + // data.setComponentVehicle(request.getParameter("componentVehicle")); + // data.setUid(request.getParameter("uid")); + // System.out.println("userId:" + request.getParameter("userId")); + // System.out.println("projectUID:" + request.getParameter("projectUID")); + // System.out.println( + // "CustomerNameBillingUnit:" + request.getParameter("customerNameBillingUnit")); + // System.out.println("CustomerLevel:" + request.getParameter("customerLevel")); + // System.out.println("objectName:" + request.getParameter("objectName")); + // System.out.println("ProjectCode:" + request.getParameter("projectCode")); + // System.out.println("type:" + request.getParameter("type")); + // System.out.println("ProjectLevel:" + request.getParameter("projectLevel")); + // System.out.println("objectDesc:" + request.getParameter("objectDesc")); + // System.out.println("fields:" + request.getParameter("fields")); + // System.out.println("PartWhereUse:" + request.getParameter("partWhereUse")); + // System.out.println("ComponentVehicle:" + request.getParameter("componentVehicle")); + // System.out.println("product:" + request.getParameter("product")); + // System.out.println("uid:" + request.getParameter("uid")); + try { + String productJson = + propertyMap.containsKey("product") ? propertyMap.get("product").toString() : null; + if (productJson != null) { + List productList = new ArrayList(); + JSONArray jsonArray = JSONArray.parseArray(productJson); + for (Object o : jsonArray) { + if (o instanceof JSONObject) { + JSONObject productJsonObject = JSONObject.parseObject(o.toString()); + if (productJsonObject.containsKey("bearingCategory") + && productJsonObject.containsKey("plant")) { + Product product = new Product(); + product.setBearingCategory(productJsonObject.getString("bearingCategory")); + product.setPlant(productJsonObject.getString("plant")); + productList.add(product); + } + } + } + // List subStringList = new ArrayList(); + // while (productJson.lastIndexOf("}") != productJson.indexOf("}")) { + // subStringList.add(productJson.substring(0, productJson.indexOf("}") + 1)); + // productJson = productJson.substring(productJson.indexOf("}") + 2, + // productJson.length()); + // System.out.println(); + // } + // subStringList.add(productJson); + // List productList = new ArrayList(); + // for (String json : subStringList) { + // System.out.println("productJson:" + json); + // Product product = JSONObject.parseObject(json, Product.class); + // productList.add(product); + // } + data.setProduct(productList); + } + String projectPUID = + TcsoaService.createOrUpdataProject( + data, itemObjectPropMap, revObjectPropMap, revMasterObjectPropMap, logFileName); + Utils.setLog(logFileName, "oaCreateOrUpdateProject", "项目UID:" + projectPUID); + System.out.println("projectUID:" + projectPUID); + JSONObject resultJSONObject = new JSONObject(); + resultJSONObject.put("Status", true); + resultJSONObject.put("ErrorMessage", ""); + resultJSONObject.put("projectUID", projectPUID); + return resultJSONObject; + } catch (Exception ex) { + Utils.setLog(logFileName, "oaCreateOrUpdateProject", "TC服务器出错" + ex.getMessage()); + JSONObject resultJSONObject = new JSONObject(); + resultJSONObject.put("Status", false); + resultJSONObject.put("ErrorMessage", "TC服务器出错" + ex.getMessage()); + resultJSONObject.put("projectUID", ""); + ex.printStackTrace(); + return resultJSONObject; + } + } + + @PostMapping(value = "/getItemProperty") + public JsonResult getItemProperty(@RequestBody List itemIdList) { + String logFileName = dateFormatLog.format(new Date()); + try { + if (tcSession == null) { + tcSession = new AppXSession(SpringbootJjwtApplication.TC_URL); + } + if (tcUser == null) { + tcUser = + tcSession.login(SpringbootJjwtApplication.TC_USER, SpringbootJjwtApplication.TC_PWD); + } + } catch (Exception ex) { + Utils.setLog(logFileName, "getItemProperty", "TC服务器出错" + ex.getMessage()); + ex.printStackTrace(); + return JsonResult.error("TC服务器登录出错" + ex.getMessage()); + } + + JsonResult jsonResult = TcsoaService.getItemPropertys(logFileName,itemIdList); + Utils.setLog(logFileName, "getItemPropertys", "jsonResult:"+jsonResult.toString()); + return jsonResult; + } + + + @GetMapping(value = "/getProjectItemProperty") + public JsonResult getProjectItemProperty(@RequestParam("uid") String uid) { + String logFileName = dateFormatLog.format(new Date()); + try { + if (tcSession == null) { + tcSession = new AppXSession(SpringbootJjwtApplication.TC_URL); + } + if (tcUser == null) { + tcUser = + tcSession.login(SpringbootJjwtApplication.TC_USER, SpringbootJjwtApplication.TC_PWD); + } + } catch (Exception ex) { + Utils.setLog(logFileName, "getProjectItemProperty", "TC服务器出错" + ex.getMessage()); + ex.printStackTrace(); + return JsonResult.error("TC服务器登录出错" + ex.getMessage()); + } + JsonResult jsonResult = TcsoaService.getProjectItemPropertys(logFileName,uid); + Utils.setLog(logFileName, "getProjectItemProperty", "jsonResult:"+jsonResult.toString()); + return jsonResult; + } +} diff --git a/src/main/java/com/pjb/springbootjjwt/api/UserApi.java b/src/main/java/com/pjb/springbootjjwt/api/UserApi.java new file mode 100644 index 0000000..0ba0d46 --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/api/UserApi.java @@ -0,0 +1,57 @@ +package com.pjb.springbootjjwt.api; + +import ch.qos.logback.core.net.SyslogOutputStream; +import com.alibaba.fastjson.JSONObject; +import com.pjb.springbootjjwt.annotation.UserLoginToken; +import com.pjb.springbootjjwt.entity.User; +import com.pjb.springbootjjwt.service.TokenService; +import com.pjb.springbootjjwt.service.UserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import javax.servlet.http.HttpServletRequest; + + +@RestController +//@RequestMapping("api") +public class UserApi { + @Autowired + UserService userService; + @Autowired + TokenService tokenService; + //登录 + @GetMapping("/getToken") + public Object login(HttpServletRequest request){ + String username = request.getParameter("username"); + String password = request.getParameter("password"); + String app_secret = request.getParameter("app_secret"); + System.out.println("username=>"+username); + JSONObject jsonObject=new JSONObject(); + User userForBase=userService.findByUsername(username); + + if(userForBase==null){ + jsonObject.put("message","登录失败,用户不存在"); + jsonObject.put("success", "1"); + return jsonObject; + }else { + System.out.println("userForBase=>"+userForBase.toString()); + if (!userForBase.getPassword().equals(password)){ + jsonObject.put("message","登录失败,密码错误"); + jsonObject.put("success", "1"); + return jsonObject; + } + if (!userForBase.getApp_secret().equals(app_secret)){ + jsonObject.put("message","登录失败,secret验证错误"); + jsonObject.put("success", "1"); + return jsonObject; + } + String token = tokenService.getToken(userForBase); + jsonObject.put("token", token); + jsonObject.put("message","获取token成功"); + jsonObject.put("success", "0"); + return jsonObject; + + } + } + + +} diff --git a/src/main/java/com/pjb/springbootjjwt/config/InterceptorConfig.java b/src/main/java/com/pjb/springbootjjwt/config/InterceptorConfig.java new file mode 100644 index 0000000..be0839e --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/config/InterceptorConfig.java @@ -0,0 +1,23 @@ +package com.pjb.springbootjjwt.config; + +import com.pjb.springbootjjwt.interceptor.AuthenticationInterceptor; +import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + + +@Configuration +public class InterceptorConfig implements WebMvcConfigurer { + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(authenticationInterceptor()) + .addPathPatterns("/**"); // 拦截所有请求,通过判断是否有 @LoginRequired 注解 决定是否需要登录 + } + @Bean + public AuthenticationInterceptor authenticationInterceptor() { + return new AuthenticationInterceptor(); + } +} diff --git a/src/main/java/com/pjb/springbootjjwt/config/SwaggerConfig.java b/src/main/java/com/pjb/springbootjjwt/config/SwaggerConfig.java new file mode 100644 index 0000000..be5dff6 --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/config/SwaggerConfig.java @@ -0,0 +1,10 @@ +package com.pjb.springbootjjwt.config; + +import org.springframework.context.annotation.Configuration; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@Configuration //说明这是一个配置类 +@EnableSwagger2// 该注解开启Swagger2的自动配置 +public class SwaggerConfig { + +} diff --git a/src/main/java/com/pjb/springbootjjwt/entity/IgtcoaFile.java b/src/main/java/com/pjb/springbootjjwt/entity/IgtcoaFile.java new file mode 100644 index 0000000..f100283 --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/entity/IgtcoaFile.java @@ -0,0 +1,15 @@ +package com.pjb.springbootjjwt.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class IgtcoaFile { + String fileId ; + String fileName ; + String fileType ; + String url ; +} diff --git a/src/main/java/com/pjb/springbootjjwt/entity/IgtcoaFileProcess.java b/src/main/java/com/pjb/springbootjjwt/entity/IgtcoaFileProcess.java new file mode 100644 index 0000000..770c51f --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/entity/IgtcoaFileProcess.java @@ -0,0 +1,17 @@ +package com.pjb.springbootjjwt.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class IgtcoaFileProcess { + String process_uid ; + String process_type ; + String process_name ; + List files ; +} diff --git a/src/main/java/com/pjb/springbootjjwt/entity/IgtcoaProcess.java b/src/main/java/com/pjb/springbootjjwt/entity/IgtcoaProcess.java new file mode 100644 index 0000000..1ec35da --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/entity/IgtcoaProcess.java @@ -0,0 +1,18 @@ +package com.pjb.springbootjjwt.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class IgtcoaProcess { + + String id ; + String project_name ; + String workflow_name ; + String workcode ; + String privary ; + String created_time ; +} diff --git a/src/main/java/com/pjb/springbootjjwt/entity/IgtcoaProcessQuery.java b/src/main/java/com/pjb/springbootjjwt/entity/IgtcoaProcessQuery.java new file mode 100644 index 0000000..4109e20 --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/entity/IgtcoaProcessQuery.java @@ -0,0 +1,18 @@ +package com.pjb.springbootjjwt.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class IgtcoaProcessQuery { + String werks ; + String workcode ; + String workflow_type ; + String privary ; + String title ; + String start_time ; + String end_time ; +} diff --git a/src/main/java/com/pjb/springbootjjwt/entity/IgtcoaResultFile.java b/src/main/java/com/pjb/springbootjjwt/entity/IgtcoaResultFile.java new file mode 100644 index 0000000..5bbd9df --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/entity/IgtcoaResultFile.java @@ -0,0 +1,14 @@ +package com.pjb.springbootjjwt.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class IgtcoaResultFile { + boolean success; + String message; + IgtcoaFileProcess result; +} diff --git a/src/main/java/com/pjb/springbootjjwt/entity/IgtcoaResultProcess.java b/src/main/java/com/pjb/springbootjjwt/entity/IgtcoaResultProcess.java new file mode 100644 index 0000000..f311c3d --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/entity/IgtcoaResultProcess.java @@ -0,0 +1,16 @@ +package com.pjb.springbootjjwt.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class IgtcoaResultProcess { + boolean success; + String message; + List result; +} diff --git a/src/main/java/com/pjb/springbootjjwt/entity/IgtcoaSignContent.java b/src/main/java/com/pjb/springbootjjwt/entity/IgtcoaSignContent.java new file mode 100644 index 0000000..e43a394 --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/entity/IgtcoaSignContent.java @@ -0,0 +1,13 @@ +package com.pjb.springbootjjwt.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class IgtcoaSignContent { + String name ; + String time ; +} diff --git a/src/main/java/com/pjb/springbootjjwt/entity/IgtcoaSignInfo.java b/src/main/java/com/pjb/springbootjjwt/entity/IgtcoaSignInfo.java new file mode 100644 index 0000000..5c12349 --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/entity/IgtcoaSignInfo.java @@ -0,0 +1,18 @@ +package com.pjb.springbootjjwt.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +/** + * @author 86177 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +public class IgtcoaSignInfo { + String file_id ; + List content ; +} diff --git a/src/main/java/com/pjb/springbootjjwt/entity/IgtcoaSignWorkflow.java b/src/main/java/com/pjb/springbootjjwt/entity/IgtcoaSignWorkflow.java new file mode 100644 index 0000000..1a0ec3e --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/entity/IgtcoaSignWorkflow.java @@ -0,0 +1,18 @@ +package com.pjb.springbootjjwt.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class IgtcoaSignWorkflow { + String workflow_id ; + boolean approval_results ; + String approval_type ; + List attached_files ; + List sign_info ; +} diff --git a/src/main/java/com/pjb/springbootjjwt/entity/JsonResult.java b/src/main/java/com/pjb/springbootjjwt/entity/JsonResult.java new file mode 100644 index 0000000..223e9f5 --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/entity/JsonResult.java @@ -0,0 +1,72 @@ +package com.pjb.springbootjjwt.entity; + +import lombok.Data; + +import java.io.Serializable; + +@Data +public class JsonResult implements Serializable { + private static final long serialVersionUID = -8191886883629303111L; + /** + * 接口是否完成操作 + */ + private boolean success = true; + /** + * 接口处理的消息 + */ + private String msg; + /** + * 状态码 + */ + private Integer code; + /** + * 返回的对象 + */ + private Object data; + + public JsonResult() {} + + public JsonResult(String msg) { + this.msg = msg; + } + + public JsonResult(String msg, Integer code) { + this.msg = msg; + this.code = code; + } + + public static JsonResult success() { + return new JsonResult(); + } + + public static JsonResult success(Object data) { + JsonResult jr = new JsonResult(); + jr.setData(data); + return jr; + } + + public static JsonResult success(String msg, Object data) { + JsonResult jr = new JsonResult(); + jr.setMsg(msg); + jr.setData(data); + return jr; + } + + public static JsonResult error() { + JsonResult jr = new JsonResult(); + jr.setSuccess(false); + return jr; + } + + public static JsonResult error(String msg) { + JsonResult jr = new JsonResult(msg); + jr.setSuccess(false); + return jr; + } + + public static JsonResult error(String msg, Integer code) { + JsonResult jr = new JsonResult(msg, code); + jr.setSuccess(false); + return jr; + } +} diff --git a/src/main/java/com/pjb/springbootjjwt/entity/OwningGroup.java b/src/main/java/com/pjb/springbootjjwt/entity/OwningGroup.java new file mode 100644 index 0000000..8ab7326 --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/entity/OwningGroup.java @@ -0,0 +1,10 @@ +package com.pjb.springbootjjwt.entity; + +import lombok.Data; + +@Data +public class OwningGroup { + String uid; + String name; + String type; +} diff --git a/src/main/java/com/pjb/springbootjjwt/entity/Product.java b/src/main/java/com/pjb/springbootjjwt/entity/Product.java new file mode 100644 index 0000000..39fd3dc --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/entity/Product.java @@ -0,0 +1,22 @@ +package com.pjb.springbootjjwt.entity; + +import lombok.Data; + +@Data +public class Product { + String bearingCategory; + String plant; + String objectName; + String objectDesc; + String cycleStatus; + String customerPoductCode; + String customerProjectName; + String productApplicationFieldOrIndustry; + String productApplicationPart; + String cUproductModel; + String productType; + String productMaterialNumber; + String sampleType; + + +} diff --git a/src/main/java/com/pjb/springbootjjwt/entity/ProjectData.java b/src/main/java/com/pjb/springbootjjwt/entity/ProjectData.java new file mode 100644 index 0000000..e5b8746 --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/entity/ProjectData.java @@ -0,0 +1,42 @@ +package com.pjb.springbootjjwt.entity; + + + +import lombok.Data; + +import java.util.List; +@Data +public class ProjectData { + String userId; + String uid; + String projectUID; + String customerNameBillingUnit; + String customerLevel; + String objectName; + String ProjectCode; + String type; + String projectLevel; + String objectDesc; + String fields; + String partWhereUse; + String componentVehicle; + OwningGroup owningGroup; + String planStartTime; + String planEndTime; + String actualStartTime; + String actualEndTime; + String cycleStatus; + String CustomerSystem; + String invoicingCustomerCode; + String nameofEndSupplyCustomer; + String developmentProcess; + String pointsWeighting; + String industries; + String projectMassProductionTime; + String salesHeadOffice; + String projectPhase; + String salesTeam; + List product; + + +} diff --git a/src/main/java/com/pjb/springbootjjwt/entity/User.java b/src/main/java/com/pjb/springbootjjwt/entity/User.java new file mode 100644 index 0000000..a265963 --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/entity/User.java @@ -0,0 +1,15 @@ +package com.pjb.springbootjjwt.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class User { + String app_secret; + String username; + String password; +} diff --git a/src/main/java/com/pjb/springbootjjwt/interceptor/AuthenticationInterceptor.java b/src/main/java/com/pjb/springbootjjwt/interceptor/AuthenticationInterceptor.java new file mode 100644 index 0000000..5d0d455 --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/interceptor/AuthenticationInterceptor.java @@ -0,0 +1,84 @@ +package com.pjb.springbootjjwt.interceptor; + +import com.auth0.jwt.JWT; +import com.auth0.jwt.JWTVerifier; +import com.auth0.jwt.algorithms.Algorithm; +import com.auth0.jwt.exceptions.JWTDecodeException; +import com.auth0.jwt.exceptions.JWTVerificationException; +import com.pjb.springbootjjwt.annotation.PassToken; +import com.pjb.springbootjjwt.annotation.UserLoginToken; +import com.pjb.springbootjjwt.entity.User; +import com.pjb.springbootjjwt.service.UserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.method.HandlerMethod; + +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.ModelAndView; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.lang.reflect.Method; + + + +public class AuthenticationInterceptor implements HandlerInterceptor { + @Autowired + UserService userService; + @Override + public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception { + String token = httpServletRequest.getHeader("access_token");// 从 http 请求头中取出 token + // 如果不是映射到方法直接通过 + if(!(object instanceof HandlerMethod)){ + return true; + } + HandlerMethod handlerMethod=(HandlerMethod)object; + Method method=handlerMethod.getMethod(); + //检查是否有passtoken注释,有则跳过认证 + if (method.isAnnotationPresent(PassToken.class)) { + PassToken passToken = method.getAnnotation(PassToken.class); + if (passToken.required()) { + return true; + } + } + //检查有没有需要用户权限的注解 + if (method.isAnnotationPresent(UserLoginToken.class)) { + UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class); + if (userLoginToken.required()) { + // 执行认证 + if (token == null) { + throw new RuntimeException("无token,请重新登录"); + } + // 获取 token 中的 user id + String userId; + try { + userId = JWT.decode(token).getAudience().get(0); + } catch (JWTDecodeException j) { + throw new RuntimeException("token验证失败"); + } + User user = userService.findUserById(userId); + if (user == null) { + throw new RuntimeException("用户不存在,请重新登录"); + } + // 验证 token + JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build(); + try { + jwtVerifier.verify(token); + } catch (JWTVerificationException e) { + throw new RuntimeException("token验证失败"); + } + return true; + } + } + return true; + } + + @Override + public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { + + } + @Override + public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { + + } +} diff --git a/src/main/java/com/pjb/springbootjjwt/interceptor/GloablExceptionHandler.java b/src/main/java/com/pjb/springbootjjwt/interceptor/GloablExceptionHandler.java new file mode 100644 index 0000000..0e04428 --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/interceptor/GloablExceptionHandler.java @@ -0,0 +1,21 @@ +package com.pjb.springbootjjwt.interceptor; + +import com.alibaba.fastjson.JSONObject; +import com.pjb.springbootjjwt.entity.JsonResult; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseBody; + + +@ControllerAdvice +public class GloablExceptionHandler { + @ResponseBody + @ExceptionHandler(Exception.class) + public JsonResult handleException(Exception e) { + String msg = e.getMessage(); + if (msg == null || msg.equals("")) { + msg = "TC服务器出错"; + } + return JsonResult.error(msg); + } +} diff --git a/src/main/java/com/pjb/springbootjjwt/mapper/IgtcoaMapper.java b/src/main/java/com/pjb/springbootjjwt/mapper/IgtcoaMapper.java new file mode 100644 index 0000000..194773c --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/mapper/IgtcoaMapper.java @@ -0,0 +1,24 @@ +package com.pjb.springbootjjwt.mapper; + +import com.pjb.springbootjjwt.entity.IgtcoaFile; +import com.pjb.springbootjjwt.entity.IgtcoaFileProcess; +import com.pjb.springbootjjwt.entity.IgtcoaProcess; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +public interface IgtcoaMapper { + List listAllProcess(@Param("status") String status,@Param("workcode") String workcode); + List listAllFile(@Param("processId") String processId); + IgtcoaFileProcess getFileProcess(@Param("processId") String processId); + void updateProcessApproval(@Param("processId") String processId, + @Param("approval") String approval); + void insertFileSigninfo(@Param("fileID") String fileID, + @Param("signName") String signName, + @Param("signDate") String signDate, + @Param("signNo") int signNo); + void deleteFileSigninfo(@Param("fileID") String fileID); + void insertOAFile(@Param("fileName") String fileName, + @Param("filePath") String filePath, + @Param("fileID") String fileID); +} diff --git a/src/main/java/com/pjb/springbootjjwt/mapper/UserMapper.java b/src/main/java/com/pjb/springbootjjwt/mapper/UserMapper.java new file mode 100644 index 0000000..10de14c --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/mapper/UserMapper.java @@ -0,0 +1,12 @@ +package com.pjb.springbootjjwt.mapper; + +import com.pjb.springbootjjwt.entity.User; +import org.apache.ibatis.annotations.Param; + + + +public interface UserMapper { + User findByUsername(@Param("username") String username); + User findByUsernameAndId(@Param("username") String username,@Param("app_secret") String Id); + User findUserById(@Param("app_secret") String Id); +} diff --git a/src/main/java/com/pjb/springbootjjwt/service/IgtcoaServer.java b/src/main/java/com/pjb/springbootjjwt/service/IgtcoaServer.java new file mode 100644 index 0000000..a1a6158 --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/service/IgtcoaServer.java @@ -0,0 +1,47 @@ +package com.pjb.springbootjjwt.service; + +import com.pjb.springbootjjwt.entity.*; +import com.pjb.springbootjjwt.mapper.IgtcoaMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + +@Service("IgoatcServer") +public class IgtcoaServer { + @Autowired + IgtcoaMapper igtcoaMapper; + public List listAllProcess(String workcode){ + List processList = igtcoaMapper.listAllProcess("0",workcode); + return processList; + } + + + public IgtcoaFileProcess getFileProcess(String processid){ + IgtcoaFileProcess fileProcess = igtcoaMapper.getFileProcess(processid); + if(fileProcess!=null){ + List fileList = igtcoaMapper.listAllFile(processid); + fileProcess.setFiles(fileList); + } + return fileProcess; + } + + public void setSignIfno(IgtcoaSignWorkflow signMsg){ + igtcoaMapper.updateProcessApproval(signMsg.getWorkflow_id(),""+signMsg.isApproval_results()); + for(IgtcoaSignInfo signinfo :signMsg.getSign_info()) { + List signcontentList = signinfo.getContent(); + igtcoaMapper.deleteFileSigninfo(signinfo.getFile_id()); + for(int i =0;i> lovMappingList = + new HashMap>(); + + public static File getTcfileByFileId2(String fileId) { + DataManagementService dmService = DataManagementService.getService(AppXSession.getConnection()); + File fileData = null; + ServiceData resultDate = dmService.loadObjects(new String[] {fileId}); + Dataset dataset = null; + ModelObject modelObject = null; + if (resultDate.sizeOfPlainObjects() > 0) { + modelObject = resultDate.getPlainObject(0); + if (modelObject instanceof Dataset) { + dataset = (Dataset) modelObject; + } + } + if (dataset == null) { + return null; + } + // fileData = TcsoaService.loadFileFromTc(dataset); + return fileData; + } + + public static String getDatasetFileName(String fileId) { + String fileOrgName = null; + DataManagementService dmService = DataManagementService.getService(AppXSession.getConnection()); + ServiceData resultDate = dmService.loadObjects(new String[] {fileId}); + Dataset dataset = null; + ModelObject modelObject = null; + if (resultDate.sizeOfPlainObjects() > 0) { + modelObject = resultDate.getPlainObject(0); + if (modelObject instanceof Dataset) { + dataset = (Dataset) modelObject; + } + } + if (dataset == null) { + return null; + } + fileOrgName = getDatasetFileName(dataset); + return fileOrgName; + } + + public static List getTcfileByFileId(String[] fileId, String item_id, String revision) { + List files = new ArrayList(); + DataManagementService dmService = DataManagementService.getService(AppXSession.getConnection()); + byte[] fileData = null; + ServiceData resultDate = dmService.loadObjects(fileId); + Dataset dataset = null; + ModelObject modelObject = null; + if (resultDate.sizeOfPlainObjects() > 0) { + for (int i = 0; i < resultDate.sizeOfPlainObjects(); i++) { + modelObject = resultDate.getPlainObject(i); + if (modelObject instanceof Dataset) { + dataset = (Dataset) modelObject; + } + if (dataset == null) { + return null; + } + File tcFile = TcsoaService.loadFileFromTc(dataset, item_id, revision); + if (tcFile != null) { + files.add(tcFile); + } + } + } + return files; + } + + public static List getTcfileByFileId(String[] fileId) { + List files = new ArrayList(); + DataManagementService dmService = DataManagementService.getService(AppXSession.getConnection()); + byte[] fileData = null; + ServiceData resultDate = dmService.loadObjects(fileId); + Dataset dataset = null; + ModelObject modelObject = null; + if (resultDate.sizeOfPlainObjects() > 0) { + for (int i = 0; i < resultDate.sizeOfPlainObjects(); i++) { + modelObject = resultDate.getPlainObject(i); + if (modelObject instanceof Dataset) { + dataset = (Dataset) modelObject; + } + if (dataset == null) { + return null; + } + File tcFile = TcsoaService.loadFileFromTc(dataset); + if (tcFile != null) { + files.add(tcFile); + } + } + } + return files; + } + + private static String getDatasetFileName(Dataset dataset) { + String orgName = null; + try { + DataManagementService dmService = + DataManagementService.getService(AppXSession.getConnection()); + + ModelObject[] objects = {dataset}; + dmService.refreshObjects(objects); + dmService.getProperties(objects, new String[] {"ref_list"}); + ModelObject[] dsfilevec = dataset.get_ref_list(); + ImanFile dsfile = (ImanFile) dsfilevec[0]; + + ModelObject[] objects1 = {dsfile}; + String[] attributes1 = {"relative_directory_path", "original_file_name"}; + dmService.refreshObjects(objects1); + dmService.getProperties(objects1, attributes1); + orgName = dsfile.get_original_file_name(); + } catch (Exception ex) { + ex.printStackTrace(); + } + + return orgName; + } + + /** + * 从TC下载数据集 + * + * @param dataset + * @return + */ + private static File loadFileFromTc(Dataset dataset, String item_id, String revision) { + if (dataset == null) { + return null; + } + File tcFile = null; + File outFile = null; + try { + DataManagementService dmService = + DataManagementService.getService(AppXSession.getConnection()); + FileManagementService fmService = + FileManagementService.getService(AppXSession.getConnection()); + Date date = new Date(); + String filePath = + System.getProperty("java.io.tmpdir") + dateFormat.format(date); + File file = new File(filePath); + if (!file.exists()) { + file.mkdir(); + } + FileManagementUtility fmu = + new FileManagementUtility( + AppXSession.getConnection(), + null, + new String[] {SpringbootJjwtApplication.TC_FMSURL}, + new String[] {SpringbootJjwtApplication.TC_FMSURL}, + filePath); + + ModelObject[] objects = {dataset}; + dmService.refreshObjects(objects); + dmService.getProperties(objects, new String[] {"ref_list"}); + objects = dataset.get_ref_list(); + String[] fileObject_string = new String[objects.length]; + for (int i = 0; i < objects.length; i++) { + dmService.getProperties(new ModelObject[] {objects[i]}, new String[] {"object_string"}); + Property property = objects[i].getPropertyObject("object_string"); + fileObject_string[i] = property.getStringValue(); + } + GetFileResponse getFileResponse = fmu.getFiles(objects); + File[] fileinfovec = getFileResponse.getFiles(); + tcFile = fileinfovec[0]; + + outFile = new File(tcFile.getParent() + File.separatorChar + fileObject_string[0]); + tcFile.renameTo(outFile); + System.out.println(); + + } catch (Exception ex) { + ex.printStackTrace(); + } + + return outFile; + } + + /** + * 从TC下载数据集 + * + * @param dataset + * @return + */ + private static File loadFileFromTc(Dataset dataset) { + if (dataset == null) { + return null; + } + File tcFile = null; + File outFile = null; + try { + DataManagementService dmService = + DataManagementService.getService(AppXSession.getConnection()); + FileManagementService fmService = + FileManagementService.getService(AppXSession.getConnection()); + FileManagementUtility fmu = + new FileManagementUtility( + AppXSession.getConnection(), + null, + new String[] {SpringbootJjwtApplication.TC_FMSURL}, + new String[] {SpringbootJjwtApplication.TC_FMSURL}, + SpringbootJjwtApplication.TC_FCCCACH); + + ModelObject[] objects = {dataset}; + dmService.refreshObjects(objects); + dmService.getProperties(objects, new String[] {"ref_list"}); + objects = dataset.get_ref_list(); + String[] fileObject_string = new String[objects.length]; + for (int i = 0; i < objects.length; i++) { + dmService.getProperties(new ModelObject[] {objects[i]}, new String[] {"object_string"}); + Property property = objects[i].getPropertyObject("object_string"); + fileObject_string[i] = property.getStringValue(); + } + GetFileResponse getFileResponse = fmu.getFiles(objects); + File[] fileinfovec = getFileResponse.getFiles(); + tcFile = fileinfovec[0]; + + outFile = new File(tcFile.getParent() + File.separatorChar + fileObject_string[0]); + tcFile.renameTo(outFile); + System.out.println(); + + } catch (Exception ex) { + ex.printStackTrace(); + } + + return outFile; + } + + /** + * 把文件转换为BYTE数组 + * + * @param file + * @return + */ + private static byte[] fileConvertToByteArray(File file) { + byte[] data = null; + + try { + FileInputStream fis = new FileInputStream(file); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + int len; + byte[] buffer = new byte[1024]; + while ((len = fis.read(buffer)) != -1) { + baos.write(buffer, 0, len); + } + + data = baos.toByteArray(); + + fis.close(); + baos.close(); + } catch (Exception e) { + e.printStackTrace(); + } + + return data; + } + + public static JsonResult osCreateWorkFlow( + String task_Uid, + String task_name, + String user_id, + String taskInstruction, + List fileList, + String project_uid, + HashMap + itemObjectPropMap, + HashMap + itemRevObjectPropMap, + HashMap + itemRevMasterObjectPropMap, + String logFileName) + throws Exception { + + JSONObject resultJSONObject = new JSONObject(); + // 创建临时交付物 + // Date date = new Date(); + // long longDate = date.getTime(); + // + ModelObject user = Utils.findUser(user_id); + if (user == null) { + return JsonResult.error("user_id:" + user_id + "不存在!"); + } + + Item item = Utils.SearchItem(task_Uid); + if (item != null) { + return JsonResult.success(resultJSONObject); + } + + DataManagementService dataManagementService = + DataManagementService.getService(AppXSession.getConnection()); + DataManagement.ItemProperties itemProperties = new DataManagement.ItemProperties(); + + itemProperties.itemId = task_Uid; + itemProperties.name = task_name; + itemProperties.type = TC_TASKPACKAGE; + + DataManagement.CreateItemsResponse itemsResponse = + dataManagementService.createItems( + new DataManagement.ItemProperties[] {itemProperties}, null, ""); + + ItemRevision itemRevision = itemsResponse.output[0].itemRev; + resultJSONObject.put("TaskPackageUID", itemRevision.get_items_tag().getUid()); + // 添加任务资料 + putRWZL(user, itemRevision, fileList); + + // 设置版本表单 + dataManagementService.getProperties( + new ModelObject[] {itemRevision}, new String[] {"IMAN_master_form_rev"}); + ModelObject[] itemRevision_master = itemRevision.get_IMAN_master_form_rev(); + + // com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct + // projectIdVecStruct = new + // com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct(); + // projectIdVecStruct.stringVec = new String[]{project_id}; + // com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct + // projectNameVecStruct = new + // com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct(); + // projectNameVecStruct.stringVec = new String[]{project_name}; + com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct taskIdVecStruct = + new com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct(); + taskIdVecStruct.stringVec = new String[] {task_Uid}; + // objectPropMap.put(TC_PAIPROJECTID, projectIdVecStruct); + // objectPropMap.put(TC_PAIPROJECTNAME, projectNameVecStruct); + itemRevMasterObjectPropMap.put("user_data_1", taskIdVecStruct); + + dataManagementService.setProperties( + new ModelObject[] {itemRevision.get_items_tag()}, itemObjectPropMap); + ServiceData sd = + dataManagementService.setProperties(new ModelObject[] {itemRevision}, itemRevObjectPropMap); + String messageValue = ""; + if (sd.sizeOfPartialErrors() > 0) { + for (int i = 0; i < sd.sizeOfPartialErrors(); i++) { + String[] messages = sd.getPartialError(i).getMessages(); + for (int j = 0; j < messages.length; j++) { + messageValue = messageValue + messages[j]; + } + } + } + System.out.println("messageValue:" + messageValue); + if (!messageValue.isEmpty()) { + Utils.setLog(logFileName, "oaCreateWorkFlow", "设置属性:" + messageValue); + } + dataManagementService.setProperties(itemRevision_master, itemRevMasterObjectPropMap); + + // 创建流程 + WorkflowService wfService = WorkflowService.getService(AppXSession.getConnection()); + + Workflow.ContextData contextData = new Workflow.ContextData(); + + String observerKey = ""; + // String name = project_name+"("+project_id+")-"+task_name+"("+task_id+")"; + String name = taskInstruction; + String subject = ""; + String description = ""; + contextData.processTemplate = TC_WORKFLOWTEMPLATE; + contextData.subscribeToEvents = false; + contextData.subscriptionEventCount = 0; + contextData.attachmentCount = 1; + contextData.attachments = new String[] {itemsResponse.output[0].itemRev.getUid()}; + contextData.attachmentTypes = new int[] {1}; + // 创建流程 + Workflow.InstanceInfo instanceInfo = + wfService.createInstance(true, observerKey, name, subject, description, contextData); + + ServiceData serviceData = instanceInfo.serviceData; + int sizeOfUpdatedObjects = serviceData.sizeOfUpdatedObjects(); + int sizeOfCreatedObjects = serviceData.sizeOfCreatedObjects(); + + ModelObject job = null; + EPMTask task = null; + EPMDoTask doTask = null; + + if (sizeOfCreatedObjects != 0) { + job = serviceData.getCreatedObject(0); + } + resultJSONObject.put("TaskWorkFlowUID", job.getUid()); + for (int i = 0; i < sizeOfUpdatedObjects; i++) { + ModelObject obj = serviceData.getUpdatedObject(i); + if (obj.getTypeObject().getName().equals("EPMTask")) { + task = (EPMTask) obj; + } + if (obj.getTypeObject().getName().equals("EPMDoTask")) { + doTask = (EPMDoTask) obj; + // 添加任务说明 + com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct + taskDescriptionVecStruct = + new com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct(); + taskDescriptionVecStruct.stringVec = new String[] {taskInstruction}; + System.out.println("==========taskInstruction==========:\n" + taskInstruction); + HashMap + doTaskPropMap = + new HashMap< + String, + com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>(); + + doTaskPropMap.put("fnd0Instructions", taskDescriptionVecStruct); + doTaskPropMap.put("object_desc", taskDescriptionVecStruct); + dataManagementService.setProperties(new ModelObject[] {doTask}, doTaskPropMap); + } + } + + if (user != null) { + // 重新指责任方 + wfService.performAction( + doTask, "SOA_EPM_assign_action", null, null, "SOA_EPM_completed", user); + // 更改所有权 + Utils.changeOwnershipModelObject( + user, + "", + new ModelObject[] { + itemsResponse.output[0].item, itemsResponse.output[0].itemRev, doTask, task, job + }); + // 将新增对象添加到newstuff文件夹 + dataManagementService.getProperties( + new ModelObject[] {user}, new String[] {"newstuff_folder"}); + Folder newstuff = (Folder) user.getPropertyObject("newstuff_folder").getModelObjectValue(); + + com.teamcenter.services.strong.core._2007_01.DataManagement.MoveToNewFolderInfo + moveToNewFolderInfo = + new com.teamcenter.services.strong.core._2007_01.DataManagement.MoveToNewFolderInfo(); + moveToNewFolderInfo.newFolder = newstuff; + moveToNewFolderInfo.objectsToMove = new ModelObject[] {itemsResponse.output[0].item}; + dataManagementService.moveToNewFolder( + new com.teamcenter.services.strong.core._2007_01.DataManagement.MoveToNewFolderInfo[] { + moveToNewFolderInfo + }); + // 关联到项目的云派任务关系文件夹 + // ModelObject[] xmkfOjects = + // Query.queryItems( + // "CUPM version", new String[] {"Description"}, new String[] {project_uid}); + + ModelObject[] xmkfOjects = loadObjects(new String[] {project_uid}, dataManagementService); + + if (xmkfOjects.length != 0) { + DataManagement.Relationship rwToXm_relationship = new DataManagement.Relationship(); + rwToXm_relationship.primaryObject = xmkfOjects[0]; + rwToXm_relationship.secondaryObject = itemsResponse.output[0].itemRev; + rwToXm_relationship.relationType = "RB3_RWGX"; + rwToXm_relationship.userData = null; + + DataManagement.Relationship xmToRw_relationship = new DataManagement.Relationship(); + xmToRw_relationship.primaryObject = itemsResponse.output[0].itemRev; + xmToRw_relationship.secondaryObject = xmkfOjects[0]; + xmToRw_relationship.relationType = "RB3_XMGX"; + xmToRw_relationship.userData = null; + DataManagement.CreateRelationsResponse createRelationsResponse = + dataManagementService.createRelations( + new DataManagement.Relationship[] {rwToXm_relationship, xmToRw_relationship}); + System.out.println(); + } + } else { + return JsonResult.error("user_id:" + user_id + "不存在"); + } + // 移除目标下的临时ItemRevision + // wfService.removeAttachments(task,new ModelObject[]{itemsResponse.output[0].itemRev}); + // 删除临时Item + // dataManagementService.deleteObjects(new ModelObject[]{itemsResponse.output[0].item}); + return JsonResult.success(resultJSONObject); + } + + private static void putRWZL(ModelObject user, ItemRevision itemRevision, List fileList) + throws Exception { + if (fileList.size() == 0) { + return; + } + // File zipFile = new File("C:\\temp\\任务资料.zip"); + // toZip(fileList, zipFile); + // 循环创建数据集对象 + for (File file : fileList) { + String fileName = file.getName(); + String ext = ""; + // 根据文档后缀名获取类型 + int ind = fileName.lastIndexOf("."); + if (ind >= 0) { + ext = fileName.substring(ind + 1); + } + if (Utils.getStrlength(fileName) > 128) { + fileName = Utils.subStrlength(fileName, 126 - ext.length()) + "." + ext; + // fileName = fileName.substring(0,126-ext.length()) + "." + ext; + } + System.out.println("文件名称:" + fileName); + String defaultFile_type = ""; // MSExcelX + String defaultNamedReferencedName = ""; // excel + String file_type = ""; // MSExcelX + String namedReferencedName = ""; // excel + // 获取首选项中配置的值 + String[] fileTypePropertys = Utils.GetPrefValues("ConnorPi_TaskAttachmentMap", true); + for (String property : fileTypePropertys) { + if (property.indexOf("=") > 0) { + if (property.split("=")[0].toUpperCase().compareTo("DEFAULT") == 0) { + String fileType = property.split("=")[1]; + if (fileType.indexOf(",") > 0) { + defaultFile_type = fileType.split(",")[0]; + defaultNamedReferencedName = fileType.split(",")[1]; + } + } + if (property.split("=")[0].toUpperCase().compareTo(ext.toUpperCase()) == 0) { + String fileType = property.split("=")[1]; + if (fileType.indexOf(",") > 0) { + file_type = fileType.split(",")[0]; + namedReferencedName = fileType.split(",")[1]; + } + } + } + } + if (file_type.isEmpty() && namedReferencedName.isEmpty()) { + file_type = defaultFile_type; + namedReferencedName = defaultNamedReferencedName; + } + + // 创建数据集 + DataManagementService dataManagementService = + DataManagementService.getService(AppXSession.getConnection()); + com.teamcenter.services.loose.core.FileManagementService fileManagementService = + com.teamcenter.services.loose.core.FileManagementService.getService( + AppXSession.getConnection()); + FileManagementUtility fileManagementUtility = + new FileManagementUtility(AppXSession.getConnection()); + com.teamcenter.services.strong.core._2008_06.DataManagement.DatasetProperties2 + datasetProperties2 = + new com.teamcenter.services.strong.core._2008_06.DataManagement.DatasetProperties2(); + datasetProperties2.name = fileName; + datasetProperties2.type = file_type; + datasetProperties2.clientId = "02242350"; + datasetProperties2.container = itemRevision; + datasetProperties2.relationType = "RB3_RWZL"; + com.teamcenter.services.strong.core._2006_03.DataManagement.CreateDatasetsResponse + ceateDatasetsResponse = + dataManagementService.createDatasets2( + new com.teamcenter.services.strong.core._2008_06.DataManagement.DatasetProperties2 + [] {datasetProperties2}); + Dataset dt = ceateDatasetsResponse.output[0].dataset; + + String WholefileName = file.getPath(); + + // Create a file to associate with dataset + com.teamcenter.services.loose.core._2006_03.FileManagement.DatasetFileInfo fileInfo = + new com.teamcenter.services.loose.core._2006_03.FileManagement.DatasetFileInfo(); + + fileInfo.allowReplace = false; + fileInfo.clientId = fileInfo.toString(); + fileInfo.fileName = WholefileName; + fileInfo.isText = false; + fileInfo.namedReferencedName = namedReferencedName; + + com.teamcenter.services.loose.core._2006_03.FileManagement.DatasetFileInfo[] fileInfos = { + fileInfo + }; + + com.teamcenter.services.loose.core._2006_03.FileManagement.GetDatasetWriteTicketsInputData + inputData = + new com.teamcenter.services.loose.core._2006_03.FileManagement + .GetDatasetWriteTicketsInputData(); + inputData.dataset = dt; + inputData.createNewVersion = false; + inputData.datasetFileInfos = fileInfos; + + FileManagement.GetDatasetWriteTicketsInputData[] inputs = {inputData}; + ServiceData response = fileManagementUtility.putFiles(inputs); + fileManagementUtility.term(); + + // 更改所有权 + try { + Utils.changeOwnershipModelObject(user, "", new ModelObject[] {dt}); + } catch (Exception e) { + e.printStackTrace(); + } + } + // 删除文件 + // for(File file:fileList){ + // file.delete(); + // } + // zipFile.delete(); + } + + public static Object osGetDeliveryInfo(List itemIdList) { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("success", true); + jsonObject.put("code", null); + DataManagementService dmService = DataManagementService.getService(AppXSession.getConnection()); + + ModelObject tempObject = null; + Date tempData = null; + try { + JSONArray jsonArray = new JSONArray(); + for (String deliveryId : itemIdList) { + JSONObject dataJson = new JSONObject(); + ModelObject[] items = loadObjects(new String[] {deliveryId}, dmService); + ModelObject object = null; + if (items != null && items.length > 0) { + object = items[0]; + } else { + // 通过查询获取对象 + ModelObject[] tempObjects = + Query.queryItems("Item...", new String[] {"Item ID"}, new String[] {deliveryId}); + if (tempObjects != null && tempObjects.length > 0) { + object = tempObjects[0]; + } + } + if (object != null && object instanceof Item) { + dmService.refreshObjects(new ModelObject[] {object}); + dmService.getProperties(new ModelObject[] {object}, new String[] {"revision_list"}); + Item item = (Item) object; + ModelObject[] revisions = item.get_revision_list(); + dmService.refreshObjects(revisions); + dmService.getProperties( + revisions, + new String[] { + "date_released", + "object_name", + "itemId", + "item_revision_id", + "IMAN_specification", + "TC_Attaches", + "release_status_list" + }); + for (ModelObject modelObject : revisions) { + ModelObject[] rslist = + modelObject.getPropertyObject("release_status_list").getModelObjectArrayValue(); + if (rslist.length > 0) { + if (tempObject != null) { + Date date = + modelObject.getPropertyObject("date_released").getCalendarValue().getTime(); + int compare = date.compareTo(tempData); + if (date.compareTo(tempData) == 1) { + tempObject = modelObject; + tempData = date; + } + } else { + tempObject = modelObject; + tempData = + modelObject.getPropertyObject("date_released").getCalendarValue().getTime(); + } + } + } + if (tempObject != null) { + ModelObject userObject = + tempObject.getPropertyObject("owning_user").getModelObjectValue(); + ItemRevision revision = (ItemRevision) tempObject; + String objectName = revision.get_object_name(); + String revisionId = revision.get_item_revision_id(); + dmService.getProperties(new ModelObject[] {userObject}, new String[] {"user_name"}); + String userName = userObject.getPropertyObject("user_name").getStringValue(); + dataJson.put("id", revision.getUid()); + dataJson.put("itemId", revision.get_item_id()); + dataJson.put("name", objectName); + dataJson.put("version", revisionId); + dataJson.put("owner", userName); + jsonObject.put("msg", null); + } else { + jsonObject.put("msg", "无最新已发布的版本!"); + } + jsonArray.add(dataJson); + } else if (object != null && object instanceof Dataset) { + // 如果是数据集,直接获取文件并返回 + dmService.refreshObjects(new ModelObject[] {object}); + dmService.getProperties(new ModelObject[] {object}, new String[] {"object_name"}); + Dataset dataset = (Dataset) object; + String objectName = dataset.get_object_name(); + String revisionId = "0"; + ModelObject userObject = dataset.getPropertyObject("owning_user").getModelObjectValue(); + dmService.getProperties(new ModelObject[] {userObject}, new String[] {"user_name"}); + String userName = userObject.getPropertyObject("user_name").getStringValue(); + dataJson.put("id", dataset.getUid()); + dataJson.put("itemId", ""); + dataJson.put("name", objectName); + dataJson.put("version", revisionId); + dataJson.put("owner", userName); + jsonObject.put("msg", null); + jsonArray.add(dataJson); + } + } + jsonObject.put("data", jsonArray); + // ModelObject[] modelObjects = + // Query.queryItems("Item Revision...", new String[] {"Item ID"}, new String[] + // {deliveryId}); + // + // dmService.refreshObjects(modelObjects); + // dmService.getProperties( + // modelObjects, new String[] {"date_released", "object_name", "item_revision_id"}); + // for (ModelObject modelObject : modelObjects) { + // ModelObject[] rslist = + // modelObject.getPropertyObject("release_status_list").getModelObjectArrayValue(); + // if (rslist.length > 0) { + // if (tempObject != null) { + // Date date = + // modelObject.getPropertyObject("date_released").getCalendarValue().getTime(); + // int compare = date.compareTo(tempData); + // if (date.compareTo(tempData) == 1) { + // tempObject = modelObject; + // tempData = date; + // } + // } else { + // tempObject = modelObject; + // tempData = + // modelObject.getPropertyObject("date_released").getCalendarValue().getTime(); + // } + // } + // } + // if (tempObject != null) { + // ModelObject userObject = + // tempObject.getPropertyObject("owning_user").getModelObjectValue(); + // ItemRevision revision = (ItemRevision) tempObject; + // String objectName = revision.get_object_name(); + // String revisionId = revision.get_item_revision_id(); + // dmService.getProperties(new ModelObject[] {userObject}, new String[] {"user_name"}); + // String userName = userObject.getPropertyObject("user_name").getStringValue(); + // dataJson.put("id", deliveryId); + // dataJson.put("name", objectName); + // dataJson.put("version", revisionId); + // dataJson.put("owner", userName); + // jsonObject.put("msg", null); + // } else { + // jsonObject.put("msg", "无最新已发布的版本!"); + // } + // jsonObject.put("data", dataJson); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + return jsonObject; + } + + public static Object oaGetHistoryDelivery(String deliveryId) { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("success", true); + + jsonObject.put("code", null); + JSONObject dataJson = new JSONObject(); + // dataJson.put("deliveryId",deliveryId); + DataManagementService dmService = DataManagementService.getService(AppXSession.getConnection()); + ModelObject[] tempObjects; + try { + ModelObject[] items = loadObjects(new String[] {deliveryId}, dmService); + ModelObject object = null; + if (items != null && items.length > 0) { + object = items[0]; + } else { + // 通过查询获取对象 + tempObjects = + Query.queryItems("Item...", new String[] {"Item ID"}, new String[] {deliveryId}); + if (tempObjects != null && tempObjects.length > 0) { + object = tempObjects[0]; + } + } + if (object != null && object instanceof Item) { + dmService.refreshObjects(new ModelObject[] {object}); + dmService.getProperties(new ModelObject[] {object}, new String[] {"revision_list"}); + Item item = (Item) object; + ModelObject[] revisions = item.get_revision_list(); + dmService.refreshObjects(revisions); + dmService.getProperties( + revisions, + new String[] { + "date_released", + "object_name", + "item_revision_id", + "IMAN_specification", + "TC_Attaches", + "release_status_list" + }); + // JSONObject deliverys[] = new JSONObject[0]; + List deliveryList = new ArrayList(); + if (revisions.length != 0) { + for (int i = revisions.length - 1; i >= 0; i--) { + ItemRevision revision = (ItemRevision) revisions[i]; + if (revision.get_release_status_list() == null + || revision.get_release_status_list().length <= 0) { + continue; + } + JSONObject deliverys = new JSONObject(); + deliverys.put("id", revision.getUid()); + deliverys.put("itemId", revision.get_item_id()); + + ModelObject userObject = + revisions[i].getPropertyObject("owning_user").getModelObjectValue(); + dmService.getProperties(new ModelObject[] {userObject}, new String[] {"user_name"}); + String userName = userObject.getPropertyObject("user_name").getStringValue(); + deliverys.put("owner", userName); + + String objectName = revision.get_object_name(); + String revisionId = revision.get_item_revision_id(); + deliverys.put("name", objectName); + deliverys.put("version", revisionId); + + ModelObject[] dataSets_IMAN_specification = + revisions[i].getPropertyObject("IMAN_specification").getModelObjectArrayValue(); + ModelObject[] dataSets_TC_Attaches = + revisions[i].getPropertyObject("TC_Attaches").getModelObjectArrayValue(); + if (dataSets_IMAN_specification.length != 0 || dataSets_TC_Attaches.length != 0) { + deliverys.put("hasFile", true); + } else { + deliverys.put("hasFile", false); + } + jsonObject.put("msg", null); + deliveryList.add(deliverys); + } + dataJson.put("delivery", deliveryList); + } else { + jsonObject.put("msg", "无已发布版本信息!"); + dataJson.put("delivery", deliveryList); + } + } else if (object != null && object instanceof Dataset) { + // 如果是数据集,直接获取文件并返回 + dmService.refreshObjects(new ModelObject[] {object}); + dmService.getProperties(new ModelObject[] {object}, new String[] {"object_name"}); + List deliveryList = new ArrayList(); + Dataset dataset = (Dataset) object; + JSONObject deliverys = new JSONObject(); + + deliverys.put("id", dataset.getUid()); + deliverys.put("itemId", ""); + + ModelObject userObject = dataset.getPropertyObject("owning_user").getModelObjectValue(); + dmService.getProperties(new ModelObject[] {userObject}, new String[] {"user_name"}); + String userName = userObject.getPropertyObject("user_name").getStringValue(); + deliverys.put("owner", userName); + + String objectName = dataset.get_object_name(); + String revisionId = "0"; + deliverys.put("name", objectName); + deliverys.put("version", revisionId); + + // ModelObject[] dataSets_IMAN_specification = + // dataset.getPropertyObject("IMAN_specification").getModelObjectArrayValue(); + // ModelObject[] dataSets_TC_Attaches = + // dataset.getPropertyObject("TC_Attaches").getModelObjectArrayValue(); + // if (dataSets_IMAN_specification.length != 0 || dataSets_TC_Attaches.length != 0) { + deliverys.put("hasFile", true); + // } else { + // deliverys.put("hasFile", false); + // } + deliveryList.add(deliverys); + jsonObject.put("msg", null); + dataJson.put("delivery", deliveryList); + } + + // tempObjects = + // Query.queryItems( + // "Item Revision...", + // new String[] {"Item ID", "Release Status"}, + // new String[] {deliveryId, "TCM Released"}); + // dmService.refreshObjects(tempObjects); + // dmService.getProperties( + // tempObjects, + // new String[] { + // "date_released", "object_name", "item_revision_id", "IMAN_specification", + // "TC_Attaches" + // }); + // + // JSONObject deliverys[] = new JSONObject[0]; + // if (tempObjects.length != 0) { + // deliverys = new JSONObject[tempObjects.length]; + // for (int i = 0; i < tempObjects.length; i++) { + // deliverys[i] = new JSONObject(); + // + // deliverys[i].put("id", deliveryId); + // + // ModelObject userObject = + // tempObjects[i].getPropertyObject("owning_user").getModelObjectValue(); + // dmService.getProperties(new ModelObject[] {userObject}, new String[] + // {"user_name"}); + // String userName = userObject.getPropertyObject("user_name").getStringValue(); + // deliverys[i].put("owner", userName); + // + // ItemRevision revision = (ItemRevision) tempObjects[i]; + // String objectName = revision.get_object_name(); + // String revisionId = revision.get_item_revision_id(); + // deliverys[i].put("name", objectName); + // deliverys[i].put("version", revisionId); + // + // ModelObject[] dataSets_IMAN_specification = + // + // tempObjects[i].getPropertyObject("IMAN_specification").getModelObjectArrayValue(); + // ModelObject[] dataSets_TC_Attaches = + // tempObjects[i].getPropertyObject("TC_Attaches").getModelObjectArrayValue(); + // if (dataSets_IMAN_specification.length != 0 || dataSets_TC_Attaches.length != 0) { + // deliverys[i].put("hasFile", true); + // } else { + // deliverys[i].put("hasFile", false); + // } + // + // jsonObject.put("msg", null); + // } + // dataJson.put("delivery", deliverys); + // } else { + // jsonObject.put("msg", "无已发布版本信息!"); + // dataJson.put("delivery", deliverys); + // } + + jsonObject.put("data", dataJson); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + return jsonObject; + } + + public static File getGetDeliveryFile(String deliveryId, String deliberyRevision) { + List files = null; + DataManagementService dmService = DataManagementService.getService(AppXSession.getConnection()); + + try { + List dataSetUidList = new ArrayList(); + // ModelObject[] modelObjects = + // Query.queryItems( + // "Item Revision...", + // new String[] {"Item ID", "Revision"}, + // new String[] {deliveryId, deliberyRevision}); + ModelObject[] modelObjects = loadObjects(new String[] {deliveryId}, dmService); + if (modelObjects == null || modelObjects.length <= 0) { + modelObjects = + Query.queryItems( + "Item Revision...", + new String[] {"Item ID", "Revision"}, + new String[] {deliveryId, deliberyRevision}); + } + if (modelObjects[0] instanceof ItemRevision) { + dmService.refreshObjects(modelObjects); + dmService.getProperties(modelObjects, new String[] {"IMAN_specification", "TC_Attaches"}); + ModelObject[] dataSets_IMAN_specification = + modelObjects[0].getPropertyObject("IMAN_specification").getModelObjectArrayValue(); + ModelObject[] dataSets_TC_Attaches = + modelObjects[0].getPropertyObject("TC_Attaches").getModelObjectArrayValue(); + for (ModelObject dataSet : dataSets_IMAN_specification) { + if (dataSet instanceof Dataset) { + dataSetUidList.add(dataSet.getUid()); + System.out.println("IMAN_specification DataSet UID" + dataSet.getUid()); + // 0224 + Dataset dt = (Dataset) dataSet; + } + } + for (ModelObject dataSet : dataSets_TC_Attaches) { + if (dataSet instanceof Dataset) { + dataSetUidList.add(dataSet.getUid()); + System.out.println("TC_Attaches DataSet UID" + dataSet.getUid()); + } + } + } else if (modelObjects[0] instanceof Dataset) { + dataSetUidList.add(modelObjects[0].getUid()); + } + if (dataSetUidList.size() != 0) { + files = + getTcfileByFileId( + dataSetUidList.toArray(new String[dataSetUidList.size()]), + deliveryId, + deliberyRevision); + if (files.size() == 1) { + return files.get(0); + } + + if (files.size() > 1) { + File zipEntry = + new File( + files.get(0).getParent() + + File.separatorChar + + deliveryId + + "-" + + deliberyRevision + + ".zip"); + toZip(files, zipEntry); + return zipEntry; + } + } else { + + } + + } catch (Exception e) { + System.out.println(); + } + return null; + } + + public static void toZip(List srcFiles, File zipFile) throws RuntimeException { + long start = System.currentTimeMillis(); + if (zipFile == null) { + System.out.println("压缩包文件名为空!"); + return; + } + if (!zipFile.getName().endsWith(".zip")) { + System.out.println("压缩包文件名异常,zipFile=" + zipFile.getPath()); + return; + } + ZipOutputStream zos = null; + FileOutputStream out = null; + try { + out = new FileOutputStream(zipFile); + zos = new ZipOutputStream(out); + for (File srcFile : srcFiles) { + byte[] buf = new byte[1024]; + zos.putNextEntry(new ZipEntry(srcFile.getName())); + int len; + FileInputStream in = new FileInputStream(srcFile); + while ((len = in.read(buf)) != -1) { + zos.write(buf, 0, len); + } + zos.closeEntry(); + in.close(); + } + long end = System.currentTimeMillis(); + System.out.println("压缩完成,耗时:" + (end - start) + " ms"); + } catch (Exception e) { + System.out.println("ZipUtil toZip exception, " + e); + throw new RuntimeException("zipFile error from ZipUtils " + e); + } finally { + if (zos != null) { + try { + zos.close(); + } catch (IOException e) { + System.out.println("ZipUtil toZip close exception, " + e); + } + } + if (out != null) { + try { + out.close(); + } catch (IOException e) { + System.out.println("ZipUtil toZip close exception, " + e); + } + } + } + } + + public static void getLovMappingPrefernce() { + PreferenceManagementService preferenceManagementService = + new PreferenceManagementRestBindingStub(AppXSession.getConnection()); + PreferenceManagement.GetPreferencesResponse getPreferencesResponse = + preferenceManagementService.getPreferences( + new String[] { + "LovMapping_rb3_khdj", + "LovMapping_rb3_xmlx", + "LovMapping_rb3_xmdj", + "LovMapping_rb3_zclx", + "LovMapping_rb3_scgc", + "LovMapping_rb3_yyly" + }, + true); + + for (PreferenceManagement.CompletePreference completePreference : + getPreferencesResponse.response) { + Map valueMap = new HashMap(); + for (String value : completePreference.values.values) { + if (value.contains("=")) { + valueMap.put(value.split("=")[0], value.split("=")[1]); + } + } + lovMappingList.put(completePreference.definition.name.replace("LovMapping_", ""), valueMap); + } + } + + public static String[] getRealLovValues(String propertyName, String[] displayValus) { + if (lovMappingList.containsKey(propertyName)) { + String[] realLovValues = new String[displayValus.length]; + for (int i = 0; i < displayValus.length; i++) { + realLovValues[i] = lovMappingList.get(propertyName).get(displayValus[i]); + System.out.println(displayValus[i] + "->" + realLovValues[i]); + } + + return realLovValues; + } else { + return displayValus; + } + } + + public static String createOrUpdataProject( + ProjectData data, + HashMap + itemObjectPropMap, + HashMap + itemRevObjectPropMap, + HashMap + itemRevMasterObjectPropMap, + String logFileName) { + String projectRevisionPUID = data.getProjectUID(); + try { + TcsoaService.getLovMappingPrefernce(); + // 创建项目对象 + if (data.getProjectUID() == null || data.getProjectUID().isEmpty()) { + + DataManagementService dataManagementService = + DataManagementService.getService(AppXSession.getConnection()); + DataManagement.ItemProperties itemProperties = new DataManagement.ItemProperties(); + + // itemProperties.itemId = task_Uid; + itemProperties.name = data.getObjectName(); + // itemProperties.type = "QF6_1"; + itemProperties.type = "RB3_XMKF"; + DataManagement.CreateItemsResponse itemsResponse = + dataManagementService.createItems( + new DataManagement.ItemProperties[] {itemProperties}, null, ""); + + ItemRevision itemRevision = itemsResponse.output[0].itemRev; + projectRevisionPUID = itemRevision.getUid(); + // ModelObject[] itemRevision_master = itemRevision.get_IMAN_master_form_rev(); + // projectRevisionPUID = itemRevision.getUid(); + // 设置版本属性 + // Map<> propertyMap = packagePropertyMap(data); + // com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct desc + // = new com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct(); + // desc.stringVec = new String[]{data.getObjectDesc()}; + + HashMap + revisionPropertyMap = setRevisionProperty(data, itemRevObjectPropMap); + + dataManagementService.setProperties( + new ModelObject[] {itemRevision.get_items_tag()}, itemObjectPropMap); + ServiceData sd = + dataManagementService.setProperties( + new ModelObject[] {itemRevision}, revisionPropertyMap); + ; + String messageValue = ""; + if (sd.sizeOfPartialErrors() > 0) { + for (int i = 0; i < sd.sizeOfPartialErrors(); i++) { + String[] messages = sd.getPartialError(i).getMessages(); + for (int j = 0; j < messages.length; j++) { + messageValue = messageValue + messages[j]; + } + } + } + System.out.println("messageValue:" + messageValue); + if (!messageValue.isEmpty()) { + Utils.setLog(logFileName, "oaCreateOrUpdateProject", "设置属性:" + messageValue); + } + + // dataManagementService.setProperties(itemRevision_master, itemRevMasterObjectPropMap); + + // 将新增对象添加到个人文件夹 + ModelObject user = Utils.findUser(data.getUserId()); + dataManagementService.getProperties(new ModelObject[] {user}, new String[] {"home_folder"}); + + String userFolderPuid = getFolderPuid(data.getUserId()); + + ServiceData ServiceData = dataManagementService.loadObjects(new String[] {userFolderPuid}); + Folder userFolder = null; + if (ServiceData.sizeOfPlainObjects() > 0) { + userFolder = (Folder) ServiceData.getPlainObject(0); + } else { + userFolder = (Folder) user.getPropertyObject("home_folder").getModelObjectValue(); + } + + // Folder home_folder = + // Utils.changeOwnershipModelObject(user,"",new + // ModelObject[]{itemsResponse.output[0].item,itemsResponse.output[0].itemRev}); + com.teamcenter.services.strong.core._2007_01.DataManagement.MoveToNewFolderInfo + moveToNewFolderInfo = + new com.teamcenter.services.strong.core._2007_01.DataManagement + .MoveToNewFolderInfo(); + + moveToNewFolderInfo.newFolder = userFolder; + moveToNewFolderInfo.objectsToMove = new ModelObject[] {itemsResponse.output[0].item}; + dataManagementService.moveToNewFolder( + new com.teamcenter.services.strong.core._2007_01.DataManagement.MoveToNewFolderInfo[] { + moveToNewFolderInfo + }); + System.out.println(); + } + // 更新项目对象 + else { + DataManagementService dataManagementService = + DataManagementService.getService(AppXSession.getConnection()); + ServiceData resultDate = + dataManagementService.loadObjects(new String[] {data.getProjectUID()}); + + if (resultDate.sizeOfPlainObjects() != 0) { + ModelObject resultModelObject = resultDate.getPlainObject(0); + HashMap + revisionPropertyMap = setRevisionProperty(data, itemRevObjectPropMap); + + dataManagementService.setProperties( + new ModelObject[] {resultModelObject}, revisionPropertyMap); + } + System.out.println(); + } + // } catch (NotLoadedException e) { + // e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + return projectRevisionPUID; + } + + /*** + * 设置版本属性 + * @param data + * @return + */ + private static HashMap< + String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct> + setRevisionProperty( + ProjectData data, + HashMap + revisionPropertyMap) { + + for (String key : revisionPropertyMap.keySet()) { + com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct vecStruct = + revisionPropertyMap.get(key); + // 获取LOV真实值 + String[] value = vecStruct.stringVec; + vecStruct.stringVec = getRealLovValues(key, value); + } + + com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct rb3_zclx = + new com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct(); + com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct rb3_scgc = + new com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct(); + int productIndex = 0; + if (data.getProduct() != null) { + String[] zclx = new String[data.getProduct().size()]; + String[] scgc = new String[data.getProduct().size()]; + for (Product product : data.getProduct()) { + zclx[productIndex] = product.getBearingCategory(); + scgc[productIndex] = product.getPlant(); + productIndex++; + } + rb3_zclx.stringVec = getRealLovValues("rb3_zclx", zclx); + rb3_scgc.stringVec = getRealLovValues("rb3_scgc", scgc); + } + // HashMap + // revisionPropertyMap = new HashMap(); + + revisionPropertyMap.put("rb3_zclx", rb3_zclx); + revisionPropertyMap.put("rb3_scgc", rb3_scgc); + return revisionPropertyMap; + } + + private static String getFolderPuid(String userId) { + String puid = null; + + PreferenceManagementService preferenceManagementService = + new PreferenceManagementRestBindingStub(AppXSession.getConnection()); + PreferenceManagement.GetPreferencesResponse getPreferencesResponse = + preferenceManagementService.getPreferences(new String[] {"RB3_IDRelation"}, true); + + PreferenceManagement.CompletePreference completePreference = getPreferencesResponse.response[0]; + Map valueMap = new HashMap(); + for (String value : completePreference.values.values) { + if (value.contains("=")) { + valueMap.put(value.split("=")[0], value.split("=")[1]); + } + } + puid = valueMap.get(userId.toUpperCase()); + if (puid == null && userId.equals("admin")) { + puid = "BgpJXvMlZFesrD"; + } + return puid; + } + + public static boolean ServiceDataError(ServiceData data) { + if (data.sizeOfPartialErrors() > 0) { + for (int i = 0; i < data.sizeOfPartialErrors(); i++) { + System.out.println(data.getPartialError(i).getMessages()); + } + return false; + } + return true; + } + + public static ModelObject[] loadObjects(String[] ids, DataManagementService dmService) { + ServiceData sData = dmService.loadObjects(ids); + List lstObj = new ArrayList(); + if (ServiceDataError(sData)) { + for (int i = 0; i < sData.sizeOfPlainObjects(); i++) { + ModelObject mobj = sData.getPlainObject(i); + lstObj.add(mobj); + } + } + return lstObj.toArray(new ModelObject[lstObj.size()]); + } + + public static void openByPass(com.teamcenter.soa.client.Connection connection) { + com.teamcenter.services.strong.core._2007_12.Session.StateNameValue[] propPairs = + new com.teamcenter.services.strong.core._2007_12.Session.StateNameValue[1]; + propPairs[0] = new com.teamcenter.services.strong.core._2007_12.Session.StateNameValue(); + propPairs[0].name = "bypassFlag"; + propPairs[0].value = com.teamcenter.soa.client.model.Property.toBooleanString(true); + + com.teamcenter.soa.client.model.ServiceData data = + SessionService.getService(connection).setUserSessionState(propPairs); + } + + public static void closeByPass(com.teamcenter.soa.client.Connection connection) { + com.teamcenter.services.strong.core._2007_12.Session.StateNameValue[] propPairs = + new com.teamcenter.services.strong.core._2007_12.Session.StateNameValue[1]; + propPairs[0] = new com.teamcenter.services.strong.core._2007_12.Session.StateNameValue(); + propPairs[0].name = "bypassFlag"; + propPairs[0].value = com.teamcenter.soa.client.model.Property.toBooleanString(false); + + com.teamcenter.soa.client.model.ServiceData data = + SessionService.getService(connection).setUserSessionState(propPairs); + } + + public static String getClassPropertyValue(ModelObject rev, String propertyName) { + try { + + // ClassificationService classService = + // ClassificationService.getService(AppXSession.getConnection()); + // + // Classification.FindClassificationObjectsResponse ics2 = + // classService.findClassificationObjects(new WorkspaceObject[] { (ItemRevision)rev }); + // ModelObject[] icos = (ModelObject[])ics2.icos[rev]; + // if (icos != null && icos.length > 0) + // { + // + // Classification.ClassificationObject ico = + // (Classification.ClassificationObject)icos[0]; + // String classID = ico.classId; + // Classification.GetAttributesForClassesResponse attributes = + // classService.getAttributesForClasses(new String[] { classID }); + // Map attributeTable = attributes.attributes; + // int propertyId = -1; + // for (Object key : attributeTable.keySet()) + // { + // if (attributeTable.get(key).toString().compareTo(propertyName) == 0) + // { + // propertyId = (int)key; + // } + // } + // Classification.ClassificationProperty[] propertys = ico.properties; + // for (ClassificationProperty property in propertys) + // { + // if (property.AttributeId == propertyId && property.Values != null && + // property.Values.Count() > 0) + // { + // return property.Values[0].DbValue; + // } + // + // } + // } + // return ""; + } catch (Exception ex) { + } + return ""; + } + + public static com.teamcenter.soa.client.model.Property GetProperty( + ModelObject obj, String propName, DataManagementService dm) throws Exception { + ModelObject[] mo = new ModelObject[] {obj}; + dm.refreshObjects(mo); + dm.getProperties(mo, new String[] {propName}); + com.teamcenter.soa.client.model.Property prop = null; + try { + prop = obj.getPropertyObject(propName); + } catch (Exception ex) { + + throw new Exception("获取属性<" + propName + ">失败,错误信息:" + ex.getMessage()); + // KMain.Log("获取属性<"+propName+">失败,错误信息:"+ex.Message); + } + return prop; + } + + public static String getItemPropertyValue( + DataManagementService dmService, ModelObject itemRevision, String propertyName) + throws Exception { + try { + if (propertyName.indexOf(".") > 0) { + String[] itemNames = propertyName.split("\\."); + ModelObject itemTag = itemRevision; + String propertyWhere = itemNames[0]; + + if (itemRevision instanceof ItemRevision) { + ItemRevision rev = (ItemRevision) itemRevision; + switch (propertyWhere) { + case "item": + dmService.getProperties(new ModelObject[] {rev}, new String[] {"items_tag"}); + itemTag = rev.get_items_tag(); + break; + case "revMaster": + dmService.getProperties( + new ModelObject[] {rev}, new String[] {"IMAN_master_form_rev"}); + ModelObject[] forms = rev.get_IMAN_master_form_rev(); + if (forms.length > 0) { + itemTag = forms[0]; + } + break; + case "class": + return getClassPropertyValue(rev, itemNames[itemNames.length - 1]); + default: + break; + } + } else if (itemRevision instanceof Item) { + Item item = (Item) itemRevision; + switch (propertyWhere) { + case "rev": + itemTag = Utils.GetLatestRev(dmService, item); + break; + case "revMaster": + ItemRevision rev = Utils.GetLatestRev(dmService, item); + dmService.getProperties( + new ModelObject[] {rev}, new String[] {"IMAN_master_form_rev"}); + ModelObject[] forms = rev.get_IMAN_master_form_rev(); + if (forms.length > 0) { + itemTag = forms[0]; + } + break; + case "class": + ItemRevision rev2 = Utils.GetLatestRev(dmService, item); + return getClassPropertyValue(rev2, itemNames[itemNames.length - 1]); + + default: + break; + } + } else if (itemRevision instanceof BOMLine) { + BOMLine bomLine = (BOMLine) itemRevision; + dmService.getProperties( + new ModelObject[] {bomLine}, new String[] {"bl_revision", "bl_item"}); + switch (propertyWhere) { + case "item": + itemTag = bomLine.get_bl_item(); + break; + case "rev": + itemTag = bomLine.get_bl_revision(); + break; + case "revMaster": + ItemRevision rev = (ItemRevision) bomLine.get_bl_revision(); + dmService.getProperties( + new ModelObject[] {rev}, new String[] {"IMAN_master_form_rev"}); + ModelObject[] forms = rev.get_IMAN_master_form_rev(); + if (forms.length > 0) { + itemTag = forms[0]; + } + break; + case "class": + ItemRevision rev2 = (ItemRevision) bomLine.get_bl_revision(); + return getClassPropertyValue(rev2, itemNames[itemNames.length - 1]); + + default: + break; + } + } + if (itemNames.length > 2) { + for (int j = 1; j < itemNames.length - 1; j++) { + com.teamcenter.soa.client.model.Property tagProperty = + GetProperty(itemTag, itemNames[j], dmService); + if (tagProperty.getPropertyDescription().isArray()) { + ModelObject[] resultObjects = tagProperty.getModelObjectArrayValue(); + if (resultObjects != null && resultObjects.length > 0) { + for (ModelObject resultProject : resultObjects) { + if (resultProject != null) { + itemTag = resultProject; + break; + } + } + } else { + return ""; + } + } else { + ModelObject resultObject = tagProperty.getModelObjectValue(); + if (resultObject != null) { + itemTag = tagProperty.getModelObjectValue(); + } else { + return ""; + } + } + // item = .getRelatedComponent(itemNames[j]); + } + com.teamcenter.soa.client.model.Property property = + GetProperty(itemTag, itemNames[itemNames.length - 1], dmService); + + if (property.getPropertyDescription().getLovUid() != null + && !property.getPropertyDescription().getLovUid().equals("")) { + com.teamcenter.services.strong.core._2010_04.DataManagement.NameLocaleStruct ns = new com.teamcenter.services.strong.core._2010_04.DataManagement.NameLocaleStruct(); + ns.locales = new String[] { "zh_CN" }; + ns.name = itemNames[itemNames.length - 1]; + com.teamcenter.services.strong.core._2010_04.DataManagement.PropertyInfo pi = new com.teamcenter.services.strong.core._2010_04.DataManagement.PropertyInfo(); + pi.object = itemTag; + pi.propsToget = new com.teamcenter.services.strong.core._2010_04.DataManagement.NameLocaleStruct[] { ns }; + com.teamcenter.services.strong.core._2015_07.DataManagement.LocalizedPropertyValuesResponse lpvr = dmService.getLocalizedProperties2(new com.teamcenter.services.strong.core._2010_04.DataManagement.PropertyInfo[] { pi }); + com.teamcenter.services.strong.core._2015_07.DataManagement.LocalizedPropertyValuesInfo2[] Output = lpvr.output; + if(Output.length > 0 && Output[0].propertyValues.length > 0 && Output[0].propertyValues[0].values.length > 0) + { + return Output[0].propertyValues[0].values[0]; + } +// LovInfo lovInfo = property.getPropertyDescription().getLovReference().getLovInfo(); +// List lovValueList = lovInfo.getValues(); +// for (LovValue lovValue : lovValueList) { +// lovValue.getDisplayValue(); +// } +// String lovUid = property.getPropertyDescription().getLovUid(); +// ModelObject[] items = loadObjects(new String[] {lovUid}, dmService); +// if (items == null || items.length <= 0) { +// return property.getDisplayableValue(); +// } +// // dmService.getProperties(items, new String[] { "lov_name" }); +// return property.getDisplayableValue(); + // String lovName = items[0].getPropertyObject("lov_name").getStringValue(); + // String value = getLovDisValue(lovName, property.getDisplayableValue()); + // if (value != null && !value.equals("")) + // { + // return value; + // } + // else + // { + // return property.getDisplayableValue(); + // } + } else { + if (itemNames[itemNames.length - 1].compareTo("object_type") == 0) { + return property.getStringValue(); + } + // else if (property.getPropertyDescription().getServerType() == 2) + // { + // return property.DateValue.ToString("yyyy-MM-dd HH:mm:ss"); + // } + else { + return property.getDisplayableValue(); + } + } + } else { + com.teamcenter.soa.client.model.Property property = + GetProperty(itemTag, itemNames[itemNames.length - 1], dmService); + if (property.getPropertyDescription().getLovUid() != null + && !property.getPropertyDescription().getLovUid().equals("")) { +// LovInfo lovInfo = property.getPropertyDescription().getLovReference().getLovInfo(); +// List lovValueList = lovInfo.getValues(); +// for (LovValue lovValue : lovValueList) { +// lovValue.getDisplayValue(); +// } + + //Teamcenter.Services.Strong.Core._2010_04.DataManagement.NameLocaleStruct ns = new Services.Strong.Core._2010_04.DataManagement.NameLocaleStruct(); + com.teamcenter.services.strong.core._2010_04.DataManagement.NameLocaleStruct ns = new com.teamcenter.services.strong.core._2010_04.DataManagement.NameLocaleStruct(); + ns.locales = new String[] { "zh_CN" }; + ns.name = itemNames[itemNames.length - 1]; + com.teamcenter.services.strong.core._2010_04.DataManagement.PropertyInfo pi = new com.teamcenter.services.strong.core._2010_04.DataManagement.PropertyInfo(); + pi.object = itemTag; + pi.propsToget = new com.teamcenter.services.strong.core._2010_04.DataManagement.NameLocaleStruct[] { ns }; + com.teamcenter.services.strong.core._2015_07.DataManagement.LocalizedPropertyValuesResponse lpvr = dmService.getLocalizedProperties2(new com.teamcenter.services.strong.core._2010_04.DataManagement.PropertyInfo[] { pi }); + com.teamcenter.services.strong.core._2015_07.DataManagement.LocalizedPropertyValuesInfo2[] Output = lpvr.output; + if(Output.length > 0 && Output[0].propertyValues.length > 0 && Output[0].propertyValues[0].values.length > 0) + { + return Output[0].propertyValues[0].values[0]; + } + + //return property.getDisplayableValue(); + } else { + if (itemNames[itemNames.length - 1].compareTo("object_type") == 0) { + return property.getStringValue(); + } else if (itemNames[itemNames.length - 1].compareTo("bl_quantity") == 0) { + if (itemTag instanceof BOMLine) { + BOMLine line = (BOMLine) itemTag; + dmService.refreshObjects(new ModelObject[] {line}); + dmService.getProperties(new ModelObject[] {line}, new String[] {"bl_quantity"}); + return line.get_bl_quantity(); + } + } else { + + return property.getDisplayableValue(); + // if (property.PropertyDescription.ServerType == 2) + // { + // return property.DateValue.ToString("yyyy-MM-dd HH:mm:ss"); + // } + // else + // { + // return property.getDisplayableValue(); + // } + } + } + // return property.DisplayableValue; + } + } + return ""; + } catch (Exception ex) { + throw new Exception("获取属性值失败!“" + ex.getMessage()); + } + } + + public static JsonResult getItemPropertys(String logFileName, List itemIdList) { + try { + + com.teamcenter.soa.client.Connection connection = AppXSession.getConnection(); + DataManagementService dmService = DataManagementService.getService(connection); + JSONArray jsonArray = new JSONArray(); + openByPass(connection); + for (int ii = 0; ii < itemIdList.size(); ii++) { + JSONObject jsonObject = new JSONObject(); + String itemId = itemIdList.get(ii); + Utils.setLog(logFileName, "getItemPropertys", "itemId:" + itemId); + + Item item = Utils.SearchItem(itemId); + + if (item == null) { + Utils.setLog(logFileName, "getItemPropertys", "通过item id" + itemId + "未获取到对象"); + return JsonResult.error("通过item id" + itemId + "未获取到对象"); + } + + // ModelObject item = items[0]; + dmService.getProperties(new ModelObject[] {item}, new String[] {"object_type"}); + // 获取对象类型 + String objectType = item.getPropertyObject("object_type").getStringValue(); + Utils.setLog(logFileName, "getItemPropertys", "objectType:" + objectType); + + // String s1 = + // "RB3_ZC-rev.item_id=materialCode=ID=item_id,rev.object_name=objectName=名称=object_name,rev.item_revision_id==版本=item_revision_id,rev.rb3_cph==产品号=rb3_cph,rev.rb3_th=designth=设计图号=rb3_th,rev.rb3_bsh==标识号=rb3_bsh,rev.rb3_sm2==说明二=rb3_sm2,rev.rb3_lth==老图号/客户图号=rb3_lth,rev.rb3_jwlh=oldItemId=旧物料号=rb3_jwlh,rev.rb3_spm==商品码=rb3_spm,rev.rb3_wxcc_nj==外形尺寸_内径(mm)=rb3_wxcc_nj,rev.rb3_wxcc_wj==外形尺寸_外径(mm)=rb3_wxcc_wj,rev.rb3_wxcc_kd==外形尺寸_宽度(mm)=rb3_wxcc_kd,rev.rb3_nqzxzpdj==内圈最小装配倒角rmin=rb3_nqzxzpdj,rev.rb3_wqzxzpdj==外圈最小装配倒角rmin=rb3_wqzxzpdj,rev.rb3_eddzh==额定动载荷Cr=rb3_eddzh,rev.rb3_edjzh==额定静载荷Cor=rb3_edjzh,rev.rb3_jxyx==径向游隙(mm)=rb3_jxyx,rev.rb3_zxyx==轴向游隙(mm)=rb3_zxyx,rev.rb3_zzl==注脂量(g)=rb3_zzl,rev.rb3_ls==列数=rb3_ls,rev.rb3_gdtdx==滚动体大小(mm)=rb3_gdtdx,rev.rb3_mlgdtsl==每列滚动体数量=rb3_mlgdtsl,rev.rb3_jyzj==节圆直径(mm)=rb3_jyzj,rev.rb3_zl==重量(kg)=rb3_zl,rev.rb3_scgc1=plant=生产工厂=rb3_scgc1,rev.rb3_yyly==应用领域=rb3_yyly,rev.rb3_cjyh==创建用户=rb3_cjyh,rev.rb3_sjr==设计人=rb3_sjr,rev.rb3_dztsyq==打字特殊要求=rb3_dztsyq,rev.rb3_jsyqbgqf==其它技术要求=rb3_jsyqbgqf,rev.rb3_sybw==使用部位=rb3_sybw,rev.rb3_ptkh==配套客户=rb3_ptkh,rev.rb3_ptcx==配套车型=rb3_ptcx,rev.rb3_ms=objectDesc=描述=rb3_ms,rev.rb3_zclx=bearingCategory=总成类型=rb3_zclx,rev.rb3_smzqzt==生命周期状态=rb3_smzqzt,rev.rb3_lswlbs==临时物料标识=rb3_lswlbs,rev.rb3_yxq==有效期=rb3_yxq"; + // String s2 = + // "RB3_LBJ-rev.item_id=materialCode=ID=item_id,rev.object_name=objectName=名称=object_name,rev.item_revision_id==版本=item_revision_id,rev.rb3_cph==产品号=rb3_cph,rev.rb3_th=designth=设计图号=rb3_th,rev.rb3_jwlh=oldItemId=旧物料号=rb3_jwlh,rev.rb3_spm==商品码=rb3_spm,rev.rb3_jh==件号=rb3_jh,rev.rb3_zl==重量(kg)=rb3_zl,rev.rb3_scgc1=plant=生产工厂=rb3_scgc1,rev.rb3_dzzxj==打字中心径=rb3_dzzxj,rev.rb3_dztsyq==打字特殊要求=rb3_dztsyq,rev.rb3_ms=objectDesc=描述=rb3_ms,rev.rb3_jsyqbgqf==其它技术要求=rb3_jsyqbgqf,rev.rb3_smzqzt==生命周期状态=rb3_smzqzt,rev.rb3_cjyh==创建用户=rb3_cjyh,rev.rb3_lswlbs==临时物料标识=rb3_lswlbs,rev.rb3_yxq==有效期=rb3_yxq"; + // String s3 = + // "RB3_GQ-rev.item_id=materialCode=ID=item_id,rev.object_name=objectName=名称=object_name,rev.item_revision_id==版本=item_revision_id,rev.rb3_cph==产品号=rb3_cph,rev.rb3_th=designth=设计图号=rb3_th,rev.rb3_bsh==标识号=rb3_bsh,rev.rb3_jwlh=oldItemId=旧物料号=rb3_jwlh,rev.rb3_spm==商品码=rb3_spm,rev.rb3_zl==重量(kg)=rb3_zl,rev.rb3_scgc1=plant=生产工厂=rb3_scgc1,rev.rb3_cjyh==创建用户=rb3_cjyh,rev.rb3_ms=objectDesc=描述=rb3_ms,rev.rb3_smzqzt==生命周期状态=rb3_smzqzt,rev.rb3_lswlbs==临时物料标识=rb3_lswlbs,rev.rb3_yxq==有效期=rb3_yxq"; + // String s4 = + // "RB3_GZ-rev.item_id=materialCode=ID=item_id,rev.object_name=objectName=名称=object_name,rev.item_revision_id==版本=item_revision_id,rev.rb3_cph==产品号=rb3_cph,rev.rb3_th=designth=设计图号=rb3_th,rev.rb3_bsh==标识号=rb3_bsh,rev.rb3_jwlh=oldItemId=旧物料号=rb3_jwlh,rev.rb3_spm==商品码=rb3_spm,rev.rb3_gzzj==滚子直径(mm)=rb3_gzzj,rev.rb3_gzcd==滚子长度(mm)=rb3_gzcd,rev.rb3_jgcs==结构参数=rb3_jgcs,rev.rb3_gzdj==滚子倒角=rb3_gzdj,rev.rb3_gztd==滚子凸度(μ)=rb3_gztd,rev.rb3_zl==重量(kg)=rb3_zl,rev.rb3_scgc1=plant=生产工厂=rb3_scgc1,rev.rb3_cjyh==创建用户=rb3_cjyh,rev.rb3_ms=objectDesc=描述=rb3_ms"; + // + // String[] propertys = new String[]{s1,s2,s3,s4}; + // 获取首选项中配置的值 + String[] propertys = Utils.GetPrefValues("connorpi_cu_matconfig", true); + String itemProperty = ""; + // 遍历获取对象类型对应的属性 + for (int i = 0; i < propertys.length; i++) { + if (propertys[i].indexOf("-") > 0) { + String[] itemPropertys = propertys[i].split("-"); + if (objectType.compareTo(itemPropertys[0]) == 0) { + itemProperty = itemPropertys[1]; + break; + } + } + } + if (itemProperty == null || itemProperty.equals("")) { + closeByPass(connection); + Utils.setLog(logFileName, "getItemPropertys", "通过首选项connorpi_cu_matconfig未获取配置的要获取的属性"); + return JsonResult.error("通过首选项connorpi_cu_matconfig未获取配置的要获取的属性"); + } + Utils.setLog(logFileName, "getItemPropertys", "itemProperty:" + itemProperty); + + List propertyNameList = new ArrayList(); + List titleNameList = new ArrayList(); + List paiNameList = new ArrayList(); + List displayNameList = new ArrayList(); + + // 拆分首选项获取属性和标题 + if (itemProperty.indexOf(",") > 0) { + String[] propertyNames = itemProperty.split(","); + for (int i = 0; i < propertyNames.length; i++) { + // 获取属性位置和标题 + if (propertyNames[i].indexOf("=") > 0) { + String[] properties = propertyNames[i].split("="); + propertyNameList.add(properties[0]); + paiNameList.add(properties[1]); + displayNameList.add(properties[2]); + titleNameList.add(properties[3]); + } + } + } else { + // 获取属性位置和标题 + if (itemProperty.indexOf("=") > 0) { + String[] properties = itemProperty.split("="); + propertyNameList.add(properties[0]); + paiNameList.add(properties[1]); + displayNameList.add(properties[2]); + titleNameList.add(properties[3]); + } + } + + JSONArray resultJSONArray = new JSONArray(); + for (int i = 0; i < titleNameList.size(); i++) { + JSONObject resultJSONObject = new JSONObject(); + resultJSONObject.put("paiName", paiNameList.get(i)); + resultJSONObject.put("displayName", displayNameList.get(i)); + resultJSONObject.put("tcName", titleNameList.get(i)); + resultJSONObject.put( + "value", getItemPropertyValue(dmService, item, propertyNameList.get(i))); + resultJSONArray.add(resultJSONObject); + } + jsonObject.put("id", itemId); + jsonObject.put("data", resultJSONArray); + jsonArray.add(jsonObject); + } + closeByPass(connection); + return JsonResult.success(jsonArray); + } catch (Exception e) { + e.printStackTrace(); + return JsonResult.error(e.getMessage()); + } + } + + public static JsonResult getProjectItemPropertys(String logFileName, String uid) { + try { + Utils.setLog(logFileName, "getProjectItemProperty", "uid:" + uid); + com.teamcenter.soa.client.Connection connection = AppXSession.getConnection(); + DataManagementService dmService = DataManagementService.getService(connection); + ModelObject[] items = loadObjects(new String[] {uid}, dmService); + + if (items == null || items.length <= 0) { + Utils.setLog(logFileName, "getProjectItemProperty", "通过uid" + uid + "未获取到对象"); + return JsonResult.error("通过uid" + uid + "未获取到对象"); + } + + openByPass(connection); + ModelObject item = items[0]; + + // 获取产品下的物料 + dmService.getProperties(items, new String[] {"object_type"}); + String itemObjectType = item.getPropertyObject("object_type").getStringValue(); + Utils.setLog(logFileName, "getProjectItemProperty", "itemObjectType:" + itemObjectType); + if (!itemObjectType.equals("RB3_XMKFRevision")) { + Utils.setLog(logFileName, "getProjectItemProperty", "uid" + uid + "获取到的对象不是项目包"); + return JsonResult.error("uid" + uid + "获取到的对象不是项目包"); + } + dmService.getProperties(items, new String[] {"RB3_WLGX"}); + ModelObject[] materials = item.getPropertyObject("RB3_WLGX").getModelObjectArrayValue(); + ModelObject[] materialRevisions = new ModelObject[materials.length]; + for (int i = 0; i < materials.length; i++) { + materialRevisions[i] = Utils.GetLatestRev(dmService, (Item) materials[i]); + } + + // dmService.getProperties(materials, new String[] {"object_type"}); + + JSONObject jsonObject = new JSONObject(); + JSONArray resultJSONArray = new JSONArray(); + + // String[] propertys = new + // String[]{"item_id=id=001=item_id,object_name=名称=002=object_name,item_revision_id=版本=003=item_revision_id,rb3_cph=产品号=004=rb3_cph,rb3_th=设计图号=005=rb3_th,rb3_jwlh=旧物料号=006=rb3_jwlh,rb3_zl=重量(kg)=007=rb3_zl,rb3_scgc1=生产工厂=008=rb3_scgc1,rb3_smzqzt=生命周期状态=009=rb3_smzqzt"}; + // 获取首选项中配置的值 + String[] propertys = Utils.GetPrefValues("connorpi_cu_matsumconfig", true); + if (propertys == null || propertys.length <= 0) { + closeByPass(connection); + Utils.setLog( + logFileName, "getProjectItemProperty", "通过首选项connorpi_cu_matsumconfig未获取配置的要获取的属性"); + return JsonResult.error("通过首选项connorpi_cu_matsumconfig未获取配置的要获取的属性"); + } + String itemProperty = propertys[0]; + Utils.setLog(logFileName, "getProjectItemProperty", "itemProperty:" + itemProperty); + // + // // 遍历获取对象类型对应的属性 + // for (int i = 0; i < propertys.length; i++) { + // if (propertys[i].indexOf("-") > 0) { + // String[] itemPropertys = propertys[i].split("-"); + // if (objectType.compareTo(itemPropertys[0]) == 0) { + // itemProperty = itemPropertys[1]; + // break; + // } + // } + // } + if (itemProperty == null || itemProperty.equals("")) { + closeByPass(connection); + Utils.setLog( + logFileName, "getProjectItemProperty", "通过首选项connorpi_cu_matsumconfig获取配置的要获取的属性为空"); + return JsonResult.error("通过首选项connorpi_cu_matconfig未获取配置的要获取的属性"); + } + + List propertyNameList = new ArrayList(); + List titleNameList = new ArrayList(); + JSONArray titleJSONArray = new JSONArray(); + // 拆分首选项获取属性和标题 + if (itemProperty.indexOf(",") > 0) { + String[] propertyNames = itemProperty.split(","); + for (int i = 0; i < propertyNames.length; i++) { + // 获取属性位置和标题 + if (propertyNames[i].indexOf("=") > 0) { + String[] properties = propertyNames[i].split("="); + JSONObject titleJSONObject = new JSONObject(); + titleJSONObject.put("name", properties[3]); + titleJSONObject.put("displayName", properties[1]); + titleJSONObject.put("order", properties[2]); + titleJSONArray.add(titleJSONObject); + propertyNameList.add(properties[0]); + titleNameList.add(properties[3]); + } + } + } else { + // 获取属性位置和标题 + if (itemProperty.indexOf("=") > 0) { + String[] properties = itemProperty.split("="); + JSONObject titleJSONObject = new JSONObject(); + titleJSONObject.put("name", properties[3]); + titleJSONObject.put("displayName", properties[1]); + titleJSONObject.put("order", properties[2]); + titleJSONArray.add(titleJSONObject); + propertyNameList.add(properties[0]); + titleNameList.add(properties[3]); + } + } + + dmService.getProperties( + materialRevisions, propertyNameList.toArray(new String[propertyNameList.size()])); + for (int ii = 0; ii < materialRevisions.length; ii++) { + ModelObject materialRevision = materialRevisions[ii]; + // 获取对象类型 + // String objectType = item.getPropertyObject("object_type").getStringValue(); + + JSONObject resultJSONObject = new JSONObject(); + for (int i = 0; i < titleNameList.size(); i++) { + String value = materialRevision.getPropertyDisplayableValue(propertyNameList.get(i)); + resultJSONObject.put(titleNameList.get(i), value); + } + resultJSONArray.add(resultJSONObject); + + closeByPass(connection); + } + jsonObject.put("title", titleJSONArray); + jsonObject.put("data", resultJSONArray); + return JsonResult.success(jsonObject); + } catch (Exception e) { + e.printStackTrace(); + return JsonResult.error(e.getMessage()); + } + } +} diff --git a/src/main/java/com/pjb/springbootjjwt/service/TokenService.java b/src/main/java/com/pjb/springbootjjwt/service/TokenService.java new file mode 100644 index 0000000..ebaec43 --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/service/TokenService.java @@ -0,0 +1,19 @@ +package com.pjb.springbootjjwt.service; + +import com.auth0.jwt.JWT; +import com.auth0.jwt.algorithms.Algorithm; +import com.pjb.springbootjjwt.entity.User; +import org.springframework.stereotype.Service; + + + +@Service("TokenService") +public class TokenService { + public String getToken(User user) { + String token=""; + token= JWT.create().withAudience(user.getApp_secret())// 将 user id 保存到 token 里面 + .sign(Algorithm.HMAC256(user.getPassword()));// 以 password 作为 token 的密钥 + System.out.printf("+++++++++++++++++++++++"+token+"+++++++++++++++++++++++"); + return token; + } +} diff --git a/src/main/java/com/pjb/springbootjjwt/service/UserService.java b/src/main/java/com/pjb/springbootjjwt/service/UserService.java new file mode 100644 index 0000000..5bbf695 --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/service/UserService.java @@ -0,0 +1,23 @@ +package com.pjb.springbootjjwt.service; + +import com.pjb.springbootjjwt.entity.User; +import com.pjb.springbootjjwt.mapper.UserMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + + +@Service("UserService") +public class UserService { + @Autowired + UserMapper userMapper; + public User findByUsername(String username){ + return userMapper.findByUsername(username); + } + public User findByUsernameAndId(User user){ + return userMapper.findByUsernameAndId(user.getUsername(),user.getApp_secret()); + } + public User findUserById(String userId) { + return userMapper.findUserById(userId); + } + +} diff --git a/src/main/java/com/pjb/springbootjjwt/test/Test.java b/src/main/java/com/pjb/springbootjjwt/test/Test.java new file mode 100644 index 0000000..afbd675 --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/test/Test.java @@ -0,0 +1,133 @@ +package com.pjb.springbootjjwt.test; + +import com.alibaba.fastjson.JSONObject; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.util.HashMap; +import java.util.Map; + +public class Test { + public static String result(String info) { + //接口地址 + String requestUrl = "http://localhost:9292/oaGetDeliveryFile"; + //params用于存储要请求的参数 + Map params = new HashMap(); + //showapi_appid的值,把###替换成你的appid + params.put("deliveryId","000730"); + params.put("deliberyRevision","A"); +// //我们请求的字符串 +// params.put("task_name",info); +// params.put("user_id","user1"); + //调用httpRequest方法,这个方法主要用于请求地址,并加上请求参数 + String string = httpRequest(requestUrl,params); + //处理返回的JSON数据并返回 + //JSONObject pageBean = JSONObject.fromObject(string).getJSONObject("showapi_res_body"); + JSONObject json1=JSONObject.parseObject(string); + return json1.getString("success"); + } + public static void retureDelivery(){ + + } + private static String httpRequest(String requestUrl,Map params) { + //buffer用于接受返回的字符 + StringBuffer buffer = new StringBuffer(); + try { + //建立URL,把请求地址给补全,其中urlencode()方法用于把params里的参数给取出来 + URL url = new URL(requestUrl+"?"+urlencode(params)); + //打开http连接 + HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection(); + httpUrlConn.setDoInput(true); + httpUrlConn.setRequestProperty("access_token","eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxIn0.dQMt-whQl9DmFOo-JIupTPRKZkApwBhUjSvIRuZ9lF8"); + httpUrlConn.setRequestMethod("POST"); + httpUrlConn.connect(); + + //获得输入 + InputStream inputStream = httpUrlConn.getInputStream(); + InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); + BufferedReader bufferedReader = new BufferedReader(inputStreamReader); + + //将bufferReader的值给放到buffer里 + String str = null; + while ((str = bufferedReader.readLine()) != null) { + buffer.append(str); + } + //关闭bufferReader和输入流 + bufferedReader.close(); + inputStreamReader.close(); + inputStream.close(); + inputStream = null; + //断开连接 + httpUrlConn.disconnect(); + + } catch (Exception e) { + e.printStackTrace(); + } + //返回字符串 + return buffer.toString(); + } + + public static String urlencode(Mapdata) { + //将map里的参数变成像 showapi_appid=###&showapi_sign=###&的样子 + StringBuilder sb = new StringBuilder(); + for (Map.Entry i : data.entrySet()) { + try { + sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + } + return sb.toString(); + } + //测试是否有效 + public static void main(String[] args) { + String user_id = "[admin]"; + user_id = user_id.substring(1,user_id.length()-1); + user_id = user_id.split(",")[0]; + System.out.println(user_id); + + + + //System.out.println(result("你好啊")); + } +} +// com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct prop = new com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct(); +// prop.stringVec = new String[]{"user1"}; +// HashMap objectPropMap = new HashMap(); +// //put that property into map....... +// //objectPropMap.put("fnd0Performer", prop); +// //objectPropMap.put("fnd0Assignee", prop); +// objectPropMap.put("resp_party", prop); +// //Call dmservice and set the properties..... +// DataManagementService dmService = DataManagementService.getService( AppXSession.getConnection()); +// +//// Session.StateNameValue[] propPairs = new Session.StateNameValue[]{new Session.StateNameValue()}; +//// //propPairs = new StateNameValue(); +//// propPairs[0].name = new String("bypassFlag"); +//// propPairs[0].value = new String(Property.toBooleanString( true )); +//// com.teamcenter.soa.client.model.ServiceData serviceData= SessionService.getService(AppXSession.getConnection()).setUserSessionState(propPairs); +//// +//// +//// AppXSession.getConnection().setOption("bypassFlag", Property.toBooleanString(true)); +// com.teamcenter.services.loose.core.SessionService sessionservice = com.teamcenter.services.loose.core.SessionService +// +// .getService(AppXSession.getConnection()); +// +// com.teamcenter.services.loose.core._2007_12.Session.StateNameValue astatenamevalue[] = new com.teamcenter.services.loose.core._2007_12.Session.StateNameValue[1]; +// +// astatenamevalue[0] = new com.teamcenter.services.loose.core._2007_12.Session.StateNameValue(); +// +// astatenamevalue[0].name = "bypassFlag"; +// +// astatenamevalue[0].value = Property.toBooleanString(true); +// +// com.teamcenter.soa.client.model.ServiceData servicedata = sessionservice.setUserSessionState(astatenamevalue); + +// dmService.setProperties(targetObject, objectPropMap ); +// +// dmService.refreshObjects(targetObject); \ No newline at end of file diff --git a/src/main/java/com/pjb/springbootjjwt/test/TestCreateDataset.java b/src/main/java/com/pjb/springbootjjwt/test/TestCreateDataset.java new file mode 100644 index 0000000..fbd4b1e --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/test/TestCreateDataset.java @@ -0,0 +1,28 @@ +package com.pjb.springbootjjwt.test; + +import com.teamcenter.clientx.AppXSession; +import com.teamcenter.soa.client.model.strong.User; + +import java.util.Date; + +public class TestCreateDataset { + private static AppXSession tcSession; + private static User tcUser; + + public static void main(String[] args) { + Date date = new Date(); + long longDate = date.getTime(); + if(tcSession == null){ + tcSession = new AppXSession("http://192.168.211.248:7001/tc"); + } + try{ + if(tcUser == null) { + tcUser = tcSession.login("admin","admin123"); + } + + }catch (Exception ex){ + ex.printStackTrace(); + } + System.out.println(); + } +} diff --git a/src/main/java/com/pjb/springbootjjwt/test/TestCreateItem.java b/src/main/java/com/pjb/springbootjjwt/test/TestCreateItem.java new file mode 100644 index 0000000..6f05633 --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/test/TestCreateItem.java @@ -0,0 +1,56 @@ +package com.pjb.springbootjjwt.test; + +import com.pjb.springbootjjwt.SpringbootJjwtApplication; +import com.teamcenter.clientx.AppXSession; +import com.teamcenter.services.strong.core.DataManagementService; +import com.teamcenter.services.strong.core._2006_03.DataManagement; +import com.teamcenter.soa.client.model.ModelObject; +import com.teamcenter.soa.client.model.ServiceData; +import com.teamcenter.soa.client.model.strong.User; +import org.springframework.boot.SpringApplication; +import org.springframework.context.ConfigurableApplicationContext; + +import java.util.Date; + +public class TestCreateItem { + + private static AppXSession tcSession; + private static User tcUser; + + public static void main(String[] args) { + Date date = new Date(); + long longDate = date.getTime(); + if(tcSession == null){ + tcSession = new AppXSession("http://plmserver:7001/tc"); + } + try{ + if(tcUser == null) { + tcUser = tcSession.login("admin","admin"); + } + + }catch (Exception ex){ + ex.printStackTrace(); + } + + DataManagementService dataManagementService = DataManagementService.getService(AppXSession.getConnection()); + +// ServiceData serviceData = dataManagementService.loadObjects(new String[]{"RNnFXMpYJVbx3A"}); +// ModelObject modelObject = serviceData.getPlainObject(0); +// dataManagementService.deleteObjects(new ModelObject[]{modelObject}); + + + + DataManagement.ItemProperties itemProperties = new DataManagement.ItemProperties(); + + itemProperties.itemId=String.valueOf(longDate); + itemProperties.name="tempItem"; + itemProperties.type = "Item"; + DataManagement.CreateItemsResponse itemsResponse = dataManagementService.createItems(new DataManagement.ItemProperties[]{itemProperties},null,""); + + dataManagementService.deleteObjects(new ModelObject[]{itemsResponse.output[0].item}); + + System.out.println(); + //dataManagementService.deleteObjects(new ModelObject[]{dataManagementService.loadObjects(new String[]{"h4sFXMpYJVbx3A"}).getPlainObject(0)}); + } + +} diff --git a/src/main/java/com/pjb/springbootjjwt/test/TestCreateWorkFlow.java b/src/main/java/com/pjb/springbootjjwt/test/TestCreateWorkFlow.java new file mode 100644 index 0000000..2e533fe --- /dev/null +++ b/src/main/java/com/pjb/springbootjjwt/test/TestCreateWorkFlow.java @@ -0,0 +1,31 @@ +package com.pjb.springbootjjwt.test; + +import com.teamcenter.clientx.AppXSession; +import com.teamcenter.clientx.Utils; +import com.teamcenter.soa.client.model.ModelObject; +import com.teamcenter.soa.client.model.strong.User; + +public class TestCreateWorkFlow { + private static AppXSession tcSession; + private static User tcUser; + public static void main(String[] args) { + + if(tcSession == null){ + tcSession = new AppXSession("http://plmserver:7001/tc"); + } + try{ + if(tcUser == null) { + tcUser = tcSession.login("admin","admin"); + } + + }catch (Exception ex){ + ex.printStackTrace(); + } + //Utils.findUser(AppXSession.getConnection(),"zc"); + try { + //Utils.changeOwnershipModelObject(AppXSession.getConnection(),"zc",""); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/com/teamcenter/clientx/AppXCredentialManager.java b/src/main/java/com/teamcenter/clientx/AppXCredentialManager.java new file mode 100644 index 0000000..28d51b4 --- /dev/null +++ b/src/main/java/com/teamcenter/clientx/AppXCredentialManager.java @@ -0,0 +1,143 @@ +//================================================== +// +// Copyright 2012 Siemens Product Lifecycle Management Software Inc. All Rights Reserved. +// +//================================================== + +package com.teamcenter.clientx; + +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.LineNumberReader; + +import com.teamcenter.schemas.soa._2006_03.exceptions.InvalidCredentialsException; +import com.teamcenter.schemas.soa._2006_03.exceptions.InvalidUserException; +import com.teamcenter.soa.client.CredentialManager; +import com.teamcenter.soa.exceptions.CanceledOperationException; + +/** + * The CredentialManager is used by the Teamcenter Services framework to get the + * user's credentials when challenged by the server. This can occur after a period + * of inactivity and the server has timed-out the user's session, at which time + * the client application will need to re-authenticate. The framework will + * call one of the getCredentials methods (depending on circumstances) and will + * send the SessionService.login service request. Upon successful completion of + * the login service request. The last service request (one that caused the challenge) + * will be resent. + * + * The framework will also call the setUserPassword setGroupRole methods when ever + * these credentials change, thus allowing this implementation of the CredentialManager + * to cache these values so prompting of the user is not required for re-authentication. + * + */ +public class AppXCredentialManager implements CredentialManager +{ + + private String name = null; + private String password = null; + private String group = ""; // default group + private String role = ""; // default role + private String discriminator = "SoaAppX"; // always connect same user + // to same instance of server + + /** + * Return the type of credentials this implementation provides, + * standard (user/password) or Single-Sign-On. In this case + * Standard credentials are returned. + * + * @see CredentialManager#getCredentialType() + */ + public int getCredentialType() + { + return CredentialManager.CLIENT_CREDENTIAL_TYPE_STD; + } + + /** + * Prompt's the user for credentials. + * This method will only be called by the framework when a login attempt has + * failed. + * + * @see CredentialManager#getCredentials(InvalidCredentialsException) + */ + public String[] getCredentials(InvalidCredentialsException e) + throws CanceledOperationException + { + System.out.println(e.getMessage()); + return promptForCredentials(); + } + + /** + * Return the cached credentials. + * This method will be called when a service request is sent without a valid + * session ( session has expired on the server). + * + * @see CredentialManager#getCredentials(InvalidUserException) + */ + public String[] getCredentials(InvalidUserException e) + throws CanceledOperationException + { + // Have not logged in yet, should not happen but just in case + if (name == null) return promptForCredentials(); + + // Return cached credentials + String[] tokens = { name, password, group, role, discriminator }; + return tokens; + } + + /** + * Cache the group and role + * This is called after the SessionService.setSessionGroupMember service + * operation is called. + * + * @see CredentialManager#setGroupRole(String, + * String) + */ + public void setGroupRole(String group, String role) + { + this.group = group; + this.role = role; + } + + /** + * Cache the User and Password + * This is called after the SessionService.login service operation is called. + * + * @see CredentialManager#setUserPassword(String, + * String, String) + */ + public void setUserPassword(String user, String password, String discriminator) + { + this.name = user; + this.password = password; + this.discriminator = discriminator; + } + + + public String[] promptForCredentials() + throws CanceledOperationException + { + try + { + LineNumberReader reader = new LineNumberReader(new InputStreamReader(System.in)); + System.out.println("Please enter user credentials (return to quit):"); + System.out.print("User Name: "); + name = reader.readLine(); + + if (name.length() == 0) + throw new CanceledOperationException(""); + + System.out.print("Password: "); + password = reader.readLine(); + } + catch (IOException e) + { + String message = "Failed to get the name and password.\n" + e.getMessage(); + System.out.println(message); + throw new CanceledOperationException(message); + } + + String[] tokens = { name, password, group, role, discriminator }; + return tokens; + } + +} diff --git a/src/main/java/com/teamcenter/clientx/AppXExceptionHandler.java b/src/main/java/com/teamcenter/clientx/AppXExceptionHandler.java new file mode 100644 index 0000000..5aed562 --- /dev/null +++ b/src/main/java/com/teamcenter/clientx/AppXExceptionHandler.java @@ -0,0 +1,102 @@ +//================================================== +// +// Copyright 2012 Siemens Product Lifecycle Management Software Inc. All Rights Reserved. +// +//================================================== + +package com.teamcenter.clientx; + +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.LineNumberReader; + +import com.teamcenter.schemas.soa._2006_03.exceptions.ConnectionException; +import com.teamcenter.schemas.soa._2006_03.exceptions.InternalServerException; +import com.teamcenter.schemas.soa._2006_03.exceptions.ProtocolException; +import com.teamcenter.soa.client.ExceptionHandler; +import com.teamcenter.soa.exceptions.CanceledOperationException; + +/** + * Implementation of the ExceptionHandler. For ConnectionExceptions (server + * temporarily down .etc) prompts the user to retry the last request. For other + * exceptions convert to a RunTime exception. + */ +public class AppXExceptionHandler implements ExceptionHandler +{ + + /* + * (non-Javadoc) + * + * @see com.teamcenter.soa.client.ExceptionHandler#handleException(com.teamcenter.schemas.soa._2006_03.exceptions.InternalServerException) + */ + public void handleException(InternalServerException ise) + { + System.out.println(""); + System.out.println("*****"); + System.out + .println("Exception caught in com.teamcenter.clientx.AppXExceptionHandler.handleException(InternalServerException)."); + + LineNumberReader reader = new LineNumberReader(new InputStreamReader(System.in)); + + if (ise instanceof ConnectionException) + { + // ConnectionException are typically due to a network error (server + // down .etc) and can be recovered from (the last request can be sent again, + // after the problem is corrected). + System.out.print("\nThe server returned an connection error.\n" + ise.getMessage() + + "\nDo you wish to retry the last service request?[y/n]"); + } + else + if (ise instanceof ProtocolException) + { + // ProtocolException are typically due to programming errors + // (content of HTTP + // request is incorrect). These are generally can not be + // recovered from. + System.out.print("\nThe server returned an protocol error.\n" + ise.getMessage() + + "\nThis is most likely the result of a programming error." + + "\nDo you wish to retry the last service request?[y/n]"); + } + else + { + System.out.println("\nThe server returned an internal server error.\n" + + ise.getMessage() + + "\nThis is most likely the result of a programming error." + + "\nA RuntimeException will be thrown."); + throw new RuntimeException(ise.getMessage()); + } + + try + { + String retry = reader.readLine(); + // If yes, return to the calling SOA client framework, where the + // last service request will be resent. + if (retry.equalsIgnoreCase("y") || retry.equalsIgnoreCase("yes")) return; + + throw new RuntimeException("The user has opted not to retry the last request"); + } + catch (IOException e) + { + System.err.println("Failed to read user response.\nA RuntimeException will be thrown."); + throw new RuntimeException(e.getMessage()); + } + } + + /* + * (non-Javadoc) + * + * @see com.teamcenter.soa.client.ExceptionHandler#handleException(com.teamcenter.soa.exceptions.CanceledOperationException) + */ + public void handleException(CanceledOperationException coe) + { + System.out.println(""); + System.out.println("*****"); + System.out.println("Exception caught in com.teamcenter.clientx.AppXExceptionHandler.handleException(CanceledOperationException)."); + + // Expecting this from the login tests with bad credentials, and the + // AnyUserCredentials class not + // prompting for different credentials + throw new RuntimeException(coe); + } + +} diff --git a/src/main/java/com/teamcenter/clientx/AppXModelEventListener.java b/src/main/java/com/teamcenter/clientx/AppXModelEventListener.java new file mode 100644 index 0000000..93aff59 --- /dev/null +++ b/src/main/java/com/teamcenter/clientx/AppXModelEventListener.java @@ -0,0 +1,64 @@ +//================================================== +// +// Copyright 2012 Siemens Product Lifecycle Management Software Inc. All Rights Reserved. +// +//================================================== + +package com.teamcenter.clientx; + + +import com.teamcenter.soa.client.model.ModelEventListener; +import com.teamcenter.soa.client.model.ModelObject; +import com.teamcenter.soa.exceptions.NotLoadedException; + +/** + * Implementation of the ChangeListener. Print out all objects that have been updated. + * + */ +public class AppXModelEventListener extends ModelEventListener +{ + + @Override + public void localObjectChange(ModelObject[] objects) + { + + if (objects.length == 0) return; + System.out.println(""); + System.out.println("Modified Objects handled in com.teamcenter.clientx.AppXUpdateObjectListener.modelObjectChange"); + System.out.println("The following objects have been updated in the client data model:"); + for (int i = 0; i < objects.length; i++) + { + String uid = objects[i].getUid(); + String type = objects[i].getTypeObject().getName(); + String name = ""; + if (objects[i].getTypeObject().isInstanceOf("WorkspaceObject")) + { + ModelObject wo = objects[i]; + try + { + name = wo.getPropertyObject("object_string").getStringValue(); + } + catch (NotLoadedException e) {} // just ignore + } + System.out.println(" " + uid + " " + type + " " + name); + } + } + + @Override + public void localObjectDelete(String[] uids) + { + + if (uids.length == 0) + return; + + System.out.println(""); + System.out.println("Deleted Objects handled in com.teamcenter.clientx.AppXDeletedObjectListener.modelObjectDelete"); + System.out.println("The following objects have been deleted from the server and removed from the client data model:"); + for (int i = 0; i < uids.length; i++) + { + System.out.println(" " + uids[i]); + } + + } + +} diff --git a/src/main/java/com/teamcenter/clientx/AppXPartialErrorListener.java b/src/main/java/com/teamcenter/clientx/AppXPartialErrorListener.java new file mode 100644 index 0000000..7ea6fd7 --- /dev/null +++ b/src/main/java/com/teamcenter/clientx/AppXPartialErrorListener.java @@ -0,0 +1,61 @@ +//================================================== +// +// Copyright 2012 Siemens Product Lifecycle Management Software Inc. All Rights Reserved. +// +//================================================== + + +package com.teamcenter.clientx; + +import com.teamcenter.soa.client.model.ErrorStack; +import com.teamcenter.soa.client.model.ErrorValue; +import com.teamcenter.soa.client.model.PartialErrorListener; + +/** + * Implementation of the PartialErrorListener. Print out any partial errors + * returned. + * + */ +public class AppXPartialErrorListener implements PartialErrorListener +{ + + @Override + public void handlePartialError(ErrorStack[] stacks) + { + if (stacks.length == 0) return; + + System.out.println(""); + System.out.println("*****"); + System.out.println("Partial Errors caught in com.teamcenter.clientx.AppXPartialErrorListener."); + + + for (int i = 0; i < stacks.length; i++) + { + ErrorValue[] errors = stacks[i].getErrorValues(); + System.out.print("Partial Error for "); + + // The different service implementation may optionally associate + // an ModelObject, client ID, or nothing, with each partial error + if (stacks[i].hasAssociatedObject()) + { + System.out.println( "object " + stacks[i].getAssociatedObject().getUid() ); + } + else if (stacks[i].hasClientId()) + { + System.out.println( "client id " + stacks[i].getClientId() ); + } + else if (stacks[i].hasClientIndex()) + System.out.println( "client index " + stacks[i].getClientIndex() ); + + + // Each Partial Error will have one or more contributing error messages + for (int j = 0; j < errors.length; j++) + { + System.out.println(" Code: " + errors[j].getCode() + "\tSeverity: " + + errors[j].getLevel() + "\t" + errors[j].getMessage()); + } + } + + } + +} diff --git a/src/main/java/com/teamcenter/clientx/AppXRequestListener.java b/src/main/java/com/teamcenter/clientx/AppXRequestListener.java new file mode 100644 index 0000000..a44def0 --- /dev/null +++ b/src/main/java/com/teamcenter/clientx/AppXRequestListener.java @@ -0,0 +1,36 @@ +//================================================== +// +// Copyright 2012 Siemens Product Lifecycle Management Software Inc. All Rights Reserved. +// +//================================================== + +package com.teamcenter.clientx; + +import com.teamcenter.soa.client.RequestListener; + +/** + * This implementation of the RequestListener, logs each service request + * to the console. + * + */ +public class AppXRequestListener implements RequestListener +{ + + /** + * Called before each request is sent to the server. + */ + public void serviceRequest ( final Info info ) + { + // will log the service name when done + } + + /** + * Called after each response from the server. + * Log the service operation to the console. + */ + public void serviceResponse( final Info info ) + { + System.out.println( info.id +": "+info.service+"."+info.operation); + } + +} diff --git a/src/main/java/com/teamcenter/clientx/AppXSession.java b/src/main/java/com/teamcenter/clientx/AppXSession.java new file mode 100644 index 0000000..0a59243 --- /dev/null +++ b/src/main/java/com/teamcenter/clientx/AppXSession.java @@ -0,0 +1,298 @@ +//================================================== +// +// Copyright 2012 Siemens Product Lifecycle Management Software Inc. All Rights Reserved. +// +//================================================== + +package com.teamcenter.clientx; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.List; +import java.util.Locale; +import java.util.Vector; + + + +import com.teamcenter.schemas.soa._2006_03.exceptions.InvalidCredentialsException; +import com.teamcenter.schemas.soa._2006_03.exceptions.ServiceException; +import com.teamcenter.services.strong.core.DataManagementService; +import com.teamcenter.services.strong.core.SessionService; +import com.teamcenter.services.strong.core._2006_03.Session.LoginResponse; +import com.teamcenter.soa.SoaConstants; +import com.teamcenter.soa.client.Connection; +import com.teamcenter.soa.client.model.ModelObject; +import com.teamcenter.soa.client.model.strong.User; +import com.teamcenter.soa.client.model.strong.WorkspaceObject; +import com.teamcenter.soa.exceptions.CanceledOperationException; +import com.teamcenter.soa.exceptions.NotLoadedException; + + +public class AppXSession +{ + /** + * Single instance of the Connection object that is shared throughout + * the application. This Connection object is needed whenever a Service + * stub is instantiated. + */ + private static Connection connection; + + /** + * The credentialManager is used both by the Session class and the Teamcenter + * Services Framework to get user credentials. + * + */ + private static AppXCredentialManager credentialManager; + + /** + * Create an instance of the Session with a connection to the specified + * server. + * + * Add implementations of the ExceptionHandler, PartialErrorListener, + * ChangeListener, and DeleteListeners. + * + * @param host Address of the host to connect to, http://serverName:port/tc + */ + public AppXSession(String host) + { + // Create an instance of the CredentialManager, this is used + // by the SOA Framework to get the user's credentials when + // challenged by the server (session timeout on the web tier). + credentialManager = new AppXCredentialManager(); + + String protocol=null; + String envNameTccs = null; + if ( host.startsWith("http") ) + { + protocol = SoaConstants.HTTP; + } + else if ( host.startsWith("tccs") ) + { + protocol = SoaConstants.TCCS; + host = host.trim(); + int envNameStart = host.indexOf('/') + 2; + envNameTccs = host.substring( envNameStart, host.length() ); + host = ""; + } + else + { + protocol = SoaConstants.IIOP; + } + + + // Create the Connection object, no contact is made with the server + // until a service request is made + connection = new Connection(host, credentialManager, SoaConstants.REST, protocol); + + if( protocol == SoaConstants.TCCS ) + { + connection.setOption( Connection.TCCS_ENV_NAME, envNameTccs ); + } + + + // Add an ExceptionHandler to the Connection, this will handle any + // InternalServerException, communication errors, XML marshaling errors + // .etc + connection.setExceptionHandler(new AppXExceptionHandler()); + + // While the above ExceptionHandler is required, all of the following + // Listeners are optional. Client application can add as many or as few Listeners + // of each type that they want. + + // Add a Partial Error Listener, this will be notified when ever a + // a service returns partial errors. + connection.getModelManager().addPartialErrorListener(new AppXPartialErrorListener()); + + // Add a Change and Delete Listener, this will be notified when ever a + // a service returns model objects that have been updated or deleted. + connection.getModelManager().addModelEventListener(new AppXModelEventListener()); + + + // Add a Request Listener, this will be notified before and after each + // service request is sent to the server. + Connection.addRequestListener( new AppXRequestListener() ); + + } + + /** + * Get the single Connection object for the application + * + * @return connection + */ + public static Connection getConnection() + { + return connection; + } + + + public User login(String userName,String pwd) + { + // Get the service stub + SessionService sessionService = SessionService.getService(connection); + + + try + { + + // ***************************** + // Execute the service operation + // ***************************** + LoginResponse out = sessionService.login(userName, pwd, + "", "","", ""); + + + return out.user; + } + catch (InvalidCredentialsException e) + { + e.printStackTrace(); + } + + + return null; + } + + /** + * Login to the Teamcenter Server + * + */ + public User login() + { + // Get the service stub + SessionService sessionService = SessionService.getService(connection); + + try + { + // Prompt for credentials until they are right, or until user + // cancels + String[] credentials = credentialManager.promptForCredentials(); + while (true) + { + try + { + + // ***************************** + // Execute the service operation + // ***************************** + LoginResponse out = sessionService.login(credentials[0], credentials[1], + credentials[2], credentials[3],"", credentials[4]); + + return out.user; + } + catch (InvalidCredentialsException e) + { + credentials = credentialManager.getCredentials(e); + } + } + } + // User canceled the operation, don't need to tell him again + catch (CanceledOperationException e) {} + + // Exit the application + System.exit(0); + return null; + } + + /** + * Terminate the session with the Teamcenter Server + * + */ + public void logout() + { + // Get the service stub + SessionService sessionService = SessionService.getService(connection); + try + { + // ***************************** + // Execute the service operation + // ***************************** + sessionService.logout(); + } + catch (ServiceException e){} + } + + /** + * Print some basic information for a list of objects + * + * @param objects + */ + public static void printObjects(ModelObject[] objects) + { + if(objects == null) + return; + + SimpleDateFormat format = new SimpleDateFormat("M/d/yyyy h:mm a", new Locale("en", "US")); // Simple no time zone + + // Ensure that the referenced User objects that we will use below are loaded + getUsers( objects ); + + System.out.println("Name\t\tOwner\t\tLast Modified"); + System.out.println("====\t\t=====\t\t============="); + for (int i = 0; i < objects.length; i++) + { + if(!(objects[i] instanceof WorkspaceObject )) + continue; + + WorkspaceObject wo = (WorkspaceObject)objects[i]; + try + { + String name = wo.get_object_string(); + User owner = (User) wo.get_owning_user(); + Calendar lastModified =wo.get_last_mod_date(); + + System.out.println(name + "\t" + owner.get_user_name() + "\t" + + format.format(lastModified.getTime())); + } + catch (NotLoadedException e) + { + // Print out a message, and skip to the next item in the folder + // Could do a DataManagementService.getProperties call at this point + System.out.println(e.getMessage()); + System.out.println("The Object Property Policy ($TC_DATA/soa/policies/Default.xml) is not configured with this property."); + } + } + + } + + + private static void getUsers( ModelObject[] objects ) + { + if(objects == null) + return; + + DataManagementService dmService = DataManagementService.getService(AppXSession.getConnection()); + + List unKnownUsers = new Vector(); + for (int i = 0; i < objects.length; i++) + { + if(!(objects[i] instanceof WorkspaceObject )) + continue; + + WorkspaceObject wo = (WorkspaceObject)objects[i]; + + User owner = null; + try + { + owner = (User) wo.get_owning_user(); + owner.get_user_name(); + } + catch (NotLoadedException e) + { + if(owner != null) + unKnownUsers.add(owner); + } + } + User[] users = (User[])unKnownUsers.toArray(new User[unKnownUsers.size()]); + String[] attributes = { "user_name" }; + + + // ***************************** + // Execute the service operation + // ***************************** + dmService.getProperties(users, attributes); + + + } + + +} diff --git a/src/main/java/com/teamcenter/clientx/Query.java b/src/main/java/com/teamcenter/clientx/Query.java new file mode 100644 index 0000000..fa06b49 --- /dev/null +++ b/src/main/java/com/teamcenter/clientx/Query.java @@ -0,0 +1,133 @@ +//================================================== +// +// Copyright 2017 Siemens Product Lifecycle Management Software Inc. All Rights Reserved. +// +//================================================== + +package com.teamcenter.clientx; + + + import com.teamcenter.schemas.soa._2006_03.exceptions.ServiceException; + import com.teamcenter.services.strong.core.DataManagementService; + import com.teamcenter.services.strong.query.SavedQueryService; + import com.teamcenter.services.strong.query._2006_03.SavedQuery.GetSavedQueriesResponse; + import com.teamcenter.services.strong.query._2007_09.SavedQuery.QueryResults; + import com.teamcenter.services.strong.query._2007_09.SavedQuery.SavedQueriesResponse; + import com.teamcenter.services.strong.query._2008_06.SavedQuery.QueryInput; + import com.teamcenter.soa.client.model.ModelObject; + import com.teamcenter.soa.client.model.ServiceData; + import com.teamcenter.soa.client.model.strong.ImanQuery; + + +public class Query +{ + + /** + * Perform a simple query of the database + * + */ + public static ModelObject[] queryItems(String queryName ,String[] entries, String[] values) + { + + ImanQuery query = null; + + // Get the service stub. + SavedQueryService queryService = SavedQueryService.getService(AppXSession.getConnection()); + DataManagementService dmService= DataManagementService.getService(AppXSession.getConnection()); + try + { + + // ***************************** + // Execute the service operation + // ***************************** + GetSavedQueriesResponse savedQueries = queryService.getSavedQueries(); + + + if (savedQueries.queries.length == 0) + { + System.out.println("There are no saved queries in the system."); + return null; + } + + // Find one called 'Item Name' + for (int i = 0; i < savedQueries.queries.length; i++) + { + + if (savedQueries.queries[i].name.equals(queryName)) + { + query = savedQueries.queries[i].query; + break; + } + } + } + catch (ServiceException e) + { + System.out.println("GetSavedQueries service request failed."); + System.out.println(e.getMessage()); + return null; + } + + if (query == null) + { + System.out.println("There is not an 'Item Name' query."); + return null; + } + ModelObject[] foundObjs = new ModelObject[0]; + try + { + //Search for all Items, returning a maximum of 25 objects + QueryInput savedQueryInput[] = new QueryInput[1]; + savedQueryInput[0] = new QueryInput(); + savedQueryInput[0].query = query; + //savedQueryInput[0].maxNumToReturn = 25; + //savedQueryInput[0].limitList = new ModelObject[0]; + savedQueryInput[0].entries = entries; + savedQueryInput[0].values = values; + + + //***************************** + //Execute the service operation + //***************************** + SavedQueriesResponse savedQueryResult = queryService.executeSavedQueries(savedQueryInput); + QueryResults found = savedQueryResult.arrayOfResults[0]; + + //System.out.println(""); + //System.out.println("Found Items:"); + + // Page through the results 10 at a time + String[] uids = new String[found.objectUIDS.length]; + for(int i=0; i< found.objectUIDS.length; i++) + { + //int pageSize = (i+10String user represent User ID + public static ModelObject findUser(String user) { + + ImanQuery query = null; + + // SavedQueryService class is in package com.teamcenter.services.strong.query + SavedQueryService queryService = SavedQueryService.getService(AppXSession.getConnection()); + try { + SavedQuery.GetSavedQueriesResponse savedQueries = queryService.getSavedQueries(); + if (savedQueries.queries.length == 0) { + return null; + } + for (int i = 0; i < savedQueries.queries.length; i++) { + // __WEB_find_user -> Query in Query builder to find the user + if (savedQueries.queries[i].name.equals("__WEB_find_user")) { + query = savedQueries.queries[i].query; + break; + } + } + + } catch (ServiceException e) { + System.out.println(e.getMessage()); + return null; + } + if (query == null) { + System.out.println("There is not an 'Item Name' query."); + return null; + } + try { + com.teamcenter.services.strong.query._2007_06.SavedQuery.SavedQueryInput savedQueryInput[] = + new com.teamcenter.services.strong.query._2007_06.SavedQuery.SavedQueryInput[1]; + savedQueryInput[0] = + new com.teamcenter.services.strong.query._2007_06.SavedQuery.SavedQueryInput(); + savedQueryInput[0].query = query; + savedQueryInput[0].maxNumToReturn = 25; + savedQueryInput[0].limitListCount = 0; + savedQueryInput[0].limitList = new ModelObject[0]; + savedQueryInput[0].entries = new String[] {"User ID"}; // Attribute in Query to search by + savedQueryInput[0].values = new String[1]; + savedQueryInput[0].values[0] = user; // Value for the search attribute + savedQueryInput[0].maxNumToInflate = 25; + + // Execute Query to find the User + com.teamcenter.services.strong.query._2007_06.SavedQuery.ExecuteSavedQueriesResponse + savedQueryResult = queryService.executeSavedQueries(savedQueryInput); + com.teamcenter.services.strong.query._2007_06.SavedQuery.SavedQueryResults found = + savedQueryResult.arrayOfResults[0]; + + // System.out.println("Found Users:"); + + ModelObject[] modelObjs = found.objects; + + return modelObjs[0]; // User object + + } catch (Exception e) { + System.out.println(e.getMessage()); + return null; + } + } + + public static ModelObject findGroup(String groupName) { + + ImanQuery query = null; + + SavedQueryService queryService = SavedQueryService.getService(AppXSession.getConnection()); + + try { + + SavedQuery.GetSavedQueriesResponse savedQueries = queryService.getSavedQueries(); + + if (savedQueries.queries.length == 0) { + return null; + } + + for (int i = 0; i < savedQueries.queries.length; i++) { + // __WEB_group -> Query in Query builder to find the group + + if (savedQueries.queries[i].name.equals("__WEB_group")) { + query = savedQueries.queries[i].query; + break; + } + } + + } catch (ServiceException e) { + + System.out.println(e.getMessage()); + return null; + } + + if (query == null) { + System.out.println("__WEB_group query not found"); + return null; + } + try { + + com.teamcenter.services.strong.query._2007_06.SavedQuery.SavedQueryInput savedQueryInput[] = + new com.teamcenter.services.strong.query._2007_06.SavedQuery.SavedQueryInput[1]; + savedQueryInput[0] = + new com.teamcenter.services.strong.query._2007_06.SavedQuery.SavedQueryInput(); + savedQueryInput[0].query = query; + savedQueryInput[0].maxNumToReturn = 25; + savedQueryInput[0].limitListCount = 0; + savedQueryInput[0].limitList = new ModelObject[0]; + savedQueryInput[0].entries = new String[] {"Name"}; // Attribute in Query to search by + savedQueryInput[0].values = new String[1]; + savedQueryInput[0].values[0] = groupName; // Value for the search attribute + savedQueryInput[0].maxNumToInflate = 25; + + // Execute Query to find the Group + + com.teamcenter.services.strong.query._2007_06.SavedQuery.ExecuteSavedQueriesResponse + savedQueryResult = queryService.executeSavedQueries(savedQueryInput); + + com.teamcenter.services.strong.query._2007_06.SavedQuery.SavedQueryResults found = + savedQueryResult.arrayOfResults[0]; + + // System.out.println("Found Users:"); + + ModelObject[] modelObjs = found.objects; + + return modelObjs[0]; // Group object + + } catch (Exception e) { + + System.out.println(e.getMessage()); + + return null; + } + } + + public static void changeOwnershipModelObject( + ModelObject user, String groupName, ModelObject[] modls) throws Exception { + DataManagementService ser1 = + com.teamcenter.services.strong.core.DataManagementService.getService( + AppXSession.getConnection()); + // ModelObject user = findUser( userName ) ; + + if (user != null) { + System.out.println( + "................................owning user found.................................."); + + } else { + + // The configured EPI-Owning-user is not found in Teamcenter. + + System.out.println("................ EPI-owning user not found ................"); + + throw new Exception( + "Change ownership service: 003.Change ownership service - The configured EPI-owning user is not found in Teamcenter."); + } + ModelObject userGroup = null; + if (groupName != "") { + userGroup = findGroup(groupName); + } else { + ser1.getProperties(new ModelObject[] {user}, new String[] {"default_group"}); + userGroup = user.getPropertyObject("default_group").getModelObjectValue(); + } + + if (userGroup != null) { + + System.out.println( + "................................owning group found.................................."); + + } else { + + System.out.println("................ EPI-owning group not found ................"); + + throw new Exception( + "Change ownership service: 004.Change ownership service - The configured EPI-owning group is not found in Teamcenter."); + } + + DataManagement.ObjectOwner[] ownerData = new DataManagement.ObjectOwner[modls.length]; + for (int i = 0; i < modls.length; i++) { + DataManagement.ObjectOwner ownrObj = + new com.teamcenter.services.strong.core._2006_03.DataManagement.ObjectOwner(); + + ownrObj.object = modls[i]; + ownrObj.group = (Group) userGroup; + ownrObj.owner = (User) user; + ownerData[i] = ownrObj; + } + ServiceData returnData = ser1.changeOwnership(ownerData); + + System.out.println( + "****************************** Ownership changed successfully ******************************"); + + if (returnData.sizeOfPartialErrors() > 0) { + + throw new Exception( + "Change ownership service: 005.Change ownership service - " + + returnData.getPartialError(0).getMessages()[0]); + } + } + + public static String[] GetPrefValues(String prefName, boolean requested) throws Exception { + try { + SessionService sessionService = SessionService.getService(AppXSession.getConnection()); + Session.ScopedPreferenceNames sprefName = new Session.ScopedPreferenceNames(); + sprefName.names = new String[] {prefName}; + sprefName.scope = "site"; + com.teamcenter.services.strong.core._2010_04.Session.MultiPreferenceResponse2 resp = + sessionService.getPreferences2(new Session.ScopedPreferenceNames[] {sprefName}); + // ThrowServiceDataError(resp.Data); + // ServiceData aaa = resp.Data; + + com.teamcenter.services.strong.core._2010_04.Session.ReturnedPreferences2[] prefs = + resp.preferences; + if (prefs.length == 0) { + throw new Exception("首选项“" + prefName + "”不存在"); + } + + String[] values = prefs[0].values; + if (values == null || values.length == 0) { + throw new Exception("首选项“" + prefName + "”未配置"); + } + if (requested && (values[0] == null || "".equals(values[0]))) { + throw new Exception("首选项“" + prefName + "”未配置"); + } + return values; + } catch (Exception ex) { + throw ex; + } + } + + public static byte[] getFile(String url) { + StringBuilder sb = new StringBuilder(url); + OkHttpClient client = new OkHttpClient(); + Request.Builder builder = new Request.Builder(); + Request request = builder.url(sb.toString()).build(); + + return executeByte(request); + } + + public static byte[] executeByte(Request request) { + Response response = null; + try { + OkHttpClient okHttpClient = new OkHttpClient(); + response = okHttpClient.newCall(request).execute(); + + if (response.isSuccessful()) { + return response.body().bytes(); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (Optional.ofNullable(response).isPresent()) { + response.close(); + } + } + return null; + } + + // 获取对象最新版本 + public static ItemRevision GetLatestRev(DataManagementService dmService, Item item) + throws NotLoadedException { + if (dmService == null) { + dmService = DataManagementService.getService(AppXSession.getConnection()); + } + dmService.getProperties(new ModelObject[] {item}, new String[] {"revision_list"}); + ModelObject[] revList = item.get_revision_list(); + // ThrowServiceDataError(dmService.RefreshObjects(revList)); + dmService.getProperties(revList, new String[] {"item_revision_id"}); + ItemRevision baseRev = (ItemRevision) revList[0]; + for (int i = 0; i < revList.length; i++) { + ItemRevision temp = (ItemRevision) revList[i]; + if (temp.get_item_revision_id().compareTo(baseRev.get_item_revision_id()) > 0) { + baseRev = temp; + } + } + return baseRev; + } + + public static void getData( + String json, + HashMap + itemObjectPropMap, + HashMap + revObjectPropMap, + HashMap + revMasterObjectPropMap, + Map fileMap, + Map propertyMap,String logFileName) { + if (json.indexOf("{") < 0 || json.indexOf("}") < 0) { + return; + } + JSONObject jsonObject = JSONObject.parseObject(json); + Map postValueMap = jsonObject.getInnerMap(); + for (String key : postValueMap.keySet()) { + Object value = postValueMap.get(key); + System.out.println("key:" + key + " value:" + value.toString()); + // 获取属性及位置 + if (key.indexOf(".") > 0) { + String itemWhere = key.split("\\.")[0]; + String itemName = key.split("\\.")[1]; + com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct valueVecStruct = + new com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct(); + valueVecStruct.stringVec = new String[] {value.toString()}; + switch (itemWhere) { + case "item": + Utils.setLog(logFileName, "getData", "【item】:【key】:"+itemName+"【value】:"+valueVecStruct); + itemObjectPropMap.put(itemName, valueVecStruct); + break; + case "rev": + Utils.setLog(logFileName, "getData", "【rev】:【key】:"+itemName+"【value】:"+valueVecStruct); + revObjectPropMap.put(itemName, valueVecStruct); + break; + case "revMaster": + Utils.setLog(logFileName, "getData", "【revMaster】:【key】:"+itemName+"【value】:"+valueVecStruct); + revMasterObjectPropMap.put(itemName, valueVecStruct); + break; + } + } else if (value.toString().indexOf("[") == 0 && value.toString().indexOf("{") < 0) { + propertyMap.put(key, value); + } else if (value instanceof JSONArray) { + JSONArray jsonArray = JSONArray.parseArray(value.toString()); + if (key.indexOf("file") >= 0) { + + Utils.setLog(logFileName, "getData", "【revMaster】:【file】【value】:"+value.toString()); + // 获取文件 + for (Object o : jsonArray) { + JSONObject fileJSONObject = JSONObject.parseObject(o.toString()); + + // 获取文件名称和url + fileMap.put(fileJSONObject.getString("url"), fileJSONObject.getString("name")); + } + + } else { + // 遍历Json + for (Object o : jsonArray) { + if (o.toString().indexOf("file") >= 0) { + getData( + o.toString(), + itemObjectPropMap, + revObjectPropMap, + revMasterObjectPropMap, + fileMap, + propertyMap,logFileName); + } else { + Utils.setLog(logFileName, "getData", "【propertyMap】:【key】:"+key+"【value】:"+value); + propertyMap.put(key, value); + getData( + o.toString(), + itemObjectPropMap, + revObjectPropMap, + revMasterObjectPropMap, + fileMap, + propertyMap,logFileName); + } + } + } + } else if (value instanceof JSONObject) { + Utils.setLog(logFileName, "getData", "【propertyMap】:【key】:"+key+"【value】:"+value); + propertyMap.put(key, value); + getData( + value.toString(), + itemObjectPropMap, + revObjectPropMap, + revMasterObjectPropMap, + fileMap, + propertyMap,logFileName); + } else { + Utils.setLog(logFileName, "getData", "【propertyMap】:【key】:"+key+"【value】:"+value); + propertyMap.put(key, value); + } + } + } + + public static void setLog(String name, String type, String log) { + log = String.format("【%s %s】:%s", dateFormatLog.format(new Date()), type, log); + String filenameTemp = + System.getProperty("java.io.tmpdir") + "//" + name + ".log"; // 文件路径+名称+文件类型 + try { + File file = new File(filenameTemp); + if (!file.exists()) { + // 如果文件不存在,则创建新的文件 + if (!file.getParentFile().exists()) { + file.getParentFile().mkdirs(); + } + file.createNewFile(); + // 创建文件成功后,写入内容到文件里 + writeFileContent(filenameTemp, log); + + } else { + writeFileContent(filenameTemp, log); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * 向文件中写入内容 + * + * @param filepath 文件路径与名称 + * @param newstr 写入的内容 + * @return + * @throws IOException + */ + public static boolean writeFileContent(String filepath, String newstr) throws IOException { + Boolean bool = false; + String filein = newstr + "\r\n"; // 新写入的行,换行 + String temp = ""; + FileInputStream fis = null; + InputStreamReader isr = null; + BufferedReader br = null; + FileOutputStream fos = null; + PrintWriter pw = null; + try { + File file = new File(filepath); // 文件路径(包括文件名称) + // 将文件读入输入流 + fis = new FileInputStream(file); + isr = new InputStreamReader(fis); + br = new BufferedReader(isr); + StringBuffer buffer = new StringBuffer(); + // 文件原有内容 + for (int i = 0; (temp = br.readLine()) != null; i++) { + buffer.append(temp); + // 行与行之间的分隔符 相当于“\n” + buffer = buffer.append(System.getProperty("line.separator")); + } + buffer.append(filein); + fos = new FileOutputStream(file); + pw = new PrintWriter(fos); + pw.write(buffer.toString().toCharArray()); + pw.flush(); + bool = true; + } catch (Exception e) { + // TODO: handle exception + e.printStackTrace(); + } finally { + // 不要忘记关闭 + if (pw != null) { + pw.close(); + } + if (fos != null) { + fos.close(); + } + if (br != null) { + br.close(); + } + if (isr != null) { + isr.close(); + } + if (fis != null) { + fis.close(); + } + } + return bool; + } + + public static int getStrlength(String str) { + int strLength = 0; + String chinese = "[\u0391-\uFFE5]"; + /* 获取字段值的长度,如果含中文字符,则每个中文字符长度为2,否则为1 */ + for (int i = 0; i < str.length(); i++) { + /* 从字符串中获取一个字符 */ + String temp = str.substring(i, i + 1); + /* 判断是否为中文字符 */ + if (temp.matches(chinese)) { + /* 中文字符长度为4 */ + strLength += 2; + } else { + /* 其他字符长度为1 */ + strLength += 1; + } + } + return strLength; + } + + public static String subStrlength(String str,int length) { + int strLength = 0; + String chinese = "[\u0391-\uFFE5]"; + /* 获取字段值的长度,如果含中文字符,则每个中文字符长度为2,否则为1 */ + StringBuffer stringBuffer = new StringBuffer(); + for (int i = 0; i < str.length(); i++) { + /* 从字符串中获取一个字符 */ + String temp = str.substring(i, i + 1); + /* 判断是否为中文字符 */ + if (temp.matches(chinese)) { + /* 中文字符长度为4 */ + strLength += 2; + } else { + /* 其他字符长度为1 */ + strLength += 1; + } + if(strLength > length) + { + return str.substring(0, i); + } + else if(strLength == length) + { + return str.substring(0, i + 1); + } + } + return str; + } + + public static Item SearchItem(String itemId) throws ServiceException { + if (itemId == null || "".equals(itemId)) + { + return null; + } + Item item = null; + ImanQuery query = null; + SavedQueryService queryService = SavedQueryService.getService(AppXSession.getConnection()); + SavedQuery.GetSavedQueriesResponse savedQueries = queryService.getSavedQueries(); + if (savedQueries.queries.length == 0) + { + //throw new System.Exception("没有从TC中找到保存的查询"); + } + for (int i = 0; i < savedQueries.queries.length; i++) + { + if (savedQueries.queries[i].name.equals("Item...")) + { + query = savedQueries.queries[i].query; + break; + } + } + if (query == null) + { + //throw new Exception("TC中不存在“零组件...”查询"); + } + com.teamcenter.services.strong.query._2007_06.SavedQuery.SavedQueryInput[] savedQueryInput = new com.teamcenter.services.strong.query._2007_06.SavedQuery.SavedQueryInput[1]; + savedQueryInput[0] = new com.teamcenter.services.strong.query._2007_06.SavedQuery.SavedQueryInput(); + savedQueryInput[0].query = query; + savedQueryInput[0].entries = new String[] { "Item ID" }; + savedQueryInput[0].values = new String[1]; + savedQueryInput[0].values[0] = itemId; + com.teamcenter.services.strong.query._2007_06.SavedQuery.ExecuteSavedQueriesResponse savedQueryResult = queryService.executeSavedQueries(savedQueryInput); + com.teamcenter.services.strong.query._2007_06.SavedQuery.SavedQueryResults found = savedQueryResult.arrayOfResults[0]; + if (found.numOfObjects > 0) + { + item = (Item)found.objects[0]; + } + return item; + } +} diff --git a/src/main/java/com/teamcenter/clientx/test.java b/src/main/java/com/teamcenter/clientx/test.java new file mode 100644 index 0000000..4f42996 --- /dev/null +++ b/src/main/java/com/teamcenter/clientx/test.java @@ -0,0 +1,176 @@ +package com.teamcenter.clientx; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.pjb.springbootjjwt.entity.Product; +import com.teamcenter.services.strong.core._2007_01.DataManagement; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class test { + + public static void main(String[] args) { + + +// String s = "杭州海康威视科技有限公司 +Q5滚珠丝杠项目(B)+PMA4707221346 +190901290A(客户代号)+全新新产品+兰兆玲+产品交期: 6月30日+PMB 产品制造可行性评审表.pdf"; +// String ext = "pdf"; +// System.out.println(Utils.getStrlength(s)); +// if(Utils.getStrlength(s) > 128) +// { +// s = Utils.subStrlength(s,127-ext.length()) + "." + ext; +// } + + + String s = "item_revision_id===item_revision_id"; + String[] ss = s.split("="); + for (int i = 0; i < ss.length; i++) { + System.out.println(ss[i]); + } + + System.out.println(Utils.getStrlength(s)); +// String json = +// "{\"developmentProcess\":\"待确认\",\"product\":[{\"uid\":\"6290a1e2e4b0c525e51819f9\",\"objectName\":\"11\",\"productApplicationFieldOrIndustry\":\"A45航空 / A4501 发动机及其他动力装置 \",\"cycleStatus\":\"Edit\",\"productType\":\"全新新产品\"}],\"projectUid\":\"62907db5e4b0c525e51806d6\",\"invoicingCustomerCode\":\"\",\"customerSystem\":\"客户体系\",\"rev.rb3_khmc\":\"测试客户名称\",\"planStartTime\":\"2022-05-27T07:28:53.896Z\",\"nameofEndSupplyCustomer\":\"\",\"owningUser\":{\"uid\":\"61c4169be4b03426b1ee797f\",\"type\":\"User\",\"rev.rb3_zbr\":\"admin\"},\"rev.rb3_xmmc\":\"测试同步接口\",\"userId\":\"admin\",\"uid\":\"62907db5e4b0c525e51806d6\",\"rev.rb3_khdj\":\"普通客户\",\"rev.rb3_xmlx\":\"PM\",\"industries\":\"A16新能源汽车 / A1601新能源驱动 \",\"rev.rb3_xmbh\":\"BH5271530\",\"rev.rb3_xmdj\":\"A(研发类)\",\"cycleStatus\":\"CREATE\",\"rev.rb3_ptcxhsbmc\":\"1530\",\"rev.rb3_sybw\":\"5271530\"}\n"; +// +// Utils.setLog("2022052701", "oaCreateWorkFlow", json); +// // 获取数据 +// HashMap itemObjectPropMap = +// new HashMap< +// String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>(); +// HashMap +// revObjectPropMap = +// new HashMap< +// String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>(); +// HashMap +// revMasterObjectPropMap = +// new HashMap< +// String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>(); +// Map fileMap = new HashMap(); +// Map propertyMap = new HashMap(); +// getData( +// json, itemObjectPropMap, revObjectPropMap, revMasterObjectPropMap, fileMap, propertyMap); +// String productJson = +// propertyMap.containsKey("product") ? propertyMap.get("product").toString() : ""; +// +// List productList = new ArrayList(); +// if (productJson != null) { +// JSONArray jsonArray = JSONArray.parseArray(productJson); +// for (Object o: jsonArray) { +// if(o instanceof JSONObject) +// { +// JSONObject jsonObject = JSONObject.parseObject(o.toString()); +// if(jsonObject.containsKey("bearingCategory") && jsonObject.containsKey("plant")) +// { +// Product product = new Product(); +// product.setBearingCategory(jsonObject.getString("bearingCategory")); +// product.setPlant(jsonObject.getString("plant")); +// productList.add(product); +// } +// } +// } +// List subStringList = new ArrayList(); +// while (productJson.lastIndexOf("}") != productJson.indexOf("}")) { +// subStringList.add(productJson.substring(0, productJson.indexOf("}") + 1)); +// productJson = productJson.substring(productJson.indexOf("}") + 2, productJson.length()); +// System.out.println(); +// } +// subStringList.add(productJson); +// List productList = new ArrayList(); +// for (String json1 : subStringList) { +// System.out.println("productJson:" + json1); +// Product product = JSONObject.parseObject(json, Product.class); +// productList.add(product); +// } +// } + // byte[] buffer = Utils.getFile("http://192.168.10.162:9334/5,0447031463cf"); + System.out.println(s); + } + + public static void getData( + String json, + HashMap itemObjectPropMap, + HashMap + revObjectPropMap, + HashMap + revMasterObjectPropMap, + Map fileMap, + Map propertyMap) { + if (json.indexOf("{") < 0 || json.indexOf("}") < 0) { + return; + } + JSONObject jsonObject = JSONObject.parseObject(json); + Map postValueMap = jsonObject.getInnerMap(); + for (String key : postValueMap.keySet()) { + Object value = postValueMap.get(key); + System.out.println("key:" + key + " value:" + value.toString()); + // 获取属性及位置 + if (key.indexOf(".") > 0) { + String itemWhere = key.split("\\.")[0]; + String itemName = key.split("\\.")[1]; + com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct valueVecStruct = + new com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct(); + valueVecStruct.stringVec = new String[] {value.toString()}; + switch (itemWhere) { + case "item": + itemObjectPropMap.put(itemName, valueVecStruct); + break; + case "rev": + revObjectPropMap.put(itemName, valueVecStruct); + break; + case "revMaster": + revMasterObjectPropMap.put(itemName, valueVecStruct); + break; + } + } else if (value.toString().indexOf("[") == 0 && value.toString().indexOf("{") < 0) { + propertyMap.put(key, value); + } else if (value instanceof JSONArray) { + JSONArray jsonArray = JSONArray.parseArray(value.toString()); + if (key.indexOf("file") >= 0) { + // 获取文件 + for (Object o : jsonArray) { + JSONObject fileJSONObject = JSONObject.parseObject(o.toString()); + + // 获取文件名称和url + fileMap.put(fileJSONObject.getString("url"), fileJSONObject.getString("name")); + } + + } else { + // 遍历Json + for (Object o : jsonArray) { + if (o.toString().indexOf("file") >= 0) { + getData( + o.toString(), + itemObjectPropMap, + revObjectPropMap, + revMasterObjectPropMap, + fileMap, + propertyMap); + } else { + propertyMap.put(key, value); + getData( + o.toString(), + itemObjectPropMap, + revObjectPropMap, + revMasterObjectPropMap, + fileMap, + propertyMap); + } + } + } + } else if (value instanceof JSONObject) { + propertyMap.put(key, value); + getData( + value.toString(), + itemObjectPropMap, + revObjectPropMap, + revMasterObjectPropMap, + fileMap, + propertyMap); + } else { + propertyMap.put(key, value); + } + } + } +} diff --git a/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/src/main/resources/META-INF/additional-spring-configuration-metadata.json new file mode 100644 index 0000000..1b08462 --- /dev/null +++ b/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -0,0 +1,28 @@ +{ + "properties": [ + { + "name": "teamcenter.url", + "type": "java.lang.String", + "description": "Description for teamcenter.url." + }, + { + "name": "teamcenter.user", + "type": "java.lang.String", + "description": "Description for teamcenter.user." + }, + { + "name": "teamcenter.pwd", + "type": "java.lang.String", + "description": "Description for teamcenter.pwd." + }, + { + "name": "teamcenter.fmsurl", + "type": "java.lang.String", + "description": "Description for teamcenter.fmsurl." + }, + { + "name": "teamcenter.fcccash", + "type": "java.lang.String", + "description": "Description for teamcenter.fcccash." + } + ] } \ No newline at end of file diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml new file mode 100644 index 0000000..5aefe29 --- /dev/null +++ b/src/main/resources/application.yaml @@ -0,0 +1,25 @@ +spring: + datasource: + driver-class-name: oracle.jdbc.OracleDriver + url: jdbc:oracle:thin:@192.168.211.239:1521:tc12 + username: infodba + password: infodba + servlet: + multipart: + max-file-size: 50MB #单个文件最大为50M + max-request-size: 50MB #单次请求文件总数大小为50M +mybatis: + config-location: classpath:mybatis.xml +debug: true +server: + port: 9292 +teamcenter: + url: http://192.168.211.248:7003/tc + user: admin + pwd: Admin123! + fmsurl: http://192.168.211.249:4544 + fcccash: C:/temp + workflowtemplate: TeamcenterForTcserverTemplate + taskPackage: RB3_TaskPackage + paiProjectId: rb3_PaiProjectID + paiProjectName: rb3_PaiProjectName \ No newline at end of file diff --git a/src/main/resources/com/pjb/springbootjjwt/mapper/IgtcoaMapper.xml b/src/main/resources/com/pjb/springbootjjwt/mapper/IgtcoaMapper.xml new file mode 100644 index 0000000..08417b6 --- /dev/null +++ b/src/main/resources/com/pjb/springbootjjwt/mapper/IgtcoaMapper.xml @@ -0,0 +1,81 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + UPDATE DOCUMENT_ATTRIBUTES_TABLE + SET APPROVE_RESULT = #{approval} + WHERE PROCESS_ID = #{processId} + + + INSERT INTO TCOA_SIGN_INFO (P_FILE_UID,P_SIGN_NAME,P_SIGN_DATE,P_NO) + VALUES (#{fileID},#{signName},#{signDate},#{signNo}) + + + DELETE TCOA_SIGN_INFO + WHERE P_FILE_UID = #{fileID} + + + + INSERT INTO TCOA_FILE (P_FILE_ID,P_FILE_NAME,P_FILE_PATH) + VALUES (#{fileID},#{fileName},#{signDate},#{filePath}) + + + + \ No newline at end of file diff --git a/src/main/resources/com/pjb/springbootjjwt/mapper/UserMapper.xml b/src/main/resources/com/pjb/springbootjjwt/mapper/UserMapper.xml new file mode 100644 index 0000000..85f9c71 --- /dev/null +++ b/src/main/resources/com/pjb/springbootjjwt/mapper/UserMapper.xml @@ -0,0 +1,20 @@ + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mybatis.xml b/src/main/resources/mybatis.xml new file mode 100644 index 0000000..4b5060b --- /dev/null +++ b/src/main/resources/mybatis.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/src/test/java/com/pjb/springbootjjwt/SpringbootJjwtApplicationTests.java b/src/test/java/com/pjb/springbootjjwt/SpringbootJjwtApplicationTests.java new file mode 100644 index 0000000..8c06bc4 --- /dev/null +++ b/src/test/java/com/pjb/springbootjjwt/SpringbootJjwtApplicationTests.java @@ -0,0 +1,16 @@ +package com.pjb.springbootjjwt; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringbootJjwtApplicationTests { + + @Test + public void contextLoads() { + } + +}