GWT Async to URL - gwt

I'm using GWT to develop a web app. I'm currently using AJAX calls to retrieve values from the server. I have following queries regarding to AJAX calls:
Assume: I have an app, name of which is: "Application" and the entry point class is: "entry.java"
I know: the application could be invoked as: http://localhost:8080/Application/entry.html
1. I would like to know what what is the output URL given by gwt.getmodulebaseURL()?
Assume: In the same application I have a service called "ServerValuesService" and its corresponding Async. I have corresponding serviceImpl, which has a method called List < String >search(String) at the server side.
I could retrieve the values from the server as well. However,
2. I would like to know what would be the direct URL to access this service? For Instance, I need to obtain the list of values, by just giving a URL (passing value for the String). i.e. I need to access the method search(String) and retrieve the list just by typing a url such as:
http://localhost:8080/Application/entry/serverValuesService?string="hello"
I'm sure the above URL is wrong. I need to know exact conversion between URL and the corresponding service. Is this possible at all?
Thanks in advance!

1) In your case it will give you http://localhost:8080/Application . Application is your modulename.
2) These services are actually HttpServlets and their URL's are defined in the web.xml file. But Google uses POST method to send your variables and takes care of serialization for you, what you are trying to do is send it via GET method which is as far as I know not implemented by Google RemoteServiceServlet.So I would say no its not possible unless you extend these services to work with GET methods yourself but I don't know if that is possible.

Assume: I have an app, name of which is: "Application" and the entry point class is: "entry.java"
I know: the application could be invoked as: http://localhost:8080/Application/entry.html
The url http://localhost:8080/Application/entry.html is called host page url. In this html page you load your GWT module using a script tag:
<!-- This script tag is what actually loads the GWT module. The -->
<!-- 'nocache.js' file (also called a "selection script") is -->
<!-- produced by the GWT compiler in the module output directory -->
<!-- or generated automatically in hosted mode. -->
<script language="javascript" src="calendar/calendar.nocache.js"></script>
So if you put above example in your entry.html, the module will be loaded from http://localhost:8080/Application/calendar/calendar.nocache.js making http://localhost:8080/Application/calendar/ your module base url.
I would like to know what would be the direct URL to access this
service? For Instance, I need to obtain the list of values, by just
giving a URL (passing value for the String). i.e. I need to access the
method search(String) and retrieve the list just by typing a url
GWT RPC use a custom serialization format to encode requests to the RPC Service on server. The RPC service is implemented as a subclass of RemoteServiceServlet on the server. The RemoteServiceServlet handles the http POST requests, de-serializing the request from client and invvoking appropriate service method of sub-class.
So for directly accessing the service you'll need:
1. The service URL
2. Request payload encoded in GWT's custom serialization format
3. Ability to HTTP POST the payload to the Service URL
1 and 3 are easy to acquire. You already know the URL at which your service is mapped in web.xml. And you can do post from any http client or browser plugins like this. The hard-part would be to generate request payload in GWT's custom serialization format. For simple cases, you can generate a request from your application and capture the raw payload from Firebug, Fiddler or similar tool and simply replay it using your http client.

Related

Restygwt download byte[]

I have only an array of byte on the client side.
Another server send me JSON
{
report - byte[]
}
I am looking for ways to save byte [] in browser
Send them to server or I can download from client side.
I can not find any solution at all.
So my question "Is it possible to save with restygwt byte [] an how???"
It is not possible to save the file directly from Resty.
https://github.com/resty-gwt/resty-gwt/issues/341
The most common workarounds to download files using AJAX are not using AJAX at all.
You can simply change the URL (using window.location) or (using javascript) create or;
create a form (using JS) and post that form.
In my projects, I simple create a URL to my REST endpoint attaching any query parameters needed and use it as the href to a link.
For instance, if your RestyGwt endpoint points to /entity/1/bytes
just do
new Anchor("Download", "/entity/1/bytes");
your endpoint must produce a downloadable file type say:
#Produces("text/txt")

How to enable/disable HTTP methods for RESTful Web service?

I'm writing a RESTful Web service.
Technologies that I use:
Eclipse EE Kepler IDE
GlassFish 3 (based on Java 6)
Jersey
JDK v7
When I annotate a Java method with, for example, the #DELETE annotation
I get the following HTTP error (invoked via URI):
HTTP Status 405 - Method Not Allowed
I would like to know how to enable/disable (so that to enable/disable the above HTTP error) those methods (PUT, HEAD, etc.) and at which level it can be done (Glassfish, Web.xml, etc). As well, can you invoke all of those resource methods (annotated with HTTP method type) from either Web browser's URI, within the <form>, or stand-alone client application (non-browser)?
For example, whether or not the following config line on deployment descriptor is present, it makes no difference:
<security-constraint>
<web-resource-collection>
<web-resource-name>RESTfulServiceDrill</web-resource-name>
<url-pattern>/drill/rest/resource/*</url-pattern>
<http-method>DELETE</http-method>
</web-resource-collection>
Of course, one's can disable a specific resource method by throwing an exception from it (and map it to an HTTP error) as the indication of it. That would indicate that the implementation is not available, for example.
So far, only #GET and #POST (on the <form>) resource methods work out, the other annotated methods, such as #POST (via URI), #PUT, #DELETE, #OPTIONS returns the above HTTP error. And this is where my question needs solutions. Why does the mentioned resource methods cause HTTP error when the former two don't?
An example of a resource method:
#DELETE
#Consumes(MediaType.TEXT_PLAIN)
#Produces(MediaType.TEXT_PLAIN)
#Path("/getDelete/{value}/{cat}")
public String getDelete(#PathParam("value") String value, #PathParam("cat") String cat){
return value+" : "+cat;
}
Invoking URL:
getDelete
The deployment descriptor is empty, except for the above lines of XML code. So far, I made the app to work by using annotations, no Web.xml (only contains some default values, such as index.jsp files).
Any ideas out there?
To my understanding, You have your REST APIs exposed and you are trying to access it from HTML <form>.Now you are able to access the GET and POST methods(REST APIs) from HTML <form> but not PUT, DELETE and other HTTP methods.
The reason why you get Method Not Allowed exception when you try to access DELETE or PUT or other HTTP methods is, HTML <form> does not support methods other than GET and POST.
Even if you try
<form method="delete"> or <form method="put">
HTML will not understand these methods and consider this as simply <form> (i.e) default form method is GET.
So even you have mentioned method as DELETE or PUT. It is a GET request.
And when the call is made, the jersey container tries to find the requestpath(here"/getDelete/{value}/{cat}") with the specified method(here GET).
Though this path exists,you have mentioned DELETE as acceptable method in your resource(#DELETE annotation says so). But Jersey is looking for GET now.Since it cant find #GET, it returns Method not allowed Exception.
So, how to solve it?
In HTML <form> you cant use HTTP methods other than GET and POST. It is better to have a wrapper in between the REST layer and HTML. So that you can make a POST call from your HTML, then the wrapper handles that call and which in-turns calls the DELETE of REST layer.
And, why POST method is not working from browser is, By default Browser makes a GET call. Have a look at Postman to make REST calls with different Http methods.

Swagger Multiple hosts in same Json spec

I am using a single host for documenting REST API's in Swagger Ui 2.0 but I need two hosts in the JSON file for calling rest API's one for http and the other one for https. Is it possible? If yes then how to do that?
Thanks!
The way swagger figures out URLs is this:
You provide the basic one in index.html from where the swagger.json gets generated. The generated swagger.json does not contain a URL per se, or any http/https information. It only has a path relative to the base URL you provided.
After the UI gets generated based on generated swagger.json, the "Try it out" buttons execute GET/POST/PUT requests based on the URL info in the address bar. check this piece of code in your swagger-ui.js:
if (url && url.indexOf('http') !== 0) {
url = this.buildUrl(window.location.href.toString(), url);
}
So, if you want to use https, use https in the address bar to hit Swagger UI. You will also need to mention the same in your index.html, and in swagger-ui.js in the above code.

Accessing JSON Resource on a RESTful one page app

Given a one page app that uses push state and RESTful backend, we can imagine accessing the listing of a resource at /resourceName (i.e. /users). So /users would create a formated list of users
Now the problem is that this resource JSON or XML feed should also be mapped to /resourceName, so if boot form my application entry point at / then all is good, when navigating to /users the JS router can trigger a Ajax call that get the JSON data. Now the problem is if the URL is pointing directly at /users then i will land on a JSON feed instead of the actual listing. I could route all call to a main entry point and then let the JS router do the work though if i do so the AJAX call to fetch JSON wil brake.
I remember a while ago people adding .json to their json request, or even a GET parameter ?format=json and then having the controller taking different actions. I find that somewhat hacky.. Are there any other ways to go about this?
For that matter i am using laravel4 backend and backboneJS
I think the .json on the end of the request is the best approach. the other approach could be to create a separate endpoint endpoint for api request api.mydomain.com vs www.mydomain.com
What method you use to get a different response depends on how you'd like to go about it. Since you're asking about an opinionated topic (There is no one right answer), here's some options you can explore.
First, here's a good read from Apigee on API design, which covers what I'll write about here. See page 20 on "Support multiple formats"
The Rails way: Append a .json, .xml or other extension at the end of your request and handle that code within Laravel (You may want to use the "before" filter to check the request or Laravel's excellent route parameters, which allow the use of regex to define the route).
You can check the "accept" header in the request and set that header in your ajax calls to "application/json" instead of the default "application/html" to inform your application which format to use in its response. Again, the before or after filters may come in handy to check the request and define the response as appropriate
Create a query string `?format=json" or similar. Same comments as in point 1.
Laravel doesn't have built-in methods to change the response for you. You can, however, fairly easily detect what's being asked and choose which format to return in. It does take some thinking about how you want to accomplish that, however.
Some options off the top of my head:
Use the "before" or "after" filter to check what the request "wants" for a format, and do some transformations on the response to make that work
Extend the request and response class to "automate" this (request class to detect format, response class to transform the response to the correct format)
Hope that helps
It's valid to say which representation do you want. E.g. JSON, XML or binary, depends on what you want and which serializers have you developed.
You framework should support either setting of default representation or if you provide some mapping URL -> method you should be able to say which representation you are going to return - also either by default or taken within some object which represents your request.
I ended up using different endpoints as suggested by #Aaron Saunders. In laravel 4 this is dumb easy to implement using group routes:
app.php:
'domain' => 'whatever.dev',
routes.php:
define('APP_DOMAIN', 'app.' . Config::get('app.domain'));
define('API_DOMAIN', 'api.' . Config::get('app.domain'));
Route::group(array('domain' => API_DOMAIN), function()
{
// API ROUTES
});
Route::group(array('domain' => APP_DOMAIN), function()
{
// VIEW ROUTES
});
Beautiful!

GWT JSONP with Post not Get

I have a web service in the form `http://....../methodName
It returns a jsonp result such as:
methodName(["a":"a", "b":"b"])
GWT provides JsonpRequestBuilder class to parse jsonp.
JsonpRequestBuilder rb = new JsonpRequestBuilder();
rb.setCallbackParam("callback");
rb.requestObject("http://...../methodName", new AsyncCallback<TestJS>(){
...
});
This structure makes a request to url :
"http://...../methodName/?callback=__gwt_jsonp_P0.onSuccess".
My web service returns a callback with methodName not with __gwt_json.....
So gwt could not create a JavaScriptObject from that response.
Also JsonpRequestBuilder works with GET not POST.
How can I achieve those: Sending requests with POST and modifying GWT's default callback name.
JSONP will NOT work with POST. Its not a GWT limitation btw.
JSONP is essentially including a javascript file from your server. So, when you make a JSONP call, a temporary tag is added to the DOM.
Now, a <script> tag can always makes a GET request. That's a browser thing, and GWT cannot do much about it.
If you want to make a cross-domain POST call, you have to chose from one of the following options (and they have nothing to do with GWT)
Use Flash plus a crossdomain.xml that allows cross domain posts
Use Cross Origin Resource Sharing, or CORS. NOTE that this is only supported in modern browsers
Use a proxy server on your domain
Unfortunatly, this isn't how JsonP works. The requests are made by adding a tag to the page, and the results are passed into a function wrapped around the data – in your case, __gwt_jsonp_P0.onSuccess.
The callback name can't be affected, at least while using JsonpRequestBuilder – the system needs to account for the fact that you could send multiple requests out at once, possibly even to different endpoints. A JsonP endpoint that doesn't allow the caller to customize the callback function name is very unusual, and even more odd is an endpoint expecting JsonP calls that expects an impossible POST.
You can implement your own JsonP client side code by using the ScriptElement type, and registering your own global callback to call into your GWT java code.
Look into the API docs for the web service, and see if there is perhaps a better way to communicate with it, perhaps by using a proxy on your own server, avoiding the cross domain issue altogether.