| 1 | |
package org.restafarian.core.utils; |
| 2 | |
|
| 3 | |
import java.io.StringWriter; |
| 4 | |
import java.sql.Timestamp; |
| 5 | |
import java.util.Date; |
| 6 | |
|
| 7 | |
import org.apache.commons.beanutils.ConvertUtils; |
| 8 | |
import org.apache.commons.beanutils.Converter; |
| 9 | |
import org.apache.commons.betwixt.io.BeanWriter; |
| 10 | |
import org.apache.commons.betwixt.strategy.ConvertUtilsObjectStringConverter; |
| 11 | |
|
| 12 | |
|
| 13 | |
|
| 14 | |
|
| 15 | 0 | public class BetwixtTool { |
| 16 | |
|
| 17 | |
|
| 18 | |
|
| 19 | |
|
| 20 | |
|
| 21 | |
|
| 22 | |
|
| 23 | |
public static String toXml(Object bean) { |
| 24 | 0 | return toXml(bean, null, true); |
| 25 | |
} |
| 26 | |
|
| 27 | |
|
| 28 | |
|
| 29 | |
|
| 30 | |
|
| 31 | |
|
| 32 | |
|
| 33 | |
|
| 34 | |
public static String toXml(Object bean, String xsl) { |
| 35 | 0 | return toXml(bean, xsl, true); |
| 36 | |
} |
| 37 | |
|
| 38 | |
|
| 39 | |
|
| 40 | |
|
| 41 | |
|
| 42 | |
|
| 43 | |
|
| 44 | |
|
| 45 | |
public static String toXml(Object bean, boolean includeDeclaration) { |
| 46 | 0 | return toXml(bean, null, includeDeclaration); |
| 47 | |
} |
| 48 | |
|
| 49 | |
|
| 50 | |
|
| 51 | |
|
| 52 | |
|
| 53 | |
|
| 54 | |
|
| 55 | |
|
| 56 | |
|
| 57 | |
public static String toXml(Object bean, String xsl, boolean includeDeclaration) { |
| 58 | |
|
| 59 | 0 | Converter dateConverter = new ISO8601DateConverter(); |
| 60 | 0 | ConvertUtils.register(dateConverter, Date.class); |
| 61 | 0 | ConvertUtils.register(dateConverter, Timestamp.class); |
| 62 | 0 | ConvertUtils.register(dateConverter, String.class); |
| 63 | |
|
| 64 | |
|
| 65 | 0 | StringWriter out = new StringWriter(); |
| 66 | 0 | BeanWriter writer = new BeanWriter(out); |
| 67 | 0 | writer.enablePrettyPrint(); |
| 68 | 0 | writer.setInitialIndentLevel(0); |
| 69 | 0 | writer.getBindingConfiguration().setMapIDs(false); |
| 70 | 0 | writer.getBindingConfiguration().setObjectStringConverter(new ConvertUtilsObjectStringConverter()); |
| 71 | |
|
| 72 | |
|
| 73 | 0 | String xml = ""; |
| 74 | |
try { |
| 75 | 0 | if (includeDeclaration) { |
| 76 | 0 | writer.writeXmlDeclaration("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); |
| 77 | 0 | if (xsl != null && !"".equals(xsl.trim())) { |
| 78 | 0 | writer.writeXmlDeclaration("<?xml-stylesheet type=\"text/xsl\" href=\"" + xsl + "\"?>"); |
| 79 | |
} |
| 80 | |
} |
| 81 | 0 | writer.write(bean); |
| 82 | 0 | out.flush(); |
| 83 | 0 | xml = out.toString(); |
| 84 | 0 | } catch (Exception e) { |
| 85 | 0 | e.printStackTrace(); |
| 86 | 0 | } |
| 87 | |
|
| 88 | 0 | return xml; |
| 89 | |
} |
| 90 | |
} |