Files
HW-03-oop-and-api-T/src/main/java/movie/apis/MovieService.java
T
2026-04-24 17:31:09 +03:30

188 lines
6.5 KiB
Java

package movie.apis;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class MovieService {
private final static String GENRES_URL = "https://api.meshcomp.ir/api/v1/genres";
private final static String MOVIE_BY_ID_URL = "https://api.meshcomp.ir/api/v1/movies/";
private final static HttpClient client = HttpClient.newHttpClient();
private String getGenresList() {
try {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(GENRES_URL))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
System.out.println("Genres List received successfully");
return response.body();
} else {
throw new IOException("HTTP error code: " + response.statusCode());
}
} catch (Exception e) {
System.out.println("!!Exception : " + e.getMessage());
}
return null;
}
private String getMoviesByGenreList(Long genreId, Long page) {
try {
String url = "https://api.meshcomp.ir/api/v1/genres/" + genreId + "/movies?page=" + page;
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: " + response.statusCode());
return null;
}
} catch (Exception e) {
System.out.println("!!Exception : " + e.getMessage());
}
return null;
}
public void displayGenres() {
String jsonResponse = getGenresList();
if (jsonResponse == null) {
System.out.println("Failed to get genres");
return;
}
try {
JsonObject rootObject = JsonParser.parseString(jsonResponse).getAsJsonObject();
JsonArray genresArray = rootObject.getAsJsonArray("genres");
Type genreListType = new TypeToken<ArrayList<Genre>>(){}.getType();
Gson gson = new Gson();
List<Genre> genres = gson.fromJson(genresArray, genreListType);
System.out.println("\nALL GENRES:");
for (Genre genre : genres) {
System.out.println(genre.getId() + ". " + genre.getName());
}
System.out.println();
} catch (Exception e) {
System.err.println("ERROR parsing genres: " + e.getMessage());
}
}
/**
* TODO 1: Display movies for a specific genre and page
*
* JSON format: { "movies": [ { "id": 1, "title": "Movie", "year": "1994" } ], "total": 177, "total_pages": 18 }
*
* 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
} catch (Exception e) {
System.err.println("ERROR: " + e.getMessage());
}
}
/**
* 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;
} catch (Exception e) {
System.out.println("!!Exception : " + e.getMessage());
}
return null;
}
/**
* BONUS TODO: Display complete movie details for a given movie ID
*
* Expected JSON format from getMovieById():
* {
* "id": 1,
* "title": "The Shawshank Redemption",
* "year": "1994",
* "genres": ["Crime", "Drama"],
* "poster": "https://moviesapi.ir/images/tt0111161_poster.jpg",
* "country": "USA",
* "imdb_rating": "9.3"
* }
*
* INSTRUCTIONS:
* 1. Call getMovieById(movieId) to get the JSON response
* 2. Check if response is null (if yes, print error and return)
* 3. Parse the JSON string to JsonObject (inside try-catch)
* 4. Extract all fields: id, title, year, genres array, poster, country, imdb_rating
* 5. Convert genres array to comma-separated string
* 6. Print all movie details in a readable format
*
* PUT ALL PARSING CODE INSIDE THE EXISTING try-catch
*
* @param movieId The ID of the movie to display
*/
public void displayMovieDetails(Long movieId) {
// Step 1: Get JSON response from API
String jsonResponse = getMovieById(movieId);
// Step 2: Check if we got valid data
if (jsonResponse == null) {
System.out.println("Failed to get movie details for ID: " + movieId);
return;
}
// Step 3-6: Parse JSON and display details (PUT YOUR CODE INSIDE try-catch)
try {
// TODO: Parse jsonResponse to JsonObject
// TODO: Extract id, title, year, genres array, poster, country, imdb_rating
// TODO: Convert genres array to a readable string
// TODO: Print all movie details
// HINT: Use JsonParser.parseString(jsonResponse).getAsJsonObject()
// HINT: Use getAsJsonArray("genres") to get genres
// HINT: For each genre, use getAsString()
// Your code here:
} catch (Exception e) {
System.err.println("ERROR parsing movie details: " + e.getMessage());
}
}
}