GithubTicket.java 8.88 KB
Newer Older
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package de.hftstuttgart.unifiedticketing.systems.github;

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;
import de.hftstuttgart.unifiedticketing.core.Logging;
import de.hftstuttgart.unifiedticketing.core.Ticket;
import de.hftstuttgart.unifiedticketing.core.TicketSystem;
import de.hftstuttgart.unifiedticketing.exceptions.DeserializationException;
import de.hftstuttgart.unifiedticketing.exceptions.HttpReqeustException;
import de.hftstuttgart.unifiedticketing.exceptions.HttpResponseException;
import de.hftstuttgart.unifiedticketing.exceptions.SerializationException;
import okhttp3.*;

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

public class GithubTicket extends Ticket<GithubTicketSystem, GithubTicket>
{
    private final static Logger logger = Logging.getLogger(GithubTicket.class.getName());

    protected static GithubTicket fromTicketResponse(GithubTicketSystem parent, GithubTicketResponse response)
    {
        GithubTicket ret = new GithubTicket(parent);
        ret.description = response.body;
        ret.id = String.valueOf(response.number);
        ret.open = response.state.equalsIgnoreCase("open");
        ret.title = response.title;

        if (response.assignees != null)
        {
            ret.assignees = response.assignees.stream()
                .map(a -> new GithubTicketAssignee(a.id, a.login))
                .collect(Collectors.toSet());
        }

        if (response.labels != null)
        {
            ret.labels = response.labels.stream()
                .map(l -> l.name)
                .collect(Collectors.toSet());
        }

        return ret;
    }

    protected GithubTicket(GithubTicketSystem parent)
    {
        super(parent);
    }

    @Override
    public GithubTicket addAssignee(String identifier)
    {
        this.assignees.add(new GithubTicketAssignee(0, identifier));
        this.updatedFields.add(FieldNames.ASSIGNEES.name());
        return this;
    }

    @Override
    public GithubTicket removeAssignee(String identifier)
    {
        this.assignees.removeIf(a -> Objects.equals(a.username, identifier));
        this.updatedFields.add(FieldNames.ASSIGNEES.name());
        return null;
    }

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

    @Override
    public GithubTicket save()
    {
        if (updatedFields.size() == 0)
        {
            logger.info("No changed fields, no save required");
            return this;
        }

        OkHttpClient client = this.getHttpClient();
        ObjectMapper mapper = new ObjectMapper()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        logger.log(Level.FINEST, String.format(
            "[Ticket %s] preparing body for update request",
            this.id
        ));

        ObjectNode body = mapper.createObjectNode();
        for (String name : this.updatedFields)
        {
            if (FieldNames.ASSIGNEES.name().equals(name))
            {
                ArrayNode arrayNode = body.putArray("assignees");
                this.assignees.forEach(a -> arrayNode.add(a.username));
            }

            else if (FieldNames.DESCRIPTION.name().equals(name))
            {
                body.put("body", this.description);
            }

            else if (FieldNames.LABELS.name().equals(name))
            {
                ArrayNode arrayNode = body.putArray("labels");
                this.labels.forEach(arrayNode::add);
            }

            else if (FieldNames.OPEN.name().equals(name))
            {
                body.put("state", (this.open) ? "open" : "closed");
            }

            else if (FieldNames.TITLE.name().equals(name))
            {
                body.put("title", this.title);
            }

            else
            {
                logger.log(Level.WARNING, String.format(
                    "[Ticket %s] unknown field %s will be ignored from update",
                    this.id,
                    name
                ));
                continue;
            }

            logger.log(Level.FINEST, String.format(
                "[Ticket %s] %s added to update",
                this.id,
                name
            ));
        }

        logger.log(Level.FINEST, String.format(
            "[Ticket %s] request body for update prepared",
            this.id
        ));

        Request.Builder builder = new Request.Builder()
            .url(String.format("%s/%s", this.parent.baseUrl, this.id))
            .addHeader("accept", parent.acceptHeader);
        try
        {
            logger.log(Level.FINEST, String.format(
                "[Ticket %s] serializing update request body",
                this.id
            ));

            String bodyJson = mapper.writeValueAsString(body);

            logger.log(Level.FINEST, String.format(
                "[Ticket %s] serialized JSON:\n%s",
                this.id,
                bodyJson
            ));
            builder
                .patch(RequestBody.create(bodyJson, MediaType.get("application/json")));
        } catch (JsonProcessingException e)
        {
            logger.log(Level.SEVERE, String.format(
                "[Ticket %s] serializing update request body FAILED!",
                this.id
            ));

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

        if (parent.username != null && parent.apiKey != null)
        {
            builder.addHeader("Authorization", Credentials.basic(parent.username, parent.apiKey));
            logger.log(Level.FINEST, String.format(
                "[Ticket %s] added token authentication header",
                this.id
            ));
        }

        Response response;
        try
        {
            Request request = builder.build();
            logger.log(Level.FINEST, String.format(
                "[Ticket %s] created request:\n%s",
                this.id,
                (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, String.format(
                "[Ticket %s] update request FAILED",
                this.id
            ));

            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(
                "[Ticket %s] update request failed with response code %d",
                this.id,
                response.code()
            ));

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

        logger.log(Level.FINEST, String.format(
            "[Ticket %s] response received",
            this.id
        ));

        ResponseBody responseBody;
        responseBody = response.body();

        if (responseBody == null)
        {
            logger.log(Level.SEVERE, String.format(
                "[Ticket %s] update request didn't deliver a body in response",
                this.id
            ));

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

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

            logger.log(Level.FINEST, String.format(
                "[Ticket %s] parsed response body to ticketResponse instance",
                this.id
            ));
        } 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);
        }

        this.updatedFields.clear();

        logger.log(Level.FINEST, String.format(
            "[Ticket %s] update mark state reset",
            this.id
        ));

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