Skip to main content
summaryrefslogtreecommitdiffstats
blob: 66299e892c9e63007239e16ae87f8d818577df16 (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
/*******************************************************************************
 * Copyright (c) 2009, 2010 Tasktop Technologies 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:
 *     Tasktop Technologies - initial API and implementation
 *******************************************************************************/
package org.eclipse.mylyn.tests.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.eclipse.mylyn.tasks.core.TaskRepository;

/**
 * A builder class for constructing {@link TaskRepository task repository} URLs.
 * 
 * @author David Green
 * @since 3.5
 */
public class UrlBuilder {
	private final StringBuilder buf = new StringBuilder(512);

	private UrlBuilder() {
	}

	public static UrlBuilder build(TaskRepository repository) {
		UrlBuilder builder = new UrlBuilder();
		String url = repository.getRepositoryUrl();
		if (url.endsWith("/")) {
			url = url.substring(0, url.length() - 1);
		}
		return builder.append(url);
	}

	public UrlBuilder append(String urlSegment) {
		buf.append(urlSegment);
		return this;
	}

	public UrlBuilder parameter(String name, Object value) {
		return parameter(name, value == null ? null : value.toString());
	}

	public UrlBuilder parameter(String name, String value) {
		int indexOfQ = buf.indexOf("?");
		if (indexOfQ == -1) {
			buf.append("?");
		} else {
			buf.append("&");
		}
		buf.append(name);
		buf.append('=');
		if (value != null) {
			buf.append(encode(value));
		}
		return this;
	}

	private String encode(String value) {
		try {
			return URLEncoder.encode(value, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new IllegalStateException(e);
		}
	}

	@Override
	public String toString() {
		return buf.toString();
	}

}

Back to the top