Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 0ca8344b9a3d2e0bfe4ca4d72660302273df0456 (plain) (blame)
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/*******************************************************************************
 * Copyright (c) 2015, 2017 Frank Becker and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Frank Becker - initial API and implementation
 *     Red Hat Inc. - modified for use with OpenShift.io
 *******************************************************************************/

package org.eclipse.linuxtools.internal.mylyn.osio.rest.core;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.linuxtools.internal.mylyn.osio.rest.core.response.data.Space;
import org.eclipse.linuxtools.internal.mylyn.osio.rest.core.response.data.WorkItemTypeData;
import org.eclipse.mylyn.commons.core.operations.IOperationMonitor;
import org.eclipse.mylyn.commons.repositories.core.RepositoryLocation;
import org.eclipse.mylyn.commons.repositories.http.core.CommonHttpClient;
import org.eclipse.mylyn.commons.repositories.http.core.CommonHttpResponse;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
import org.eclipse.mylyn.tasks.core.data.TaskData;

import com.google.common.base.Throwables;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

@SuppressWarnings("restriction")
public class OSIORestPostNewTask extends OSIORestPostRequest<String> {
	
	private final TaskData taskData;
	private final Space space;
	private final TaskRepository taskRepository;
	private final OSIORestConnector connector;
	private final OSIORestConfiguration taskConfiguration;
	public class TaskAttributeTypeAdapter extends TypeAdapter<TaskData> {
		RepositoryLocation location;

		public TaskAttributeTypeAdapter(RepositoryLocation location) {
			super();
			this.location = location;
		}

		@Override
		public void write(JsonWriter out, TaskData taskData) throws IOException {
			out.beginObject();
			out.name("data"); //$NON-NLS-1$
			out.beginObject();
			out.name("attributes"); //$NON-NLS-1$
			out.beginObject();
			out.name("system.state").value("new"); //$NON-NLS-1$ //$NON-NLS-2$
			TaskAttribute titleAttribute = taskData.getRoot().getAttribute(taskSchema.SUMMARY.getKey());
			out.name("system.title").value(titleAttribute.getValue()); //$NON-NLS-1$
			out.name("version").value("1"); //$NON-NLS-1$ //$NON-NLS-2$
			TaskAttribute descAttribute = taskData.getRoot().getAttribute(taskSchema.DESCRIPTION.getKey());
			if (descAttribute != null) {
				String description = descAttribute.getValue();
				if (description != null && !description.isEmpty()) {
					out.name("system.description").value(description);
				}
			}
			out.endObject();
			out.name("relationships"); //$NON-NLS-1$
			out.beginObject();
			out.name("baseType"); //$NON-NLS-1$
			out.beginObject();
			out.name("data"); //$NON-NLS-1$
			out.beginObject();
			TaskAttribute taskType = taskData.getRoot().getAttribute(taskSchema.WORKITEM_TYPE.getKey());
			WorkItemTypeData taskTypeData = space.getWorkItemTypes().get(taskType.getValue());
			out.name("id").value(taskTypeData.getId()); //$NON-NLS-1$
			out.name("type").value("workitemtypes"); //$NON-NLS-1$
			out.endObject();
			out.endObject();
			out.name("space"); //$NON-NLS-1$
			out.beginObject();
			out.name("data"); //$NON-NLS-1$
			out.beginObject();
			out.name("id").value(space.getId()); //$NON-NLS-1$
			out.name("type").value("spaces"); //$NON-NLS-1$ //$NON-NLS-2$
			out.endObject();
			out.endObject();
			out.endObject();
			out.name("type").value("workitems"); //$NON-NLS-1$ //$NON-NLS-2$
			out.endObject();
			out.name("included"); //$NON-NLS-1$
			out.beginArray();
			out.value(true);
			out.endArray();
			out.endObject();
		}

		@Override
		public TaskData read(JsonReader in) throws IOException {
			throw new UnsupportedOperationException(
					"TaskAttributeTypeAdapter in OSIORestPatchUpdateTask only supports write"); //$NON-NLS-1$
		}

	}
	
	public OSIORestPostNewTask(CommonHttpClient client, TaskData taskData, Space space, OSIORestConnector connector,
			TaskRepository taskRepository) throws CoreException {
		super(client, "/spaces/" + space.getId() + "/workitems", true); //$NON-NLS-1$ //$NON-NLS-2$
		this.space = space;
		this.connector = connector;
		this.taskRepository = taskRepository;
		this.taskConfiguration = connector.getRepositoryConfiguration(taskRepository);
		this.taskData = taskData;
	}

	List<NameValuePair> requestParameters;

	@SuppressWarnings("deprecation")
	@Override
	protected void addHttpRequestEntities(HttpRequestBase request) throws OSIORestException {
		super.addHttpRequestEntities(request);
		try {
			Gson gson = new GsonBuilder()
					.registerTypeAdapter(TaskData.class, new TaskAttributeTypeAdapter(getClient().getLocation()))
					.create();
			StringEntity requestEntity = new StringEntity(gson.toJson(taskData));
			((HttpPost) request).setEntity(requestEntity);
		} catch (UnsupportedEncodingException e) {
			Throwables.propagate(new CoreException(
					new Status(IStatus.ERROR, OSIORestCore.ID_PLUGIN, "Can not build HttpRequest", e))); //$NON-NLS-1$
		}
	}

	@Override
	protected void doValidate(CommonHttpResponse response, IOperationMonitor monitor)
			throws IOException, OSIORestException {
		validate(response, HttpStatus.SC_CREATED, monitor);
	}

	public static String convert(String str) {
		str = str.replace("\"", "\\\"").replace("\n", "\\\n"); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$//$NON-NLS-4$
		StringBuffer ostr = new StringBuffer();
		for (int i = 0; i < str.length(); i++) {
			char ch = str.charAt(i);
			if ((ch >= 0x0020) && (ch <= 0x007e)) {
				ostr.append(ch);
			} else {
				ostr.append("\\u"); //$NON-NLS-1$
				String hex = Integer.toHexString(str.charAt(i) & 0xFFFF);
				for (int j = 0; j < 4 - hex.length(); j++) {
					ostr.append("0"); //$NON-NLS-1$
				}
				ostr.append(hex.toLowerCase());
			}
		}
		return (new String(ostr));
	}

	@Override
	protected String parseFromJson(InputStreamReader in) {
		TypeToken<String> type = new TypeToken<String>() {
		};
		return new GsonBuilder().registerTypeAdapter(type.getType(), new JSonTaskDataDeserializer())
				.create()
				.fromJson(in, type.getType());
	}

	OSIORestTaskSchema taskSchema = OSIORestTaskSchema.getDefault();

	private class JSonTaskDataDeserializer implements JsonDeserializer<String> {

		@Override
		public String deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
				throws JsonParseException {
			OSIORestTaskDataHandler dataHandler = (OSIORestTaskDataHandler) connector.getTaskDataHandler();
			dataHandler.getAttributeMapper(taskRepository);
			JsonObject workitemdata = json.getAsJsonObject().get("data").getAsJsonObject(); //$NON-NLS-1$
			JsonObject attributes = workitemdata.get("attributes").getAsJsonObject(); //$NON-NLS-1$
			JsonObject relationships = workitemdata.get("relationships").getAsJsonObject(); //$NON-NLS-1$
			JsonObject space = relationships.get("space").getAsJsonObject(); //$NON-NLS-1$
			JsonObject spaceData = space.get("data").getAsJsonObject(); //$NON-NLS-1$
			String spaceId = spaceData.get("id").getAsString(); //$NON-NLS-1$
			Map<String, Space> spaces = taskConfiguration.getSpaces();
			Space actualSpace = null;
			for (Space entry : spaces.values()) {
				if (entry.getId().equals(spaceId)) {
					actualSpace = entry;
					break;
				}
			}
			String spaceName = actualSpace.getName();
			int number = attributes.get("system.number").getAsInt(); //$NON-NLS-1$
			String taskId = spaceName + "#" + number; //$NON-NLS-1$
			return taskId;
//			taskData.getTaskId()
//			try {
//				dataHandler.initializeTaskData(taskRepository, taskData, null, null);
//			} catch (CoreException e) {
//				com.google.common.base.Throwables.propagate(e);
//			}
//			TaskAttribute idAttribute = taskData.getRoot().getAttribute(taskSchema.ID.getKey());
//			idAttribute.setValue(taskId);
//			TaskAttribute uuidAttribute = taskData.getRoot().getAttribute(taskSchema.UUID.getKey());
//			String uuid = workitemdata.get("id").getAsString(); //$NON-NLS-1$
//			uuidAttribute.setValue(uuid);
//			TaskAttribute spaceAttribute = taskData.getRoot().getAttribute(taskSchema.SPACE.getKey());
//			spaceAttribute.setValue(spaceName);
//			// handle fields in the attributes section
//			for (Entry<String, JsonElement> entry : attributes.entrySet()) {
//				String attributeId = OSIORestTaskSchema.getAttributeNameFromFieldName(entry.getKey());
//				if (entry.getKey().equals("system.updated_at")) { //$NON-NLS-1$
//					TaskAttribute attribute = taskData.getRoot()
//							.getAttribute(taskSchema.DATE_MODIFICATION.getKey());
//					JsonElement value = entry.getValue(); //.get("real_name");
//					if (attribute != null) {
//						try {
//							SimpleDateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'", //$NON-NLS-1$
//									Locale.US);
//							iso8601Format.setTimeZone(TimeZone.getTimeZone("UTC")); //$NON-NLS-1$
//							Date tempDate = iso8601Format.parse(value.getAsString());
//							attribute.setValue(Long.toString(tempDate.getTime()));
//							continue;
//						} catch (ParseException e) {
//							com.google.common.base.Throwables.propagate(
//									new CoreException(new Status(IStatus.ERROR, OSIORestCore.ID_PLUGIN,
//											"Can not parse Date (" + value.getAsString() + ")"))); //$NON-NLS-1$ //$NON-NLS-2$
//						}
//					}
//				} else if (entry.getKey().equals("system.created_at")) { //$NON-NLS-1$
//					TaskAttribute attribute = taskData.getRoot()
//							.getAttribute(taskSchema.DATE_CREATION.getKey());
//					JsonElement value = entry.getValue(); //.get("real_name");
//					if (attribute != null) {
//						try {
//							SimpleDateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'", //$NON-NLS-1$
//									Locale.US);
//							iso8601Format.setTimeZone(TimeZone.getTimeZone("UTC")); //$NON-NLS-1$
//							Date tempDate = iso8601Format.parse(value.getAsString());
//							attribute.setValue(Long.toString(tempDate.getTime()));
//							continue;
//						} catch (ParseException e) {
//							com.google.common.base.Throwables.propagate(
//									new CoreException(new Status(IStatus.ERROR, OSIORestCore.ID_PLUGIN,
//											"Can not parse Date (" + value.getAsString() + ")"))); //$NON-NLS-1$ //$NON-NLS-2$
//						}
//					}
//				} 
//
//				TaskAttribute attribute = taskData.getRoot().getAttribute(attributeId);
//				if (attribute != null) {
//					JsonElement value = entry.getValue();
//					if (!value.isJsonNull()) {
//						if (value.isJsonArray()) {
//							JsonArray valueArray = value.getAsJsonArray();
//							attribute.clearValues();
//							for (JsonElement jsonElement : valueArray) {
//								attribute.addValue(jsonElement.getAsString());
//							}
//						} else {
//							attribute.setValue(entry.getValue().getAsString());
//						}
//					}
//				}
//			}
//			// handle fields in the relationships section
//			for (Entry<String, JsonElement> entry : relationships.entrySet()) {
//				String attributeId = OSIORestTaskSchema.getAttributeNameFromFieldName(entry.getKey());
//				if (attributeId.equals("space") //$NON-NLS-1$
//						|| attributeId.equals("assignees") //$NON-NLS-1$
//						|| attributeId.equals("creator") //$NON-NLS-1$
//						|| attributeId.equals("children")) { //$NON-NLS-1$
//					continue;
//				}
//				TaskAttribute attribute = taskData.getRoot().getAttribute(attributeId);
//				if (attribute != null) {
//					JsonObject entryObject = entry.getValue().getAsJsonObject();
//					if (entryObject.has("data")) { //$NON-NLS-1$
//						JsonObject entryData = entryObject.get("data").getAsJsonObject(); //$NON-NLS-1$
//						String entryId = entryData.get("id").getAsString(); //$NON-NLS-1$
//						Map<String, IdNamed> itemMap = actualSpace.getMapFor(entry.getKey());
//						if (itemMap != null) {
//							for (Entry<String, IdNamed> itemEntry : itemMap.entrySet()) {
//								if (itemEntry.getValue().getId().equals(entryId)) {
//									attribute.setValue(itemEntry.getKey());
//									break;
//								}
//							}
//						}
//					}
//				}
//			}
//
//			// add assignee id (will resolve later)
//			TaskAttribute assigneeIDs = taskData.getRoot().getAttribute(taskSchema.ASSIGNEE_IDS.getKey());
//			JsonObject assigneeObject = relationships.get("assignees").getAsJsonObject(); //$NON-NLS-1$
//			if (assigneeObject.get("data") != null) { //$NON-NLS-1$
//				JsonArray assigneeArray = assigneeObject.get("data").getAsJsonArray(); //$NON-NLS-1$
//				for (JsonElement entry : assigneeArray) {
//					JsonObject entryObject = entry.getAsJsonObject();
//					String id = entryObject.get("id").getAsString(); //$NON-NLS-1$
//					assigneeIDs.addValue(id);
//				}
//			}
//
//			// add creator id (will resolve later)
//			TaskAttribute creatorID = taskData.getRoot().getAttribute(taskSchema.CREATOR_ID.getKey());
//			JsonObject creatorObject = relationships.get("creator").getAsJsonObject(); //$NON-NLS-1$
//			JsonObject creatorData = creatorObject.get("data").getAsJsonObject(); //$NON-NLS-1$
//			creatorID.setValue(creatorData.get("id").getAsString());
//
//			// add workitem url
//			TaskAttribute workitemURL = taskData.getRoot().getAttribute(taskSchema.TASK_URL.getKey());
//			JsonObject linksObject = workitemdata.get("links").getAsJsonObject(); //$NON-NLS-1$
//			String workitemself = linksObject.get("self").getAsString(); //$NON-NLS-1$
//			workitemURL.setValue(workitemself);
//
//			OSIORestConfiguration config;
//			try {
//				config = connector.getRepositoryConfiguration(taskRepository);
//				if (config != null) {
//					config.addValidOperations(taskData);
//				}
//			} catch (CoreException e) {
//				com.google.common.base.Throwables.propagate(e);
//			}
//			return taskData;
		}
	}

}

Back to the top