View Javadoc

1   package com.atlassian.plugins.rest.sample.helloworld;
2   
3   import org.apache.commons.lang.StringUtils;
4   
5   import java.net.URI;
6   import java.net.URISyntaxException;
7   import java.util.LinkedList;
8   import java.util.List;
9   
10  public class UriBuilder
11  {
12      private static final String CONTEXT_SYSTEM_PROPERTY = "context.path";
13      private static final String HTTP_PORT_SYSTEM_PROPERTY = "http.port";
14      private static final int DEFAULT_HTTP_PORT = 0;
15  
16      private final static String CONTEXT;
17      private final static int HTTP_PORT;
18  
19      static
20      {
21          CONTEXT = System.getProperty(CONTEXT_SYSTEM_PROPERTY);
22          HTTP_PORT = Integer.valueOf(System.getProperty(HTTP_PORT_SYSTEM_PROPERTY, String.valueOf(DEFAULT_HTTP_PORT)));
23  
24          if (CONTEXT == null || HTTP_PORT == DEFAULT_HTTP_PORT)
25          {
26              throw new IllegalStateException(CONTEXT_SYSTEM_PROPERTY + " or " + HTTP_PORT_SYSTEM_PROPERTY + " not set!");
27          }
28      }
29  
30      private final List<String> paths = new LinkedList<String>();
31  
32      private UriBuilder()
33      {
34      }
35  
36      public static UriBuilder create()
37      {
38          return new UriBuilder();
39      }
40  
41      public UriBuilder path(String path)
42      {
43          paths.add(path);
44          return this;
45      }
46  
47      public URI build()
48      {
49          try
50          {
51              return new URI("http", null, "localhost", HTTP_PORT, buildPath(), buildQuery(), buildFragment());
52          }
53          catch (URISyntaxException e)
54          {
55              // will not happen
56              return null;
57          }
58      }
59  
60      private String buildPath()
61      {
62          final StringBuilder path = new StringBuilder(paths.size() * 8);
63          if (StringUtils.isNotBlank(CONTEXT))
64          {
65              path.append(CONTEXT).append("/");
66          }
67          for (String element : paths)
68          {
69              path.append(element).append("/");
70          }
71          if (path.charAt(0) != '/')
72          {
73              path.insert(0, '/');
74          }
75          return path.toString();
76      }
77  
78      private String buildQuery()
79      {
80          return null;
81      }
82  
83      private String buildFragment()
84      {
85          return null;
86      }
87  }