24 enero 2009

Extending the Hibernate Validation Framework for Complex Rules

Extending the Hibernate Validation Framework for Complex Rules

Posted by jgilbert01 under Components
[8] Comments

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

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



Test Driven Modeling

Gilbert's Blog : Weblog

The key to successful agile model driven development is to follow test driven methods.

When you think about it, where is the majority of the effort expended when doing model driven development?
  • The bulk of code is generated from the model.
  • The test script skeletons are also generated from the model.
  • The test script execution is automated.

So, the majority of effort is spent doing modeling.

Test driven methods show that the best way to derive the requirements is to start by creating the test cases. These are concrete examples that are very easy to digest, as apposed to the more abstract use cases. I'm sure we have all had the experience, when reviewing use cases, where some one says, "I'm not really getting it, can you give me an example?". So why not focus on the examples?

Here is how test driven modeling flows with Taylor MDA and Taylor Results.
  1. Start your analysis with a context diagram with actors
  2. Model some high level business use cases (diagrams only)
  3. Identify different scenarios and divide them into test cases
  4. Elaborate the test cases in outline form using wiki text
  5. Model the elements/requirements that you discover along the way
  6. Generate the code and scripts
  7. Evolve the test case outlines into executable scripts by adding the wiki tables
  8. Customize the code where necessary to satisfy the test cases
  9. Check everything in and let your continuous integration build server execute the tests
  10. Iterate!!!
As you can see, test driven modeling reduces duplicate effort by moving test creation to the forefront where they can be used to drive the creation of the model as they evolve from outline form to executable scripts. The result is a high quality application that evolves just-in-time as the tests evolve.

And don't forget to put the working software in the hands of the customer along the way!

How to make JBoss Seam work with Eclipse (for Windows) « Techieexchange’s Techblog

How to make JBoss Seam work with Eclipse (for Windows) « Techieexchange’s Techblog

23 enero 2009

eclipse Omondo

JBoss Seam support New

eclipse interesting plugins

Other Tools

Plugins

Servers

Other

Taylor's model driven architecture

"Stereotype".equals("Annotation")

Java Annotations are one of the most controversial new features of Java 5. However, they are very powerful when combined with a Model Driven Architecture. In fact Java 5 Annotations are exactly equal to UML Stereotypes. Stereotypes are the UML approach for extending the UML language. Stereotypes have all the same features as annotations:

  • They have a name.
  • They specify which components they can be applied to: class, field, method, etc..
  • They can have attritbutes.
  • Those attributes can be arbitrarily complex.

Stereotypes are then grouped into profiles that can be applied to a model. Taylor comes with several profiles that correspond to the standard Java annotations:

  • EJB3 - for defining Session Beans
  • JPA - for defining Entity Beans
  • JWS - for flagging Session Beans to be exposed as Web Services
  • Types - a platform independent set of basic types

These profiles are automatically applied when a Taylor model is created. Many stereotypes are automatically applied when dragging components to a canvas, while others are applied on demand through the navigator. The defaults of the stereotypes also match the defaults of the annotations to comply with the configuration-by-exception approach of EJB3. On the screen shots page you can see the stereotypes in the Navigator and in the Properties view. The label of each node shows the applied stereotypes (e.g. <>). Stereotype attributes are set via the Properties view. The stereotypes are then generated verbatim into the source code as Java 5 Annotations. Hence the Power of Annotations in an MDA.

Experience Model Driven Development with Taylor MDA 1.2.0 | Eclipse Zone

Experience Model Driven Development with Taylor MDA 1.2.0 | Eclipse Zone


Taylor consists of a set of Eclipse plugins for simplified UML modeling and the generation of JEE code such as: EJB3 entity and session beans, JSF with Seam and Facelets, and JMS-based business processes. It leverages many other open-source tools instead of reinventing the wheel. Read more about the Architecture.

The Taylor team is pleased to announce the release of Taylor MDA 1.2.0. Here are some of the improvements:

  • Switched from generating Portlet Apps to generating Web Apps
  • Advanced Search Filters and Saved Filters
  • Seam Theme support
  • Seam Excel support
  • Data XML Import/Export
  • User, Group and Profile Maintenance
  • Upgrade of Seam and Richfaces libraries
  • Eclipse 3.4 compatibility
  • Various fixes and improvements

Ejemplo de generar código Java y DDL con HiberObjects

Probar el ejemplo de HiberObjects

HiberObjects - UML for Hibernate

HiberObjects - UML for Hibernate


HiberObjects

HiberObjects is a UML tool for programmers, especially suited for Hibernate, JPA, GWT and Grails.

We want to use UML in an agile way, following these principles:

  • Don't try to model everything; use UML for what it does best. HiberObjects focuses on the domain model.
  • Design a little, code a little, test a little. HiberObjects is an Eclipse plugin, so you can design, implement and unit test in the same environment.
  • Don't repeat yourself! Generate code from the diagrams, don't design and then implement the same thing manually.
  • Simplify documentation. Diagrams that are used to generate code will always be correct.
  • Improve communication. Diagrams can be a good help to give an overview of the code.
  • Simplify unit testing. Use object diagrams to initialize objects.

HiberObjects supports UML class diagrams, sequence diagrams and object diagrams. It can generate code for Java Persistence API (JPA) or Hibernate classes and DAO's, GWT services and unit tests.

The generated JPA classes can be used as the model in a Grails application.

PropertyChange support and DTO's for Google Web Toolkit (GWT) can also be generated.

Database development with HiberObjects « Techieexchange’s Techblog

Database development with HiberObjects « Techieexchange’s Techblog

There are a lot of UML and ER tools out there, but they cost a lot of money, too.
This is a step-by-step to develop your database with Eclipse and HiberObjects for free.
It is a fast way for Java developers to develop database tables.
It uses an UML-ER Model to generate JavaBeans, which can create tables on the database by using Hibernate as persistence manager.

How to make JBoss Seam work with Eclipse (for Windows) « Techieexchange’s Techblog

How to make JBoss Seam work with Eclipse (for Windows) « Techieexchange’s Techblog

How to make JBoss Seam work with Eclipse (for Windows)


This is a step-by-step tutorial. I made this Tutorial, because I was not happy with the four project folders generated by JBoss Tools 2.0.0 when I select a new Seam EAR project. The work is a bit confusing. If I create a new Seam WAR project I only get two projects (one of them is a test project). I had a lot of trouble with the WAR project. I was not able to not get the EJB3 examples work with it. Never the less the folder structure is different from the Seam-gen generated projects. This tutorial works completely without JBoss Tool. You can use JBoss Tools anyway, it has nice functions do build a RichFaces JSF page, but keep in mind that new generated projects are difficult to handle, since you have to keep an overview of all four projects and the changes you made in each of them.


How to make JBoss Seam work with Eclipse (for Windows) « Techieexchange’s Techblog

How to make JBoss Seam work with Eclipse (for Windows) « Techieexchange’s Techblog

3 | Max
February 4th, 2008 at 7:11 pm

The 2 additional projects for EAR serves multiple purposes:

Eclipse WTP wants it like that for their tooling to work

Without it the classpath would not be correct when running tests, code completion etc.

there are both plus and minuses…I should write about them at some point ,)

btw. jbosstools also works with seam-gen’ed projects (at least the code gen option) - we are working on having the wizards and other parts working on non-wtp projects like seamgen for upcoming versions.

Seam Framework - Web Beans Overview

Seam Framework - Web Beans Overview

Seam localized message bundles

Storing your messages in a database



Java 6 provides enhanced ResourceBundle support

Seam has great i8ln - it provides a built in locale selector which it uses to provide localized message bundles. You can load different message bundles for different pages.

Seam's built in message bundle uses properties files to define the resources - but what if you want to store your messages in a database? You might want to allow an admin to edit the properties through a web admin panel for example. Here we will cover the basic entities and wiring needed - you will probably want to add in some CRUD views for the resources.

Entities

We create two entites, first a resource bundle entity, which defines the bundle name, and the locale which it is for:

@Entity
public class ResourceBundle {

@Id @GeneratedValue
private Integer id;

private String name;

private ResourceLocale resourceLocale;

@OneToMany(mappedBy="resourceBundle")
¨¨private List resources;
}



Marcadores sociales - Wikipedia, la enciclopedia libre

Marcadores sociales - Wikipedia, la enciclopedia libre

In Relation To...  ACL Security in Seam

In Relation To... ACL Security in Seam

17 enero 2009

jasperReports + Seam: información en el forum del seamframework

http://www.seamframework.org/search_d.seam?query=jasper


Para llamar al servlet desde un xhtml (sacado de esta página):







jasperReports webapp sample

Mirar los ejemplos del jasperreports-3.1.3-project. En especial hay uno llamado webapp con un servlet que nos viene genial.




package servlets;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JRRuntimeException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.j2ee.servlets.ImageServlet;
import datasource.WebappDataSource;


/**
* @author Teodor Danciu (teodord@users.sourceforge.net)
* @version $Id: HtmlServlet.java 1236 2006-04-22 07:51:44Z teodord $
*/
public class HtmlServlet extends HttpServlet
{


/**
*
*/
public void service(
HttpServletRequest request,
HttpServletResponse response
) throws IOException, ServletException
{
ServletContext context = this.getServletConfig().getServletContext();

response.setContentType("text/html");
PrintWriter out = response.getWriter();

try
{
File reportFile = new File(context.getRealPath("/reports/WebappReport.jasper"));
if (!reportFile.exists())
throw new JRRuntimeException("File WebappReport.jasper not found. The report design must be compiled first.");

JasperReport jasperReport = (JasperReport)JRLoader.loadObject(reportFile.getPath());

Map parameters = new HashMap();
parameters.put("ReportTitle", "Address Report");
parameters.put("BaseDir", reportFile.getParentFile());

JasperPrint jasperPrint =
JasperFillManager.fillReport(
jasperReport,
parameters,
new WebappDataSource()
);

JRHtmlExporter exporter = new JRHtmlExporter();

request.getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint);

exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, out);
exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, "image?image=");

exporter.exportReport();
}
catch (JRException e)
{
out.println("");
out.println("");
out.println("");
out.println("");
out.println("");

out.println("");

out.println("JasperReports encountered this error :");
out.println("

");

e.printStackTrace(out);

out.println("

");

out.println("");
out.println("");
}
}


}

Respuesta: Jasper Report + iReport + NetBeans 4

código que funciona (sólo JasperReports, no JFaces no Seam)

Hola gente del foro, les cuento este es mi primer posteo....Me suscribir para pedir ayuda deseperada, pero leyendo lo subido por Uds pude crear mi reporte y utilizarlo des mi Aplicacion.... Aca les dejo el codigo que utilize si a alguno le sirve....Gracias

Query q=null;
Map params = new HashMap();
params.put("jTextField1NumEnt", this.jTextField1NumEnt.getText().toString());
try {
q = new Query();
} catch (Exception ex) {
Logger.getLogger(EntradaEnReparacion.class.getName ()).log(Level.SEVERE, null, ex);
}
try{
//Ruta de Archivo Jasper
String fileName="C:\\reports\\reportEntradaPersona.jasper ";
//Ruta de archivo pdf de destino
String destFileNamePdf="C:\\reports\\reportEntradaPersona .pdf";

//Preparacion del PDF
JasperPrint jasperPrint = null;
try {
jasperPrint = JasperFillManager.fillReport(fileName, params, q.getConection());
} catch (SQLException ex) {
Logger.getLogger(EntradaEnReparacion.class.getName ()).log(Level.SEVERE, null, ex);
GuiTools.ErrorMessage(ex.getMessage());
}
//Creación del PDF
JasperExportManager.exportReportToPdfFile(jasperPr int, destFileNamePdf);
//Edita la vista en pantalla del PDF
JasperViewer jw= new JasperViewer(jasperPrint, false);
jw.setTitle("Entrada en Reparacion: "+this.jTextField1FechaEntrda.getText());
jw.setExtendedState(0);
jw.setFocusable(true);
jw.setFocusableWindowState(true);
jw.setResizable(true);
jw.setEnabled(true);
jw.setVisible(true);
jw.setAlwaysOnTop(true);

Fiddler proxy

Fiddler

Fiddler is a HTTP Debugging Proxy which logs all HTTP traffic between your computer and the Internet. Fiddler allows you to inspect all HTTP Traffic, set breakpoints, and "fiddle" with incoming or outgoing data. Fiddler includes a powerful event-based scripting subsystem, and can be extended using any .NET language.

Fiddler is freeware and can debug traffic from virtually any application, including Internet Explorer, Mozilla Firefox, Opera, and thousands more.

16 enero 2009

Problemas com Facelets + JSF + Jasper

En esta página hay muchos links sobre jsf, seam y jasperReports.

Aunque hay que mirar las otras, la que he visto primero es:


http://www.guj.com.br/posts/list/99584.java


public static void geraPdf(JasperPrint jasperPrintSecao){
try{

//GERA PDF
// @ outputStream
ByteArrayOutputStream pdfStream = new ByteArrayOutputStream();
JasperExportManager.exportReportToPdfStream(jasperPrintSecao, pdfStream);

HttpServletResponse response
= (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=relatorio.pdf");
response.setContentLength(pdfStream.size()); //para o pdfStream


// Flush pdfStream pra response
ServletOutputStream flusher;
flusher = response.getOutputStream();
pdfStream.writeTo(flusher);
flusher.flush();
flusher.close();
FacesContext.getCurrentInstance().responseComplete();
pdfStream.close();
pdfStream = null;


}catch (Exception e) {
e.printStackTrace();
}

}





Llamada al método anterior:


List lista = new Vector();
lista = RelatorioFaturaDAOHibernate.selectDuplicata(faturaVO,
dataInicial, dataFinal);
String caminho = "relatorio_fatura.jasper";
String figura1 = "bandeira_brasil.jpg";
String figura2 = "bandeira_brasil.jpg";

Map parametros = new HashMap();
parametros.put("imagem_esquerda", getClass().getResourceAsStream(
figura1));
parametros.put("imagem_direita", getClass()
.getResourceAsStream(figura2));
try {
JasperPrint jasperPrintSecao = JasperFillManager.fillReport(
getClass().getResourceAsStream(caminho), parametros,
new JRBeanCollectionDataSource(lista));
JSFUtil.geraPdf(jasperPrintSecao);
...




javaranch - CodeBarn

No tiene sentido intentar reinventar la rueda. Si está hecho, usarlo, si se puede mejorar, mejorarlo. Si no, a quemarse la cabeza. Esta última opción es menos preferida, pero puede pasar.

The JavaRanch Codebarn - http://faq.javaranch.com/java/CodeBarn

12 enero 2009

82.158.213.5

82.158.213.5

carlos
carlosC
carlosE
faisco

07 enero 2009

Definición de reglas

Defining constraints


What is a constraint?

A constraint is a rule that a given element (field, property or bean) has to comply to. The rule semantic is expressed by an annotation. A constraint usually has some attributes used to parameterize the constraints limits. The constraint applies to the annotated element.



JBossJSFUnit

JBossJSFUnit

JSFUnit: In-container testing for JSF applications

JSFUnit is a test framework for JSF applications. It is designed to allow complete integration testing and unit testing of JSF applications using a simplified API. JSFUnit tests run inside the container, which provides the developer full access to managed beans, the FacesContext, EL Expressions, and the internal JSF component tree. At the same time, you also have access to parsed HTML output of each client request.

JSFUnit

JSFUnit


JSFUnit is a test framework for JSF applications. It is designed to allow complete integration testing and unit testing of JSF applications using a simplified API. JSFUnit tests run inside the container, which provides the developer full access to managed beans, the FacesContext, EL Expressions, and the internal JSF component tree. At the same time, you also have access to parsed HTML output of each client request.

After each faces request, you get access to the full internal state of your application through the FacesContext. With the FacesContext in hand, you have the keys to the kingdom. Between the JSF API and the JSFUnit helper classes, you can see what "really happened" after each request. You can also make additional HTTP requests to simulate a user session. And, since your application is fully deployed, you can assert state at any level of abstraction all the way from the client HTML down to your database.

The typical usage pattern of JSFUnit is to programatically submit an http request and examine both the parsed HTML output and the JSF internals. JSFUnit makes this very easy to do.