commit 4757004b0d83304e34c0126ef5efd88b46279b83 Author: lijh Date: Tue Mar 10 13:45:07 2026 +0800 first commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..d58dfb7 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# 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. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/lib/commons-io-2.11.0.jar b/lib/commons-io-2.11.0.jar new file mode 100644 index 0000000..be507d9 Binary files /dev/null and b/lib/commons-io-2.11.0.jar differ diff --git a/lib/ojdbc7.jar b/lib/ojdbc7.jar new file mode 100644 index 0000000..2077ea3 Binary files /dev/null and b/lib/ojdbc7.jar differ diff --git a/mvnw b/mvnw new file mode 100644 index 0000000..19529dd --- /dev/null +++ b/mvnw @@ -0,0 +1,259 @@ +#!/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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + 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" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..249bdf3 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@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 Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..bf54b22 --- /dev/null +++ b/pom.xml @@ -0,0 +1,330 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.3.7.RELEASE + + + com.connor.sso + getClass + 0.0.1-SNAPSHOT + sso + Demo project for Spring Boot + + + + + + + + + + + + + + + 8 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + org.mybatis.spring.boot + mybatis-spring-boot-starter + 1.1.1 + + + + com.microsoft.sqlserver + mssql-jdbc + 12.4.0.jre8 + + + + com.oracle.database.nls + orai18n + 19.8.0.0 + + + + com.alibaba + fastjson + 2.0.48 + + + + + + + teamcenter + commons-io + 2.5 + + + teamcenter + commons-logging + 2.5 + + + teamcenter + fccclient + 12.3.0 + + + + teamcenter + fscclient + 12.3.0 + + + + teamcenter + httpclient + 12.3.0 + + + + teamcenter + httpcore + 12.3.0 + + + + teamcenter + httpmime + 12.3.0 + + + + teamcenter + log4j + 12.3.0 + + + + teamcenter + TcSoaAdministrationStrong + 12.3.0 + + + + teamcenter + TcSoaAiStrong + 12.3.0 + + + + teamcenter + TcSoaAllocationsStrong + 12.3.0 + + + + teamcenter + TcSoaBomStrong + 12.3.0 + + + + teamcenter + TcSoaBusinessModelerStrong + 12.3.0 + + + + teamcenter + TcSoaCadBomAlignmentStrong + 12.3.0 + + + + teamcenter + TcSoaCadStrong + 12.3.0 + + + + teamcenter + TcSoaCaeStrong + 12.3.0 + + + + teamcenter + TcSoaCalendarManagementStrong + 12.3.0 + + + + teamcenter + TcSoaChangeManagementStrong + 12.3.0 + + + + teamcenter + TcSoaClassificationStrong + 12.3.0 + + + + teamcenter + TcSoaClient + 12.3.0 + + + + teamcenter + TcSoaCommon + 12.3.0 + + + + teamcenter + TcSoaConfigurationStrong + 12.3.0 + + + + teamcenter + TcSoaCoreLoose + 12.3.0 + + + + teamcenter + TcSoaCoreStrong + 12.3.0 + + + + teamcenter + TcSoaDocumentManagementStrong + 12.3.0 + + + + teamcenter + TcSoaImportExportStrong + 12.3.0 + + + + teamcenter + TcSoaQueryStrong + 12.3.0 + + + + teamcenter + TcSoaStrongModel + 12.3.0 + + + + teamcenter + TcSoaWorkflowLoose + 12.3.0 + + + teamcenter + TcSoaWorkflowStrong + 12.3.0 + + + + teamcenter + xercesImpl + 12.3.0 + + + org.projectlombok + lombok + 1.18.20 + + + teamcenter + xml-apis + 12.3.0 + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + + + javax.xml.bind + jaxb-api + 2.3.1 + + + + + org.glassfish.jaxb + jaxb-runtime + 2.3.1 + + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.apache.maven.plugins + maven-jar-plugin + 2.6 + + + + true + lib/ + com.connor.sso.sso.SsoApplication + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 8 + 8 + + + + + + diff --git a/src/main/java/com/connor/sso/sso/MyControl.java b/src/main/java/com/connor/sso/sso/MyControl.java new file mode 100644 index 0000000..5856526 --- /dev/null +++ b/src/main/java/com/connor/sso/sso/MyControl.java @@ -0,0 +1,556 @@ +package com.connor.sso.sso; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.connor.sso.sso.clientx.AppXSession; +import com.connor.sso.sso.mapper.ClassFieldBean; +import com.connor.sso.sso.mapper.FieldBean; +import com.connor.sso.sso.mapper.MyMapper; +import com.connor.sso.sso.mapper.SqlFieldBean; +import com.connor.sso.sso.util.LoginUtil; +import com.teamcenter.services.strong.classification.ClassificationService; +import com.teamcenter.services.strong.classification._2007_01.Classification; +import com.teamcenter.services.strong.core.DataManagementService; +import com.teamcenter.services.strong.core._2010_04.DataManagement; +import com.teamcenter.soa.client.Connection; +import com.teamcenter.soa.client.model.ModelObject; +import com.teamcenter.soa.client.model.ServiceData; +import com.teamcenter.soa.client.model.strong.Icm0; +import com.teamcenter.soa.client.model.strong.ItemRevision; +import com.teamcenter.soa.client.model.strong.WorkspaceObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.*; +class TreeNode { + private String id; + private String parentId; + private String name; + private List children = new ArrayList<>(); + + public TreeNode(String id, String parentId,String name) { + this.id = id; + this.parentId = parentId; + this.name = name; + } + + @Override + public String toString() { + return "TreeNode{" + + "id='" + id + '\'' + + ", parentId='" + parentId + '\'' + + ", name='" + name + '\'' + + ", children=" + children + + '}'; + } +// Getter 和 Setter + + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getParentId() { + return parentId; + } + + public void setParentId(String parentId) { + this.parentId = parentId; + } + + public List getChildren() { + return children; + } + + public void setChildren(List children) { + this.children = children; + } +} +@RestController +@RequestMapping("/tc") +public class MyControl { + + @Autowired + MyMapper mapper; + @GetMapping("/getClassTree") + public String getClassTree() { + + List fieldBeans = mapper.selectTree(); + System.out.println("bean============"+fieldBeans.size()); + HashMap map = new HashMap<>(); + String top = ""; + for (int i = 0; i < fieldBeans.size(); i++) { + FieldBean fieldBean = fieldBeans.get(i); + //根 + if((fieldBean.getPklassi() == null || fieldBean.getPklassi().isEmpty()) && (fieldBean.getParent() == null || fieldBean.getParent().isEmpty())){ + + top = fieldBean.getPcid()+":"+fieldBean.getPname(); + //top = fieldBean.getPcid(); + }else if((fieldBean.getPklassi() == null || fieldBean.getPklassi().isEmpty()) && (fieldBean.getParent() != null && !fieldBean.getParent().isEmpty())){ + //map.put(fieldBean.getPcid(),fieldBean.getParent()); + map.put(fieldBean.getPcid()+":"+fieldBean.getPname(),fieldBean.getParent()); + }else if((fieldBean.getPklassi() != null && !fieldBean.getPklassi().isEmpty()) && (fieldBean.getParent() == null || fieldBean.getParent().isEmpty())){ + //map.put(fieldBean.getPcid(),fieldBean.getPklassi()); + + map.put(fieldBean.getPcid()+":"+fieldBean.getPname(),fieldBean.getPklassi()); + } + + + } + + // 存储所有节点 + Map nodeMap = new HashMap<>(); + TreeNode root = new TreeNode(top.split(":")[0],"",top.split(":")[1]); + nodeMap.put(top.split(":")[0],root); + // 创建所有节点并放入 map 中 + for (Map.Entry entry : map.entrySet()) { + String id = entry.getKey(); + String parentId = entry.getValue(); + String[] split = id.split(":"); + TreeNode node = new TreeNode(split[0], parentId,split[1]); + nodeMap.put(split[0], node); + + } + // 构建父子关系 + for (TreeNode node : nodeMap.values()) { + if (node.getParentId() != null && nodeMap.containsKey(node.getParentId())) { + TreeNode parent = nodeMap.get(node.getParentId()); + parent.getChildren().add(node); + } + } + + // 使用 FastJSON 输出树形结构 + String jsonTree = JSON.toJSONString(root, true); // true 表示格式化输出 + System.out.println(jsonTree); + + return jsonTree; + } + + + + @PostMapping("/getClassFields") + public String getClassField(@RequestBody String json) { + + JSONObject parse = (JSONObject) JSONObject.parse(json); + String id = parse.getString("id"); + JSONObject result = new JSONObject(); + + if(id == null || id.isEmpty()){ + result.put("result",false); + result.put("msg","id不能为空!"); + return result.toString(); + } + List maps = mapper.selectClassField(id); + JSONArray fields = new JSONArray(); + for (int i = 0; i < maps.size(); i++) { + ClassFieldBean bean = maps.get(i); + JSONObject tempJsonObject = new JSONObject(); + tempJsonObject.put("fieldId",bean.getPunct()); + tempJsonObject.put("fieldName",bean.getPname()); + fields.add(tempJsonObject); + } + + result.put("result",true); + result.put("msg","success"); + result.put("fields",fields); + return result.toString(); + } + private AppXSession session; + + + @PostMapping("/getClassData") + public String getClassData(@RequestBody String json) { + + errorMsg = ""; + JSONObject parse = null; + JSONObject result = new JSONObject(); + try{ + parse = (JSONObject) JSONObject.parse(json); + }catch (Exception e){ + result.put("result",false); + result.put("msg","json格式不对"); + return result.toString(); + } + + String id = parse.getString("id"); + + if(id == null || id.isEmpty()){ + result.put("result",false); + result.put("msg","id不能为空!"); + return result.toString(); + } + + + List sqlFieldBeans = mapper.selectFields(id); + StringBuilder sql = new StringBuilder(); + sql.append("SELECT "); + LinkedHashMap> stringArrayListLinkedHashMap = new LinkedHashMap<>(); + for (int i = 0; i < sqlFieldBeans.size(); i++) { + SqlFieldBean sqlFieldBean = sqlFieldBeans.get(i); + ArrayList strings = new ArrayList<>(); + strings.add(sqlFieldBean.getPunct()); + strings.add(sqlFieldBean.getPname()); + if(sqlFieldBean.getPdbindex() == 0){ + sql.append("p"+sqlFieldBean.getPref_options().toLowerCase()); + stringArrayListLinkedHashMap.put("p"+sqlFieldBean.getPref_options().toLowerCase(),strings); + }else{ + sql.append("psm"+(sqlFieldBean.getPdbindex() < 10 ? "0" : "") + sqlFieldBean.getPdbindex()); + stringArrayListLinkedHashMap.put("psm"+(sqlFieldBean.getPdbindex() < 10 ? "0" : "") + sqlFieldBean.getPdbindex(),strings); + } + if(i != sqlFieldBeans.size() - 1){ + sql.append(","); + } + } + sql.append(" from PICM0 p1 left join PITEMREVISION p3 on p3.puid = p1.rerefu left join PITEM p4 on p4.puid = p3.ritems_tagu left join PWORKSPACEOBJECT p5 on p1.rerefu = p5.puid left join PG2_DESIGNREVISION p2 on p1.rerefu = p2.puid where p1.pcid = '"); + sql.append(id); + sql.append("'"); + System.out.println("sql======"+sql.toString()); + List> lists = mapper.selectClassData(sql.toString()); + // System.out.println("lists=="+lists); + JSONArray jsonArray = new JSONArray(); + for (int i = 0; i < lists.size(); i++) { + Map tempMap = lists.get(i); + + JSONArray tempJsonArray = new JSONArray(); + JSONObject lineObject = new JSONObject(); + + + for (Map.Entry> map : stringArrayListLinkedHashMap.entrySet() + ) { + JSONObject tempObject = new JSONObject(); + String key = map.getKey(); + ArrayList value = map.getValue(); + if(tempMap != null && tempMap.containsKey(key)){ + tempObject.put("fieldId",(Integer)value.get(0)); + tempObject.put("fieldName",(String)value.get(1)); + tempObject.put("fieldValue",tempMap.get(key)); + tempJsonArray.add(tempObject); + }else{ + tempObject.put("fieldId",(Integer)value.get(0)); + tempObject.put("fieldName",(String)value.get(1)); + tempObject.put("fieldValue",""); + tempJsonArray.add(tempObject); + } + + } + lineObject.put("line",tempJsonArray); + + jsonArray.add(lineObject); + } + + result.put("result",true); + result.put("msg","success"); + result.put("data",jsonArray); + + + + + + JSONArray conditionsArray = JSONObject.parseObject(json).getJSONArray("conditions"); + if(conditionsArray == null || conditionsArray.size() <= 0){ + return result.toString(); + } + List conditions = parseConditions(conditionsArray); + + + + JSONArray dataArray = result.getJSONArray("data"); + + // 构造最终输出 + JSONObject resultJsonObject = new JSONObject(); + resultJsonObject.put("result", true); + resultJsonObject.put("msg", "success"); + + JSONArray filteredData = new JSONArray(); + + for (int i = 0; i < dataArray.size(); i++) { + JSONObject itemObject = dataArray.getJSONObject(i); + JSONArray lineArray = itemObject.getJSONArray("line"); + if (matchesAllConditions(lineArray, conditions)) { + filteredData.add(itemObject); + } + } + + System.out.println("errorMsg========"+errorMsg); + if(!errorMsg.isEmpty()){ + JSONObject resultError = new JSONObject(); + resultError.put("result",false); + resultError.put("msg",errorMsg); + return resultError.toString(); + } + + + resultJsonObject.put("data", filteredData); + + + + return resultJsonObject.toJSONString(); + +// try{ +// if(session == null){ +// System.out.println("开始登录"); +// LoginUtil loginUtil = new LoginUtil(SsoApplication.tcUrl,SsoApplication.user,SsoApplication.pass); +// session = loginUtil.loginTC(); +// System.out.println("登录成功"); +// } +// List list = mapper.selectClassData(id); +// System.out.println("list=================="+list.size()); +// DataManagementService service = DataManagementService.getService(AppXSession.getConnection()); +// +// ServiceData sd = service.loadObjects(new String[]{"AsFAAEbt526JcB"}); +// ModelObject[] foundObjs = new ModelObject[ sd.sizeOfPlainObjects()]; +// for( int k =0; k< sd.sizeOfPlainObjects(); k++) { +// foundObjs[k] = sd.getPlainObject(k); +// } +// +// // ServiceData sd = service.loadObjects(list.toArray(new String[0])); +// +// // ModelObject[] foundObjs = new ModelObject[ sd.sizeOfPlainObjects()]; +//// for( int k =0; k< sd.sizeOfPlainObjects(); k++) +//// { +//// foundObjs[k] = sd.getPlainObject(k); +//// Classification.ClassificationObject classificationObject = (Classification.ClassificationObject)sd.getPlainObject(k); +//// Classification.ClassificationProperty[] properties = classificationObject.properties; +//// for (Classification.ClassificationProperty property : properties) { +//// Integer sxId = property.attributeId; +//// String value = property.values[0].dbValue; +//// +//// System.out.println("sxId="+sxId+"-----value="+value); +//// } +//// } +// +// +// Connection connection = session.getConnection(); +// // 获取服务 +// ClassificationService classService = ClassificationService.getService(connection); +// // 1. 批量获取分类对象 +// Classification.FindClassificationObjectsResponse classificationObjects1 = classService.findClassificationObjects(new WorkspaceObject[]{(ItemRevision)foundObjs[0]}); +// //获取分类对象 +// Map icos = classificationObjects1.icos; +// +// if (icos.size() > 0) { +// List classObjs = new ArrayList<>(); +// for(Map.Entry entry : icos.entrySet()){ +// if(entry.getValue() != null && entry.getValue().length > 0){ +// System.out.println("key:"+entry.getKey().getUid()); +// System.out.println("value::"+entry.getValue()[0].getUid()); +// classObjs.add(entry.getValue()[0]); +// } +// } +// Classification.GetClassificationObjectsResponse classificationObjects = +// classService.getClassificationObjects(classObjs.toArray(new ModelObject[0])); +// Map classObjects = classificationObjects.clsObjs; +// //获取对象和分类的映射 +// for (ModelObject mod : classObjects.keySet()) { +// Classification.ClassificationObject classificationObject = classObjects.get(mod); +// Classification.ClassificationProperty[] properties = classificationObject.properties; +// for (Classification.ClassificationProperty property : properties) { +// try{ +// Integer sxId = property.attributeId; +// System.out.println("sxid==="+sxId); +// String value = property.values[0].dbValue; +// System.out.println("sxId="+sxId+"-----value="+value); +// +// }catch (Exception e){ +// System.out.println("111111111111"); +// } +// } +// } +// } +// +// +// }catch (Exception e){ +// e.printStackTrace(); +// } + + } + + +private String errorMsg = ""; + + + + + private List parseConditions(JSONArray conditionsArray) { + List conditions = new ArrayList<>(); + for (int i = 0; i < conditionsArray.size(); i++) { + JSONObject conditionObj = conditionsArray.getJSONObject(i); + Condition cond = new Condition(); + cond.fieldId = conditionObj.getString("fieldId"); + cond.operator = conditionObj.getString("operator").trim(); + cond.value = conditionObj.getString("value"); + cond.min = conditionObj.getString("min"); + cond.max = conditionObj.getString("max"); + conditions.add(cond); + } + return conditions; + } + + private boolean matchesAllConditions(JSONArray lineArray, List conditions) { + Map fieldMap = new HashMap<>(); + + // 构建 fieldId -> fieldValue 映射 + for (int i = 0; i < lineArray.size(); i++) { + JSONObject fieldObj = lineArray.getJSONObject(i); + String fieldId = fieldObj.getString("fieldId"); + String fieldValue = fieldObj.getString("fieldValue"); + fieldMap.put(fieldId, fieldValue); + } + + for (Condition cond : conditions) { + String fieldValue = fieldMap.get(cond.fieldId); + if (fieldValue == null) continue; // 忽略不存在的字段 + + if (!evaluateCondition(fieldValue, cond)) { + return false; + } + } + return true; + } + + private boolean evaluateCondition(String fieldValue, Condition cond) { + switch (cond.operator) { + case "等于": + return fieldValue.equals(cond.value); + case "不等于": + return !fieldValue.equals(cond.value); + case "小于": + return compare(fieldValue, cond.value) < 0; + case "小于等于": + return compare(fieldValue, cond.value) <= 0; + case "大于": + return compare(fieldValue, cond.value) > 0; + case "大于等于": + return compare(fieldValue, cond.value) >= 0; + case "包含": + return fieldValue.contains(cond.value); + case "不包含": + return !fieldValue.contains(cond.value); + case "开始以": + return fieldValue.startsWith(cond.value); + case "结束以": + return fieldValue.endsWith(cond.value); + case "开始不是以": + return !fieldValue.startsWith(cond.value); + case "结束不是以": + return !fieldValue.endsWith(cond.value); + case "是空的": + return fieldValue.isEmpty(); + case "不是空的": + return !fieldValue.isEmpty(); + case "介于": + try { + double val = Double.parseDouble(fieldValue); + double minVal = Double.parseDouble(cond.min); + double maxVal = Double.parseDouble(cond.max); + return val >= minVal && val <= maxVal; + } catch (NumberFormatException e) { + return false; + } + default: + //throw new IllegalArgumentException("不支持的操作符: " + cond.operator); + errorMsg = "不支持的操作符: " + cond.operator; + return false; + } + } + + private int compare(String a, String b) { + try { + return Double.compare(Double.parseDouble(a), Double.parseDouble(b)); + } catch (NumberFormatException e) { + return a.compareTo(b); // 字符串比较 + } + } + + private static class Condition { + String fieldId; + String operator; + String value; + String min; + String max; + } + + + + + + + + + + + + + + + + + + /** + * 批量获取分类属性 + * @param + * @param ids + * @return + */ + public void batchGetClassificationAttributes(ItemRevision[] workspaceObjects, List ids, LinkedHashMap> attrExportMap, DataManagementService dmService) { + + try { + + + Connection connection = session.getConnection(); + // 获取服务 + ClassificationService classService = ClassificationService.getService(connection); + // 1. 批量获取分类对象 + Classification.FindClassificationObjectsResponse classificationObjects1 = classService.findClassificationObjects(workspaceObjects); + //获取分类对象 + Map icos = classificationObjects1.icos; + + if (icos.size() > 0) { + List classObjs = new ArrayList<>(); + for(Map.Entry entry : icos.entrySet()){ + if(entry.getValue() != null && entry.getValue().length > 0){ + System.out.println("key:"+entry.getKey().getUid()); + System.out.println("value::"+entry.getValue()[0].getUid()); + classObjs.add(entry.getValue()[0]); + } + } + Classification.GetClassificationObjectsResponse classificationObjects = + classService.getClassificationObjects(classObjs.toArray(new ModelObject[0])); + Map classObjects = classificationObjects.clsObjs; + //获取对象和分类的映射 + for (ModelObject mod : classObjects.keySet()) { + Classification.ClassificationObject classificationObject = classObjects.get(mod); + Classification.ClassificationProperty[] properties = classificationObject.properties; + for (Classification.ClassificationProperty property : properties) { + Integer sxId = property.attributeId; + String value = property.values[0].dbValue; + } + } + } + + } catch (Exception e) { + e.printStackTrace(); + } + } + + } + + + diff --git a/src/main/java/com/connor/sso/sso/SsoApplication.java b/src/main/java/com/connor/sso/sso/SsoApplication.java new file mode 100644 index 0000000..05a4b69 --- /dev/null +++ b/src/main/java/com/connor/sso/sso/SsoApplication.java @@ -0,0 +1,21 @@ +package com.connor.sso.sso; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; + +@SpringBootApplication +public class SsoApplication { + + public static String tcUrl; + public static String user; + public static String pass; + public static void main(String[] args) { + + ConfigurableApplicationContext contenxt = SpringApplication.run(SsoApplication.class, args); + tcUrl = contenxt.getEnvironment().getProperty("tc.server"); + user = contenxt.getEnvironment().getProperty("tc.user"); + pass = contenxt.getEnvironment().getProperty("tc.password"); + } + +} diff --git a/src/main/java/com/connor/sso/sso/clientx/AppXCredentialManager.java b/src/main/java/com/connor/sso/sso/clientx/AppXCredentialManager.java new file mode 100644 index 0000000..6a7a4ba --- /dev/null +++ b/src/main/java/com/connor/sso/sso/clientx/AppXCredentialManager.java @@ -0,0 +1,145 @@ +//================================================== +// +// Copyright 2017 Siemens Product Lifecycle Management Software Inc. All Rights Reserved. +// +//================================================== + +package com.connor.sso.sso.clientx; + +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; + +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.LineNumberReader; + +/** + * 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 new String[0]; + } + + /** + * 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; + return new String[0]; + } + + /** + * Cache the group and role + * This is called after the SessionService.setSessionGroupMember service + * operation is called. + * + * @see CredentialManager#setGroupRole(String, + * String) + */ + public void setGroupRole(String group, String role) + { + this.group = group; + this.role = role; + } + + /** + * Cache the User and Password + * This is called after the SessionService.login service operation is called. + * + * @see CredentialManager#setUserPassword(String, + * String, String) + */ + public void setUserPassword(String user, String password, String discriminator) + { + this.name = user; + this.password = password; + this.discriminator = discriminator; + } + + + public String[] promptForCredentials() + throws CanceledOperationException + { + try + { + LineNumberReader reader = new LineNumberReader(new InputStreamReader(System.in)); + System.out.println("Please enter user credentials (return to quit):"); + System.out.print("User Name: "); + name = reader.readLine(); + + if (name.length() == 0) + throw new CanceledOperationException(""); + + System.out.print("Password: "); + password = reader.readLine(); + } + catch (IOException e) + { + String message = "Failed to get the name and password.\n" + e.getMessage(); + System.out.println(message); + throw new CanceledOperationException(message); + } + + String[] tokens = { name, password, group, role, discriminator }; + return tokens; + } + +} diff --git a/src/main/java/com/connor/sso/sso/clientx/AppXExceptionHandler.java b/src/main/java/com/connor/sso/sso/clientx/AppXExceptionHandler.java new file mode 100644 index 0000000..4fe493a --- /dev/null +++ b/src/main/java/com/connor/sso/sso/clientx/AppXExceptionHandler.java @@ -0,0 +1,48 @@ +//================================================== +// +// Copyright 2017 Siemens Product Lifecycle Management Software Inc. All Rights Reserved. +// +//================================================== + +package com.connor.sso.sso.clientx; + +import com.teamcenter.schemas.soa._2006_03.exceptions.InternalServerException; +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) + { + throw new RuntimeException(ise.getMessage()); + } + + /* + * (non-Javadoc) + * + * @see com.teamcenter.soa.client.ExceptionHandler#handleException(com.teamcenter.soa.exceptions.CanceledOperationException) + */ + public void handleException(CanceledOperationException coe) + { + System.out.println(""); + System.out.println("*****"); + System.out.println("Exception caught in com.teamcenter.clientx.AppXExceptionHandler.handleException(CanceledOperationException)."); + + // Expecting this from the login tests with bad credentials, and the + // AnyUserCredentials class not + // prompting for different credentials + throw new RuntimeException(coe); + } + +} diff --git a/src/main/java/com/connor/sso/sso/clientx/AppXModelEventListener.java b/src/main/java/com/connor/sso/sso/clientx/AppXModelEventListener.java new file mode 100644 index 0000000..72a479e --- /dev/null +++ b/src/main/java/com/connor/sso/sso/clientx/AppXModelEventListener.java @@ -0,0 +1,57 @@ +package com.connor.sso.sso.clientx;////================================================== +//// +//// Copyright 2017 Siemens Product Lifecycle Management Software Inc. All Rights Reserved. +//// +////================================================== +// +//package com.connor.cadService.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; +// 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; +// for (int i = 0; i < uids.length; i++) +// { +// System.out.println(" " + uids[i]); +// } +// +// } +// +//} diff --git a/src/main/java/com/connor/sso/sso/clientx/AppXPartialErrorListener.java b/src/main/java/com/connor/sso/sso/clientx/AppXPartialErrorListener.java new file mode 100644 index 0000000..1ea1580 --- /dev/null +++ b/src/main/java/com/connor/sso/sso/clientx/AppXPartialErrorListener.java @@ -0,0 +1,57 @@ +//================================================== +// +// Copyright 2017 Siemens Product Lifecycle Management Software Inc. All Rights Reserved. +// +//================================================== + + +package com.connor.sso.sso.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; + + + for (int i = 0; i < stacks.length; i++) + { + ErrorValue[] errors = stacks[i].getErrorValues(); + System.out.print("Partial Error for "); + + // The different service implementation may optionally associate + // an ModelObject, client ID, or nothing, with each partial error + if (stacks[i].hasAssociatedObject()) + { + System.out.println( "object " + stacks[i].getAssociatedObject().getUid() ); + } + else if (stacks[i].hasClientId()) + { + System.out.println( "client id " + stacks[i].getClientId() ); + } + else if (stacks[i].hasClientIndex()) + System.out.println( "client index " + stacks[i].getClientIndex() ); + + + // Each Partial Error will have one or more contributing error messages + for (int j = 0; j < errors.length; j++) + { + System.out.println(" Code: " + errors[j].getCode() + "\tSeverity: " + + errors[j].getLevel() + "\t" + errors[j].getMessage()); + } + } + + } + +} diff --git a/src/main/java/com/connor/sso/sso/clientx/AppXRequestListener.java b/src/main/java/com/connor/sso/sso/clientx/AppXRequestListener.java new file mode 100644 index 0000000..aaca651 --- /dev/null +++ b/src/main/java/com/connor/sso/sso/clientx/AppXRequestListener.java @@ -0,0 +1,36 @@ +package com.connor.sso.sso.clientx;////================================================== +//// +//// Copyright 2017 Siemens Product Lifecycle Management Software Inc. All Rights Reserved. +//// +////================================================== +// +//package com.connor.cadService.clientx; +// +//import com.teamcenter.soa.client.RequestListener; +// +///** +// * This implementation of the RequestListener, logs each service request +// * to the console. +// * +// */ +//public class AppXRequestListener implements RequestListener +//{ +// +// /** +// * Called before each request is sent to the server. +// */ +// public void serviceRequest ( final Info info ) +// { +// // will log the service name when done +// } +// +// /** +// * Called after each response from the server. +// * Log the service operation to the console. +// */ +// public void serviceResponse( final Info info ) +// { +// System.out.println( info.id +": "+info.service+"."+info.operation); +// } +// +//} diff --git a/src/main/java/com/connor/sso/sso/clientx/AppXSession.java b/src/main/java/com/connor/sso/sso/clientx/AppXSession.java new file mode 100644 index 0000000..7b5137a --- /dev/null +++ b/src/main/java/com/connor/sso/sso/clientx/AppXSession.java @@ -0,0 +1,275 @@ +//================================================== +// +// Copyright 2017 Siemens Product Lifecycle Management Software Inc. All Rights Reserved. +// +//================================================== + +package com.connor.sso.sso.clientx; + +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.NotLoadedException; + +import java.text.SimpleDateFormat; +import java.util.*; + +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 AppXCredentialManager credentialManager; + + private User user; + + /** + * 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() ); +// +// } + public AppXSession(String host) throws Exception{ + // 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). + System.out.println("host"+host); + 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; + } + + System.out.println(protocol); + + // 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); + + System.out.println(connection); + 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; + } + + /** + * Login to the Teamcenter Server + * + */ + public User login(String userId, String password, String group, String role) throws Exception { + System.out.println("userid :"+userId+"password"+password); + SessionService sessionService = SessionService.getService(connection); + String[] credentials = new String[] { userId, password, group, role,UUID.randomUUID().toString()}; + LoginResponse out = sessionService.login(credentials[0], credentials[1], credentials[2], credentials[3], "zh_CN", credentials[4]); + this.user = out.user; + return out.user; + } + + public User getUser() { + return this.user; + } + + /** + * 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 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 void getUsers(ModelObject[] objects) { + if (objects == null) + return; + + DataManagementService dmService = DataManagementService.getService(getConnection()); + + List unKnownUsers = new Vector(); + for (int i = 0; i < objects.length; i++) { + if (!(objects[i] instanceof WorkspaceObject)) + continue; + + WorkspaceObject wo = (WorkspaceObject) objects[i]; + + User owner = null; + try { + owner = (User) wo.get_owning_user(); + owner.get_user_name(); + } catch (NotLoadedException e) { + if (owner != null) + unKnownUsers.add(owner); + } + } + User[] users = (User[]) unKnownUsers.toArray(new User[unKnownUsers.size()]); + String[] attributes = { "user_name" }; + + // ***************************** + // Execute the service operation + // ***************************** + dmService.getProperties(users, attributes); + + } + +} diff --git a/src/main/java/com/connor/sso/sso/mapper/ClassFieldBean.java b/src/main/java/com/connor/sso/sso/mapper/ClassFieldBean.java new file mode 100644 index 0000000..ab48634 --- /dev/null +++ b/src/main/java/com/connor/sso/sso/mapper/ClassFieldBean.java @@ -0,0 +1,28 @@ +package com.connor.sso.sso.mapper; + +public class ClassFieldBean { + + private Integer punct; + private String pname; + + public ClassFieldBean(Integer punct, String pname) { + this.punct = punct; + this.pname = pname; + } + + public Integer getPunct() { + return punct; + } + + public void setPunct(Integer punct) { + this.punct = punct; + } + + public String getPname() { + return pname; + } + + public void setPname(String pname) { + this.pname = pname; + } +} diff --git a/src/main/java/com/connor/sso/sso/mapper/FieldBean.java b/src/main/java/com/connor/sso/sso/mapper/FieldBean.java new file mode 100644 index 0000000..f3e6d72 --- /dev/null +++ b/src/main/java/com/connor/sso/sso/mapper/FieldBean.java @@ -0,0 +1,59 @@ +package com.connor.sso.sso.mapper; + +public class FieldBean { + + private String puid; + private String pcid; + private String pname; + private String pklassi; + private String parent; + + + public FieldBean(String puid, String pcid, String pname, String pklassi, String parent) { + this.puid = puid; + this.pcid = pcid; + this.pname = pname; + this.pklassi = pklassi; + this.parent = parent; + } + + public String getPuid() { + return puid; + } + + public void setPuid(String puid) { + this.puid = puid; + } + + public String getPcid() { + return pcid; + } + + public void setPcid(String pcid) { + this.pcid = pcid; + } + + public String getPname() { + return pname; + } + + public void setPname(String pname) { + this.pname = pname; + } + + public String getPklassi() { + return pklassi; + } + + public void setPklassi(String pklassi) { + this.pklassi = pklassi; + } + + public String getParent() { + return parent; + } + + public void setParent(String parent) { + this.parent = parent; + } +} diff --git a/src/main/java/com/connor/sso/sso/mapper/MyMapper.java b/src/main/java/com/connor/sso/sso/mapper/MyMapper.java new file mode 100644 index 0000000..4d522a5 --- /dev/null +++ b/src/main/java/com/connor/sso/sso/mapper/MyMapper.java @@ -0,0 +1,38 @@ +package com.connor.sso.sso.mapper; + +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@org.apache.ibatis.annotations.Mapper +public interface MyMapper { + +// @Select("Select puid from PPom_USER where puser_id = #{puser_id,jdbcType=VARCHAR}") +// public String selectUserUid(@Param("puser_id")String puser_id); +// +// @Select("SELECT count(*) FROM PWORKSPACEOBJECT t_01 , PEPMTASK t_02 WHERE ( ( ( ( ( t_02.pstate_value = 4 OR ( t_02.pstate_value >= 128 ) ) AND t_02.rresponsible_partyu = #{rresponsible_partyu,jdbcType=VARCHAR} ) AND t_01.pobject_type NOT IN ('EPMNotifyTask', 'EPMPerformSignoffTask' ) ) AND ( t_01.pobject_type = 'EPMRouteTask' OR NOT EXISTS ( SELECT DISTINCT t_03.puid FROM PEPMTASK t_03 WHERE ( ( t_03.pstate_value = 4 OR ( t_03.pstate_value >= 128 ) ) AND ( t_03.rparent_tasku = t_02.puid ) ) ) ) ) AND ( t_01.puid = t_02.puid ) )") +// public int selectCount(@Param("rresponsible_partyu")String rresponsible_partyu); + +// @Select("select VLA_847_3 from PFOLDER where puid =(SELECT PVAlu_0 FROM PCONTENTS WHERE PUID = (SELECT PUID from PWORKSPACEOBJECT where POBJECT_NAME like '%#{id}%' and Pobject_type = 'TaskInbox') and rownum=1)") +// public int selectCount(@Param("id")String id); + + + @Select("select t1.puid,t1.pcid,t1.pname,t1.pklassi,t2.pval_0 as parent from PSMLB0 t1 left join PPARENT t2 on t1.puid = t2.puid") + public List selectTree(); + + @Select({"select b.punct,c.pname from PSMLB0 a inner join PSMLB1 b on a.puid = b.rtag_to_headeru inner join PUNCT_DICT c on b.punct = c.punct where a.pcid = #{pcid}"}) + public List selectClassField(String pcid); + + @Select("${_parameter}") + List> selectClassData(String sql); + + @Select({"select t1.punct ,t2.pname,t2.pref_options,t1.pdbindex from PSMLB1 t1" + + " inner join (SELECT pref_options,punct,pname FROM PPOM_OBJECT a1, PUNCT_DICT a2 WHERE a1.puid=a2.puid AND a2.puid IN (SELECT t_02.puid FROM PSMLB1 t_01 , PUNCT_DICT t_02 WHERE ( t_01.rtag_to_headeru IN ( SELECT t_03.puid FROM PSMLB0 t_03 WHERE ( t_03.pcid = #{pcid} ) ) AND ( t_01.punct = t_02.punct ) ))) t2" + + " on t1.punct = t2.punct" + + " where t1.rtag_to_headeru= (select puid from PSMLB0 where pcid = #{pcid}) order by punct ASC"}) + public List selectFields(String pcid); + +} diff --git a/src/main/java/com/connor/sso/sso/mapper/SqlFieldBean.java b/src/main/java/com/connor/sso/sso/mapper/SqlFieldBean.java new file mode 100644 index 0000000..cbb7d2b --- /dev/null +++ b/src/main/java/com/connor/sso/sso/mapper/SqlFieldBean.java @@ -0,0 +1,59 @@ +package com.connor.sso.sso.mapper; + +public class SqlFieldBean { + + private Integer punct; + private String pname; + private String pref_options; + private Integer pdbindex; + private String value; + public SqlFieldBean(Integer punct, String pname, String pref_options, Integer pdbindex) { + this.punct = punct; + this.pname = pname; + this.pref_options = pref_options; + this.pdbindex = pdbindex; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public Integer getPunct() { + return punct; + } + + public void setPunct(Integer punct) { + this.punct = punct; + } + + public String getPname() { + return pname; + } + + public void setPname(String pname) { + this.pname = pname; + } + + public String getPref_options() { + return pref_options; + } + + public void setPref_options(String pref_options) { + this.pref_options = pref_options; + } + + public Integer getPdbindex() { + return pdbindex; + } + + public void setPdbindex(Integer pdbindex) { + this.pdbindex = pdbindex; + } + + + +} diff --git a/src/main/java/com/connor/sso/sso/util/KUtil.java b/src/main/java/com/connor/sso/sso/util/KUtil.java new file mode 100644 index 0000000..9ea7459 --- /dev/null +++ b/src/main/java/com/connor/sso/sso/util/KUtil.java @@ -0,0 +1,809 @@ +package com.connor.sso.sso.util; +//teamcenter.com/Schemas/Manufacturing/2018-11/StructureManagement + + + +import com.connor.sso.sso.clientx.AppXSession; +import com.teamcenter.schemas.soa._2006_03.exceptions.ServiceException; +import com.teamcenter.services.loose.core._2006_03.FileManagement; +import com.teamcenter.services.strong.core.DataManagementService; +import com.teamcenter.services.strong.core.FileManagementService; +import com.teamcenter.services.strong.core.SessionService; +import com.teamcenter.services.strong.core._2007_01.DataManagement; +import com.teamcenter.services.strong.core._2007_06.DataManagement.ExpandGRMRelationsData; +import com.teamcenter.services.strong.core._2007_06.DataManagement.ExpandGRMRelationsPref; +import com.teamcenter.services.strong.core._2007_06.DataManagement.ExpandGRMRelationsResponse; +import com.teamcenter.services.strong.core._2007_06.DataManagement.RelationAndTypesFilter2; +import com.teamcenter.services.strong.core._2007_12.Session; +import com.teamcenter.services.strong.core._2008_06.DataManagement.SaveAsNewItemInfo; +import com.teamcenter.services.strong.core._2008_06.DataManagement.SaveAsNewItemResponse2; +import com.teamcenter.services.strong.query.SavedQueryService; +import com.teamcenter.services.strong.query._2006_03.SavedQuery.GetSavedQueriesResponse; +import com.teamcenter.services.strong.query._2006_03.SavedQuery.SavedQueryObject; +import com.teamcenter.services.strong.query._2007_06.SavedQuery.ExecuteSavedQueriesResponse; +import com.teamcenter.services.strong.query._2007_06.SavedQuery.SavedQueryInput; +import com.teamcenter.services.strong.query._2007_09.SavedQuery; +import com.teamcenter.soa.client.Connection; +import com.teamcenter.soa.client.FileManagementUtility; +import com.teamcenter.soa.client.GetFileResponse; +import com.teamcenter.soa.client.model.ModelObject; +import com.teamcenter.soa.client.model.Property; +import com.teamcenter.soa.client.model.ServiceData; +import com.teamcenter.soa.client.model.strong.*; + +import java.io.File; +import java.io.FileNotFoundException; +import java.util.*; + +public class KUtil { + + + private static User loginedUser; + public static DataManagementService dmService; + private static Map loadedObjects = new HashMap(); + private static Map loadedQueries = new HashMap(); + private static SavedQueryService queryService; + private static AppXSession session; + + private KUtil() { + + } + public static void changeOwner(ModelObject newComp, User userOwn, Group group) { + com.teamcenter.services.strong.core._2006_03.DataManagement.ObjectOwner objectOwner + = new com.teamcenter.services.strong.core._2006_03.DataManagement.ObjectOwner(); + objectOwner.object = newComp; + objectOwner.owner = userOwn; + objectOwner.group = group; + //更改所有者 + dmService.changeOwnership(new com.teamcenter.services.strong.core._2006_03.DataManagement.ObjectOwner[]{objectOwner}); + } + + public static void changeOwners(ModelObject[] newComps, User userOwn, Group group) { + com.teamcenter.services.strong.core._2006_03.DataManagement.ObjectOwner[] mobjs = + new com.teamcenter.services.strong.core._2006_03.DataManagement.ObjectOwner[newComps.length]; + for (int i = 0; i < newComps.length; i++) { + com.teamcenter.services.strong.core._2006_03.DataManagement.ObjectOwner objectOwner = + new com.teamcenter.services.strong.core._2006_03.DataManagement.ObjectOwner(); + objectOwner.object = newComps[i]; + objectOwner.owner = userOwn; + objectOwner.group = group; + mobjs[i] = objectOwner; + } + dmService.changeOwnership(mobjs); + } + + /** + * 通过SOA创建ITEM对象 + * + * @param itemID + * 创建对象的ID + * @param itemRev + * 创建对象的版本 + * @param itemType + * 创建对象的类型 + * @param itemName + * 创建对象的名称 + * @param itemDesc + * 创建对象的描述 + * @param unit + * 创建对象的单位 + * @param itemPropMap + * 创建对象的ITEM属性 + * @param itemRevPropMap + * 创建对象的版本属性 + * @param itemRevMasterPropMap + * 创建对象的版本表单属性 + */ + public static Item createNewItemSoa( + String itemID, String itemRev, String itemType, String itemName, + String itemDesc, String unit, Map itemPropMap, + Map itemRevPropMap, + Map itemRevMasterPropMap, Group group, User userOwn, ItemRevision zcRev) { + Item newComp = null; + try { + DataManagementService datamanagementservice = DataManagementService + .getService(AppXSession.getConnection()); + com.teamcenter.services.strong.core._2006_03.DataManagement.CreateItemsResponse createitemsresponse = null; + // 设置创建对象的主要属性 + com.teamcenter.services.strong.core._2006_03.DataManagement.ItemProperties aitemproperties[] = new com.teamcenter.services.strong.core._2006_03.DataManagement.ItemProperties[1]; + aitemproperties[0] = new com.teamcenter.services.strong.core._2006_03.DataManagement.ItemProperties(); + aitemproperties[0].clientId = Integer.toString(1); + aitemproperties[0].description = itemDesc; + aitemproperties[0].itemId = itemID; + aitemproperties[0].name = itemName; + aitemproperties[0].revId = itemRev; + aitemproperties[0].type = itemType; + aitemproperties[0].uom = unit; + ArrayList list = new ArrayList(); + // 设置item对象的扩展属性 + if (itemPropMap != null) { + com.teamcenter.services.strong.core._2006_03.DataManagement.RevisionIds revids = null; + com.teamcenter.services.strong.core._2006_03.DataManagement.ExtendedAttributes extendedattributesItem = new com.teamcenter.services.strong.core._2006_03.DataManagement.ExtendedAttributes(); + extendedattributesItem = new com.teamcenter.services.strong.core._2006_03.DataManagement.ExtendedAttributes(); + extendedattributesItem.objectType = itemType; + extendedattributesItem.attributes = itemPropMap; + list.add(extendedattributesItem); + } + // 设置REV的扩展属性 + if (itemRevPropMap != null) { + com.teamcenter.services.strong.core._2006_03.DataManagement.ExtendedAttributes extendedattributesRev = new com.teamcenter.services.strong.core._2006_03.DataManagement.ExtendedAttributes(); + extendedattributesRev = new com.teamcenter.services.strong.core._2006_03.DataManagement.ExtendedAttributes(); + extendedattributesRev.objectType = itemType + "Revision"; + extendedattributesRev.attributes = itemRevPropMap; + list.add(extendedattributesRev); + } + // 设置REVMASTER的扩展属性 + if (itemRevMasterPropMap != null) { + com.teamcenter.services.strong.core._2006_03.DataManagement.ExtendedAttributes extendedattributesRevMaster = new com.teamcenter.services.strong.core._2006_03.DataManagement.ExtendedAttributes(); + extendedattributesRevMaster = new com.teamcenter.services.strong.core._2006_03.DataManagement.ExtendedAttributes(); + extendedattributesRevMaster.objectType = itemType + + "RevisionMaster"; + extendedattributesRevMaster.attributes = itemRevMasterPropMap; + list.add(extendedattributesRevMaster); + } + // 添加扩展属性 + if (list.size() != 0) { + com.teamcenter.services.strong.core._2006_03.DataManagement.ExtendedAttributes extendedattributes[] = null; + extendedattributes = new com.teamcenter.services.strong.core._2006_03.DataManagement.ExtendedAttributes[list + .size()]; + for (int i = 0; i < list.size(); i++) { + extendedattributes[i] = list.get(i); + } + aitemproperties[0].extendedAttributes = extendedattributes; + } + ModelObject tccomponent1 = null; + String s1 = ""; + createitemsresponse = datamanagementservice.createItems( + aitemproperties, tccomponent1, s1); + if (createitemsresponse.serviceData.sizeOfPartialErrors() == 0) { + newComp = createitemsresponse.output[0].item; + + changeOwner(newComp,userOwn,group); + changeOwner(createitemsresponse.output[0].itemRev,userOwn,group); + com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship[] + rela_vec = new com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship[1]; + com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship + one_rela = new com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship(); + one_rela.clientId = ""; + one_rela.primaryObject = createitemsresponse.output[0].itemRev; + one_rela.secondaryObject = zcRev; + one_rela.relationType = "IMAN_METarget"; + one_rela.userData = null; + rela_vec[0] = one_rela; + dmService.createRelations(rela_vec); + }else { + System.out.println(createitemsresponse.serviceData.getPartialError(0).getMessages()[0]); + } + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + System.out.println("创建对象[item_id= " + itemID + " / rev =" + itemRev + + " / name= " + itemName + "]失败"); + } + return newComp; + } + public static Item saveAsItem(ItemRevision rev, String itemId, String revId, String name, Group group, User userOwn, ItemRevision gyrev){ + DataManagementService service1 = DataManagementService.getService(AppXSession.getConnection()); + + SaveAsNewItemInfo[] infos = + new SaveAsNewItemInfo[1]; + SaveAsNewItemInfo info = + new SaveAsNewItemInfo(); + info.baseItemRevision = rev; + info.newItemId = itemId; + info.name = name; + info.newRevId = revId; + info.clientId = "clientId"; + + infos[0] = info; + + try { +// service1.revise() +// service1.revise() + System.out.println("开始另存"); + SaveAsNewItemResponse2 saveAsNewItem = service1.saveAsNewItem2(infos); + System.out.println("结束另存"); + ServiceData serviceData = saveAsNewItem.serviceData; + KUtil.checkPartialError(serviceData); + int sizeOfCreatedObjects = saveAsNewItem.serviceData.sizeOfCreatedObjects(); + System.out.println("另存对象个数:"+sizeOfCreatedObjects); + Item createdObject = null; + if(saveAsNewItem.serviceData.sizeOfCreatedObjects()>0){ + for (int t = 0; t < sizeOfCreatedObjects; t++) { + ModelObject modj = saveAsNewItem.serviceData.getCreatedObject(t); + if (modj instanceof Item) { + System.out.println("开始修改所有权"); + createdObject = (Item) saveAsNewItem.serviceData.getCreatedObject(t); + try { + refreshAndGetProperties(createdObject, new String[] {"revision_list","bom_view_tags"}); + + ModelObject[] revisionList = createdObject.get_revision_list(); + System.out.println("开始修改所有权"); + changeOwner(createdObject,userOwn,group); + changeOwner(revisionList[0],userOwn,group); + System.out.println("结束修改所有权"); + removeRelation("IMAN_METarget", revisionList[0]); + if(gyrev != null) { + com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship[] + rela_vec = new com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship[1]; + com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship + one_rela = new com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship(); + one_rela.clientId = ""; + //one_rela.primaryObject = createitemsresponse.output[0].itemRev; + one_rela.primaryObject = revisionList[0]; + one_rela.secondaryObject = gyrev; + one_rela.relationType = "IMAN_METarget"; + one_rela.userData = null; + rela_vec[0] = one_rela; + dmService.createRelations(rela_vec); + } + ModelObject[] bom_view_tags = createdObject.get_bom_view_tags(); + if(bom_view_tags!=null && bom_view_tags.length>0) { + changeOwner(bom_view_tags[0],userOwn,group); + } + + + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + +// System.out.println("createdObject"+createdObject); + return createdObject; + } + + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static void removeRelation(String relationType, ModelObject revision) throws Exception { + refreshAndGetProperties(revision, new String[] { relationType }); + ModelObject[] modelObjectArrayValue = revision.getPropertyObject(relationType).getModelObjectArrayValue(); + byte b; + int i; + ModelObject[] arrayOfModelObject1; + for (i = (arrayOfModelObject1 = modelObjectArrayValue).length, b = 0; b < i; ) { + ModelObject modelObject = arrayOfModelObject1[b]; + com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship[] rela_vec = new com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship[1]; + com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship one_rela = new com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship(); + one_rela.clientId = "Connor"; + one_rela.primaryObject = revision; + one_rela.secondaryObject = modelObject; + one_rela.relationType = relationType; + one_rela.userData = null; + rela_vec[0] = one_rela; + ServiceData serviceData = dmService.deleteRelations(rela_vec); + b++; + } + } + public static void getChildTask(ScheduleTask fnd0SummaryTask, ArrayList child_tasks){ + try { + child_tasks.add(fnd0SummaryTask); + KUtil.refreshAndGetProperties(fnd0SummaryTask, "child_task_taglist"); + ScheduleTask[] child_task_taglist = fnd0SummaryTask.get_child_task_taglist(); + for(ScheduleTask scheduleTask:child_task_taglist){ + getChildTask(scheduleTask,child_tasks); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + + + public static void checkLogin() throws Exception { + if (loginedUser == null) { + throw new Exception("请先登录"); + } + } + + public static User getLoginUser() { + return loginedUser; + } + + + public static GroupMember findGroupMember(String group, String role, String userId) + { + ImanQuery query = null; + GroupMember groupMember = null; + + SavedQueryService queryService = SavedQueryService.getService(session.getConnection()); + DataManagementService dmService= DataManagementService.getService(session.getConnection()); + try + { + GetSavedQueriesResponse savedQueries = queryService.getSavedQueries(); + if (savedQueries.queries.length == 0) + { + System.out.println("There are no saved queries in the system."); + return groupMember; + } + + for (int i = 0; i < savedQueries.queries.length; i++) + { + + if (savedQueries.queries[i].name.equals("__EINT_group_members")) + { + query = savedQueries.queries[i].query; + break; + } + } + } + catch (ServiceException e) + { + System.out.println("GetSavedQueries service request failed."); + System.out.println(e.getMessage()); + return groupMember; + } + + if (query == null) + { + System.out.println("There is not an '__EINT_group_members' query."); + return groupMember; + } + +// try +// { + com.teamcenter.services.strong.query._2008_06.SavedQuery.QueryInput savedQueryInput[] = new com.teamcenter.services.strong.query._2008_06.SavedQuery.QueryInput[1]; + savedQueryInput[0] = new com.teamcenter.services.strong.query._2008_06.SavedQuery.QueryInput(); + savedQueryInput[0].query = query; + savedQueryInput[0].entries = new String[3]; + savedQueryInput[0].values = new String[3]; + savedQueryInput[0].entries[0] = "Group"; + savedQueryInput[0].values[0] = "*"; + savedQueryInput[0].entries[1] = "Role"; + savedQueryInput[0].values[1] = "*"; + savedQueryInput[0].entries[2] = "User"; + savedQueryInput[0].values[2] = userId; + savedQueryInput[0].maxNumToReturn = 25; + + SavedQuery.SavedQueriesResponse savedQueryResult = queryService.executeSavedQueries(savedQueryInput); + SavedQuery.QueryResults found = savedQueryResult.arrayOfResults[0]; + + int length = found.objectUIDS.length; + + String[] uids = new String[length]; + for( int ii = 0; ii < length; ii++) + { + uids[ii]= found.objectUIDS[ii]; + } + ServiceData sd = dmService.loadObjects(uids); + ModelObject[] foundObjs = new ModelObject[ sd.sizeOfPlainObjects()]; + for( int k =0; k< sd.sizeOfPlainObjects(); k++) + { + foundObjs[k] = sd.getPlainObject(k); + } + groupMember = (GroupMember) foundObjs[0]; +// } +// catch (Exception e) +// { +// System.out.println("ExecuteSavedQuery service request failed."); +// System.out.println(e.getMessage()); +// } + return groupMember; + } + + public synchronized static ModelObject UidToString(String uid) { + + + ServiceData sd = dmService.loadObjects(new String[] {uid}); +// ModelObject[] foundObjs = new ModelObject[ sd.sizeOfPlainObjects()]; + + if(sd.sizeOfPartialErrors()>0) { + + + return null; + } + + + return sd.getPlainObject(0); + + } + + + + public synchronized static AppXSession login(String url, String user, String password) throws Exception { + System.out.println("登录到TC:" + user + "url" + url); + String group = ""; + String role = ""; + + System.out.println("开始连接服务器:"+url+ new Date()); + session = new AppXSession(url); + + try { + System.out.println("开始登录" +new Date()); + loginedUser = session.login(user, password, group, role); + + System.out.println("登陆成功"); +// loginedUser.get_de + } catch (Exception e) { + e.printStackTrace(); + System.out.println("登录失败"); + } + if (loginedUser == null) { + throw new Exception("登录到Teamcenter失败"); + } + dmService = DataManagementService.getService(AppXSession.getConnection()); + queryService = SavedQueryService.getService(AppXSession.getConnection()); + return session; + } + + public static void getProperties(ModelObject modelObject, String... properties) throws Exception { + loadedObjects.put(modelObject.getUid(), modelObject); + ServiceData resp = dmService.getProperties(new ModelObject[]{modelObject}, properties); + checkPartialError(resp); + } + + public static void refreshAndGetProperties(ModelObject modelObject, String... properties) throws Exception { + System.out.println("开始刷新"); + ServiceData resp = dmService.refreshObjects(new ModelObject[]{modelObject}); + System.out.println("结束刷新"); + checkPartialError(resp); + System.out.println("获取属性"); + getProperties(modelObject, properties); + System.out.println("结束属性"); + } + + public static List getGRMChildren(ModelObject modelObject, String relation, String[] typeNames) throws Exception { + List res = new ArrayList(); + ExpandGRMRelationsPref pref = new ExpandGRMRelationsPref(); + RelationAndTypesFilter2 filter = new RelationAndTypesFilter2(); + filter.relationName = relation; + filter.objectTypeNames = typeNames; + pref.expItemRev = false; + pref.info = new RelationAndTypesFilter2[]{filter}; + ExpandGRMRelationsResponse resp = dmService.expandGRMRelationsForPrimary(new ModelObject[]{modelObject}, pref); + checkPartialError(resp.serviceData); + ExpandGRMRelationsData[] datas = resp.output[0].otherSideObjData; + int len = KUtil.getLen(datas); + for (int i = 0; i < len; i++) { + ExpandGRMRelationsData data = datas[i]; + ModelObject[] cc = data.otherSideObjects; + int childCnt = KUtil.getLen(cc); + for (int j = 0; j < childCnt; j++) { + res.add(cc[i]); + } + } + return res; + } + + public synchronized static void logoutAndClearCache2() { + if (loginedUser == null) { + return; + } +// KUtil.log(logger, "注销并释放资源"); + try { + if (loadedObjects.size() > 0) { + dmService.unloadObjects(loadedObjects.values().toArray(new ModelObject[]{})); + } + } catch (Exception e) { + e.printStackTrace(); +// KUtil.log(logger, "卸载对象失败", e); + } + try { + setByPass(false); + } catch (Exception e) { + e.printStackTrace(); +// KUtil.log(logger, "关闭旁路失败", e); + } + session.logout(); + loginedUser = null; +// KUtil.log(logger, "已结束"); + } + + public static void checkPartialError(ServiceData data) throws Exception { + if (data.sizeOfPartialErrors() > 0) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < data.sizeOfPartialErrors(); i++) { + for (String msg : data.getPartialError(i).getMessages()) { + sb.append(msg + "\r\n"); + } + } + if (sb.length() > 0) { + throw new Exception(sb.toString()); + } + } + } + + public static boolean isEmpty(String str) { + return str == null || "".equals(str.trim()); + } + + public static ImanQuery findQuery(String queryName) throws Exception { + if (KUtil.isEmpty(queryName)) { + throw new Exception("查询名称不可为空"); + } + if (loadedQueries.containsKey(queryName)) { + return loadedQueries.get(queryName); + } + GetSavedQueriesResponse resp = queryService.getSavedQueries(); + checkPartialError(resp.serviceData); + int len = resp.queries == null ? 0 : resp.queries.length; + for (int i = 0; i < len; i++) { + SavedQueryObject queryObj = resp.queries[i]; + if (queryName.equals(queryObj.name)) { + loadedQueries.put(queryName, queryObj.query); + return queryObj.query; + } + } + throw new Exception("未找到保存的查询“" + queryName + "”"); + } + + public static List query(ImanQuery query, String[] entries, String[] values) throws Exception { + List res = new ArrayList(); + SavedQueryInput input = new SavedQueryInput(); + input.query = query; + input.entries = entries; + input.values = values; + input.resultsType = 0; + ExecuteSavedQueriesResponse resp = queryService.executeSavedQueries(new SavedQueryInput[]{input}); + checkPartialError(resp.serviceData); + for (ModelObject e : resp.arrayOfResults[0].objects) { + res.add(e); + } + return res; + } + + public static void setByPass(boolean b) throws Exception { + Session.StateNameValue[] propPairs = new Session.StateNameValue[1]; + propPairs[0] = new Session.StateNameValue(); + propPairs[0].name = new String("bypassFlag"); + propPairs[0].value = new String(Property.toBooleanString(b)); + ServiceData data = SessionService.getService(AppXSession.getConnection()).setUserSessionState(propPairs); + checkPartialError(data); + } + + public static void setProperty(ModelObject mo, String propName, String propValue) throws Exception { + Map properties = new HashMap(); + DataManagement.VecStruct vec = new DataManagement.VecStruct(); + vec.stringVec = new String[]{propValue}; + properties.put(propName, vec); + ServiceData sd = dmService.setProperties(new ModelObject[]{mo}, properties); + checkPartialError(sd); + } + + public static void openByPass() { + Session.StateNameValue[] propPairs = new Session.StateNameValue[1]; + propPairs[0] = new Session.StateNameValue(); + (propPairs[0]).name = "bypassFlag"; + (propPairs[0]).value = Property.toBooleanString(true); + ServiceData data = SessionService.getService(AppXSession.getConnection()).setUserSessionState(propPairs); + } + + public static void closeByPass() { + Session.StateNameValue[] propPairs = new Session.StateNameValue[1]; + propPairs[0] = new Session.StateNameValue(); + (propPairs[0]).name = "bypassFlag"; + (propPairs[0]).value = Property.toBooleanString(false); + ServiceData data = SessionService.getService(AppXSession.getConnection()).setUserSessionState(propPairs); + } + public static File[] getDatasetFile(Dataset dataset, DataManagementService dm, String fmsurl) throws Exception { + if (dataset == null) { + return null; + } + ModelObject[] mo = new ModelObject[]{dataset}; + dm.refreshObjects(mo); + dm.getProperties(mo, new String[]{"ref_list"}); + ModelObject[] files = dataset.get_ref_list(); + if (files.length == 0) { + return null; + } + ImanFile imanFile = (ImanFile) files[0]; +// imanFile.get_fi + dm.getProperties(new ModelObject[]{imanFile}, new String[]{"original_file_name"}); + String fileName = imanFile.get_original_file_name(); + String[] url = new String[]{fmsurl}; + GetFileResponse resp = null; + try { + FileManagementUtility fm = new FileManagementUtility(AppXSession.getConnection(), null, null, url,"D:\\"); + resp = fm.getFiles(new ModelObject[]{imanFile}); + throwServiceDataError(resp); + } catch (Exception e) { +// e.printStackTrace(); + + FileManagementUtility fm = new FileManagementUtility(AppXSession.getConnection(), null, null, new String[]{fmsurl.replaceAll("Server1","Server2")}, "D:\\"); + resp = fm.getFiles(new ModelObject[]{imanFile}); + throwServiceDataError(resp); + + } + + File[] respFiles = resp.getFiles(); + File targetFile = new File("D:\\" + fileName); + if (respFiles.length > 0) { + respFiles[0].renameTo(targetFile); + } + + dm.deleteObjects(new ModelObject[] {dataset}); + + return new File[]{targetFile}; + } + public static void throwServiceDataError(GetFileResponse serviceData) throws Exception { + if (serviceData.sizeOfPartialErrors() > 0) { + StringBuilder errInfo = new StringBuilder(); + for (int i = 0; i < serviceData.sizeOfPartialErrors(); i++) { + for (String msg : serviceData.getPartialError(i).getMessages()) { + errInfo.append(msg + "\n"); + } + } + throw new Exception(errInfo.toString()); + } + } + public static Dataset createDataset(ItemRevision revision, DataManagementService dmService, String name) throws Exception { + Dataset dataset = null; + openByPass(); + com.teamcenter.services.strong.core._2010_04.DataManagement.DatasetInfo[] datasetInfos = new com.teamcenter.services.strong.core._2010_04.DataManagement.DatasetInfo[1]; + datasetInfos[0] = new com.teamcenter.services.strong.core._2010_04.DataManagement.DatasetInfo(); + datasetInfos[0].name = name; + datasetInfos[0].type = "PDF"; + datasetInfos[0].description = "TCServerCreate"; + com.teamcenter.services.strong.core._2010_04.DataManagement.CreateDatasetsResponse response = dmService.createDatasets(datasetInfos); + dataset = response.datasetOutput[0].dataset; + com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship[] + rela_vec = new com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship[1]; + com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship + one_rela = new com.teamcenter.services.strong.core._2006_03.DataManagement.Relationship(); + one_rela.clientId = ""; + one_rela.primaryObject = revision; + one_rela.secondaryObject = dataset; + one_rela.relationType = "IMAN_specification"; + one_rela.userData = null; + rela_vec[0] = one_rela; + + //解除锁定对象 + dmService.refreshObjects2(new ModelObject[]{revision, dataset}, false); + + //创建关系 + com.teamcenter.services.strong.core._2006_03.DataManagement.CreateRelationsResponse + reResp = null; + int breakTime = 0; + boolean createSuccess = false; + while (!createSuccess){ + try { + reResp= dmService.createRelations(rela_vec); + createSuccess = true; + }catch (Exception e){ + createSuccess = false; + System.out.println("创建关系失败:"); + } + breakTime ++; + + Thread.sleep(1000); + + if(breakTime > 15){ + System.out.println("循环15秒创建关系依旧失败,不再创建关系"); + break; + } + } + System.out.println("开始更改所有者"); + //获取版本的所有者和所有组 + dmService.getProperties(new ModelObject[]{revision}, new String[]{"owning_user", "owning_group"}); + + User ownUser = (User) revision.get_owning_user(); + Group ownGroup = (Group) revision.get_owning_group(); + com.teamcenter.services.strong.core._2006_03.DataManagement.ObjectOwner objectOwner + = new com.teamcenter.services.strong.core._2006_03.DataManagement.ObjectOwner(); + objectOwner.object = dataset; + objectOwner.owner = ownUser; + objectOwner.group = ownGroup; + Date sourcetime = new Date(); + //更改所有者 + dmService.changeOwnership(new com.teamcenter.services.strong.core._2006_03.DataManagement.ObjectOwner[]{objectOwner}); + System.out.println("结束更改所有者"); + dmService.refreshObjects2(new ModelObject[]{revision, dataset}, false); + if (reResp!=null && reResp.serviceData.sizeOfPartialErrors() > 0) { + System.out.println("下挂数据集失败"); +// logger.info(String.format("对版本对象[%s]数据集对象[%s]下挂数据集失败[%s]")); + return null; + } + System.out.println("结束创建关系"); + closeByPass(); + return dataset; + } + + public static void upload(String filePath, DataManagementService dmService, Dataset dataset, String fmsurl){ + + Connection connection = AppXSession.getConnection(); + System.out.println("开始上传文件"+dataset.getUid()); + FileManagementService service = FileManagementService.getService(AppXSession.getConnection()); +// Connection connection = com.teamcenter.clientx.Session.getConnection(); + openByPass(); + String[] url = { fmsurl }; + ModelObject[] mo = new ModelObject[]{dataset}; + dmService.refreshObjects(mo); + FileManagementUtility fm = null; + try { + fm = new FileManagementUtility(connection, null, null, url, null); + System.out.println(fm); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + FileManagement.DatasetFileInfo fileInfo = new FileManagement.DatasetFileInfo(); +// File file=new File(filePath); +// if(file.exists()) { +// +// } + fileInfo.fileName = filePath; + fileInfo.allowReplace = true; + fileInfo.isText = false; + fileInfo.namedReferencedName = "PDF_Reference";//"PDF_Reference"; + FileManagement.GetDatasetWriteTicketsInputData inputData = new FileManagement.GetDatasetWriteTicketsInputData(); + inputData.dataset = dataset; + inputData.createNewVersion = false; + inputData.datasetFileInfos = new FileManagement.DatasetFileInfo[]{fileInfo}; + ServiceData sd = fm.putFiles(new FileManagement.GetDatasetWriteTicketsInputData[]{inputData}); + try { + throwServiceDataError(sd); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + dmService.refreshObjects(mo); + System.out.println("上传文件完成"); + closeByPass(); + } + + + public static void throwServiceDataError(ServiceData serviceData) throws Exception { + if (serviceData.sizeOfPartialErrors() > 0) { + StringBuilder errInfo = new StringBuilder(); + for (int i = 0; i < serviceData.sizeOfPartialErrors(); i++) { + for (String msg : serviceData.getPartialError(i).getMessages()) { + errInfo.append(msg + "\n"); + } + } + throw new Exception(errInfo.toString()); + } + } + + public static List query(String queryName, String[] entries, String[] values) throws Exception { +// KUtil.log(logger, "执行查询 %s %s = %s", queryName, Arrays.toString(entries), Arrays.toString(values)); + SavedQueryService queryService = SavedQueryService.getService(session.getConnection()); + ImanQuery query = null; + GetSavedQueriesResponse savedQueries = queryService.getSavedQueries(); + for (int i = 0; i < savedQueries.queries.length; i++) { + if (!savedQueries.queries[i].name.equals(queryName)) + { + continue; + } + query = savedQueries.queries[i].query; + break; + } + if (query == null) { + System.out.println("There is not an " + queryName + " query."); + return null; + } + List res = new ArrayList(); + SavedQueryInput input = new SavedQueryInput(); + input.query = query; + input.entries = entries; + input.values = values; + input.resultsType = 0; + ExecuteSavedQueriesResponse resp = queryService.executeSavedQueries(new SavedQueryInput[]{input}); + checkPartialError(resp.serviceData); + for (ModelObject e : resp.arrayOfResults[0].objects) { + res.add(e); + } + return res; + } + + + public static int getLen(E[] arr) { + return arr == null ? 0 : arr.length; + } + + + public static String getMessage(Exception e) { + String message = e.getLocalizedMessage(); + if (KUtil.isEmpty(message)) { + message = e.getClass().getName() + " - 无详细信息"; + } + return message; + } + + + +} \ No newline at end of file diff --git a/src/main/java/com/connor/sso/sso/util/LoginUtil.java b/src/main/java/com/connor/sso/sso/util/LoginUtil.java new file mode 100644 index 0000000..c33b508 --- /dev/null +++ b/src/main/java/com/connor/sso/sso/util/LoginUtil.java @@ -0,0 +1,30 @@ +package com.connor.sso.sso.util; + + +import com.connor.sso.sso.clientx.AppXSession; +import org.springframework.stereotype.Service; + + +public class LoginUtil { + + private final String server; + private final String user; + private final String password; + + public LoginUtil(String server, String user, String password) { + this.server = server; + this.user = user; + this.password = password; + } + + public AppXSession loginTC() throws Exception { + AppXSession session = null; + session = KUtil.login(server, user, password); + return session; + } +// public AppXSession loginTC(String url,String name,String pass) throws Exception { +// AppXSession session = null; +// session = KUtil.login(url, name, pass); +// return session; +// } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..f21551a --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,16 @@ +spring.application.name=sso +server.port=9891 + +spring.datasource.url=jdbc:sqlserver://192.168.1.52:1433;databaseName=TC;encrypt=true;trustServerCertificate=true; +spring.datasource.username=sa +spring.datasource.password=Glorydb.com +spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver +spring.datasource.hikari.minimum-idle=1 +spring.datasource.hikari.maximum-pool-size=5 +spring.datasource.hikari.auto-commit=true + +tc.server=http://192.168.1.52:7001/tc +# TC¼ûҪԿ·Ȩ +tc.user=admin +# TC¼ +tc.password=admin diff --git a/src/test/java/com/connor/sso/sso/SsoApplicationTests.java b/src/test/java/com/connor/sso/sso/SsoApplicationTests.java new file mode 100644 index 0000000..e889c0a --- /dev/null +++ b/src/test/java/com/connor/sso/sso/SsoApplicationTests.java @@ -0,0 +1,13 @@ +package com.connor.sso.sso; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SsoApplicationTests { + + @Test + void contextLoads() { + } + +}