View Javadoc

1   /*
2    * Copyright (C) 2012 Atlassian
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package com.atlassian.jira.rest.client.internal.json.gen;
18  
19  import com.atlassian.jira.rest.client.api.domain.BasicUser;
20  import com.atlassian.jira.rest.client.api.domain.Visibility;
21  import com.atlassian.jira.rest.client.api.domain.input.WorklogInput;
22  import com.atlassian.jira.rest.client.internal.json.JsonParseUtil;
23  import org.codehaus.jettison.json.JSONException;
24  import org.codehaus.jettison.json.JSONObject;
25  import org.joda.time.format.DateTimeFormatter;
26  
27  public class WorklogInputJsonGenerator implements JsonGenerator<WorklogInput> {
28  
29      private final JsonGenerator<Visibility> visibilityGenerator = new VisibilityJsonGenerator();
30      private final JsonGenerator<BasicUser> basicUserJsonGenerator = new BasicUserJsonGenerator();
31      private final DateTimeFormatter dateTimeFormatter;
32  
33      public WorklogInputJsonGenerator() {
34          this(JsonParseUtil.JIRA_DATE_TIME_FORMATTER);
35      }
36  
37      public WorklogInputJsonGenerator(DateTimeFormatter dateTimeFormatter) {
38          this.dateTimeFormatter = dateTimeFormatter;
39      }
40  
41      @Override
42      public JSONObject generate(final WorklogInput worklogInput) throws JSONException {
43          final JSONObject res = new JSONObject()
44                  .put("self", worklogInput.getSelf())
45                  .put("comment", worklogInput.getComment())
46                  .put("started", dateTimeFormatter.print(worklogInput.getStartDate()))
47                  .put("timeSpent", worklogInput.getMinutesSpent() + "m");
48  
49          putGeneratedIfNotNull("visibility", worklogInput.getVisibility(), res, visibilityGenerator);
50          putGeneratedIfNotNull("author", worklogInput.getAuthor(), res, basicUserJsonGenerator);
51          putGeneratedIfNotNull("updateAuthor", worklogInput.getUpdateAuthor(), res, basicUserJsonGenerator);
52          return res;
53      }
54  
55      private <K> JSONObject putGeneratedIfNotNull(final String key, final K value, final JSONObject dest, final JsonGenerator<K> generator)
56              throws JSONException {
57          if (value != null) {
58              dest.put(key, generator.generate(value));
59          }
60          return dest;
61      }
62  }