SOA+SpringBoot
1、Spring Boot 简介
简化Spring应用开发的一个框架; 整个Spring技术栈的一个大整合; J2EE开发的一站式解决方案;
SpringBoot优点:
快速创建独立运行的Spring项目以及与主流框架集成
使用嵌入式的Servlet容器,应用无需打成WAR包
starters自动依赖与版本控制
大量的自动配置,简化开发,也可修改默认值
无需配置XML,无代码生成,开箱即用
准生产环境的运行时应用监控
与云计算的天然集成
2、微服务
2014,martin fowler 微服务:每一个功能元素最终都是一个可独立替换和独立升级的软件单元。 架构风格(服务微化)
- 一个应用应该是一组小型服务; - 可以通过HTTP的方式进行互通;单体应用:ALL IN ONE 详细参照微服务文档
3、环境准备
1. 环境约束
–jdk1.8:Spring Boot 推荐jdk1.7及以上;java version "1.8.0_112"
–maven3.x:maven 3.3以上版本;Apache Maven 3.3.9
–IntelliJIDEA2017:IntelliJ IDEA 2017.2.2 x64、STS
–SpringBoot 1.5.9.RELEASE:1.5.9;
2. MAVEN设置
给maven 的settings.xml配置文件的profiles标签添加:
<profile>
<id>jdk-1.8</id>
<activation>
<activeByDefault>true</activeByDefault>
<jdk>1.8</jdk>
</activation>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
</properties>
</profile>
3. IDEA设置
IDEA整合maven:
4、Spring Boot HelloWorld
一个功能:浏览器发送hello请求,服务器接受请求并处理,响应Hello World字符串。
1、创建一个maven工程;(jar)
2、导入spring boot相关的依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
3、编写一个主程序;启动Spring Boot应用
/**
* @SpringBootApplication 来标注一个主程序类,说明这是一个Spring Boot应用
*/
@SpringBootApplication
public class SoaApplication {
public static void main(String[] args) {
// Spring应用启动起来
SpringApplication.run(SoaApplication.class,args);
}
}
4、编写相关的Controller、Service
@Controller
public class HelloController {
@ResponseBody
@RequestMapping("/hello")
public String hello(){
return "Hello World!";
}
}
5、简化部署
将这个应用打成jar包,直接使用java -jar的命令进行执行。
<!-- 这个插件,可以将应用打包成一个可执行的jar包;-->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
6、运行主程序测试
5、连接TC
1、添加配置文件application.properties
application.properties中配置TC的连接信息
配置文件中,配置名称需符合JAVA命名规范,若是全大写会出现无法读取的情况。
例如:tc.TYPE = HTTP
则程序无法读取
server.port = 8000
tc.type = HTTP
tc.host = 127.0.0.1
tc.port = 7001
tc.name = tc
tc.username = infodba
tc.password = infodba
2、创建libs文件夹添加引用的jar文件
3、复制soaclient中的示例程序中clientx中的类
AppXCredentialManager
CredentialManager由Teamcenter Services框架使用,当服务器挑战时获取用户的凭据。这可能发生在一段时间的不活动之后,服务器已经超时了用户的会话,此时客户端应用程序将需要重新身份验证。框架将调用getCredentials方法之一(取决于具体情况)并发送SessionService。登录服务请求。成功完成登录服务请求后。最后一个服务请求(引起质疑的请求)将被重发。
当这些凭据发生变化时,框架还将调用setUserPassword setGroupRole方法,从而允许CredentialManager的实现缓存这些值,以便不需要提示用户进行重新身份验证。
//==================================================
//
// Copyright 2012 Siemens Product Lifecycle Management Software Inc. All Rights Reserved.
//
//==================================================
package com.teamcenter.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 promptForCredentials();
}
/**
* Return the cached credentials.
* This method will be called when a service request is sent without a valid
* session ( session has expired on the server).
*
* @see CredentialManager#getCredentials(InvalidUserException)
*/
public String[] getCredentials(InvalidUserException e)
throws CanceledOperationException
{
// Have not logged in yet, should not happen but just in case
if (name == null) return promptForCredentials();
// Return cached credentials
String[] tokens = { name, password, group, role, discriminator };
return tokens;
}
/**
* Cache the group and role
* This is called after the SessionService.setSessionGroupMember service
* operation is called.
*
* @see CredentialManager#setGroupRole(String,
* String)
*/
public void setGroupRole(String group, String role)
{
this.group = group;
this.role = role;
}
/**
* Cache the User and Password
* This is called after the SessionService.login service operation is called.
*
* @see CredentialManager#setUserPassword(String,
* String, String)
*/
public void setUserPassword(String user, String password, String discriminator)
{
this.name = user;
this.password = password;
this.discriminator = discriminator;
}
public String[] promptForCredentials()
throws CanceledOperationException
{
try
{
LineNumberReader reader = new LineNumberReader(new InputStreamReader(System.in));
System.out.println("Please enter user credentials (return to quit):");
System.out.print("User Name: ");
name = reader.readLine();
if (name.length() == 0)
throw new CanceledOperationException("");
System.out.print("Password: ");
password = reader.readLine();
}
catch (IOException e)
{
String message = "Failed to get the name and password.\n" + e.getMessage();
System.out.println(message);
throw new CanceledOperationException(message);
}
String[] tokens = { name, password, group, role, discriminator };
return tokens;
}
public String[] promptForCredentials(String userName,String passWord)
throws CanceledOperationException
{
name = userName;
password = passWord;
String[] tokens = { name, password, group, role, discriminator };
return tokens;
}
}
AppXExceptionHandler
ExceptionHandler的实现。对于ConnectionExceptions(服务器暂时关闭),提示用户重试最后一个请求。对于其他异常,转换为运行时异常。
//==================================================
//
// Copyright 2012 Siemens Product Lifecycle Management Software Inc. All Rights Reserved.
//
//==================================================
package com.teamcenter.clientx;
import com.teamcenter.schemas.soa._2006_03.exceptions.ConnectionException;
import com.teamcenter.schemas.soa._2006_03.exceptions.InternalServerException;
import com.teamcenter.schemas.soa._2006_03.exceptions.ProtocolException;
import com.teamcenter.soa.client.ExceptionHandler;
import com.teamcenter.soa.exceptions.CanceledOperationException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
/**
* Implementation of the ExceptionHandler. For ConnectionExceptions (server
* temporarily down .etc) prompts the user to retry the last request. For other
* exceptions convert to a RunTime exception.
*/
public class AppXExceptionHandler implements ExceptionHandler
{
/*
* (non-Javadoc)
*
* @see com.teamcenter.soa.client.ExceptionHandler#handleException(com.teamcenter.schemas.soa._2006_03.exceptions.InternalServerException)
*/
public void handleException(InternalServerException ise)
{
System.out.println("");
System.out.println("*****");
System.out
.println("Exception caught in com.teamcenter.clientx.AppXExceptionHandler.handleException(InternalServerException).");
LineNumberReader reader = new LineNumberReader(new InputStreamReader(System.in));
if (ise instanceof ConnectionException)
{
// ConnectionException are typically due to a network error (server
// down .etc) and can be recovered from (the last request can be sent again,
// after the problem is corrected).
System.out.print("\nThe server returned an connection error.\n" + ise.getMessage()
+ "\nDo you wish to retry the last service request?[y/n]");
}
else
if (ise instanceof ProtocolException)
{
// ProtocolException are typically due to programming errors
// (content of HTTP
// request is incorrect). These are generally can not be
// recovered from.
System.out.print("\nThe server returned an protocol error.\n" + ise.getMessage()
+ "\nThis is most likely the result of a programming error."
+ "\nDo you wish to retry the last service request?[y/n]");
throw new RuntimeException(ise);
}
else
{
System.out.println("\nThe server returned an internal server error.\n"
+ ise.getMessage()
+ "\nThis is most likely the result of a programming error."
+ "\nA RuntimeException will be thrown.");
throw new RuntimeException(ise.getMessage());
}
try
{
String retry = reader.readLine();
// If yes, return to the calling SOA client framework, where the
// last service request will be resent.
if (retry.equalsIgnoreCase("y") || retry.equalsIgnoreCase("yes")) return;
throw new RuntimeException("The user has opted not to retry the last request");
}
catch (IOException e)
{
System.err.println("Failed to read user response.\nA RuntimeException will be thrown.");
throw new RuntimeException(e.getMessage());
}
}
/*
* (non-Javadoc)
*
* @see com.teamcenter.soa.client.ExceptionHandler#handleException(com.teamcenter.soa.exceptions.CanceledOperationException)
*/
public void handleException(CanceledOperationException coe)
{
System.out.println("");
System.out.println("*****");
System.out.println("Exception caught in com.teamcenter.clientx.AppXExceptionHandler.handleException(CanceledOperationException).");
// Expecting this from the login tests with bad credentials, and the
// AnyUserCredentials class not
// prompting for different credentials
throw new RuntimeException(coe);
}
}
AppXModelEventListener
changellistener的实现。打印出所有已更新的对象。
//==================================================
//
// Copyright 2012 Siemens Product Lifecycle Management Software Inc. All Rights Reserved.
//
//==================================================
package com.teamcenter.clientx;
import com.teamcenter.soa.client.model.ModelEventListener;
import com.teamcenter.soa.client.model.ModelObject;
import com.teamcenter.soa.exceptions.NotLoadedException;
/**
* Implementation of the ChangeListener. Print out all objects that have been updated.
*
*/
public class AppXModelEventListener extends ModelEventListener
{
@Override
public void localObjectChange(ModelObject[] objects)
{
if (objects.length == 0) return;
// System.out.println("");
// System.out.println("Modified Objects handled in com.teamcenter.clientx.AppXUpdateObjectListener.modelObjectChange");
// System.out.println("The following objects have been updated in the client data model:");
for (int i = 0; i < objects.length; i++)
{
String uid = objects[i].getUid();
String type = objects[i].getTypeObject().getName();
String name = "";
if (objects[i].getTypeObject().isInstanceOf("WorkspaceObject"))
{
ModelObject wo = objects[i];
try
{
name = wo.getPropertyObject("object_string").getStringValue();
}
catch (NotLoadedException e) {} // just ignore
}
// System.out.println(" " + uid + " " + type + " " + name);
}
}
@Override
public void localObjectDelete(String[] uids)
{
if (uids.length == 0)
return;
// System.out.println("");
// System.out.println("Deleted Objects handled in com.teamcenter.clientx.AppXDeletedObjectListener.modelObjectDelete");
// System.out.println("The following objects have been deleted from the server and removed from the client data model:");
for (int i = 0; i < uids.length; i++)
{
// System.out.println(" " + uids[i]);
}
}
}
AppXPartialErrorListener
PartialErrorListener的实现。打印返回的所有部分错误。
//==================================================
//
// Copyright 2012 Siemens Product Lifecycle Management Software Inc. All Rights Reserved.
//
//==================================================
package com.teamcenter.clientx;
import com.teamcenter.soa.client.model.ErrorStack;
import com.teamcenter.soa.client.model.ErrorValue;
import com.teamcenter.soa.client.model.PartialErrorListener;
/**
* Implementation of the PartialErrorListener. Print out any partial errors
* returned.
*
*/
public class AppXPartialErrorListener implements PartialErrorListener
{
@Override
public void handlePartialError(ErrorStack[] stacks)
{
if (stacks.length == 0) return;
System.out.println("");
System.out.println("*****");
System.out.println("Partial Errors caught in com.teamcenter.clientx.AppXPartialErrorListener.");
for (int i = 0; i < stacks.length; i++)
{
ErrorValue[] errors = stacks[i].getErrorValues();
System.out.print("Partial Error for ");
// The different service implementation may optionally associate
// an ModelObject, client ID, or nothing, with each partial error
if (stacks[i].hasAssociatedObject())
{
System.out.println( "object " + stacks[i].getAssociatedObject().getUid() );
}
else if (stacks[i].hasClientId())
{
System.out.println( "client id " + stacks[i].getClientId() );
}
else if (stacks[i].hasClientIndex())
System.out.println( "client index " + stacks[i].getClientIndex() );
// Each Partial Error will have one or more contributing error messages
for (int j = 0; j < errors.length; j++)
{
System.out.println(" Code: " + errors[j].getCode() + "\tSeverity: "
+ errors[j].getLevel() + "\t" + errors[j].getMessage());
}
}
}
}
AppXRequestListener
RequestListener的这个实现将每个服务请求记录到控制台。
//==================================================
//
// Copyright 2012 Siemens Product Lifecycle Management Software Inc. All Rights Reserved.
//
//==================================================
package com.teamcenter.clientx;
import com.teamcenter.soa.client.RequestListener;
/**
* This implementation of the RequestListener, logs each service request
* to the console.
*
*/
public class AppXRequestListener implements RequestListener
{
/**
* Called before each request is sent to the server.
*/
public void serviceRequest ( final Info info )
{
// will log the service name when done
}
/**
* Called after each response from the server.
* Log the service operation to the console.
*/
public void serviceResponse( final Info info )
{
System.out.println( info.id +": "+info.service+"."+info.operation);
}
}
AppXSession
Connection:在整个应用程序中共享的Connection对象的单个实例。每当实例化服务存根时都需要此连接对象。
AppXCredentialManager:Session类和Teamcenter服务框架都使用credentialManager来获取用户凭据。
//==================================================
//
// Copyright 2012 Siemens Product Lifecycle Management Software Inc. All Rights Reserved.
//
//==================================================
package com.teamcenter.clientx;
import com.teamcenter.schemas.soa._2006_03.exceptions.InvalidCredentialsException;
import com.teamcenter.schemas.soa._2006_03.exceptions.ServiceException;
import com.teamcenter.services.loose.core.SessionService;
import com.teamcenter.services.loose.core._2006_03.Session.LoginResponse;
import com.teamcenter.services.strong.administration.PreferenceManagementService;
import com.teamcenter.services.strong.core.DataManagementService;
import com.teamcenter.services.strong.core.ReservationService;
import com.teamcenter.services.strong.query.SavedQueryService;
import com.teamcenter.services.strong.structuremanagement.StructureService;
import com.teamcenter.services.strong.workflow.WorkflowService;
import com.teamcenter.soa.SoaConstants;
import com.teamcenter.soa.client.Connection;
import com.teamcenter.soa.client.model.ModelObject;
import com.teamcenter.soa.exceptions.CanceledOperationException;
import com.teamcenter.soa.exceptions.NotLoadedException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.Vector;
public class AppXSession
{
/**
* Single instance of the Connection object that is shared throughout
* the application. This Connection object is needed whenever a Service
* stub is instantiated.
*/
private static Connection connection;
/**
* The credentialManager is used both by the Session class and the Teamcenter
* Services Framework to get user credentials.
*
*/
private static AppXCredentialManager credentialManager;
public ReservationService rvService = null; //签入、签出服务
public SessionService sessionService = null;
public SavedQueryService queryService = null;
public DataManagementService dmService = null; //数据管理服务,获取属性、关联关系等
public StructureService strongSService = null;
public WorkflowService workflowService = null;
public PreferenceManagementService pmService = null; //首选项管理服务
public com.teamcenter.services.strong.cad.StructureManagementService cadSMService = null; //用于打开BOM
public com.teamcenter.services.strong.bom.StructureManagementService bomSMService = null; //用于BOM结构管理,如添加、移除BOM
public AppXSession(String type,String host,int port,String appname,String local)
{
// Create an instance of the CredentialManager, this is used
// by the SOA Framework to get the user's credentials when
// challanged by the server (sesioin timeout on the web tier).
credentialManager = new AppXCredentialManager();
String protocol=null;
String envNameTccs = null;
String serverHost = "";
if ( "http".equalsIgnoreCase(type) )
{
protocol = SoaConstants.HTTP;
serverHost = "http://" + host + ":" + port + "/" + appname;
}
else if ( "tccs".equalsIgnoreCase(type) )
{
protocol = SoaConstants.TCCS;
host = host.trim();
int envNameStart = host.indexOf('/') + 2;
envNameTccs = host.substring( envNameStart, host.length() );
serverHost = "";
}
else
{
protocol = SoaConstants.IIOP;
serverHost = "iiop:" + host + ":" + port + "/" + appname;
}
System.out.println(serverHost);
// Create the Connection object, no contact is made with the server
// until a service request is made
connection = new Connection(serverHost, 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());
this.getService();
}
/**
* 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
// challanged by the server (sesioin 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
{
System.setProperty("jacorb.suppress_no_props_warning", "on");
}
// 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());
this.getService();
}
/**
* Get the single Connection object for the application
*
* @return connection
*/
public static Connection getConnection()
{
return connection;
}
/**
* Login to the Teamcenter Server
*
*/
public ModelObject login()
{
// Get the service stub
SessionService sessionService = SessionService.getService(connection);
try
{
// Prompt for credentials until they are right, or until user
// cancels
String[] credentials = credentialManager.promptForCredentials();
while (true)
{
try
{
// *****************************
// Execute the service operation
// *****************************
LoginResponse out = sessionService.login(credentials[0], credentials[1],
credentials[2], credentials[3],"", credentials[4]);
return out.user;
}
catch (InvalidCredentialsException e)
{
credentials = credentialManager.getCredentials(e);
}
}
}
// User canceled the operation, don't need to tell him again
catch (CanceledOperationException e) {}
// Exit the application
System.exit(0);
return null;
}
/**
* Terminate the session with the Teamcenter Server
*
*/
public void logout()
{
// Get the service stub
SessionService sessionService = SessionService.getService(connection);
try
{
// *****************************
// Execute the service operation
// *****************************
sessionService.logout();
}
catch (ServiceException e){}
}
/*
* 获取各种service
*/
private void getService(){
rvService = ReservationService.getService(connection);
sessionService = SessionService.getService(connection);
queryService = SavedQueryService.getService(connection);
dmService = DataManagementService.getService(connection);
workflowService = WorkflowService.getService(connection);
cadSMService = com.teamcenter.services.strong.cad.StructureManagementService.getService(connection);
bomSMService = com.teamcenter.services.strong.bom.StructureManagementService.getService(connection);
strongSService = StructureService.getService(connection);
pmService = PreferenceManagementService.getService(connection);
}
/**
* Print some basic information for a list of objects
*
* @param objects
*/
public static void printObjects(ModelObject[] objects)
{
if(objects == null)
return;
SimpleDateFormat format = new SimpleDateFormat("M/d/yyyy h:mm a", new Locale("en", "US")); // Simple no time zone
// Ensure that the referenced User objects that we will use below are loaded
getUsers( objects );
System.out.println("Name\t\tOwner\t\tLast Modified");
System.out.println("====\t\t=====\t\t=============");
for (int i = 0; i < objects.length; i++)
{
if (!objects[i].getTypeObject().isInstanceOf("WorkspaceObject"))
continue;
ModelObject wo = objects[i];
try
{
String name = wo.getPropertyObject("object_string").getStringValue();
ModelObject owner = wo.getPropertyObject("owning_user").getModelObjectValue();
Calendar lastModified =wo.getPropertyObject("last_mod_date").getCalendarValue();
System.out.println(name + "\t" + owner.getPropertyObject("user_name").getStringValue() + "\t"
+ format.format(lastModified.getTime()));
}
catch (NotLoadedException e)
{
// Print out a message, and skip to the next item in the folder
// Could do a DataManagementService.getProperties call at this point
System.out.println(e.getMessage());
System.out.println("The Object Property Policy ($TC_DATA/soa/policies/Default.xml) is not configured with this property.");
}
}
}
private static void getUsers( ModelObject[] objects )
{
if(objects == null)
return;
DataManagementService dmService = DataManagementService.getService(AppXSession.getConnection());
List<ModelObject> unKnownUsers = new Vector<ModelObject>();
for (int i = 0; i < objects.length; i++)
{
if (!objects[i].getTypeObject().isInstanceOf("WorkspaceObject"))
continue;
ModelObject wo = objects[i];
ModelObject owner = null;
try
{
owner = wo.getPropertyObject("owning_user").getModelObjectValue();
owner.getPropertyObject("user_name");
}
catch (NotLoadedException e)
{
if(owner != null)
unKnownUsers.add(owner);
}
}
ModelObject[] users = (ModelObject[])unKnownUsers.toArray(new ModelObject[unKnownUsers.size()]);
String[] attributes = { "user_name" };
// *****************************
// Execute the service operation
// *****************************
dmService.getProperties(users, attributes);
}
/*
* 登陆TC
* para1:用户名
* para2:密码
*/
public ModelObject login(String userName,String passWord){
try {
System.out.println("userName:"+userName);
System.out.println("passWord:"+passWord);
SessionService sessionService = SessionService.getService(connection);
LoginResponse out = sessionService.login(userName, passWord,
"", "","", "SoaAppX");
return out.user;
} catch (InvalidCredentialsException e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
}
4、Bean组件使用配置登录信息连接TC
此处获取配置信息登录至TC
package com.ekunde.rs.soa.bean;
import com.ekunde.rs.soa.config.TcConfig;
import com.teamcenter.clientx.AppXSession;
import com.teamcenter.soa.client.Connection;
import com.teamcenter.soa.client.model.ModelObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Component
public class Session {
@Autowired
private TcConfig config;
private Connection connection;
private ModelObject user;
private AppXSession session;
@Bean
public AppXSession init() {
if(null == connection)
{
String type = config.getType();
String host = config.getHost();
String local = config.getLocal();
int port = config.getPort();
String name = config.getName();
session = new AppXSession(type, host, port, name,local);
user = session.login(config.getUsername(), config.getPassword());
connection = AppXSession.getConnection();
}
return session;
}
public AppXSession getSession(){
return session;
}
public ModelObject getUser() {
return user;
}
public Connection getConnection() {
return connection;
}
}
5、pom.xml导入常用TC包
<!-- 导入TC包 == start -->
<dependency>
<groupId>avalon-framework</groupId>
<artifactId>avalon-framework</artifactId>
<version>4.1.5</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/avalon-framework-4.1.5.jar</systemPath>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/commons-codec.jar</systemPath>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/commons-httpclient-3.1.jar</systemPath>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/commons-logging.jar</systemPath>
</dependency>
<dependency>
<groupId>fccclient</groupId>
<artifactId>fccclient</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/fccclient.jar</systemPath>
</dependency>
<dependency>
<groupId>fscclient</groupId>
<artifactId>fscclient</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/fscclient.jar</systemPath>
</dependency>
<dependency>
<groupId>jacorb</groupId>
<artifactId>jacorb</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/jacorb.jar</systemPath>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/log4j.jar</systemPath>
</dependency>
<dependency>
<groupId>logkit</groupId>
<artifactId>logkit</artifactId>
<version>1.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/logkit-1.2.jar</systemPath>
</dependency>
<dependency>
<groupId>resolver</groupId>
<artifactId>resolver</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/resolver.jar</systemPath>
</dependency>
<dependency>
<groupId>tcserverjavabinding</groupId>
<artifactId>tcserverjavabinding</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/tcserverjavabinding.jar</systemPath>
</dependency>
<dependency>
<groupId>TcSoaAdministrationStrong</groupId>
<artifactId>TcSoaAdministrationStrong</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/TcSoaAdministrationStrong_11000.2.0.jar</systemPath>
</dependency>
<dependency>
<groupId>TcSoaAdministrationTypes</groupId>
<artifactId>TcSoaAdministrationTypes</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/TcSoaAdministrationTypes_11000.2.0.jar</systemPath>
</dependency>
<dependency>
<groupId>TcSoaBomStrong</groupId>
<artifactId>TcSoaBomStrong</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/TcSoaBomStrong_11000.2.0.jar</systemPath>
</dependency>
<dependency>
<groupId>TcSoaBomTypes</groupId>
<artifactId>TcSoaBomTypes</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/TcSoaBomTypes_11000.2.0.jar</systemPath>
</dependency>
<dependency>
<groupId>TcSoaCadStrong</groupId>
<artifactId>TcSoaCadStrong</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/TcSoaCadStrong_11000.2.0.jar</systemPath>
</dependency>
<dependency>
<groupId>TcSoaCadTypes</groupId>
<artifactId>TcSoaCadTypes</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/TcSoaCadTypes_11000.2.0.jar</systemPath>
</dependency>
<dependency>
<groupId>TcSoaClient</groupId>
<artifactId>TcSoaClient</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/TcSoaClient_11000.2.0.jar</systemPath>
</dependency>
<dependency>
<groupId>TcSoaCommon</groupId>
<artifactId>TcSoaCommon</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/TcSoaCommon_11000.2.0.jar</systemPath>
</dependency>
<dependency>
<groupId>TcSoaCoreStrong</groupId>
<artifactId>TcSoaCoreStrong</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/TcSoaCoreStrong_11000.2.0.jar</systemPath>
</dependency>
<dependency>
<groupId>TcSoaCoreTypes</groupId>
<artifactId>TcSoaCoreTypes</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/TcSoaCoreTypes_11000.2.0.jar</systemPath>
</dependency>
<dependency>
<groupId>TcSoaQueryStrong</groupId>
<artifactId>TcSoaQueryStrong</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/TcSoaQueryStrong_11000.2.0.jar</systemPath>
</dependency>
<dependency>
<groupId>TcSoaQueryTypes</groupId>
<artifactId>TcSoaQueryTypes</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/TcSoaQueryTypes_11000.2.0.jar</systemPath>
</dependency>
<dependency>
<groupId>TcSoaStrongModel</groupId>
<artifactId>TcSoaStrongModel</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/TcSoaStrongModel_11000.2.0.jar</systemPath>
</dependency>
<dependency>
<groupId>TcSoaStructureManagementStrong</groupId>
<artifactId>TcSoaStructureManagementStrong</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/TcSoaStructureManagementStrong_11000.2.0.jar</systemPath>
</dependency>
<dependency>
<groupId>TcSoaStructureManagementTypes</groupId>
<artifactId>TcSoaStructureManagementTypes</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/TcSoaStructureManagementTypes_11000.2.0.jar</systemPath>
</dependency>
<dependency>
<groupId>TcSoaWorkflowStrong</groupId>
<artifactId>TcSoaWorkflowStrong</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/TcSoaWorkflowStrong_11000.2.0.jar</systemPath>
</dependency>
<dependency>
<groupId>TcSoaWorkflowTypes</groupId>
<artifactId>TcSoaWorkflowTypes</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/TcSoaWorkflowTypes_11000.2.0.jar</systemPath>
</dependency>
<dependency>
<groupId>tctp</groupId>
<artifactId>tctp</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/tctp_11000.2.0.jar</systemPath>
</dependency>
<dependency>
<groupId>teamcenter_sso_applib</groupId>
<artifactId>teamcenter_sso_applib</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/teamcenter_sso_applib.jar</systemPath>
</dependency>
<dependency>
<groupId>teamcenter_sso_common</groupId>
<artifactId>teamcenter_sso_common</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/teamcenter_sso_common.jar</systemPath>
</dependency>
<dependency>
<groupId>teamcenter_sso_webtoolkit</groupId>
<artifactId>teamcenter_sso_webtoolkit</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/teamcenter_sso_webtoolkit.jar</systemPath>
</dependency>
<dependency>
<groupId>xercesImpl</groupId>
<artifactId>xercesImpl</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/xercesImpl.jar</systemPath>
</dependency>
<dependency>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/xml-apis.jar</systemPath>
</dependency>
<dependency>
<groupId>TcSoaClassificationTypes</groupId>
<artifactId>TcSoaClassificationTypes</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/TcSoaClassificationTypes_11000.2.0.jar</systemPath>
</dependency>
<dependency>
<groupId>TcSoaClassificationLoose</groupId>
<artifactId>TcSoaClassificationLoose</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/TcSoaClassificationLoose_11000.2.0.jar</systemPath>
</dependency>
<dependency>
<groupId>TcSoaClassificationStrong</groupId>
<artifactId>TcSoaClassificationStrong</artifactId>
<version>11000.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/TcSoaClassificationStrong_11000.2.0.jar</systemPath>
</dependency>
<!-- 导入TC包 == end -->
6、测试案例获取Home文件夹
- 1) 项目目录结构
- 2) 主要程序代码
Controller类
package com.ekunde.soa.controller;
import com.alibaba.fastjson2.JSONArray;
import com.ekunde.soa.Service.ITestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
@Autowired
private ITestService testService;
@ResponseBody
@RequestMapping("/hello")
public String hello(){
return "Hello World!";
}
@ResponseBody
@RequestMapping("/home")
public JSONArray getHome(){
return testService.getHome();
}
}
Service
package com.ekunde.soa.Service;
import com.alibaba.fastjson2.JSONArray;
/**
* Description:业务层接口
*/
public interface ITestService {
JSONArray getHome();
}
service实现类
package com.ekunde.soa.Service.Impl;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ekunde.soa.Service.ITestService;
import com.teamcenter.bean.Session;
import com.teamcenter.clientx.AppXSession;
import com.teamcenter.services.strong.core.DataManagementService;
import com.teamcenter.soa.client.model.ModelObject;
import com.teamcenter.soa.exceptions.NotLoadedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Calendar;
/**
* Description:业务处理层
*/
@Service
public class TestServiceImpl implements ITestService {
@Autowired
private Session session;
@Override
public JSONArray getHome() {
JSONArray jsonArray = new JSONArray();
AppXSession xSession = session.getSession();
ModelObject home = null;
ModelObject[] contents = null;
// Get the service stub
DataManagementService dmService = DataManagementService.getService(AppXSession.getConnection());
try
{
//获取当前登录用户
ModelObject user = xSession.login();
// User was a primary object returned from the login command
// the Object Property Policy should be configured to include the
// 'home_folder' property. However the actual 'home_folder' object
// was a secondary object returned from the login request and
// therefore does not have any properties associated with it. We will need to
// get those properties explicitly with a 'getProperties' service request.
home = user.getPropertyObject("home_folder").getModelObjectValue();
}
catch (NotLoadedException e)
{
System.out.println(e.getMessage());
System.out.println("The Object Property Policy ($TC_DATA/soa/policies/Default.xml) is not configured with this property.");
return jsonArray;
}
try
{
ModelObject[] objects = { home };
String[] attributes = { "contents" };
// *****************************
// Execute the service operation
// *****************************
dmService.getProperties(objects, attributes);
// The above getProperties call returns a ServiceData object, but it
// just has pointers to the same object we passed into the method, so the
// input object have been updated with new property values
contents = home.getPropertyObject("contents").getModelObjectArrayValue();
}
// This should never be thrown, since we just explicitly asked for this
// property
catch (NotLoadedException e){}
System.out.println("");
System.out.println("Home Folder:");
for (int i = 0; i < contents.length; i++)
{
if (!contents[i].getTypeObject().isInstanceOf("WorkspaceObject"))
continue;
ModelObject wo = contents[i];
try
{
String name = wo.getPropertyObject("object_string").getStringValue();
ModelObject owner = wo.getPropertyObject("owning_user").getModelObjectValue();
Calendar lastModified =wo.getPropertyObject("last_mod_date").getCalendarValue();
JSONObject json = new JSONObject();
json.put("object_string",name);
json.put("owning_user",owner);
json.put("last_mod_date",lastModified);
jsonArray.add(json);
}
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.");
}
}
return jsonArray;
}
}