I have a question about authentication with jain sip library. I am using jain sip for registering sip accounts to Asterisk server.
As soon as I try to add AuthorizationHeader the following error message appears:
The method makeAuthHeader(HeaderFactory, Response, Request, String, String) is undefined for the type Utils
Here is the code snippet:
AuthorizationHeader authHeader = Utils.makeAuthHeader(
headerFactory, response, request, userId, password);
request.addHeader(authHeader);
It seems that cannot method makeAuthHeader() cannot be found.
Code SipClientServiceImpl.java:
#Service("clientService")
public class SipClientServiceImpl implements SipClientService, SipListener {
SipFactory sipFactory; // Used to access the SIP API.
SipStack sipStack; // The SIP stack.
SipProvider sipProvider; // Used to send SIP messages.
MessageFactory messageFactory; // Used to create SIP message factory.
HeaderFactory headerFactory; // Used to create SIP headers.
AddressFactory addressFactory; // Used to create SIP URIs.
ListeningPoint listeningPoint; // SIP listening IP address/port.
Properties properties; // Other properties.
// Objects keeping local configuration.
String ip; // The local IP address.
int port = 6060; // The local port.
String protocol = "udp"; // The local protocol (UDP).
int tag = (new Random()).nextInt(); // The local tag.
Address contactAddress; // The contact address.
ContactHeader contactHeader;
String asteriskServer = "10.0.0.0.0";
int asteriksPort = 5060;
String sipPasswordForAllAccounts = "1234";
Request request = null;
Response response = null;
private ClientTransaction inviteTid;
long invco = 1;
public void registerToAsterisk(String userId) throws ParseException,
InvalidArgumentException, PeerUnavailableException,
TransportNotSupportedException, ObjectInUseException,
TooManyListenersException {
init();
try {
// Get the destination address from the text field.
Address addressTo = addressFactory.createAddress("sip:" + userId
+ '#' + asteriskServer + ":" + asteriksPort);
// Create the request URI for the SIP message.
javax.sip.address.URI requestURI = addressTo.getURI();
// Create the SIP message headers.
// The "Via" headers.
ArrayList viaHeaders = new ArrayList();
ViaHeader viaHeader = this.headerFactory.createViaHeader(this.ip,
this.port, "udp", null);
viaHeaders.add(viaHeader);
// The "Max-Forwards" header.
MaxForwardsHeader maxForwardsHeader = this.headerFactory
.createMaxForwardsHeader(70);
// The "Call-Id" header.
CallIdHeader callIdHeader = this.sipProvider.getNewCallId();
// The "CSeq" header.
CSeqHeader cSeqHeader = this.headerFactory.createCSeqHeader(1L,
"REGISTER");
// The "From" header.
FromHeader fromHeader = this.headerFactory.createFromHeader(
this.contactAddress, String.valueOf(this.tag));
// The "To" header.
ToHeader toHeader = this.headerFactory.createToHeader(addressTo,
null);
// AuthorizationHeader authHeader = Utils.makeAuthHeader(
// headerFactory, response, request, userId,
// sipPasswordForAllAccounts);
// Create the REGISTER request.
Request request = this.messageFactory.createRequest(requestURI,
"REGISTER", callIdHeader, cSeqHeader, fromHeader, toHeader,
viaHeaders, maxForwardsHeader);
// Add the "Contact" header to the request.
request.addHeader(contactHeader);
// request.addHeader(authHeader);
// Send the request statelessly through the SIP provider.
this.sipProvider.sendRequest(request);
} catch (Exception e) {
// TODO: handle exception
}
// TODO Auto-generated method stub
}
public void processRequest(RequestEvent requestEvent) {
}
public void processResponse(ResponseEvent responseEvent) {
Response response = responseEvent.getResponse();
System.out.println(response);
ClientTransaction tid = responseEvent.getClientTransaction();
CSeqHeader cseq = (CSeqHeader) response.getHeader(CSeqHeader.NAME);
System.out.println("Response received : Status Code = "
+ response.getStatusCode() + " " + cseq);
// if (tid == null) {
// System.out.println("Stray response -- dropping ");
// return;
// }
try {
if (response.getStatusCode() == Response.PROXY_AUTHENTICATION_REQUIRED
|| response.getStatusCode() == Response.UNAUTHORIZED) {
AuthenticationHelper authenticationHelper = ((SipStackExt) sipStack)
.getAuthenticationHelper(new AccountManagerImpl(),
headerFactory);
inviteTid = authenticationHelper.handleChallenge(response, tid,
sipProvider, 5, false);
inviteTid.sendRequest();
invco++;
}
} catch (Exception ex) {
ex.printStackTrace();
System.exit(0);
}
}
public void processTimeout(TimeoutEvent timeoutEvent) {
// TODO Auto-generated method stub
}
public void processIOException(IOExceptionEvent exceptionEvent) {
// TODO Auto-generated method stub
}
public void processTransactionTerminated(
TransactionTerminatedEvent transactionTerminatedEvent) {
// TODO Auto-generated method stub
}
public void processDialogTerminated(
DialogTerminatedEvent dialogTerminatedEvent) {
// TODO Auto-generated method stub
}
public void init() {
// Get the local IP address.
try {
this.ip = InetAddress.getLocalHost().getHostAddress();
// Create the SIP factory and set the path name.
this.sipFactory = SipFactory.getInstance();
this.sipFactory.setPathName("gov.nist");
// Create and set the SIP stack properties.
this.properties = new Properties();
this.properties.setProperty("javax.sip.STACK_NAME", "stack");
// Create the SIP stack.
this.sipStack = this.sipFactory.createSipStack(this.properties);
// Create the SIP message factory.
this.messageFactory = this.sipFactory.createMessageFactory();
// Create the SIP header factory.
this.headerFactory = this.sipFactory.createHeaderFactory();
// Create the SIP address factory.
this.addressFactory = this.sipFactory.createAddressFactory();
// Create the SIP listening point and bind it to the local IP
// address, port and protocol.
this.listeningPoint = this.sipStack.createListeningPoint(this.ip,
this.port, this.protocol);
// Create the SIP provider.
this.sipProvider = this.sipStack
.createSipProvider(this.listeningPoint);
// Add our application as a SIP listener.
this.sipProvider.addSipListener(this);
// Create the contact address used for all SIP messages.
this.contactAddress = this.addressFactory.createAddress("sip:"
+ this.ip + ":" + this.port);
// Create the contact header used for all SIP messages.
this.contactHeader = this.headerFactory
.createContactHeader(contactAddress);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Stack trace:
javax.sip.SipException: Unexpected exception
at gov.nist.javax.sip.clientauthutils.AuthenticationHelperImpl.handleChallenge(AuthenticationHelperImpl.java:298)
at com.musala.ving.voip.SipClientServiceImpl.processResponse(SipClientServiceImpl.java:152)
at gov.nist.javax.sip.EventScanner.deliverEvent(EventScanner.java:296)
at gov.nist.javax.sip.EventScanner.run(EventScanner.java:519)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
at gov.nist.javax.sip.clientauthutils.AuthenticationHelperImpl.handleChallenge(AuthenticationHelperImpl.java:149)
... 4 more
Any suggestion is appreciated!
Thank you!
Well, Utils is not part of the API and it simply doesn't have the method you are trying to use. The best way to do client auth is to use the example from https://svn.java.net/svn/jsip~svn/trunk/src/examples/authorization/ShootistAuth.java
This is the relevant part:
if (response.getStatusCode() == Response.PROXY_AUTHENTICATION_REQUIRED
|| response.getStatusCode() == Response.UNAUTHORIZED) {
AuthenticationHelper authenticationHelper =
((SipStackExt) sipStack).getAuthenticationHelper(new AccountManagerImpl(), headerFactory);
inviteTid = authenticationHelper.handleChallenge(response, tid, sipProvider, 5);
inviteTid.sendRequest();
invco++;
}
The class Utils doesn't own this method as you can see here:
http://grepcode.com/file/repo1.maven.org/maven2/javax.sip/jain-sip-ri/1.2.203/gov/nist/javax/sip/Utils.java
You have to use something different but I cannot find anything about what class/method to use.
Related
I generated my client soap from wsimport JAX-WS, I have already consumed others webservice that it had fault message mapped, but the service current doesn't have.
When I call the service and it returns fault message I can't get the message in the Java, but if call from soapUI I can see the error.
The fault message is the same of the success, generated from JAX-WS.
My code:
//before I setter my request
try{
IPGApiOrderService iPGApiOrderService = new IPGApiOrderService();
IPGApiOrder client = iPGApiOrderService.getIPGApiOrderSoap11();
IPGApiOrderResponse response = client.ipgApiOrder(request)
}catch (SOAPFaultException soapEx) {
System.out.println("Fault ............. " + soapEx.getFault());
System.out.println("Detail ............ " + soapEx.getFault().getDetail());
System.out.println("FaultCode.......... " + soapEx.getFault().getFaultCode());
System.out.println("FaultActor......... " + soapEx.getFault().getFaultActor());
System.out.println("Message............ " + soapEx.getMessage());
soapEx.printStackTrace();
}
follow the out
Fault ............. [SOAP-ENV:Fault: null]
Detail ............ [detail: null]
FaultCode.......... SOAP-ENV:Client
FaultActor......... null
Message............ Client received SOAP Fault from server: ProcessingException Please see the server log to find more detail regarding exact cause of the failure.
com.sun.xml.internal.ws.fault.ServerSOAPFaultException: Client received SOAP Fault from server: ProcessingException Please see the server log to find more detail regarding exact cause of the failure.
at com.sun.xml.internal.ws.fault.SOAP11Fault.getProtocolException(SOAP11Fault.java:178)
at com.sun.xml.internal.ws.fault.SOAPFaultBuilder.createException(SOAPFaultBuilder.java:124)
at com.sun.xml.internal.ws.client.sei.StubHandler.readResponse(StubHandler.java:238)
at com.sun.xml.internal.ws.db.DatabindingImpl.deserializeResponse(DatabindingImpl.java:189)
at com.sun.xml.internal.ws.db.DatabindingImpl.deserializeResponse(DatabindingImpl.java:276)
at com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:104)
at com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:77)
at com.sun.xml.internal.ws.client.sei.SEIStub.invoke(SEIStub.java:147)
at com.sun.proxy.$Proxy36.ipgApiOrder(Unknown Source)
at com.firstdata.test.demo.MainTest.main(MainTest.java:53)
I resolved my problem with following steps.
Create SOAPHandler;
It'll be necessary implement 4 methods;
On method handleFault get SOAPMessageContext -> SOAPMessage -> SOAPBody -> Fault -> Detail -> add detail with xml error or some information do you want.
3.1 Fault you can put fault code, if API you was consuming always return one code error to API fault.
4. On exception you find that detail you set and work with it.
Code:
public class SOAPHandlerImpl implements SOAPHandler<SOAPMessageContext> {
public static final QName JSON_ERROR = new QName("json-error");
public boolean handleMessage(SOAPMessageContext smc) {
SOAPMessage message = smc.getMessage();
Boolean isOut = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
return isOut;
}
#Override
public boolean handleFault(SOAPMessageContext context) {
SOAPMessage message = context.getMessage();
try {
StringOutputStream str = new StringOutputStream();
message.writeTo(str);
ErrorDTO dto = XmlUtil.buildErroDTO(str.toString());
Detail detail = message.getSOAPBody().getFault().getDetail();
Gson gson = new Gson();
String obj = gson.toJson(dto);
detail.addDetailEntry(JSON_ERROR).addTextNode(obj);
message.getSOAPBody().getFault().setFaultCode(String.valueOf(dto.getTransactionId()));
} catch (Exception e) {
System.out.println("Exception in handler: " + e);
}
return true;
}
#Override
public void close(MessageContext context) {
// TODO Auto-generated method stub
}
#Override
public Set<QName> getHeaders() {
// TODO Auto-generated method stub
return null;
}
}
Catch exception
} catch (SOAPFaultException sopex) {
ErrorDTO error = null;
Iterator childElements = sopex.getFault().getDetail().getChildElements();
while (childElements.hasNext()) {
DetailEntry next = (DetailEntry) childElements.next();
if (SOAPHandlerImpl.JSON_ERROR.getLocalPart().equals(next.getNodeName())) {
Gson gson = new Gson();
error = gson.fromJson(next.getValue(), ErrorDTO.class);
}
}
String message = null;
if(error.getProcessorResponseCode() != null) {
message = ErrorApiUtil.getInstance().getMessage(error.getProcessorResponseCode());
}else {
message = error.getMessage();
}
throw new BusinessException(message);
}
I develop gwt client application for web and i used google app engine for server
I write the server in java
I send the requests to server with RequestBuilder
how I can sync the cookies between server and client.
every request client send to server the server create new session
I want to avoid it
in server I write code like this in every request
private void addCookies(){
String jsessionId = request.getParameter("JSESSIONID");
if (jsessionId != null && !jsessionId.isEmpty()) {
Cookie userCookie = new Cookie("JSESSIONID", jsessionId);
response.addCookie(userCookie);
} else {
String sessionId = request.getSession().getId();
Cookie userCookie = new Cookie("JSESSIONID", sessionId);
response.addCookie(userCookie);
}
}
So for the first request I created cookie with sessionId and I return the session id to client in response
In client I write code like this
public void setSessionId(String sessionId) {
Cookies.setCookie(JSESSIONID, sessionId);
}
I get the sessionId from server and add to cookie
When i send request with RequestBuilder is see like this
public void sendRequest(final BaseRequest baseReuest){
long currentTime = getApplicationServices().getTimeManager().getCurrentDate().getTime();
if(isSessionIdle()){
getBaseClientFactory().restart(true);
return;
}
if(baseReuest.getOptionsRequest().isShowLoader()){
showLoader(true);
loaderRequestsCounter++;
}
try {
String url = baseUrl + baseReuest.getMethodName();
RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST, url);
requestBuilder.setHeader("Content-type", "application/x-www-form-urlencoded");
baseReuest.addParam(JSESSIONID, getSessionId());
requestBuilder.sendRequest(baseReuest.getParamsAsString(), new RequestCallback() {
#Override
public void onResponseReceived(Request request, Response response) {
requestFinish(baseReuest);
int status = response.getStatusCode();
if(status == 200){
String json = response.getText();
BaseRequestResponse baseRequestResponse = baseReuest.buildResponse(json);
if(!baseRequestResponse.isSuccess()){
showFailureMessage(baseRequestResponse.getFailureResponse());
}
baseReuest.notifyResponse(baseRequestResponse);
}
else{
onErrorResponse();
}
}
#Override
public void onError(Request request, Throwable exception) {
onErrorResponse();
}
private void onErrorResponse(){
requestFinish(baseReuest);
String message = getLabels().getLabel(IGeneralInfoLabels.THERE_IS_PROBLEM_ACCESSING_THE_SERVER);
if(!isOnline()){
message = getApplicationServices().getGeneralManager().getLocalLabel().connectionNotAvailable();
}
FailureResponse failureResponse = new FailureResponse(message);
showFailureMessage(failureResponse);
baseReuest.notifyFailureResponse(failureResponse);
}
private void showFailureMessage(FailureResponse failureResponse){
if(baseReuest.getOptionsRequest().isShowMessage()){
BaseRequestManager.this.showFailureMessage(failureResponse);
}
}
});
lastRequestSentTime = currentTime;
} catch (RequestException e) {
showLoader(false);
requestFinish(baseReuest);
}
}
for example for first request the sessionId is jk7br57mo1e5 so I add the sessionId to cookie in client
but in every request the server created new sessionId why?
thank you
In a Java HttpServlet, is it possible to request data from another local service using the original request's header information without necessarily forwarding?
For example, I have FooBar.java:
// Handles the url at /foo/bar and can be accessed at http://localhost/foo/bar
public class FooBar extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
Object data = ... // 1. Retrieve data at http://localhost/foo/baz utilizing the current request's header
Object newData = doSomething(data); // 2. Process the data
response.getWriter().write(newData.toString); // 3. Return the processed data
}
private Object doSomething(Object data)
{
// Perform some business logic
}
}
Step 1 is the issue here. The purpose of this is that I want to be able to perform some sort of logic on the data before returning it in full, but don't necessarily have access do make the changes on the handler at /foo/baz do to the propriety nature of things.
You can use this answer of me to create a HTTP Request: send get request
In addition, it may be necessary to copy the request header with some care:
private static final Set forbiddenCopyHeaders = new HashSet<>(Arrays.asList(new String[]{
"connection"
, "transfer-encoding"
, "content-length" // POST kann zu Status 500 führen, wenn die content-length kopiert wird
, "via"
, "x-forwarded-for"
, "x-forwarded-host"
, "x-forwarded-server"
}));
private void copyRequestHeaders(HttpServletRequest customerRequest, HttpRequestBase internRequest) throws
HttpException
{
Enumeration<String> headerNames = customerRequest.getHeaderNames();
String connectionHeader = customerRequest.getHeader("connection");
while (headerNames.hasMoreElements())
{
String headerName = headerNames.nextElement();
boolean copyAllowed = !forbiddenCopyHeaders.contains(headerName.toLowerCase()) &&
!StringUtils.containsIgnoreCase(connectionHeader, headerName);
if (copyAllowed)
{
Enumeration<String> values = customerRequest.getHeaders(headerName);
while (values.hasMoreElements())
{
internRequest.addHeader(headerName, values.nextElement());
}
}
}
setProxySpecificRequestHeaders(customerRequest, internRequest);
}
private void setProxySpecificRequestHeaders(HttpServletRequest customerRequest,
HttpRequestBase internRequest) throws HttpException
{
String serverHostName = "doorman";
try
{
serverHostName = InetAddress.getLocalHost().getHostName();
}
catch (UnknownHostException e)
{
logger.error("Couldn't get the hostname needed for headers x-forwarded-server and Via", e);
}
String originalVia = customerRequest.getHeader("via");
StringBuilder via = new StringBuilder("");
if (originalVia != null)
{
if (originalVia.contains(serverHostName))
{
logger.error("This proxy has already handled the Request, will abort.");
throw new HttpException("Request has a cyclic dependency on this proxy.");
}
else
{
via.append(originalVia).append(", ");
}
}
via.append(customerRequest.getProtocol()).append(" ").append(serverHostName);
internRequest.addHeader("via", via.toString());
internRequest.addHeader("x-forwarded-for", customerRequest.getRemoteAddr());
internRequest.addHeader("x-forwarded-host", customerRequest.getServerName());
internRequest.addHeader("x-forwarded-server", serverHostName);
internRequest.addHeader("accept-encoding", "");
}
Using HttpURLConnection and altering the header to include a property from the original request, I was able to get a BufferedReader from the HTTP request:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// Step 1
String serverName = request.getLocalName();
String contextPath = request.getContextPath();
URL url = new URL("https://" + serverName + contextPath + "/baz");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Key Header", request.getHeader("Key Header"));
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
// Step 2
... // Do something with the data from the reader
// Step 3
... // Write the data back using the response
}
I have a JAX-WS 2.2 WebService and I must take the IP Address of each client that communicate with it. I write a SOAP protocol handler but I can't see the addresses because the handlers doesn't contain this information and using the mimeheaders I can't also see this information. The code of my handler is the follow:
public class AddressHandler implements SOAPHandler<SOAPMessageContext> {
private void takeIPAddress(SOAPMessageContext context) {
try {
SOAPMessage original = context.getMessage();
MimeHeaders mimeheaders = original.getMimeHeaders();
MimeHeader mimeheader = null;
Iterator<?> iter = mimeheaders.getAllHeaders();
for (; iter.hasNext();) {
mimeheader = (MimeHeader) iter.next();
System.out.println("name=" + mimeheader.getName() + ", value="
+ mimeheader.getValue());
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void close(MessageContext arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean handleFault(SOAPMessageContext arg0) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean handleMessage(SOAPMessageContext context) {
takeIPAddress(context);
return true;
}
#Override
public Set<QName> getHeaders() {
// TODO Auto-generated method stub
return null;
}
}
Now I'm seeing that would be possible to see the addresses using the following code:
SOAPMessageContext jaxwsContext = (SOAPMessageContext)wsContext.getMessageContext();
HttpServletRequest request = HttpServletRequest)jaxwsContext.get(SOAPMessageContext.SERVLET_REQUEST);
String ipAddress = request.getRemoteAddr();
But I can't import correctly the HttpServletRequest class. Do you have any ideas?
UPDATE
Thanks to A Nyar Thar, I've seen that exists another method to take address and I've implemented this in my code, that now is:
private void takeIPAddress(SOAPMessageContext context) {
HttpExchange exchange = (HttpExchange)context.get("com.sun.xml.ws.http.exchange");
InetSocketAddress remoteAddress = exchange.getRemoteAddress();
String remoteHost = remoteAddress.getHostName();
System.out.println(remoteHost);
}
But the code execution create this error (where row 39 is where I do exchange.getRemoteAddress()):
java.lang.NullPointerException
at server.AddressHandler.takeIPAddress(AddressHandler.java:39)
at server.AddressHandler.handleMessage(AddressHandler.java:80)
at server.AddressHandler.handleMessage(AddressHandler.java:1)
at com.sun.xml.internal.ws.handler.HandlerProcessor.callHandleMessage(HandlerProcessor.java:282)
at com.sun.xml.internal.ws.handler.HandlerProcessor.callHandlersRequest(HandlerProcessor.java:125)
at com.sun.xml.internal.ws.handler.ServerSOAPHandlerTube.callHandlersOnRequest(ServerSOAPHandlerTube.java:123)
at com.sun.xml.internal.ws.handler.HandlerTube.processRequest(HandlerTube.java:105)
at com.sun.xml.internal.ws.api.pipe.Fiber.__doRun(Fiber.java:626)
at com.sun.xml.internal.ws.api.pipe.Fiber._doRun(Fiber.java:585)
at com.sun.xml.internal.ws.api.pipe.Fiber.doRun(Fiber.java:570)
at com.sun.xml.internal.ws.api.pipe.Fiber.runSync(Fiber.java:467)
at com.sun.xml.internal.ws.server.WSEndpointImpl$2.process(WSEndpointImpl.java:299)
at com.sun.xml.internal.ws.transport.http.HttpAdapter$HttpToolkit.handle(HttpAdapter.java:593)
at com.sun.xml.internal.ws.transport.http.HttpAdapter.handle(HttpAdapter.java:244)
at com.sun.xml.internal.ws.transport.http.server.WSHttpHandler.handleExchange(WSHttpHandler.java:95)
at com.sun.xml.internal.ws.transport.http.server.WSHttpHandler.handle(WSHttpHandler.java:80)
at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:77)
at sun.net.httpserver.AuthFilter.doFilter(AuthFilter.java:83)
at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:80)
at sun.net.httpserver.ServerImpl$Exchange$LinkHandler.handle(ServerImpl.java:677)
at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:77)
at sun.net.httpserver.ServerImpl$Exchange.run(ServerImpl.java:649)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
I think that the real problem is that I don't know how take WebServiceContext from my class AddressHandler. Do you have ideas?
For JAX-WS based webservice, you can access remote host info from javax.xml.ws.spi.http.HttpExchange, that can be accessed based on JAX-WS version,
JAX-WS 2.1
SOAPMessageContext soapContext = (SOAPMessageContext)wsContext.getMessageContext();
HttpExchange exchange = (HttpExchange)soapContext.get(JAXWSProperties.HTTP_EXCHANGE);
JAX-WS 2.2
SOAPMessageContext soapContext = (SOAPMessageContext)wsContext.getMessageContext();
HttpExchange exchange = (HttpExchange)soapContext.get("com.sun.xml.ws.http.exchange");
Note that wsContext.getMessageContext() will return MessageContext. If you want it, don't cast to SOAPMessageContext, like that,
MessageContext msgContext = wsContext.getMessageContext();
Finally you can access remote address info,
InetSocketAddress remoteAddress = exchange.getRemoteAddress();
String remoteHost = remoteAddress.getHostName();
I am trying to invoke a webservice method which takes 2 input parameters and also needs a cookie to authenticate.
PostMethod method = new PostMethod("webservice EP URL");
NameValuePair code = new NameValuePair("Code", "");
NameValuePair revision = new NameValuePair("Rev", "Latest");
NameValuePair targetUri = new NameValuePair("TARGET", "GetObject");
method.setRequestBody(new NameValuePair[] { code, revision,targetUri});
int statusNew = client.executeMethod(method);
I dont know how to achieve it. Above code is what i am doing currently.
Most probably you are dealing with RESTful web services (Just my guess as you are passing parameters as http form params). Here is how to pass cookies
method.setRequestHeader("Cookie", "special-cookie=value");
Here just change "special-cookie=value" to your specific cookie that you are trying to pass.
EDIT: Adding cookie to SOAP request:
The quickest way to do is as follows
(Assuming that the call object you are using is an instance of org.apache.axis.client.Call)
call.setProperty(
org.apache.axis.client.Call.SESSION_MAINTAIN_PROPERTY,
new Boolean(true));
call.setProperty(
org.apache.axis.transport.http.HTTPConstants.HEADER_COOKIE2,
"\r\nCookieName=" + "CookieValue");
Please check "Use a SOAPAction HTTP Header" topic on this link.
Using the SOAP Handler, we can pass the headers in the request and it will do the job.
GetObject_Service_Impl impl = new GetObject_Service_Impl();
// Get Iterator for all service ports
Iterator iter = impl.getPorts();
// Now create a new List of HandlerInfo objects - only one really.
// Our client handler
List handlerChain = new ArrayList();
handlerChain.add(new HandlerInfo(SoapHandler.class, null, null));
// Get Handler Registry
HandlerRegistry registry = impl.getHandlerRegistry();
// Register each port with the handler
while (iter.hasNext())
registry.setHandlerChain((QName) iter.next(), handlerChain);
And Write a new class say SoapHandler.java as below
public class SoapHandler extends GenericHandler {
HandlerInfo hi;
public void init(HandlerInfo info) {
hi = info;
}
public QName[] getHeaders() {
return hi.getHeaders();
}
public boolean handleResponse(MessageContext context) {
return true;
}
/**
* This method is use to add custom headers to existing SAOP request
*/
public boolean handleRequest(MessageContext context) {
System.out.println("response");
try {
SOAPMessageContext smc = (SOAPMessageContext) context;
SOAPMessage message = smc.getMessage();
MimeHeaders hd = message.getMimeHeaders();
hd.addHeader("Authorization", "Basic some credentials");
} catch (Exception e) {
throw new JAXRPCException(e);
}
return true;
}
}
And thats it.....its ready to go.