GWT JsonpRequestBuilder Timeout issue - json

I am getting time out from using JsonpRequestBuilder.
The entry point code goes like this:
// private static final String SERVER_URL = "http://localhost:8094/data/view/";
private static final String SERVER_URL = "http://www.google.com/calendar/feeds/developer-calendar#google.com/public/full?alt=json-in-script&callback=insertAgenda&orderby=starttime&max-results=15&singleevents=true&sortorder=ascending&futureevents=true";
private static final String SERVER_ERROR = "An error occurred while "
+ "attempting to contact the server. Please check your network "
+ "connection and try again.";
/**
* This is the entry point method.
*/
public void onModuleLoad() {
JsonpRequestBuilder requestBuilder = new JsonpRequestBuilder();
// requestBuilder.setTimeout(10000);
requestBuilder.requestObject(SERVER_URL, new Jazz10RequestCallback());
}
class Jazz10RequestCallback implements AsyncCallback<Article> {
#Override
public void onFailure(Throwable caught) {
Window.alert("Failed to send the message: " + caught.getMessage());
}
#Override
public void onSuccess(Article result) {
// TODO Auto-generated method stub
Window.alert(result.toString());
}
The article class is simply:
import com.google.gwt.core.client.JavaScriptObject;
public class Article extends JavaScriptObject {
protected Article() {};
}
The gwt page, however, always hit the onFailure() callback and show this alert:
Failed to send the message. Timeout while calling <url>.
Fail to see anything on the Eclipse plugin console. I tried the url and it works perfectly.
Would appreciate any tip on debugging technique or suggestion

Maybe you should set the callback function explicitly via setCallbackParam, since you have callback=insertAgenda in your url - I presume that informs the server what should be the name of the callback function that wraps the JSON.
Also, it's worth checking Firebug's console (or a similar tool for your browser) - even if GWT doesn't report any exceptions, Firebug still might.
PS: It's useful to use a tool like Firebug to see if the application does in fact receive the response from the server (that would mean that, for example, you do need the setCallbackParam call) or maybe there's something wrong on the server side (for whatever reason).

You have to read the callback request-Parameter (default callback, value something like __gwt_jsonp__.P0.onSuccess) on serversite and have to modify the output to
<callback>(<json>);
In this case:
__gwt_jsonp__.P0.onSuccess(<json>);

Both of these guys are absolutely correct, but here is a concrete example to help you understand exactly what they are referring too.
This is a public JSON api. Take a look at the results:
http://ws.geonames.org/postalCodeLookupJSON?postalcode=M1&country=GB&maxRows=4
This public API supports JSONP through the predefined parameter 'callback'. Basically whatever value you pass into callback, will be used as the function name to wrap around the JSON data you desire. Take a look at the results of these few requests:
http://ws.geonames.org/postalCodeLookupJSON?postalcode=M1&country=GB&maxRows=4&callback=totallyMadeUp
http://ws.geonames.org/postalCodeLookupJSON?postalcode=M1&country=GB&maxRows=4&callback=trollingWithJSONP

It could be happening because of another reason, that the webservice call is returning a JSON object and but the callback is expecting JSONP object (note there is a difference).
So if you are dealing with google maps api, and you are seeing this exception, you need to change it to api provide by maps api, something like
final GeocoderRequest request = GeocoderRequest.create();
request.setAddress(query);
try {
GWT.log("sending GeoCoderRequest");
if (m_geocoder == null) {
m_geocoder = Geocoder.create();
}
m_geocoder.geocode(request, new Geocoder.Callback() {
#Override
public void handle(final JsArray<GeocoderResult> results,
final GeocoderStatus status) {
handleSuccess(results, status);
}
});
} catch (final Exception ex) {
GWT.log("GeoCoder", ex);
}
Or else you could use RequestBuilder as in gwt library.

Related

Get json content of request and response on annotated Spring Controller

I want to build a library that will save the Json content of request and response on annotated Spring controller.
So i've build my own annotation #Foo and put it on some controllers:
#Foo
#RequestMapping(method = RequestMethod.POST, value = "/doSomeThing", produces = {
MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_XML_VALUE,
MediaType.APPLICATION_XML_VALUE})
public ResponseEntity<T> doSomething(/*some parameters*/) {
T t = doSomeJob(T.class);
return new ResponseEntity<T>(t, HttpStatus.OK);
}
I have no guarantee that request and response are in Contrellor's parameters!
And i'm catching the call on any Controller having that annotation within an #AfterReturning AOP pointcut.
#Component
#Aspect
public class XYInterceptor
#AfterReturning(
pointcut = "execution(#my.annotation.Foo)")
public void doSomethingWithJsonContent(JoinPoint joinPoint) throws Throwable {
//How can i get json value of request and response here?
}
How can I get request and response content formatted in json (such as it is send/returned to the client) ?
Thanx for your help!
Well, you need request and response somehow accessible from your controller method, either via an injected class member, method parameter or method return value. It has got to be somewhere. Because you did not explain where you intend to get it from, I can just post a general answer showing how to determine method arguments and return value from an #AfterReturning advice. If you update the question with more detailed information, I can also update the answer accordingly.
My pointcut (the commented-out one also works, choose your favourite one) binds the return value to a parameter and just assumes that both request and response are of String type. Feel free to replace by your favourite. Furthermore, you can bind a parameter from your intercepted method (no matter where it is in the signature) to a typed advice method parameter if you know that the parameter exists and also know its (super) type. This way you can get rid of the slow and ugly loop over getArgs().
//#AfterReturning(pointcut = "execution(#my.annotation.Foo * *(..))", returning = "response")
#AfterReturning(pointcut = "#annotation(my.annotation.Foo)", returning = "response")
public void interceptRequest(String response, JoinPoint thisJoinPoint) {
System.out.println(thisJoinPoint);
for (Object arg : thisJoinPoint.getArgs()) {
if (arg instanceof String)
System.out.println(" request = " + arg);
}
System.out.println(" response = " + response);
}

How to show custom error page in ServiceStack

I have read through Error Handling, ServiceStack_Succinctly.pdf, ServiceStack 4 Cookbook and various SO questions and am still unable to get the following working.
I want a way to show my own "pretty" error page for any exception that is thrown in any of my services. If any exception is thrown I want to take the user to a friendly page that shows the error message without any information that "mere mortals" won't understand.
Ideally I want this while maintaining typed responses on my service requests, i.e. not
public object Get(GetOrder request)
{
return new GetOrderResponse()
{
...
}
}
but rather
public GetOrderResponse Get(GetOrder request)
{
return new GetOrderResponse()
{
...
}
}
I'd appreciate guidance on how to get this working or an example where this is done.
Thanks.
Have a look at the options for Fallback Error Pages e.g. you can display an /oops.cshtml Razor page with:
public override void Configure(Container container)
{
Plugins.Add(new RazorFormat()); //Register ServiceStack.Razor Plugin
this.GlobalHtmlErrorHttpHandler = new RazorHandler("/oops"),
}
Or for more fine-grained control, use IAppHost.CustomHttpHandlers for specifying custom HttpHandlers to use with specific error status codes, e.g.:
public override void Configure(Container container)
{
this.CustomHttpHandlers[HttpStatusCode.NotFound] =
new RazorHandler("/notfound");
this.CustomHttpHandlers[HttpStatusCode.Unauthorized] =
new RazorHandler("/login");
}

WebSocketServlet: Send message to particular connection

I am trying implement a Websocket connection taking an example from here - https://gist.github.com/chitan/3063774.
This is a echo server.
My question is -
How can i take a message from a particular user and send it to another user instead of echoing to the same user.
I have searched a lot and most of the examples i have found are Echo examples.
In Java EE7, you can do that easily. Think about an simple example. If you write client.getBasicRemote().sendObject(message); in a method with #OnMessage annotation than it will be available only active client session.
#ServerEndpoint("/websocket")
public class ChatEndpoint {
#OnMessage
public void message(String message, Session client) throws IOException, EncodeException {
client.getBasicRemote().sendObject(message);
}
}
if you loop the message on client.getOpenSessions() then it will be available to all clients:
#OnMessage
public void message(String message, Session client) throws IOException, EncodeException {
for (Session peer : client.getOpenSessions()) {
peer.getBasicRemote().sendObject(message);
}
}
For details, go to this tutorial.
If you still need to use Java 6 and WebSocketServlet you can do something like this:
public class WsChatServlet extends WebSocketServlet{
public StreamInbound createWebSocketInbound(String protocol){
MyMessageInbound ms = new MyMessageInbound();
// store ms somewhere and than find it and use getWsOutbound() to respond
return ms;
}
...
}

Call a Rest method with mockito

I use Jersey and I have the following Rest function which returns a JSON string when my server is deployed:
#GET
#Path("getallemployees")
#Produces("application/json")
public Response getAllEmployees() {
//building the entity object which is List<Employee>
return Response.ok(entity).build();
}
I need to develop some unit tests (not integration testing) and I want to somehow mock the HTTPRequest that invokes this method and then get the json String. The best option would be to use mockito for this.
Is there any suggestion on how to do it ?
Thanks !!
The problem is that the method returns a Response object to the caller which is deep within the framework code. It doesn't return JSON strings.
You can use Mockito, if you need to mock something inside the method itself. That should work.
But you may need to take the value returned by the method and convert it to JSON like this if you are using Jackson with Jersey.
Response response = getAllEmployees();
Object retval = response.getEntity();
try {
ObjectMapper mapper = new ObjectMapper();
// I like this formatting. You can change it.
mapper.configure(Feature.INDENT_OUTPUT, true);
mapper.configure(Feature.WRITE_ENUMS_USING_TO_STRING, true);
mapper.configure(Feature.USE_ANNOTATIONS, false);
mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false);
mapper.setSerializationInclusion(Inclusion.NON_NULL);
mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
mapper.getSerializationConfig().withSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
String json = mapper.writeValueAsString(retval);
... assert something about the string
} catch (JsonProcessingException e) {
// do something
} catch (IOException e) {
// do something
}
Some of this is guess work and speculation on my part but it may help. You could try using the Jersey Test Framework with the InMemoryTestContainerFactory:
It starts Jersey application and directly calls internal APIs to handle request created by client provided by test framework. There is no network communication involved. This containers does not support servlet and other container dependent features, but it is a perfect choice for simple unit tests.
It looks like to use it, all you need to do is extend JerseyTest and then override getTestContainerFactory() and follow the rest of the instructions, e.g.:
public class EmployeeResourceTest extends JerseyTest {
#Override
protected Application configure() {
// set up employee resource with mock dependencies etc...
return new ResourceConfig().registerInstances(employeeResource);
}
#Test
public void getAllEmployees() {
final String response = target("getallemployees").request().get(String.class);
// assert etc...
}
}
I used registerInstances instead of registerClasses in configure() as it looks like you can present a ready made Resource but set up with any mock dependencies you may want - although I haven't tried this myself.
The test class is a bit inflexible as you can only do one-time set up of dependencies in the configure() method, so it might be worth investigating using the MockitoJUnitRunner - although I'm not sure if it will work with the JerseyTest inheritance. It could allow you to do add behaviour to mocks in each #Test method, e.g.:
#Mock
private EmployeeResourceDependency dependency;
#InjectMocks
private EmployeeResource employeeResource;
// configure() as above but without mock setup up etc...
#Test
public void getAllEmployees() {
given(dependency.getEmployees()).willReturn(...);
// etc...
But like I said it might not be possible to mix them at all.

Exception handling with WCF Data Services

I want to customize exceptions/errors thrown from my WCF Data Service, so clients get as much as possible information about what exactly went wrong/what is missing. Any thoughts on how this could be achieved?
There are a few things you need to do to ensure exceptions bubble over HTTP pipe to the client .
You must attribute your DataService class with the following:
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class MyDataService : DataService
You must enable verbose errors in the configuration:
public static void InitializeService(DataServiceConfiguration config)
{
config.UseVerboseErrors = true;
}
It is best to throw DataServiceException within. The WCF Data Service runtime knows how to map the properties to the HTTP response and will always wrap it in a TargetInvocationException.
[WebGet]
public Entity OperationName(string id)
{
try
{
//validate param
Guid entityId;
if (!Guid.TryParse(id, out entityId))
throw new ArgumentException("Unable to parse to type Guid", "id");
//operation code
}
catch (ArgumentException ex)
{
throw new DataServiceException(400, "Code", ex.Message, string.Empty, ex);
}
}
You can then unpack this for the client consumer by overriding the HandleException in your DataService like so:
/// <summary>
/// Unpack exceptions to the consumer
/// </summary>
/// <param name="args"></param>
protected override void HandleException(HandleExceptionArgs args)
{
if ((args.Exception is TargetInvocationException) && args.Exception.InnerException != null)
{
if (args.Exception.InnerException is DataServiceException)
args.Exception = args.Exception.InnerException as DataServiceException;
else
args.Exception = new DataServiceException(400, args.Exception.InnerException.Message);
}
}
See here for more info...
You can decorate your service class with this attribute ServiceBehaviorAttribute like so :
[ServiceBehavior(IncludeExceptionDetailInFaults=true)]
public class PricingDataService : DataService<ObjectContext>, IDisposable
{
...
}
You need to create custom exceptions for this.
Please read this post here: Why Create Custom Exceptions?
Which language are you developing in?
If you need further guidance, please add some comments.
I don't think he wants to know how to throw / catch exceptions in .NET.
He probably want to get thoughts on how to tell the clients consuming a WCF Data Service that something (and what) went wrong when an exception is being thrown / caught at the server(service) side.
WCF Data Services uses HTTP request / response messages and you can't just throw an exception from the service to the client.