31 marzo 2010

hibernate: procesos batch

Procesos batch

si por alguna razón queremos deshabilitar o evitar el uso del cache, podemos usar un tipo especial de session: StatelessSession, se obtiene de la sessionFactory con el método openStatelessSession(). Yo la uso en el caso de los procesos batch, por ejemplo cuando tengo que hacer inserts o updates masivos, así evito que cada vez que hago el save de un objeto, el mismo me quede en memoria y en el correr del proceso se produzca un error del tipo OutOfMemoryError. La StatelessSession no interactúa con el First Level Cache ni con el Second Level Cache, es casi como si utilizáramos JDBC directamente.

29 marzo 2010

@PreUpdate @PrePersist

prueba de @PreUpdate

no pasa por el preUpdate de booking ni con los Home ni con el entityManager

código de la prueba (action1.java)
package org.domain.test11.session;

import javax.persistence.EntityManager;

import org.domain.test11.entity.Booking;
import org.domain.test11.entity.Hotel;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.international.StatusMessages;
import org.jboss.seam.log.Log;

@Name("action1")
public class Action1
{
@Logger private Log log;

@In StatusMessages statusMessages;

@In(create=true) BookingHome bookingHome;
@In(create=true) HotelHome hotelHome;
public void action1()
{
// implement your business logic here
log.info("action1.action1() action called");
statusMessages.add("action1");

update3();

}

@In EntityManager entityManager;
public void update2() {
Booking b = (Booking)entityManager.find(Booking.class, new Long(1));
b.getCustomer().setName("pepero");
entityManager.persist(b);
}

public void update3() {
Hotel hotel = hotelHome.getEntityManager().find(Hotel.class, new Long(1));
Booking booking = bookingHome.getEntityManager().find(Booking.class, new Long(1));
booking.getHotel().setCity("madrid3");
booking.getCustomer().setName("manolo6");
bookingHome.setInstance(booking);
bookingHome.update();
}

// add additional action methods

}

24 marzo 2010

para los logs de los procesos

en este código se puede ver cómo añadir un appender al logger de la clase. La clase llamará a un método en un servicio pasándole el logger, y este servicio añadirá al logger el appender.
También podemos pasar del log de seam y configurar el logger de la forma clásica en log4j (como en el ejemplo siguiente).
package es.imserso.sample.log;
import java.io.IOException;
import java.util.Enumeration;

import org.apache.log4j.Appender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.SimpleLayout;



public class Inicio {

static Logger logger = Logger.getLogger(Inicio.class);

/**
* @param args
*/
public static void main(String[] args) {
PropertyConfigurator.configure("log4j.properties");

logger.info("comienzo de la aplicación");

Inicio i = new Inicio();
i.ejecuta();

logger.info("fin de la aplicación");

}


private void ejecuta() {

try {
Appender appender = null;
logger.addAppender(new FileAppender(new SimpleLayout(), "proceso2.log"));
logger.info("iniciando proceso...");
logger.info("este fichero tiene que ser proceso2.log");

Enumeration e = logger.getAllAppenders();

while (e.hasMoreElements()) {
appender = e.nextElement();
appender.setName("myappender");
}

logger.info("finalizando proceso...");
logger.removeAppender(appender);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
logger.error("mosramos un error");

}

}

17 marzo 2010

New (3.2.3) Hibernate identifier generators

Desde la url Hibernate Core 3.3.1 released, pinchamos en enhanced id generators y accedemos a una página donde se detallan exhaustivamente los drásticos cambios que se han hecho en esta versión.

Lo más importante es lo que pone en la conclusion:

Conclusion

I would expect that these two new generators actually replace currently existing ones in terms of short-hand names. Specifically, I would expect

  • the implementation behind sequence to change from org.hibernate.SequenceGenerator to the new org.hibernate.id.enhanced.SequenceStyleGenerator
  • the implementation behing table to change from org.hibernate.TableGenerator to the new org.hibernate.id.enhanced.TableGenerator

The second is the more risky replacement because of the big difference between the two. But we've all along discouraged direct use of the current table generator so I think we should be safe there. I am still uncertain when that replacement will happen (probably 4.0?), but in the meantime, the new generators are available and highly recommended for use.

Hay que pensarlo bien, parece que lo mejor es usar estos nuevos generadores

Unified error page and exception handling

Unified error page and exception handling


A web application can run into a server-side error for many different reasons and at any point in time. Finding the right strategy for your application, how to deal with these error conditions and exceptional situations, can be difficult. This page provides some guidelines and a simple but effective solution.

When a client request is handled by a web application server, exceptions can be thrown by code at any time. Typically, you need to consider:

  • Exceptions thrown by the web application server, usually the servlet container. For example, exceptions you definitely have to expect and handle include session limit violations. If your servlet container reaches its configured maximum active session limit, your users should be presented with a nice error message that tells them to come back later.
  • Exceptions can be thrown by the web application frameworks and 3rd party libraries you are using. In a Seam application, those frameworks would typically include JSF, Facelets, Hibernate, and of course Seam and any of its integration modules. There are many exceptions that are obvioulsy related to bugs in your application, for these you might want to encourage the users to report these with a nice message. But you also have other exceptions, such as database lock acquisition failures, that indicate an overloaded system, which does not necessarily require a bug report.
  • Finally, you have your own error handling in your web application. You use (runtime) infrastructure exceptions to indicate fatal error conditions which should be reported by users when they encounter them. You use (checked) application exceptions that are expected and are handled in your code, probably without even letting the users know that some exceptional application flow occurred behind the scenes.

Handling recoverable exceptions

Seam comes with an exception handling servlet filter that wraps its processing of a request:

(... seguir leyendo en el sitio original)

16 marzo 2010

hermes: exceptions

Enabling Seam exception handling

mirar seam_reference: 6.12.2. Enabling Seam exception handling

You need to disable Facelets development mode in web.xml and Seam debug mode in
components.xml if you want your exception handlers to fire

--------


Las excepciones que sean gordas las podemos redirigir desde la misma excepción:

@Redirect(viewId="/failure.xhtml", end=true)
@ApplicationException
public class UnrecoverableApplicationException extends RuntimeException { ... }


Esta excepción hace que se redirija siempre que se propague fuera de la capa de componentes Seam. Asímismo finaliza la conversación.

-----

hay que declarar en el components.xml:

<core:resource-loader>
<core:bundle-names>
<value>messages</value>
</core:bundle-names>
</core:resource-loader>

---------

cualquiera de estas dos formas de coger los mensajes en la excepción funciona:

String msg1 = SeamResourceBundle.getBundle().getString("exception.myexception");


String msg2 = ResourceBundle.getBundle("messages", FacesContext.getCurrentInstance().getViewRoot().getLocale()).getString("exception.myexception");


-------------

En el messages.properties:

exception.message1=Eureka, dijo {0}

Esta excepción funciona:

import org.jboss.seam.core.Interpolator;
import org.jboss.seam.core.SeamResourceBundle;

public class MyException extends Exception {

@Override
public String getMessage() {

String msg1 = SeamResourceBundle.getBundle().getString(
"exception.message1");
String msg2 = Interpolator.instance().interpolate(msg1, "Arquímedes");

return msg2;
}
}