001
014
015 package com.liferay.util.xml;
016
017 import com.liferay.portal.kernel.log.Log;
018 import com.liferay.portal.kernel.log.LogFactoryUtil;
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 import com.liferay.portal.kernel.util.TextFormatter;
023 import com.liferay.portal.kernel.xml.Element;
024
025 import java.lang.reflect.Method;
026
027 import java.util.List;
028
029
032 public class BeanToXMLUtil {
033
034 public static void addBean(Object obj, Element parentEl) {
035 String classNameWithoutPackage = getClassNameWithoutPackage(
036 obj.getClass().getName());
037
038 Element el = parentEl.addElement(classNameWithoutPackage);
039
040 addFields(obj, el);
041 }
042
043 public static void addFields(Object obj, Element parentEl) {
044 Method[] methods = obj.getClass().getMethods();
045
046 for (int i = 0; i < methods.length; i++) {
047 Method method = methods[i];
048
049 if (method.getName().startsWith("get") &&
050 !method.getName().equals("getClass")) {
051
052 String memberName = StringUtil.replace(
053 method.getName(), "get", StringPool.BLANK);
054
055 memberName = TextFormatter.format(memberName, TextFormatter.I);
056 memberName = TextFormatter.format(memberName, TextFormatter.K);
057
058 try {
059 Object returnValue = method.invoke(obj, new Object[] {});
060
061 if (returnValue instanceof List<?>) {
062 List<Object> list = (List<Object>)returnValue;
063
064 Element listEl = parentEl.addElement(memberName);
065
066 for (int j = 0; j < list.size(); j++) {
067 addBean(list.get(j), listEl);
068 }
069 }
070 else {
071 DocUtil.add(
072 parentEl, memberName, returnValue.toString());
073 }
074 }
075 catch (Exception e) {
076 if (_log.isWarnEnabled()) {
077 _log.warn(e.getMessage());
078 }
079 }
080 }
081 }
082 }
083
084 public static String getClassNameWithoutPackage(String className) {
085 String[] classNameArray = StringUtil.split(className, CharPool.PERIOD);
086
087 String classNameWithoutPackage =
088 classNameArray[classNameArray.length - 1];
089
090 classNameWithoutPackage = TextFormatter.format(
091 classNameWithoutPackage, TextFormatter.I);
092 classNameWithoutPackage = TextFormatter.format(
093 classNameWithoutPackage, TextFormatter.K);
094
095 return classNameWithoutPackage;
096 }
097
098 private static Log _log = LogFactoryUtil.getLog(BeanToXMLUtil.class);
099
100 }