Estructura de las carpetas del proyecto con sus respectivos archivos:
│ pom.xml
│
└───src
├───main
│ ├───java
│ │
└───com
│ │
└───cpxall
│ │
│ Principal.form
│ │
│ Principal.java
│ │
│
│ │
├───conexion
│ │
│ ConexionOracle.java
│ │
│
│ │
└───util
│ │ Reportes.java
│ │ Utilidades.java
│ │
│ └───resources
│ ├───imagenes
│ │
back.png
│ │
back_f2.png
│ │
cargando.gif
│ │
cpxall.png
│ │
file.png
│ │
file_f2.png
│ │
netbeans.png
│ │
reporte.jpg
│ │
│ └───reportes
│ Mi_primer_reporte.jasper
│ Mi_primer_reporte.jrxml
│
└───test
└───java
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.toures.balon</groupId>
<artifactId>AppMiPrimerReporte</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.java.net.substance</groupId>
<artifactId>substance</artifactId>
<version>5.3</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>6.3.1</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>com.oracle.jdbc</groupId>
<artifactId>ojdbc7</artifactId>
<version>12.1.0.1.0</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.7</version>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<name>AppMiPrimerReporte</name>
</project>
Principal.java
package com.cpxall;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import com.cpxall.util.Reportes;
import com.cpxall.util.Utilidades;
import java.util.HashMap;
import java.util.Map;
import com.cpxall.conexion.ConexionOracle;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.apache.log4j.BasicConfigurator;
/**
*
* @author Administrador
*/
public class Principal extends javax.swing.JFrame implements Runnable {
private final JFileChooser guardar = new JFileChooser();
private final JFileChooser abrir = new JFileChooser();
public static final boolean ENABLELOGGING = false;
private static final Logger logger = Logger.getLogger(Principal.class.getName());
/**
* Creates new form Principal
*/
/**
* Creates new form frmPrincipal
*/
public Principal() {
abrir.addChoosableFileFilter(null);
FileNameExtensionFilter filtro = new FileNameExtensionFilter("Jrprint", "jrprint");
abrir.setFileFilter(filtro);
// guardar.setFileFilter (filtro);
BasicConfigurator.configure();
logger.info("Entrar en la aplicación");
JFrame.setDefaultLookAndFeelDecorated(true);
initComponents();
this.setLocationRelativeTo(null);
this.add(guardar);
this.add(abrir);
ImageIcon icono = new ImageIcon(this.getClass().getResource("/imagenes/cpxall.png"));
this.setIconImage(icono.getImage());
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanelFactura = new javax.swing.JPanel();
jComboBoxReportes = new javax.swing.JComboBox();
jButtonGenerar = new javax.swing.JButton();
jButtonAbrirArchivos = new javax.swing.JButton();
jCheckBoxGuardar = new javax.swing.JCheckBox();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Cpxall - Reportes v1.0");
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
setLocationByPlatform(true);
setResizable(false);
jPanelFactura.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Impresión General", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Verdana", 1, 16), new java.awt.Color(51, 51, 255))); // NOI18N
jComboBoxReportes.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Generar PDF" }));
jComboBoxReportes.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboBoxReportesItemStateChanged(evt);
}
});
jComboBoxReportes.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBoxReportesActionPerformed(evt);
}
});
jButtonGenerar.setBackground(new java.awt.Color(0, 102, 204));
jButtonGenerar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/back.png"))); // NOI18N
jButtonGenerar.setMnemonic('g');
jButtonGenerar.setText("Generar");
jButtonGenerar.setToolTipText("Generar Factura");
jButtonGenerar.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/back_f2.png"))); // NOI18N
jButtonGenerar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonGenerarActionPerformed(evt);
}
});
jButtonAbrirArchivos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/file.png"))); // NOI18N
jButtonAbrirArchivos.setMnemonic('a');
jButtonAbrirArchivos.setText("Abrir");
jButtonAbrirArchivos.setToolTipText("Abrir Jrprint");
jButtonAbrirArchivos.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/file.png"))); // NOI18N
jButtonAbrirArchivos.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/file_f2.png"))); // NOI18N
jButtonAbrirArchivos.setRolloverSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/file.png"))); // NOI18N
jButtonAbrirArchivos.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/file.png"))); // NOI18N
jButtonAbrirArchivos.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonAbrirArchivosActionPerformed(evt);
}
});
jCheckBoxGuardar.setText("Guardar Copia");
javax.swing.GroupLayout jPanelFacturaLayout = new javax.swing.GroupLayout(jPanelFactura);
jPanelFactura.setLayout(jPanelFacturaLayout);
jPanelFacturaLayout.setHorizontalGroup(
jPanelFacturaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelFacturaLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanelFacturaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jComboBoxReportes, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanelFacturaLayout.createSequentialGroup()
.addGroup(jPanelFacturaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jCheckBoxGuardar)
.addComponent(jButtonGenerar, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(56, 56, 56)
.addComponent(jButtonAbrirArchivos)))
.addGap(188, 188, 188))
);
jPanelFacturaLayout.setVerticalGroup(
jPanelFacturaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelFacturaLayout.createSequentialGroup()
.addComponent(jComboBoxReportes, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(94, 94, 94)
.addComponent(jCheckBoxGuardar)
.addGap(9, 9, 9)
.addGroup(jPanelFacturaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonGenerar, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButtonAbrirArchivos, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanelFactura, javax.swing.GroupLayout.PREFERRED_SIZE, 336, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanelFactura, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jComboBoxReportesItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBoxReportesItemStateChanged
// TODO add your handling code here:
}//GEN-LAST:event_jComboBoxReportesItemStateChanged
private void jButtonGenerarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGenerarActionPerformed
if (jCheckBoxGuardar.isSelected()) {
guardar.setSelectedFile(new File("Customer" + "-" + Utilidades.fechaDinamicaDiaMesAno()));
int selecion = 0;
selecion = guardar.showSaveDialog(this.jPanelFactura);
switch (selecion) {
case JFileChooser.APPROVE_OPTION:
Thread hilo = new Thread(this);
hilo.start();
break;
// JOptionPane.showMessageDialog(this,"Operacion Cancelada.","Informacion",JOptionPane.INFORMATION_MESSAGE);
case JFileChooser.CANCEL_OPTION:
break;
case JFileChooser.ERROR_OPTION:
JOptionPane.showMessageDialog(this, "Debe seleccionar un nombre de archivo valido.", "Error", JOptionPane.ERROR_MESSAGE);
break;
default:
break;
}
} else {
Thread hilo = new Thread(this);
hilo.start();
}
}//GEN-LAST:event_jButtonGenerarActionPerformed
private void jButtonAbrirArchivosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAbrirArchivosActionPerformed
int selecion = 0;
selecion = abrir.showOpenDialog(this.jPanelFactura);
switch (selecion) {
case JFileChooser.APPROVE_OPTION:
try {
// try {
// TODO add your handling code here:
//Reportes re= new Reportes();
// re.mostrarReporte(abrir.getSelectedFile().getAbsolutePath());
Utilidades.abrirArchivos(abrir.getSelectedFile());
// } catch (FileNotFoundException ex) {
// Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
//} catch (JRException ex) {
// }
// }
} catch (IOException ex) {
logger.log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(this, ex.toString(), "Error", JOptionPane.ERROR_MESSAGE);
} catch (Exception ex) {
logger.log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(this, ex.toString(), "Error", JOptionPane.ERROR_MESSAGE);
}
break;
case JFileChooser.CANCEL_OPTION:
JOptionPane.showMessageDialog(this, "Debe Escojer un archivo.", "Informacion", JOptionPane.INFORMATION_MESSAGE);
break;
case JFileChooser.ERROR_OPTION:
JOptionPane.showMessageDialog(this, "Debe seleccionar un nombre de archivo valido.", "Error", JOptionPane.ERROR_MESSAGE);
break;
default:
break;
}
}//GEN-LAST:event_jButtonAbrirArchivosActionPerformed
private void jComboBoxReportesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxReportesActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBoxReportesActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new Principal().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButtonAbrirArchivos;
private javax.swing.JButton jButtonGenerar;
private javax.swing.JCheckBox jCheckBoxGuardar;
private javax.swing.JComboBox jComboBoxReportes;
private javax.swing.JPanel jPanelFactura;
// End of variables declaration//GEN-END:variables
public void run() {
start();
}
public void start() {
try {
jButtonGenerar.setText("Cargando.....");
switch (jComboBoxReportes.getSelectedIndex()) {
case 0:
//Acta de Visitas Solicitudes y Quejas
jButtonGenerar.setText("Cargando.....");
Thread.sleep(1000);
if (jComboBoxReportes.getSelectedIndex() == 0) {
Reportes reporte = new Reportes();
Map<String, Object> para = new HashMap<String, Object>();
ConexionOracle.getInstancia().conectar();
if (jCheckBoxGuardar.isSelected()) {
if (!reporte.jasperReport(guardar.getSelectedFile().toString(), Principal.class.getResourceAsStream("/reportes/Mi_primer_reporte.jrxml"), para, ConexionOracle.getInstancia().getConexion())) {
JOptionPane.showMessageDialog(null, "La consulta no genero resultados.", "Informacion", JOptionPane.INFORMATION_MESSAGE);
}
} else if (!reporte.jasperReportInterno(Principal.class.getResourceAsStream("/reportes/Mi_primer_reporte.jrxml"), para, ConexionOracle.getInstancia().getConexion())) {
JOptionPane.showMessageDialog(null, "La consulta no genero resultados.", "Informacion", JOptionPane.INFORMATION_MESSAGE);
}
ConexionOracle.getInstancia().desconectar();
}
jButtonGenerar.setText("Generar");
break;
default:
break;
}
} catch (ClassNotFoundException ex) {
logger.log(Level.SEVERE, null, ex);
} catch (Exception ex) {
logger.log(Level.SEVERE, null, ex);
}
finally {
try {
jButtonGenerar.setText("Generar");
ConexionOracle.getInstancia().desconectar();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
ConexionOracle.java
package com.cpxall.conexion;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
*
* @author Cpxall
*/
public class ConexionOracle {
private Connection conexion; /// Abtrae una conexion a la base de datos
private String usuario = "JACABARCAS"; // usuario con permisos para conectarse a BD
private String password = "123456"; // contrasena del usuario que se puede conectar
private String driver = "oracle.jdbc.driver.OracleDriver"; // Clase del Driver de jConnector
private String beseDatos="jdbc:oracle:thin:@localhost:1521:xe";
private static ConexionOracle instancia;
/** Creates a new instance of BaseDao
* @return ConexionOracle*/
public static ConexionOracle getInstancia (){
if(ConexionOracle.instancia==null){
ConexionOracle.instancia=new ConexionOracle();
}
return instancia;
}
public static void main(String arg[])throws Exception{
ConexionOracle.getInstancia().conectar();
}
public void conectar()throws Exception {
if(this.getConexion()!=null){
return;
}
else if(this.getConexion() == null){
try {
Class.forName(this.getDriver()) ; // obtine una istancia de la clase Diver
// establece la conexion con el Diver jconector y este a su vez con la base de datos
this.setConexion(DriverManager.getConnection(this.getBeseDatos(), this.getUsuario(), this.getPassword()));
} catch (SQLException ex) {
throw new Exception("ERROR AL CONECTARCE CON LA BASE DE DATOS");
} catch (ClassNotFoundException ex) {
throw new Exception("ERROR EL DRIVER NO HA SIDO INSTALADO");
}
}
}
public void desconectar()throws Exception{
if(this.conexion!=null){
this.setConexion(null);
}
}
public ConexionOracle() {
}
public Connection getConexion() {
return conexion;
}
public void setConexion(Connection conexion) {
this.conexion = conexion;
}
public String getUsuario() {
return usuario;
}
public void setUsuario(String usuario) {
this.usuario = usuario;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getBeseDatos() {
return beseDatos;
}
public void setBeseDatos(String beseDatos) {
this.beseDatos = beseDatos;
}
}
Utilidades.java
package com.cpxall.util;
import java.awt.Desktop;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedList;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author Cpxall
*/
public class Utilidades {
public static String fechaDinamica() {
Calendar cal = Calendar.getInstance();
return cal.get(Calendar.SECOND) + "-" + cal.get(Calendar.MINUTE) + "-" + cal.get(Calendar.DATE) + "-" + cal.get(Calendar.MONTH) + "-" + cal.get(Calendar.YEAR);
}
public static String fechaDinamicaDiaMesAno() {
Calendar cal = Calendar.getInstance();
return cal.get(Calendar.DATE) + "-" + cal.get(Calendar.MONTH) + "-" + cal.get(Calendar.YEAR);
}
public static LinkedList<String> paginate(int numeropaginar, int paginacion, String Url) {
LinkedList<String> lista = new LinkedList<>();
if (numeropaginar % paginacion == 0) {
for (int x = 0; x < (numeropaginar / paginacion); x++) {
lista.add(Url);
}
} else {
for (int x = 0; x <= (numeropaginar / paginacion); x++) {
lista.add(Url);
}
}
return lista;
}
public static void main(String arg[]) {
String fecha = "02/16/2011";
Calendar cal = Calendar.getInstance();
cal.setLenient(false);
Date StringToDate = Utilidades.StringToDateMesDiaAno(fecha, "/");
cal.setTime(StringToDate);
//System.out.print(cal.get(Calendar.DAY_OF_MONTH));
//System.out.print( Utilidades.fechaMayor(cal));
System.out.print(cal.get(Calendar.DAY_OF_MONTH));
//System.out.print( Utilidades.isEmail("gesm..elloc@hotma.com"));
}
public static boolean prueba(String correo) {
Pattern pat = null;
Matcher mat = null;
pat = Pattern.compile("([0-9a-zA-Z]([_.])*@)$");
mat = pat.matcher(correo);
if (mat.find()) {
System.out.println("[" + mat.group() + "]");
return true;
} else {
return false;
}
}
/*valida la fecha ingresada por el usuario para ver si es valida*/
public static boolean fechaValida(String fecha) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
sdf.setLenient(false);
sdf.parse(fecha);
} catch (ParseException ex) {
return false;
}
return true;
}
/*Convierte una cadena a date con el siguiente Formato(yyyy-MM-dd)*/
public static Date StringToDate(String fecha) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
Date fechaFormato = null;
try {
sdf.setLenient(false);
fechaFormato = sdf.parse(fecha);
} catch (ParseException ex) {
}
return fechaFormato;
}
public static Date StringToDateMesDiaAno(String fecha, String clave) {
SimpleDateFormat sdf = null;
Date fechaFormato = null;
String union = null;
try {
if (clave.equals("/")) {
sdf = new SimpleDateFormat("yyyy/MM/dd", Locale.getDefault());
union = fecha.substring(6, 10) + "/" + fecha.substring(0, 2) + "/" + fecha.substring(3, 5);
} else {
sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
union = fecha.substring(6, 10) + "-" + fecha.substring(0, 2) + "-" + fecha.substring(3, 5);
}
sdf.setLenient(false);
fechaFormato = sdf.parse(union);
} catch (ParseException ex) {
}
return fechaFormato;
}
/*Convierte un Date a String con el siguiente Formato(yyyy-MM-dd)*/
public static String DateToString(Date fecha) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String fechaFormato = null;
sdf.setLenient(false);
fechaFormato = sdf.format(fecha);
return fechaFormato;
}
/*Agrega dias a una fecha*/
public static Date agregarDias(Date fecha, int dia) {
Calendar cal = new GregorianCalendar();
cal.setLenient(false);
cal.setTime(fecha);
//cal.set(cal.get(Calendar.YEAR)+ano,cal.get( Calendar.MONTH)+mes,cal.get( Calendar.DAY_OF_MONTH)+dia);
cal.add(Calendar.DAY_OF_MONTH, dia);
return cal.getTime();
}
/*Quita dias a una fecha*/
public static Date quitarDias(Date fecha, int dia) {
Calendar cal = new GregorianCalendar();
cal.setLenient(false);
cal.setTime(fecha);
cal.add(Calendar.DAY_OF_MONTH, -dia);
return cal.getTime();
}
/*Devuelve verdadero si la fecha ingresada por el usuario es mayor que la del sistema*/
public static boolean fechaMayor(Calendar fechaUsuario) {
Calendar fechaSistema = Calendar.getInstance();
if (fechaSistema.after(fechaUsuario)) {
return false;
}
return true;
}
/*Devuelve los metadatos de la base de datos con sus propiedades*/
/*convierte un date a Calendar*/
public static Calendar DateFecha(Date fecha) {
Calendar calendar = Calendar.getInstance();
calendar.setLenient(false);
calendar.setTime(fecha);
return calendar;
}
public static boolean isEmail(String correo) {
Pattern pat = null;
Matcher mat = null;
pat = Pattern.compile("^([0-9a-zA-Z]([_.w]*[0-9a-zA-Z])"
+ "*@([0-9a-zA-Z][-w]*[0-9a-zA-Z].)"
+ "+([a-zA-Z]{2,9}.)+[a-zA-Z]{2,3})$");
mat = pat.matcher(correo);
if (mat.find()) {
System.out.println("[" + mat.group() + "]");
return true;
} else {
return false;
}
}
public static boolean copiarArchivos(FileInputStream archivo, String rutaGuardar) {
try {
InputStream in = archivo;
OutputStream out = new FileOutputStream(rutaGuardar);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
return true;
} catch (Exception e) {
System.out.println(e);
}
return false;
}
public static boolean isNumeric(String cadena) {
try {
Integer.parseInt(cadena);
return true;
} catch (NumberFormatException nfe) {
return false;
}
}
public static boolean validarArchivo(String cadena) {
String input = cadena;
Pattern p = Pattern.compile("[^\\<>\\*\\?\"/]$");
Matcher m = p.matcher(input);
Pattern patron2 = Pattern.compile("[0-9A-za-z-_,]\\.{1}\\.*+[a-zA-z]{2}");
//
if (m.find()) {
m = patron2.matcher(input);
if (m.find()) {
return true;
}
}
return false;
}
//Abre un archivo cualquiera llamando al predeterminado por el sistema
public static boolean abrirArchivos(File archivo) throws IOException, Exception {
if (Utilidades.validarArchivo(archivo.getName())) {
Pattern patron2 = Pattern.compile("[0-9A-za-z-_,]\\.{1}\\.*jrprint");
Matcher m = patron2.matcher(archivo.getName());
if (m.find()) {
Reportes repor = new Reportes();
repor.mostrarReporte(archivo.getAbsolutePath());
return true;
}
if (Desktop.isDesktopSupported() == true) {
//obtengo la instancia de la clase Desktop del entorno actual
Desktop desktop = Desktop.getDesktop();
if (archivo.canExecute()) {
//ejecuto el archivo o URI
desktop.open(archivo);
} else {
//sino, lanzo una execpcion con las dos posibles causas de error
throw new Exception("No se encontro el archivo " + archivo.getAbsolutePath() + " o no cuenta con permisos para ejecutarlo");
}
} else {
//la clase no es soportada
throw new Exception("No se puede ejecutar el comando de apertura en este sistema operativo");
}
return true;
}
return false;
}
}
Reportes.java
package com.cpxall.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Connection;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.engine.util.JRSaver;
import net.sf.jasperreports.export.Exporter;
import net.sf.jasperreports.export.ExporterInput;
import net.sf.jasperreports.export.OutputStreamExporterOutput;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;
import net.sf.jasperreports.export.SimplePdfExporterConfiguration;
import net.sf.jasperreports.view.JasperViewer;
/**
*
* @author Cpxall
*/
public class Reportes implements Serializable {
private JasperReport reporte;
private FileInputStream entrada;
private JasperPrint print;
private JasperPrint jasperPrintAux;
// sirve para exportar pdf
public boolean jasperReport(String ruta, InputStream dataSourceName, Map<String, Object> params, Connection conn) throws ClassNotFoundException, JRException, FileNotFoundException, IOException {
this.reporte = JasperCompileManager.compileReport(dataSourceName);
OutputStreamExporterOutput output;
try (OutputStream out = new FileOutputStream(ruta+".pdf")) {
this.print = JasperFillManager.fillReport(this.reporte, params, conn);
if (this.print.getPages().isEmpty()) {
return false;
} Exporter exporter = new JRPdfExporter();
SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
ExporterInput inp = new SimpleExporterInput(this.print);
configuration.setCreatingBatchModeBookmarks(true);
//configuration.setIccProfilePath(ruta);
configuration.set128BitKey(Boolean.TRUE);
exporter.setConfiguration(configuration);
JRSaver.saveObject(this.print, ruta + ".jrprint");
exporter.setExporterInput(inp);
output = new SimpleOutputStreamExporterOutput(out);
exporter.setExporterOutput(output);
exporter.exportReport();
}
output.close();
JasperViewer.viewReport(this.print, false, Locale.getDefault());
return true;
}
//Genera el reporte mostrandolo en el editor interno de Ireport
public boolean jasperReportInterno(InputStream dataSourceName, Map<String, Object> params, Connection conn) throws ClassNotFoundException, JRException {
this.reporte = JasperCompileManager.compileReport(dataSourceName);
this.print = JasperFillManager.fillReport(this.reporte, params, conn);
if (this.print.getPages().isEmpty()) {
return false;
}
JasperViewer.viewReport(this.print, false, Locale.getDefault());
return true;
}
//Muestra el reporte al abrir un archivo jrxml
public void mostrarReporte(String ruta) throws JRException, FileNotFoundException {
try {
URL url = new URL(new File(ruta).toURI().toString());
JasperPrint jasperPrint2;
jasperPrint2 = (JasperPrint) JRLoader.loadObject(url);
JasperViewer jviewer = new JasperViewer(jasperPrint2, false, Locale.getDefault());
JasperViewer.viewReport(jasperPrint2, false);
} catch (MalformedURLException ex) {
Logger.getLogger(Reportes.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Mi_primer_reporte.jrxml
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="Mi_primer_reporte" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="84b92a62-ec5b-4ccd-9288-f5ee1e1f5db3">
<property name="ireport.zoom" value="1.0"/>
<property name="ireport.x" value="0"/>
<property name="ireport.y" value="0"/>
<queryString>
<![CDATA[select c.* from CUSTOMER c where rownum<=100]]>
</queryString>
<field name="CUSID" class="java.math.BigDecimal"/>
<field name="CREDITCARDNUMBER" class="java.lang.String"/>
<field name="CREDITCARDTYPE" class="java.lang.String"/>
<field name="EMAIL" class="java.lang.String"/>
<field name="FNAME" class="java.lang.String"/>
<field name="LNAME" class="java.lang.String"/>
<field name="PASSWORD" class="java.lang.String"/>
<field name="PHONENUMBER" class="java.lang.String"/>
<field name="STATUS" class="java.lang.String"/>
<background>
<band splitType="Stretch"/>
</background>
<title>
<band height="32" splitType="Stretch">
<staticText>
<reportElement x="0" y="0" width="555" height="30" uuid="73f3eb21-c297-4597-a115-31c2cd2254ce"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<text><![CDATA[Mi Primer Reporte]]></text>
</staticText>
</band>
</title>
<pageHeader>
<band splitType="Stretch"/>
</pageHeader>
<columnHeader>
<band height="20" splitType="Stretch">
<staticText>
<reportElement x="0" y="0" width="100" height="20" uuid="0fa90d1d-6cef-4b89-a396-b29902a5b8af"/>
<text><![CDATA[CUSID]]></text>
</staticText>
<staticText>
<reportElement x="100" y="0" width="100" height="20" uuid="d89f3c11-da23-45f9-bfe8-aa303025c67c"/>
<text><![CDATA[FNAME]]></text>
</staticText>
<staticText>
<reportElement x="200" y="0" width="100" height="20" uuid="92d2b556-1c1e-4e01-9299-558096c51213"/>
<text><![CDATA[LNAME]]></text>
</staticText>
<staticText>
<reportElement x="300" y="0" width="100" height="20" uuid="a3fdddf2-8089-42e2-bfcb-f6f2fe2eab9d"/>
<text><![CDATA[PHONENUMBER]]></text>
</staticText>
<staticText>
<reportElement x="400" y="0" width="100" height="20" uuid="53caca70-b33e-41ea-90a8-3c92ae04eb2f"/>
<text><![CDATA[STATUS]]></text>
</staticText>
</band>
</columnHeader>
<detail>
<band height="20" splitType="Stretch">
<textField>
<reportElement positionType="Float" stretchType="RelativeToBandHeight" x="0" y="0" width="100" height="20" uuid="2a5e3bfd-e043-4e56-8629-70519e9eff39"/>
<textFieldExpression><![CDATA[$F{CUSID}]]></textFieldExpression>
</textField>
<textField>
<reportElement positionType="Float" stretchType="RelativeToBandHeight" x="100" y="0" width="100" height="20" uuid="4c8e07ae-595e-4175-9a71-3c9ff16fda13"/>
<textFieldExpression><![CDATA[$F{FNAME}]]></textFieldExpression>
</textField>
<textField>
<reportElement positionType="Float" stretchType="RelativeToBandHeight" x="200" y="0" width="100" height="20" uuid="0d99f240-e182-4674-9757-5082e0afa799"/>
<textFieldExpression><![CDATA[$F{LNAME}]]></textFieldExpression>
</textField>
<textField>
<reportElement positionType="Float" stretchType="RelativeToBandHeight" x="300" y="0" width="100" height="20" uuid="9acd22ff-5873-4ade-b394-0f066f2bdf73"/>
<textFieldExpression><![CDATA[$F{PHONENUMBER}]]></textFieldExpression>
</textField>
<textField>
<reportElement positionType="Float" stretchType="RelativeToBandHeight" x="400" y="0" width="100" height="20" uuid="7a6f7274-8a31-4857-9e9d-9bfe59c32aec"/>
<textFieldExpression><![CDATA[$F{STATUS}]]></textFieldExpression>
</textField>
</band>
</detail>
<columnFooter>
<band splitType="Stretch"/>
</columnFooter>
<pageFooter>
<band splitType="Stretch"/>
</pageFooter>
<summary>
<band splitType="Stretch"/>
</summary>
</jasperReport>
Vídeo con el proyecto corriendo
No hay comentarios:
Publicar un comentario