Skip to main content
summaryrefslogtreecommitdiffstats
blob: 7fb1e1e2b4750beceade77db282fb46ee296f9a6 (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
/*******************************************************************************
 * Copyright (c) 2013 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
 *******************************************************************************/

package org.eclipse.mylyn.internal.bugzilla.rest.core;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.mylyn.commons.core.operations.IOperationMonitor;
import org.eclipse.mylyn.commons.core.operations.OperationUtil;
import org.eclipse.mylyn.commons.net.AuthenticationCredentials;
import org.eclipse.mylyn.commons.repositories.core.RepositoryLocation;
import org.eclipse.mylyn.commons.repositories.core.auth.AuthenticationType;
import org.eclipse.mylyn.commons.repositories.core.auth.UserCredentials;
import org.eclipse.mylyn.internal.commons.core.operations.NullOperationMonitor;
import org.eclipse.mylyn.internal.tasks.core.IRepositoryConstants;
import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector;
import org.eclipse.mylyn.tasks.core.IRepositoryQuery;
import org.eclipse.mylyn.tasks.core.ITask;
import org.eclipse.mylyn.tasks.core.RepositoryInfo;
import org.eclipse.mylyn.tasks.core.RepositoryVersion;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.mylyn.tasks.core.data.AbstractTaskDataHandler;
import org.eclipse.mylyn.tasks.core.data.TaskData;
import org.eclipse.mylyn.tasks.core.data.TaskDataCollector;
import org.eclipse.mylyn.tasks.core.sync.ISynchronizationSession;

import com.google.common.base.Optional;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.UncheckedExecutionException;

public class BugzillaRestConnector extends AbstractRepositoryConnector {

	public static final Duration CLIENT_CACHE_DURATION = new Duration(24, TimeUnit.HOURS);

	public static final Duration CONFIGURATION_CACHE_EXPIRE_DURATION = new Duration(7, TimeUnit.DAYS);

	public static final Duration CONFIGURATION_CACHE_REFRESH_AFTER_WRITE_DURATION = new Duration(1, TimeUnit.DAYS);

	private static final ThreadLocal<IOperationMonitor> context = new ThreadLocal<IOperationMonitor>();

	private boolean ignoredProperty(String propertyName) {
		if (propertyName.equals(RepositoryLocation.PROPERTY_LABEL) || propertyName.equals(TaskRepository.OFFLINE)
				|| propertyName.equals(IRepositoryConstants.PROPERTY_ENCODING)
				|| propertyName.equals(TaskRepository.PROXY_HOSTNAME) || propertyName.equals(TaskRepository.PROXY_PORT)
				|| propertyName.equals("org.eclipse.mylyn.tasklist.repositories.savePassword")
				|| propertyName.equals("org.eclipse.mylyn.tasklist.repositories.proxy.usedefault")
				|| propertyName.equals("org.eclipse.mylyn.tasklist.repositories.proxy.savePassword")
				|| propertyName.equals("org.eclipse.mylyn.tasklist.repositories.proxy.username")
				|| propertyName.equals("org.eclipse.mylyn.tasklist.repositories.proxy.password")
				|| propertyName.equals("org.eclipse.mylyn.tasklist.repositories.proxy.enabled")) {
			return true;
		}
		return false;
	}

	private final PropertyChangeListener repositoryChangeListener4ClientCache = new PropertyChangeListener() {

		@Override
		public void propertyChange(PropertyChangeEvent evt) {
			if (ignoredProperty(evt.getPropertyName())) {
				return;
			}
			TaskRepository taskRepository = (TaskRepository) evt.getSource();
			clientCache.invalidate(new RepositoryKey(taskRepository));
		}
	};

	private final PropertyChangeListener repositoryChangeListener4ConfigurationCache = new PropertyChangeListener() {

		@Override
		public void propertyChange(PropertyChangeEvent evt) {
			if (ignoredProperty(evt.getPropertyName())
					|| evt.getPropertyName().equals("org.eclipse.mylyn.tasklist.repositories.password")) {
				return;
			}
			TaskRepository taskRepository = (TaskRepository) evt.getSource();
			configurationCache.invalidate(new RepositoryKey(taskRepository));
		}
	};

	private final LoadingCache<RepositoryKey, BugzillaRestClient> clientCache = CacheBuilder.newBuilder()
			.expireAfterAccess(CLIENT_CACHE_DURATION.getValue(), CLIENT_CACHE_DURATION.getUnit())
			.build(new CacheLoader<RepositoryKey, BugzillaRestClient>() {

				@Override
				public BugzillaRestClient load(RepositoryKey key) throws Exception {
					TaskRepository repository = key.getRepository();
					repository.addChangeListener(repositoryChangeListener4ClientCache);
					return createClient(repository);
				}
			});

	private final LoadingCache<RepositoryKey, Optional<BugzillaRestConfiguration>> configurationCache;

	public BugzillaRestConnector() {
		this(CONFIGURATION_CACHE_REFRESH_AFTER_WRITE_DURATION);
	}

	public BugzillaRestConnector(Duration refreshAfterWriteDuration) {
		super();
		configurationCache = createCacheBuilder(CONFIGURATION_CACHE_EXPIRE_DURATION, refreshAfterWriteDuration)
				.build(new CacheLoader<RepositoryKey, Optional<BugzillaRestConfiguration>>() {

					@Override
					public Optional<BugzillaRestConfiguration> load(RepositoryKey key) throws Exception {
						BugzillaRestClient client = clientCache.get(key);
						TaskRepository repository = key.getRepository();
						repository.addChangeListener(repositoryChangeListener4ConfigurationCache);
						return Optional.fromNullable(client.getConfiguration(key.getRepository(), context.get()));
					}

					@Override
					public ListenableFuture<Optional<BugzillaRestConfiguration>> reload(final RepositoryKey key,
							Optional<BugzillaRestConfiguration> oldValue) throws Exception {
						// asynchronous!
						ListenableFutureJob<Optional<BugzillaRestConfiguration>> job = new ListenableFutureJob<Optional<BugzillaRestConfiguration>>(
								"") {

							@Override
							protected IStatus run(IProgressMonitor monitor) {
								BugzillaRestClient client;
								try {
									client = clientCache.get(key);
									set(Optional
											.fromNullable(client.getConfiguration(key.getRepository(), context.get())));
								} catch (ExecutionException e) {
									e.printStackTrace();
									return new Status(IStatus.ERROR, BugzillaRestCore.ID_PLUGIN,
											"BugzillaRestConnector reload Configuration", e);
								}
								return Status.OK_STATUS;
							}
						};
						job.schedule();
						return job;
					}
				});
	}

	protected CacheBuilder<Object, Object> createCacheBuilder(Duration expireAfterWriteDuration,
			Duration refreshAfterWriteDuration) {
		return CacheBuilder.newBuilder()
				.expireAfterWrite(expireAfterWriteDuration.getValue(), expireAfterWriteDuration.getUnit())
				.refreshAfterWrite(refreshAfterWriteDuration.getValue(), refreshAfterWriteDuration.getUnit());
	}

	@Override
	public boolean canCreateNewTask(TaskRepository repository) {
		return true;
	}

	@Override
	public boolean canCreateTaskFromKey(TaskRepository repository) {
		// ignore
		return false;
	}

	@Override
	public String getConnectorKind() {
		return BugzillaRestCore.CONNECTOR_KIND;
	}

	@Override
	public String getLabel() {
		return "Bugzilla 5.0 or later with REST";
	}

	@Override
	public String getRepositoryUrlFromTaskUrl(String taskUrl) {
		if (taskUrl == null) {
			return null;
		}
		int index = taskUrl.indexOf("/rest.cgi/");
		return index == -1 ? null : taskUrl.substring(0, index);
	}

	@Override
	public TaskData getTaskData(TaskRepository repository, String taskIdOrKey, IProgressMonitor monitor)
			throws CoreException {
		// ignore
		return null;
	}

	@Override
	public String getTaskIdFromTaskUrl(String taskUrl) {
		// ignore
		return null;
	}

	@Override
	public String getTaskUrl(String repositoryUrl, String taskIdOrKey) {
		return repositoryUrl + "/rest.cgi/bug/" + taskIdOrKey;
	}

	@Override
	public boolean hasTaskChanged(TaskRepository taskRepository, ITask task, TaskData taskData) {
		// ignore
		return false;
	}

	@Override
	public IStatus performQuery(TaskRepository repository, IRepositoryQuery query, TaskDataCollector collector,
			ISynchronizationSession session, IProgressMonitor monitor) {
		// ignore
		return null;
	}

	@Override
	public void updateRepositoryConfiguration(TaskRepository taskRepository, IProgressMonitor monitor)
			throws CoreException {
		context.set(monitor != null ? OperationUtil.convert(monitor) : new NullOperationMonitor());
		configurationCache.refresh(new RepositoryKey(taskRepository));
		context.remove();
	}

	@Override
	public void updateTaskFromTaskData(TaskRepository taskRepository, ITask task, TaskData taskData) {
		task.setUrl(taskData.getRepositoryUrl() + "/rest.cgi/bug/" + taskData.getTaskId());
	}

	@Override
	public AbstractTaskDataHandler getTaskDataHandler() {
		return new BugzillaRestTaskDataHandler(this);
	}

	private BugzillaRestClient createClient(TaskRepository repository) {
		RepositoryLocation location = new RepositoryLocation(repository.getProperties());
		AuthenticationCredentials credentials1 = repository
				.getCredentials(org.eclipse.mylyn.commons.net.AuthenticationType.REPOSITORY);
		UserCredentials credentials = new UserCredentials(credentials1.getUserName(), credentials1.getPassword(), null,
				true);
		location.setCredentials(AuthenticationType.REPOSITORY, credentials);
		BugzillaRestClient client = new BugzillaRestClient(location);

		return client;
	}

	/**
	 * Returns the Client for the {@link TaskRepository}.
	 *
	 * @param repository
	 *            the {@link TaskRepository} object
	 * @return the client Object
	 * @throws CoreException
	 */
	public BugzillaRestClient getClient(TaskRepository repository) throws CoreException {
		try {
			return clientCache.get(new RepositoryKey(repository));
		} catch (ExecutionException e) {
			throw new CoreException(
					new Status(IStatus.ERROR, BugzillaRestCore.ID_PLUGIN, "TaskRepositoryManager is null"));
		}
	}

	@Override
	public RepositoryInfo validateRepository(TaskRepository repository, IProgressMonitor monitor) throws CoreException {
		try {
			BugzillaRestClient client = createClient(repository);
			if (!client.validate(OperationUtil.convert(monitor))) {
				throw new CoreException(
						new Status(IStatus.ERROR, BugzillaRestCore.ID_PLUGIN, "repository is invalide"));
			}
			BugzillaRestVersion version = client.getVersion(OperationUtil.convert(monitor));
			return new RepositoryInfo(new RepositoryVersion(version.toString()));
		} catch (Exception e) {
			throw new CoreException(new Status(IStatus.ERROR, BugzillaRestCore.ID_PLUGIN, e.getMessage(), e));
		}
	}

	public BugzillaRestConfiguration getRepositoryConfiguration(TaskRepository repository) throws CoreException {
		if (clientCache.getIfPresent(new RepositoryKey(repository)) == null) {
			getClient(repository);
		}
		try {
			Optional<BugzillaRestConfiguration> configurationOptional = configurationCache
					.get(new RepositoryKey(repository));
			return configurationOptional.isPresent() ? configurationOptional.get() : null;
		} catch (UncheckedExecutionException e) {
			throw new CoreException(new Status(IStatus.ERROR, BugzillaRestCore.ID_PLUGIN, e.getMessage(), e));
		} catch (ExecutionException e) {
			throw new CoreException(new Status(IStatus.ERROR, BugzillaRestCore.ID_PLUGIN, e.getMessage(), e));
		}
	}

	public void clearClientCache() {
		clientCache.invalidateAll();
	}

	public void clearConfigurationCache() {
		configurationCache.invalidateAll();
	}

	public void clearAllCaches() {
		clearClientCache();
		clearConfigurationCache();
	}

	@Override
	public boolean isRepositoryConfigurationStale(TaskRepository repository, IProgressMonitor monitor)
			throws CoreException {
		return false;
	}

}

Back to the top