提交代码

master
祁云辉 2 years ago
commit 859f15c2d5

25
.gitignore vendored

@ -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/

Binary file not shown.

After

Width:  |  Height:  |  Size: 954 KiB

@ -0,0 +1 @@
SpringBoot集成JWT实现token验证

225
mvnw vendored

@ -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 "$@"

143
mvnw.cmd vendored

@ -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%

@ -0,0 +1,310 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.pjb</groupId>
<artifactId>springboot-jjwt</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot-jjwt</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc8</artifactId>
<version>12.2.0.1</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>commons-logging</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>fccclient</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>fscclient</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>httpclient</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>httpcore</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>httpmime</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>log4j</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>TcSoaAdministrationStrong</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>TcSoaAiStrong</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>TcSoaAllocationsStrong</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>TcSoaBomStrong</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>TcSoaBusinessModelerStrong</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>TcSoaCadBomAlignmentStrong</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>TcSoaCadStrong</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>TcSoaCaeStrong</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>TcSoaCalendarManagementStrong</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>TcSoaChangeManagementStrong</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>TcSoaClassificationStrong</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>TcSoaClient</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>TcSoaCommon</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>TcSoaConfigurationStrong</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>TcSoaCoreLoose</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>TcSoaCoreStrong</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>TcSoaDocumentManagementStrong</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>TcSoaImportExportStrong</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>TcSoaQueryStrong</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>TcSoaStrongModel</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>xercesImpl</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>xml-apis</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>teamcenter</groupId>
<artifactId>TcSoaWorkflowStrong</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.8.0</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>1.3.50</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.3.4.RELEASE</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.6</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>com.pjb.springbootjjwt.SpringbootJjwtApplication</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>

@ -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();
}
}

@ -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 );
}
}
}
}
}
}
}

@ -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<String, KeyLOVDefinition2> keyLOVs = response.keyLOVs;
System.out.println("*****Lov Details*******"+keyLOVs.size());
Set<String> keys = keyLOVs.keySet();
for(Iterator<String> 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<keyLOVEntries.length;i++)
{
KeyLOVEntry keyLOVEntries1 = lovDef.keyLovEntries[i];
System.out.println("LOV Entry Key : "+keyLOVEntries1.lovKey);
System.out.println("LOV Entry Value : "+keyLOVEntries1.lovValue);
System.out.println("Depricated Status : "+keyLOVEntries1.deprecatedSatus);
System.out.println("************************************* ");
System.out.println("****************Key End************** ");
System.out.println("************************************* ");
}
}
}
}

@ -0,0 +1,95 @@
// 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.ClassAttribute;
import com.teamcenter.services.strong.classification._2007_01.Classification.GetAttributesForClassesResponse;
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 Class get the classification class attributes 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 GetAttributesForClasses2Sample
{
/**
* get the classification class attributes from the class ID's.
*
* @throws ServiceException
*/
public void testgetGetAttributesForClasses()
throws ServiceException
{
ClassificationService clsService = ClassificationService.getService(AppXSession.getConnection());
String[] classIds = new String[1];
classIds[0] = "ICM4001";
System.out.println( "Calling the SOA testgetGetAttributesForClasses..." );
GetAttributesForClassesResponse response = clsService.getAttributesForClasses( classIds );
if ( response.data.sizeOfPartialErrors() > 0)
throw new ServiceException( "ClassificationService.getAttributesForClasses returned a partial Error.");
ClassAttribute[] clsattr = new ClassAttribute[1];
Map<String, ClassAttribute[]> attributes = response.attributes;
System.out.println( "After Call SOA " );
Set<String> keys = attributes.keySet();
for( Iterator<String> 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( "****************************************************" );
}
}
}

@ -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<String, ClassDef> 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()");
}
}

@ -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<String, KeyLOVDefinition2> keyLOVs = response.keyLOVs;
System.out.println("*****Lov Details******* "+keyLOVs.size());
Set<String> keys = keyLOVs.keySet();
for(Iterator<String> 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<keyLOVEntries.length;i++)
{
KeyLOVEntry keyLOVEntries1 = lovDef.keyLovEntries[i];
System.out.println("KeyLOV Entry Key : "+keyLOVEntries1.lovKey);
System.out.println("KeyLOV Entry Value : "+keyLOVEntries1.lovValue);
System.out.println("Deprecated Status : "+keyLOVEntries1.deprecatedSatus);
System.out.println("*************************************************************");
}
}
}
}

@ -0,0 +1,77 @@
// 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;
import com.teamcenter.services.strong.classification.ClassificationService;
import com.teamcenter.services.strong.classification._2007_01.Classification.GetKeyLOVsResponse;
import com.teamcenter.services.strong.classification._2007_01.Classification.KeyLOVDefinition;
import com.teamcenter.schemas.soa._2006_03.exceptions.ServiceException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* 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 GetKeyLOVsSample
{
/**
* get the KeyLOV definitions from keyLOV ID's.
*
* @throws ServiceException
*/
public void testGetKeyLOVs1()throws ServiceException
{
String[] keyLOVIds = new String[1];
keyLOVIds[0] = "-2894";
System.out.println("Calling the SOA getKeyLOVs");
ClassificationService clsService = ClassificationService.getService(AppXSession.getConnection());
GetKeyLOVsResponse response = clsService.getKeyLOVs( keyLOVIds );
if ( response.data.sizeOfPartialErrors() > 0)
throw new ServiceException( "ClassificationService.getKeyLOVs returned a partial Error.");
Map<String, KeyLOVDefinition> keyLOVs = response.keyLOVs;
System.out.println("*****LOV Details******* ");
Set<String> keys = keyLOVs.keySet();
for(Iterator<String> 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<String,String> keyLovEntries= lovDef.keyValuePairs;
Set<String> keySet = keyLovEntries.keySet();
for ( Iterator<String> 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("*************************************************************");
}
}
}
}

@ -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");
}
}

@ -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;
}

@ -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;
}

@ -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<String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>
itemObjectPropMap =
new HashMap<
String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>();
HashMap<String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>
revObjectPropMap =
new HashMap<
String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>();
HashMap<String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>
revMasterObjectPropMap =
new HashMap<
String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>();
Map<String, String> fileMap = new HashMap<String, String>();
Map<String, Object> propertyMap = new HashMap<String, Object>();
// Map<String, Object> 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<String> productList = new ArrayList<String>();
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<File> fileList = new ArrayList<File>();
try {
// MultiValueMap fileMap = ((StandardMultipartHttpServletRequest)
// request).getMultiFileMap();
//
// System.out.println("fileMap.size();:"+fileMap.size());
// Collection<MultipartFile> 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<JSONObject> 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<Part> 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<String> 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<String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>
itemObjectPropMap =
new HashMap<
String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>();
HashMap<String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>
revObjectPropMap =
new HashMap<
String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>();
HashMap<String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>
revMasterObjectPropMap =
new HashMap<
String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>();
Map<String, String> fileMap = new HashMap<String, String>();
Map<String, Object> propertyMap = new HashMap<String, Object>();
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<Product> productList = new ArrayList<Product>();
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<String> subStringList = new ArrayList<String>();
// 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<Product> productList = new ArrayList<Product>();
// 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<String> 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;
}
}

@ -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;
}
}
}

@ -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();
}
}

@ -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 {
}

@ -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 ;
}

@ -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<IgtcoaFile> files ;
}

@ -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 ;
}

@ -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 ;
}

@ -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;
}

@ -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<IgtcoaProcess> result;
}

@ -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 ;
}

@ -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<IgtcoaSignContent> content ;
}

@ -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<String> attached_files ;
List<IgtcoaSignInfo> sign_info ;
}

@ -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;
}
}

@ -0,0 +1,10 @@
package com.pjb.springbootjjwt.entity;
import lombok.Data;
@Data
public class OwningGroup {
String uid;
String name;
String type;
}

@ -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;
}

@ -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> product;
}

@ -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;
}

@ -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 {
}
}

@ -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);
}
}

@ -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<IgtcoaProcess> listAllProcess(@Param("status") String status,@Param("workcode") String workcode);
List<IgtcoaFile> 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);
}

@ -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);
}

@ -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<IgtcoaProcess> listAllProcess(String workcode){
List<IgtcoaProcess> processList = igtcoaMapper.listAllProcess("0",workcode);
return processList;
}
public IgtcoaFileProcess getFileProcess(String processid){
IgtcoaFileProcess fileProcess = igtcoaMapper.getFileProcess(processid);
if(fileProcess!=null){
List<IgtcoaFile> 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<IgtcoaSignContent> signcontentList = signinfo.getContent();
igtcoaMapper.deleteFileSigninfo(signinfo.getFile_id());
for(int i =0;i<signcontentList.size();i++) {
igtcoaMapper.insertFileSigninfo(signinfo.getFile_id(),
signcontentList.get(i).getName(),
signcontentList.get(i).getTime(),i+1);
}
}
}
public void insertOAFiles(String fileID,String fileName,String filePath){
igtcoaMapper.insertOAFile(fileName,filePath,fileID);
}
}

@ -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;
}
}

@ -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);
}
}

@ -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(Map<String,Object>data) {
//将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<String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct> objectPropMap = new HashMap<String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>();
// //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);

@ -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();
}
}

@ -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)});
}
}

@ -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();
}
}
}

@ -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;
}
}

@ -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);
}
}

@ -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]);
}
}
}

@ -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());
}
}
}
}

@ -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);
}
}

@ -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<User> unKnownUsers = new Vector<User>();
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);
}
}

@ -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+10<found.objectUIDS.length)? 10:found.objectUIDS.length-i;
uids[i]= found.objectUIDS[i];
// for(int j=0; j<pageSize; j++)
// {
// uids[j]= found.objectUIDS[i+j];
// }
ServiceData sd = dmService.loadObjects( uids );
foundObjs = new ModelObject[ sd.sizeOfPlainObjects()];
for( int k =0; k< sd.sizeOfPlainObjects(); k++)
{
foundObjs[k] = sd.getPlainObject(k);
// Group wo = (Group) foundObjs[k];
// System.out.println("get_name:"+wo.get_name());
}
// Group wo = (Group) foundObjs[0];
// String s = wo.get_name();
// Object[] obj = Arrays.stream(foundObjs).toArray();
//AppXSession.printObjects( foundObjs );
}
}
catch (Exception e)
{
System.out.println("ExecuteSavedQuery service request failed.");
System.out.println(e.getMessage());
return null;
}
return foundObjs;
}
}

@ -0,0 +1,567 @@
package com.teamcenter.clientx;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.DataManagement;
import com.teamcenter.services.strong.core._2007_01.Session;
import com.teamcenter.services.strong.query.SavedQueryService;
import com.teamcenter.services.strong.query._2006_03.SavedQuery;
import com.teamcenter.soa.client.model.ModelObject;
import com.teamcenter.soa.client.model.ServiceData;
import com.teamcenter.soa.client.model.strong.*;
import com.teamcenter.soa.exceptions.NotLoadedException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class Utils {
private static SimpleDateFormat dateFormatLog = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Find user using User ID ->String 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<String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>
itemObjectPropMap,
HashMap<String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>
revObjectPropMap,
HashMap<String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>
revMasterObjectPropMap,
Map<String, String> fileMap,
Map<String, Object> propertyMap,String logFileName) {
if (json.indexOf("{") < 0 || json.indexOf("}") < 0) {
return;
}
JSONObject jsonObject = JSONObject.parseObject(json);
Map<String, Object> 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;
}
}

@ -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<String, DataManagement.VecStruct> itemObjectPropMap =
// new HashMap<
// String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>();
// HashMap<String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>
// revObjectPropMap =
// new HashMap<
// String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>();
// HashMap<String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>
// revMasterObjectPropMap =
// new HashMap<
// String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>();
// Map<String, String> fileMap = new HashMap<String, String>();
// Map<String, Object> propertyMap = new HashMap<String, Object>();
// getData(
// json, itemObjectPropMap, revObjectPropMap, revMasterObjectPropMap, fileMap, propertyMap);
// String productJson =
// propertyMap.containsKey("product") ? propertyMap.get("product").toString() : "";
//
// List<Product> productList = new ArrayList<Product>();
// 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<String> subStringList = new ArrayList<String>();
// 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<Product> productList = new ArrayList<Product>();
// 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<String, DataManagement.VecStruct> itemObjectPropMap,
HashMap<String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>
revObjectPropMap,
HashMap<String, com.teamcenter.services.strong.core._2007_01.DataManagement.VecStruct>
revMasterObjectPropMap,
Map<String, String> fileMap,
Map<String, Object> propertyMap) {
if (json.indexOf("{") < 0 || json.indexOf("}") < 0) {
return;
}
JSONObject jsonObject = JSONObject.parseObject(json);
Map<String, Object> 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);
}
}
}
}

@ -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."
}
] }

@ -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

@ -0,0 +1,81 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.pjb.springbootjjwt.mapper.IgtcoaMapper">
<resultMap id="processMapper" type="com.pjb.springbootjjwt.entity.IgtcoaProcess">
<result property="id" column="PROCESS_ID"></result>
<result property="project_name" column="PROJECT_NAME"></result>
<result property="workflow_name" column="PROCESS_NAME"></result>
<result property="workcode" column="WORK_NUMBER"></result>
<result property="privary" column="SECURITY_LEVEL"></result>
<result property="created_time" column="CREATION_DATE"></result>
</resultMap>
<resultMap id="fileProcessMapper" type="com.pjb.springbootjjwt.entity.IgtcoaFileProcess">
<result property="process_uid" column="PROCESS_ID"></result>
<result property="process_name" column="PROCESS_NAME"></result>
</resultMap>
<resultMap id="fileMapper" type="com.pjb.springbootjjwt.entity.IgtcoaFile">
<result property="fileId" column="DATASET_UID"></result>
<result property="fileName" column="DATASET_NAME"></result>
<result property="url" column="DATASET_ADDRESS"></result>
<result property="fileType" column="DOCUMENT_TYPE"></result>
</resultMap>
<select id="listAllProcess" resultMap="processMapper">
SELECT
T1.PROCESS_ID,
T1.PROCESS_NAME,
T1.CREATION_DATE,
T1.WORK_NUMBER,
T2.PROJECT_NAME,
T2.SECURITY_LEVEL
FROM PROCESS_ATTRIBUTES_TABLE T1
LEFT JOIN WORK_ATTRIBUTES_TABLE T11 ON T1.PROCESS_ID = T11.PROCESS_ID
LEFT JOIN PROJECT_ATTRIBUTES_TABLE T2 ON T1.PROJECT_ID = T2.PROJECT_ID
WHERE T1.PSTATUS = #{status} and T11.WORK_NUMBER = #{workcode}
</select>
<select id="listAllFile" resultMap="fileMapper">
SELECT
T1.DATASET_UID,
T1.DATASET_NAME,
T1.DATASET_ADDRESS,
T2.DOCUMENT_TYPE
FROM DATASET_ATTRIBUTES_TABLE T1
LEFT JOIN DOCUMENT_ATTRIBUTES_TABLE T2 ON T1.DOCUMENT_ID = T2.DOCUMENT_ID AND T1.DOCUMNET_REV = T2.DOCUMNET_REV
WHERE T2.PROCESS_ID =#{processId}
</select>
<select id="getFileProcess" resultMap="fileProcessMapper">
SELECT
T1.PROCESS_ID,
T1.PROCESS_NAME
FROM PROCESS_ATTRIBUTES_TABLE T1
WHERE T1.PROCESS_ID = #{processId}
</select>
<update id="updateProcessApproval">
UPDATE DOCUMENT_ATTRIBUTES_TABLE
SET APPROVE_RESULT = #{approval}
WHERE PROCESS_ID = #{processId}
</update>
<insert id="insertFileSigninfo">
INSERT INTO TCOA_SIGN_INFO (P_FILE_UID,P_SIGN_NAME,P_SIGN_DATE,P_NO)
VALUES (#{fileID},#{signName},#{signDate},#{signNo})
</insert>
<update id="deleteFileSigninfo">
DELETE TCOA_SIGN_INFO
WHERE P_FILE_UID = #{fileID}
</update>
<insert id="insertOAFile">
INSERT INTO TCOA_FILE (P_FILE_ID,P_FILE_NAME,P_FILE_PATH)
VALUES (#{fileID},#{fileName},#{signDate},#{filePath})
</insert>
</mapper>

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.pjb.springbootjjwt.mapper.UserMapper">
<select id="findByUsername" resultType="com.pjb.springbootjjwt.entity.User">
SELECT app_secret,username,password FROM tcoauser
where
username=#{username}
</select>
<select id="findByUsernameAndId" resultType="com.pjb.springbootjjwt.entity.User">
SELECT app_secret,username,password FROM tcoauser
where
username=#{username} and app_secret=#{app_secret}
</select>
<select id="findUserById" resultType="com.pjb.springbootjjwt.entity.User">
SELECT app_secret,username,password FROM tcoauser
where
app_secret=#{app_secret}
</select>
</mapper>

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="logImpl" value="SLF4J"/>
<!-- 开启驼峰命名转换 Table(create_time) -> Entity(createTime) -->
<setting name="mapUnderscoreToCamelCase" value="false" />
</settings>
</configuration>

@ -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() {
}
}
Loading…
Cancel
Save