Skip to content

Commit 6d205d0

Browse files
committed
DbManager, metodo para actualizar la estructura de la base de datos.
AbstractDataObject, corrección readWrite. IAppSystemEvents, eventos del sistema (login, logout, crear sesion, error) LocalDates, se agrego el metodo minutesInterval, AppGenericConfig, se agrego updateDatabase, getDBVersion, getDBVersionForThisApp
1 parent e5f9106 commit 6d205d0

File tree

13 files changed

+243
-158
lines changed

13 files changed

+243
-158
lines changed

business/src/main/java/org/javabeanstack/data/DBManager.java

Lines changed: 124 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,13 @@
1818
* License along with this library; if not, write to the Free Software
1919
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
2020
* MA 02110-1301 USA
21-
*/
22-
21+
*/
2322
package org.javabeanstack.data;
2423

2524
import java.util.Date;
2625
import java.util.HashMap;
2726
import java.util.Iterator;
27+
import java.util.List;
2828
import java.util.Map;
2929
import javax.annotation.Resource;
3030
import javax.ejb.Lock;
@@ -38,44 +38,53 @@
3838
import org.apache.log4j.Logger;
3939

4040
import org.javabeanstack.error.ErrorManager;
41+
import org.javabeanstack.error.IErrorReg;
4142
import org.javabeanstack.util.Dates;
43+
import org.javabeanstack.util.Fn;
44+
import org.javabeanstack.util.Strings;
45+
import org.javabeanstack.xml.DomW3cParser;
46+
import org.w3c.dom.Document;
47+
import org.w3c.dom.Element;
4248

4349
/**
44-
* Contiene metodos para gestionar el acceso a los datos, es utilizado
45-
* por GenericDAO
46-
*
50+
* Contiene metodos para gestionar el acceso a los datos, es utilizado por
51+
* GenericDAO
52+
*
4753
* @author Jorge Enciso
4854
*/
4955
@Startup
5056
@Lock(LockType.READ)
51-
public class DBManager implements IDBManager{
52-
private static final Logger LOGGER = Logger.getLogger(DBManager.class);
57+
public class DBManager implements IDBManager {
58+
59+
private static final Logger LOGGER = Logger.getLogger(DBManager.class);
5360
private int entityIdStrategic = IDBManager.PERSESSION;
54-
private Date lastPurge=new Date();
55-
61+
private Date lastPurge = new Date();
62+
5663
private final Map<String, Data> entityManagers = new HashMap<>();
5764

5865
@Resource
5966
SessionContext context;
6067

6168
/**
62-
* Devuelve la estrategia de acceso/creación de los entityManagers.
63-
* Los valores posibles son: un entityManager por Thread o un entityManager
64-
* por sesión del usuario.
69+
* Devuelve la estrategia de acceso/creación de los entityManagers. Los
70+
* valores posibles son: un entityManager por Thread o un entityManager por
71+
* sesión del usuario.
72+
*
6573
* @return estrategia de acceso/creación de los entityManagers.
6674
*/
6775
@Override
6876
public int getEntityIdStrategic() {
6977
return entityIdStrategic;
7078
}
7179

72-
7380
/**
74-
* Devuelve un entityManager, lo crea si no existe en la unidad de persistencia solicitada
75-
* @param key id thread
81+
* Devuelve un entityManager, lo crea si no existe en la unidad de
82+
* persistencia solicitada
83+
*
84+
* @param key id thread
7685
* @return Devuelve un entityManager
77-
*/
78-
@Override
86+
*/
87+
@Override
7988
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
8089
public EntityManager getEntityManager(String key) {
8190
try {
@@ -93,77 +102,144 @@ public EntityManager getEntityManager(String key) {
93102
purgeEntityManager();
94103
return em;
95104
} catch (Exception ex) {
96-
ErrorManager.showError(ex,LOGGER);
105+
ErrorManager.showError(ex, LOGGER);
97106
}
98107
return null;
99108
}
100109

101110
/**
102-
* Crea un entitymanager dentro de un Map utiliza la unidad de persistencia
111+
* Crea un entitymanager dentro de un Map utiliza la unidad de persistencia
103112
* y el threadid o sessionid del usuario como clave
104-
*
105-
* @param key id thread o sessionid del usuario
113+
*
114+
* @param key id thread o sessionid del usuario
106115
* @return el entity manager creado.
107116
*/
108-
@Override
109-
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
117+
@Override
118+
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
110119
@Lock(LockType.WRITE)
111-
public EntityManager createEntityManager(String key) {
120+
public EntityManager createEntityManager(String key) {
112121
EntityManager em;
113122
try {
114-
String persistentUnit = key.substring(0,key.indexOf(':')).toLowerCase();
123+
String persistentUnit = key.substring(0, key.indexOf(':')).toLowerCase();
115124
em = (EntityManager) context.lookup("java:comp/env/persistence/" + persistentUnit);
116125
Data data = new Data();
117126
data.em = em;
118127
entityManagers.put(key, data);
119128
LOGGER.debug("--------- Se ha creado un nuevo EntityManager --------- " + key);
120129
return em;
121130
} catch (Exception ex) {
122-
ErrorManager.showError(ex,LOGGER);
131+
ErrorManager.showError(ex, LOGGER);
123132
}
124133
return null;
125134
}
126-
135+
127136
/**
128137
* Elimina los entityManagers del map, a aquellos que no se esta utilizando
129138
* en un periodo dado.
130139
*/
131-
protected void purgeEntityManager(){
132-
LOGGER.debug("purgeEntityManager() "+lastPurge);
140+
protected void purgeEntityManager() {
141+
LOGGER.debug("purgeEntityManager() " + lastPurge);
133142
Date now = new Date();
134143
//Solo procesar si la ultima purga fue hace 5 minutos.
135-
if (!lastPurge.before(DateUtils.addMinutes(now, -5))){
144+
if (!lastPurge.before(DateUtils.addMinutes(now, -5))) {
136145
return;
137146
}
138147
//Purgar aquellos entityManagers que no fueron referenciados hace 5 minutos
139-
now = DateUtils.addMinutes(Dates.now(),-5);
140-
for(Iterator<Map.Entry<String, Data>> it = entityManagers.entrySet().iterator(); it.hasNext(); ) {
148+
now = DateUtils.addMinutes(Dates.now(), -5);
149+
for (Iterator<Map.Entry<String, Data>> it = entityManagers.entrySet().iterator(); it.hasNext();) {
141150
Map.Entry<String, Data> entry = it.next();
142-
if(entry.getValue().lastRef.before(now)) {
143-
LOGGER.debug("Se elimino entityManager: " + entry.getKey());
151+
if (entry.getValue().lastRef.before(now)) {
152+
LOGGER.debug("Se elimino entityManager: " + entry.getKey());
144153
it.remove();
145-
}
154+
}
146155
}
147156
lastPurge = new Date();
148-
LOGGER.debug("Se proceso purgeEntityManager "+lastPurge);
157+
LOGGER.debug("Se proceso purgeEntityManager " + lastPurge);
149158
}
150-
159+
151160
/**
152-
* Ejecuta rollback de una transacción
153-
*/
154-
@Override
155-
@Lock(LockType.WRITE)
156-
public void rollBack(){
161+
* Ejecuta rollback de una transacción
162+
*/
163+
@Override
164+
@Lock(LockType.WRITE)
165+
public void rollBack() {
157166
try {
158-
context.setRollbackOnly();
159-
}
160-
catch (Exception exp){
167+
context.setRollbackOnly();
168+
} catch (Exception exp) {
161169
//
162170
}
163171
}
164-
172+
173+
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
174+
public static void dbScriptUpdateExecute(IGenericDAO dao, String sessionId, Document domScript, Map<String, Object> parameters) throws Exception {
175+
176+
List<Element> sqlScriptNodes = DomW3cParser.getChildren(domScript, "/ROOT/SCRIPTS");
177+
IErrorReg errorReturn;
178+
179+
//Inicio================================================
180+
String initCommand = "INSERT INTO {schema}.dic_logupdate "
181+
+ "(secuencia, filename,script, appuser) "
182+
+ " values "
183+
+ "(:secuencia,:filename,:script, :appuser)";
184+
185+
dao.sqlExec(sessionId, initCommand, parameters);
186+
187+
String persistUnit = dao.getDBLinkInfo(sessionId).getPersistUnit();
188+
String motorDatos = dao.getDataEngine(persistUnit);
189+
for (Element sqlScriptNode : sqlScriptNodes) {
190+
//Solo se ejecuta los scripts que corresponde a motor de la base
191+
if (!sqlScriptNode.getAttribute("motor").equals(motorDatos)) {
192+
continue;
193+
}
194+
String stringEnd = "\nGO\n";
195+
if (!Fn.inList(motorDatos, "SQLSERVER", "Microsoft SQL Server", "SYBASE")) {
196+
stringEnd = "\n/\n";
197+
}
198+
String script = sqlScriptNode.getTextContent();
199+
//Actualizar script a ejecutarse
200+
parameters.put("script", DomW3cParser.getXmlText(sqlScriptNode));
201+
String command = "UPDATE {schema}.dic_logupdate "
202+
+ " SET script = :script "
203+
+ " where secuencia = :secuencia";
204+
dao.sqlExec(sessionId, command, parameters);
205+
parameters.put("script", "");
206+
207+
while (!script.isEmpty()) {
208+
String sentencia;
209+
int posicion = script.toUpperCase().indexOf(stringEnd);
210+
if (posicion < 0) {
211+
sentencia = Strings.substr(script, 0);
212+
script = "";
213+
} else {
214+
sentencia = Strings.substr(script, 0, posicion );
215+
script = Strings.substr(script, posicion + stringEnd.length());
216+
}
217+
// Ejecución del Script
218+
errorReturn = dao.sqlExec(sessionId, sentencia, parameters);
219+
if (errorReturn.getErrorNumber() > 0) {
220+
if (!Fn.toLogical(parameters.get("CONTINUE_WITH_ERROR"))) {
221+
//Revertir proceso==================================
222+
String revertCommand = "delete from {schema}.dic_logupdate where secuencia = :secuencia";
223+
dao.sqlExec(sessionId, revertCommand, parameters);
224+
throw new Exception(errorReturn.getMessage());
225+
} else {
226+
Exception ex = new Exception("ACTUALIZACIÓN BASE DE DATOS " + errorReturn.getMessage());
227+
ErrorManager.showError(ex, LOGGER);
228+
}
229+
}
230+
}
231+
}
232+
//Fin ============================================
233+
String endCommand = "UPDATE {schema}.dic_logupdate "
234+
+ " SET concluido = {true} "
235+
+ " where secuencia = :secuencia";
236+
237+
dao.sqlExec(sessionId, endCommand, parameters);
238+
}
239+
165240
class Data {
166-
EntityManager em;
167-
Date lastRef = Dates.now();
241+
242+
EntityManager em;
243+
Date lastRef = Dates.now();
168244
}
169245
}

business/src/main/java/org/javabeanstack/datactrl/AbstractDataObject.java

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ public abstract class AbstractDataObject<T extends IDataRow> implements IDataObj
8484
/**
8585
* Si los datos a recuperar puede ser de lectura y escritura
8686
*/
87-
private boolean readWrite;
87+
private boolean readWrite = true;
8888
/**
8989
* Filtro, se utiliza para seleccionar los datos de la base
9090
*/
@@ -146,7 +146,7 @@ public abstract class AbstractDataObject<T extends IDataRow> implements IDataObj
146146
* @return Devuelve true si los datos son de solo lectura
147147
*/
148148
@Override
149-
public boolean isReadwrite() {
149+
public boolean isReadWrite() {
150150
return readWrite;
151151
}
152152

@@ -596,7 +596,7 @@ public boolean open() {
596596
filters = new HashMap();
597597
firstRow = 0;
598598
maxrows = -1;
599-
return this.open("", "", true, -1);
599+
return this.open("", "", null, -1);
600600
}
601601

602602
/**
@@ -610,8 +610,9 @@ public boolean open() {
610610
* @return verdadero si tu exito la recuperación, falso si no
611611
*/
612612
@Override
613-
public boolean open(String order, String filter, boolean readwrite, int maxrows) {
613+
public boolean open(String order, String filter, Boolean readwrite, int maxrows) {
614614
try {
615+
readwrite = (readwrite == null) ? this.readWrite : readwrite;
615616
errorApp = null;
616617
this.beforeOpen(order, filter, readwrite, maxrows);
617618
//
@@ -778,12 +779,12 @@ public boolean requery() {
778779
}
779780

780781
public void openOrRequery(String filter) {
781-
openOrRequery("", filter, true, -1);
782+
openOrRequery("", filter, -1);
782783
}
783784

784-
public void openOrRequery(String order, String filter, boolean readwrite, int maxrows) {
785+
public void openOrRequery(String order, String filter, int maxrows) {
785786
if (!this.isOpen()) {
786-
this.open(order, filter, true, 0);
787+
this.open(order, filter, null, 0);
787788
if (maxrows == 0) {
788789
return;
789790
}
@@ -795,7 +796,7 @@ public void openOrRequery(String order, String filter, boolean readwrite, int ma
795796
public boolean openOrRequery(String fieldName, Object fieldValue, String order, int maxrows) {
796797
boolean result = false;
797798
if (!this.isOpen() || fieldValue == null) {
798-
this.open("", "", true, 0);
799+
this.open("", "", null, 0);
799800
}
800801
if (fieldValue != null) {
801802
Map<String, Object> param = new HashMap();
@@ -816,7 +817,7 @@ public boolean openOrRequery(String fieldName, Object fieldValue, String order,
816817
public boolean openOrRequeryIf(String fieldName, Object fieldValue, String order, int maxrows) {
817818
boolean result = false;
818819
if (!this.isOpen() || fieldValue == null) {
819-
this.open("", "", true, 0);
820+
this.open("", "", null, 0);
820821
}
821822
if (fieldValue != null && !fieldValue.equals(idParent)) {
822823
Map<String, Object> param = new HashMap();

business/src/main/java/org/javabeanstack/security/Sessions.java

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -213,12 +213,13 @@ protected boolean processCreateSession(IUserSession session, Object idcompany, I
213213
// Tiempo de expiración en minutos desde ultima actividad
214214
session.setIdleSessionExpireInMinutes(idleSessionExpireInMinutes);
215215

216-
// Metodo que se ejecuta al final del proceso con el fin de que en clases derivadas
217-
// se pueda realizar tareas adicionales como anexar otros atributos a la sesión.
218-
afterCreateSession(session);
219216
// Agregar sesión al pool de sesiones
220217
sessionVar.put(sessionId, session);
221218
LOGGER.debug("Sesión creada: " + sessionId);
219+
220+
// Metodo que se ejecuta al final del proceso con el fin de que en clases derivadas
221+
// se pueda realizar tareas adicionales como anexar otros atributos a la sesión.
222+
afterCreateSession(session);
222223
return true;
223224
}
224225

@@ -329,13 +330,14 @@ protected boolean processCreateSessionFromToken(IUserSession session, IAppAuthCo
329330
// Tiempo de expiración en minutos desde ultima actividad
330331
session.setIdleSessionExpireInMinutes(idleSessionExpireInMinutes);
331332

332-
// Metodo que se ejecuta al final del proceso con el fin de que en clases derivadas
333-
// se pueda realizar tareas adicionales como anexar otros atributos a la sesión.
334-
afterCreateSession(session);
335333
// Agregar sesión al pool de sesiones
336334
sessionVar.put(token, session);
337335
//
338336
LOGGER.debug("Sesión creada: " + token);
337+
338+
// Metodo que se ejecuta al final del proceso con el fin de que en clases derivadas
339+
// se pueda realizar tareas adicionales como anexar otros atributos a la sesión.
340+
afterCreateSession(session);
339341
return true;
340342
}
341343

@@ -589,7 +591,7 @@ public UserSession getUserSession(String sessionIdEncrypted) {
589591
* @param sessionId identificador de la sesión o el token
590592
* @return DBLinkInfo
591593
*/
592-
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
594+
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
593595
@Override
594596
public IDBLinkInfo getDBLinkInfo(String sessionId) {
595597
IDBLinkInfo dbLinkInfo = new DBLinkInfo();

0 commit comments

Comments
 (0)