001
014
015 package com.liferay.portal.json.transformer;
016
017 import com.liferay.portal.kernel.json.JSONIncludesManagerUtil;
018 import com.liferay.portal.kernel.json.JSONTransformer;
019 import com.liferay.portal.kernel.util.CharPool;
020 import com.liferay.portal.kernel.util.StringBundler;
021 import com.liferay.portal.kernel.util.StringPool;
022
023 import flexjson.JSONContext;
024 import flexjson.Path;
025 import flexjson.PathExpression;
026
027 import flexjson.transformer.ObjectTransformer;
028
029 import java.util.List;
030
031 import jodd.bean.BeanUtil;
032
033
036 public class FlexjsonObjectJSONTransformer
037 extends ObjectTransformer implements JSONTransformer {
038
039 @Override
040 public void transform(Object object) {
041 Class<?> type = resolveClass(object);
042
043 List<PathExpression> pathExpressions =
044 (List<PathExpression>)BeanUtil.getDeclaredProperty(
045 getContext(), "pathExpressions");
046
047 String path = _getPath();
048
049 String[] excludes = JSONIncludesManagerUtil.lookupExcludes(type);
050
051 _exclude(pathExpressions, path, excludes);
052
053 String[] includes = JSONIncludesManagerUtil.lookupIncludes(type);
054
055 _include(pathExpressions, path, includes);
056
057 super.transform(object);
058 }
059
060 private void _exclude(
061 List<PathExpression> pathExpressions, String path, String... names) {
062
063 for (String name : names) {
064 PathExpression pathExpression = new PathExpression(
065 path.concat(name), false);
066
067 for (int i = 0; i < pathExpressions.size(); i++) {
068 PathExpression curPathExpression = pathExpressions.get(i);
069
070 if (pathExpression.equals(curPathExpression) &&
071 curPathExpression.isIncluded()) {
072
073
074
075
076 pathExpressions.set(i, pathExpression);
077
078 return;
079 }
080 }
081
082 pathExpressions.add(pathExpression);
083 }
084 }
085
086 private String _getPath() {
087 JSONContext jsonContext = getContext();
088
089 Path path = jsonContext.getPath();
090
091 List<String> paths = path.getPath();
092
093 if (paths.isEmpty()) {
094 return StringPool.BLANK;
095 }
096
097 StringBundler sb = new StringBundler(paths.size() * 2);
098
099 for (String curPath : paths) {
100 sb.append(curPath);
101 sb.append(CharPool.PERIOD);
102 }
103
104 return sb.toString();
105 }
106
107 private void _include(
108 List<PathExpression> pathExpressions, String path, String... names) {
109
110 for (String name : names) {
111 PathExpression pathExpression = new PathExpression(
112 path.concat(name), true);
113
114 if (!pathExpressions.contains(pathExpression)) {
115 pathExpressions.add(0, pathExpression);
116 }
117 }
118 }
119
120 }