Guest User

Untitled

a guest
May 31st, 2018
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 19.80 KB | None | 0 0
  1. package eu.epitech.epimarket.mapper;
  2.  
  3. import java.beans.BeanInfo;
  4. import java.beans.Introspector;
  5. import java.beans.PropertyDescriptor;
  6. import java.lang.reflect.Method;
  7. import java.sql.Connection;
  8. import java.sql.DriverManager;
  9. import java.sql.PreparedStatement;
  10. import java.sql.ResultSet;
  11. import java.sql.SQLException;
  12. import java.util.ArrayList;
  13. import java.util.List;
  14.  
  15. import com.mysql.jdbc.ResultSetMetaData;
  16. import com.mysql.jdbc.Statement;
  17.  
  18. public class ObjectMapper {
  19.  
  20. private boolean registered = false;
  21. Connection connection;
  22.  
  23. public ObjectMapper()
  24. {
  25. }
  26.  
  27. private void register() throws RuntimeException {
  28. if (!registered) {
  29. try {
  30. Class.forName("com.mysql.jdbc.Driver").newInstance();
  31. } catch (Exception e) {
  32. throw new RuntimeException(e.getMessage());
  33. }
  34. registered = true;
  35. }
  36. }
  37.  
  38. protected void getConnection() throws RuntimeException
  39. {
  40. try {
  41.  
  42. register();
  43. this.connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/epimarket", "root", "");
  44.  
  45. } catch (Exception e) {
  46. throw new RuntimeException(e.getMessage());
  47. }
  48. }
  49. /* ----------------------------- FIND -------------------------------------------*/
  50.  
  51. public String findEntity(String key, String table)
  52. {
  53. String sql = "";
  54. PreparedStatement statement = null;
  55. String tmpString = "";
  56.  
  57. try {
  58. this.getConnection();
  59. sql = "SELECT ID FROM " + table + " WHERE NAME = " + key;
  60. statement = this.connection.prepareStatement(sql);
  61. ResultSet p = statement.executeQuery();
  62. try {
  63. p.next();
  64. } catch (SQLException e) {
  65. e.printStackTrace();
  66. }
  67. try {
  68. tmpString = (String)p.getObject("ID");
  69. } catch (SQLException e) {
  70. e.printStackTrace();
  71. }
  72. }
  73. catch (Exception e) {
  74. throw new RuntimeException(e.getMessage());
  75. }
  76. return (tmpString);
  77. }
  78.  
  79. /* ----------------------------- UPDATE --------------------------------------- */
  80. public void updateEntity(Object object)
  81. {
  82. String sql = "UPDATE ";
  83. BeanInfo beanInfo = null;
  84. boolean first = true;
  85. String id = "";
  86. PreparedStatement statement = null;
  87.  
  88. try
  89. {
  90. this.getConnection();
  91. sql += object.getClass().getSimpleName().substring(0, object.getClass().getSimpleName().length() - "Bean".length());
  92. sql += "_ENTITY";
  93. sql += " SET ";
  94. beanInfo = Introspector.getBeanInfo(object.getClass());
  95. for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
  96. String column = property.getName();
  97. if (column.compareTo("class") != 0 && column.toUpperCase().contains("ID") == false)
  98. {
  99. if (!first)
  100. sql += ", ";
  101. sql += column.toUpperCase();
  102. sql += " = ";
  103. if (property.getReadMethod().toString().contains("getChildList()") ||
  104. property.getReadMethod().toString().contains("getFatherList()"))
  105. {
  106. column = "";
  107. @SuppressWarnings("unchecked")
  108. List<Object> oList = (List<java.lang.Object>) property.getReadMethod().invoke(object);
  109. for (Object p : oList)
  110. {
  111. Method t = p.getClass().getMethod("getId");
  112. if (column != "")
  113. column += ",";
  114. else
  115. column = "'";
  116. column += t.invoke(p);
  117. }
  118. if (oList.size() == 0)
  119. sql += "NULL";
  120. else {
  121. sql += column + "'";
  122. }
  123. }
  124. else
  125. sql += "'" + property.getReadMethod().invoke(object).toString() + "'";
  126. first = false;
  127. }
  128. else if (column.toUpperCase().contains("ID"))
  129. id = property.getReadMethod().invoke(object).toString();
  130. }
  131. sql += " WHERE ID = '" + id + "'";
  132. statement = this.connection.prepareStatement(sql);
  133. statement.executeUpdate();
  134. }
  135. catch (Exception e)
  136. {
  137. throw new RuntimeException(e.getMessage());
  138. }
  139. }
  140. /* ----------------------------- CREATE ----------------------------------------*/
  141. public void writeEntity(Object object)
  142. {
  143. String sql = "INSERT INTO ENTITYLIST (ENTITY_ID, ENTITY_TYPE) VALUES(NULL, ?)";
  144. PreparedStatement statement = null;
  145. ResultSet rs = null;
  146. String key = "";
  147. BeanInfo beanInfo = null;
  148.  
  149. try
  150. {
  151. this.getConnection();
  152.  
  153. /*---------INSERTION DANS LA ENTITYLIST----------*/
  154. statement = this.connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
  155. statement.setString(1, object.getClass().getSimpleName().substring(0, object.getClass().getSimpleName().length() - "Bean".length()));
  156. statement.executeUpdate();
  157. rs = statement.getGeneratedKeys();
  158. if (rs.next()) {
  159. ResultSetMetaData rsmd = (ResultSetMetaData) rs.getMetaData();
  160. int colCount = rsmd.getColumnCount();
  161. do {
  162. for (int i = 1; i <= colCount; i++) {
  163. key = rs.getString(i);
  164. }
  165. }
  166. while (rs.next());
  167. }
  168. else {
  169. throw new RuntimeException("Unable to retrieve Generated KEY.");
  170. }
  171. /*--------INSERTION DANS LA TABLE ASSOCIATIVE-------*/
  172. sql = "INSERT INTO ";
  173. sql += object.getClass().getSimpleName().substring(0, object.getClass().getSimpleName().length() - "Bean".length()).toUpperCase() + "_ENTITY ";
  174. sql += "(ID";
  175. beanInfo = Introspector.getBeanInfo(object.getClass());
  176. for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
  177. String column = property.getName();
  178. if (column.compareTo("class") != 0 && column.toUpperCase().contains("ID") == false)
  179. sql += "," + column.toUpperCase();
  180. }
  181. sql += ") VALUES('" + key + "'";
  182. for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
  183. String column = "";
  184. if (property.getReadMethod().toString().contains("getChildList()") ||
  185. property.getReadMethod().toString().contains("getFatherList()"))
  186. {
  187. @SuppressWarnings("unchecked")
  188. List<Object> oList = (List<java.lang.Object>) property.getReadMethod().invoke(object);
  189. for (Object p : oList)
  190. {
  191. Method t = p.getClass().getMethod("getId");
  192. if (column != "")
  193. column += ",";
  194. else
  195. column = "'";
  196. column += t.invoke(p);
  197. }
  198. if (oList.size() == 0)
  199. sql += ",NULL";
  200. else {
  201. sql += "," + column + "'";
  202. }
  203. }
  204. else if (property.getReadMethod().toString().contains("public final native java.lang.Class") == false &&
  205. property.getReadMethod().toString().contains(".getId()") == false)
  206. {
  207. column = property.getReadMethod().invoke(object).toString();
  208. sql += ",'" + column + "'";
  209. }
  210. }
  211. sql += ")";
  212. statement = this.connection.prepareStatement(sql);
  213. statement.executeUpdate();
  214.  
  215. Method t = object.getClass().getMethod("setId", int.class);
  216. t.invoke(object, Integer.parseInt(key));
  217. }
  218. catch (Exception e) {
  219. throw new RuntimeException(e.getMessage());
  220. }
  221. }
  222.  
  223. /* ----------------------------- READ ----------------------------------------*/
  224. private String getTypeOfEntity(int key) throws RuntimeException
  225. {
  226. this.getConnection();
  227.  
  228. String result = null;
  229. String request = "SELECT ENTITY_TYPE FROM ENTITYLIST WHERE ENTITY_ID = ?";
  230. PreparedStatement statement = null;
  231. ResultSet resultset = null;
  232.  
  233. try {
  234. statement = this.connection.prepareStatement(request);
  235. statement.setInt(1, key);
  236. resultset = statement.executeQuery();
  237.  
  238. while (resultset.next())
  239. result = (String)resultset.getObject(1);
  240. } catch (Exception e) {
  241. throw new RuntimeException(e.getMessage());
  242. }
  243.  
  244. if (result == null)
  245. throw new RuntimeException("Null String");
  246. return (result);
  247. }
  248.  
  249. @SuppressWarnings({ "rawtypes" })
  250. private Class getClassByKey(int key) throws RuntimeException
  251. {
  252. String className;
  253. Class requestClass = null;
  254.  
  255. try {
  256.  
  257. className = getTypeOfEntity(key);
  258. requestClass = Class.forName("eu.epitech.epimarket.entity." + className + "Bean");
  259.  
  260. } catch (Exception e) {
  261. throw new RuntimeException(e.getMessage());
  262. }
  263.  
  264. if (requestClass == null)
  265. throw new RuntimeException("Null Class");
  266.  
  267. return (requestClass);
  268. }
  269.  
  270. private ResultSet launchRequest(String request, int key) throws RuntimeException
  271. {
  272. PreparedStatement statement = null;
  273. ResultSet resultset = null;
  274.  
  275. try {
  276.  
  277. statement = this.connection.prepareStatement(request);
  278. statement.setInt(1, key);
  279. resultset = statement.executeQuery();
  280. } catch (Exception e) {
  281. throw new RuntimeException(e.getMessage());
  282. }
  283. return (resultset);
  284. }
  285.  
  286. @SuppressWarnings("rawtypes")
  287. private String prepareRequest(Class requestClass) throws RuntimeException
  288. {
  289. String request = "SELECT ";
  290. boolean first = true;
  291. BeanInfo beanInfo;
  292.  
  293. try {
  294.  
  295. beanInfo = Introspector.getBeanInfo(requestClass);
  296. for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
  297. String column = property.getName();
  298. if (column.compareTo("class") != 0)
  299. {
  300. if (!first) {
  301. request += ",";
  302. }
  303. request += column.toUpperCase();
  304. first = false;
  305. }
  306. }
  307. String cleanClassName = requestClass.getName().substring(requestClass.getName().lastIndexOf(".") + 1, requestClass.getName().length() - 4);
  308. request += " FROM ";
  309. request += cleanClassName.toUpperCase() + "_ENTITY";
  310. request += " WHERE ID=?;";
  311.  
  312. } catch (Exception e) {
  313. throw new RuntimeException(e.getMessage());
  314. }
  315.  
  316. return (request);
  317. }
  318.  
  319. @SuppressWarnings({ "unused", "rawtypes" })
  320. private Object buildObject(ResultSet resultSet, Class requestClass) throws RuntimeException
  321. {
  322. BeanInfo beanInfo = null;
  323. Object object = null;
  324.  
  325. try {
  326. object = requestClass.newInstance();
  327. beanInfo = Introspector.getBeanInfo(requestClass);
  328. Method classMethod[] = object.getClass().getMethods();
  329.  
  330. resultSet.next();
  331.  
  332. int i = 0;
  333. while (i < classMethod.length)
  334. {
  335. if (classMethod[i].toString().contains(".set"))
  336. {
  337. String cleanMethodName = classMethod[i].toString().substring(classMethod[i].toString().lastIndexOf("set") + 3, classMethod[i].toString().indexOf("("));
  338. Object result = null;
  339. result = resultSet.getObject(cleanMethodName.toUpperCase());
  340. classMethod[i].invoke(object, result);
  341. }
  342. ++i;
  343. }
  344.  
  345. } catch (Exception e) {
  346. throw new RuntimeException(e.getMessage());
  347. }
  348. if (object == null)
  349. throw new RuntimeException("Null Object");
  350. return (object);
  351. }
  352.  
  353. private String[] getChildList(ResultSet resultSet)
  354. {
  355. String[] childList = null;
  356. String childString = null;
  357.  
  358. try {
  359.  
  360. childString = (String)resultSet.getObject("CHILDLIST");
  361. if (childString == null || childString.isEmpty())
  362. return (null);
  363. childList = childString.split(",");
  364.  
  365. } catch (SQLException e) {
  366. return (null);
  367. }
  368.  
  369. return (childList);
  370. }
  371.  
  372. @SuppressWarnings("unused")
  373. private String[] getParentList(ResultSet resultSet)
  374. {
  375. String[] childList = null;
  376. String childString = null;
  377.  
  378. try {
  379.  
  380. childString = (String)resultSet.getObject("FATHERLIST");
  381. if (childString == null || childString.isEmpty())
  382. return (null);
  383. childList = childString.split(",");
  384.  
  385. } catch (SQLException e) {
  386. return (null);
  387. }
  388.  
  389. return (childList);
  390. }
  391.  
  392. private Object doRecursivity(Object object, ResultSet resultSet, String[] childList, List<Integer> antiloop) throws RuntimeException
  393. {
  394. for (String sId : childList)
  395. {
  396. Integer id = Integer.parseInt(sId);
  397. if (antiloop.contains(id) == false)
  398. {
  399. try
  400. {
  401. Object tmp = this.recursiveReadEntity(id, true, antiloop);
  402. Method m = object.getClass().getMethod("addChild", Object.class);
  403. m.invoke(object, tmp);
  404.  
  405. } catch (Exception e) {
  406. throw new RuntimeException(e.getMessage());
  407. }
  408. }
  409. }
  410. return (object);
  411. }
  412.  
  413. @SuppressWarnings("rawtypes")
  414. private Object recursiveReadEntity(int key, boolean recursive, List<Integer> antiloop) throws RuntimeException
  415. {
  416. String request = null;
  417. Class requestClass = null;
  418. ResultSet resultSet = null;
  419. Object object = null;
  420. String[] childList = null;
  421.  
  422. if (antiloop == null)
  423. antiloop = new ArrayList<Integer>();
  424. antiloop.add(new Integer(key));
  425.  
  426. this.getConnection();
  427.  
  428. requestClass = this.getClassByKey(key);
  429. request = this.prepareRequest(requestClass);
  430. resultSet = this.launchRequest(request, key);
  431.  
  432. if (resultSet == null)
  433. throw new RuntimeException("Null ResultSet");
  434.  
  435. object = this.buildObject(resultSet, requestClass);
  436.  
  437. if (recursive && (childList = this.getChildList(resultSet)) != null)
  438. object = doRecursivity(object, resultSet, childList, antiloop);
  439. return (object);
  440. }
  441.  
  442. public Object readEntity(int key, boolean recursive) throws RuntimeException
  443. {
  444. return (this.recursiveReadEntity(key, recursive, null));
  445. }
  446.  
  447. /* ----------------------------- DELETE ----------------------------------------*/
  448.  
  449. private void launchUpdate(String request, int key) throws RuntimeException
  450. {
  451. PreparedStatement statement = null;
  452.  
  453. try {
  454. statement = this.connection.prepareStatement(request);
  455. statement.setInt(1, key);
  456. statement.executeUpdate();
  457. } catch (Exception e) {
  458. throw new RuntimeException(e.getMessage());
  459. }
  460. }
  461.  
  462. private void launchDelete(String request, int key) throws RuntimeException
  463. {
  464. PreparedStatement statement = null;
  465.  
  466. try {
  467. statement = this.connection.prepareStatement(request);
  468. statement.setInt(1, key);
  469. statement.execute();
  470. } catch (Exception e) {
  471. throw new RuntimeException(e.getMessage());
  472. }
  473. }
  474.  
  475. //Sam
  476. public int getObjectId(String cleanClassName, String key)
  477. {
  478. String request = "SELECT ID FROM " + cleanClassName.toUpperCase() + "_ENTITY WHERE NAME=?;";
  479. ResultSet resultSet = null;
  480. PreparedStatement statement = null;
  481. ResultSet resultset = null;
  482. String s = "";
  483. try {
  484.  
  485. statement = this.connection.prepareStatement(request);
  486. statement.setString(1, key);
  487. resultset = statement.executeQuery();
  488. s = (String)resultset.getObject("ID");
  489. } catch (Exception e) {
  490. throw new RuntimeException(e.getMessage());
  491. }
  492. return (Integer.parseInt(s));
  493. }
  494.  
  495. public String getRowById(String cleanClassName, Integer key, String column)
  496. {
  497. String request = "SELECT ? FROM " + cleanClassName.toUpperCase() + "_ENTITY WHERE ID=?;";
  498. ResultSet resultSet = null;
  499. PreparedStatement statement = null;
  500. ResultSet resultset = null;
  501. String s = "";
  502.  
  503. try {
  504. statement = this.connection.prepareStatement(request);
  505. statement.setString(1, column);
  506. statement.setInt(2, key);
  507. resultset = statement.executeQuery();
  508. s = (String)resultset.getObject(column);
  509. } catch (Exception e) {
  510. throw new RuntimeException(e.getMessage());
  511. }
  512. return (s);
  513. }
  514.  
  515. @SuppressWarnings("null")
  516. public List<Integer> getAllRow(String cleanClassName, String column)
  517. {
  518. String request = "SELECT ? FROM " + cleanClassName.toUpperCase() + "_ENTITY;";
  519. ResultSet resultSet = null;
  520. PreparedStatement statement = null;
  521. ResultSet resultset = null;
  522. List<Integer> s = null;
  523.  
  524. try {
  525.  
  526. statement = this.connection.prepareStatement(request);
  527. statement.setString(1, column);
  528. resultset = statement.executeQuery();
  529. do {
  530. if (resultSet.getObject(column) != null)
  531. s.add(Integer.parseInt((String)resultset.getObject(column)));
  532. }
  533. while (resultset.next());
  534.  
  535. } catch (Exception e) {
  536. throw new RuntimeException(e.getMessage());
  537. }
  538. return s;
  539. }
  540.  
  541.  
  542. private ResultSet getObjectInfo(String cleanClassName, int key)
  543. {
  544. String request = "SELECT * FROM " + cleanClassName.toUpperCase() + "_ENTITY WHERE ID=?;";
  545. ResultSet resultSet = null;
  546. resultSet = this.launchRequest(request, key);
  547.  
  548. return (resultSet);
  549. }
  550.  
  551. @SuppressWarnings("rawtypes")
  552. private void deleteKeyFromParent(String cleanClassName, int key)
  553. {
  554. System.out.print("toto - OK\n");
  555. ResultSet resultSet = getObjectInfo(cleanClassName, key);
  556. System.out.print("titi - OK\n");
  557.  
  558. try {
  559. resultSet.next();
  560. } catch (SQLException e1) {
  561.  
  562. }
  563.  
  564. System.out.print("tutu - OK\n");
  565.  
  566. String childString = null;
  567. String tmpString = null;
  568. try {
  569. childString = (String)resultSet.getObject("CHILDLIST");
  570. tmpString = (String)resultSet.getObject("FATHERLIST");
  571. } catch (SQLException e)
  572. {
  573.  
  574. }
  575.  
  576. System.out.print("bosh - OK\n");
  577.  
  578.  
  579. String[] parentList;
  580.  
  581. String[] childList = null;
  582. Class requestClass = null;
  583. String className = null;
  584. String request = null;
  585.  
  586. System.out.print("First\n");
  587. if (tmpString != null && !tmpString.isEmpty())
  588. {
  589. parentList = tmpString.split(",");
  590. for (String p : parentList)
  591. {
  592. requestClass = this.getClassByKey(Integer.parseInt(p));
  593. className = requestClass.getName().substring(requestClass.getName().lastIndexOf(".") + 1, requestClass.getName().length() - 4);
  594. resultSet = getObjectInfo(className, Integer.parseInt(p));
  595. try {
  596. resultSet.next();
  597. } catch (SQLException e) {
  598. e.printStackTrace();
  599. }
  600. try {
  601. tmpString = (String)resultSet.getObject("CHILDLIST");
  602. } catch (SQLException e) {
  603. e.printStackTrace();
  604. }
  605. childList = tmpString.split(",");
  606.  
  607.  
  608.  
  609. request = "UPDATE " + className.toUpperCase() + "_ENTITY SET CHILDLIST=\"";
  610.  
  611. boolean isFirst = true;
  612. for (String c : childList)
  613. {
  614. if (Integer.parseInt(c) != key)
  615. {
  616. if (!isFirst)
  617. request += ",";
  618. request += c;
  619. isFirst = false;
  620. }
  621. }
  622.  
  623. request += "\" WHERE ID=?;";
  624. this.launchUpdate(request, Integer.parseInt(p));
  625. }
  626. }
  627. System.out.print("Second\n");
  628.  
  629. if (childString == null || childString.isEmpty())
  630. return;
  631. childList = childString.split(",");
  632. for (String child : childList)
  633. {
  634. requestClass = this.getClassByKey(Integer.parseInt(child));
  635. className = requestClass.getName().substring(requestClass.getName().lastIndexOf(".") + 1, requestClass.getName().length() - 4);
  636. resultSet = getObjectInfo(className, Integer.parseInt(child));
  637. try {
  638. resultSet.next();
  639. } catch (SQLException e) {
  640. // TODO Auto-generated catch block
  641. e.printStackTrace();
  642. }
  643. try {
  644. tmpString = (String)resultSet.getObject("FATHERLIST");
  645. } catch (SQLException e) {
  646. // TODO Auto-generated catch block
  647. e.printStackTrace();
  648. }
  649. parentList = tmpString.split(",");
  650.  
  651.  
  652. request = "UPDATE " + className.toUpperCase() + "_ENTITY SET FATHERLIST=\"";
  653.  
  654. boolean isFirst = true;
  655. for (String parent : parentList)
  656. {
  657. if (Integer.parseInt(parent) != key)
  658. {
  659. if (!isFirst)
  660. request += ",";
  661. request += parent;
  662. isFirst = false;
  663. }
  664. }
  665.  
  666. request += "\" WHERE ID=?;";
  667. this.launchUpdate(request, Integer.parseInt(child));
  668. }
  669. }
  670.  
  671. @SuppressWarnings("rawtypes")
  672. public void deleteEntity(int key) throws RuntimeException
  673. {
  674. try
  675. {
  676. Class requestClass = this.getClassByKey(key);
  677. String request = "DELETE FROM ";
  678.  
  679. System.out.print("1 - OK\n");
  680.  
  681. String cleanClassName = requestClass.getName().substring(requestClass.getName().lastIndexOf(".") + 1, requestClass.getName().length() - 4);
  682.  
  683. System.out.print("2 - OK\n");
  684.  
  685. deleteKeyFromParent(cleanClassName, key);
  686.  
  687. System.out.print("3 - OK\n");
  688.  
  689. request += cleanClassName.toUpperCase() + "_ENTITY";
  690. request += " WHERE ID=?;";
  691. this.launchDelete(request, key);
  692. request = "DELETE FROM ENTITYLIST WHERE ENTITY_ID = ?;";
  693. this.launchDelete(request, key);
  694.  
  695. System.out.print("4 - OK\n");
  696. }
  697. catch (Exception e) {
  698. throw new RuntimeException(e.getMessage());
  699. }
  700. }
  701. }
Add Comment
Please, Sign In to add comment