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