Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package eu.epitech.epimarket.mapper;
- import java.beans.BeanInfo;
- import java.beans.Introspector;
- import java.beans.PropertyDescriptor;
- import java.lang.reflect.Method;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import java.util.List;
- import com.mysql.jdbc.ResultSetMetaData;
- import com.mysql.jdbc.Statement;
- public class ObjectMapper {
- private boolean registered = false;
- Connection connection;
- public ObjectMapper()
- {
- }
- private void register() throws RuntimeException {
- if (!registered) {
- try {
- Class.forName("com.mysql.jdbc.Driver").newInstance();
- } catch (Exception e) {
- throw new RuntimeException(e.getMessage());
- }
- registered = true;
- }
- }
- protected void getConnection() throws RuntimeException
- {
- try {
- register();
- this.connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/epimarket", "root", "");
- } catch (Exception e) {
- throw new RuntimeException(e.getMessage());
- }
- }
- /* ----------------------------- FIND -------------------------------------------*/
- public String findEntity(String key, String table)
- {
- String sql = "";
- PreparedStatement statement = null;
- String tmpString = "";
- try {
- this.getConnection();
- sql = "SELECT ID FROM " + table + " WHERE NAME = " + key;
- statement = this.connection.prepareStatement(sql);
- ResultSet p = statement.executeQuery();
- try {
- p.next();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- try {
- tmpString = (String)p.getObject("ID");
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- catch (Exception e) {
- throw new RuntimeException(e.getMessage());
- }
- return (tmpString);
- }
- /* ----------------------------- UPDATE --------------------------------------- */
- public void updateEntity(Object object)
- {
- String sql = "UPDATE ";
- BeanInfo beanInfo = null;
- boolean first = true;
- String id = "";
- PreparedStatement statement = null;
- try
- {
- this.getConnection();
- sql += object.getClass().getSimpleName().substring(0, object.getClass().getSimpleName().length() - "Bean".length());
- sql += "_ENTITY";
- sql += " SET ";
- beanInfo = Introspector.getBeanInfo(object.getClass());
- for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
- String column = property.getName();
- if (column.compareTo("class") != 0 && column.toUpperCase().contains("ID") == false)
- {
- if (!first)
- sql += ", ";
- sql += column.toUpperCase();
- sql += " = ";
- if (property.getReadMethod().toString().contains("getChildList()") ||
- property.getReadMethod().toString().contains("getFatherList()"))
- {
- column = "";
- @SuppressWarnings("unchecked")
- List<Object> oList = (List<java.lang.Object>) property.getReadMethod().invoke(object);
- for (Object p : oList)
- {
- Method t = p.getClass().getMethod("getId");
- if (column != "")
- column += ",";
- else
- column = "'";
- column += t.invoke(p);
- }
- if (oList.size() == 0)
- sql += "NULL";
- else {
- sql += column + "'";
- }
- }
- else
- sql += "'" + property.getReadMethod().invoke(object).toString() + "'";
- first = false;
- }
- else if (column.toUpperCase().contains("ID"))
- id = property.getReadMethod().invoke(object).toString();
- }
- sql += " WHERE ID = '" + id + "'";
- statement = this.connection.prepareStatement(sql);
- statement.executeUpdate();
- }
- catch (Exception e)
- {
- throw new RuntimeException(e.getMessage());
- }
- }
- /* ----------------------------- CREATE ----------------------------------------*/
- public void writeEntity(Object object)
- {
- String sql = "INSERT INTO ENTITYLIST (ENTITY_ID, ENTITY_TYPE) VALUES(NULL, ?)";
- PreparedStatement statement = null;
- ResultSet rs = null;
- String key = "";
- BeanInfo beanInfo = null;
- try
- {
- this.getConnection();
- /*---------INSERTION DANS LA ENTITYLIST----------*/
- statement = this.connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
- statement.setString(1, object.getClass().getSimpleName().substring(0, object.getClass().getSimpleName().length() - "Bean".length()));
- statement.executeUpdate();
- rs = statement.getGeneratedKeys();
- if (rs.next()) {
- ResultSetMetaData rsmd = (ResultSetMetaData) rs.getMetaData();
- int colCount = rsmd.getColumnCount();
- do {
- for (int i = 1; i <= colCount; i++) {
- key = rs.getString(i);
- }
- }
- while (rs.next());
- }
- else {
- throw new RuntimeException("Unable to retrieve Generated KEY.");
- }
- /*--------INSERTION DANS LA TABLE ASSOCIATIVE-------*/
- sql = "INSERT INTO ";
- sql += object.getClass().getSimpleName().substring(0, object.getClass().getSimpleName().length() - "Bean".length()).toUpperCase() + "_ENTITY ";
- sql += "(ID";
- beanInfo = Introspector.getBeanInfo(object.getClass());
- for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
- String column = property.getName();
- if (column.compareTo("class") != 0 && column.toUpperCase().contains("ID") == false)
- sql += "," + column.toUpperCase();
- }
- sql += ") VALUES('" + key + "'";
- for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
- String column = "";
- if (property.getReadMethod().toString().contains("getChildList()") ||
- property.getReadMethod().toString().contains("getFatherList()"))
- {
- @SuppressWarnings("unchecked")
- List<Object> oList = (List<java.lang.Object>) property.getReadMethod().invoke(object);
- for (Object p : oList)
- {
- Method t = p.getClass().getMethod("getId");
- if (column != "")
- column += ",";
- else
- column = "'";
- column += t.invoke(p);
- }
- if (oList.size() == 0)
- sql += ",NULL";
- else {
- sql += "," + column + "'";
- }
- }
- else if (property.getReadMethod().toString().contains("public final native java.lang.Class") == false &&
- property.getReadMethod().toString().contains(".getId()") == false)
- {
- column = property.getReadMethod().invoke(object).toString();
- sql += ",'" + column + "'";
- }
- }
- sql += ")";
- statement = this.connection.prepareStatement(sql);
- statement.executeUpdate();
- Method t = object.getClass().getMethod("setId", int.class);
- t.invoke(object, Integer.parseInt(key));
- }
- catch (Exception e) {
- throw new RuntimeException(e.getMessage());
- }
- }
- /* ----------------------------- READ ----------------------------------------*/
- private String getTypeOfEntity(int key) throws RuntimeException
- {
- this.getConnection();
- String result = null;
- String request = "SELECT ENTITY_TYPE FROM ENTITYLIST WHERE ENTITY_ID = ?";
- PreparedStatement statement = null;
- ResultSet resultset = null;
- try {
- statement = this.connection.prepareStatement(request);
- statement.setInt(1, key);
- resultset = statement.executeQuery();
- while (resultset.next())
- result = (String)resultset.getObject(1);
- } catch (Exception e) {
- throw new RuntimeException(e.getMessage());
- }
- if (result == null)
- throw new RuntimeException("Null String");
- return (result);
- }
- @SuppressWarnings({ "rawtypes" })
- private Class getClassByKey(int key) throws RuntimeException
- {
- String className;
- Class requestClass = null;
- try {
- className = getTypeOfEntity(key);
- requestClass = Class.forName("eu.epitech.epimarket.entity." + className + "Bean");
- } catch (Exception e) {
- throw new RuntimeException(e.getMessage());
- }
- if (requestClass == null)
- throw new RuntimeException("Null Class");
- return (requestClass);
- }
- private ResultSet launchRequest(String request, int key) throws RuntimeException
- {
- PreparedStatement statement = null;
- ResultSet resultset = null;
- try {
- statement = this.connection.prepareStatement(request);
- statement.setInt(1, key);
- resultset = statement.executeQuery();
- } catch (Exception e) {
- throw new RuntimeException(e.getMessage());
- }
- return (resultset);
- }
- @SuppressWarnings("rawtypes")
- private String prepareRequest(Class requestClass) throws RuntimeException
- {
- String request = "SELECT ";
- boolean first = true;
- BeanInfo beanInfo;
- try {
- beanInfo = Introspector.getBeanInfo(requestClass);
- for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
- String column = property.getName();
- if (column.compareTo("class") != 0)
- {
- if (!first) {
- request += ",";
- }
- request += column.toUpperCase();
- first = false;
- }
- }
- String cleanClassName = requestClass.getName().substring(requestClass.getName().lastIndexOf(".") + 1, requestClass.getName().length() - 4);
- request += " FROM ";
- request += cleanClassName.toUpperCase() + "_ENTITY";
- request += " WHERE ID=?;";
- } catch (Exception e) {
- throw new RuntimeException(e.getMessage());
- }
- return (request);
- }
- @SuppressWarnings({ "unused", "rawtypes" })
- private Object buildObject(ResultSet resultSet, Class requestClass) throws RuntimeException
- {
- BeanInfo beanInfo = null;
- Object object = null;
- try {
- object = requestClass.newInstance();
- beanInfo = Introspector.getBeanInfo(requestClass);
- Method classMethod[] = object.getClass().getMethods();
- resultSet.next();
- int i = 0;
- while (i < classMethod.length)
- {
- if (classMethod[i].toString().contains(".set"))
- {
- String cleanMethodName = classMethod[i].toString().substring(classMethod[i].toString().lastIndexOf("set") + 3, classMethod[i].toString().indexOf("("));
- Object result = null;
- result = resultSet.getObject(cleanMethodName.toUpperCase());
- classMethod[i].invoke(object, result);
- }
- ++i;
- }
- } catch (Exception e) {
- throw new RuntimeException(e.getMessage());
- }
- if (object == null)
- throw new RuntimeException("Null Object");
- return (object);
- }
- private String[] getChildList(ResultSet resultSet)
- {
- String[] childList = null;
- String childString = null;
- try {
- childString = (String)resultSet.getObject("CHILDLIST");
- if (childString == null || childString.isEmpty())
- return (null);
- childList = childString.split(",");
- } catch (SQLException e) {
- return (null);
- }
- return (childList);
- }
- @SuppressWarnings("unused")
- private String[] getParentList(ResultSet resultSet)
- {
- String[] childList = null;
- String childString = null;
- try {
- childString = (String)resultSet.getObject("FATHERLIST");
- if (childString == null || childString.isEmpty())
- return (null);
- childList = childString.split(",");
- } catch (SQLException e) {
- return (null);
- }
- return (childList);
- }
- private Object doRecursivity(Object object, ResultSet resultSet, String[] childList, List<Integer> antiloop) throws RuntimeException
- {
- for (String sId : childList)
- {
- Integer id = Integer.parseInt(sId);
- if (antiloop.contains(id) == false)
- {
- try
- {
- Object tmp = this.recursiveReadEntity(id, true, antiloop);
- Method m = object.getClass().getMethod("addChild", Object.class);
- m.invoke(object, tmp);
- } catch (Exception e) {
- throw new RuntimeException(e.getMessage());
- }
- }
- }
- return (object);
- }
- @SuppressWarnings("rawtypes")
- private Object recursiveReadEntity(int key, boolean recursive, List<Integer> antiloop) throws RuntimeException
- {
- String request = null;
- Class requestClass = null;
- ResultSet resultSet = null;
- Object object = null;
- String[] childList = null;
- if (antiloop == null)
- antiloop = new ArrayList<Integer>();
- antiloop.add(new Integer(key));
- this.getConnection();
- requestClass = this.getClassByKey(key);
- request = this.prepareRequest(requestClass);
- resultSet = this.launchRequest(request, key);
- if (resultSet == null)
- throw new RuntimeException("Null ResultSet");
- object = this.buildObject(resultSet, requestClass);
- if (recursive && (childList = this.getChildList(resultSet)) != null)
- object = doRecursivity(object, resultSet, childList, antiloop);
- return (object);
- }
- public Object readEntity(int key, boolean recursive) throws RuntimeException
- {
- return (this.recursiveReadEntity(key, recursive, null));
- }
- /* ----------------------------- DELETE ----------------------------------------*/
- private void launchUpdate(String request, int key) throws RuntimeException
- {
- PreparedStatement statement = null;
- try {
- statement = this.connection.prepareStatement(request);
- statement.setInt(1, key);
- statement.executeUpdate();
- } catch (Exception e) {
- throw new RuntimeException(e.getMessage());
- }
- }
- private void launchDelete(String request, int key) throws RuntimeException
- {
- PreparedStatement statement = null;
- try {
- statement = this.connection.prepareStatement(request);
- statement.setInt(1, key);
- statement.execute();
- } catch (Exception e) {
- throw new RuntimeException(e.getMessage());
- }
- }
- //Sam
- public int getObjectId(String cleanClassName, String key)
- {
- String request = "SELECT ID FROM " + cleanClassName.toUpperCase() + "_ENTITY WHERE NAME=?;";
- ResultSet resultSet = null;
- PreparedStatement statement = null;
- ResultSet resultset = null;
- String s = "";
- try {
- statement = this.connection.prepareStatement(request);
- statement.setString(1, key);
- resultset = statement.executeQuery();
- s = (String)resultset.getObject("ID");
- } catch (Exception e) {
- throw new RuntimeException(e.getMessage());
- }
- return (Integer.parseInt(s));
- }
- public String getRowById(String cleanClassName, Integer key, String column)
- {
- String request = "SELECT ? FROM " + cleanClassName.toUpperCase() + "_ENTITY WHERE ID=?;";
- ResultSet resultSet = null;
- PreparedStatement statement = null;
- ResultSet resultset = null;
- String s = "";
- try {
- statement = this.connection.prepareStatement(request);
- statement.setString(1, column);
- statement.setInt(2, key);
- resultset = statement.executeQuery();
- s = (String)resultset.getObject(column);
- } catch (Exception e) {
- throw new RuntimeException(e.getMessage());
- }
- return (s);
- }
- @SuppressWarnings("null")
- public List<Integer> getAllRow(String cleanClassName, String column)
- {
- String request = "SELECT ? FROM " + cleanClassName.toUpperCase() + "_ENTITY;";
- ResultSet resultSet = null;
- PreparedStatement statement = null;
- ResultSet resultset = null;
- List<Integer> s = null;
- try {
- statement = this.connection.prepareStatement(request);
- statement.setString(1, column);
- resultset = statement.executeQuery();
- do {
- if (resultSet.getObject(column) != null)
- s.add(Integer.parseInt((String)resultset.getObject(column)));
- }
- while (resultset.next());
- } catch (Exception e) {
- throw new RuntimeException(e.getMessage());
- }
- return s;
- }
- private ResultSet getObjectInfo(String cleanClassName, int key)
- {
- String request = "SELECT * FROM " + cleanClassName.toUpperCase() + "_ENTITY WHERE ID=?;";
- ResultSet resultSet = null;
- resultSet = this.launchRequest(request, key);
- return (resultSet);
- }
- @SuppressWarnings("rawtypes")
- private void deleteKeyFromParent(String cleanClassName, int key)
- {
- System.out.print("toto - OK\n");
- ResultSet resultSet = getObjectInfo(cleanClassName, key);
- System.out.print("titi - OK\n");
- try {
- resultSet.next();
- } catch (SQLException e1) {
- }
- System.out.print("tutu - OK\n");
- String childString = null;
- String tmpString = null;
- try {
- childString = (String)resultSet.getObject("CHILDLIST");
- tmpString = (String)resultSet.getObject("FATHERLIST");
- } catch (SQLException e)
- {
- }
- System.out.print("bosh - OK\n");
- String[] parentList;
- String[] childList = null;
- Class requestClass = null;
- String className = null;
- String request = null;
- System.out.print("First\n");
- if (tmpString != null && !tmpString.isEmpty())
- {
- parentList = tmpString.split(",");
- for (String p : parentList)
- {
- requestClass = this.getClassByKey(Integer.parseInt(p));
- className = requestClass.getName().substring(requestClass.getName().lastIndexOf(".") + 1, requestClass.getName().length() - 4);
- resultSet = getObjectInfo(className, Integer.parseInt(p));
- try {
- resultSet.next();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- try {
- tmpString = (String)resultSet.getObject("CHILDLIST");
- } catch (SQLException e) {
- e.printStackTrace();
- }
- childList = tmpString.split(",");
- request = "UPDATE " + className.toUpperCase() + "_ENTITY SET CHILDLIST=\"";
- boolean isFirst = true;
- for (String c : childList)
- {
- if (Integer.parseInt(c) != key)
- {
- if (!isFirst)
- request += ",";
- request += c;
- isFirst = false;
- }
- }
- request += "\" WHERE ID=?;";
- this.launchUpdate(request, Integer.parseInt(p));
- }
- }
- System.out.print("Second\n");
- if (childString == null || childString.isEmpty())
- return;
- childList = childString.split(",");
- for (String child : childList)
- {
- requestClass = this.getClassByKey(Integer.parseInt(child));
- className = requestClass.getName().substring(requestClass.getName().lastIndexOf(".") + 1, requestClass.getName().length() - 4);
- resultSet = getObjectInfo(className, Integer.parseInt(child));
- try {
- resultSet.next();
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- try {
- tmpString = (String)resultSet.getObject("FATHERLIST");
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- parentList = tmpString.split(",");
- request = "UPDATE " + className.toUpperCase() + "_ENTITY SET FATHERLIST=\"";
- boolean isFirst = true;
- for (String parent : parentList)
- {
- if (Integer.parseInt(parent) != key)
- {
- if (!isFirst)
- request += ",";
- request += parent;
- isFirst = false;
- }
- }
- request += "\" WHERE ID=?;";
- this.launchUpdate(request, Integer.parseInt(child));
- }
- }
- @SuppressWarnings("rawtypes")
- public void deleteEntity(int key) throws RuntimeException
- {
- try
- {
- Class requestClass = this.getClassByKey(key);
- String request = "DELETE FROM ";
- System.out.print("1 - OK\n");
- String cleanClassName = requestClass.getName().substring(requestClass.getName().lastIndexOf(".") + 1, requestClass.getName().length() - 4);
- System.out.print("2 - OK\n");
- deleteKeyFromParent(cleanClassName, key);
- System.out.print("3 - OK\n");
- request += cleanClassName.toUpperCase() + "_ENTITY";
- request += " WHERE ID=?;";
- this.launchDelete(request, key);
- request = "DELETE FROM ENTITYLIST WHERE ENTITY_ID = ?;";
- this.launchDelete(request, key);
- System.out.print("4 - OK\n");
- }
- catch (Exception e) {
- throw new RuntimeException(e.getMessage());
- }
- }
- }
Add Comment
Please, Sign In to add comment