martes, 1 de mayo de 2012

Jasper en jsf, parte 2. La leyenda continua!


Siguiendo con el post:
http://emanuelpeg.blogspot.com.ar/2012/04/jasper-en-jsf.html

Ahora vamos a crear objetos que representen a los reportes y sus parámetros. Luego hacemos una pagina donde se pueda elegir el reporte,completar los parámetros e imprimir.
Clase reporte:

import java.util.ArrayList;
import java.util.List;

/**
 * @author emanuel
 *
 */
public class Report {
 
 private Long id;
 
 private String nombre;
 
 private List parameters = new ArrayList();
 
 private String fileName;
 
 private String urlConnection;
 
 private String driver;

 public Report() {
 }

 public Report(Long id, String nombre, List parameters,
   String fileName, String urlConnection, String driver) {
  super();
  this.id = id;
  this.nombre = nombre;
  this.parameters = parameters;
  this.fileName = fileName;
  this.urlConnection = urlConnection;
  this.driver = driver;
 }

 //Getters and setters
 
}


Clase Parametro
package org.assembly.tyr.reports.model;

/**
 * @author emanuel
 *
 */
public class Parameter {
 
 private String nombre;
 
 private Type type;
 
 private Object value;
 
 public Parameter(String nombre, Type type) {
  super();
  this.nombre = nombre;
  this.type = type;
 }

 //Getters and setters
}


El enum type
public enum Type {
 
 STRING, NUMBER, DATE

}

Ahora hago un dao, no quiero usar la base de datos por lo tanto hago un mapa, ustedes usen la base de datos.

package org.assembly.tyr.reports.dao;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.assembly.tyr.reports.model.Parameter;
import org.assembly.tyr.reports.model.Report;
import org.assembly.tyr.reports.model.Type;

/**
 * @author emanuel
 *
 */
public class ReportDao {
 
 private Map reports = new HashMap();
 
 public ReportDao() {
  List parameter1 = new ArrayList();
  Report report1 = new Report(1l,"hola1", parameter1, "/resources/reports/reporte.jasper",    
                                             "jdbc:mysql://localhost:3306/holaMundo?user=root&password=", 
                                             "com.mysql.jdbc.Driver");
  reports.put(1l, report1);
  
  List parameter2 = Arrays.asList(new Parameter("prueba1", Type.NUMBER), 
                      new Parameter("prueba2", Type.STRING), 
                      new Parameter("prueba3", Type.DATE));
  Report report2 = new Report(2l,"hola2", parameter2, 
                         "/resources/reports/reporte2.jasper", 
                         "jdbc:mysql://localhost:3306/holaMundo?user=root&password=", 
                         "com.mysql.jdbc.Driver");
  reports.put(2l, report2);
 }
 
 public Collection getAll() {
  return reports.values();
 }
 
 public Report get(Long id) {
  return reports.get(id);
 }

}


Ahora agrego en el face-config.xml el controller.

  
  reportGenerator
  org.assembly.tyr.reports.ui.ReportGeneratorController
  session
 

Agrego la pagina


    Report


    
    

Report


y modifico el controller

package org.assembly.tyr.reports.ui;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperRunManager;

import org.assembly.tyr.reports.dao.ReportDao;
import org.assembly.tyr.reports.model.Parameter;
import org.assembly.tyr.reports.model.Report;

public class ReportGeneratorController {
 
 private ReportDao reportDao = new ReportDao();
 private Long reportId;
 private List parameters;
 private Map parameterValues = new HashMap();
 
 public List getReportList() {
  List result = new ArrayList();
  Collection reports = reportDao.getAll();
  for (Report report : reports) {
   SelectItem item = new SelectItem(report.getId(), report.getNombre());
   result.add(item);
  }
  return result;
 }
 
 public Long getReportId() {
  return reportId;
 }

 public void setReportId(Long reportId) {
  this.reportId = reportId;
 }

 public List getParameters() {
  if ( reportId!= null) {
   Report report = this.reportDao.get(reportId);
   parameters = report.getParameters();
  }
  return parameters;
 }

 public void setParameters(List parameters) {
  this.parameters = parameters;
 }
 
 public Map getParameterValues() {
  return parameterValues;
 }

 public void setParameterValues(Map parameterValues) {
  this.parameterValues = parameterValues;
 }
 
 public Object getParameterValue(String key) {
  return this.parameterValues.get(key);
 }

 public String generateReportSubmit()
   throws ClassNotFoundException, SQLException, IOException,
   JRException {
  Connection connection;
  
  if (parameters != null) {
   for (Parameter parameter: parameters) {
    parameterValues.put(parameter.getNombre(), parameter.getValue());
   }
  }
  
  Report report = this.reportDao.get(reportId);
  
  //Buscamos el contexto de jsf
  FacesContext facesContext = FacesContext.getCurrentInstance();
  HttpServletResponse response = (HttpServletResponse) facesContext
    .getExternalContext().getResponse();
  //Con el contexto buscamos el jasper
  InputStream reportStream = facesContext.getExternalContext()
    .getResourceAsStream(report.getFileName());
  ServletOutputStream servletOutputStream = response.getOutputStream();
  
  //Nos conectamos a la base de datos (creamos una coneccion)
  Class.forName(report.getDriver());
  connection = DriverManager
     .getConnection(report.getUrlConnection());
  facesContext.responseComplete();
  //seteamos el contentType
  response.setContentType("application/pdf");
  
  //ejecutamos el reporte
  JasperRunManager.runReportToPdfStream(reportStream,
    servletOutputStream, this.parameterValues, connection);
  // Cerramos la coneccion a la Base
  connection.close();
  // flush y close del reporte
  servletOutputStream.flush();
  servletOutputStream.close();
  return null;
 }
 
}


Para ver el codigo:
https://code.google.com/p/jaspertyr