RESTful Web Service using Netbeans and Java Issue - java

I'm new at Restful webservices and im trying to create a WS server to work with an android app. I'm using Netbeans and i followed this tuturial to get started (http://netbeans.org/kb/docs/websvc/rest.html) . I was able to successfully teste the basic features as explained in the tuturial. But now I am not able to add a new feature to the WS. Say I have a table in my DB called User. With the tuturial I can access the table Users by ID trhough the function
#GET
#Path("{id}")
#Produces(
{
"application/xml", "application/json"
})
public User find(#PathParam("id") Integer id)
{
return super.find(id);
}
The problem is if I want to get a User by its name for example. If I create a similar function like
#GET
#Path("{name}")
#Produces(
{
"application/xml", "application/json"
})
public User find(#PathParam("name") String name)
{
return super.find(name);
}
The server crashes. So my question is , what's the procedure to be able to get a User by other parameters different of id.
Thank you

Here there is a video of one hour long where you can see an implementation of a web-service front end that allows users to insert and also access database rows.
The principle should be the same, because web services are meant to serve inter-operable clients, doesn't mind if it is an android app or what ever.
In this video you will see how 2 parameters are used to form a query and fire it against an oracle database.
I think something that can help you would be an EJB to implement a CRUD facade.
I hope it helps: http://www.youtube.com/watch?v=0_0gGL2C1ys&feature=player_embedded

Related

What is the essence of "exposing" an API especially in Google Cloud Endpoint?

I am totally new to the whole Google Cloud Endpoint/Google App Engine world. If you have gone through the Hello World example that Google provides(and you probably have), you might remember that there are 2 classes that are auto-generated for you: MyBean and MyEndpoint.
These are something like this:
/**
* The object model for the data we are sending through endpoints
*/
public class MyBean {
private String myData;
public String getData() {
return myData;
}
public void setData(String data) {
myData = data;
}
}
And,
/**
* An endpoint class we are exposing
*/
#Api(
name = "myApi",
version = "v1",
namespace = #ApiNamespace(
ownerDomain = "backend.myapplication.DJ.example.com",
ownerName = "backend.myapplication.DJ.example.com",
packagePath = ""
)
)
public class MyEndpoint {
/**
* A simple endpoint method that takes a name and says Hi back
*/
#ApiMethod(name = "sayHi")
public MyBean sayHi(#Named("name") String name) {
MyBean response = new MyBean();
response.setData("Hi, " + name);
return response;
}
}
Now, I examined the code in index.html(which gets opened on deploying the backend). I found the following call in the javascript:
gapi.client.myApi.sayHi({'name': name}).execute(
Now, I can see that myApi is the name through annotation and sayHi() is the corresponding method, What I don't understand is the concept of exposing an API and annotation is aiding in that. There isn't any information about exposing APIs.
Could anyone help me understand this?
I think your question can be divided in 3 parts:
1/ What is exposing an API?
Basically, you are offering an access to your business logic through an Interface (the API), with full control on what you want to show or not. This Stack Exchange answer is a great explanation: https://softwareengineering.stackexchange.com/questions/203844/what-does-it-mean-to-expose-something
2/ What are these annotations in the auto-generated endpoints class?
If I can summarize it like that, Google endpoint is a "framework" which generates "default" APIs based on your java beans. By default you get CRUD operations in the API, but you can modify and/or enrich the endpoint to offer more complex business logic. The Endpoints classes that are generated include specific annotations that are used by the framework (in particular while generating a corresponding servlet) and define the URI you will call to interact with the methods of the APIs. See https://cloud.google.com/appengine/docs/java/endpoints/
3/ What is this gapi.client call?
gapi stands for Google API Client Library. It is the library that is offered by Google to interact with Endpoints from a web browser. See https://developers.google.com/api-client-library/javascript/
You could use other methods to call the Endpoint APIs, like jquery Ajax methods (http://api.jquery.com/jquery.ajax/), since Endpoints follow the REST architectural style. Note that you can call your endpoints from other "clients" than a web browser, e.g. an Android or iOS App. In these cases, you would not use the Google API Client Library but some other libraries.
I hope this clarifies a bit. Do not hesitate to ask for more details.

How to approach this authentication mechanism in Jersey

I am new to Jersey REST Framework , so please excuse if this is a dumb question .
I am using Tomcat with Hibernate and Jersey REST Webservices.
I have got set of HTML pages in my Web APP
login.html
dealer.html
sales.html
I dont want the User to access the HTML pages directly other than login.html
So to resolve this issue , when submit is pressed , under login.html call
following call is made to the backend
#Path("/webchecklogin")
public class WebLoginCheck {
#Context
private HttpServletResponse response;
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces("application/json")
public String getData(LoginInfo loginInfo ) throws JSONException,ClassNotFoundException, SQLException
{
String ID = loginInfo.getID();
String email = loginInfo.getEmail();
// validate this values with Database and if successfully logged in , stored them in session AND cookies also
}
}
And inside dealer.html and sales.html , on page ready i am calling a service as shown below
var checkcallajax = $.ajax({
type: 'GET',
url: url + '/ORIENT/orn/checkifuserloggedin',
jsonpCallback: 'jsonCallback',
success: function(response) {
}
})
#Path("/checkifuserloggedin")
public class CheckIfUserLoggedIn {
#Context
private HttpServletRequest request;
#GET
#Consumes(MediaType.APPLICATION_JSON)
#Produces("application/json")
public String checkIfUserLoggedIn() throws JSONException,ClassNotFoundException, SQLException
{
// On what basis , should i check wheher the USER is logged or NOT
// I tried storing data with Session and cookies , but i am unable to retrive them here
//return true or false
// based on true or false , i am redireting user to appropiate page
}
}
Could anybody please let me know how to approach this
RestFUL web services are supposed to be stateless, so in theory, you could send the credential with every request, and that would be totally stateless from the "server point of view"
Most will find this cumbersome, resource intensive, and storing credentials on the client is somewhat bad from a security point.
The alternative approach could be that your login method returns a token, that needs to be re-sent (in a header maybe) to the server with every request.
The client must know how to store it (session cookie? on the domain
serving html, if you are in a CORS scenario)
The server must know how to validate the token.
On top of it, the validation of the Token can be done in a JaxRS Filter... before reaching your service entry point. And even better, this filter could add roles to the request context, so you can the use the #RolesAllowed annotation with your services.
I "very personnally" avoid relying on the javax.servlet.Session, as this is fundamentally stateful. But, you should be able to do it, given that the clients stores the jSessionId (other other cookie name) in a session cookie. If it does not work, you might have CORS or other domain specific problem, preventing the client from storing and returning this cookie automatically.
Hope it helps.

How to submit a key value object from java based web application to asp.net mvc application

This question related to cross site submission across JSP/Servelet based web application and ASP.NET MVC based web application. I could able to submit a NameValueCollection object from an ASP.NET Web project to another ASP.NET MVC project like below.
using (var client = new WebClient())
{
client.Credentials = CredentialCache.DefaultNetworkCredentials;
string transId = Guid.NewGuid().ToString(); //In Java we may use UUID class
var data = new NameValueCollection
{
{ "TransId", transId },
{ "Name", "Regi" },
{ "DOB", "10/17/2013" },
{ "ZIPCode", "673010" },
};
var result = client.UploadValues("http://localhost:50976/api/Trans/Trans", data);
string s = Encoding.ASCII.GetString(result); //May be Base64.encodeToString(fileData, Base64.CRLF) in Java?
if (s == "1")
{
Response.Redirect("http://localhost:50976/Product/ProductList?TransId=" + transId + "");
}
}
ASP.NET MVC project has a WebAPI which is catching this submission like below.
public int Trans(TransViewModel transViewModel)
{
return 1;
}
My ViewModel definition like below
public class TransViewModel
{
public string TransId { get; set; }
public string Name { get; set; }
public DateTime DOB { get; set; }
}
So now I need to replace my 1st WebProject where ASP.NET MVC
application is calling, with a Java based web application. How can I
accomplish the same submission using alternate JAVA classes in place
of WebClient and also to submit a NameValueCollection type to the same
ASP.NET MVC application? This submission should be accepted by ASP.NET
MVC application like above through a ViewModel
Hmm.. I haven't tried but if you just use regular HTTP GET or POST it doesn't matter what web framework you are using. What ASP.NET MVC want is just a NORMAL request (for example: http://yourwebsite.com:8081/Main/Index?name=Me&email=me#gmail.com).If you send it from any java or other web frameworks your MVC router will be able to map them to a particular action method. In my example this is the Main controller and Index action (HTTP GET) with parameters name and email (string type). The same for Post (add HTTP POST attribute for the action). Problems could have place if you were using models. In this case I always use fiddler to see what exactly I am sending to MVC and also you have to understand how standard MVC model binding works. If you find that your java data structure can't be handled with the MVC standard model binder you can whether change the data structure or implement custom model binder and directly get access to all request data. MVC is a very pluggable framework and I believe this is one of the best web frameworks ever created!
I am not sure that you are trying to do. But I think that there is no way to DIRECTLY pass data between MVC and let's say plain java servlet. You always send data as HTTP requests and it's up to web framework how to handle them. If you need a similar to MVC you can use Spring MVC (java). Again I am not really sure what you are trying to achieve. However, you can make any HTTP based calls from server as well. For example, you have a servlet mapped to /doSomething in your java environment. In the servlet inside get method you have all access to request parameters. So in your MVC project you are free to just make a server side http based call to the servlet mapped address and pass any parameters. In the servlet you generate output and return to the mvc server. After it's up to you what to do with it!

How to authenticate users in Java(REST) app?

I have some java server application and some WEB interface(jQuery). For REST services i'm using Jersey implementation. I can easily sent JSON to the server from WEB page and vice versa.
Example of my REST service:
#Path("/users")
public class User {
#POST
#Path("/login")
#Consumes(MediaType.APPLICATION_JSON)
public Response authUser(User user) {
//code
}
}
But there is one problem. How can I auth users?
For example, i have some private resources: when user in not log in, he can't see it resource/web page, but when he logined(enter correct name and password) he can see it resource.
I didn't use sping application. I have googled a lot of time but I didn't find easy examples, then i tried to read Jose's Sandoval book "RESTful Java Web Services", in "Security" section a lot of useful information but there isn't examples.
Could you please help me?
There are different ways to approach this I believe. One way is that when the user authenticates, you send him back a token [which expires after some time] and he then passes back that token in subsequent calls.
Save the token to a file or db. In subsequent requests that come from client , compare token timestamp and value.
Once that token expires he has to re-authenticate.

Securing jax-rs with OAuth

I have following problem:
I have JAX-RS service which has a get operation:
#Path("/unsecure/")
#Produces("application/json")
public class MyUnsecureService {
public MyUnsecureService() {
}
#GET
#Path("/get/{id}")
#Produces("application/json")
public User get(#PathParam("id") String id) {
return User.get(id);
}
}
now, I'm going to open this API for mobile devices and I need authentication and authorization mechanism to access the API.
My problem is that I have trusted apps (internal jobs, a website which runs on my hosting) which should be able to expose this API as they want, with no limitation, and mobile devices, which should be able to expose this API only if they have a token, formed using real User's encrypted login/pass, which can be used on service-side to determine:
If the request to that method is allowed.
If the parameters are correct (so, the user can't get other user's info).
Is this possible to do using OAuth1 or OAuth2?
This is a very valid question to raise.
You might want to have a look at Oz (backgroud), which AFAIU will go a long way towards your use cases. Personally, I have interest to solve the issue for Java and track Eran's work with Java implementations ( jiron, hawkj ). To finally do Oz (or something like it) in Java.
Much is not ripe for publishing right now, but get in touch for details if you like.
Specific problem with JAX-RS right now seems to be SecurityContext.
The answer is found:
Using Client Credentials and Resource Owner authorization grants, which are implemented in OAuth2 implementation of Apache CXF.

Categories