Calling SOAP web service from GWT client - java

I don't have any experience working with SOAP so please help me.
i have web project with GWT on the client side. as for the information needed for this site, i have to call/access SOAP web service. i've read some forums that i should use RequestBuilder in order to do so. i have the following code:
RequestBuilder builder = new RequestBuilder( RequestBuilder.POST, URL.encode( url ) );
try {
builder.sendRequest( null, new RequestCallback() {
public void onResponseReceived( Request request, Response response) {
if (200 == response.getStatusCode()) {
// processing response here
} else {
// Handle the error
}
}
public void onError(Request request, Throwable exception) {
// error
}
});
} catch (RequestException e) {
// Couldn't connect to server
}
This code causes an error and return status code 0. I think it's the SOP(Same-Origin-Policy) again.
Is there any other way I can do to access SOAP web service in GWT?
E D I T
In this project, a .wsdl file, which is located from an existing domain,
http://sample.com/server/soap/soap.wsdl
is already provided. And I also have this:
http://sample.com/server/soap/soapserver.php
How does it help me to connect to the SOAP web service?
I have created a SOAP Client in java but i encountered an error on javax.xml.* about inheriting the required modules.

If you're trying to access SOAP service from another domain then you're probably limited by SOP. I'd suggest building a thin server-side layer that will actually talk to the SOAP service. To talk to your GWT server-side you can use, for example, DispatchAsync or RequestFactory.

Related

How to use non-blocking HTTP requests in Mulesoft 4 Custom Connector

I'm trying to build a Mulesoft custom connector which makes HTTP requests to a third-party system, and I'd like these HTTP requests to be made in a non-blocking manner such that execution can continue without waiting on the HTTP response to be returned.
There is an example of this in the Mulesoft documentation here which shows this example code:
public void request(String url, #Connection HttpClient client, #Content String body,
CompletionCallback<InputStream, HttpAttributes> callback ) {
client.send(url, body, new HttpResponseCallback() {
void onResponse(HttpResponse response) {
callback.success(Result.<InputStream, HttpAttributes>builder()
.output(response.getBody())
.attributes(toAttributes(response))
.build());
}
void onError(Exception e) {
callback.error(e);
}
});
}
It also states that non-blocking behaviour can be provided
by an HttpClient that supports asynchronous responses
Mulesoft's custom connector documentation states
The HttpClient is capable of using non-blocking I/O to make the requests.
but I don't understand how!
The example code above calls a method send(String, String, HttpResponseCallback) from the HttpClient interface. However, the HttpClient interface, as documented in Mulesoft's API javadoc does not have such a method.
I see that the HttpClient interface does have sendAsync(HttpRequest request) methods, but I'm failing to understand how that could be used with the example code.
I understand that Mulesoft's HttpClient is implemented using Project Grizzly's HTTP client, and that supports non-blocking requests, so I feel this is possible to do, I just don't understand how...
Thanks for any tips!
Hi was trying to achieve the same thing, with the same non-blocking-operations documentation, but I wasn't able, So I try based on the
Slack connector, it has a lot of examples there, and they use other code to achieve async calls ChannelOperations with CompletionCallback
However, this did not work for me, I think maybe I have to make another workaround on the server-side to achieve async calls.
Anyway, In the end, I use CompletableFuture to run the request in other thread,
the request is in sync way but is performed Async in the CompletableFuture.runAsync
public void request(String url, #Connection HttpClient client, #Content String body) {
HttpResponse response = null;
HttpEntity entity = new ByteArrayHttpEntity(body.toString().getBytes());
HttpRequest httpRequest = HttpRequest.builder().uri(url).addHeader("Content-Type", "application/json")
.method("POST").entity(entity).build();
CompletableFuture.runAsync(() -> {
try {
client.start();
response = client.send(httpRequest, 30000, true, null);
} catch (IOException | TimeoutException e) {
LOGGER.error(response.toString());
}
LOGGER.info(response.toString());
client.stop();
LOGGER.info("Finish");
});
}
There is a Mule connector similar to DMI where the calls are made async

How can you consume a distant rest api using gwt?

I have a couple of sipring boot restfull APIs, that I want to communicate with, from a GWT based front-end. I've looked a bit on the Internet and found the RestyGWT framework, but as far as I've seen, all the documentation available is for using the embeded GWT server as a restfull API.
Can anyone please direct me to a usefull tutorial that I can follow.
Thanks to all.
I actually found a way to GET data through JsonPRequestBuilder, the problem now resides in POSTing data in json format.
final RequestBuilder reqBuilder = new RequestBuilder(httpMethod, url);
final Request request = reqBuilder.sendRequest(requestData, new RequestCallback()
{
#Override
public void onResponseReceived(Request request, Response response)
{
GWT.log(response.getText());
}
#Override
public void onError(Request request, Throwable exception)
{
}
}
httpMethod is something from com.google.gwt.http.client.Method like Method.GET
request is a String in which you pass the json.
response.getText will display the json.
To convert from object to json I would suggest to look at https://github.com/nmorel/gwt-jackson or https://github.com/vegegoku/gwt-jackson-apt (first one is older and has more features, second one is newer and better suited for future (GWT 3.0) but maybe has some features missing).

Configure Response object for Rest Services inside a Jersey-Grizzly server, in OSGi container (CORS error prevention with Jersey 1x)

The last couple of days, I have been struggling with an issue. I've created a rest service hosted by a Grizzly server inside an OSGi container. Everything is working perfectly at this point.
Now, I want to add a header in every response.Not so complex or illogical right? Yet, I can't find a way to do it.
I have tried to:
1) Get the response object inside the rest functions as this question suggests (pretty textbook when you are not under OSGi).
2) Add a handler using the code above (in this case the service method is never called)
server.getServerConfiguration().addHttpHandler(
new HttpHandler() {
#Override
public void service(Request arg0, Response arg1)
throws Exception {
arg1.setHeader("Access-Control-Allow-Origin", "*");
}
});
I am using jersey-server/client/core 1.18.1 and grizzly2-server 1.18.1, hence i prefer a solution that can be applied in this version, but I am willing to update jar versions if it cannot be done in 1.18.x.
You could give a try to Jersey filters.
In a nutshell, you should create class implementing ContainerResponseFilter:
public class MyFilter implements ContainerResponseFilter {
#Override
public void filter(
ContainerRequest request,
ContainerResponse response
) throws IOException {
request.getHttpHeaders().add(<header name>, <header value>);
}
}
Then, you should register this filter in your Jersey server configuration.
Please, note, that this filter would be invoked on every response. To bind it only to specific resources, you could use annotation-binding, that is described here.
All other information you could find here.

What is the best way to unit test REST Endpoints (Jersey)

I have a REST controller that has multiple GET/POST/PUT methods that all respond/request JSON.
I am not using Spring in this application (yet).
I was looking into the REST-assured framework and I like how that looks but I can only use it when my web server is up and running.
Is there a way for me to run a in-memory web server, or something like that?
Are there any examples of REST endpoint testing that someone can provide?
If you are using JAX-RS 2.0 you should find your answer here
You can take a look at the example also
An integration test example, could be:
public class CustomerRestServiceIT {
#Test
public void shouldCheckURIs() throws IOException {
URI uri = UriBuilder.fromUri("http://localhost/").port(8282).build();
// Create an HTTP server listening at port 8282
HttpServer server = HttpServer.create(new InetSocketAddress(uri.getPort()), 0);
// Create a handler wrapping the JAX-RS application
HttpHandler handler = RuntimeDelegate.getInstance().createEndpoint(new ApplicationConfig(), HttpHandler.class);
// Map JAX-RS handler to the server root
server.createContext(uri.getPath(), handler);
// Start the server
server.start();
Client client = ClientFactory.newClient();
// Valid URIs
assertEquals(200, client.target("http://localhost:8282/customer/agoncal").request().get().getStatus());
assertEquals(200, client.target("http://localhost:8282/customer/1234").request().get().getStatus());
assertEquals(200, client.target("http://localhost:8282/customer?zip=75012").request().get().getStatus());
assertEquals(200, client.target("http://localhost:8282/customer/search;firstname=John;surname=Smith").request().get().getStatus());
// Invalid URIs
assertEquals(404, client.target("http://localhost:8282/customer/AGONCAL").request().get().getStatus());
assertEquals(404, client.target("http://localhost:8282/customer/dummy/1234").request().get().getStatus());
// Stop HTTP server
server.stop(0);
}
}

CXF Custom Validation Interceptor with custom response not working

I am trying to write a Custom CXF Interceptor to do some validations on SOAP request to a web service. Based on the validation results, I want to block the request to web service and return the response with some modified parameters.
For this, I have written custom CXF ininterceptor extending from AbstractPhaseInterceptor, to run in phase USER_LOGICAL, which does validations, but I am not able to stop the subsequent call to web service and also not able to pass the Custom Response object(Custom Response object type is same as web service return type). How can I do this using interceptors?
I did some research upon the tip from nadirsaghar and I found it to be the cleanes solution available. Using message.getExchange() in JAX-WS is a complete pain, since you have to setup a conduit and fill the response message yourself...
So better do it this way, using HttpServletResponse. - You need to have the java servlet-api.jar on your Path. If you're developing without maven, just link it from your webserver (e.g. tomcat) directory, but exlude it from deployment.
<!-- With Maven add the following dependency -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<!-- The version should match your WebService version e.g. 3.0 for JDK7-->
<version>2.5</version>
<scope>provided</scope>
</dependency>
With scope provided it will not be deployed and is just available so you can access the HttpServletResponse class.
Your Handler Code:
#Override
public void handleMessage( final Message message ) throws Fault
{
if( shouldBlockMessage( message ) )
{
message.getInterceptorChain().abort();
final HttpServletResponse response = (HttpServletResponse)message.get( AbstractHTTPDestination.HTTP_RESPONSE );
// To redirect a user to a different Page
response.setStatus( HttpServletResponse.SC_MOVED_TEMPORARILY );
response.setHeader( "Location", "http://www.bla.blubb/redirectPage" );
// Other possibility if a User provides faulty login data
response.setStatus( HttpServletResponse.SC_FORBIDDEN );
}
}
You can abort execution of the interceptorChain including the webservice using abort method
public void handleMessage(SoapMessage message) {
InterceptorChain chain = message.getInterceptorChain();
chain.abort();
}
Something like this, there is no need to play with Interceptor chain.
public void handleMessage(Message message) {
//your logic
Response response = Response.status(Status.UNAUTHORIZED).type(MediaType.APPLICATION_JSON).build();
message.getExchange().put(Response.class, response);
}

Categories

Resources