How to use Holder<Payload> holder in SOAP web client - java

I am trying to figure out how to use a webservice which was generated from a wsdl file. In this project I am going send request by using the generated webservice client. The interface is shown below:
public interface IConnectService {
public void processMessage(
#WebParam(name = "payload", mode =
WebParam.Mode.INOUT)
Holder<Payload> payload);
}
The client is like this:
public class ConnectService
extends Service
{
private final static URL CONNECTSERVICE_WSDL_LOCATION;
private final static WebServiceException CONNECTSERVICE_EXCEPTION;
private final static QName CONNECTSERVICE_QNAME = new
QName("http://xxxxxx-asi.com/services", "ConnectService");
static {
URL url = null;
WebServiceException e = null;
try {
url = new URL("http://localhost/wsdl/xxxxx");
} catch (MalformedURLException ex) {
e = new WebServiceException(ex);
}
CONNECTSERVICE_WSDL_LOCATION = url;
CONNECTSERVICE_EXCEPTION = e;
}
public ConnectService() {
super(__getWsdlLocation(), CONNECTSERVICE_QNAME);
}
public ConnectService(WebServiceFeature... features) {
super(__getWsdlLocation(), CONNECTSERVICE_QNAME, features);
}
public ConnectService(URL wsdlLocation) {
super(wsdlLocation, CONNECTSERVICE_QNAME);
}
public ConnectService(URL wsdlLocation, WebServiceFeature...
features) {
super(wsdlLocation, CONNECTSERVICE_QNAME, features);
}
public ConnectService(URL wsdlLocation, QName serviceName) {
super(wsdlLocation, serviceName);
}
public ConnectService(URL wsdlLocation, QName serviceName,
WebServiceFeature... features) {
super(wsdlLocation, serviceName, features);
}
#WebEndpoint(name = "BasicHttpBinding_IConnectService")
public IConnectService getBasicHttpBindingIConnectService() {
return super.getPort(new QName("http://xxxxxxx-
asi.com/services", "BasicHttpBinding_IConnectService"),
IConnectService.class);
}
#WebEndpoint(name = "BasicHttpBinding_IConnectService")
public IConnectService
getBasicHttpBindingIConnectService(WebServiceFeature... features) {
return super.getPort(new QName("http://xxxxxx-asi.com/services",
"BasicHttpBinding_IConnectService"), IConnectService.class,
features);
}
private static URL __getWsdlLocation() {
if (CONNECTSERVICE_EXCEPTION!= null) {
throw CONNECTSERVICE_EXCEPTION;
}
return CONNECTSERVICE_WSDL_LOCATION;
}
}
The soap request message structure is going to be like in the picture: enter image description here
So my question is how can I use the client to make call which includes my soapmessage using the interface method? To my understand, the Holder object can only take Payload object, which is an childelement of ProcessMessege (as shown in the structure), and ProcessMessage is a childelement of SOAP body. I need to put the security credentials in the SOAP header and I already did that. So right now if I use the webservice method, I only can pass the payload object, but the web server will not accept the request because no credentials inside of the payload part. Anybody can help out for this problem? I really appreciate your help!

I solved this problem by using soapmessage handler and handler resolver. The handler can insert the credentials in the soap header and modifier the soap body to satisfy all my requirements for the soap message.

Related

Modifying request body in Zuul pre filter not working

In my app I am using netflix zuul to route a request from a microservice (gateway) to another. The requests are being routed fine but I also want to introduce some parameters in the request body before it is routed to the appropriate microservice. For this I am using Zuul pre filter like this.
public class SimpleFilter extends ZuulFilter {
private static Logger log = LoggerFactory.getLogger(SimpleFilter.class);
#Override
public String filterType() {
return "pre";
}
#Override
public int filterOrder() {
return 1;
}
#Override
public boolean shouldFilter() {
return true;
}
#Override
public Object run() {
try {
RequestContext context = RequestContext.getCurrentContext();
InputStream in = (InputStream) context.get("requestEntity");
if (in == null) {
in = context.getRequest().getInputStream();
}
String body = StreamUtils.copyToString(in, Charset.forName("UTF-8"));
// body = "request body modified via set('requestEntity'): "+ body;
body = body.toUpperCase();
context.set("requestEntity", new ByteArrayInputStream(body.getBytes("UTF-8")));
} catch (IOException e) {
log.error(e.getMessage(), e);
}
return null;
}
}
For now I am just trying to change the body to upper case but the microservice to which this request is routed doesn't receive the modified body (upper case). Instead it receives the original one. Am I doing something wrong. Any help would be appreciated. Thanks !!
Was able to do the following - transform a GET request to a POST request, and add body content to the (proxied) POST request.
public Object run() throws ZuulException {
RequestContext context = RequestContext.getCurrentContext();
context.addZuulRequestHeader("Content-Type", "application/x-www-form-urlencoded");
String body = String.format("a=%s&b=%s", a, b);
final byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
context.setRequest(new HttpServletRequestWrapper(context.getRequest()) {
#Override
public ServletInputStream getInputStream() {
return new ServletInputStreamWrapper(bytes);
}
#Override
public int getContentLength() {
return bytes.length;
}
#Override
public long getContentLengthLong() {
return bytes.length;
}
#Override
public String getMethod() {
return "POST";
}
});
return null;
}
try this one It's may be work in your case .
requestContext.getCurrentContext().put("requestEntity", new ByteArrayInputStream(body.getBytes("UTF-8")));
Turned out this method cannot change the request body within the requestContext. Truly in the requestContext, a new field "requestEntity" is added, however, the request body from context.getRequest().getInputStream() remains the same after this operation.
You can modify the request body, see this answer for an example. You just need to wrap the new request data and make sure you correctly report it's new content length.

Challenges performing basic HTTP authentication on RPC SOAP client

Been trying to follow some online examples as I need to do basic authentication on a webservice client.
I generated the stub classes of the project using wsimport and tried passing the authentication credentials using javax.xml.rpc.stub class but casting the proxy class throws a java.lang.ClassCastException:
com.sun.proxy.$Proxy29 cannot be cast to javax.xml.rpc.Stub.
please can anyone review this code and point me in the right direction if am doing something wrong.
public class WebClientTester
{
public static void main(String[] args)
{
doNameEnquiry("XXXXXXXXX");
}
public static void doNameEnquiry(String acct)
{
boolean txnOk = false;
try
{
String str = "http://XXX.XXX.XXX.XXX/GwHolderService.svc?wsdl";
URL url = new URL(str.substring(0, str.indexOf("?")));
QName qname = new QName("http://tempuri.org/", "GwHolderService");
Service service = Service.create(url, qname);
SInfoHolder port = (SInfoHolder) service.getPort(SInfoHolder.class);
((javax.xml.rpc.Stub) port)._setProperty(javax.xml.rpc.Stub.USERNAME_PROPERTY, "myUser");
((javax.xml.rpc.Stub) port)._setProperty(javax.xml.rpc.Stub.PASSWORD_PROPERTY, "myPwd");
InfoHolderRequest request = new InfoHolderRequest();
request.setHolderAccountNumber(acct);
InfoHolderResponse response = port.infoHolder(request);
// System.out.println("authenticated: "+
// response.getRespMessageCode());
System.out.println("******************END RESPONSE***********");
System.out.println("responseCode: " + response.getCoderesp());
System.out.println(processResponseXML(response));
System.out.println("******************LIST DETAILS***********");
listDetails(processResponseXML(response));
}
catch (Exception ex)
{
ex.printStackTrace();
}
// return txnOk;
}
}

Retrieve a list of a given user's tweets using Twitter API 1.1 and Retrofit

I'm trying to obtain a list of a user's tweets and I've run into some trouble when trying to authenticate my call to the API. I currently get a 401 when executing the code below:
public interface TwitterApi {
String API_URL = "https://api.twitter.com/1.1";
String CONSUMER_KEY = "<CONSUMER KEY GOES HERE>";
String CONSUMER_SECRET = "<CONSUMER SECRET GOES HERE>";
String ACCESS_TOKEN = "<ACCESS TOKEN GOES HERE>";
String ACCESS_TOKEN_SECRET = "<ACCESS TOKEN SECRET GOES HERE>";
#GET("/statuses/user_timeline.json")
List<Tweet> fetchUserTimeline(
#Query("count") final int count,
#Query("screen_name") final String screenName);
}
The following throws a 401 Authorisation error when calling fetchUserTimeline()
RetrofitHttpOAuthConsumer consumer = new RetrofitHttpOAuthConsumer(TwitterApi.CONSUMER_KEY, TwitterApi.CONSUMER_SECRET);
consumer.setTokenWithSecret(TwitterApi.ACCESS_TOKEN, TwitterApi.ACCESS_TOKEN_SECRET);
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(TwitterApi.API_URL)
.setClient(new SigningOkClient(consumer))
.build();
TwitterApi twitterApi = restAdapter.create(TwitterApi.class)
tweets = twitterApi.fetchUserTimeline(2, screenName);
I've also included the relevant code from the signpost-retrofit plugin:
public class SigningOkClient extends OkClient {
private final RetrofitHttpOAuthConsumer mOAuthConsumer;
public SigningOkClient(RetrofitHttpOAuthConsumer consumer) {
mOAuthConsumer = consumer;
}
public SigningOkClient(OkHttpClient client, RetrofitHttpOAuthConsumer consumer) {
super(client);
mOAuthConsumer = consumer;
}
#Override
public Response execute(Request request) throws IOException {
Request requestToSend = request;
try {
HttpRequestAdapter signedAdapter = (HttpRequestAdapter) mOAuthConsumer.sign(request);
requestToSend = (Request) signedAdapter.unwrap();
} catch (OAuthMessageSignerException | OAuthExpectationFailedException | OAuthCommunicationException e) {
// Fail to sign, ignore
e.printStackTrace();
}
return super.execute(requestToSend);
}
}
The signpost-retrofit plugin can be found here: https://github.com/pakerfeldt/signpost-retrofit
public class RetrofitHttpOAuthConsumer extends AbstractOAuthConsumer {
private static final long serialVersionUID = 1L;
public RetrofitHttpOAuthConsumer(String consumerKey, String consumerSecret) {
super(consumerKey, consumerSecret);
}
#Override
protected HttpRequest wrap(Object request) {
if (!(request instanceof retrofit.client.Request)) {
throw new IllegalArgumentException("This consumer expects requests of type " + retrofit.client.Request.class.getCanonicalName());
}
return new HttpRequestAdapter((Request) request);
}
}
Any help here would be great. The solution doesn't have to include the use of signpost but I do want to use Retrofit. I also do not want to show the user an 'Authenticate with Twitter' screen in a WebView - I simply want to display a handful of relevant tweets as part of a detail view.
Are you certain the signpost-retrofit project works for twitter oauth? I've used twitter4j successfully in the past - and if you don't want the full library you can use their code for reference. twitter4j

CXF, out interceptor, alter response SOAP body

Using CXF interceptor, I want to alter the response body which is being sent to the client as response. (I want to add some more nodes)
My interceptor is configured as an outgoing interceptor, is being invoked but the body is empty.
public class AlterOutBodyInterceptor extends AbstractSoapInterceptor {
private SAAJOutInterceptor saajOut = new SAAJOutInterceptor();
public AlterOutBodyInterceptor() {
super(Phase.PRE_MARSHAL);
getBefore().add(SAAJOutInterceptor.class.getName());
}
public void handleMessage(SoapMessage message) throws Fault {
SOAPMessage doc = message.getContent(SOAPMessage.class);
if (doc == null) {
saajOut.handleMessage(message);
doc = message.getContent(SOAPMessage.class);
// it is executed
}
try {
SOAPBody body = doc.getSOAPBody();
// here, body doesn't contain anything that the client gets
} catch (SOAPException e) {
e.printStackTrace();
}
}
}
I am doing trial-error with getBefore - getAfter and Phases, but without luck. Thanks in advance!
The solution is as here:
(we checked cxf sources because it contains a lot of interceptors, we got the ideas from there)
public class Interceptor extends AbstractPhaseInterceptor<Message> {
private ObjectFactory objectFactory = new ObjectFactory();
public Interceptor() {
super(Phase.PRE_LOGICAL);
addBefore(HolderOutInterceptor.class.getName());
}
#Override
public void handleMessage(Message message) {
MessageContentsList outObjects = MessageContentsList.getContentsList(message);
Assert.isTrue(outObjects.size() == 1);
Object outObject = outObjects.get(0);
// object is our soap response
}
}

Java web service : User defined meta-data

I have a SOAP web service implementation on Jboss 4.2.3. I want to add a version number check for the service. Whenever a client makes a call, I will pass the client version number. I will write an interceptor at the server that would check the client version number. If it is a client with a different version number, I would not process the request.
What I want to know is if there is a way to pass the version number from the client in some context parameter other than adding it in the web service method signature?
In general, if I want to pass some custom META-DATA from client to server, how do I do it ?
In general, if I want to pass some custom META-DATA from client to
server, how do I do it ?
This can be achieved through SOAP Message Handlers both side (Client and Server ) in Jax-WS .
Client Side:
The custom-meta-data , like version number, UUID , Signature information can be added via SOAP Headers.
1..Write a VersionNumberHandler as shown below.
public class VersionNumberHandler implements SOAPHandler<SOAPMessageContext> {
private static final String LoggerName = "ClientSideLogger";
private Logger logger;
private final boolean log_p = true; // set to false to turn off
public VersionNumberHandler() {
logger = Logger.getLogger(LoggerName);
}
public boolean handleMessage(SOAPMessageContext ctx) {
if (log_p)
logger.info("handleMessage");
// Is this an outbound message, i.e., a request?
Boolean request_p = (Boolean) ctx
.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
// Manipulate the SOAP only if it's a request
if (request_p) {
// Get the Version Number from some property file ,
// to place in the message header.
String versionNumber = "v1.0";
try {
SOAPMessage msg = ctx.getMessage();
SOAPEnvelope env = msg.getSOAPPart().getEnvelope();
SOAPHeader hdr = env.getHeader();
// Ensure that the SOAP message has a header.
if (hdr == null)
hdr = env.addHeader();
QName qname = new QName("http://ticket.example.com/",
"versionnumber");
SOAPHeaderElement helem = hdr.addHeaderElement(qname);
// In SOAP 1.2, setting the actor is equivalent to
// setting the role.
helem.setActor(SOAPConstants.URI_SOAP_ACTOR_NEXT);
helem.setMustUnderstand(true);
helem.addTextNode(versionNumber);
msg.saveChanges();
// For tracking, write to standard output.
msg.writeTo(System.out);
} catch (SOAPException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
}
}
return true; // continue down the chain
}
public boolean handleFault(SOAPMessageContext ctx) {
if (log_p)
logger.info("handleFault");
try {
ctx.getMessage().writeTo(System.out);
} catch (SOAPException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
}
return true;
}
public Set<QName> getHeaders() {
if (log_p)
logger.info("getHeaders");
return null;
}
public void close(MessageContext messageContext) {
if (log_p)
logger.info("close");
}
2..Mention this class in the Handler-Chain.xml.
<javaee:handler>
<javaee:handler-class>
com.example.client.handler.VersionNumberHandler
</javaee:handler-class>
</javaee:handler>
3..Add the handler-chain in the client (Stub) also.
#WebServiceClient(name = "TicketWSImplService", targetNamespace = "http://ticket.example.com/", wsdlLocation = "http://localhost:8080/ticket?wsdl")
#HandlerChain(file = "handler-chain.xml")
public class TicketWSImplService extends Service {
#WebMethod
public void method(){
}
Here, we are adding a new header element "versionnumber" and mustunderstand=true, which means the server/intermediaries has to process this element, otherwise Jax-WS-Runtime will throw SOAP Fault exception to the client. Now we need to write a Validator(SOAP Handler) at the server side to validate this version number which is being passed by the clients.
Server Side:
1..Write a VersionNumberValidator as shown below.
public class VersionNumberValidator implements SOAPHandler<SOAPMessageContext> {
#SuppressWarnings("unused")
#Override
public boolean handleMessage(SOAPMessageContext ctx) {
// Is this an inbound message, i.e., a request?
Boolean response_p = (Boolean) ctx
.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
// Manipulate the SOAP only if it's incoming.
if (!response_p) {
try {
SOAPMessage msg = ctx.getMessage();
SOAPEnvelope env = msg.getSOAPPart().getEnvelope();
SOAPHeader hdr = env.getHeader();
// Ensure that the SOAP message has a header.
if (hdr == null) {
generateSOAPFault(msg, "No message header.");
return true;
}
Iterator mustUnderstandHeaders = msg.getSOAPHeader()
.examineMustUnderstandHeaderElements(
"http://schemas.xmlsoap.org/soap/actor/next");
String value = null;
while (mustUnderstandHeaders.hasNext()) {
Node next = (Node) mustUnderstandHeaders.next();
System.out.println("mustUnderstandHeaders name:"
+ next.getValue());
if (next.getNodeName().equalsIgnoreCase("versionnumber"))
value = next.getValue();
if (value != null && !value.equalsIgnoreCase("v1.0")) {
generateSOAPFault(msg, "Version Number Mismatch");
}
}
// For tracking, write to standard output.
msg.writeTo(System.out);
} catch (SOAPException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
}
}
return true; // continue down the chain
}
#Override
public boolean handleFault(SOAPMessageContext ctx) {
return true; // do continue down the chain
}
// For now, no-ops.
#Override
public Set<QName> getHeaders() {
Set<QName> headers = new HashSet<QName>();
QName qName = new QName("http://ticket.example.com/", "versionnumber");
headers.add(qName);
return headers;
}
#Override
public void close(MessageContext messageContext) {
}
private void generateSOAPFault(SOAPMessage msg, String reason) {
try {
SOAPBody body = msg.getSOAPBody();
SOAPFault fault = body.addFault();
QName fault_name = new QName(
SOAPConstants.URI_NS_SOAP_1_2_ENVELOPE, "UltimateReceiver");
fault.setFaultCode(fault_name);
fault.setFaultRole("http://ticket.example.com/versionNumber_validator");
fault.addFaultReasonText(reason, Locale.US);
} catch (SOAPException e) {
}
}
2..Mention this class in the Handler-Chain-server.xml.
<javaee:handler>
<javaee:handler-class>
com.example.client.handler.VersionNumberValidator
</javaee:handler-class>
</javaee:handler>
3..Publish the webservices.
Now, the every client request will be having "version number =v1.0", At the server side , you will be validating this value is correct or not. If it is not correct, SOAPFaultException will be thrown.
You could add it to the http-headers but that would mean your client would need to do this which also means they can change it and give you wrong numbers causing issues on the server. It's only as reliable as the messages being sent in.
Either way, this isn't the right way to restrict access to your Web Service, you should use http basic authentication or if it's version differences then you should create multiple version endpoints giving clients access to the versions they need.
Also, JBoss 4.2.3 is so old it might not even work. See [1]
Mus
[1] https://community.jboss.org/message/534711
It's a bad idea to try to add out-of-band metadata to a web service. Just pick a new URL for each version if the data structures are incompatible. If they are compatible, put the version number inside the request.
This way you can still support interoperation with all different libraries and not require your clients to find a new hoop to jump through for each toolkit.

Categories

Resources