30 diciembre 2009

Setting an isolation level

Setting an isolation level
Every JDBC connection to a database is in the default isolation level of the DBMS—
usually read committed or repeatable read. You can change this default in the
DBMS configuration. You may also set the transaction isolation for JDBC connec-
tions on the application side, with a Hibernate configuration option:
hibernate.connection.isolation = 4
Hibernate sets this isolation level on every JDBC connection obtained from a
connection pool before starting a transaction. The sensible values for this option
are as follows (you may also find them as constants in java.sql.Connection):
■ 1—Read uncommitted isolation
■ 2—Read committed isolation
■ 4—Repeatable read isolation
■ 8—Serializable isolation
Note that Hibernate never changes the isolation level of connections obtained
from an application server-provided database connection in a managed environ-
ment! You can change the default isolation using the configuration of your appli-
cation server. (The same is true if you use a stand-alone JTA implementation.)
As you can see, setting the isolation level is a global option that affects all con-
nections and transactions. From time to time, it’s useful to specify a more restric-
tive lock for a particular transaction. Hibernate and Java Persistence rely on
optimistic concurrency control, and both allow you to obtain additional locking
guarantees with version checking and pessimistic locking.

Transaction types




RESOURCE-LOCAL=>EntityTransaction
JTA=>UserTransaction

Hibernate exceptions

Any Hibernate operation, including flushing the persistence context, can throw a
RuntimeException. Even rolling back a transaction can throw an exception! You
want to catch this exception and log it; otherwise, the original exception that led
to the rollback is swallowed.
An optional method call in the example is setTimeout(), which takes the
number of seconds a transaction is allowed to run. However, real monitored trans-
actions aren’t available in a Java SE environment. The best Hibernate can do if
you run this code outside of an application server (that is, without a transaction
manager) is to set the number of seconds the driver will wait for a Prepared-
Statement to execute (Hibernate exclusively uses prepared statements). If the
limit is exceeded, an SQLException is thrown.

You don’t want to use this example as a template in your own application,
because you should hide the exception handling with generic infrastructure code.
You can, for example, write a single error handler for RuntimeException that
knows when and how to roll back a transaction. The same can be said about open-
ing and closing a Session. We discuss this with more realistic examples later in
the next chapter and again in chapter 16, section 16.1.3, “The Open Session in
View pattern.”
Hibernate throws typed exceptions, all subtypes of RuntimeException that help
you identify errors:
■ The most common HibernateException is a generic error. You have to
either check the exception message or find out more about the cause by
calling getCause() on the exception.
■ A JDBCException is any exception thrown by Hibernate’s internal JDBC
layer. This kind of exception is always caused by a particular SQL statement,
and you can get the offending statement with getSQL(). The internal
exception thrown by the JDBC connection (the JDBC driver, actually) is
available with getSQLException() or getCause(), and the database- and
vendor-specific error code is available with getErrorCode().
■ Hibernate includes subtypes of JDBCException and an internal converter
that tries to translate the vendor-specific error code thrown by the database
driver into something more meaningful. The built-in converter can pro-
duce JDBCConnectionException, SQLGrammarException, LockAquisition-
Exception, DataException, and ConstraintViolationException for the
most important database dialects supported by Hibernate. You can either
manipulate or enhance the dialect for your database, or plug in a SQLEx-
ceptionConverterFactory to customize this conversion.
■ Other RuntimeExceptions thrown by Hibernate should also abort a transac-
tion. You should always make sure you catch RuntimeException, no matter
what you plan to do with any fine-grained exception-handling strategy.

You now know what exceptions you should catch and when to expect them. How-
ever, one question is probably on your mind: What should you do after you’ve
caught an exception?
All exceptions thrown by Hibernate are fatal. This means you have to roll back
the database transaction and close the current Session. You aren’t allowed to con-
tinue working with a Session that threw an exception.

Usually, you also have to exit the application after you close the Session fol-
lowing an exception, although there are some exceptions (for example, Stale-
ObjectStateException) that naturally lead to a new attempt (possibly after
interacting with the application user again) in a new Session.

A history of exceptions

Exceptions and how they should be handled always
end in heated debates between Java developers. It isn’t surprising that
Hibernate has some noteworthy history as well. Until Hibernate 3.x, all
exceptions thrown by Hibernate were checked exceptions, so every Hiber-
nate API forced the developer to catch and handle exceptions. This strat-
egy was influenced by JDBC, which also throws only checked exceptions.
However, it soon became clear that this doesn’t make sense, because all
exceptions thrown by Hibernate are fatal. In many cases, the best a
developer can do in this situation is to clean up, display an error message,
and exit the application. Therefore, starting with Hibernate 3.x, all
exceptions thrown by Hibernate are subtypes of the unchecked Runtime-
Exception, which is usually handled in a single location in an application.
This also makes any Hibernate template or wrapper API obsolete.

Manning.Java.Persistence.with.Hibernate.Nov.2006.pdf

06 diciembre 2009

Have you ever found yourself frustrated with a ClassNotFoundException?

Tattletale

Have you ever found yourself frustrated with a ClassNotFoundException? Would you like to know what libraries are in your project and what they depend on? Would you like to get a full report on this stuff every time you run your ant build? If so you need to use the JBoss Tattletale project!

JBoss Tattletale is a tool that can help you get an overview of the project you are working on or a product that you depend on.

The tool will provide you with reports that can help you

  • Identify dependencies between JAR files

  • Find missing classes from the classpath

  • Spot if a class/package is located in multiple JAR files

  • Spot if the same JAR file is located in multiple locations

  • With a list of what each JAR file requires and provides

  • Verify the SerialVersionUID of a class

  • Find similar JAR files that have different version numbers

  • Find JAR files without a version number

  • Find unused JAR files

  • Identify sealed and signed JAR archives

  • Locate a class in a JAR file

  • Get the OSGi status of your project

JBoss Tattletale will recursive scan the directory pass as the argument for JAR files and then build the reports as HTML files.

JBoss Tattletale is licensed under GNU Lesser General Public License (LGPL) version 2.1 or later.

We hope that JBoss Tattletale will help you in your development tasks !

Please, visit the official JBoss Tattletale project page at http://www.jboss.org/tattletale/.

JavaBeans

Javabeans may be used just like a stateless or stateful session bean. However, they do not provide the functionality of a session bean (declarative transaction demarcation, declarative security, efficient clustered state replication, EJB 3.0 persistence, timeout methods, etc).

Seam JavaBean components may be instantiated using Component.getInstance() or
@In(create=true). They should not be directly instantiated using the new operator.

Entity beans

Entity beans are not usually used as JSF action listeners, but do often function as backing beans that provide properties to JSF components for display or form submission. In particular, it is common to use an entity as a backing bean, together with a stateless session bean action listener to implement create/update/delete type functionality.

Seam entity bean components may be instantiated using Component.getInstance(),
@In(create=true) or directly using the new operator.

Stateful session beans

Application state that does not belong in the database should usually be held by stateful session beans. Instead of sticking information about the current
conversation directly in the HttpSession, you should keep it in instance variables of a stateful session bean that is bound to the conversation context.

Stateful session beans are often used as JSF action listener, and as backing beans that provide properties to JSF components for display or form submission.

Seam stateful session bean components may be instantiated using Component.getInstance()
or @In(create=true)
. They should not be directly instantiated via JNDI lookup or the new operator.

Stateless session beans

Stateless session beans can be accessed concurrently as a new instance is used for each request. Assigning the instance to the request is the responsibility of the EJB3 container (normally instances will be allocated from a reusable pool meaning that you may find any instance variables contain data from previous uses of the bean).

Seam stateless session bean components may be instantiated using Component.getInstance() or @In(create=true). They should not be directly instantiated via JNDI lookup or the new operator.

05 diciembre 2009

El catalán es un dialecto del español

definiciones:

dialecto.

(Del lat. dialectus, y este del gr. διάλεκτος).

1. m. Ling. Sistema lingüístico considerado con relación al grupo de los varios derivados de un tronco común. El español es uno de los dialectos nacidos del latín.

2. m. Ling. Sistema lingüístico derivado de otro, normalmente con una concreta limitación geográfica, pero sin diferenciación suficiente frente a otros de origen común.

3. m. Ling. Estructura lingüística, simultánea a otra, que no alcanza la categoría social de lengua.


lengua.

(Del lat. lingua).

1. f. Órgano muscular situado en la cavidad de la boca de los vertebrados y que sirve para gustación, para deglutir y para modular los sonidos que les son propios.

2. f. Sistema de comunicación verbal y casi siempre escrito, propio de una comunidad humana.

3. f. Sistema lingüístico cuyos hablantes reconocen modelos de buena expresión. La lengua de Cervantes es oficial en 21 naciones

4. f. Sistema lingüístico considerado en su estructura.

5. f. Vocabulario y gramática propios y característicos de una época, de un escritor o de un grupo social. La lengua de Góngora La lengua gauchesca


idioma.

(Del lat. idiōma, y este del gr. ἰδίωμα, propiedad privada).

1. m. Lengua de un pueblo o nación, o común a varios.




catalán, na.

1. adj. Natural de Cataluña. U. t. c. s.

2. adj. Perteneciente o relativo a este antiguo principado, hoy comunidad autónoma de España.

3. m. Lengua romance vernácula que se habla en Cataluña y en otros dominios de la antigua Corona de Aragón.



castellano, na.

(Del lat. Castellānus).

1. adj. Natural de Castilla. U. t. c. s.

2. adj. Perteneciente o relativo a esta región de España.

3. adj. Dicho de una gallina: De cierta variedad negra muy ponedora.

4. m. Lengua española, especialmente cuando se quiere introducir una distinción respecto a otras lenguas habladas también como propias en España.

5. m. Dialecto románico nacido en Castilla la Vieja, del que tuvo su origen la lengua española.

6. m. Variedad de la lengua española hablada modernamente en Castilla la Vieja.




español, la.

(Del prov. espaignol, y este del lat. mediev. Hispaniŏlus, de Hispania, España).

1. adj. Natural de España. U. t. c. s.

2. adj. Perteneciente o relativo a este país de Europa.

3. m. Lengua común de España y de muchas naciones de América, hablada también como propia en otras partes del mundo.








a favor:











en contra:

04 diciembre 2009

hsqldb

para instalar y gestionar bases de datos hsqldb:

1.- bajar hsqldb de su web
2.- descomprimir en c:\hsqldb
3,. ejecutar
java -cp lib/hsqldb.jar org.hsqldb.Server -database.0 file:mydb -dbname.0 xdb

4.- ejecutar desde demo:
runManagerSwing.bat

5.- conectar mediante el wizard del manager (jdbc:hsqldb:hsql://localhost/xdb)
6.- generar el esquema ejecutando:
CREATE SCHEMA ROOT AUTHORIZATION dba;
SET SCHEMA ROOT;
CREATE USER root PASSWORD root ADMIN;
7.- crear las tablas como por ejemplo:
create table MESSAGES (
MESSAGE_ID bigint generated by default as identity (start with 1),
MESSAGE_TEXT varchar(255),
NEXT_MESSAGE_ID bigint,
primary key (MESSAGE_ID)
);

alter table MESSAGES
add constraint FK131AF14C3CD7F3EA
foreign key (NEXT_MESSAGE_ID)
references MESSAGES;
8.- Desde el HSQL Manager seleccionamos Schemas -> HERMES

03 diciembre 2009

hibernate3:hbm2ddl

hibernate3:hbm2ddl

  1. la solución más fácil para lo del esquema en hsqldb es crear el esquema a mano desde HSQLDB database manager
  2. otra solución sencilla puede ser definir el esquema en orm.xml y eliminarlo de las entities (lo que ponga en el orm.xml sobreescribe lo que ponga en anotaciones)
  3. la solución óptima parece ser eliminar @Table de las entities y declarar el default_schema en persistence.xml, en hibernate.properties y/o en hibernate.cfg.xml
  4. <?xml version="1.0" encoding="UTF-8"?>
    <entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_1_0.xsd"
    version="1.0">

    <persistence-unit-metadata>
    <persistence-unit-defaults>
    <schema>hermes</schema>
    </persistence-unit-defaults>
    </persistence-unit-metadata>

    </entity-mappings>

  5. la solución más elegante, aunque mucho más complicada, es aplicar los parches a:
  • src/org/hibernate/dialect/Dialect.java
  • src/org/hibernate/dialect/HSQLDialect.java
  • src/org/hibernate/cfg/Configuration.java

30 noviembre 2009

Palestina: región o estado

fuente: http://www.mgar.net/africa/israel.htm

El plan de las Naciones Unidas (1947):

...Contemplaba la división de Palestina en dos países independientes

...Hasta el punto de que éstos, ante la imposibilidad de resolver un problema cada vez más enrevesado, recurrieron a las Naciones Unidas, que en célebre reunión del 19 de noviembre de 1947 decidió la partición de Palestina en dos Estados: uno israelí y otro árabe con una zona internacional para Jerusalén. Poco después se proclamaría la independencia del Estado judío el 15 de mayo de 1948, con la huida masiva de palestinos de su territorio. Y la guerra que siguió, hasta 1949, permitió ampliar el espacio israelí en 5.000 kilómetros cuadrados sobre la previa partición de la ONU, incluyendo una zona muy importante de Jerusalén. La Palestina árabe quedó sometida a sendos despojos, la franja de Gaza y de Cisjordania.(Ramón Tamames)



Palestina: un Estado ocupado, un pueblo masacrado.

...para que devuelvan a Palestina el status de nación libre y soberana.
El pueblo palestino quiere recuperar su patria, su libertad.



Palestina; Historia de un pais robado

Este site describe MUY BIEN la historia palestina desde el siglo XV muy detalladamente










sites que defienden la idea de que no ha existido nunca un estado palestino:


http://www.elimparcial.es/contenido/13682.html

De llegar a nacer, habría sido creado el primer país palestino en la historia pues, a diferencia de Israel, nunca antes ha constituido un Estado, si bien ha sido dominado por diferentes imperios como el romano, el turco otomano o, más tarde, el británico. Palestina nunca ha constituido una entidad por sí misma.
















29 noviembre 2009

IBM WebSphere Application Server for Developers

IBM WebSphere Application Server 7 for Developers

WebSphere Application Server for Developers - Now downloadable, No charge

Want to try out WebSphere Application Server V7.0 for development? Check!
Want to do it without having to order a CD? Check!
Want to do it without having to work with purchasing? Check!
Want to do it by yourself as a developer? Double Check!

I talk to many developers who want to install WebSphere Application Server for development, but every license is tracked and installed by their operations team on some remote server. Working with the operations team and (gasp) purchasing would take more time than the time to write the application they wanted to write. So they go off and download some other runtime and later port the application back to WebSphere Application Server or abandon the project altogether.

This won't be the story after today. Go here to download a no-charge copy of WebSphere Application Server for your development needs.

From the download page:

Download WebSphere Application Server for Developers, a no-charge offering that satisfies the need for a no-cost WebSphere Application Server development runtime for projects that don't warrant the expense of a priced and supported runtime on the developer desktop. Reduce testing effort and develop with confidence using a runtime environment that is identical to the production runtime environment your applications will eventually run on.

proyecto base para hermes con seam 2.2.0.GA y JBoss AS 5.1

El ejemplo Seam 2.2 Booking Example -(EAR including a tutorial) que podemos bajar desde eclipse nos puede servir de base para migrar hermes a seam 2.2.0, puesto que funcionan los test a la primera.

Sólo hay que cambiar el servidor a JBoss AS 5.1 y seam a 2.2.0.GA

Using Maven, Eclipse and JBoss Tools

Using Maven, Eclipse and JBoss Tools

Para usar el template de proyectos seam mavenizados con eclipse

(muestra cómo configurar eclipse con UTF-8 en MUCHAS preferencias)

A Mavenized Seam Project Template

A Mavenized Seam Project Template

Know IT Objectnet developers have created a Mavenized Seam project template. Due to the lack of Maven support in the Seam project, we felt the need to get a project started for the topic. After some research and development, the base was ready to be put in use. We felt that it was only right to make the project available to the public, and put together a google code project. As of now the project is aimed at running on the JBoss-4.2.3 and JBoss-5.x application servers deployed as an EAR project.

We welcome fellow Seam + Maven fans to this project. Whether you want to use this template to develop your own projects, or you want to contribute to the project, we invite you to check out the code.

To get started check out this tutorial

26 noviembre 2009

Manejar Proyectos J2EE

Manejar Proyectos J2EE


1 . Introducción
2 . Elegir
3 . Colaboración del Equipo
3.1 . El Respositorio de Proyecto de Maven
3.2 . El Modelo de Objeto de Proyecto (POM) de Maven
4 . Obtener Feedback del Proyecto
4.1 . Utilizar CruiseControl con Maven
5 . Manejar el Ciclo Construir/Desplegar con un sólo Click
6 . Desarrollar Varios Proyectos
7 . Empaquetar un Proyecto J2EE
8 . Tutorial de Manejo de Código
8.1 . Iniciar el Proyecto
8.2 . El Plug-in genapp de Maven
8.3 . El Plug-in JDeveloper de Maven
8.4 . Ejecutar Maven desde dentro de JDeveloper
8.5 . La Consola Maven
9 . Sumario
10 . Próximos Pasos

Hacer un merge entre dos ramas de SVN

No es la primera vez que me enfrento a ello, pero siempre se me olvida cómo se hace y pierdo un montón de tiempo con ello. Así que lo apunto:

El escenario son 2 rama: el trunk y un branch del primero. El branch se creó en el día D, y en la revisión 100 (esto es importante!, mirad el log del svn si no lo sabéis). Hoy, trunk está en la revisión 400. El objetivo es mover todos los desarrollos de la branch a trunk.

1. Lo primero que hay que hacer es sincronizar todos los cambios de branch y trunk, y asegurarse que nadie trabaja en branch
2. Se baja la última versión de trunk, y no se modifica!
3. Se selecciona el proyecto trunk, y se pulsa en Team/Merge…
4. En el campo From se elige el proyecto Trunk en la revisión 100 (cuando se creó el branch!)
5. En el campo To se elige el proyecto Branch, en la HEAD revision
6. Ejecutar un DryRun. Esto simula el merge y así se puede ver si vamos bien o no
7. Ejecutar el Merge
8. Revisar todos los conflictos, los ficheros que se han borrado del trunk (aparecerán como nuevos, con el ? de svn). Borrarlos definitivamente, o no.

Y bueno, ahora volver a hacer un syncronize y un commit a ver que conflictos encontramos

25 noviembre 2009

deploying JEE5 apps on Websphere

Integrating WebSphere EJB Deploy Ant Task with Maven 2

by Peter Pilgrim

Maven 2.0 has a valuable plug-in called maven-ejb-plugin, which creates an EJB-JAR file from a series of classes and resources. Unfortunately maven-ejb-plugin, since it is open source, does not know to build proprietary skeletons and stubs for commercial application server. In other words it does not compile or generate EJB application server specific artifacts. For Websphere this means running a specific EJB compiler. Compare this behaviour directly with the Ant EJB doclet task. How does one intercept the workings of the maven-ejb-plugin such that we can instrument EJB JAR with the Websphere EJB compiler?

Maven 2 and WebSphere - automated build and deployment of J2EE applications

muestra los pom.xml COMPLETOS para EJB, WAR, EAR y parent, partiendo del link anterior de Peter Pilgrim

WAS6 maven plugin

TODO: probar una aplicación JEE5 simple, sin Seam, desplegarla en WAS7 y correrla

This plugin can be used to

  • Generate EJB stub code
  • Generate or modify resource descriptor
  • Deploy EARs to targets (servers and/or clusters)
  • Start/stop applications
  • Start/stop targets (servers and/or clusters).
  • Execute arbitrary scripts controlling WAS environments.
  • Generate EAR files suitable for deploying into a WebSphere Process Server environment using ServiceDeploy.

Developing Rich Internet Applications for WebSphere Application Server Community Edition

quizás pueda servir de ejemplo

23 noviembre 2009

Seam 2.2.0.GA JEE5 application running on WAS7

seam_reference.pdf => Chapter 40: Seam on IBM's Websphere AS



(TODO: maven2 deploy on WAS7)

28 octubre 2009

persistencia y transacciones

http://www.jboss.org/ejb3/docs/reference/build/reference/en/html/hibernate.html#d0e314


5.1. Hibernate Mapping Files

Persistent classes that are mapped using Hibernate .hbm.xml files are supported. The EJB3 Deployer will search the archive for any .hbm.xml files and add them to the definition of the underlying Hibernate SessionFactory. These .hbm.xml files can be virtually anywhere within the archive under any java package or directory.

Class Mappings defined in .hbm.xml files can be managed by EntityManagers just as annotated @Entity beans are. Also, you are allowed to have relationships between a .hbm.xml mapped class and an EJB3 entity. So, mixing/matching is allowed.

5.2. Injection Hibernate Session and SessionFactory

You can inject a org.hibernate.Session and org.hibernate.SessionFactory directly into your EJBs just as you can do with EntityManagers and EntityManagerFactorys. The behavior of a Session is just the same as the behavior of an injected EntityManager. The application server controls the lifecycle of the Session so that you do not have to open, flush, or close the session. Extended persistence contexts also work with injected Hibernate Sessions.

import org.hibernate.Session;
import org.hibernate.SessionFactory;

@Stateful public class MyStatefulBean ... {
@PersistenceContext(unitName="crm") Session session1;
@PersistenceContext(unitName="crm2", type=EXTENDED) Session extendedpc;
@PersistenceUnit(unitName="crm") SessionFactory factory;

}

5.3. Access to org.hibernate.Session

You can get access to the current underlying Hibernate Session by typecasting your reference to EntityManager.

 @PersistenceContext EntityManager entityManager;
public void someMethod();
{
org.jboss.ejb3.entity.HibernateSession hs = (HibernateSession)entityManager;
org.hibernate.Session session = hs.getHibernateSession();
}

5.4. Access to org.hibernate.Query

You can get access to the current underlying Hibernate Query by typecasting your reference to a org.hibernate.ejb.QueryImpl.

 @PersistenceContext EntityManager entityManager;
public void someMethod();
{
javax.persistence.Query query = entityManager.createQuery(...);
org.hiberante.ejb.QueryImpl hs = (QueryImpl)query;
org.hibernate.Query hbQuery = hs.getHibernateQuery();
}


programmatic persistence properties in JPA

JPA also supports programmatic configuration, with a map of options:

Map myProperties = new HashMap();
myProperties.put("hibernate.hbm2ddl.auto", "create-drop");
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("helloworld", myProperties)

Custom programmatic properties override any property you’ve set in the persis-
tence.xml configuration file.

persistencia y transacciones

otra forma de establecer los boundaries de una transacción en JPA:

package hello;
import java.util.*;
import javax.persistence.*;
public class HelloWorld {
public static void main(String[] args) {
// Start EntityManagerFactory
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("helloworld");
// First unit of work
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
Message message = new Message("Hello World");
em.persist(message);
tx.commit();
em.close();
// Second unit of work
EntityManager newEm = emf.createEntityManager();
EntityTransaction newTx = newEm.getTransaction();
newTx.begin();
List messages = newEm
.createQuery("select m from Message m
➥ order by m.text asc")
.getResultList();

System.out.println( messages.size() + " message(s) found" );
for (Object m : messages) {
Message loadedMsg = (Message) m;
System.out.println(loadedMsg.getText());
}
newTx.commit();
newEm.close();
// Shutting down the application
emf.close();
}
}

persistencia y transacciones

These are your primary programming interfaces in Java Persistence:

■ javax.persistence.Persistence—A startup class that provides a static method for the creation of an EntityManagerFactory.

■ javax.persistence.EntityManagerFactory—The equivalent to a Hibernate SessionFactory. This runtime object represents a particular persistence unit. It’s thread-safe, is usually handled as a singleton, and provides methods for the creation of EntityManager instances.

■ javax.persistence.EntityManager—The equivalent to a Hibernate Session. This single-threaded, nonshared object represents a particular unit of work for data access. It provides methods to manage the lifecycle of entity instances and to create Query instances.

■ javax.persistence.Query—This is the equivalent to a Hibernate Query.
An object is a particular JPA query language or native SQL query representation, and it allows safe binding of parameters and provides various methods for the execution of the query.

javax.persistence.EntityTransaction—This is the equivalent to a Hibernate Transaction, used in Java SE environments for the demarcation of RESOURCE_LOCAL transactions. In Java EE, you rely on the standardized javax.transaction.UserTransaction interface of JTA for programmatic transaction demarcation.

persistencia y transacciones

otra forma de establecer los boundaries de la transacción:


package hello;
import java.util.*;
import org.hibernate.*;
import persistence.*;
public class HelloWorld {
public static void main(String[] args) {
// First unit of work
Session session =
HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Message message = new Message("Hello World");
Long msgId = (Long) session.save(message);
tx.commit();
session.close();
// Second unit of work
Session newSession =
HibernateUtil.getSessionFactory().openSession();
Transaction newTransaction = newSession.beginTransaction();
List messages =
newSession.createQuery("from Message m order by
➥ m.text asc").list();
System.out.println( messages.size() +
" message(s) found:" );
for ( Iterator iter = messages.iterator();
iter.hasNext(); ) {
Message loadedMsg = (Message) iter.next();
System.out.println( loadedMsg.getText() );
}
newTransaction.commit();
newSession.close();
// Shutting down the application
HibernateUtil.shutdown();
}
}


sacado del chapter2.pdf del libro de hibernate (pag.47)

Test: trucos para acceder a recursos en los test

(sacado del ejemplo de hibernate caveatemptor-jpa-061211)

testsuite-integration-ejb3.xml:
<!-- DBUnit needs a database connection -->
<parameter name="jndi_datasource" value="java:/caveatemptorTestingDatasource">

<!-- How do we get an EntityManagerFactory from JNDI in tests? -->
<parameter name="jndi_name_emf" value="java:/EntityManagerFactories/caveatEmptorEMF">

<!-- How do we get a JTA UserTransaction from JNDI in tests? -->
<parameter name="jndi_name_usertx" value="UserTransaction">

HIBERNATE: Para que solamente detecte las anotaciones

En el persistence.xml:

<!-- Only scan and detect annotated entities -->
<property name="hibernate.archive.autodetection" value="class">


(sacado del ejemplo de hibernate caveatemptor)

18 octubre 2009

Hibernate - Cascade recommendations

Recommendations:

  • It doesn't usually make sense to enable cascade on a @ManyToOne or @ManyToMany association. Cascade is often useful for @OneToOne and @OneToMany associations.

  • If the child object's lifespan is bounded by the lifespan of the parent object, make the parent a full lifecycle object by specifying CascadeType.ALL and org.hibernate.annotations.CascadeType.DELETE_ORPHAN (please refer to the Hibernate reference guide for the semantics of orphan delete)

  • Otherwise, you might not need cascade at all. But if you think that you will often be working with the parent and children together in the same transaction, and you want to save yourself some typing, consider using cascade={PERSIST, MERGE}. These options can even make sense for a many-to-many association.

Hibernate - Query Hints

3.4.1.7. Query hints


Query hints (for performance optimization, usually) are implementation specific. Hints are declared using the query.setHint(String name, Object value) method, or through the @Named(Native)Query(hints) annotation Note that these are not SQL query hints! The Hibernate EJB3 implementation offers the following query hints:

Table 3.1. Hibernate query hints

HintDescription
org.hibernate.timeoutQuery timeout in seconds ( eg. new Integer(10) )
org.hibernate.fetchSizeNumber of rows fetched by the JDBC driver per roundtrip ( eg. new Integer(50) )
org.hibernate.commentAdd a comment to the SQL query, useful for the DBA ( e.g. new String("fetch all orders in 1 statement") )
org.hibernate.cacheableWhether or not a query is cacheable ( eg. new Boolean(true) ), defaults to false
org.hibernate.cacheModeOverride the cache mode for this query ( eg. CacheMode.REFRESH )
org.hibernate.cacheRegionCache region of this query ( eg. new String("regionName") )
org.hibernate.readOnlyEntities retrieved by this query will be loaded in a read-only mode where Hibernate will never dirty-check them or make changes persistent ( eg. new Boolean(true) ), default to false
org.hibernate.flushModeFlush mode used for this query
org.hibernate.cacheModeCache mode used for this query

The value object accept both the native type or its string equivalent (eg. CaheMode.REFRESH or “REFRESH”). Please refer to the Hibernate reference documentation for more information.

27 septiembre 2009

Deploying custom resources

creamos un nuevo action:

public void action1_(){
ResourceBundle bundle = SeamResourceBundle.getBundle();
String sql = bundle.getString("sql1");

log.info("sql: " + sql);
statusMessages.add("sql: " + sql);
}

y ponemos el sql.properties en el directorio src/hot:

sql1=select h from Hotel h where h.name like '%#{exampleHotel.name}%'







from http://seamframework.org/Community/IncludingAResourceBundleNotCalledMessages


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




from seam reference 2.1.1-GA.pdf


29.10. Deploying custom resources (externalizar SQL's)


Se trata de crear un componente que se cargue en el arranque de la aplicación, y contenga un set de properties con las sql's de la aplicación, y que se pueda desplegar en caliente por si se actualiza el fichero de properties.

21 septiembre 2009

24.2.1. Using the Hibernate API

24.2.1. Using the Hibernate API

To use the Hibernate API to manage the database objects, we inject a Hibernate Session in-
stead of an EntityManager into the ManagerPojo class. The API methods in the Hibernate
Session is roughly equivalent to methods in the EntityManager; they have only slightly dif-
ferent method names. This is the Hibernate version of the ManagerPojo class:

@Name("manager")
@Scope (APPLICATION)
public class ManagerPojo {
@In (required=false) @Out (required=false)
private Person person;
@In (create=true)
private Session helloSession;
Long pid;
@DataModel
private List fans;
@DataModelSelection
private Person selectedFan;
public String sayHello () {
helloSession.save (person);
return "fans";
}
@Factory("fans")
public void findFans () {
fans = helloSession.createQuery(
"select p from Person p")
.list();
}
public void setPid (Long pid) {
this.pid = pid;
if (pid != null) {
person = (Person)
helloSession.get(Person.class, pid);
} else {
person = new Person ();
}
}
public Long getPid () {
return pid;
}
public String delete () {
Person toDelete =
(Person) helloSession.merge (selectedFan);
helloSession.delete( toDelete );
findFans ();
return null;
}
public String update () {
return "fans";
}
}

Display Error Messages on the Web Form

10.4. Display Error Messages on the Web Form



s:decorate>
f:facet name="beforeInvalidField">
h:graphicimage src="anotherError.gif">
/h:graphicimage>
f:facet name="afterInvalidField">
s:message styleclass="anotherError">
/s:message>
f:facet name="aroundInvalidField">
s:span styleclass="error">
/s:span>
h:inputtext value="#{person.name}">
/h:inputtext>/f:facet>/f:facet>/f:facet>/s:decorate>

exception management in pages.xml

14.4., “Use pages.xml for System
Exceptions”



from booking example:



pages.xml


You must be logged in to use this feature





Session expired, please log in again

Annotate exceptios

From the book 'JBoss Seam Simplicity and Power Beyond Java EE':

14.3 Annotate Exceptions

@ApplicationException(rollback=true)
@Redirect(viewId="/inventoryError.xhtml")
public class InventoryException
extends Exception {
public InventoryException () { }
}
14.4. Use pages.xml for System Exceptions

SVN hooks for hudson builds

En el directorio hooks del repositorio renombramos/copiamos post-commit.bat (o .exe)

en el fichero post-commit.bat escribimos:

python C:\svnrepos\notify_hudson.py




escribir este script en un fichero llamado notify_hudson.py:


import urllib, urllib2, time

url = 'http://localhost:8080/hudson/job/seam4hudson/build?token=build&cause=svncommit+texto'

values = {'token' : 'build', #write ur specific key/value pair
'key2' : 'value2',
'key3' : 'value3',
}

try:
# data = urllib.urlencode(values)
req = urllib2.Request(url)
response = urllib2.urlopen(req)
the_page = response.read()
print the_page
except Exception, detail:
print "Err ", detail




script sacado de http://love-python.blogspot.com/2008/04/get-content-html-source-of-url-by-http.html

24 julio 2009

maven release version plugin

Para modificar las versiones de los pom.xml y sus hijos:

=======

http://stackoverflow.com/questions/415764/hierarchy-of-maven-projects-without-scattering-the-version-number
I think this approach can be complemented with Maven version plug-in: mojo.codehaus.org/versions-maven-plugin It can increment the parent.version tag in child projects automatically; see versions:update-child-modules goal. – Dan May 13 at 16:38


=======

Versions Maven Plugin




=======

Maven Release Plugin


=======

09 julio 2009

Taylor 1.3.0 - Writing Custom Generators


Writing Custom Generators

From Taylor

Taylor MDA comes with a set of code generation templates. But you may want to write your own templates for any number of reasons:

  • You want to use a different language: Ruby, PHP, .Net, etc
  • You want to use a different framework: Seam vs Spring, JSF vs GWT, etc
  • You simply want the code to generate different
  • Etc...

If you just want to fix a bug you can override a template: Customize Code Templates

The following outlines how to create your own code generator plugin. These are sometime called cartridges.

Contents

[hide]

Plugin Basics

For starters, code generators are just Eclipse plugins, so here is a good primer:

Create Plugin

  1. Start by creating a basic plugin project.
    1. Copy net.taylor.mda.samplegen to get a jump start.
  2. Modify the MANIFEST.MF to match the project name, package and version.
  3. Modify the PLUGIN_ID in the GeneratorPlugin class.
  4. Build the plugin

Here is the basic layout of a plugin:

  • project
    • src
      • net.taylor.mda.mygen.GeneratorPlugin
      • net.taylor.mda.generator.template.*
    • templates
      • main
        • java
        • resources
      • maven
      • test
        • java
        • resources
      • Header.jetinc
    • META-INF
      • MANIFEST.MF
    • plugin.xml
    • build.properties
    • .jetproperties
    • .classpath
    • .project

NOTE: By convention the template directory mimics the structure of the generated code. For example, src/main/java, src/main/resources, src/test/java, src/test/resources

Create Template

If you are new to JET, you will want to review and refer back to these tutorials:

The sample generator plugin contains a sample template.

Use the JET editor (included with taylor) to test the sample template

  • You will need to register it with *.*jet extensions

Here are the highlights of a template:

  • Name template files with an informational extensions such as: *.javajet, *.xmljet, *.xhtmljet
  • The first line of the template defines the class name and the imports.
  • The second line defines the type of UML element that is passed as an argument to the template.
<%@ jet package="net.taylor.mda.generator.template.main.java.sample" class="SampleGen"
imports="org.eclipse.uml2.uml.* java.util.* net.taylor.mda.generator.util.* org.eclipse.emf.codegen.util.*"
%>
<%Model uml2Package = (Model) argument;%>
  • This code handles formatting imports for java code. Imports are adding implicitly based on the UML model. Framework imports are added explicitly as shown below.
<%ImportManager importManager=null;%>
<%if (NameHelper.getQualifiedName(uml2Package) != null) {%>
<%importManager = ImportHelper.makeImportManager(NameHelper.getQualifiedName(uml2Package));%>
<%} else {%>
<%importManager = ImportHelper.makeImportManager("");%>
<%}%>
<%importManager.addImport("java.io.Serializable");%>
<%importManager.addImport("org.jboss.seam.ScopeType");%>
<%importManager.addImport("org.jboss.seam.annotations.Logger");%>
<%importManager.addImport("org.jboss.seam.annotations.Name");%>
<%importManager.addImport("org.jboss.seam.annotations.Observer");%>
<%importManager.addImport("org.jboss.seam.annotations.Scope");%>
<%importManager.addImport("org.jboss.seam.log.Log");%>

<%
StringBuffer importStringBuffer = stringBuffer;
int importInsertionPoint = stringBuffer.length();
importManager.addCompilationUnitImports(stringBuffer.toString());
%>

...

<%importStringBuffer.insert(importInsertionPoint, importManager.computeSortedImports());%>

  • This block shows an example of generating java code.
  • Various helper classes are available in package net.taylor.mda.generator.util.
<%@ include file="../../Header.jetinc"%>
package <%=NameHelper.getQualifiedName(uml2Package)%>;

...

/**
* <%=TypeHelper.getDocumentation(uml2Package)%>
*
* @author <%=System.getProperty("user.name")%>
* @generated
*/
@Name("<%=NameHelper.getUncapName(uml2Package)%>Init")
@Scope(ScopeType.APPLICATION)
public class <%=NameHelper.getCapName(uml2Package)%>Init implements Serializable {

/** @generated */
@Logger
private Log log;

/** @generated */
@Observer("org.jboss.seam.postInitialization")
public void init() throws Exception {
log.info("Starting <%=NameHelper.getCapName(uml2Package)%>Init...");
}
}

Register Template

This is the part that is uniquely Taylor.

Each template is registered in its plugin.xml file using the template extension point. The engine in the Generator plugin uses these extensions to determine which templates to execute and how to render the menus.

                  id="EntityClass"
path="/main/java/entity/EntityClass.javajet"
outputPattern="/src/main/java/{0}/{1}.java"
ifExists="merge"
projectSuffix="jpa"
hasStereotype="javax.persistence.Entity"
modelElement="org.eclipse.uml2.uml.internal.impl.ClassImpl">


  • id - a unique name that will be used to reference this template
  • path - the relative location and name of the template
  • modelElement - what UML type does the template apply to
  • hasStereotype - further restrict matches based on an applied stereotype
  • outputPattern - describes the generated file name and path with substitutions
    • {0} - path based on UML Package
    • {1} - name of UML element
    • {2} - name of parent UML element
    • {3} - fully qualified UML element name with '::' replaced with '-'
    • {4} - lower case model name with '_' replaced with '.'
    • {5} - model name with '_' replaced with '.'
  • ifExists - what to do if the file already exists: merge, skip, backup
  • projectSuffix - files are generated in project named -, a new project is created if it doesn't exist


See the existing template plugins as examples.

Test Template

We already used the JET Editor preview tab to unit test a template. Now we need to test that the template is properly registered.

  1. Run the plug-in project as an Eclipse Application from the tool bar.
  2. Create a test model
  3. Test the Generate menu to verify that you template appears (see Generate Code)
  4. Now Generate and validate the results
  • You will likely want to install the EMF and UML2 SDKs for debugging.
  • The Engine will also log exceptions to the console.
  • Plugging errors will show up in the Eclipse Error Log view.

That is basically it!

The following are some optional topics.

Profiles

Taylor comes with many profiles. However, you may want to create your own for a specific framework or specification.

If you are new to UML Profiles, you will want to review and refer back to this tutorial:

You can reverse engineer a profile from a jar that contains annotations.

  • File > Import > Taylor > Import Java Annotations to UML Profile

Package the profile in a plug-in, such as the one with the templates.

Adding the following extensions to the plugin.xml will automatically add the profile to any new models.

  
source="pathmap://MY_PROFILES/"
target="platform:/plugin/my.plugin.profiles/profiles/">




id="pathmap://MY_PROFILES/my.profile.uml"/>

See plug-in net.taylor.mda.profiles for examples.

Utility Actions

You often need to make mass changes to a model such as spinning through all the elements and adding various stereotypes. This saves time and improves consistency.

This is accomplished using the standard Eclipse action menu mechanism. Package these actions in a plugin along side your templates and profiles.

See the net.taylor.mda.jpagen plug-in for examples.

The following example shows how to register the utilities in a plugin.xml file to be applied to a particular type of UML element.

           point="org.eclipse.ui.navigator.viewer">
viewerId="net.taylor.mda.ModelNavigator">






point="org.eclipse.ui.navigator.navigatorContent">
id="net.taylor.mda.jpagen.actions.AddEnumerationAction"
class="net.taylor.mda.jpagen.actions.AddEnumerationActionExtension">







Taylor 1.3.0-building the plugins

Taylor 1.3.0

Building the plugins


Building the Plug-ins

  1. Start by creating a dedicated workspace.
  2. Then checkout the plug-ins from SVN.
  3. To build the plug-ins right-click on the net.taylor.mda project and select Export>Plug-in Development>Deployable features
  4. Specify a Destination Directory, such as C:\workspaces\build, and press Finish
  5. Copy the features and plugins directories from your build directory to your eclipse directory
  6. Restart Eclipse with the -clean option

Testing the Plug-ins

  1. Follow the steps above to checkout the plug-in projects
  2. Select the net.taylor.mda project
  3. Go to Run>Run As>Eclipse Application or Run>Debug As>Eclipse Application

Optional

  • Install the SDKs for GMF and its dependencies for debugging

01 junio 2009

estructura proyecto seam

lo mejor para el nuevo proyecto es estructurarlo como los proyectos maven2:

src-main-java
src-main-resources
src-test-java
src-test-resources

23 mayo 2009

importar proyectos taylor a eclipse

crear nuevo workspace

import -> maven projects from scm

Seleccionar el directorio padre de todos los proyectos (no el master). El plugin buscará todos los pom.xml en los subdiretorios y creará los proyectos

por ejemplo para el proyecto taylor-tracker-1.2.0:

http://taylor.svn.sourceforge.net/svnroot/taylor/applications/branches/taylor-tracker-1.2.0

Generar DDL con maven2

En el proyecto de taylor-tracker que viene en el fichero taylor-tracker-jboss-bundle-1.2.0.zip, en la carpeta:

jboss-4.2.0.GA\server\all\deploy\taylor-tracker-app-1.2.0.ear\taylor-tracker-jpa-1.2.0.jar\META-INF\maven\taylor-tracker\taylor-tracker-jpa

está el pom.xml del artefacto. En este fichero hay un comentario que nos puede servir para facilitar la generación de la DDL a partir del proyecto jpa generado por el modelo:



create the hbm2ddl.properties file with your dialect:
hibernate.dialect=org.hibernate.dialect.Oracle9Dialect

el fichero hay que crearlo en src/test/resources/hbm2ddl.properties


generará el fichero en hibernate3/sql/schema.sql

then run: mvn hibernate3:hbm2ddl


19 mayo 2009

another UML tool

UML tool

http://topcased-mm.gforge.enseeiht.fr/website/modeling/uml/index.html

updatesite: http://topcased-mm.gforge.enseeiht.fr/release/update-site

puntos interesantes en seam_reference-2.1.2.CR1.pdf

Sets the character encoding of submitted form data.

This filter is not installed by default and requires an entry in components.xml to enable it:


<web:character-encoding-filter encoding="UTF-16" override-client="true" url-pattern="*.seam"/>




Transactions

Finally, let's talk about transactions. In an EJB3 environment, we recommend the use of a special built-in component for transaction management, that is fully aware of container transactions, and can correctly process transaction success events registered with the Events component. If you don't add this line to your components.xml file, Seam won't know when container-managed transactions end:

<transaction:ejb-transaction/>





20 abril 2009

persistence unit

Packaging

EJB3 JPA is standardizing POJO persistence. Thus, entities aren't limited to EJB modules; they can be packaged in a Web module, ejb-jar module, library module in the EAR level, or a standard jar file. You can also use entities in Java SE. You must package a descriptor (persistence.xml), like the following, in the archive that contain entities:



oracle.toplink.essentials.PersistenceProvider
jdbc/OracleDS
...

This descriptor identifies the persistence provider, persistent units, and the data source used by a persistent unit. As the name suggests, a persistent unit is a collection of entities that are managed together. If you have a single persistent unit defined in a specific module, you don't have to identify the entity classes in the persistence.xml; it will be dynamically discovered by the persistence provider.

persist an entity (Serializable) on application-managed entity manager

from Standardizing Java Persistence with the EJB3 Java Persistence API

If you persist an entity, any state changes to associated entities will be persisted as well if CascadeType for the relationship is set to PERSIST or ALL. Unless you're using an extended persistent context, the entities will become detached after the end of the transaction. The merge operation lets you merge a detached entity instance with the persistent context; the state of a detached entity will be synchronized with the database. This helps you get rid of the Data Transfer Object (DTO) anti-pattern prevalent in EJB 2.x because entities, being POJOs, can be transferred between tiers. The only requirement is that the entity class must implement the java.io.Serializable interface.

Extending the Hibernate Validation Framework for Complex Rules

Extending the Hibernate Validation Framework for Complex Rules


go

The Hibernate Validation Framework leverages annotations to define data validation rules on entity beans. Out of the box it comes with many useful annotations for defining simple validation rules such as, NotNull, Min, Max, etc... However, for complex rules that involve multiple properties you will have to write your own validators. This posting shows two approaches to make this easier by using expression language and custom code fragments.

Simple Validations


Here is an example of a simple validation. The annotation on the amount property is scoped just to that property. Thus only simple rules can be defined.

@Entity
public class Loan {
@NotNull(message="The Amount must be provided.")
private Double amount;
...
}

Complex Validation


Here is an example of a complex validation. The annotation on the class is scoped to the whole class. Thus complex rules can be defined that involve any property in the class.

@Entity
@StartDateBeforeEndDate(message="The start date must be before the end date.")
public class Loan {
private Date startDate;
private Date endDate;
...
}

These features pretty much cover all the various validation requirements. However, defining complex validation rules requires writing both a custom annotation and a custom validator for each rule, which can become very cumbersome. Here are two ways around this issue.

Expression Language Validator


By using expression language we can write a generic validator that can be reused for various rules. The generic Expression annotation is used to define the rule.


@Entity
@Expression(value="value.startDate <>", message="The start date must be before the end date.")
public class Loan {
private Date startDate;
private Date endDate;
...
}

The ExpressionValidator class uses the commons-jexl library to evaluate the expression. The value variable in the expression equals the instance of the object being validated. In this case value is a loan.

public class ExpressionValidator implements Validator {
private String expression;
public void initialize(Expression expression) {
this.expression = expression.value();
}

public boolean isValid(Object value) {
org.apache.commons.jexl.Expression e = ExpressionFactory.createExpression(expression);
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("value", value);
return (Boolean) e.evaluate(jc);
}
}

Custom Assertion Validator


There are times when you will just have to write custom validation code. But instead of writing a custom annotation and validator class it would be nice to encapsulate the rules in the same class for which the rules apply. This generic Assertion annotation and IAssertion interface do the trick.

@Entity
@Assertion(value=Loan.StartDateBeforeEndDateAssertion.class, message="The start date must be before the end date.")
public class Loan {
private Date startDate;
private Date endDate;
...
public static class StartDateBeforeEndDateAssertion implements IAssertion
{
public boolean isValid(Object value) {
Loan loan = (Loan) value;
return
loan.getStartDate().before(loan.getEndDate());
}
}
}

The AssertionValidator class will create an instance of the IAssertion and execute it against the object being validated.

public class AssertionValidator implements Validator {
private IAssertion assertion;
public void initialize(Assertion assertion) {
this.assertion = (IAssertion) assertion.value().newInstance();
}

public boolean isValid(Object value) {
return assertion.isValid(value);
}
}

Hopefully the expression appoach will satisfy all your needs and you wont need this custom code approach. For example, you could add an isStartDateBeforeEndDate() method to your entity and call it in a simple expression as show below. But the custom code approach is here just in case.

@Entity
@Expression(value="value.startDateBeforeEndDate", message="The start date must be before the end date.")
public class Loan {
...
public boolean isStartDateBeforeEndDate() {
return startDate.before(endDate);
}
}

Multiple Rules


There is still another piece to this puzzle. We need to be able to apply multiple expressions or assertions. To do this we need a container annotation.

@Entity
@Expressions ({
@Expression(value="value.startDate <>", message="..."),
@Expression(value="...", message="...")
})
public class Loan {
private Date startDate;
private Date endDate;
...
}

Note that this capability relies on a requested Hibernate enhancement. You can vote for this enhancement here: JIRA Issue ANN-513. Or you can apply the patch yourself.

Resources