Fetch JSON data from a third-party and getting around the SOP - java

The Same Origin Policy is preventing me from fetching the JSON data I need from another web site (with permission). I saw one person who was working around this with JsonpRequestBuilder, but I'm not sure if that's going to be the best solution for me. The only other option that comes to my mind would be to have an intermediary servlet on my server.
What's my best bet here? I have concerns with both methods. With an intermediary servlet, I worry about the delay that would introduce. With the JsonpRequestBuilder, it looks like I have to create a complete JavascriptObject for each method I'll call from the other site, even though I only need to pull out a single value from some of those methods.

I don't use Java, but JSONP is what I usually implement when I need cross-domain chatter, and I'm sure someone will have made a Java library that unwraps it. It requires a change on the third-part's site, but it is a very simple change.
EDIT: Sounds like that is what that library does, sorry... but still... it's the way to go :)

Check out the CORS Specification. We are using this to successfully circumvent the SOP using our own server with GWT's devmode Jetty.

You don't have to "create a complete JavaScriptObject", a JavaScriptObject is actually just a mean to call to JavaScript from the Java world, so you only need the one getter for the value you need, and it can even return a "nested" value:
public native String getFoo() /*-{
return this.nested[0].obj.foo;
}-*/;
Whether you'll use JSONP (and JsonpRequestBuilder) or a "proxy servlet" actually only depends by the capabilities of the "service" you need to call: JSONP is JavaScript, not JSON, so the server has to return a "JSONP response script" or you won't be able to use JsonpRequestBuilder (and similarly, you won't be able to (safely) use CORS or a proxy-servlet if the server returns a "JSONP script" rather than application/json).

Related

How to determine JAX-RS resource paths programatically?

Suppose I have a set of JAX-RS locators and sublocators, like the following:
#Path("/users")
public class UserListResource {
#Path("/{id}")
public UserResource getCustomer(#PathParam("id") int id) {
// Find and return user object
}
}
public class UserResource {
#GET
public String get() {...}
}
For example, a UserResource object with the ID 5 would have the path "/users/5". In my system, I have several different resources.
Now the question is: How can the server figure out the path of a given resource? Can I do this programmatically via some JAX-RS API or do I have to implement code that uses reflection? (I know how to do the latter, but would prefer the other approach.)
At the point when I need to know the path, I do not have a request object at all. For example, I have a timer which does some background processing, then changes some entities in the domain model, then informs all clients about the changed entities (including their paths).
I know that within the scope of a request, I can inject a UriInfo object that provides this, but I need to know the path in advance (to inform clients of a change that did not necessarily happen through the JAX-RS resource).
I don't want to repeat the path information in another place, and I also don't want to have a set of path fragment constants for each resource type (in this case "/users" and "/{id}").
As I read your question, you need to build a URI knowing only the resource class and the id parameter.
It can be done using the UriBuilder class as in:
UriBuilder builder=UriBuilder.fromResource(UserListResource.class);
URI uri=builder.path(UserListResource.class,"getCustomer").build(5);
It uses reflection under the hood, so it is not so easy to refactor, but it is all it is available at the moment.
Overall, be aware that something sounds rather strange with the architecture of your application. It's hard to put a finger on, but the pattern of questions you are asking is raising a number of red flags about how you're going about this. Be aware that if you are seeking to create a RESTful API to your application that you may need to stop, take a few steps back, and rethink what you are trying to do.
To your explicit questions…
Now the question is: How can the server figure out the path of a given resource? Can I do this programmatically via some JAX-RS API or do I have to implement code that uses reflection? (I know how to do the latter, but would prefer the other approach.)
The server knows the path, as that's always supplied by the user and is used to navigate through the collection of resource classes that make up your application. If you need a UriInfo instance for a particular call, you should inject it as part of that specific call:
#GET
public String get(#Context UriInfo info) {...}
Any information required from the outer context (e.g., what the resource's ID is) is best passed in during construction. You can reparse it out of the URL (obtainable from the UriInfo) again, but that's probably the wrong approach.
Otherwise, if you're doing something much more complex then you need to be more specific in your question.
At the point when I need to know the path, I do not have a request object at all. For example, I have a timer which does some background processing, then changes some entities in the domain model, then informs all clients about the changed entities (including their paths).
I know that within the scope of a request, I can inject a UriInfo object that provides this, but I need to know the path in advance (to inform clients of a change that did not necessarily happen through the JAX-RS resource).
How are you going to have the clients be informed? There's normally no mechanism to push messages from the server to the clients, and clients are typically firewalled so that they can't directly host a service.
Theoretically, you could associate (explicitly, by URL) each resource with its own RSS feed to which a client could listen to if they chose. You wouldn't be able to force clients to listen, but you could give them the option to do so. If you go this route, you don't need to know the UriInfo “ahead of time” as the location information will be present at key times (i.e., at resource creation) and afterwards you're just referring to something that you have control over.
But that's just one way to do it and it adds a lot of complexity; you'd only do it if it was critical to your application. It's often simpler to just have clients poll from time to time. (Note that some sorts of modifications are inherently very destructive; particularly altering the ID or deleting the resource. Don't expect things to cope smoothly with those.)
I don't want to repeat the path information in another place, and I also don't want to have a set of path fragment constants for each resource type (in this case "/users" and "/{id}").
Tough. Repeating information in multiple places, provided you draw it consistently from a single source, is a common practice. There's nothing actually wrong with it.
As I understand your question, you want to know the path as the request is coming in but before it hits your resource; are you open to using Servlet Filters?
JAX-RS specific filters are only supported in 2.0
For the record: after I had posted the question, I thought about our architecture a bit more and came to the conclusion that sending URLS is not as useful as I thought. The application has to know some details about the application structure anyway:
Continuing the example above: even if the client did not know the URL pattern for individual users, it must assume that there is a list of users and know its URL; it also has hard-coded knowledge what dialog to display for editing a user etc.
So all in all, attempting to tell the client (most) URLs it needs is not worth the effort. Instead, we decided to go with a custom API definition file which includes data about the resource contents and their URL scheme. This file is used to generate the following:
the server-side resource classes with the correct JAX-RS annotations
a URL scheme specification document for other developers to code against
classes for our own client (including the URL know how, e.g. user with ID 5 has the URL ...), so we don't have to worry about inconsistencies between our client and server.
This approach has the following advantages:
The need for the server to figure out the URLs from the annotations vanishes, as the client can now do that on its own once it receives a notification that includes the object ID.
We don't have to worry about inconsistencies between our client and the server, as all information is drawn from a single source.
We have one source for the API definition under version control which can be used to verify backwards compatibility with older releases.
Note:
I would probably not claim that the resulting API stays "faithful" to the idea of RESTful webservices, but it works for us and the elements that it borrows from "actual" REST architectural style should make the API clearer and easier to learn than a traditional contract-first webservice.

Setting Request Header in java

Is there any way to modify or set-header of request inside action class? I want to modify it or you can say i want to put flag inside request Header just like we put values in 'attribute' and parameters.
You can do this using HttpServletRequestWrapper. But it's quite dirty solution. Are there really no other ways to solve your problem?
You cannot. Request parameters returned from the servlet are unmodifiable Map. You cannot add/delete content returned from request (via servlet).
In order to set a flag, my suggestion is to store it in a session, and on another action, retrieve the flag & delete it from session.
I think you'd need to wrap the original request into a request class containing the change you wish to have.
It might be better design to have the request parameters parsed earlier in processing to such objects that make more sense to your application logic, and then set the state of those objects in the place where you now would like to modify the original header.
The answer to this depends on what problem you're trying to solve.
One of your comments suggests you're trying to test; if this is the case you have two basic options:
Use a mock request (unit-style testing).
Change the header from the client (integration-style testing).
For testing from real clients, set headers on the client side.
For mocking client interactions, you should be using some form of mock. StrutsTestCase, for example, provides MockStrutsTestCase (outside container) and CactusStrutsTestCase (inside container) classes allowing easy manipulation of request properties and characteristics.
If you are trying to open a URL connection using Java,
you can something like this What is the proper way of setting headers in a URLConnection?
If you can make requests with a browser,
You can use this Firefox plugin to add/modify any number of request headers.
https://addons.mozilla.org/en-US/firefox/addon/modify-headers/
Good Luck
You need to give more details. It sounds like you want to manipulate the request header once the server has received the request. I'm not sure I understand why you would want to do that. Modifying the response headers make sense. But not the request.
I think they only clean way you can do this is via an HttpServletRequestWrapper
Just override getHeader, getHeaders, getHeaderNames and you are good to go.

jQuery AJAX to call Java method

Using jQuery AJAX, can we call a specific JAVA method (e.g. From an Action class)
The returned data from that Java method would be used to fill in some HTML code.
Please let me know if this can be done easily using jQuery (like it does in DWR)..Also for multiple data points in HTML, do we need to make multple AJAX requests?
The simple answer is you map your ajax calls to urls, which are in turned map to methods in your java code. The Ajax -> URI mapping happens on the client side (which ever js framework you are using, and the URI -> specific handler mapping happens within the java application)
What java framework are you using? There should be very clear and simple documentation on how to do this. For standard Java EE mappings (meaning you are not using any frameworks like Spring or Roo) I found this on google: http://javapapers.com/servlet/what-is-servlet-mapping/
"For multiple data points in HTML" I assume you are talking about having multiple parts of the html update. You can do this with multiple requests, or you can do it with one request. If you do the latter, the server needs to return all the data you need to update the dom appropriately.
It's not as transparent as with DWR--DWR handles making JavaScript look like Java. With jQuery you'll get JSON (or just HTML if/when it's easier that way). It's still pretty straight-forward, though. You'd send the Ajax request to a URL, rather than having it look like a local method call.
I'm not sure what you mean by "multiple data points in HTML" -- you get back whatever data you get back, and you can do with it whatever you want. If the response has all the data you need, then you wouldn't need to make multiple requests.

How to read a response of a servlet using PHP

I would like to send a request to a Java Servlet from PHP and receive the response from the same and show it on the PHP page. How should this be done?
Thanks and Regards
Abishek R Srikaanth
If all you want is to print the response of a GET request to an external resource plain vanilla into the PHP response, then you can use file_get_contents() for that.
<?php echo file_get_contents("http://example.com/someservlet"); ?>
The servlet's doGet() method will be invoked and whatever response it returns (which can even be a forwarded JSP) will be printed as string to the PHP response.
If you want a little more fine grained control, e.g. using POST or something, then head to curl() instead. The linked PHP manual contains several examples.
Regardless of the way, please note that whenever it returns HTML, that you should ensure that you end up with valid HTML. For example, nesting <html> tags is illegal. Pass the PHP page through the w3 validator if you're unsure. Otherwise you'd better have to parse the HTML to extract the <body> pieces of interest or to use an <iframe> instead.
<iframe src="http://example.com/someservlet"></iframe>
If I'm understanding you correctly you want to read the response of a servlet in php and then output it from php?
You can use file_get_contents to the url (Probaly not the best way, but for simplicities sake it the easiest) and then just echo the output.
For example:
$content = file_get_content('http://www.google.com');
echo $content;
But if you want to be able to login or use the session at the servlet side you will need think of something else. As each request to the server from php will be a new one, it does not store cookies etc.. like browsers do.
Hope that helps
This is a situation which might do well to be rethought, but, if there are no other options...
If there is a way to actually update the portlet, then I would recommend creating some form of service call -- SOAP, custom RPC, etc -- on the Java side. Technically this is the most correct way to do things.
Failing that, if this is a simple GET request, then use file_get_contents.
If it has to be a POST/PUT/DELETE, then you can use cURL. cURL also has the benefit of being able to handle simulated sessions, which means that you are then able to simulate a log in and actions following that (though not without some difficulty).
If you don't have cURL and you need to POST/PUT/DELETE, then the streams library might be able to give you what you need.
If you don't have the streams library or cURL and you need to POST/PUT/DELETE, then there are other means of accomplishing that, but maybe you should really re-rethink that situation.
If all of the above don't work, then you will need to tame the Spectral Wolf. The Spectral Wolf fears only fire. I can no longer help you, but if you master the Spectral Wolf, he will guide you. Godspeed.
If you really want to do that, you can create a Java app that takes parameters to populate request and response objects, instantiates a servlet, runs the correct method, gets the result and displays it, then call this Java app from PHP.
Or you can use the experimental and unrecommended PHP / Java Integration module.

Javascript classes and DWR

I've been playing with DWR and converters for a while and I really wanted to map my Java classes to JavaScript classes. Using DWR converters, I have the option to point out what is the name of my JS constructor given a Java class. So far so good... The problem arises when my JS constructor is within a JS package-like name (just like YUI's package system, eg my.beautiful.package.MyClass). DWR's current implementation doesn't allow me to use this kind of construct, giving me a SyntaxError when I try to use it. Is there an elegant way arround this limitation?
As far as I know the this isn't possible directly. I have in my current work project experimented with enhancing each returned object on the client side with methods from a Javascript class, which gets the result that I think you are interested in.
DwrService.getThings({
callback:function(things){
for(thing in things){
YAHOO.augmentProto(thing, my.beautiful.package.MyClass);
}
// do your stuff here
}
});
I'll have to check at work on monday (now is sunday) that augmentProto is correct one to use, but I think it is. There may even be a better hook into DWR that'll allow you to do this on the fly automagically.

Categories