summaryrefslogtreecommitdiff
path: root/src/main/java/com/mavlushechka/a1qa/utils/JSONPlaceholderAPI.java
blob: 17e2a874790d26c6a6f46fd7bb85532a317640a5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.mavlushechka.a1qa.utils;

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 JSONPlaceholderAPI {

    public static Post getPost(String spec) throws IOException {
        return getObject(spec, Post.class);
    }

    public static List<Post> getPosts(String spec) throws IOException {
        return getObjects(spec, Post.class);
    }

    public static Post postPost(String spec, Post post) throws IOException {
        return postObject(spec, post, Post.class);
    }

    public static User getUser(String spec) throws IOException {
        return getObject(spec, User.class);
    }

    public static List<User> getUsers(String spec) throws IOException {
        return getObjects(spec, User.class);
    }

    public static User postUser(String spec, User user) throws IOException {
        return postObject(spec, user, User.class);
    }

    private static <T> T getObject(String spec, Class<T> classOfObject) throws IOException {
        return JSONParser.convertToObject(URLConnectionManager.get(spec), classOfObject);
    }

    private static <T> List<T> getObjects(String spec, Class<T> classOfObject) throws IOException {
        Object[] objects = JSONParser.convertArray(URLConnectionManager.get(spec), classOfObject);
        ArrayList<T> objectsArrayList = new ArrayList<>();

        for (Object object : objects) {
            objectsArrayList.add((T) object);
        }
        return objectsArrayList.stream().toList();
    }

    private static <T> T postObject(String spec, T object, Class<T> classOfObject) throws IOException {
        return JSONParser.convertToObject(URLConnectionManager.post(spec, JSONParser.convertToJSON(object)), classOfObject);
    }

}