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 getObject(postsSpec + "/" + id, Post.class); } public static List getPosts() throws IOException { return getObjects(postsSpec, Post.class); } public static Post postPost(Post post) throws IOException { return postObject(postsSpec, post, Post.class); } public static User getUser(int id) throws IOException { return getObject(usersSpec + "/" + id, User.class); } public static List getUsers() throws IOException { return getObjects(usersSpec, User.class); } public static User postUser(User user) throws IOException { return postObject(usersSpec, user, User.class); } private static T getObject(String spec, Class classOfObject) throws IOException { return JSONParser.convertToObject(URLConnectionManager.get(spec), classOfObject); } 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(); } private static T postObject(String spec, T object, Class classOfObject) throws IOException { return JSONParser.convertToObject(URLConnectionManager.post(spec, JSONParser.convertToJSON(object)), classOfObject); } }