View Javadoc
1   /*
2    * Copyright (C) 2003-2014 eXo Platform SAS.
3    *
4    * This program is free software: you can redistribute it and/or modify
5    * it under the terms of the GNU Affero General Public License as published by
6    * the Free Software Foundation, either version 3 of the License, or
7    * (at your option) any later version.
8    *
9    * This program is distributed in the hope that it will be useful,
10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12   * GNU Affero General Public License for more details.
13   *
14   * You should have received a copy of the GNU Affero General Public License
15   * along with this program. If not, see <http://www.gnu.org/licenses/>.
16   */
17  
18  package org.exoplatform.calendar.ws;
19  
20  import javax.ws.rs.Path;
21  import javax.ws.rs.core.UriInfo;
22  
23  import java.lang.reflect.Method;
24  import java.net.URI;
25  import java.util.LinkedList;
26  import java.util.List;
27  
28  import org.exoplatform.services.rest.resource.ResourceContainer;
29  
30  public class SubResourceHrefBuilder {
31    private List<String> subResources = new LinkedList<String>();
32    
33    public SubResourceHrefBuilder(ResourceContainer restService) {
34      subResources = getResourcesInfo(restService);
35    }
36  
37    public String[] buildResourceMap(UriInfo uriInfo) {
38      List<String> resources = new LinkedList<String>();
39          
40      StringBuilder uriBuilder = new StringBuilder();
41      URI uri = uriInfo.getBaseUri();
42      uriBuilder.append(uri.getScheme()).append("://");
43      uriBuilder.append(uri.getHost());
44      if (uri.getPort() != 80 && uri.getPort() != 443) {
45        uriBuilder.append(":").append(uri.getPort());
46      }
47      uriBuilder.append(uri.getPath());
48      String base = uriBuilder.toString();
49      
50      for (String rs : subResources) {
51        resources.add(base + rs);
52      }
53      return resources.toArray(new String[resources.size()]);
54    }
55    
56    private List<String> getResourcesInfo(ResourceContainer restService) {
57      List<String> subResources = new LinkedList<String>();
58      
59      Path path = restService.getClass().getAnnotation(Path.class);
60      if (path == null) {
61        throw new IllegalStateException("base path for " + restService + " is not found");
62      }
63      String basePath = path.value();
64      
65      for (Method method : restService.getClass().getMethods()) {
66        Path mPath = method.getAnnotation(Path.class);
67        
68        if (mPath != null) {
69          String methodPath = mPath.value();       
70          
71          subResources.add(basePath + methodPath);
72        }
73      }
74      
75      return subResources;
76    }
77  }