Rest Webservice returning http status 404 - java

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

Related

Getting internal server error - #XmlRootElement

I have this Model class:
package org.myapp.model;
import java.util.Date;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name="Message")
#XmlAccessorType(XmlAccessType.FIELD)
public class Message {
public long id;
public String message;
public Date created;
public String author;
public Message() {
}
public Message(long id,String message, String author) {
this.id = id;
this.message = message;
this.author = author;
this.created = new Date();
}
#XmlElement
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
#XmlElement
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
#XmlElement
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
The Service Class:
package org.myapp.services;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.myapp.model.Message;
public class MessageService {
public List<Message> getAllMessages(){
Message msg1 = new Message(1L,"How are you?", "natalie");
Message msg2 = new Message(2L,"How are you?", "amir");
List<Message> msglist = new ArrayList<Message>();
msglist.add(msg1);
msglist.add(msg2);
return msglist;
}
}
The Resource Class:
package org.myapp.resource;
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;
import org.myapp.model.Message;
import org.myapp.services.MessageService;
#Path("messageresource")
public class MessageResource {
MessageService messageService = new MessageService();
#GET
#Produces(MediaType.APPLICATION_XML)
public List<Message> getMessage() {
return messageService.getAllMessages(); //"app chal rhi hai!";
}
#GET
#Produces(MediaType.APPLICATION_XML)
#Path("/{messageId}")
public String getMessageID(#PathParam("messageId") String messageId) {
Message message = new Message(1L,"How are you?", "natalie");
return message.getMessage()+", "+messageId;
}
}
I am trying to print the data in Service(MessageService) class in an XML format. I think, the error is being caused because the return value of this class' method (return type List<Message>) and the tag #XMLRootElement on the top of the Model (Message) class are not consistent. I tried different MediaType properties but nothing helped.
When I am accessing this path : localhost:8080/messengerapp/webapi/messageresource
I am getting this error - Internal Server Error
I have just started to learn to write web services.I have tried different ways to get around this problem but nothing is helping me. Please help me understand and solve this.
try with this,
annotate the root element of xml
#XmlRootElement (name="Messages")
public class MessageService implements Serializable{
private List<Message> msglist = new ArrayList<Message>();
public List<Message> getAllMessages(){
Message msg1 = new Message(1L,"How are you?", "natalie");
Message msg2 = new Message(2L,"How are you?", "amir");
msglist.add(msg1);
msglist.add(msg2);
return msglist;
}
public void setAllMessages(List<Message> msglist){
this.msglist = msglist;
}
}
structure of the xml
<Messages> <!-- root element of xml -->
<Message>
...
</Message>
<Message>
...
</Message>
</Messages>

Cannot upload deployment On WildFly 11

I have a problem that is driving crazy the last few days.
I am trying to deploy a webapp in wildfly and I am getting the following error :
Cannot upload deployment: {"WFLYCTL0080: Failed services" => {"jboss.undertow.deployment.default-server.default-host./webapp" => "com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes. Caused by: com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes."}}
This is my class
package com.stavros.ticketmanagement.rest;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Application;
import com.stavros.ticketmanagement.domain.Ticket;
#Path("/tickets")
public class TicketResource extends Application {
#GET
#Produces("application/xml")
public List<Ticket> getAllTickets(){
List<Ticket> results= new ArrayList<Ticket>();
results.add(new Ticket(1, "TestName", "Test time", 100, 0));
results.add(new Ticket(2, "TestName2", "Test time2", 102, 0));
return results;
}
}
This is my web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>
javax.faces.webapp.FacesServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<!-- Configuration for JAX-RS -->
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.stavros.ticketmanagement.rest</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/webservice/*</url-pattern>
</servlet-mapping>
</web-app>
This is the Ticket class which I use in TicketResource
//Domain class. A class that represents the actual real word object (in this case a ticket)
package com.stavros.ticketmanagement.domain;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.xml.bind.annotation.XmlRootElement;
#Entity //Make the class usable from JPA (We store data to db with this class)
#XmlRootElement
public class Ticket implements java.io.Serializable {
public Ticket() {
//required by JPA but not used
super();
}
#Id //Used from JPA as primary key
#GeneratedValue(strategy=GenerationType.AUTO)
private int ticketId;
private String eventName;
private String eventTime;
private int price;
private int isReserved;
#OneToMany(cascade=CascadeType.MERGE) // in the events of an un-persistence obj being found in the Nnotes collection jpa is free to automatically call persist on that obj
private Set<Note> notes; //this is used to keep a reference of the relative notes to each ticket. Its a collection (Set is better for DBs)Set: collection on obj with no particular order and no duplicate obj
// #ManyToOne //(cascade=CascadeType.PERSIST) // this should be manytoone
// private Set<User> users;
public Ticket(int ticketId, String eventName, String eventTime, int price, int isReserved) {
super();
this.notes = new HashSet<Note>();
this.ticketId = ticketId;
this.eventName = eventName;
this.eventTime = eventTime;
this.price = price;
this.isReserved = isReserved;
}
public int getTicketId() {
return ticketId;
}
public void setTicketId(int ticketId) {
this.ticketId = ticketId;
}
public String getEventTime() {
return eventTime;
}
public void setEventTime(String eventTime) {
this.eventTime = eventTime;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getIsReserved() {
return isReserved;
}
public void setIsReserved(int isReserved) {
this.isReserved = isReserved;
}
public Set<Note> getNotes() {
return notes;
}
public void setNotes(Set<Note> notes) {
this.notes = notes;
}
public String getEventName() {
return eventName;
}
//this is what the find*Ticket will return in TestHarness
public String toString() {
return "Ticket [ticketId=" + ticketId + ", eventName=" + eventName + ", eventTime=" + eventTime + ", price="+ price + ", isReserved=" + isReserved + "]";
}
//Regular methods, for example -10% to a ticket
public void setEventName(String newEventName) {
this.eventName = newEventName; //updates the eventName in the db
}
//bsn methods
//add a note
public void addNote(String newNoteText) {
Note newNote=new Note(newNoteText);
this.notes.add(newNote);
}
//add a user
// public void addUser(int userId, String userName, String password, String email, int accessLevel) {
// User newUser=new User(userId, userName, password, email, accessLevel);
// this.users.add(newUser);
// }
public Set<Note> getAllNotes() {
// TODO Auto-generated method stub
return this.notes;
}
}
I have tried every possible solution I found. The paths inside the web.xml are correct.
Here is a photo of my libs.
Thank you very much in advance for your help.!

Getting 404 error while accessing a restful web service

I have created a simple UserManagement restful web service. in which I have created 3 classes. The source codes are as following.
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(){
List<User> userList = null;
try {
File file = new File("Users.dat");
if (!file.exists()) {
User user = new User(1, "Mahesh", "Teacher");
userList = new ArrayList<User>();
userList.add(user);
saveUserList(userList);
}
else{
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
userList = (List<User>) ois.readObject();
ois.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return userList;
}
private void saveUserList(List<User> userList){
try {
File file = new File("Users.dat");
FileOutputStream fos;
fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(userList);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
UserService class
package com.tutorialspoint;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("/UserService")
public class UserService {
UserDao userDao = new UserDao();
#GET
#Path("/users")
#Produces(MediaType.APPLICATION_XML)
public List<User> getUsers(){
return userDao.getAllUsers();
}
}
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>User Management</display-name>
<servlet>
<servlet-name>Jersey RESTful Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer </servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.tutorialspoint</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Jersey RESTful Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
Then I have created its war and deployed in Tomcat and start the Tomcat
But when I am accessing this restfull web service by hitting the url http://localhost:8080/UserManagement/rest/UserService/users
using Postman it gives 404 error.
Please some one help me out on this.
Try change servlet class with com.sun.jersey.spi.container.servlet.ServletContainer .

Internal Server Error - Tomcat & Jersey

I'm trying to go through the following tutorial, but I keep getting an error:
https://www.tutorialspoint.com/restful/restful_first_application.htm
When I try to acces the following link I get an HTTP Status 500 - Interval Server Error:
http://localhost:8080/NoteMandatory/rest/NoteService/notes
This is the error description I get:
org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor aroundWriteTo SEVERE: MessageBodyWriter not found for media type=application/xml, type=class java.util.ArrayList, genericType=java.util.List.
The project folder:
Note.java:
package com.note;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "note")
public class Note implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String title;
private String text;
public Note(){
}
public Note(int id, String title, String text){
this.id = id;
this.title = title;
this.text = text;
}
//Getters
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public String getText() {
return text;
}
//Setters
#XmlElement
public void setId(int id) {
this.id = id;
}
#XmlElement
public void setTitle(String title) {
this.title = title;
}
#XmlElement
public void setText(String text) {
this.text = text;
}
}
NoteDataAccess.java:
public class NoteDataAccess {
public List<Note> getAllNotes(){
List<Note> noteList = null;
try {
File file = new File("Notes.dat");
if (!file.exists()) {
Note note = new Note(1, "Remember this", "Buy milk and do homework");
noteList = new ArrayList<Note>();
noteList.add(note);
saveNoteList(noteList);
}else{
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
noteList = (List<Note>) ois.readObject();
ois.close();
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("NoteDataAccess_getAllNotes Exception 1");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("NoteDataAccess_getAllNotes Exception 2");
}
return noteList;
}
private void saveNoteList(List<Note> noteList){
try {
File file = new File("Notes.dat");
FileOutputStream fos;
fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(noteList);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("NoteDataAccess_saveNoteList Exception 1");
} catch (IOException e) {
e.printStackTrace();
System.out.println("NoteDataAccess_saveNoteList Exception 2");
}
}
}
NoteService.java:
package com.note;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.annotation.XmlElement;
import org.apache.tomcat.jni.User;
#Path("/NoteService")
public class NoteService {
NoteDataAccess theNoteDataAccess = new NoteDataAccess();
#GET
#Path("/notes")
#Produces(MediaType.APPLICATION_XML)
public List<Note> getNotes(){
return theNoteDataAccess.getAllNotes();
}
}
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>NoteMandatory</display-name>
<servlet>
<servlet-name>Jersey RESTful Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.note</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Jersey RESTful Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
Jersey jar files:
I think the problem is that you are returning a list into an XML format. Jersey has trouble with this and you want to wrap it with a GenericEntity:
import javax.ws.rs.core.GenericEntity;
...
public class NoteService {
NoteDataAccess theNoteDataAccess = new NoteDataAccess();
#GET
#Path("/notes")
#Produces(MediaType.APPLICATION_XML)
public Response getNotes(){
List<Note> notes = theNoteDataAccess.getAllNotes();
GenericEntity<List<Note>> entity = new GenericEntity<List<Note>>(Lists.newArrayList(notes)) {};
return Response.ok().entity(entity).build();
}
See this SO Question.

JAX-RS REST API Basic Authentication

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.

Categories