View Javadoc

1   package com.atlassian.marketplace.client.util;
2   
3   import java.net.URI;
4   import java.net.URISyntaxException;
5   
6   import org.apache.http.client.utils.URIBuilder;
7   
8   import static com.google.common.base.Preconditions.checkNotNull;
9   
10  /**
11   * Simplified wrapper for Apache URIBuilder that gives it the nicer interface of the jax-rs UriBuilder,
12   * without having to bring in that dependency. 
13   */
14  public class UriBuilder
15  {
16      private final URIBuilder builder;
17      
18      private UriBuilder(URIBuilder builder)
19      {
20          this.builder = checkNotNull(builder);
21      }
22      
23      public static UriBuilder fromUri(URI uri)
24      {
25          return new UriBuilder(new URIBuilder(checkNotNull(uri)));
26      }
27      
28      public static UriBuilder fromUri(String uri)
29      {
30          try
31          {
32              return new UriBuilder(new URIBuilder(checkNotNull(uri)));
33          }
34          catch (URISyntaxException e)
35          {
36              throw new IllegalArgumentException(e);
37          }
38      }
39      
40      public URI build()
41      {
42          try
43          {
44              return builder.build();
45          }
46          catch (URISyntaxException e)
47          {
48              throw new IllegalArgumentException(e);
49          }
50      }
51      
52      public UriBuilder host(String host)
53      {
54          builder.setHost(checkNotNull(host));
55          return this;
56      }
57      
58      public UriBuilder path(String addPath)
59      {
60          checkNotNull(addPath);
61          String old = builder.getPath();
62          if (!old.endsWith("/") && !addPath.startsWith("/"))
63          {
64              old = old + "/";
65          }
66          builder.setPath(old + addPath);
67          return this;
68      }
69      
70      public UriBuilder queryParam(String name, Object... value)
71      {
72          for (Object v: checkNotNull(value))
73          {
74              builder.addParameter(checkNotNull(name), String.valueOf(checkNotNull(v)));
75          }
76          return this;
77      }
78  }