El Blog de Trespams

Blog personal sobre tecnologia, gestió de projectes i coses que se me passen pel cap

Velocity

Ahir vaig estar llegint-me la documentació de Velocity un sistema de plantilles fet en Java i que es pot integrar dins aplicacions clàssiques o web. La integració dins una aplicació de consola ha estat trivial, sols seguir l'exemple de la documentació. L'únic entrebanc que m'he trobat ha estat amb la part del loggin. Velocity fa servir per defecte el logger del projecte Avalon, projecte que està tancat. Així que m'he disposat a canviar de logger pel més habitual Log4j i aquí han començat els problemes, ja que Velocity està prepart per fer servir Category com a mecanisme per establir el tipus de log (info, debug, warn, ...) i les noves versions de Log4j han abandonat aquesta via i sols utilitzen el logger. Això ha fet que m'estigués barrallant una bona estona amb tot això, primer per descobrir que em faltava el l'Avalon LogKit i després per substituïr-ho per Log4j. Finalment l'exemple ha quedat així:

    /*
  • Copyright 2000-2001,2004 The Apache Software Foundation.
  • Licensed under the Apache License, Version 2.0 (the "License");
  • you may not use this file except in compliance with the License.
  • You may obtain a copy of the License at
  • http://www.apache.org/licenses/LICENSE-2.0
  • Unless required by applicable law or agreed to in writing, software
  • distributed under the License is distributed on an "AS IS" BASIS,
  • WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  • See the License for the specific language governing permissions and
  • limitations under the License.

*/ import org.apache.velocity.app.Velocity; import org.apache.velocity.VelocityContext; import org.apache.velocity.Template; import org.apache.log4j.; import org.apache.log4j.Logger; import org.apache.velocity.exception.ParseErrorException; import org.apache.velocity.exception.ResourceNotFoundException; import java.io.; import java.util.ArrayList;

/

  • This class is a simple demonstration of how the Velocity Template Engine
  • can be used in a standalone application.
  • Fent servir log4j com a logger. *
  • @author Jason van Zyl
  • @author Geir Magnusson Jr.
  • @author aaloy
  • @version $Id: Example.java,v 1.4.8.1 2004/03/04 00:18:29 geirm Exp $ */

public class Example

{ static Category logger = Logger.getLogger(Example.class.getName()); public Example(String templateFile) { BasicConfigurator.configure(); // Now set its priority. logger.info("Proves ...."); logger.debug("Iniciant"); try { /* * setup / logger.debug("Carregant les propietats"); Velocity.init("velocity.properties"); logger.debug("Propietats carregades"); //Velocity.init(); / * Make a context object and populate with the data. This * is where the Velocity engine gets the data to resolve the * references (ex. $list) in the template */

        logger.debug("Carregam el contexte");
        VelocityContext context = new VelocityContext();
        logger.debug("Contexte carregat");
        context.put("list", getNames());
        /*
         *  get the Template object.  This is the parsed version of your 
         *  template input file.  Note that getTemplate() can throw
         *   ResourceNotFoundException : if it doesn't find the template
         *   ParseErrorException : if there is something wrong with the VTL
         *   Exception : if something else goes wrong (this is generally
         *        indicative of as serious problem...)
         */

        Template template =  null;
        try 
        {
            template = Velocity.getTemplate(templateFile);
        }
        catch( ResourceNotFoundException rnfe )
        {
            logger.debug("Example : error : cannot find template " + templateFile );                
        }
        catch( ParseErrorException pee )
        {
            logger.debug("Example : Syntax error in template " + templateFile + ":" + pee );
        }
        /*
         *  Now have the template engine process your template using the
         *  data placed into the context.  Think of it as a  'merge' 
         *  of the template and the data to produce the output stream.
         */
        BufferedWriter writer = writer = new BufferedWriter(
        new OutputStreamWriter(System.out));
        if ( template != null)
            template.merge(context, writer);
        /*
         *  flush and cleanup
         */
        writer.flush();
        writer.close();
    }
    catch( Exception e )
    {
        System.out.println(e);
    }
}
public ArrayList getNames()
{
    ArrayList list = new ArrayList();
    list.add("ArrayList element 1");
    list.add("ArrayList element 2");
    list.add("ArrayList element 3");
    list.add("ArrayList element 4");
    return list;
}
public static void main(String[] args)
{
    //Log myLog;
    Example t;
    Example.logger.info("Arrancant");
    //myLog = LogFactory.getLog(Example.class);
    //myLog.info("Iniciant");
t = new Example("example.vm");
//myLog.info("Acabat");
}
}

El arxiu de plantilla està agafat directament de l'exemple de velocity així que m'estalvio de posar-ho.

Els arxius de configuració que he fet servir són

log4j.properties

log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#log4j.appender.stdout.layout.ConversionPattern=%p [%t] [%c] %C{1}.%M(%L) | %m%n
log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p %c - %m%n


velocity.properties
runtime.log = velocity_example.log
runtime.log.logsystem.class=org.apache.velocity.runtime.log.SimpleLog4JLogSystem
log4j.logger.org.apache.velocity.runtime.log.SimpleLog4JLogSystem=DEBUG

Pel rootLogger he anat a sac, però s'ha d'anar alerta si feim servir aquesta configuració en un altre tipus d'entorn, una aplicació J2EE per exemple, la quantitat d'informació que surt enlenteix molt la posada en marxa de l'aplicatiu.

Amb tot això ja tenc mig enllestit el primer projecte que em permetrà tenir la base de futurs desenvolupaments: Struts, Velocity, JSP2 i Hibernate ja funcionen plegats i sols falta que l'aplicatiu faci alguna cosa de profit, com escriure a la base de dades quelcom interessant, però encara no he decidit quina miniaplicació fer.

Em falta ara integrar una parell de d'utilitats d'interfície d'usuari (ja tenc el calendari i l'editor de texts), menús i posar un mini-exemple d'Ajax. A l'inici tot això duu una feinada, costa molt lligar-ho tot i fer un mini projecte així, però una vegada fet servirà de base a futurs desenvolupaments. Esper poder-ho penjar per aquí aviat.

blog comments powered by Disqus