S.O OpenSuse

openSUSE es un sistema operativo libre basado en Linux. La distribución openSUSE es estable, sencilla de usar, completa y de propósito general

Node.js

Node es una platafoma y un entorno de desarrollo basado en JavaScript al lado del servidor

Java

Java es un entorno de desarrollo multiplataforma

Java

Java es un entorno de desarrollo multiplataforma

This is default featured post 5 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by Lasantha Bandara - Premiumbloggertemplates.com.

domingo, 19 de junio de 2016

Abrir archivo de reporte jasper desde un jar

Hola buen dia

 Les dejo un  pequeño video con un ejemplo de como abrir un archivo jasper report desde un archivo jar.




Saludos!!

sábado, 23 de mayo de 2015

Log usando Spring y Log4j

En esta entrada les traigo un ejemplo de como colocar un log dentro de nuestro sistema web usando Spring y la libreria de Apache Log4j

Requisitos:


  • JDK 1.6
  • NetBeans IDE
  • Log4j

  • Creamos un nuevo proyecto web desde Netbeans usando Spring.
    new --> web aplication 
    En la parte donde tenemos que elegir el framework usamos spring web MVC

    En el archivo web.xml configuramos el archivo log4j-helloworld.properties y nuestro DispatcherServlet.

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
     
        <display-name>HelloWorld</display-name>
        <context-param>
            <param-name>log4jConfigLocation</param-name>
            <param-value>/WEB-INF/log4j-helloworld.properties</param-value>
        </context-param> 
        <listener>
            <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
        </listener>
        <servlet>
            <servlet-name>HelloWorld</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>HelloWorld</servlet-name>
            <url-pattern>*.html</url-pattern>
        </servlet-mapping>
        <session-config>
            <session-timeout>
                30
            </session-timeout>
        </session-config>
        <welcome-file-list>
            <welcome-file>index.jsp</welcome-file>
        </welcome-file-list>
    </web-app>

    crear el archivo log4j-helloworld.properties en la ruta /WEB-INF/ e incluir la siguiente configuración en el
    log4j.rootLogger=ERROR, stdout, rollingFile
     
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
     
    log4j.appender.rollingFile=org.apache.log4j.RollingFileAppender
    log4j.appender.rollingFile.File=${webapp.root}/WEB-INF/logs/helloworld.log
    #log4j.appender.rollingFile.File=${catalina.home}/logs/helloworld.log
    log4j.appender.rollingFile.MaxFileSize=512KB
    log4j.appender.rollingFile.MaxBackupIndex=10
    log4j.appender.rollingFile.layout=org.apache.log4j.PatternLayout
    log4j.appender.rollingFile.layout.ConversionPattern=%d %p [%c] - %m%n
    log4j.appender.rollingFile.Encoding=UTF-8

    posteriormente creamos el archivo de configuracion en la ruta y nombre /WEB-INF/HelloWorld-servlet

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd">
        <context:component-scan base-package="it.helloworld.controller" />
     
        <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix">
                <value>/WEB-INF/views/</value>
            </property>
            <property name="suffix">
                <value>.jsp</value>
            </property>
        </bean>
    </beans>

    creamos el archivo /WEB-INF/index.jsp
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
       "http://www.w3.org/TR/html4/loose.dtd"> 
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>Welcome Page</title>
        </head>
        <body>
            <jsp:forward page="helloWorld.html" />
        </body>
    </html>

    creamos el archivo WEB-INF/views/helloWorld.jsp con lo siguiente:
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
       "http://www.w3.org/TR/html4/loose.dtd">
     
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>JSP Page</title>
        </head>
        <body>
            <h1>Hello World desde las vistas!!!</h1>
        </body>
    </html>

    creamos la siguiente clase HelloWorldController en el siguiente paquete: it.helloworld.controller

    package it.helloworld.controller;
     
    import org.apache.log4j.Logger;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.servlet.ModelAndView;
     
    @Controller
    public class HelloWorldController {
     
        private static org.apache.log4j.Logger log = Logger.getLogger(HelloWorldController.class);
     
        @RequestMapping(value = {"/index", "/helloWorld"})
        public ModelAndView helloWorld() {
     
            log.trace("Ejemplo Trace");
            log.debug("Ejemplo Debug");
            log.info("Ejemplo Info");
            log.warn("Ejemplo Warn");
            log.error("Ejemplo Error");
            log.fatal("Ejemplo Fatal");
     
            return new ModelAndView("helloWorld");
        }
    }


    les dejo el link del proyecto de prueba SpringLog

    viernes, 29 de marzo de 2013

    Node.js Descarga e Instalacion en OpenSuse





    Node es una plataforma y un entorno de desarrollo basado en codigo javaScript al lado del servidor, es personalizable ademas que tiene mayor rendimiento, a diferencia de Apache que trae por default varios modulos que aveces es muy complicado modificar, Node es una plantilla en blanco esta preparada para que tu la puedas personalizar segun tus necesidades, otra de las grandes ventajas de Node.js es el uso de memoria mientras que los servidores normales crean un hilo diferente para solicitud Node los procesa todo mediante un unico hilo multitarea de javascript.

    Descarga 

    En la pagina de Node.js descargamos las opcion que vemos en la imagen.

    Requisitos

    antes de continuar con la instalación debemos asegurarnos que tenemos instalados las siguientes dependencias.


    • zlib-devel
    • g++
    • gcc
    • make
    • libssl-dev
    • python 2.6 o 2.7

    Mediante la terminal nos ubicamos en la carpeta que se halla descargado y descomprimir el paquete con el comando tar.


    Nos ubicamos en la carpeta que se creo al descomprimir y ejecutamos lo siguiente ./configure

    posteriormente preparamos la instalación y ejecutamos make.

    por ultimo con sudo make install realizamos la instalación.

    para esta versión que utilizamos en este post al instalar Node crea la variable path, lo que significa que no importa en el directorio que nos encontremos si tecleamos el comando node este se ejecutara correctamente.
    para verificar que se instaló correctamente ejecutamos node -v en la terminal y nos mostrara la version instalada.



    Listo Node quedo instalado correctamente en Opensuse.

    en los próximos post publicare como configurar un servidor en Node y crear el primer proyecto.

    miércoles, 27 de febrero de 2013

    Exportar lista de Directorios a Excel, txt o Pdf usando itext y POI

    En algunas ocaciones necesite una saber la lista de de archivos que se encontraban dentro de un directorio y subdirectorio y guardarlos en un archivo. asi que implemente una pequeña utileriapara ello.


    Requisitos


    Creando el proyecto

    Creamos un nuevo proyecto Java y agregamos las librerias de iText y POI



    Creamos una nueva clase llamada ExportaTxt dentro de esta crearemos el metodo crearTxt le pasaremos como parametros un List de String y un String con la cadena y el nombre del archivo.
    01 public class ExportaTxt {
    02 
    03     public void crearTxt(ArrayList<String> list, String archivo) {
    04         FileWriter fichero = null;
    05         PrintWriter pw = null;
    06         try {
    07             fichero = new FileWriter(archivo);
    08             pw = new PrintWriter(fichero);
    09 for (String string : list) {
    10                 pw.println(string);
    11             }
    12         } catch (Exception e) {
    13             e.printStackTrace();
    14         }
    15         finally {
    16             try {
    17                 if (fichero != null) {
    18                     fichero.close();
    19                 }
    20             } catch (Exception e) {
    21                 e.printStackTrace();
    22             }
    23         }
    24     }
    25 }
    26 
    
    Ahora agregamos la clase exporta excel esta tendra un metodo que crearExcel al cual le pasaremos como parametros una lista de directorios, el nombre del libro y la ruta con el nombre del archivo.
    01 public class ExportaExcel {
    02 
    03     public void crearExcel(ArrayList<String> list, String libro, String archivo) {
    04         HSSFWorkbook book = new HSSFWorkbook();
    05         HSSFSheet hoja = book.createSheet(libro);
    06         HSSFRow fil = hoja.createRow(0);
    07         HSSFCell celd = fil.createCell(0);
    08         celd.setCellValue("Lista de archivos");
    09         CellStyle stilo = book.createCellStyle();
    10         stilo.setFillForegroundColor(HSSFColor.GREY_50_PERCENT.index);
    11         stilo.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    12         HSSFFont font = book.createFont();
    13         font.setFontHeightInPoints((short) 12);
    14         font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    15         stilo.setFont(font);
    16         celd.setCellStyle(stilo);
    17 for (String lis : list) {
    18             HSSFRow fila = hoja.createRow(list.indexOf(lis) + 1);
    19             HSSFCell celda = fila.createCell(0);
    20             celda.setCellValue(lis);
    21             hoja.autoSizeColumn(0);
    22             try {
    23                 FileOutputStream fichero = new FileOutputStream(archivo);
    24                 book.write(fichero);
    25                 fichero.close();
    26             } catch (Exception e) {
    27                 e.printStackTrace();
    28             }
    29         }
    30     }
    31 }
    32 
    

    ahora creamos la clase ExportaPdf esta clase tendra un metodo llamado crearPdf le pasaremos como parametros la lista de archivos o directorios y la ruta con el nombre del archivo.
    01 public class ExportaPdf {
    02 
    03     public void crerPdf(ArrayList<String> list, String archivo) {
    04         try {
    05             Document document = new Document();
    06             PdfWriter.getInstance(document, new FileOutputStream(archivo));
    07             document.open();
    08             Font font = new Font();
    09             font.setStyle(Font.BOLD);
    10             PdfPTable table = new PdfPTable(1);
    11             table.setWidths(new int[] {1});
    12             PdfPCell cell;
    13             cell = new PdfPCell(new Phrase("lista de archivos", font));
    14             cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    15             table.addCell(cell);
    16 for (String string : list) {
    17                 cell = new PdfPCell(new Phrase(string));
    18                 cell.setHorizontalAlignment(Element.ALIGN_LEFT);
    19                 table.addCell(cell);
    20             }
    21             document.add(table);
    22             document.close();
    23         } catch (Exception e) {
    24             e.printStackTrace();
    25         }
    26 
    27     }
    28 } 

    Creamos una clase que sera nuestro controlador esta clase contenda un medor que nos retorne una lista de los archivos ,directorios y subdirectorios. ademas se implemetaran tres metodos exportarTxt, exportarExcel y exportarPdf.
    01 public class Direc {
    02 
    03     ArrayList lista = new ArrayList<String>();
    04 
    05     public ArrayList<String> getDir(String directorio) {
    06         File file = new File(directorio);
    07         File[] dirs = file.listFiles();
    08 for (File file1 : dirs) {
    09             lista.add(file1.getName());
    10             if (file1.isDirectory()) {
    11                 getDir(file1.getAbsolutePath());
    12             }
    13         }
    14 
    15         return lista;
    16     }
    17 
    18     public void exportarExcel(String dir, String dondeGuardar) {
    19         ArrayList<String> list = getDir(dir);
    20         ExportaExcel excel = new ExportaExcel();
    21         excel.crearExcel(list, "lista de archivos", dondeGuardar + "/archivos.xls");
    22     }
    23 
    24     public void exportarTxt(String dir, String dondeGuardar) {
    25         ArrayList<String> list = getDir(dir);
    26         ExportaTxt txt = new ExportaTxt();
    27         txt.crearTxt(list, dondeGuardar + "/archivos.txt");
    28     }
    29 
    30     public void exportarPdf(String dir, String dondeGuardar) {
    31         ArrayList<String> list = getDir(dir);
    32         ExportaPdf pdf = new ExportaPdf();
    33         pdf.crerPdf(list, dondeGuardar + "/archivos.pdf");
    34     }
    35 }
    36 
    

    y por ultimo implementamos un pequeña interfaz.


     y listo.

    aqui les dejo el codigo fuente.






    martes, 30 de octubre de 2012

    CRUD Hibernate 3 con Sql Server 2008 en NetBeans - Parte II.- Desarrollo

    Continuando con la Practica CRUD Hibernate 3 con Sql Server 2008 ahora vamos a realizar altas, bajas, cambios de una Base de Datos. 
    • Creando los Paquetes 

      Creamos un nuevo proyecto web llamado DVDStore debemos crear los paquetes:
      • bean
      • dao
      • util
      • vista
        En el paquete default crearemos los archivos de configuracion hibernate.cfg.xml y hibernate.reveng.xml tal como se crean en el post anterior. 
     En el paquete bean creamos los archivos que seran mapeados a la base de datos. sobre el paquete bean -> new -> Hibenate Mapping Files and POJOs from Database. con esto crearemos los archivo Actor.hbm.xml y Actor.java
    En el paquete until creamos la clase HibenateUtil esta clase viene incluida en el Framework de Hibernate. 
    new->HibernateUtil y le nombramos HibenateUtil
    continuamos creando nuetra clase DAO(Data Access Object) la cual nos facilitara la manipulacion de los datos contenidos en la tabla. esta clase estara contenida en el paquete dao y la llamaremos ActorDao en esta clase tendremos los metodos. insert(), update(Actor actor),  find(String busqueda), find(int id) y delete(int id).
    05 package dao;
    06 
    07 import bean.Actor;
    08 import java.util.ArrayList;
    09 import javax.swing.JOptionPane;
    10 import org.hibernate.HibernateException;
    11 import org.hibernate.Session;
    12 import org.hibernate.SessionFactory;
    13 import org.hibernate.Transaction;
    14 import org.hibernate.cfg.Configuration;
    15 import util.HibernateUtil;
    16 
    17 /**
    18  *
    19  * @author xm07689
    20  */
    21 public class ActorDao {
    22 
    23     public void insert(Actor actor) {
    24         Session sess = null;
    25         try {
    26             SessionFactory factory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
    27             sess = factory.getCurrentSession();
    28             Transaction tx = sess.beginTransaction();
    29             sess.save(actor);
    30             tx.commit();
    31             JOptionPane.showMessageDialog(null, "Successfully data insert in database");
    32         } catch (Exception e) {
    33             JOptionPane.showMessageDialog(null, e.getMessage());
    34         }
    35     }
    36 
    37     public void update(Actor actor) {
    38         Session sess = null;
    39         try {
    40             SessionFactory factory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
    41             sess = factory.getCurrentSession();
    42             Transaction tx = sess.beginTransaction();
    43             sess.update(actor);
    44             tx.commit();
    45             JOptionPane.showMessageDialog(null, "Successfully data update in database");
    46         } catch (Exception e) {
    47             JOptionPane.showMessageDialog(null, e.getMessage());
    48         }
    49     }
    50 
    51     public ArrayList<Actor> find(String busqueda) {
    52         Session sess = null;
    53         ArrayList<Actor> listAct;
    54         SessionFactory factory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
    55         sess = factory.getCurrentSession();
    56         Transaction tx = sess.beginTransaction();
    57         if (busqueda.equals("")) {
    58             listAct = (ArrayList<Actor>) sess.createQuery("from Actor").list();
    59         } else {
    60             listAct = (ArrayList<Actor>) sess.createQuery("from Actor where name='" + busqueda + "'").list();
    61         }
    62         return listAct;
    63     }
    64 
    65     public Actor find(int id) {
    66         Actor actor = null;
    67         Session sess = null;
    68         SessionFactory factory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
    69         sess = factory.getCurrentSession();
    70         Transaction tx = sess.beginTransaction();
    71         actor = (Actor) sess.createQuery("from Actor where actor_id=" + id).uniqueResult();
    72 
    73         return actor;
    74     }
    75 
    76     public void delete(int id) {
    77         try {
    78             Session sess = null;
    79             sess = HibernateUtil.getSessionFactory().openSession();
    80             sess.beginTransaction();
    81             Actor actor = (Actor) sess.createQuery("from Actor where actor_id=" + id).uniqueResult();
    82             sess.delete(actor);
    83             sess.getTransaction().commit();
    84             sess.close();
    85         } catch (HibernateException ie) {
    86             JOptionPane.showMessageDialog(null, ie.getMessage());
    87         }
    88     }
    89 }  

    El ultimo paso es creal la vista asi que en este paquete creamos un nuevo JFrame Form este ya viene predefinido en los paqutes de Swing Gui Forms de Netbeans
    new->JFrame Form lo llamaremos FrmActor.

    el proyecto debe quedar de la siguente forma.
      
    el paquete img es una carpeta que debemos crear para ir guardando las imagenes de los actores este proceso de guardado y se hace en la clase FrmActor. les dejo unas imagenes de como funciona el ejemplo y ademas les pondre el script de la base de datos y los fuentes del proyecto. espero les sirva de ejemplo.

                                                          cargando los datos......
    Ventana Principal

    Seleccionando un actor
    cambiando la foto

    Saludos y dejen sus cometarios.