summaryrefslogtreecommitdiff
path: root/plugins/tasks/tasks-core/src/com/intellij/tasks/redmine/RedmineRepository.java
blob: f1571fb61447c4e30faa61e5c6e65531ca914821 (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
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
package com.intellij.tasks.redmine;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.tasks.Comment;
import com.intellij.tasks.Task;
import com.intellij.tasks.TaskRepository;
import com.intellij.tasks.TaskType;
import com.intellij.tasks.impl.BaseRepository;
import com.intellij.tasks.impl.BaseRepositoryImpl;
import com.intellij.tasks.impl.TaskUtil;
import com.intellij.util.NullableFunction;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.xmlb.annotations.Tag;
import icons.TasksIcons;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.xml.sax.InputSource;

import javax.swing.*;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Dennis.Ushakov
 */
@Tag("Redmine")
public class RedmineRepository extends BaseRepositoryImpl {
  private static final Logger LOG = Logger.getInstance("#com.intellij.tasks.redmine.RedmineRepository");

  private Pattern myPattern;
  private String myAPIKey;
  private String myProjectId;

  @SuppressWarnings({"UnusedDeclaration"})
  public RedmineRepository() {}

  public RedmineRepository(RedmineRepositoryType type) {
    super(type);
  }

  public RedmineRepository(RedmineRepository other) {
    super(other);
    setAPIKey(other.myAPIKey);
    setProjectId(other.myProjectId);
  }

  @Override
  public void testConnection() throws Exception {
    getIssues("", 10, 0);
  }

  @Override
  public Task[] getIssues(@Nullable String query, int max, long since) throws Exception {
    List<Element> children = getIssues(query, max);

    final List<Task> tasks = ContainerUtil.mapNotNull(children, new NullableFunction<Element, Task>() {
      public Task fun(Element o) {
        return createIssue(o);
      }
    });
    return tasks.toArray(new Task[tasks.size()]);
  }

  @Nullable
  private Task createIssue(final Element element) {
    final String id = element.getChildText("id");
    if (id == null) {
      return null;
    }
    final String summary = element.getChildText("subject");
    if (summary == null) {
      return null;
    }
    final Element status = element.getChild("status");
    final boolean isClosed = status == null || "Closed".equals(status.getAttributeValue("name"));
    final String description = element.getChildText("description");
    final Ref<Date> updated = new Ref<Date>();
    final Ref<Date> created = new Ref<Date>();
    try {
      updated.set(parseDate(element, "updated_on"));
      created.set(parseDate(element, "created_on"));
    } catch (ParseException e) {
      LOG.warn(e);
    }

    return new Task() {
      @Override
      public boolean isIssue() {
        return true;
      }

      @Override
      public String getIssueUrl() {
        final String id = getRealId(getId());
        return id != null ? getUrl() + "/issues/" + id : null;
      }

      @NotNull
      @Override
      public String getId() {
        return myProjectId + "-" + id;
      }

      @NotNull
      @Override
      public String getSummary() {
        return summary;
      }

      public String getDescription() {
        return description;
      }

      @NotNull
      @Override
      public Comment[] getComments() {
        return new Comment[0];
      }

      @NotNull
      @Override
      public Icon getIcon() {
        return TasksIcons.Redmine;
      }

      @NotNull
      @Override
      public TaskType getType() {
        return TaskType.BUG;
      }

      @Override
      public Date getUpdated() {
        return updated.get();
      }

      @Override
      public Date getCreated() {
        return created.get();
      }

      @Override
      public boolean isClosed() {
        return isClosed;
      }

      @Override
      public TaskRepository getRepository() {
        return RedmineRepository.this;
      }

      @Override
      public String getPresentableName() {
        return getId() + ": " + getSummary();
      }
    };
  }

  @Nullable
  private static Date parseDate(Element element, String name) throws ParseException {
    final String date = element.getChildText(name);
    if (date.matches(".*\\+\\d\\d:\\d\\d")) {
      final SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd'T'HH:mm:ss", Locale.US);
      final int timeZoneIndex = date.length() - 6;
      format.setTimeZone(TimeZone.getTimeZone("GMT" + date.substring(timeZoneIndex)));
      return format.parse(date.substring(0, timeZoneIndex));
    }
    // Ad-hoc fix for IDEA-110012
    Date parsed;
    try {
      parsed = (new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.US)).parse(date);
    }
    catch (ParseException e) {
      LOG.warn("Unparseable date: " + date, e);
      parsed = TaskUtil.parseDate(date);
    }
    return parsed;
  }

  @Override
  public boolean isConfigured() {
    return super.isConfigured() && !StringUtil.isEmpty(myProjectId);
  }

  private List<Element> getIssues(@Nullable String query, int max) throws Exception {
    String url = "/projects/" + myProjectId + "/issues.xml?";
    final boolean hasKey = !StringUtil.isEmpty(myAPIKey) && !isUseHttpAuthentication();
    if (hasKey) {
      url +="key=" + myAPIKey;
    }
    if (hasKey) url += "&";
    // getting only open id's
    url += encodeUrl("fields[]") + "=status_id&"  + 
           encodeUrl("operators[status_id]") + "=o&" +
           encodeUrl("values[status_id][]") + "=1";
    final boolean hasQuery = !StringUtil.isEmpty(query);
    if (hasQuery) {
      url += "&" + encodeUrl("fields[]") + "=subject&" +
             encodeUrl("operators[subject]") + "=" + encodeUrl("~") + "&" + 
             encodeUrl("values[subject][]") + "=" + encodeUrl(query);
    }
    if (max >= 0) {
      url += "&per_page=" + encodeUrl(String.valueOf(max));
    }
    HttpMethod method = doREST(url, false);
    final String response = method.getResponseBodyAsString();
    final Reader stream = new StringReader(response);
    final InputSource source = new InputSource(stream);
    source.setEncoding("UTF-8");
    Element element;
    try {
      element = new SAXBuilder(false).build(source).getRootElement();
    } catch (Throwable t) {
      LOG.error("Error fetching issues for: " + url + ", HTTP status code: " + method.getStatusCode(), t, response);
      throw new Exception("Error fetching issues for: " + url + ", HTTP status code: " + method.getStatusCode() +
                          "\n" + response);
    }

    if (!"issues".equals(element.getName())) {
      LOG.warn("Error fetching issues for: " + url + ", HTTP status code: " + method.getStatusCode());
      throw new Exception("Error fetching issues for: " + url + ", HTTP status code: " + method.getStatusCode() +
                          "\n" + element.getText());
    }

    return element.getChildren("issue");
  }

  private HttpMethod doREST(String request, boolean post) throws Exception {
    final HttpClient client = getHttpClient();
    client.getParams().setContentCharset("UTF-8");
    String uri = getUrl().replace("https://", EASY_HTTPS + "://") + request;
    HttpMethod method = post ? new PostMethod(uri) : new GetMethod(uri);
    configureHttpMethod(method);
    client.executeMethod(method);
    return method;
  }

  @Nullable
  @Override
  public Task findTask(String id) throws Exception {
    final String realId = getRealId(id);
    if (realId == null) return null;
    HttpMethod method = doREST("/issues/" + realId + ".xml", false);
    InputStream stream = method.getResponseBodyAsStream();
    Element element = new SAXBuilder(false).build(stream).getRootElement();
    return element.getName().equals("issue") ? createIssue(element) : null;
  }

  @Override
  public BaseRepository clone() {
    return new RedmineRepository(this);
  }

  @Nullable
  private String getRealId(String id) {
    final String start = myProjectId + "-";
    return id.startsWith(start) ? id.substring(start.length()) : null;
  }

  @Nullable
  public String extractId(String taskName) {
    Matcher matcher = myPattern.matcher(taskName);
    return matcher.find() ? matcher.group(1) : null;
  }

  public String getAPIKey() {
    return myAPIKey;
  }

  public void setAPIKey(String APIKey) {
    myAPIKey = APIKey;
  }

  public String getProjectId() {
    return myProjectId;
  }

  public void setProjectId(String projectId) {
    myProjectId = projectId;
    myPattern = Pattern.compile("(" + projectId + "\\-\\d+):\\s+");
  }

  @Override
  public boolean equals(Object o) {
    if (!super.equals(o)) return false;
    if (!(o instanceof RedmineRepository)) return false;

    RedmineRepository that = (RedmineRepository)o;
    if (getAPIKey() != null ? !getAPIKey().equals(that.getAPIKey()) : that.getAPIKey() != null) return false;
    if (getProjectId() != null ? !getProjectId().equals(that.getProjectId()) : that.getProjectId() != null) return false;
    return true;
  }


  @Override
  public String getPresentableName() {
    final String name = super.getPresentableName();
    return name +
           "/projects" +
           (!StringUtil.isEmpty(getProjectId()) ? "/" + getProjectId() : "");
  }

  @Override
  protected int getFeatures() {
    return super.getFeatures() | BASIC_HTTP_AUTHORIZATION;
  }
}