package com.mavlushechka.a1qa.utils; import com.mavlushechka.a1qa.constants.Endpoint; import com.mavlushechka.a1qa.models.Post; import com.mavlushechka.a1qa.models.User; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class JSONPlaceholderAPIManager { private final static String postsSpec = Endpoint.POSTS.getSpec(); private final static String usersSpec = Endpoint.USERS.getSpec(); public static Post getPost(int id) throws IOException { return JSONParser.convertToObject(URLConnectionManager.get(postsSpec + "/" + id), Post.class); } public static int getPostResponseCode(int id, String requestMethod) throws IOException { return URLConnectionManager.getResponseCode(postsSpec + "/" + id, requestMethod); } public static List getPosts() throws IOException { return getObjects(postsSpec, Post.class); } public static int getPostsResponseCode(String requestMethod) throws IOException { return URLConnectionManager.getResponseCode(postsSpec, requestMethod); } public static Post postPost(Post post) throws IOException { return JSONParser.convertToObject(URLConnectionManager.post(postsSpec, JSONParser.convertToJSON(post)), Post.class); } public static User getUser(int id) throws IOException { return JSONParser.convertToObject(URLConnectionManager.get(usersSpec + "/" + id), User.class); } public static List getUsers() throws IOException { return getObjects(usersSpec, User.class); } public static int getUsersResponseCode(String requestMethod) throws IOException { return URLConnectionManager.getResponseCode(usersSpec, requestMethod); } private static List getObjects(String spec, Class classOfObject) throws IOException { Object[] objects = JSONParser.convertArray(URLConnectionManager.get(spec), classOfObject); ArrayList objectsArrayList = new ArrayList<>(); for (Object object : objects) { objectsArrayList.add((T) object); } return objectsArrayList.stream().toList(); } }