View Javadoc
1   /*
2    * Copyright (C) 2003-2015 eXo Platform SAS.
3    *
4    * This program is free software; you can redistribute it and/or
5    * modify it under the terms of the GNU Affero General Public License
6    * as published by the Free Software Foundation; either version 3
7    * of the License, or (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 General Public License for more details.
13   *
14   * You should have received a copy of the GNU General Public License
15   * along with this program; if not, see<http://www.gnu.org/licenses/>.
16  */
17  
18  package org.exoplatform.social.rest.api;
19  
20  import java.text.ParseException;
21  import java.text.SimpleDateFormat;
22  import java.util.Calendar;
23  import java.util.Date;
24  import java.util.List;
25  import java.util.Map;
26  import java.util.TimeZone;
27  
28  import javax.ws.rs.WebApplicationException;
29  import javax.ws.rs.core.MediaType;
30  import javax.ws.rs.core.Response.Status;
31  import javax.ws.rs.core.UriInfo;
32  
33  import org.exoplatform.commons.utils.CommonsUtils;
34  import org.exoplatform.commons.utils.ISO8601;
35  import org.exoplatform.services.rest.impl.ApplicationContextImpl;
36  import org.exoplatform.services.security.ConversationState;
37  import org.exoplatform.services.security.IdentityConstants;
38  import org.exoplatform.social.rest.entity.DataEntity;
39  
40  public class RestUtils {
41  
42    public static final int    DEFAULT_LIMIT  = 20;
43  
44    public static final int    DEFAULT_OFFSET = 0;
45  
46    public static final int    HARD_LIMIT     = 50;
47  
48    public static final String SUPPORT_TYPE   = "json";
49  
50    public static final String ADMIN_GROUP    = "/platform/administrators";
51    
52    public static String formatISO8601(Date date) {
53      Calendar calendar = Calendar.getInstance();
54      calendar.setTime(date);
55      return ISO8601.format(calendar);
56    }
57  
58    /**
59     * Gets the json media type
60     * 
61     * @return a media type
62     */
63    public static MediaType getJsonMediaType() {
64      return getMediaType(SUPPORT_TYPE, new String[]{SUPPORT_TYPE});
65    }
66    
67    /**
68     * Gets the media type from an expected format string (usually the input) and an array of supported format strings.
69     * If expectedFormat is not found in the supported format array, Status.UNSUPPORTED_MEDIA_TYPE is thrown.
70     * The supported format must include one of those format: json, xml, atom or rss, otherwise Status.NOT_ACCEPTABLE
71     * could be thrown.
72     *
73     * @param expectedFormat the expected input format
74     * @param supportedFormats the supported format array
75     * @return the associated media type
76     */
77    public static MediaType getMediaType(String expectedFormat, String[] supportedFormats) {
78  
79      if (!isSupportedFormat(expectedFormat, supportedFormats)) {
80        throw new WebApplicationException(Status.UNSUPPORTED_MEDIA_TYPE);
81      }
82  
83      if (expectedFormat.equals("json") && isSupportedFormat("json", supportedFormats)) {
84        return MediaType.APPLICATION_JSON_TYPE;
85      } else if (expectedFormat.equals("xml") && isSupportedFormat("xml", supportedFormats)) {
86        return MediaType.APPLICATION_XML_TYPE;
87      } else if (expectedFormat.equals("atom") && isSupportedFormat("atom", supportedFormats)) {
88        return MediaType.APPLICATION_ATOM_XML_TYPE;
89      }
90      //TODO What's about RSS format?
91      throw new WebApplicationException(Status.NOT_ACCEPTABLE);
92    }
93  
94    /**
95     * Checks if an expected format is supported not not.
96     *
97     * @param expectedFormat the expected format
98     * @param supportedFormats the array of supported format
99     * @return true or false
100    */
101   private static boolean isSupportedFormat(String expectedFormat, String[] supportedFormats) {
102     for (String supportedFormat : supportedFormats) {
103       if (supportedFormat.equals(expectedFormat)) {
104         return true;
105       }
106     }
107     return false;
108   }
109   
110   /**
111    * Check if the authenticated user is a member of the admin group
112    * 
113    * @return
114    */
115   public static boolean isMemberOfAdminGroup() {
116     return ConversationState.getCurrent().getIdentity().isMemberOf(ADMIN_GROUP);
117   }
118   
119   /** 
120    * Get base url of rest service
121    * 
122    * @param type the type of rest service
123    * @param id the id of object
124    * 
125    * @return base rest url like : http://localhost:8080/rest/v1/social/users/123456
126    */
127   public static String getRestUrl(String type, String id, String restPath) {
128     String version = restPath.split("/")[1]; // path /v1/social/identities
129     String socialResource = restPath.split("/")[2]; // path /v1/social/identities
130     
131     return new StringBuffer(getBaseRestUrl())
132     .append("/").append(version)
133     .append("/").append(socialResource)
134     .append("/").append(type)
135     .append("/").append(id).toString();
136   }
137 
138   /** 
139    * Get base url of rest service
140    * 
141    * @return base rest url like : https://localhost:8080/rest
142    */
143   public static String getBaseRestUrl() {
144     return new StringBuffer(getBaseUrl()).append("/").append(CommonsUtils.getRestContextName()).toString();
145   }
146 
147   /** 
148    * Get base url of rest service
149    * 
150    * @return base rest url like : https://localhost:8080
151    */
152   public static String getBaseUrl() {
153     String fullUrl = ApplicationContextImpl.getCurrent().getBaseUri().toString();
154     return (fullUrl != null && !fullUrl.isEmpty()) ? fullUrl.substring(0, fullUrl.indexOf("/", 9)) : "";
155   }
156 
157   /**
158    * Check if the current user is authenticated
159    * 
160    * @return true if user not authenticated
161    */
162   public static boolean isAnonymous() {
163     return IdentityConstants.ANONIM.equals(ConversationState.getCurrent().getIdentity().getUserId());
164   }
165   
166   public static String getPathParam(UriInfo uriInfo, String name) {
167     return uriInfo.getPathParameters().getFirst(name);
168   }
169 
170   public static String getQueryParam(UriInfo uriInfo, String name) {
171     return uriInfo.getQueryParameters().getFirst(name);
172   }
173 
174   public static int getLimit(UriInfo uriInfo) {
175     Integer limit = getIntegerValue(uriInfo, "limit");
176     return (limit != null && limit > 0) ? Math.min(HARD_LIMIT, limit) : DEFAULT_LIMIT;
177   }
178 
179   public static int getOffset(UriInfo uriInfo) {
180     Integer offset = getIntegerValue(uriInfo, "offset");
181     return (offset != null) ? offset : 0;
182   }
183 
184   public static Integer getIntegerValue(UriInfo uriInfo, String name) {
185     String value = getQueryParam(uriInfo, name);
186     if (value == null)
187       return null;
188     try {
189       return Integer.parseInt(value);
190     } catch (NumberFormatException e) {
191       return null;
192     }
193   }
194 
195   public static Long getLongValue(UriInfo uriInfo, String name) {
196     String value = getQueryParam(uriInfo, name);
197     if (value == null)
198       return null;
199     try {
200       return Long.valueOf(value);
201     } catch (NumberFormatException e) {
202       return null;
203     }
204   }
205 
206   public static boolean isReturnSize(UriInfo uriInfo) {
207     return Boolean.parseBoolean(getQueryParam(uriInfo, "returnSize"));
208   }
209   
210   public static DataEntity extractInfo(DataEntity inEntity, List<String> returnedProperties) {
211     DataEntity outEntity = new DataEntity();
212     for (Map.Entry<String, Object> entry : inEntity.entrySet()) {
213       if (returnedProperties.contains(entry.getKey())) {
214         outEntity.setProperty(entry.getKey(), entry.getValue());
215       }
216     }
217     return outEntity;
218   }
219   
220   public static long getBaseTime(String baseDateTime) throws ParseException {
221     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
222     sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
223     Date date = sdf.parse(baseDateTime);
224     return date.getTime(); 
225   }
226 }