GWT RPC response header - gwt

Is there any way to read the header information received by GWT client, on the RPC response?
Response header
Server Apache-Coyote/1.1
Set-Cookie JSESSIONID=3379B1E57BEB2FE227EDC1F57BF550ED; Path=/GWT
Content-Encoding gzip
Content-Disposition attachment
Content-Type application/json;charset=utf-8
Content-Length 209
Date Fri, 05 Nov 2010 13:07:31 GMT
I'm particularly interest in identifying when client receives the Set-Cookie attribute on its header.
Is there any way to do that on GWT?
I found that on
com.google.gwt.user.client.rpc.impl.RequestCallbackAdapter<T>
exist the method
public void onResponseReceived(Request request, Response response) { ... }
On the parameter Response seems to have the information I need. The this is, exist some way to get that without "racking" the GWT compiler code?
thanks
JuDaC

You may try to override the RpcRequestBuilder.doSetCallback method and force your service to use it:
MyServiceAsync service = GWT.create(MyService.clas);
((ServiceDefTarget) service).setRpcRequestBuilder(new RpcRequestBuilder() {
#Override
protected void doSetCallback(RequestBuilder rb, final RequestCallback callback) {
super.doSetCallback(rb, new RequestCallback() {
#Override
public void onResponseReceived(Request request, Response response) {
String headerValue = response.getHeader("my-header");
// do sth...
callback.onResponseReceived(request, response);
}
#Override
public void onError(Request request, Throwable exception) {
callback.onError(request, exception);
}
});
}
});
Inspired by http://stuffthathappens.com/blog/2009/12/22/custom-http-headers-with-gwt-rpc/

If you declare your async service method to return a RequestBuilder you should be able to set a RequestCallback that will be notified when the Response is received. I haven't tried this myself, but it looks like what you need.

Related

Spring Boot WebSockets simple example

I'm trying to create a very basic example of a socket server in Spring Boot.
I have the following classes
WebSocketConfigurer:
#Configuration
#EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
#Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myHandler(), "/path");
}
#Bean
public WebSocketHandler myHandler() {
return new SimpleWebSocketHandler();
}
}
TextWebSocketHandler:
public class SimpleWebSocketHandler extends TextWebSocketHandler {
private static Logger logger = LoggerFactory.getLogger(SimpleWebSocketHandler.class);
#Override
public void afterConnectionEstablished(WebSocketSession session) {
logger.debug("Opened new session in instance " + this);
}
#Override
public void handleTextMessage(WebSocketSession session, TextMessage message)
throws Exception {
String echoMessage = message.getPayload();
logger.debug(echoMessage);
}
#Override
public void handleTransportError(WebSocketSession session, Throwable exception)
throws Exception {
session.close(CloseStatus.SERVER_ERROR);
}
}
Application:
#SpringBootApplication
public class WebSocketServerApplication {
public static void main(String[] args) {
SpringApplication.run(WebSocketServerApplication.class, args);
}
}
Then I have a C program that will open a socket and send simple text to a server.
When I try to send just plain text (e.g. “Hello”) over the socket, I get the following error message back to the client:
HTTP/1.1 400 Bad Request
Server: Apache-Coyote/1.1
Transfer-Encoding: chunked
Date: Tue, 18 Aug 2015 09:22:05 GMT
Connection: close
And the server displays a “Error parsing HTTP request header” message. I assume that is to be expected as the server is running in an embedded tomcat server and is only configured for HTTP.
When I then try to send a HTTP POST message as text from the C application e.g.
POST /path HTTP/1.0\r\n Content-Type: text/plain\r\n Content-Length: 5\r\n \r\n Hello
I get nothing on the server side and the connection on the client eventually just times out.
I’m missing something obvious?
Do I need to specify a controller class? Is that not covered when I register the web socket handler at a path?

trying to send httpRequest from server side in GWT

I am trying to make http request to server from my GWT Application
Below is the code i am using which works fine from Client Side ..
But I want to do this from Server side ..
If I can get some solution for that
String url = "http://www.myserver.com/getData?type=3";
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
try {
Request request = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
// Couldn't connect to server (could be timeout, SOP violation, etc.)
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
// Process the response in response.getText()
} else {
// Handle the error. Can get the status text from response.getStatusText()
}
}
});
} catch (RequestException e) {
// Couldn't connect to server
}
Reference: www.gwtproject.org/doc/latest/DevGuideServerCommunication.html
com.google.gwt.http.client.RequestBuilder is meant to be used on the GWT client side.
For your server side code to make HTTP requests, I recommend using the Apache HttpClient library.

GWT RequestBuilder Post Response return 0 StatusCode

I have created a very simple servlet that uses HTTP Post method. I have tested it on my local Apache Tomcat server using a simple HTML form that works. I want to integrate it with my GWT app. I am able to call it using FormPanel - in that case it downloads content and there is a flicker in my browser window.
I know I need to use RequestBuilder to access it. But my response.getStatusCode() in my overloaded public void onResponseReceived(Request request, Response response) method always return status as 0 and response.getText() return null
String url = "http://localhost:8080/servlets/servlet/ShapeColor";
builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url));
try {
String json = getJSONString();
//builder.setTimeoutMillis(10000);
builder.setHeader("Access-Control-Allow-Origin", "*");
builder.setHeader("Content-type", "application/x-www-form-urlencoded");
builder.sendRequest(json, new RequestCallback() {
#Override
public void onError(Request request, Throwable exception) {
Window.alert("Couldn't retrieve JSON");
}
#Override
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
System.out.println("res:"+response.getText());
} else {
System.out.println("err: " + response.getStatusCode()+","+response.getText());
}
}
});
//Request response = builder.send();
} catch (RequestException e) {
// TODO Auto-generated catch block
}
I have tried many thing including changing my servlet following CORS reference ( https://code.google.com/p/gwtquery/wiki/Ajax#CORS_%28Cross_Origin_Resource_Sharing%29 )
It always works on browser using my test.html, but not from my App. Although, onResponseReceived method always gets called
Thanks
KKM
Have you checked if your call in the app violates the Same-origin policy (http://en.wikipedia.org/wiki/Same-origin_policy) in some way? The GWT RequestBuilder uses XMLHttpRequest internally, so it does fall under the SOP.
Does your GWT app run inside the same domain (server + port) as the servlet? Does it use the same protocol (https or http)?

Origin http://127.0.0.1:8888 is not allowed by Access-Control-Allow-Origin

I got this problem while trying to access REST web service using GWT client.
I inspect the chrome page then i got the following error from console
XMLHttpRequest cannot load http://localhost:8080/RestWeb/webresources/generic/get. Origin http://127.0.0.1:8888 is not allowed by Access-Control-Allow-Origin.
Following is my client side code
public void onModuleLoad() {
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET,
"http://localhost:8080/RestWeb/webresources/generic/get");
builder.setCallback(new RequestCallback() {
#Override
public void onResponseReceived(Request request, Response response) {
Window.alert("onResponseReceived");
}
#Override
public void onError(Request request, Throwable exception) {
}
});
builder.setHeader("Content-Type",
"text/plain,application/json,text/xml");
builder.setHeader("Access-Control-Allow-Methods",
"PUT, GET, POST, DELETE, OPTIONS");
builder.setHeader("Access-Control-Allow-Headers", "Content-Type");
builder.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8888");
try {
builder.send();
} catch (RequestException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
My server side code is :
#Path("generic")
#WebService
public class GenericResource {
#Context
private UriInfo context;
#Context
private HttpServletResponse response;
private String content = "content";
/**
* Creates a new instance of GenericResource
*/
public GenericResource() {
}
#GET
#Path("/get")
#Produces("application/json,text/plain")
public String getXml() {
System.out.println("GET");
//response.addHeader(content, content);
return this.content + " from get method";
}
}
I tried in different ways to get answer. Please help me.
You need to change your server code to support CORS.
One option is a filter:
public class CorsFilter extends OncePerRequestFilter {
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
// CORS "pre-flight" request
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
response.addHeader("Access-Control-Allow-Headers", "Content-Type");
response.addHeader("Access-Control-Max-Age", "1800");//30 min
}
filterChain.doFilter(request, response);
}
}
The web.xml needs adding the following too:
<filter>
<filter-name>cors</filter-name>
<filter-class>com.xxx.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Since it's an old question, if one is facing similar issues today - he or she may want to consider using a nice "CORS Filter" that handles all CORS stuff for you in a completely transparent way. Here's the link

GWT - spring security - session timeout

I have a GWT + Spring Security web app. I was trying to add:
<security:session-management invalid-session-url="/X.html"/>
However, when I try to test this. It seems I see a:
com.google.gwt.user.client.rpc.InvocationException
with message as the HTML content of X.html. Can someone please advise on how to fix this?
Because GWT communicates with a server via Ajax RPC requests, the browser will not be redirected to X.html. What you need to do in your service calls is throw an exception if they are not authorized and handle in in void onFailure(Throwable caught) method of your AsyncCallback.
If you want to redirect to /X.html try:
Window.Location.replace(GWT.getHostPageBaseURL()+"X.html");
However, if you want to send the request to the server use RequestBuilder:
String url = GWT.getHostPageBaseURL() + "/X.html";
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
try {
Request request = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
// invalid request
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
// success
} else {
// sth went wrong
}
}
});
} catch (RequestException e) {
// couldn't connect to server
}