Back to project page MproEntity.
The source code is released under:
GNU General Public License
If you think the Android project MproEntity listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
package br.com.mpro3.utils; // www . j a v a2s. c o m import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Matheus Castello * Funciona mas o cdigo est bem sujo!! Merece receber um clean!!! Quem se abilita? */ @SuppressWarnings("unchecked") public abstract class MproEntity { private static LauDB _conn = new LauDB("MproEntity.lau"); private Class<?> _class; public int cod; public int superCod = 0; private boolean joined = false; //private String nameRelation = ""; private ArrayList<String> namesRelation = new ArrayList<String>(); private MproEntity refObject = null; /** * Retorna a tabela inteira sem exeo */ public static <T> ArrayList<T> getAll(Class<T> classe) { return MproEntity.getAll(classe, null, null, null, null); } /** * Retorna dados limitados */ public static <T> ArrayList<T> getAll(Class<T> classe, int[] limiter) { return MproEntity.getAll(classe, limiter, null, null, null); } /** * Retorna dados onde ordenados */ public static <T> ArrayList<T> getAll(Class<T> classe, String where, String ordBy) { return MproEntity.getAll(classe, null, null, where, ordBy); } /** * Retorna dados limitados e ordenados */ public static <T> ArrayList<T> getAll(Class<T> classe, int[] limiter, String ordBy) { return MproEntity.getAll(classe, limiter, null, null, ordBy); } /** * Retorna dados ordenados */ public static <T> ArrayList<T> getAll(Class<T> classe, String ordBy) { return MproEntity.getAll(classe, null, null, null, ordBy); } /** * Retorna os dados com limite onde ordenados */ public static <T> ArrayList<T> getAll(Class<T> classe, int[] limiter, MproEntity superFilter, String where, String ordBy) { ArrayList<T> list = new ArrayList<T>(); ArrayList<Field> contains = new ArrayList<Field>(); try { T c = classe.newInstance(); String[][] res; T tmp; //Class<?> arrT = null; //Field join = null; ArrayList<Class<?>> arrT = new ArrayList<Class<?>>(); ArrayList<Field> join = new ArrayList<Field>(); for(int j = 0; j < c.getClass().getFields().length; j++) { if(c.getClass().getFields()[j].getType().equals(ArrayList.class) || c.getClass().getFields()[j].getType().equals(List.class)) { //join = c.getClass().getFields()[j]; join.add(c.getClass().getFields()[j]); //arrT = (Class<?>)((ParameterizedType) c.getClass().getFields()[j].getGenericType()).getActualTypeArguments()[0]; arrT.add((Class<?>)((ParameterizedType) c.getClass().getFields()[j].getGenericType()).getActualTypeArguments()[0]); } else contains.add(c.getClass().getFields()[j]); } String parts = ""; //for(int j = 0; j < c.getClass().getFields().length; j++) for(int j = 0; j < contains.size(); j++) { //parts += c.getClass().getFields()[j].getName() + ", "; parts += contains.get(j).getName() + ", "; } parts = parts.replaceAll(", $", ""); if(superFilter == null) res = _conn.query("SELECT " + parts + " FROM " + c.getClass().getName().replace('.', '_') + " " + ((where == null) || (where == "") ? "" : " WHERE(" + where + ")") + " " + ((ordBy == null) || (ordBy == "") ? "" : " ORDER BY " + ordBy + "") + " " + ((limiter == null) ? "" : "LIMIT " + limiter[0] + ", " + limiter[1]) + ";"); else res = _conn.query("SELECT " + parts + " FROM " + c.getClass().getName().replace('.', '_') + " WHERE cod IN (SELECT codref FROM Reference WHERE class = '" + superFilter.getClass().getName().replace('.', '_') + "' AND cod = " + superFilter.cod + " AND classref = '" + c.getClass().getName().replace('.', '_') + "') " + " " + ((where == null) || (where == "") ? "" : " AND (" + where + ")") + " " + ((ordBy == null) || (ordBy == "") ? "" : " ORDER BY " + ordBy + "") + " " + ((limiter == null) ? "" : "LIMIT " + limiter[0] + ", " + limiter[1]) + ";"); if(res != null) { for(int i = 0; i < res.length; i++) { tmp = classe.newInstance(); for(int j = 0; j < contains.size(); j++) { Field f = contains.get(j); if(res[i][j] != null) { if(f.getType().equals(int.class)) f.set(tmp, Integer.parseInt(res[i][j])); else if(f.getType().equals(boolean.class)) f.set(tmp, (res[i][j].equals("1") ? true : false)); else if(f.getType().equals(double.class)) f.set(tmp, Double.parseDouble(res[i][j])); else if(f.getType().equals(long.class)) f.set(tmp, Long.parseLong(res[i][j])); else { Class<?> theClass = f.getType(); f.set(tmp, theClass.cast(res[i][j])); } } } //if(join != null) if(join.size() > 0) { //MproEntity t = (MproEntity) arrT.newInstance(); //t.superCod = ((MproEntity)tmp).cod; //ArrayList<?> mpR = MproEntity.getWhere(arrT.cast(t)); for(int k = 0; k < join.size(); k++) { ArrayList<?> mpR = MproEntity.getAll(arrT.get(k), null, (MproEntity)tmp, null, null); join.get(k).set(tmp, mpR); } } list.add(tmp); if(superFilter != null) { ((MproEntity)tmp).setRefObject(superFilter); } } } } catch (InstantiationException ex) { Logger.getLogger(MproEntity.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(MproEntity.class.getName()).log(Level.SEVERE, null, ex); } catch (SecurityException ex) { Logger.getLogger(MproEntity.class.getName()).log(Level.SEVERE, null, ex); } return list; } public static <T> ArrayList<T> getWhere(T filterObj, int[] limiter, String ordBy) { return getWhere(filterObj, limiter, null, ordBy, false); } public static <T> ArrayList<T> getWhere(T filterObj, int[] limiter) { return getWhere(filterObj, null, null, null, false); } public static <T> ArrayList<T> getWhere(T filterObj, String ordBy) { return getWhere(filterObj, null, null, ordBy, false); } public static <T> ArrayList<T> getWhere(T filterObj) { return getWhere(filterObj, null, null, null, false); } /** * Pega os campos no nulos filtrados */ public static <T> ArrayList<T> getWhere(T filterObj, int[] limiter, MproEntity superFilter, String ordBy, boolean enaB) { ArrayList<T> list = new ArrayList<T>(); ArrayList<String> fildsnames = new ArrayList<String>(); Class<?> c = filterObj.getClass(); String where = ""; String filds = ""; //String sql = "SELECT "; //Field cf = null; ArrayList<Field> cf = new ArrayList<Field>(); try { // constroi o where for(int j = 0; j < c.getFields().length; j++) { /*if(!"cod".equals(c.getFields()[j].getName())) {*/ if (c.getFields()[j].getType().equals(ArrayList.class) || c.getFields()[j].getType().equals(List.class)) { //cf = c.getFields()[j]; cf.add(c.getFields()[j]); continue; } else fildsnames.add(c.getFields()[j].getName()); if((c.getFields()[j].getType() == int.class) && !(c.getFields()[j].get(filterObj).equals(Integer.MAX_VALUE))) { where += c.getFields()[j].getName() + " = " + c.getFields()[j].get(filterObj).toString() + ", "; filds += c.getFields()[j].getName() + ", "; } else if((c.getFields()[j].getType() == long.class) && !(c.getFields()[j].get(filterObj).equals(Long.MAX_VALUE))) { where += c.getFields()[j].getName() + " = " + c.getFields()[j].get(filterObj).toString() + ", "; filds += c.getFields()[j].getName() + ", "; } else if((c.getFields()[j].getType() == double.class) && !(c.getFields()[j].get(filterObj).equals(Double.MAX_VALUE ))) { where += c.getFields()[j].getName() + " = " + c.getFields()[j].get(filterObj).toString() + ", "; filds += c.getFields()[j].getName() + ", "; } else if((c.getFields()[j].getType() == boolean.class) && enaB) { where += c.getFields()[j].getName() + " = " + (c.getFields()[j].get(filterObj).toString().equals("true") ? "1" : "0") + ", "; filds += c.getFields()[j].getName() + ", "; } else if((c.getFields()[j].getType() != long.class) && (c.getFields()[j].getType() != double.class) && (c.getFields()[j].getType() != int.class) && (c.getFields()[j].getType() != boolean.class) && (c.getFields()[j].get(filterObj) != null)) { where += c.getFields()[j].getName() + " = '" + c.getFields()[j].get(filterObj).toString() + "', "; filds += c.getFields()[j].getName() + ", "; } //} } where = where.replaceAll(", ", " AND "); where = where.replaceFirst("AND $", " "); filds = filds.replaceFirst(", $", " "); //sql += filds + " FROM " + c.getName().replace('.', '_') + " WHERE " + where + ";"; /*sql += "* FROM " + c.getName().replace('.', '_') + " WHERE " + where + ";"; String[][] res = _conn.query(sql); for(int i = 0; i < res.length; i++) { T tmp = (T) c.newInstance(); //for(int j = 0; j < c.getFields().length; j++) for(int j = 0; j < fildsnames.size(); j++) { if(res[i][j] != null) { if(tmp.getClass().getField(fildsnames.get(j)).getType().equals(int.class)) tmp.getClass().getField(fildsnames.get(j)).set(tmp, Integer.parseInt(res[i][j])); else if(tmp.getClass().getField(fildsnames.get(j)).getType().equals(double.class)) tmp.getClass().getField(fildsnames.get(j)).set(tmp, Double.parseDouble(res[i][j])); else if(tmp.getClass().getField(fildsnames.get(j)).getType().equals(long.class)) tmp.getClass().getField(fildsnames.get(j)).set(tmp, Long.parseLong(res[i][j])); else if(tmp.getClass().getField(fildsnames.get(j)).getType().equals(boolean.class)) tmp.getClass().getField(fildsnames.get(j)).set(tmp, (res[i][j].equals("1") ? true : false)); else { Class<?> theClass = tmp.getClass().getField(fildsnames.get(j)).getType(); tmp.getClass().getField(fildsnames.get(j)).set(tmp, theClass.cast(res[i][j])); } } } //if(cf != null) if(cf.size() > 0) { for(int k = 0; k < cf.size(); k++) { Class<?> typin = (Class<?>)((ParameterizedType) cf.get(k).getGenericType()).getActualTypeArguments()[0]; MproEntityRelation t = (MproEntityRelation) typin.newInstance(); t.superCod = ((MproEntity)tmp).cod; ArrayList<?> mpR = MproEntity.getWhere(typin.cast(t)); cf.get(k).set(tmp, mpR); } } list.add(tmp); }*/ return (ArrayList<T>) MproEntity.getAll(c, limiter, superFilter, where, ordBy); } catch (IllegalArgumentException ex) { Logger.getLogger(MproEntity.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(MproEntity.class.getName()).log(Level.SEVERE, null, ex); } catch (SecurityException ex) { Logger.getLogger(MproEntity.class.getName()).log(Level.SEVERE, null, ex); } return list; } public MproEntity() { this.cod = 0; this._class = this.getClass(); this.toNull(); this.initialConfig(); } public void setRefObject(MproEntity obj) { this.refObject = obj; } public MproEntity getRefObject() { return this.refObject; } public void Save(String classref, int codref) { _conn.execute("INSERT INTO Reference VALUES('" + classref + "', '" + this._class.getName().replace('.', '_') + "', " + codref + ", " + this.cod + ");"); } /** * Insere os dados atuais no banco; */ public void Save() { if(this.cod == Integer.MAX_VALUE) { _conn.execute("INSERT INTO " + this._class.getName().replace('.', '_') + " VALUES( " + this.getValues() + ");"); _conn.query("SELECT * FROM " + this.getClass().getName().replace('.', '_') + ";"); this.cod = _conn.get_last_insert_rowid(); if(this.joined) // salva nossos amigos { try { for(int j = 0; j < this.namesRelation.size(); j++) { ArrayList<MproEntity> arr = (ArrayList<MproEntity>) this._class.getField(this.namesRelation.get(j)).get(this); if(arr != null) { for(int i = 0; i < arr.size(); i++) { arr.get(i).superCod = this.cod; arr.get(i).Save(); arr.get(i).Save(this._class.getName().replace('.', '_'), this.cod); arr.get(i).setRefObject(this); } } } } catch (NoSuchFieldException ex) { Logger.getLogger(MproEntity.class.getName()).log(Level.SEVERE, null, ex); } catch (SecurityException ex) { Logger.getLogger(MproEntity.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalArgumentException ex) { Logger.getLogger(MproEntity.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(MproEntity.class.getName()).log(Level.SEVERE, null, ex); } } } else { _conn.execute("UPDATE " + this._class.getName().replace('.', '_') + " SET " + this.getValuesUpdate() + " WHERE cod = " + this.cod); if(this.joined) // salva nossos amigos { try { for(int j = 0; j < this.namesRelation.size(); j++) { ArrayList<MproEntity> arr = (ArrayList<MproEntity>) this._class.getField(this.namesRelation.get(j)).get(this); if(arr != null) { for(int i = 0; i < arr.size(); i++) { arr.get(i).superCod = this.cod; arr.get(i).Save(); arr.get(i).Save(this._class.getName().replace('.', '_'), this.cod); } } } this.joined = true; } catch (NoSuchFieldException ex) { Logger.getLogger(MproEntity.class.getName()).log(Level.SEVERE, null, ex); } catch (SecurityException ex) { Logger.getLogger(MproEntity.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalArgumentException ex) { Logger.getLogger(MproEntity.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(MproEntity.class.getName()).log(Level.SEVERE, null, ex); } } } } public void Delete(String classref, int codref) { _conn.execute("DELETE FROM Reference WHERE cod = " + codref + " AND codref = " + this.cod + " AND class = '" + classref + "' AND classref = '" + this._class.getName().replace('.', '_') + "';"); } /** * Apaga o registro */ public void Delete() { if(this.cod != 0) { if(this.namesRelation.size() < 0) this.getValues(); if(joined) { for(int j = 0; j < this.namesRelation.size(); j++) { ArrayList<MproEntity> arr; try { arr = (ArrayList<MproEntity>) this._class.getField(this.namesRelation.get(j)).get(this); if(arr != null) { for(int i = 0; i < arr.size(); i++) { arr.get(i).Delete(arr.get(i).getRefObject().getClass().getName().replace('.', '_'), this.cod); } } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } } } if(this.refObject == null) { _conn.execute("DELETE FROM " + this._class.getName().replace('.', '_') + " WHERE cod = " + this.cod); this.cod = 0; //this.Delete(this._class.getName().replace('.', '_'), this.cod); } else { _conn.execute("DELETE FROM Reference WHERE cod = " + this.refObject.cod + " AND codref = " + this.cod + " AND class = '" + this.refObject.getClass().getName().replace('.', '_') + "'" + " AND classref = '" + this._class.getName().replace('.', '_') + "';"); //this.refObject._class.getField(); } } } private void toNull() { try { for(int i = 0; i < this._class.getFields().length; i++) { if(this._class.getFields()[i].getType().equals(int.class)) this._class.getFields()[i].set(this, Integer.MAX_VALUE); else if(this._class.getFields()[i].getType().equals(double.class)) this._class.getFields()[i].set(this, Double.MAX_VALUE); else if(this._class.getFields()[i].getType().equals(long.class)) this._class.getFields()[i].set(this, Long.MAX_VALUE); else if(!this._class.getFields()[i].getType().equals(boolean.class)) this._class.getFields()[i].set(this, null); } } catch (IllegalArgumentException ex) { Logger.getLogger(MproEntity.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(MproEntity.class.getName()).log(Level.SEVERE, null, ex); } } /** * Na construcao vamos ver se a tabela ja existe */ private void initialConfig() { //CREATE TABLE IF NOT EXISTS __teste__ (cod INTEGER PRIMARY KEY, nome TEXT, jujubas TEXT); //pragma table_info(__teste__); //pragma table_info(__testa); boolean isEqual = false; String[][] tableInfo = _conn.query("PRAGMA table_info(" + this._class.getName().replace('.', '_') + ")"); ArrayList<String> fieldNot = new ArrayList<String>(); ArrayList<containField> changesTable = new ArrayList<containField>(); if((tableInfo == null) || (tableInfo.length == 0)) { // cria do zero _conn.execute("CREATE TABLE " + this._class.getName().replace('.', '_') + "(" + this.getTableFields() + ");"); _conn.execute("CREATE TABLE IF NOT EXISTS Reference (class TEXT, classref TEXT, cod INTEGER, codref INTEGER, PRIMARY KEY(class, classref, cod, codref));"); return; } else { // verifica os campos for(int j = 0; j < this._class.getFields().length; j++) { for(int i = 0; i < tableInfo.length; i++) { if(this._class.getFields()[j].getType() != ArrayList.class) { isEqual = tableInfo[i][1].equals(this._class.getFields()[j].getName()) ? true : false; if(isEqual) break; } else { this.joined = true; //this.nameRelation = this._class.getFields()[j].getName(); } } // se tem campo q nao tem temos q alterar if(!isEqual) { fieldNot.add(this._class.getFields()[j].getName()); } } // se tem algum no fieldNot if(fieldNot.size() > 0) { fieldNot = this.getTableFieldsFromArrayList(fieldNot); for(String s : fieldNot) { _conn.execute(s); } } // vamos testar se temos que trocar algo isEqual = false; for(int w = 0; w < tableInfo.length; w++) { containField cf = new containField(tableInfo[w][1], tableInfo[w][2], false); for(int q = 0; q < this._class.getFields().length; q++) { cf.isDB = this._class.getFields()[q].getName().equals(cf.name) ? true : false; if(cf.isDB) break; } if(cf.isDB) changesTable.add(cf); else isEqual = true; } // agora podemos fazer as querys if((changesTable.size() > 0) && isEqual) this.changeTable(changesTable); } } /** * Pega uma string j parametrizada */ private String getTableFields() { String parts = ""; this.namesRelation.clear(); for(int i = 0; i < this._class.getFields().length; i++) { if((this._class.getFields()[i].getType() != ArrayList.class) && (this._class.getFields()[i].getType() != List.class)) { if(!"cod".equals(this._class.getFields()[i].getName())) parts += this._class.getFields()[i].getName() + " " + (this._class.getFields()[i].getType() == String.class ? "TEXT, " : "NUMERIC, "); else parts += this._class.getFields()[i].getName() + " INTEGER PRIMARY KEY, "; } else { this.joined = true; //this.nameRelation = this._class.getFields()[i].getName(); this.namesRelation.add(this._class.getFields()[i].getName()); } } parts = parts.replaceFirst(", $", ""); return parts; } /** * */ private void changeTable(ArrayList<containField> arrcf) { if(arrcf.size() > 0) { String parts = "CREATE TABLE tmp(" + this.getTableFields() + ");"; String parts1 = "INSERT INTO tmp( "; String parts2 = ""; for(int i = 0; i < arrcf.size(); i++) { if(i < arrcf.size() -1) parts2 += arrcf.get(i).name + ", "; else parts2 += arrcf.get(i).name + " "; } parts1 += parts2 + " SELECT "+ parts2 +" FROM " + this._class.getName().replace('.', '_') + ";"; // comea _conn.execute(parts); _conn.execute(parts1 ); _conn.execute("DROP TABLE " + this._class.getName().replace('.', '_') + ";"); _conn.execute("ALTER TABLE tmp RENAME TO " + this._class.getName().replace('.', '_') + ";"); } } /** * Pega os parametrizados para alterao */ private ArrayList<String> getTableFieldsFromArrayList(ArrayList<String> arrl) { String parts; ArrayList<String> parts_ = new ArrayList<String>(); parts_.add("CREATE TABLE tmp(" + this.getTableFields() + ");"); parts = ""; for(int i = 0; i < arrl.size(); i++) { for(int j = 0; j < this._class.getFields().length; j++) { if(!arrl.get(i).equals(this._class.getFields()[j].getName())) { parts += this._class.getFields()[j].getName() + ", "; } } } parts = parts.replaceFirst(", $", " "); parts_.add("INSERT INTO tmp(" + parts + ") SELECT " + parts + "FROM " + this._class.getName().replace('.', '_') + ";"); parts_.add("DROP TABLE " + this._class.getName().replace('.', '_') + ";"); parts_.add("ALTER TABLE tmp RENAME TO " + this._class.getName().replace('.', '_') + ";"); return parts_; } /** * Pega valores para insert */ private String getValues() { String parts = ""; this.namesRelation.clear(); for(int i = 0; i < this._class.getFields().length; i++) { try { if((this._class.getFields()[i].getType() != ArrayList.class) && (this._class.getFields()[i].getType() != List.class)) { if(this._class.getFields()[i].getType() == boolean.class) parts += (Boolean) this._class.getFields()[i].get(this) ? "1, " : "0, "; else if(!"cod".equals(this._class.getFields()[i].getName())) parts += (this._class.getFields()[i].getType() == String.class ? "'" : "") + this._class.getFields()[i].get(this).toString() + (this._class.getFields()[i].getType() == String.class ? "', " : ", "); else parts += "NULL, "; } else { this.joined = true; //this.nameRelation = this._class.getFields()[i].getName(); this.namesRelation.add(this._class.getFields()[i].getName()); } } catch (IllegalArgumentException ex) { Logger.getLogger(MproEntity.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(MproEntity.class.getName()).log(Level.SEVERE, null, ex); } } parts = parts.replaceFirst(", $", " "); return parts; } /** * Pega valores com seus campos para update */ private String getValuesUpdate() { String parts = ""; this.namesRelation.clear(); for(int i = 0; i < this._class.getFields().length; i++) { try { if((this._class.getFields()[i].getType() != ArrayList.class) && (this._class.getFields()[i].getType() != List.class)) { if(this._class.getFields()[i].getType() == boolean.class) parts += this._class.getFields()[i].getName() + " = " + ((Boolean)this._class.getFields()[i].get(this) ? "1, " : "0, "); if(i < this._class.getFields().length -1) parts += this._class.getFields()[i].getName() + " = " + (this._class.getFields()[i].getType() == String.class ? "'" : "") + this._class.getFields()[i].get(this).toString() + (this._class.getFields()[i].getType() == String.class ? "', " : ", "); else parts += this._class.getFields()[i].getName() + " = " + (this._class.getFields()[i].getType() == String.class ? "'" : "") + this._class.getFields()[i].get(this).toString() + (this._class.getFields()[i].getType() == String.class ? "'" : ""); } else { this.joined = true; //this.nameRelation = this._class.getFields()[i].getName(); this.namesRelation.add(this._class.getFields()[i].getName()); } } catch (IllegalArgumentException ex) { Logger.getLogger(MproEntity.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(MproEntity.class.getName()).log(Level.SEVERE, null, ex); } } return parts; } public static LauDB getConnection() { return _conn; } @SuppressWarnings("unused") private class containField { public boolean isDB; public String name; public String type; public Field field; public containField(String _name, String _type, boolean _isdb) { this.isDB = _isdb; this.name = _name; this.type = _type; } public containField(Field _field) { this.field = _field; } } }