JAX-RS REST API Basic Authentication - java

i am trying to implement basic authentication to somehow secure my rest api.To test, i tried below code to filter the url parameter that contains users however it is not aborting the request without authorization. and the most important is i need to implement it in the way that only update and delete needs to be authorized with the respective username and password. other things i just don't want to filter. i have an user class having username and password (encrypted) properties. so if the url contains PUT or delete method on users/{userID} i want it to verify with the username and password of that specific users. i have listed code of model , resources and filter class below.. i really need your help. thanks in advance.
filter class.
package Authentication;
import java.io.IOException;
import java.util.List;
import java.util.StringTokenizer;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import org.glassfish.jersey.internal.util.Base64;
#Provider
public class SecureFilter implements ContainerRequestFilter {
private static final String Auth_Header = "Authorization";
private static final String Auth_Header_Prefix = "Basic ";
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
if (requestContext.getUriInfo().getPath().contains("users")) {
List<String> authHeader = requestContext.getHeaders().get(Auth_Header);
if (authHeader != null && authHeader.size() > 0) {
String authToken = authHeader.get(0);
authToken = authToken.replaceFirst(Auth_Header_Prefix, "");
String decodedString = Base64.decodeAsString(authToken);
StringTokenizer tokenizer = new StringTokenizer(decodedString, ":");
String userName = tokenizer.nextToken();
String password = tokenizer.nextToken();
if ("user".equals(userName) && "password".equals(password)) {
return;
}
Response unauthorizedstatus = Response
.status(Response.Status.UNAUTHORIZED)
.entity("these resources needs authorization. ")
.build();
requestContext.abortWith(unauthorizedstatus);
}
}
}
}
resource class:
import com.mycompany.samplehospital.model.Alert;
import com.mycompany.samplehospital.model.Message;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import com.mycompany.samplehospital.model.User;
import com.mycompany.samplehospital.Services.UserServices;
import com.mycompany.samplehospital.exception.objectNotFound;
import com.mycompany.samplehospital.Services.AlertServices;
import com.mycompany.samplehospital.Services.MessageServices;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
/**
*
* #author sandesh poudel
*/
#Produces(MediaType.APPLICATION_XML)
#Path("/users")
public class userResources {
UserServices service ;
public userResources() throws Exception{
service = new UserServices();
}
#GET
#Produces(MediaType.APPLICATION_XML)
public List<User> getAllUser(){
return UserServices.getUsers();
}
#Path("/{userId}")
#GET
#Produces(MediaType.APPLICATION_XML)
public User getUser(#PathParam("userId") int ID ) throws Exception{
User myUserList = service.getUser(ID);
if (myUserList == null){
throw new objectNotFound("User not Found");
}else {
return myUserList;
}
}
#POST
#Produces(MediaType.APPLICATION_XML)
#Consumes(MediaType.APPLICATION_XML)
public User addUser(User user ) throws Exception{
return service.AddUser(user);
}
}
#PUT
#Path("/{userId}")
#Produces(MediaType.APPLICATION_XML)
#Consumes(MediaType.APPLICATION_XML)
public User updtaeUser(User user) throws Exception{
return service.updateUser(user);
}
#DELETE
#Path("/{userId}")
#Produces(MediaType.APPLICATION_XML)
public User delUser(#PathParam("userId") int ID) throws Exception{
return service.removeUser(ID);
}
#Path("/{userId}/messages")
#GET
#Produces(MediaType.APPLICATION_XML)
public List<Message> getAllMessageByUser(#PathParam("userId") int ID) throws Exception{
MessageServices mservice = new MessageServices();
List<Message> messageUserList = mservice.getAllMessageByUser(ID);
if (messageUserList == null ){
throw new objectNotFound("messages not Found");
} return messageUserList;
}
#GET
#Produces(MediaType.APPLICATION_XML)
#Path("/{userId}/alerts")
public List<Alert> AlertsResources(#PathParam("userId") int userId){
AlertServices myAlert = new AlertServices();
List<Alert> newAlertUserList = myAlert.getAllAlertByUser(userId) ;
if (newAlertUserList == null){
throw new objectNotFound("messages not Found");
} return newAlertUserList;
}
Model class User
package com.mycompany.samplehospital.model;
import java.io.Serializable;
import java.util.Map;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import Authentication.HashPassword;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author sandeshpoudel
*/
#XmlRootElement
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String title;
private int age;
private String Sex;
private String Address;
private int phoneNo;
private String fullName;
private int id;
private Map<Integer, Message> allMessage;
private Map<Integer,Alert> allAlerts;
private String userName;
private String passWord;
private HashPassword hs ;
public User() {
}
public User(int id,String fullName, String Sex, Integer age, Integer phoneNumber, String Address, String title,String userName,String password) throws Exception {
hs = new HashPassword();
this.id= id;
this.fullName = fullName;
this.title = title;
this.age = age;
this.Sex = Sex;
this.Address = Address;
this.phoneNo = phoneNumber;
setPassWord(password);
// setPassWord(passWord) uncomment this and remove next line to execute on encryption mode;
this.userName= userName;
}
public void setId(int id){
this.id= id;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public void setTitle(String title) {
this.title = title;
}
public void setAge(int age) {
this.age = age;
}
public void setSex(String Sex) {
this.Sex = Sex;
}
public void setAddress(String Address) {
this.Address = Address;
}
public void setPhoneNo(int phoneNo) {
this.phoneNo = phoneNo;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
#XmlElement
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) throws Exception {
hs = new HashPassword();
this.passWord = hs.encrypt(passWord);
// this.passWord = passWord;
}
#XmlElement
public String getFullName() {
return fullName;
}
/*
*/
#XmlElement
public int getId(){
return id;
}
#XmlElement
public String getTitle() {
return title;
}
#XmlElement
public int getAge() {
return age;
}
#XmlElement
public String getSex() {
return Sex;
}
#XmlElement
public String getAddress() {
return Address;
}
#XmlElement
public int getPhoneNo() {
return phoneNo;
}
#XmlTransient
public Map<Integer, Message> getAllMessage() {
return allMessage;
}
public void setAllMessage(Map<Integer, Message> allMessage) {
this.allMessage = allMessage;
} #XmlTransient
public Map<Integer, Alert> getAllAlerts() {
return allAlerts;
}
public void setAllAlerts(Map<Integer, Alert> allAlerts) {
this.allAlerts = allAlerts;
}
#Override
public String toString(){
return (getSex() +" "+ getAddress()+" "+ getPhoneNo() +" "+ getFullName());
}
}

Basic authentication is part of the servlet specification. So if you run in a servlet container, which is the case, you can just enable basic authentication in the web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<security-constraint>
<web-resource-collection>
<web-resource-name>all-content</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>user</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>foo-realm</realm-name>
</login-config>
<security-role>
<role-name>user</role-name>
</security-role>
</web-app>
You must also configure the realm, and the roles, this depend on your servlet container implementation.

If you are running you app in a Java EE Container you can use standard web security defined in web.xml
https://docs.oracle.com/javaee/7/tutorial/security-webtier002.htm#GKBAA
Or if you use Spring
https://spring.io/guides/gs/securing-web/

In a sample jax rs api, I implemented basic authentication by getting the HttpServletRequest in my rest resource.
I created a doAuthorize() method which extract the Authentication header, decode and validate authentication as you have done.
Then I call doAuthorize() in the resource path methods which need it.

Related

retrieve of email and password from MySql databse using springboot

I want retrieve user email from MySql database table using spring boot.i used findByEmailAndPassword in controller but it retrieve null value for email.
Here is my Code
controller
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.example.demo.JPARepository;
import com.example.demo.pojo.regisbean;
#Controller
public class registerController {
regisbean pp;
#RequestMapping(value = "/")
public String mm() {
System.out.println("I am in m1 method");
return "index";
}
#RequestMapping(value = { "/register", "home" })
public String m1() {
System.out.println("I am in mm method");
return "register";
}
#Autowired
JPARepository jpaRepository;
#PostMapping("/register")
public String regis(#ModelAttribute regisbean rb)
{
System.out.println("I m in regis method");
regisbean b=jpaRepository.save(rb);
if(b!=null)
return "index";
else
return "fail";
}
#RequestMapping(value= {"/login1","login2"})
public String m2() {
System.out.println("i m in m2()");
return "login";
}
#PostMapping("/login")
public String login(#ModelAttribute regisbean rx,Model m) {
System.out.println("I am in Login");
regisbean re=jpaRepository.findByEmailAndPassword(rx.getEmail(), rx.getPassword());
if(re!=null)
{
m.addAttribute("email",rx.getEmail());
m.addAttribute("password",rx.getPassword());
System.out.println("yes");
return "loginsuccess";
}
else
{
System.out.println(rx.getEmail());
System.out.println("failed");
return "register";
}
}
}
pojo class
package com.example.demo.pojo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "pro")
public class regisbean {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column
private String name;
#Column
private String email;
#Column
private String phonenumber;
#Column
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhonenumber() {
return phonenumber;
}
public void setPhonenumber(String phonenumber) {
this.phonenumber = phonenumber;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Repository
package com.example.demo;
import org.springframework.data.repository.CrudRepository;
import com.example.demo.pojo.regisbean;
public interface JPARepository extends CrudRepository<regisbean, Integer> {
public regisbean findByEmailAndPassword(String email,String password);
}
I was able to get your code to work by inserting a row in the table:
INSERT INTO pro (
id
,email
,name
,password
,phonenumber
)
VALUES (
0
,'user#domain.com'
,'Jim'
,'secret'
,'123-123-1234'
)
Then changing:
public String login(#ModelAttribute regisbean rx,Model m) {
to:
public String login(#RequestBody RegisBean rx,Model m) {
and POSTing the following request body to the /login resource:
{
"email": "user#domain.com",
"password": "secret"
}
I didn't have to make any changes to your Repo. I suspect your attempt was failing because RegisBean was never being initialized with any values and so the repo was asked to find a record with a null email and a null password.

Rest Webservice returning http status 404

I am using Apache Tomcat 6 and the Jersey 2.0 libraries. I am running this service on 8088 port. While trying to access it, getting 404 not found error. This is my service:
User Class
package com.tutorialspoint;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private String profession;
public User(){}
public User(int id, String name, String profession){
this.id = id;
this.name = name;
this.profession = profession;
}
public int getId() {
return id;
}
#XmlElement
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
#XmlElement
public void setName(String name) {
this.name = name;
}
public String getProfession() {
return profession;
}
#XmlElement
public void setProfession(String profession) {
this.profession = profession;
}
}
UserDao Class
package com.tutorialspoint;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public class UserDao {
public List<User> getAllUsers(int id){
List<User> userList = null;
try {
User user = null;
if(id == 1){
user = new User(1, "Mahesh", "Teacher");
}
if(id == 2){
user = new User(2, "Manish", "Doctor");
}
userList = new ArrayList<User>();
userList.add(user);
} catch (Exception e) {
e.printStackTrace();
}
return userList;
}
}
UserService class
package com.tutorialspoint;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("/UserService")
public class UserService {
UserDao userDao = new UserDao();
#GET
#Path("{id}")
#Produces(MediaType.APPLICATION_XML)
public List<User> getUsers(#PathParam("id") int id){
return userDao.getAllUsers(id);
}
}
web.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns = "http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id = "WebApp_ID" version = "3.0">
<display-name>UserManagement</display-name>
<servlet>
<servlet-name>Jersey RESTful Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Jersey RESTful Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
My project Stucture is like this
Getting this error

Unmarshaling (JSON) in apache camel

I am new in apache camel. And I wanna do some simple task using apache camel. I have json data available on this url http://localhost:8080/users/. There are json data from my rest service. But I wanna get this json data and unmarshal it to POJO using apache camel and write some data to txt file. But my app starts and then doesnt't stop.
Here is my JSON data available on http://localhost:8080/users/
[{"id":1,"login":"admin","password":"admin","passwordAgain":null,"email":"admin#admin.com","firstName":"Admin","lastName":"Adminovich","birthday":"2010-10-10","role":{"id":1,"name":"admin"}},
{"id":5,"login":"Snow123","password":"1111","passwordAgain":null,"email":"john#snow.com","firstName":"John","lastName":"Snow","birthday":"2010-10-10","role":{"id":2,"name":"user"}}]
spring.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:camel="http://camel.apache.org/schema/spring"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<bean id="MyRouteBuilder" class="MyRouteBuilder" init-method="restart">
</bean>
<camelContext xmlns="http://camel.apache.org/schema/spring">
<routeBuilder ref="MyRouteBuilder"/>
</camelContext>
</beans>
MyRouteBuilder
import Mapping.User;
import Mapping.Users;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;
import org.apache.camel.component.restlet.RestletConstants;
import org.apache.camel.model.dataformat.JsonLibrary;
import org.restlet.Response;
import org.restlet.data.MediaType;
import org.restlet.data.Status;
public class MyRouteBuilder extends RouteBuilder {
private String routePort = null;
private String routeAnswer = null;
public void restart() {
String start = "Route Property Placeholder Example started on port" + " 8080" + "!";
System.out.println(start);
}
public void configure() throws Exception {
from("timer:foo?repeatCount=1").to("http://10.10.34.145:8080/users/").unmarshal().json(JsonLibrary.Jackson, Users.class ).log("STARTED!")
.process(new Processor() {
public void process (Exchange exchange) throws Exception {
Users usersList = exchange.getIn().getBody(Users.class);
exchange.getIn().setBody(usersList.usersList);
System.out.println(usersList.usersList.size());
}
}).to("file:///home/name/username/Desktop/camel.txt").stop();
}
}
User
package Mapping;
import com.google.gson.FieldNamingStrategy;
import java.lang.reflect.Field;
public class User {
public User() {
}
private int id;
private String login;
private String password;
private String passwordAgain;
private String email;
private String firstName;
private String lastName;
private String birthday;
public void setId(int id) {
this.id = id;
}
public void setLogin(String login) {
this.login = login;
}
public void setPassword(String password) {
this.password = password;
}
public void setPasswordAgain(String passwordAgain) {
this.passwordAgain = passwordAgain;
}
public void setEmail(String email) {
this.email = email;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public void setRole(String role) {
this.role = role;
}
public int getId() {
return id;
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
public String getPasswordAgain() {
return passwordAgain;
}
public String getEmail() {
return email;
}
public String getFirsteName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getBirthday() {
return birthday;
}
public String getRole() {
return role;
}
private String role;
}
Users
package Mapping;
import java.util.ArrayList;
import java.util.List;
public class Users {
public List<User> usersList = new ArrayList<User>();
}
Main
import org.apache.camel.main.Main;
public class MainClass {
public static void main(String[] args) {
Main main = new Main();
main.enableHangupSupport();
MyRouteBuilder rb = new MyRouteBuilder();
main.addRouteBuilder(rb);
try {
main.run(args);
} catch (Exception e) {
e.printStackTrace();
}
}
}
In my case I converted JsonData to Java object and created a custom CSV file using following dependencies.
jackson-mapper-asl
jackson-core-asl
You can create simple text file or CSV whatever it is.
This is my route:
from("couchdb:http://localhost:5984/order")
.startupOrder(1)
.process(new JsonToCsvProcessor())
.to("file:/home/r2/Desktop/ofBizFile?fileExist=append&fileName=orders-${date:now:dd-MM-yyyy}.csv");
This is my Processor where I am passing JsonString to ObjectMapper for Pojo:
{
public void process(Exchange exchange)throws Exception{
String jsonString = exchange.getIn().getBody(String.class);
exchange.getOut().setBody(convertJsonToCSV(jsonString).toString());
}
public StringBuilder convertJsonToCSV(String jsonStringArgs){
StringBuilder csvFile = new StringBuilder();
//Here customize data format using append()
.
.
return csvFile;
}
}
If you don't know how to use ObjectMapper this link will help you out.
https://www.youtube.com/watch?v=02X6U81MdJ0&t=1s
Use one of the amounts in json's case: Jackson or Gson
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-jackson</artifactId>
<version>${camel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-gson</artifactId>
<version>${camel.version}</version>
</dependency>
I recommend checking the documentation
you can do the unmarshal direct on the route:
unmarshal().json(JsonLibrary.Jackson, MyModel.class)
or you can create a processor:
#Component
public class MyModelUnMarshalProccessor implements Processor {
#Override
public void process(Exchange exchange) throws Exception {
MyModel model = exchange.getIn().getBody(MyModel.class);
exchange.getOut().setBody(model);
exchange.getOut().setHeader("id", body.getId());
}
}
#Autowired
MyModelUnMarshalProccessor myModelUnMarshalProccessor;
from("{{fromServices}}")
.log("${body}")
.process(myModelMarshalProccessor)
good luck

How can I use put method to insert data to my MySQL databse using restful webservice

I use this tutorrial and I created this
table (id ,username) prints;
and now I want to insert data to it using the restful web service
what should I put in the content text box to do that ?
this is my paints class
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package entities;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author subhi
*/
#Entity
#Table(name = "prints")
#XmlRootElement(name = "prints")
#NamedQueries({
#NamedQuery(name = "Prints.findAll", query = "SELECT p FROM Prints p"),
#NamedQuery(name = "Prints.findById", query = "SELECT p FROM Prints p WHERE p.id = :id"),
#NamedQuery(name = "Prints.findByUsername", query = "SELECT p FROM Prints p WHERE p.username = :username")})
public class Prints implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 30)
#Column(name = "username")
private String username;
public Prints() {
}
public Prints(Integer id) {
this.id = id;
}
public Prints(Integer id, String username) {
this.id = id;
this.username = username;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Prints)) {
return false;
}
Prints other = (Prints) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entities.Prints[ id=" + id + " ]";
}
}
I tried use put method but I got this error
and why I didn't have post method in combobox?
controller code java EE 6
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package service;
import entities.Prints;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import org.netbeans.saas.RestResponse;
import org.netbeans.saas.google.GoogleMapService;
/**
*
* #author subhi
*/
#Stateless
#Path("entities.prints")
public class PrintsFacadeREST extends AbstractFacade<Prints> {
#PersistenceContext(unitName = "test3PU")
private EntityManager em;
public PrintsFacadeREST() {
super(Prints.class);
}
#POST
#Override
#Consumes({"application/xml", "application/json"})
public void create(Prints entity) {
super.create(entity);
}
#PUT
#Override
#Consumes({"application/xml", "application/json"})
public void edit(Prints entity) {
super.edit(entity);
}
#DELETE
#Path("{id}")
public void remove(#PathParam("id") Integer id) {
super.remove(super.find(id));
}
#GET
#Path("{id}")
#Produces({"application/xml", "application/json"})
public Prints find(#PathParam("id") Integer id) {
return super.find(id);
}
#GET
#Override
#Produces({"application/xml", "application/json"})
public List<Prints> findAll() {
return super.findAll();
}
#GET
#Path("{from}/{to}")
#Produces({"application/xml", "application/json"})
public List<Prints> findRange(#PathParam("from") Integer from, #PathParam("to") Integer to) {
return super.findRange(new int[]{from, to});
}
#GET
#Path("count")
#Produces("text/plain")
public String countREST() {
return String.valueOf(super.count());
}
#Override
protected EntityManager getEntityManager() {
return em;
}
#GET
#Produces("text/html")
public String getGoogleMap() {
// Drag and drop the getGoogleMap operation here
try {
String address = "16 Network Circle, Menlo Park";
java.lang.Integer zoom = 15;
String iframe = "false";
RestResponse result = GoogleMapService.getGoogleMap(address, zoom, iframe);
return result.getDataAsString();
} catch (Exception ex) {
ex.printStackTrace();
}
return "";
}
}
Put the request body part there.If you going to update some entity then you should pass the dto with data which should be updated.I didn't go through your link.this part can be in Json or XML.(like below)
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<prints>
<id>1</id>
<username>test</username>
</prints>
you have to annotate your dto lets say printsDTO as below
#XmlRootElement(name = "prints")
public class PrintsDTO {
private int id;
private String username;
// have getters and setteres for above
}
I used code to insert data to my restful web service using restful client application as follow
NewJerseyClient client = new NewJerseyClient();
Prints p = new Prints();
p.setId(235);
p.setUsername("subhi");
client.create_XML(p);
and this is sufficient for my case

Spring MVC error

I'm pretty much completely new to the world of computer programming, so it's been something of a struggle getting a really in depth understanding of many concepts. Right now, I'm working on a project in which we are implementing Spring MVC. The first step in the project is to make a login page for a website. I've tried modelling mine after one that we did in class, but I can't seem to get past the following error in my web browser:
Unsupported auto value type java.lang.String for field injuryReports.Login.userName
Here is my Login entity class:
package injuryReports;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Login implements Serializable {
private static final long serialVersionUID = 1L;
#Id #GeneratedValue
private String userName;
private String password;
private int userId;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public Login() {
}
public Login(String userName, String password) {
super();
this.userName = userName;
this.password = password;
}
public Login(int userId, String userName2, String password2) {
this.userId = userId;
this.userName = userName2;
this.password = password2;
}
}
My LoginDao Class:
package injuryReports;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
/**
*
* #author nGent
*
*/
#Component
public class LoginDao {
#PersistenceContext private EntityManager em;
#Transactional
public void persist(Login user) {
em.persist(user);
}
public List<Login> getAllUsers() {
TypedQuery<Login> query = em.createQuery(
"Select u FROM Login u ORDER BY u.id", Login.class);
return query.getResultList();
}
public Login validateLogin(String userName, String password) {
Login login = null;
TypedQuery<Login> query = em.createQuery(
"Select u From Login u where u.userName = :userName " +
" and u.password = :password", Login.class).setParameter(
"userName", userName).setParameter("password", password);
try {
login = query.getSingleResult();
}
catch (Exception e) {
//TODO: Handle Exception
}
return login;
}
}
And my LoginController class:
package injuryReports;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class LoginController {
#Autowired
private LoginDao loginDao;
#RequestMapping(value = "/user", method = {RequestMethod.POST})
public ModelAndView userEntry(HttpServletRequest request) {
String userName = request.getParameter("userName");
String password = request.getParameter("password");
if (userName != "" && password != "") {
loginDao.persist(new Login(userName, password));
}
return new ModelAndView("logon.jsp", "loginDao", loginDao);
}
#RequestMapping(value = "/login")
public ModelAndView login(HttpServletRequest request) {
String userName = request.getParameter("userName");
String password = request.getParameter("password");
String page = "login.jsp";
if (userName != "" && password != "") {
try {
Login login = loginDao.validateLogin(userName, password);
if (login != null) {
request.getSession().setAttribute("UserId", login.getUserId());
page = "login.jsp";
}
}
catch (Exception e) {
//TODO: Handle Exception
}
}
return new ModelAndView(page, getDaos());
}
#RequestMapping(value = "/logon", method = {RequestMethod.GET})
public ModelAndView logon(HttpServletRequest request) {
//int userId = (Integer) request.getSession().getAttribute("userId");
//request.getSession().setAttribute("UserID", userId);
return new ModelAndView("logon.jsp", getDaos());
}
public Map<String, Object> getDaos() {
Map<String, Object> models = new HashMap<String, Object>();
models.put("loginDao", loginDao);
return models;
}
}
Sorry this is a bit long- I wanted to provide as much information as possible. I'd really appreciate any help!
You cannot use #GeneratedValue on String property. It uses database sequences or AUTOINCREMENT features depending on the underlying database engine.
Either remove this annotation:
#Id
private String userName;
or use integer/long for id:
#Id #GeneratedValue
private int userId;

Categories