高度なカスタマイズ > Info*Engine ユーザーガイド > Web サービスフレームワーク > Java ベースの Web サービスクライアントの作成
  
Java ベースの Web サービスクライアントの作成
プロジェクトディレクトリ (src__クライアント) と Java ソースファイルの例 (src_client/org/myorg/MathClient.java) が手順プロジェクトの作成で作成されました。
MathClient.java ソースファイルは、展開済みの Web サービスから生成されるソースコンポーネントに依存しています。クライアントソースを作成する前に、これらのコンポーネントを生成し、コンパイルする必要があります。生成と同時に MathClient.java がコンパイルされますが、それを使用して Web サービスメソッドを呼び出すまで、何も行いません。
これらのコンポーネントを取得するには、以下のコマンドを使用して、空のクライアントをコンパイルする必要があります。
% cd <Windchill>/prog_examples/jws/MyProject/src_client
% ant
Apache Ant スクリプトによって、アプリケーションの JAR 実行ファイルも生成されます。
<Windchill>/prog_examples/jws/MyProject/dist_client/MathServiceClient.jar
ただし、メインクラスが何も行わないので、JAR を実行しても何も行われません。前の ant コマンドを実行すると、Web サービスの WSDL が処理され、Java ソースコンポーネントが以下のロケーションに生成されます。
<Windchill>/prog_examples/jws/MyProject/gensrc_client
これにより、Java ソースコードが com.ptc.jws.service.org.myorg.mathservice パッケージ内に作成されます。サービスネームスペースから派生した名前を持つパッケージに Java コードが生成されないようにするには、build.xml ファイル内の jaxws.package プロパティを使用して、ソースコードの生成先のパッケージを明示的に定義します。
クライアントソースコードを編集して、クライアントを完成させます。
1. テキストエディタで次のファイルを開きます。
<Windchill>/prog_examples/jws/MyProject/src_client/org/myorg/MathClient.java
ソースは以下のようになります。
package org.myorg;
// import the classes generated when compiling your client
//import com.ptc.jws.service.?.*;
import com.ptc.jws.client.handler.*;
public class MathClient
{
public static void main ( String [] args ) throws java.lang.Exception
{
// depending on your security requirements you may need to specify credentials up
// front, or on the command-line where most policies will prompt for them
//Credentials.setUsername ( "demo" );
//Credentials.setPassword ( "demo" );
// TODO implement your client /*
MathServiceImplService service = new MathServiceImplService();
MathServiceImpl port = service.getMathServiceImplPort ();
//invoke an action
//port.methodName ( <arguments> );
*/
}
}
2. 以下のように、サーバー側の Web サービスコンポーネントをインポートしてメソッドを呼び出すようにソースを更新します。
package org.myorg;
// import the classes generated when compiling your client
import com.ptc.jws.service.org.myorg.mathservice.*;
public class MathClient
{
public static void main ( String [] args ) throws java.lang.Exception
{
int a = args.length > 0 ? Integer.parseInt ( args[0] ) : 0;
int b = args.length > 1 ? Integer.parseInt ( args[1] ) : 0;
MathServiceImplService service = new MathServiceImplService();
MathServiceImpl port = service.getMathServiceImplPort ();
System.out.printf ( "a+b=%d\n", port.add ( a, b ) );
System.out.printf ( "a-b=%d\n", port.subtract ( a, b ) );
System.out.printf ( "a*b=%d\n", port.multiply ( a, b ) );
System.out.printf ( "a/b=%f\n", port.divide ( a, b ) );
}
}
3. クライアントを再コンパイルし、更新されたクラスが含まれるように実行可能 JAR を更新します。
% ant compile
% ant dist
4. 新しい Web サービスクライアントをコマンドラインから実行します。
% java -jar ../dist_client/MathServiceClient.jar 10 20
Username:<パスワード>
Password:<ユーザー名>
a+b=30
a-b=-10
a*b=200
a/b=0.500000
ここで、<ユーザー名> はユーザー名、<パスワード> は先に指定したパスワードです。クライアントを実行すると、コマンドラインで資格証明が要求されます。