001
014
015 package com.liferay.portal.jsonwebservice;
016
017 import com.liferay.portal.kernel.jsonwebservice.JSONWebService;
018 import com.liferay.portal.kernel.servlet.HttpMethods;
019 import com.liferay.portal.kernel.util.CamelCaseUtil;
020 import com.liferay.portal.kernel.util.SetUtil;
021 import com.liferay.portal.kernel.util.StringPool;
022 import com.liferay.portal.kernel.util.StringUtil;
023
024 import java.lang.reflect.Method;
025
026 import java.util.Set;
027
028
031 public class JSONWebServiceMappingResolver {
032
033 public String resolveHttpMethod(Method method) {
034 JSONWebService jsonWebServiceAnnotation = method.getAnnotation(
035 JSONWebService.class);
036
037 String httpMethod = null;
038
039 if (jsonWebServiceAnnotation != null) {
040 httpMethod = jsonWebServiceAnnotation.method().trim();
041 }
042
043 if ((httpMethod != null) && (httpMethod.length() != 0)) {
044 return httpMethod;
045 }
046
047 String methodName = method.getName();
048
049 String methodNamePrefix = _cutPrefix(methodName);
050
051 return _prefixToHttpMethod(methodNamePrefix);
052 }
053
054 public String resolvePath(Class<?> clazz, Method method) {
055 JSONWebService jsonWebServiceAnnotation = method.getAnnotation(
056 JSONWebService.class);
057
058 String path = null;
059
060 if (jsonWebServiceAnnotation != null) {
061 path = jsonWebServiceAnnotation.value().trim();
062 }
063
064 if ((path == null) || (path.length() == 0)) {
065 path = CamelCaseUtil.fromCamelCase(method.getName());
066 }
067
068 if (!path.startsWith(StringPool.SLASH)) {
069 path = StringPool.SLASH + path;
070
071 String pathFromClass = null;
072
073 jsonWebServiceAnnotation = clazz.getAnnotation(
074 JSONWebService.class);
075
076 if (jsonWebServiceAnnotation != null) {
077 pathFromClass = jsonWebServiceAnnotation.value().trim();
078 }
079
080 if ((pathFromClass == null) || (pathFromClass.length() == 0)) {
081 pathFromClass = _classNameToPath(clazz);
082 }
083
084 if (!pathFromClass.startsWith(StringPool.SLASH)) {
085 pathFromClass = StringPool.SLASH + pathFromClass;
086 }
087
088 path = pathFromClass + path;
089 }
090
091 return path;
092 }
093
094 private String _classNameToPath(Class<?> clazz) {
095 String className = clazz.getSimpleName();
096
097 className = StringUtil.replace(className, "Impl", StringPool.BLANK);
098 className = StringUtil.replace(className, "Service", StringPool.BLANK);
099
100 return className.toLowerCase();
101 }
102
103 private String _cutPrefix(String methodName) {
104 int i = 0;
105
106 while (i < methodName.length()) {
107 if (Character.isUpperCase(methodName.charAt(i))) {
108 break;
109 }
110
111 i++;
112 }
113
114 return methodName.substring(0, i);
115 }
116
117 private String _prefixToHttpMethod(String prefix) {
118 if (_prefixes.contains(prefix)) {
119 return HttpMethods.GET;
120 }
121
122 return HttpMethods.POST;
123 }
124
125 private static Set<String> _prefixes = SetUtil.fromArray(
126 new String[] {"get", "has", "is"});
127
128 }