Click here to Skip to main content
15,888,313 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to create rest client which allows the user to insert, update and delete film from the database. I keep getting 500 internal server error not sure what's wrong with the code. Can someone help please.

What I have tried:

I have searched online to find out what 500 internal server error is, nothing is showing.

FilmsResourse.java:
package com.democo.jersey.film.resources;


import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
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.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import com.democo.jersey.film.model.Film;
import com.democo.jersey.film.model.FilmDAO;


// Will map the resource to the URL films
@Path("/films")
// Creating public class FilmsResource
public class FilmsResource {
	// Allows to insert contextual objects into the class, 
	// e.g. ServletContext, Request, Response, UriInfo
	@Context
	UriInfo uriInfo;
	@Context
	Request request;


	// Return and get the list of films to the user in the browser
	@GET
	// Creating media type for the text_xml
	@Produces(MediaType.TEXT_XML)
	// Calling the getFilmsBrowser method and calling the list of films
	public List<Film> getFilmsBrowser() {
		// Creating new rray list of film
		List<Film> films = new ArrayList<Film>();
		// Adding all the films and calling the filmdao class.
		// Get instance and calling the getModel method 
		films.addAll( FilmDAO.getInstance().getModel().values());
		// Return the films
		return films; 
	} // CLose public getFilmsBrowser method

	// Return the list of films for applications
	@GET
	// Creating media type for the xml and json
	@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	// Creating public getFilms method
	public List<Film> getFilms() {
		// Creating new array list of films
		List<Film> films = new ArrayList<Film>();
		// Calling the film class and filmdao to get the instance and getting the model for the id
		// add all films
//		films.addAll( FilmDAO.instance.getModel().values() );
		films.addAll( FilmDAO.getAllFilms());
		// Return the films
		return films; 
	} // Close public getFilms method


	// Returns the number of films
	// Use http://localhost:8080/com.democo.jersey.film/rest/todos/count
	// to get the total number of records
	@GET
	@Path("count")
	@Produces(MediaType.TEXT_PLAIN)
	// Creating public string for the getCount method
	public String getCount() {
		// Creating integer count equal to filmdao to get the instance and calling the getModel in the filmDao class
		int count = FilmDAO.getInstance().getModel().size();
		// Return the strint value of the count
		return String.valueOf(count);
	} // Close get Count method
	

	// Posting the film using the form
	@POST
	// Creating media type for the text_html and media type for the application form
	@Produces(MediaType.TEXT_HTML)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	// Creating new film
	public void newFilm(
			// Creating form params for the different columns
			@FormParam("id") int id,
			@FormParam("title") String title,
			@FormParam("year") int year,
			@FormParam("director") String director,
			@FormParam("stars") String stars,
			@FormParam("review") String review,
			@Context HttpServletResponse servletResponse
			) throws IOException {
		// Creating new film
		Film film = new Film(id,title,year, director, stars, review);
		// If the title is not equal to null, return the title
		if (title!=null){
			film.setTitle(title);
		} // Close if statement for title not equal to null
		// Calling the filmdao to get the instance and calling the getModel method to update the film using the id
		FilmDAO.getInstance().getModel().put(id+"", film);
		// Calling the create_film.html for the servletResponse
		servletResponse.sendRedirect("../create_film.html");
	} // Close public void new film


	// Defines that the next path parameter after film is
	// treated as a parameter and passed to the FilmResources
	// Allows to type http://localhost:8080/com.democo.jersey.film/rest/films/1
	// 1 will be treated as parameter film and passed to FilmResource
	@Path("{film}")
	@Produces(MediaType.TEXT_XML)
	public FilmResource getFilm(
			// Creating path param for the film and getting string id
			@FormParam("film") String id) {
		// Setting int id equal to 0
		int intId=0;
		// Creating try and catch for the int id and return new FilmResource 
		try{
			intId=Integer.parseInt(id);
		}catch(Exception e){}
		return new FilmResource(uriInfo, request, intId);
	} // Close public FilmResource for the get film
} // Close public class FilmsResource



FilmResourse.java:
package com.democo.jersey.film.resources;


import java.util.ArrayList;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
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.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;

import com.democo.jersey.film.model.Film;
import com.democo.jersey.film.model.FilmDAO;
/**
 * Creating film resource for the crdue mthods.
 * create, retrieve, update and delte
 * Retrive would get all the films on the browser
 * Update(put) would allow to update film.
 * Delete would delete the film from the database based on id
 * @author Dhanyaal. 
 */

//@Path("films")
public class FilmResource {
	// Creating new film dao and calling the FilmDAO class
	// it asks the dao and then prints out the list of films

	FilmDAO dao = new FilmDAO();
	// Creating context and creating variables for the UriInfo
	// Allows to insert contextual objects into the class, 
	// e.g. ServletContext, Request, Response, UriInfo
	@Context
	UriInfo uriInfo;
	// Creating another context and creating variable for the request and int id
	@Context
	Request request;
	int id;

	//TODO function added
	//	// Getting all films from the array list
	//	ArrayList<Film> FilmList = FilmDAO.getAllFilms();	
	//	// Creating form loop for one film and then printing out the film
	//	for (int i=0; i<FilmList.size(); i++ ) {
	//		// Get film
	//		Film oneFilm = FilmList.get(i);
	//		// Print films out onto the console
	//		System.out.println(oneFilm.toString());
	//		System.out.println("All data displayed successfully");
	//	} // Close for loop
	
	// Creating public FilmResource method
	public FilmResource(UriInfo uriInfo, Request request, int id) {
		this.uriInfo = uriInfo;
		this.request = request;
		this.id = id;
	} // Close public FilmResource method

	//getAllFilms
	@GET
	@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	@Path("/allFilms")
	public ArrayList<Film> getAllFilms(){
		return FilmDAO.getAllFilms();
	}


	//getFilmsMatching
	@GET
	@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	@Path("/search/{search}")
	public ArrayList<Film> getFilmsMatching(@PathParam("search") String search){

		ArrayList<Film> films = FilmDAO.getFilmsMatching(search);

		if(films==null) {
			throw new RuntimeException("Get: Film containing " + search +  " not found");
		}

		return films;
	}

	// For the browser
	// Getting/reading the film on the browser
	@GET
	// Creating media type for the text_xml
	@Produces(MediaType.TEXT_XML)
	// Creating public film for the get film html
	public Film getFilmHTML() {
		// Calling the film class and filmdao to get the instance and getting the model for the id
		Film film = FilmDAO.getInstance().getModel().get(id);
		// If statement for film equal to null
		if(film==null)
			throw new RuntimeException("Get: film with " + id +  " not found");
		// Return the film
		return film;
	} // Close getFilmHTML method

	// Creating put to Update/Replace film
	@PUT
	// Creating media type for the putFIilm and creating media type for the xml
	@Consumes(MediaType.APPLICATION_XML)
	// Creating putFIilm method for the jax b element and callin ghte film class
	public Response putFIilm(JAXBElement<Film> film) {
		// getting value from the film class
		Film f = film.getValue();
		// Return the put and get responce
		return putAndGetResponse(f);
	} // CLose put film method

	// Creating delete to delete the film
	@DELETE
	// Creating public void deleteFilm method which would delete the film from the database
	public void deleteFilm() {
		// Calling the film class and filmdao to get the instance and getting the model.
		// removing the id from the database to delete the film
		Film f = FilmDAO.getInstance().getModel().remove(id);
		// If statement for f equal to null
		if(f==null)
			throw new RuntimeException("Delete: film with " + id +  " not found");
	} // Close delete film method

	// Creating public response for the put and get
	private Response putAndGetResponse(Film film) {
		// Variable for the response
		Response res;
		// if filmdao.instance get model contains key get the id
		if(FilmDAO.instance.getModel().containsKey(film.getId())) {
			// Creating res variable equal to response.noContent
			res = Response.noContent().build();
		} // Close if statement
		// Otherwise response.created
		else {
			res = Response.created(uriInfo.getAbsolutePath()).build();
		} // CLose else
		// Update the film
		FilmDAO.getInstance().getModel().put(film.getId()+"", film);
		// return response
		return res;
	} // Close private putAndGetResponse
}



Tester.java:
package com.democo.jersey.film.client;

import java.net.URI;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import com.democo.jersey.film.model.Film;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.representation.Form;



public class Tester {
	public static void main(String[] args) {
		ClientConfig config = new DefaultClientConfig();
		Client client = Client.create(config);
//		URI url=new URI("com.democo.jersey.film");
//		System.out.print(getBaseURI());
		WebResource service = client.resource(getBaseURI());
		// Create one todo
		Film film = new Film(123456, 
				"Four Lions",
				2010,
				"Chris Morris, Omar, Hassan, Barry, Waj and Faisal",
				"Chris Morris, Omar, Hassan, Barry, Waj and Faisal",
				"Four Lions is an English movie released on 07 May, 2010. The movie is directed by Christopher Morris and featured Will Adamsdale and Adeel Akhtar as lead characters.");
//		ClientResponse response = service.path("rest").path("films").path(film.getId()+"").accept(MediaType.APPLICATION_XML).put(ClientResponse.class, film);
		ClientResponse response = service.path("rest").path("films").accept(MediaType.APPLICATION_XML).put(ClientResponse.class, film);
		// Return code should be 201 == created resource
		System.out.println(response.getStatus());
		// Get the films
		System.out.println(service.path("rest").path("films").accept(
				MediaType.TEXT_XML).get(String.class));
		// Get XML for application
		System.out.println(service.path("rest").path("films").accept(
				MediaType.APPLICATION_JSON).get(String.class));
		// Get JSON for application
		System.out.println(service.path("rest").path("films").accept(
				MediaType.APPLICATION_XML).get(String.class));

		// Get the fim with id 1
		System.out.println(service.path("rest").path("films/1").accept(
				MediaType.APPLICATION_XML).get(String.class));
		// get film with id 1
		service.path("rest").path("films/3").delete();
		// Get all films, id 1 should be deleted
		System.out.println(service.path("rest").path("films").accept(
				MediaType.APPLICATION_XML).get(String.class));

		// Create a film
		Form form = new Form();
		form.add("id", 12345666);
		form.add("title", "One film");
		form.add("year", 2019);
		form.add("director", "Dhany");
		form.add("stars", "Dhany and John");
		form.add("review", "5 star");
		// add the film
		response = service.path("rest").path("films").type(MediaType.APPLICATION_FORM_URLENCODED)
				.post(ClientResponse.class, form);
		// Print response
		System.out.println("Form response " + response.getEntity(String.class));
		// Get the all films, id 4 should be created
		System.out.println(service.path("rest").path("films").accept(
				MediaType.APPLICATION_XML).get(String.class));
	} // CLose main method
	
	// Creating privte static URI to get the base uri
	private static URI getBaseURI() {
		// Return the uri builder from the uro
		return UriBuilder.fromUri(
				"http://localhost:8080/com.democo.jersey.film").build();
	} // Close private static uri get base uri
} // Close public class tester




Index.html:

<!DOCTYPE html>
<html>
<head>
<!--- Creating a heading for the form to create new film in the application -->
<h1>INSERT A FILM</h1>
<title>Form to create a new film</title>
<link rel="stylesheet" href="css/styles.css" type="text/css" />
</head>
<body>
	<!-- 	<form actsion="ControlInsertFilm" method="POST"> -->
	<form action="/com.democo.jersey.film/rest/films" method="POST">
		<label for="id">ID</label> <input name="id" value='"getId()"' /> <br />
		<label for="title">title</label> <input name="title"
			value='"getTitle()"' /> <br /> <label for="year">year</label> <input
			name="year" value='"getYear()"' /> <br /> <label for="director">director</label>
		<input name="director" value='"getDirector()"' /> <br /> <label
			for="stars">stars</label> <input name="stars" value='"getStars()"' />
		<br /> <label for="review">review</label> <input name="review"
			value='"get()"' /> <br /> <input type="submit" value="Submit" />
	</form>
</body>
</html>
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900