PageRenderTime 70ms CodeModel.GetById 32ms RepoModel.GetById 1ms app.codeStats 0ms

/smooks-examples/dao-router/src/main/java/example/Main.java

https://github.com/zubairov/smooks
Java | 346 lines | 230 code | 94 blank | 22 comment | 4 complexity | 07f3639cdaa875c0e31172bbf246ce9f MD5 | raw file
  1. /*
  2. Milyn - Copyright (C) 2006 - 2010
  3. This library is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU Lesser General Public
  5. License (version 2.1) as published by the Free Software
  6. Foundation.
  7. This library is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  10. See the GNU Lesser General Public License for more details:
  11. http://www.gnu.org/licenses/lgpl.txt
  12. */
  13. package example;
  14. import java.io.BufferedReader;
  15. import java.io.ByteArrayInputStream;
  16. import java.io.FileInputStream;
  17. import java.io.IOException;
  18. import java.io.InputStream;
  19. import java.io.InputStreamReader;
  20. import java.io.Reader;
  21. import java.sql.SQLException;
  22. import java.util.List;
  23. import java.util.Map;
  24. import java.util.Set;
  25. import javax.persistence.EntityManager;
  26. import javax.persistence.EntityManagerFactory;
  27. import javax.persistence.EntityTransaction;
  28. import javax.persistence.Persistence;
  29. import javax.xml.transform.stream.StreamSource;
  30. import org.milyn.Smooks;
  31. import org.milyn.SmooksException;
  32. import org.milyn.container.ExecutionContext;
  33. import org.milyn.event.report.HtmlReportGenerator;
  34. import org.milyn.io.StreamUtils;
  35. import org.milyn.persistence.util.PersistenceUtil;
  36. import org.milyn.routing.db.StatementExec;
  37. import org.milyn.scribe.adapter.ibatis.SqlMapClientRegister;
  38. import org.milyn.scribe.adapter.jpa.EntityManagerRegister;
  39. import org.milyn.scribe.register.DaoRegister;
  40. import org.milyn.scribe.register.MapDaoRegister;
  41. import org.milyn.util.HsqlServer;
  42. import org.xml.sax.SAXException;
  43. import com.ibatis.common.resources.Resources;
  44. import com.ibatis.sqlmap.client.SqlMapClient;
  45. import com.ibatis.sqlmap.client.SqlMapClientBuilder;
  46. import example.dao.CustomerDao;
  47. import example.dao.OrderDao;
  48. import example.dao.ProductDao;
  49. /**
  50. * Simple example main class.
  51. * @author <a href="mailto:tom.fennelly@gmail.com">tom.fennelly@gmail.com</a>
  52. */
  53. public class Main {
  54. private HsqlServer dbServer;
  55. private EntityManagerFactory emf;
  56. private EntityManager em;
  57. private SqlMapClient sqlMapClient;
  58. public static byte[] messageInDao = readInputMessage("dao");
  59. public static byte[] messageInJpa = readInputMessage("jpa");
  60. public static byte[] messageInIbatis = readInputMessage("ibatis");
  61. public static void main(String[] args) throws Exception {
  62. Main main = new Main();
  63. System.out.println("\n\nThis sample will use Smooks to extract data from an message and load it into a Database (Hypersonic)\n");
  64. try {
  65. Main.pause("First the database needs be started. Press return to start the database...");
  66. main.startDatabase();
  67. main.initDatabase();
  68. main.createSqlMapInstance();
  69. System.out.println();
  70. Main.pause("The database is started now. Press return to see its contents.");
  71. main.printOrders();
  72. System.out.println();
  73. System.out.println("\n\nThis first run Smooks will use data access objects (DAOs) to persist and lookup entities.");
  74. Main.pause("Press return to see the sample message for the first run..");
  75. System.out.println("\n" + new String(messageInDao) + "\n");
  76. Main.pause("Press return to execute Smooks.");
  77. main.runSmooksTransformWithDao();
  78. System.out.println();
  79. Main.pause("Smooks has processed the message. Now press return to view the contents of the database again. This time there should be orders and orderlines...");
  80. main.printOrders();
  81. System.out.println("\n\nThis second run Smooks will use JPA to persist and lookup entities.");
  82. Main.pause("Press return to see the sample message for the second run..");
  83. System.out.println("\n" + new String(messageInJpa) + "\n");
  84. System.out.println();
  85. Main.pause("Press return to execute Smooks.");
  86. main.runSmooksTransformWithJpa();
  87. System.out.println();
  88. Main.pause("Smooks has processed the message. Now press return to view the contents of the database again. There should be new orders and orderlines...");
  89. main.printOrders();
  90. System.out.println("\n\nThis third run Smooks will use iBatis to persist and lookup entities.");
  91. Main.pause("Press return to see the sample message for the second run..");
  92. System.out.println("\n" + new String(messageInIbatis) + "\n");
  93. System.out.println();
  94. Main.pause("Now press return to execute Smooks.");
  95. main.runSmooksTransformWithIbatis();
  96. Main.pause("Smooks has processed the message. Now press return to view the contents of the database again. There should be new orders and orderlines...");
  97. main.printOrders();
  98. Main.pause("And that's it! Press return exit...");
  99. } finally {
  100. main.stopDatabase();
  101. }
  102. }
  103. protected void runSmooksTransformWithDao() throws IOException, SAXException, SmooksException {
  104. Smooks smooks = new Smooks("./smooks-configs/smooks-dao-config.xml");
  105. try {
  106. ExecutionContext executionContext = smooks.createExecutionContext();
  107. // Configure the execution context to generate a report...
  108. executionContext.setEventListener(new HtmlReportGenerator("target/report/report-dao.html"));
  109. DaoRegister<Object> register =
  110. MapDaoRegister.builder()
  111. .put("product", new ProductDao(em))
  112. .put("customer", new CustomerDao(em))
  113. .put("order", new OrderDao(em))
  114. .build();
  115. PersistenceUtil.setDAORegister(executionContext, register);
  116. EntityTransaction tx = em.getTransaction();
  117. tx.begin();
  118. smooks.filterSource(executionContext, new StreamSource(new ByteArrayInputStream(messageInDao)));
  119. tx.commit();
  120. } finally {
  121. smooks.close();
  122. }
  123. }
  124. protected void runSmooksTransformWithJpa() throws IOException, SAXException, SmooksException {
  125. Smooks smooks = new Smooks("./smooks-configs/smooks-jpa-config.xml");
  126. try {
  127. ExecutionContext executionContext = smooks.createExecutionContext();
  128. // Configure the execution context to generate a report...
  129. executionContext.setEventListener(new HtmlReportGenerator("target/report/report-jpa.html"));
  130. PersistenceUtil.setDAORegister(executionContext, new EntityManagerRegister(em));
  131. EntityTransaction tx = em.getTransaction();
  132. tx.begin();
  133. smooks.filterSource(executionContext, new StreamSource(new ByteArrayInputStream(messageInJpa)));
  134. tx.commit();
  135. } finally {
  136. smooks.close();
  137. }
  138. }
  139. protected void runSmooksTransformWithIbatis() throws IOException, SAXException, SmooksException, SQLException {
  140. Smooks smooks = new Smooks("./smooks-configs/smooks-ibatis-config.xml");
  141. try {
  142. ExecutionContext executionContext = smooks.createExecutionContext();
  143. // Configure the execution context to generate a report...
  144. executionContext.setEventListener(new HtmlReportGenerator("target/report/report-ibatis.html"));
  145. PersistenceUtil.setDAORegister(executionContext, new SqlMapClientRegister(sqlMapClient));
  146. sqlMapClient.startTransaction();
  147. smooks.filterSource(executionContext, new StreamSource(new ByteArrayInputStream(messageInIbatis)));
  148. sqlMapClient.commitTransaction();
  149. } finally {
  150. sqlMapClient.endTransaction();
  151. smooks.close();
  152. }
  153. }
  154. public void printOrders() throws SQLException {
  155. List<Map<String, Object>> customers = getCustomers();
  156. List<Map<String, Object>> products = getProducts();
  157. List<Map<String, Object>> orders = getOrders();
  158. List<Map<String, Object>> orderItems = getOrderItems();
  159. printResultSet("Customers", customers);
  160. printResultSet("Products", products);
  161. printResultSet("Orders", orders);
  162. printResultSet("Order Items", orderItems);
  163. }
  164. public List<Map<String, Object>> getOrders() throws SQLException {
  165. StatementExec exec1OrderItems = new StatementExec("select * from orders");
  166. List<Map<String, Object>> rows = exec1OrderItems.executeUnjoinedQuery(dbServer.getConnection());
  167. return rows;
  168. }
  169. public List<Map<String, Object>> getOrderItems() throws SQLException {
  170. StatementExec exec1OrderItems = new StatementExec("select * from orderlines");
  171. List<Map<String, Object>> rows = exec1OrderItems.executeUnjoinedQuery(dbServer.getConnection());
  172. return rows;
  173. }
  174. public List<Map<String, Object>> getProducts() throws SQLException {
  175. StatementExec exec1OrderItems = new StatementExec("select * from products");
  176. List<Map<String, Object>> rows = exec1OrderItems.executeUnjoinedQuery(dbServer.getConnection());
  177. return rows;
  178. }
  179. public List<Map<String, Object>> getCustomers() throws SQLException {
  180. StatementExec exec1OrderItems = new StatementExec("select * from customers");
  181. List<Map<String, Object>> rows = exec1OrderItems.executeUnjoinedQuery(dbServer.getConnection());
  182. return rows;
  183. }
  184. private void printResultSet(String name, List<Map<String, Object>> resultSet) {
  185. System.out.println(("---- " + name + " -------------------------------------------------------------------------------------------------").substring(0, 80));
  186. if(resultSet.isEmpty()) {
  187. System.out.println("(No rows)");
  188. } else {
  189. for(int i = 0; i < resultSet.size(); i++) {
  190. Set<Map.Entry<String, Object>> row = resultSet.get(i).entrySet();
  191. System.out.println("Row " + i + ":");
  192. for (Map.Entry<String, Object> field : row) {
  193. System.out.println("\t" + field.getKey() + ":\t" + field.getValue());
  194. }
  195. }
  196. }
  197. System.out.println(("---------------------------------------------------------------------------------------------------------------------").substring(0, 80));
  198. }
  199. public void startDatabase() throws Exception {
  200. dbServer = new HsqlServer(9201);
  201. emf = Persistence.createEntityManagerFactory("db");
  202. em = emf.createEntityManager();
  203. }
  204. public void initDatabase() throws Exception {
  205. InputStream schema = new FileInputStream("init-db.sql");
  206. try {
  207. dbServer.execScript(schema);
  208. } finally {
  209. schema.close();
  210. }
  211. }
  212. void stopDatabase() throws Exception {
  213. try {
  214. em.close();
  215. } catch (Exception e) {
  216. }
  217. try {
  218. emf.close();
  219. } catch (Exception e) {
  220. }
  221. dbServer.stop();
  222. }
  223. private static byte[] readInputMessage(String msg) {
  224. try {
  225. return StreamUtils.readStream(new FileInputStream("input-message-"+ msg +".xml"));
  226. } catch (IOException e) {
  227. e.printStackTrace();
  228. return "<no-message/>".getBytes();
  229. }
  230. }
  231. private void createSqlMapInstance() {
  232. try {
  233. String resource = "ibatis/sql-map-config.xml";
  234. Reader reader = Resources.getResourceAsReader(resource);
  235. sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
  236. } catch (Exception e) {
  237. throw new RuntimeException("Error initializing SqlMapConfig class. Cause: " + e);
  238. }
  239. }
  240. static void pause(String message) {
  241. try {
  242. BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  243. System.out.print("> " + message);
  244. in.readLine();
  245. } catch (IOException e) {
  246. }
  247. System.out.println("\n");
  248. }
  249. }