サービス参照を含めるほか、クライアントコードがルックアップできるよう、アプリケーションは配備時にその service-ref を JNDI 名にバインドする必要があります。サービスロケータパターンを使用、実装する主なクラスを見てみます。
submitPO
メソッドで重要なのは、サービスロケータを使用している部分です。サービスロケータを使用して、Web サービスに対する参照を取得してから、Web サービスを呼び出します。public class SchemaPOServiceBD {
private ServiceLocator serviceLocator;
public SchemaPOServiceBD(){
serviceLocator = new ServiceLocator();
}
public String submitPO(com.sun.j2ee.blueprints.docoriented.client.PurchaseOrder po) throws RequestHandlerException {
try {
SchemaDefinedPurchaseOrderServiceSEI port = (SchemaDefinedPurchaseOrderServiceSEI)
serviceLocator.getServicePort(JNDINames.SCHEMA_SERVICE_REF, SchemaDefinedPurchaseOrderServiceSEI.class);
// エンドポイントに送信する order のサービス型にPO オブジェクトを変換
...
String ret = port.submitPO(order);
return ret;
} catch ...
....
}
}
import javax.naming.*;
import java.rmi.Remote;
import javax.xml.rpc.*;
/**
* Implements Service Locator pattern for Web services
*/
public class ServiceLocator {
private transient InitialContext ic;
public ServiceLocator() throws ServiceLocatorException {
try {
setInitialContext();
} catch (Exception e) {
throw new ServiceLocatorException(e);
}
}
private void setInitialContext() throws javax.naming.NamingException {
ic = new InitialContext();
}
/**
* Service class acts as a factory of the Dynamic proxy for the target service endpoint.
* @see java.xml.rpc.Service.java
* @return the Service instance
*/
public Remote getServicePort(String jndiName, Class className) throws ServiceLocatorException {
try {
if (ic == null) setInitialContext();
Service service = (Service) ic.lookup(jndiName);
return service.getPort(className);
} catch (Exception e) {
throw new ServiceLocatorException("ServiceLocator can not lookup jndiName=" + jndiName + " and className=" + className, e);
}
}
}
package com.sun.j2ee.blueprints.docoriented.client;
public class ServiceLocatorException extends RuntimeException {
public ServiceLocatorException() {}
public ServiceLocatorException(String msg) { super(msg); }
public ServiceLocatorException(String msg, Throwable cause) { super(msg, cause); }
public ServiceLocatorException(Throwable cause) { super(cause); }
}