GitlabTicketBuilder.java 6.88 KB
Newer Older
1
package de.hftstuttgart.unifiedticketing.systems.gitlab;
2
3
4
5
6
7

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
8
9
10
11
12
import de.hftstuttgart.unifiedticketing.core.Logging;
import de.hftstuttgart.unifiedticketing.core.TicketBuilder;
import de.hftstuttgart.unifiedticketing.core.TicketSystem;
import de.hftstuttgart.unifiedticketing.exceptions.*;
import de.hftstuttgart.unifiedticketing.exceptions.*;
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import okhttp3.*;

import java.io.IOException;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;

public class GitlabTicketBuilder extends TicketBuilder<GitlabTicketBuilder, GitlabTicket, GitlabTicketSystem>
{
    private static Logger logger = Logging.getLogger(GitlabTicketBuilder.class.getName());

    protected GitlabTicketBuilder(GitlabTicketSystem parent) {
        super(parent);
    }

    @Override
    public GitlabTicketBuilder assignees(String... identifiers)
    {
        try
        {
34
35
            Arrays.stream(identifiers)
                .forEach(Integer::parseInt);
36
37
38
39

        } catch (NumberFormatException e)
        {
            logger.log(Level.SEVERE, String.format("not as integer parsable assignee id encountered!"));
40
41
            if (parent.getConfigTrue(TicketSystem.ConfigurationOptions.RETURN_NULL_ON_ERROR)) return this;
            else throw new AssertionException(e);
42
43
        }

44
        return super.assignees(identifiers);
45
46
47
48
    }

    public GitlabTicketBuilder assignees(int... identifiers)
    {
49
50
51
        return super.assignees(Arrays.stream(identifiers)
            .mapToObj(String::valueOf)
            .toArray(String[]::new));
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
    }

    protected OkHttpClient getHttpClient() { return new OkHttpClient(); }

    /**
     * creates a new ticket with the collected data and retrieves a new ticket instance from
     * the api response
     * @return newly created Ticket as {@link GitlabTicket} instance
     */
    @Override
    public GitlabTicket create()
    {
        logger.log(Level.FINEST, "starting Ticket creation from builder data");

        ObjectMapper mapper = new ObjectMapper()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        ObjectNode body = mapper.createObjectNode();

        if (this.title == null)
        {
            logger.log(Level.SEVERE, "mandatory field title not set before building Ticket");

            if (this.parent.getConfigTrue(TicketSystem.ConfigurationOptions.RETURN_NULL_ON_ERROR)) return null;
            else throw new AssertionException("GitLab Tickets need at-least a title");
        }
78
79

        body.put("title", this.title);
80
81
82
83
84
        logger.log(Level.FINEST, "title set");

        if (this.assignees != null)
        {
            ArrayNode ids = body.putArray("assignee_ids");
85
86
87
88
            assignees
                .stream()
                .mapToInt(Integer::parseInt)
                .forEach(ids::add);
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
            logger.log(Level.FINEST, "assignees set");
        }

        if (this.description != null)
        {
            body.put("description", this.description);
            logger.log(Level.FINEST, "description set");
        }
        if (this.labels != null)
        {
            body.put("labels", this.labels.stream()
                .reduce((l1, l2) -> l1 + "," + l2)
                .orElse(""));
            logger.log(Level.FINEST, "labels set");
        }

        String jsonBody;

        try
        {
            jsonBody = mapper.writeValueAsString(body);
            logger.log(Level.FINER, String.format(
                "body for new Ticket serialized as json:\n%s",
                jsonBody
            ));
        }
        catch (JsonProcessingException e)
        {
            logger.log(Level.SEVERE, "json serialization FAILED");

            if (this.parent.getConfigTrue(TicketSystem.ConfigurationOptions.RETURN_NULL_ON_ERROR)) return null;
            else throw new SerializationException(e);
        }

        OkHttpClient client = getHttpClient();

        Request.Builder builder = new Request.Builder()
            .url(String.format("%s/issues", parent.baseUrl));

        builder.post(RequestBody.create(jsonBody, MediaType.get("application/json")));

        if (this.parent.apiKey != null)
        {
            builder.addHeader("PRIVATE-TOKEN", this.parent.apiKey);
            logger.log(Level.FINEST, "added token authentication header");
        }

        Response response;
        try
        {
            Request request = builder.build();
            logger.log(Level.FINEST, String.format(
                "created request:\n%s",
                (this.parent.apiKey != null)
                    ? request.toString().replace(this.parent.apiKey, "SECRET")
                        : request.toString()
            ));

            response = client.newCall(request).execute();
        }
        catch (IOException e)
        {
            logger.log(Level.SEVERE, "create request FAILED");

            if (this.parent.getConfigTrue(TicketSystem.ConfigurationOptions.RETURN_NULL_ON_ERROR)) return null;
            else throw new HttpReqeustException(e);
        }

        if (response.code() >= 400)
        {
            logger.log(Level.SEVERE, String.format(
                "create request failed with response code %d",
                response.code()
            ));

            if (this.parent.getConfigTrue(TicketSystem.ConfigurationOptions.RETURN_NULL_ON_ERROR)) return null;
            else throw new HttpResponseException(
                String.format("ticket creation failed, error response code %d", response.code()),
                response.code());
        }

        logger.log(Level.FINEST, "response received\n");

        ResponseBody responseBody;
        responseBody = response.body();

        if (responseBody == null)
        {
            logger.log(Level.SEVERE, "create request didn't deliver a body in response");

            if (this.parent.getConfigTrue(TicketSystem.ConfigurationOptions.RETURN_NULL_ON_ERROR)) return null;
            else throw new HttpResponseException("ticket creation failed, no response body", response.code());
        }

        GitlabTicketResponse ticketResponse;
        try
        {
            ticketResponse = mapper.readValue(responseBody.bytes(), GitlabTicketResponse.class);

            logger.log(Level.FINEST, "parsed response body to ticketResponse instance");
        } catch (IOException e)
        {
            logger.log(Level.SEVERE, String.format("parsing update response FAILED with: %s", e.getMessage()));

            if (this.parent.getConfigTrue(TicketSystem.ConfigurationOptions.RETURN_NULL_ON_ERROR)) return null;
            else throw new DeserializationException(e);
        }

        return GitlabTicket.fromTicketResponse(this.parent, ticketResponse);
    }
}