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+ */
2322package org .javabeanstack .data ;
2423
2524import java .util .Date ;
2625import java .util .HashMap ;
2726import java .util .Iterator ;
27+ import java .util .List ;
2828import java .util .Map ;
2929import javax .annotation .Resource ;
3030import javax .ejb .Lock ;
3838import org .apache .log4j .Logger ;
3939
4040import org .javabeanstack .error .ErrorManager ;
41+ import org .javabeanstack .error .IErrorReg ;
4142import 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 = "\n GO\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}
0 commit comments