complete MovieService class

This commit is contained in:
2026-04-30 12:30:18 +03:30
parent 3f86160361
commit 3c3d1d73b3
+231 -77
View File
@@ -11,6 +11,8 @@ import java.net.http.HttpResponse;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.InputMismatchException;
public class MovieService {
@@ -87,105 +89,257 @@ public class MovieService {
}
}
/**
* TODO 1: Display movies for a specific genre and page
*
* Open this link in your browser (and check Pretty-print checkbox) to view json format:
* https://api.meshcomp.ir/api/v1/genres/1/movies
*
* Steps:
* - Call getMoviesByGenreList(genreId, page) to get JSON
* - Parse JSON to JsonObject
* - Get "movies" array (NOT "data")
* - Loop through array and print: "ID: {id} | {title} ({year})"
* - Also print total and total_pages
*
* PUT ALL PARSING CODE INSIDE try-catch
*/
public void displayMoviesByGenre(Long genreId, Long page) {
// TODO: Write your code here
// All parsing code must be inside try-catch
try {
// Your code here
public List<Movie> parseMoviesFromJson(String json)
{
if (json == null || json.isEmpty())
{
return new ArrayList<>();
}
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<Movie>>() {}.getType();
return gson.fromJson(json, listType);
}
} catch (Exception e) {
System.err.println("ERROR: " + e.getMessage());
public void displayListOfMovies()
{
Scanner scanner = new Scanner(System.in);
Long selectedGenreId = null;
System.out.println("---Select a genre---");
displayGenres();
System.out.println("Enter the genre ID to view movies or 0 to exit: ");
try
{
if (scanner.hasNextLong())
{
selectedGenreId = scanner.nextLong();
}
else
{
System.out.println("Invalid! Enter a number.");
return;
}
}
catch (InputMismatchException e)
{
System.out.println("Invalid input. Please enter a number.");
scanner.next();
return;
}
if (selectedGenreId == 0)
{
return;
}
System.out.println("----Movies for genre ID: " + selectedGenreId + "----");
Long page = 1L;
try
{
String json = getMoviesByGenreList(selectedGenreId, page);
if (json == null || json.isEmpty())
{
System.out.println("No movies found.");
return;
}
JsonObject rootObject = JsonParser.parseString(json).getAsJsonObject();
JsonArray moviesArray = rootObject.getAsJsonArray("movies");
if (moviesArray == null || moviesArray.isEmpty())
{
System.out.println("No movies found.");
return;
}
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<Movie>>() {}.getType();
List<Movie> movies = gson.fromJson(moviesArray, listType);
if (movies != null && !movies.isEmpty())
{
for (Movie movie : movies)
{
System.out.println("ID: " + movie.getId() + " | " + movie.getTitle() + " (" + movie.getYear() + ")");
}
}
else
{
System.out.println("No movies found for this genre.");
}
}
catch (Exception e)
{
System.err.println("ERROR displaying movies: " + e.getMessage());
e.printStackTrace();
}
}
public void displayMoviesByGenre(Long genreId, Long page) {
try
{
String json = getMoviesByGenreList(genreId, page);
JsonObject rootObject = JsonParser.parseString(json).getAsJsonObject();
JsonArray moviesArray = rootObject.getAsJsonArray("movies");
if (moviesArray == null || moviesArray.isEmpty())
{
System.out.println("No movies found for this genre/page.");
return;
}
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<Movie>>() {}.getType();
List<Movie> movies = gson.fromJson(moviesArray, listType);
if (rootObject.has("total"))
{
int total = rootObject.get("total").getAsInt();
System.out.println("Total movies: " + total);
}
if (rootObject.has("total_pages"))
{
int totalPages = rootObject.get("total_pages").getAsInt();
System.out.println("Total pages: " + totalPages);
}
System.out.println("\n====================");
for (Movie movie: movies)
{
System.out.println("ID: " + movie.getId() + " | " + movie.getTitle() + " (" + movie.getYear() + ")");
}
System.out.println("--------------------\n");
}
catch (Exception e)
{
System.err.println("ERROR parsing movie list: " + e.getMessage());
e.printStackTrace();
}
}
/**
* BONUS: Fetch movie details from API using movie ID
* URL format: https://api.meshcomp.ir/api/v1/movies/{movieId}
*/
private String getMovieById(Long movieId) {
try {
// TODO: Complete this method
// String url = MOVIE_BY_ID_URL + movieId;
// HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url)).build();
// HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
// if (response.statusCode() == 200) return response.body();
return null;
String url = MOVIE_BY_ID_URL + movieId;
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
return response.body();
} else
{
System.out.println("HTTP error code for movie ID " + movieId + ": " + response.statusCode());
return null;
}
} catch (Exception e) {
System.out.println("!!Exception : " + e.getMessage());
}
return null;
}
/*
BONUS TODO: Display complete movie details for a given movie ID
Open this link in your browser (and check Pretty-print checkbox) to view json format:
https://api.meshcomp.ir/api/v1/movies/1
INSTRUCTIONS:
1. Call getMovieById(movieId) to get the JSON response string
2. Check if response is null (if yes, print error and return)
3. Parse the JSON string to JsonObject (inside try-catch)
4. Use Gson to extract all fields from the JSON and map them to your Movie class:
- Add missing JSON fields to your Movie class first (actors, awards, director,
imdb_id, imdb_votes, metascore, plot, rated, released, runtime, type, writer)
- Then use Gson to parse your json string
5. Print all movie details in a readable format
(PUT ALL PARSING CODE INSIDE THE EXISTING try-catch)
*/
/* EXAMPLE OUTPUT:
=======================================================================
THE SHAWSHANK REDEMPTION (1994)
=======================================================================
Rating: 9.3/10 | Votes: 1,738,596
Director: Frank Darabont
Cast: Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler
Genre: Crime, Drama
Runtime: 142 min | Rated: R
Country: USA | Released: 14 Oct 1994
Plot: Two imprisoned men bond over a number of years, finding
solace and eventual redemption through acts of common decency.
Awards: Nominated for 7 Oscars. Another 19 wins & 30 nominations.
=======================================================================
*/
public void displayMovieDetails(Long movieId) {
// Step 1: Get JSON response from API
String jsonResponse = getMovieById(movieId);
// Step 2: Check if we got valid data
// Step 3-5: Parse JSON and display details (PUT YOUR CODE INSIDE try-catch)
if (jsonResponse == null) {
System.out.println("Failed to get movie details for ID: " + movieId);
return;
}
try {
// TODO: Parse jsonResponse to JsonObject
// HINT: Use JsonParser.parseString(jsonResponse).getAsJsonObject()
// TODO: use Gson to parse the json
// Your code here:
} catch (Exception e) {
JsonObject rootObject = JsonParser.parseString(jsonResponse).getAsJsonObject();
Movie movie;
if (rootObject.has("movie"))
{
String movieJson = rootObject.get("movie").toString();
movie = new Gson().fromJson(movieJson, Movie.class);
} else
{
movie = new Gson().fromJson(jsonResponse, Movie.class);
}
if (movie == null)
{
System.err.println("Error: Movie object could not be parsed.");
return;
}
int width = 60;
String title = (movie.getTitle() != null ? movie.getTitle() : "Unknown Title");
String year = (movie.getYear() != null ? movie.getYear() : "");
String titleYear = title + (year.isEmpty() ? "" : " (" + year + ")");
if (titleYear.length() > width) {
width = titleYear.length() + 10;
}
int totalPadding = width - titleYear.length();
int leftPadding = totalPadding / 2;
int rightPadding = totalPadding - leftPadding;
String centeredTitle = " ".repeat(leftPadding) + titleYear.toUpperCase() + " ".repeat(rightPadding);
System.out.println("=============================================================");
System.out.println(centeredTitle);
System.out.println("=============================================================");
if (movie.getImdb_rating() != null && !movie.getImdb_rating().isEmpty())
{
try
{
double rating = Double.parseDouble(movie.getImdb_rating());
System.out.printf("Rating: %.1f/10", rating);
if (movie.getImdb_votes() != null && !movie.getImdb_votes().isEmpty())
{
String votesStr = movie.getImdb_votes().replace(",", "");
long votes = Long.parseLong(votesStr);
System.out.printf(" | Votes: %,d%n", votes);
} else
{
System.out.println();
}
} catch (NumberFormatException e)
{
System.out.println("Rating: " + movie.getImdb_rating() + " (Format Error)");
}
} else
{
System.out.println("Rating: N/A");
}
if (movie.getDirector() != null)
{
System.out.println("Director: " + movie.getDirector());
}
if (movie.getActors() != null)
{
System.out.println("Cast: " + movie.getActors());
}
if (movie.getGenres() != null && !movie.getGenres().isEmpty())
{
String genresStr = String.join(" , ", movie.getGenres());
System.out.println("Genre: " + genresStr);
} else
{
System.out.println("Genre: N/A");
}
if (movie.getRuntime() != null)
{
System.out.println("Runtime: " + movie.getRuntime() + " | Rated: " + movie.getRated());
}
if (movie.getCountry() != null)
{
System.out.println("Country: " + movie.getCountry() + " | Released: " + movie.getReleased());
}
if (movie.getPlot() != null)
{
System.out.println("Plot: " + movie.getPlot());
}
if (movie.getAwards() != null)
{
System.out.println("Awards: " + movie.getAwards());
}
System.out.println("=======================================================================");
} catch (Exception e)
{
System.err.println("ERROR parsing movie details: " + e.getMessage());
}
}