You are viewing a plain text version of this content. The canonical link for it is here.
Posted to java-dev@axis.apache.org by Himakar Chennapragada <hi...@us.ibm.com> on 2012/04/05 20:38:59 UTC
issue when trying to reuse OperationClient?
Hi
I would like to reuse OperationClient across multiple (different) service
invocations i.e. I plan to have at least one dedicated OperationClient per
thread in a multi-threaded environment to avoid recreating it for each
request and degrade performance since it is a big overhead. When I use
"reset" it clears the OperationContext to null and gets a NLP exception.
Can someone help in this regard or should I got ahead and modify the
"reset" method to suit our needs. Any help or suggestions appreciated.
Best Regards,
-HK
Re: issue when trying to reuse OperationClient?
Posted by Guillermo Rodriguez Gonzalez <gr...@estudiantes.uci.cu>.
My friend, i hope this helps you:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.kms.ws.client;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.xml.namespace.QName;
import org.apache.axiom.attachments.Attachments;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMAttribute;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.soap.SOAP12Constants;
import org.apache.axiom.soap.SOAPBody;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axiom.soap.SOAPFactory;
import org.apache.axiom.util.activation.EmptyDataSource;
import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.OperationClient;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.client.async.AxisCallback;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.context.OperationContext;
import org.apache.axis2.databinding.utils.BeanUtil;
import org.apache.axis2.description.java2wsdl.TypeTable;
import org.apache.axis2.engine.DefaultObjectSupplier;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.axis2.wsdl.WSDLConstants;
import org.apache.commons.httpclient.protocol.Protocol;
import org.kms.domain.ws.AttachmentInfo;
import org.kms.domain.ws.FileAttachment;
import org.kms.events.NotifLevel;
import org.kms.events.Notification;
import org.kms.events.NotifyEventSource;
import org.kms.exception.connect.TimeOutException;
import org.kms.exception.util.ExUtil;
import org.kms.exception.ws.ServerException;
import org.kms.util.Constant;
import org.kms.util.ws.ssl.AuthSSLProtocolSocketFactory;
/**
*
* @author Guillermo Rdguez Glez
*/
public final class WSClient extends NotifyEventSource {
private static int ID = 0;
//==========================================================================
private int id;
private ServiceClient servClient;
private String toEPR;
private String targetNameSpace;
private String transportProtocol;
private AuthSSLProtocolSocketFactory sslMutualSocketFact;
private Protocol proto;
public WSClient(ConfigurationContext configurationContext,
String endPointRef,
String targetNameSpace,
String transportProtocol,
boolean manageSesions) {
try {
id = ID++;
servClient = new ServiceClient(configurationContext, null);
servClient.getOptions().setExceptionToBeThrownOnSOAPFault(true);
this.targetNameSpace = targetNameSpace;
this.transportProtocol = transportProtocol;
manageSession(manageSesions);
setToEndPointReference(endPointRef);
} catch (AxisFault ex) {
Logger.getLogger(WSClient.class.getName()).log(Level.SEVERE, null, ex);
throw new RuntimeException(ex);
}
}
public WSClient(ConfigurationContext configurationContext, boolean
manageSesions) {
try {
id = ID++;
servClient = new ServiceClient(configurationContext, null);
servClient.getOptions().setExceptionToBeThrownOnSOAPFault(true);
manageSession(manageSesions);
// Protocol authhttps = new Protocol("https", new
EasySSLProtocolSocketFactory(), 443);
// Protocol.registerProtocol("https", authhttps);
//
servClient.getOptions().setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER,
authhttps);
} catch (AxisFault ex) {
Logger.getLogger(WSClient.class.getName()).log(Level.SEVERE, null, ex);
throw new RuntimeException(ex);
}
}
public void prepareSSlProtSocketFact(boolean verifyHostname,
String keystorePath, CallbackHandler keystorePassCBH,
String truststorePath, CallbackHandler truststorePassCBH) {
try {
URL ksUrl = new URL(keystorePath);
URL tsUrl = new URL(truststorePath);
PasswordCallback ksPwCB = new PasswordCallback("Key Store
password", true);
PasswordCallback tsPwCB = new PasswordCallback("Trust Store
password", true);
keystorePassCBH.handle(new Callback[]{ksPwCB});
truststorePassCBH.handle(new Callback[]{tsPwCB});
sslMutualSocketFact = new AuthSSLProtocolSocketFactory(
ksUrl, String.valueOf(ksPwCB.getPassword()),
tsUrl, String.valueOf(tsPwCB.getPassword()),
verifyHostname);
proto = new Protocol("https", sslMutualSocketFact, 443);
servClient.getOptions().setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER,
proto);
} catch (IOException ex) {
Logger.getLogger(WSClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedCallbackException ex) {
Logger.getLogger(WSClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
public ServiceClient getServClient() {
return servClient;
}
public int getId() {
return id;
}
public String getTargetNameSpace() {
return targetNameSpace;
}
public void setTargetNameSpace(String targetNameSpace) {
this.targetNameSpace = targetNameSpace;
}
public String getToEndPointReference() {
return toEPR;
}
public void setToEndPointReference(String toEPR) {
this.toEPR = toEPR;
EndpointReference endPointRef = new EndpointReference(toEPR);
servClient.getOptions().setTo(endPointRef);
}
public String getTransportProtocol() {
return transportProtocol;
}
public void setTransportProtocol(String transportProtocol) {
this.transportProtocol = transportProtocol;
servClient.getOptions().setTransportInProtocol(transportProtocol);
}
public void engageModule(String modName) {
try {
servClient.engageModule(modName);
} catch (AxisFault ex) {
}
}
public void manageSession(boolean enable) {
if (true) {
engageModule(Constants.MODULE_ADDRESSING);
engageModule(Constant.MODULE_RAMPART);
} else {
servClient.disengageModule(Constants.MODULE_ADDRESSING);
servClient.disengageModule(Constant.MODULE_RAMPART);
}
servClient.getOptions().setManageSession(enable);
}
public void configureAttachmentsEngine(String attachTempDirPath,
int fileSizeThresHold, boolean enableMTOM) {
servClient.getOptions().setProperty(Constants.Configuration.ENABLE_SWA,
Constants.VALUE_TRUE);
servClient.getOptions().setProperty(Constants.Configuration.CACHE_ATTACHMENTS,
true);
servClient.getOptions().setProperty(Constants.Configuration.ATTACHMENT_TEMP_DIR,
attachTempDirPath);
servClient.getOptions().setProperty(Constants.Configuration.FILE_SIZE_THRESHOLD,
fileSizeThresHold);
servClient.getOptions().setProperty(Constants.Configuration.ENABLE_MTOM,
enableMTOM);
}
/**
* Invoke a web service operation with return value, in a
synchronous manner
*
* @param methodName The name of the method which will be invoked
in the
* service specified.
* @param args The arguments of that method
* @param retType The return types Cass of that method
* @return The objects array that represent the response of the call.
*/
public synchronized Object[] invoke(String methodName, Object[]
args, Class retType) throws AxisFault {
Notification notif = fireNotifyEvent(NotifLevel.CALL, "Calling
" + methodName + " Operation.", null);
Object[] response = null;
try {
OMElement payload = createPayload(methodName, args);
OMElement omResponse = servClient.sendReceive(payload);
response = BeanUtil.deserialize(omResponse,
getClassArrayOfTypeFromOMElement(retType, omResponse), new
DefaultObjectSupplier());
fireNotifyEvent(NotifLevel.RESPONSE, "Calling " +
methodName + " Operation.", notif);
} catch (AxisFault ex) {
ServerException servEx = ExUtil.reflectServerException(ex);
if (servEx != null) {
fireNotifyEvent(NotifLevel.ERROR, servEx.getMessage(),
notif);
throw servEx;
} else {
throw ex;
}
}
return response;
}
/**
* Simillar to "Object[] invoke(...)" bat the invokation will be
done in a
* asynchronous manner.
*
* @param methodName The name of the method which will be invoked
in the
* service specified.
* @param args The arguments of that method
* @param callBack The callbackobject which will recive the server
respose
* when operation conclude. We recomend you use <a
*
href="org.cu.kms.ws.client.DefaultAxisCallback">DefaultAxisCallback</a>
* implementation.
*/
public synchronized void invokeAsync(final String methodName,
Object[] args, final AxisCallback callBack) throws AxisFault {
final Notification notif = fireNotifyEvent(NotifLevel.CALL,
"Calling " + methodName + " Operation.", null);
try {
OMElement payload = createPayload(methodName, args);
servClient.sendReceiveNonBlocking(payload, new AxisCallback() {
@Override
public void onMessage(MessageContext msgContext) {
fireNotifyEvent(NotifLevel.RESPONSE, "Calling " +
methodName + " Operation.", notif);
callBack.onMessage(msgContext);
}
@Override
public void onFault(MessageContext msgContext) {
callBack.onFault(msgContext);
}
@Override
public void onError(Exception e) {
callBack.onError(e);
}
@Override
public void onComplete() {
callBack.onComplete();
}
});
} catch (AxisFault ex) {
ServerException servEx = ExUtil.reflectServerException(ex);
if (servEx != null) {
fireNotifyEvent(NotifLevel.ERROR, servEx.getMessage(),
notif);
throw servEx;
} else {
throw ex;
}
}
}
public synchronized void invoke(String methodName, Object[] args)
throws AxisFault {
Notification notif = fireNotifyEvent(NotifLevel.CALL, "Calling
" + methodName + " Operation.", null);
try {
OMElement payload = createPayload(methodName, args);
servClient.sendRobust(payload);
} catch (AxisFault ex) {
ServerException servEx = ExUtil.reflectServerException(ex);
if (servEx != null) {
fireNotifyEvent(NotifLevel.ERROR, servEx.getMessage(),
notif);
throw servEx;
} else {
throw ex;
}
}
}
public synchronized Object[] invokeWithAttachments(String
methodName, Object[] args, Class retType, AxisCallback callBack, String
downloadDirPath) throws IOException, TimeOutException {
return opClientInvoke(methodName, args, retType, 400l, callBack
!= null, callBack, downloadDirPath);
}
private Object[] opClientInvoke(String methodName, Object[] args,
Class retType, long timeOutMS, boolean asynchronousCall, AxisCallback
callBack, String downloadDirPath) throws IOException, TimeOutException {
Object[] response = null;
try {
OperationClient opClient =
servClient.createClient(ServiceClient.ANON_OUT_IN_OP);
MessageContext outMsgCtx = new MessageContext();
outMsgCtx.setServiceContext(servClient.getServiceContext());
outMsgCtx.setOptions(servClient.getOptions());
addAttachments(outMsgCtx, args);
SOAPEnvelope envelop = creatSOAPEnvelop(methodName, args);
servClient.addHeadersToEnvelope(envelop);
outMsgCtx.setEnvelope(envelop);
opClient.addMessageContext(outMsgCtx);
if (asynchronousCall) {
opClient.setCallback(callBack);
opClient.execute(false);
} else {
opClient.execute(true);
MessageContext inMsgtCtx = null;
SOAPBody omBodyResponse = null;
if (retType != null) {
long startTime = System.currentTimeMillis();
while ((inMsgtCtx =
opClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE)) == null
|| inMsgtCtx.getEnvelope() == null) {
if ((System.currentTimeMillis() - startTime) >
timeOutMS) {
throw new TimeOutException();
}
}
if (servClient.getOptions().isCallTransportCleanup()) {
inMsgtCtx.getEnvelope().build();
cleanupTransport(outMsgCtx.getOperationContext());
}
omBodyResponse = inMsgtCtx.getEnvelope().getBody();
}
// if (downloadDirPath != null) {
// recoveryAttachments(inMsgtCtx, downloadDirPath);
// }
Object[] classArrayOfTypeFromOMElement =
getClassArrayOfTypeFromOMElement(retType, omBodyResponse);
Class[] retTypes = new
Class[classArrayOfTypeFromOMElement.length];
for (int i = 0; i <
classArrayOfTypeFromOMElement.length; i++) {
Class c = (Class) classArrayOfTypeFromOMElement[i];
retTypes[i] = c;
}
extractAttachments(inMsgtCtx, args);
response = omBodyResponse == null ? null :
BeanUtil.deserialize(omBodyResponse.getFirstElement(), retTypes, new
DefaultObjectSupplier());
}
} catch (TimeOutException ex) {
throw new TimeOutException();
} catch (AxisFault ex) {
ServerException servEx = ExUtil.reflectServerException(ex);
if (servEx != null) {
fireNotifyEvent(NotifLevel.ERROR, servEx.getMessage(),
null);
throw servEx;
} else {
throw ex;
}
}
return response;
}
public synchronized void invokeAsyncWithAttachment(final String
methodName, Object[] args, final AxisCallback callBack, File attachment)
throws AxisFault {
final Notification notif = fireNotifyEvent(NotifLevel.CALL,
"Calling " + methodName + " Operation.", null);
try {
OMElement payload = createPayload(methodName, args);
servClient.sendReceiveNonBlocking(payload, new AxisCallback() {
@Override
public void onMessage(MessageContext msgContext) {
fireNotifyEvent(NotifLevel.RESPONSE, "Calling " +
methodName + " Operation.", notif);
callBack.onMessage(msgContext);
}
@Override
public void onFault(MessageContext msgContext) {
callBack.onFault(msgContext);
}
@Override
public void onError(Exception e) {
callBack.onError(e);
}
@Override
public void onComplete() {
callBack.onComplete();
}
});
} catch (AxisFault ex) {
ServerException servEx = ExUtil.reflectServerException(ex);
if (servEx != null) {
fireNotifyEvent(NotifLevel.ERROR, servEx.getMessage(),
notif);
throw servEx;
} else {
throw ex;
}
}
}
private Object[] getClassArrayOfTypeFromOMElement(Class type,
OMElement oMElement) {
List<Class> list = new ArrayList<Class>();
Iterator iterator = oMElement.getChildElements();
while (iterator.hasNext()) {
Object next = iterator.next();
if (next instanceof OMElement) {
OMElement element = (OMElement) next;
Iterator attrs = element.getAllAttributes();
Class classType = null;
while (attrs.hasNext()) {
OMAttribute attr = (OMAttribute) attrs.next();
if ("type".equals(attr.getLocalName())) {
String[] components =
attr.getAttributeValue().split(":");
classType = resolveSubType(components[0],
components[1], element);
if (classType == null) {
classType = resolveSubType(components[0],
components[1], oMElement);
}
if (classType != null) {
break;
}
}
}
list.add(classType != null ? classType : type);
}
}
return list.toArray();
}
private Class resolveSubType(String packNs, String classSimpleName,
OMElement element) {
Class classType = null;
Iterator nsIt = element.getAllDeclaredNamespaces();
while (nsIt.hasNext()) {
OMNamespace ns = (OMNamespace) nsIt.next();
if (packNs.equals(ns.getPrefix())) {
try {
URL url = new URL(ns.getNamespaceURI());
String host = url.getHost();
String[] splitedHostName = host.split("\\.");
String typePackage = "";
for (String pack : splitedHostName) {
typePackage = pack + "." + typePackage;
}
String className = typePackage + classSimpleName;
classType = Class.forName(className);
} catch (Exception ex) {
}
}
}
return classType;
}
/**
* Return the SOAP factory to use depending on what options have
been set.
* If the SOAP version can not be seen in the options, version 1.1
is the
* default.
*
* @return the SOAP factory
* @see Options#setSoapVersionURI(String)
*/
private SOAPFactory getSOAPFactory() {
String soapVersionURI =
servClient.getOptions().getSoapVersionURI();
if
(SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI.equals(soapVersionURI)) {
return OMAbstractFactory.getSOAP12Factory();
} else {
// make the SOAP 1.1 the default SOAP version
return OMAbstractFactory.getSOAP11Factory();
}
}
private OMElement createPayload(String methodName, Object[] args) {
QName method = new QName(this.targetNameSpace, methodName);
this.servClient.getOptions().setAction("urn:" + methodName);
OMElement payload = BeanUtil.getOMElement(method, args, null,
false, new TypeTable());
return payload;
}
private SOAPEnvelope creatSOAPEnvelop(String methodName, Object[]
args) {
SOAPFactory fac = getSOAPFactory();
SOAPEnvelope envelope = fac.getDefaultEnvelope();
OMElement payload = createPayload(methodName, args);
if (payload != null) {
envelope.getBody().addChild(payload);
}
return envelope;
}
public void cleanupTransport(OperationContext opCtx) throws AxisFault {
if (opCtx != null) {
MessageContext outMsgCtx =
opCtx.getMessageContext(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
if (outMsgCtx != null) {
if (outMsgCtx.getTransportOut() != null &&
outMsgCtx.getTransportOut().getSender() != null) {
outMsgCtx.getTransportOut().getSender().cleanup(outMsgCtx);
}
}
}
}
private void addAttachments(MessageContext outMsgCtx, Object[] args) {
if (args != null && args.length > 0) {
for (Object arg : args) {
if (arg instanceof AttachmentInfo) {
AttachmentInfo attachInf = (AttachmentInfo) arg;
DataSource dataSource = attachInf.isEmpty()
? EmptyDataSource.INSTANCE
: attachInf.createDataSource();
DataHandler dataHandler = new DataHandler(dataSource);
if (attachInf.getIdAttach() == null) {
String contentId =
outMsgCtx.addAttachment(dataHandler);
attachInf.setIdAttach(contentId);
} else {
outMsgCtx.addAttachment(attachInf.getIdAttach(), dataHandler);
}
}
}
}
}
private void recoveryAttachments(MessageContext inMsgtCtx, String
downloadDirPath) {
Attachments attachmentMap = inMsgtCtx.getAttachmentMap();
if (attachmentMap != null) {
for (String contentId : attachmentMap.getAllContentIDs()) {
DataHandler attachment =
inMsgtCtx.getAttachment(contentId);
if (attachment != null) {
File attachmentFile = new File(downloadDirPath +
File.separator + contentId);
FileOutputStream outputStream;
try {
outputStream = new
FileOutputStream(attachmentFile);
attachment.writeTo(outputStream);
} catch (IOException ex) {
Logger.getLogger(WSClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
public void reset() {
try {
servClient.cleanup();
} catch (AxisFault ex) {
Logger.getLogger(WSClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void extractAttachments(MessageContext inMsgtCtx, Object[]
args) throws IOException {
for (Object arg : args) {
if (arg instanceof AttachmentInfo && arg != null) {
AttachmentInfo attachmentInfo = (AttachmentInfo) arg;
DataHandler attachment =
inMsgtCtx.getAttachment(attachmentInfo.getIdAttach());
if (attachment != null && attachmentInfo instanceof
FileAttachment) {
File attachmentFile = new File(((FileAttachment)
attachmentInfo).getFilePath());
FileOutputStream outputStream = null;
try {
outputStream = new
FileOutputStream(attachmentFile);
attachment.writeTo(outputStream);
outputStream.flush();
outputStream.close();
} catch (IOException ex) {
Logger.getLogger(WSClient.class.getName()).log(Level.SEVERE, null, ex);
try {
outputStream.close();
} catch (IOException ex1) {
throw ex1;
}
}
}
}
}
}
}
10mo. ANIVERSARIO DE LA CREACION DE LA UNIVERSIDAD DE LAS CIENCIAS INFORMATICAS...
CONECTADOS AL FUTURO, CONECTADOS A LA REVOLUCION
http://www.uci.cu
http://www.facebook.com/universidad.uci
http://www.flickr.com/photos/universidad_uci
---------------------------------------------------------------------
To unsubscribe, e-mail: java-dev-unsubscribe@axis.apache.org
For additional commands, e-mail: java-dev-help@axis.apache.org