All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.sf.blunder.service.persistence.InMemoryPersistenceService Maven / Gradle / Ivy

Go to download

Blunder is an automated tool for analyzing chained exceptions in Java. It's usefull for classify, generate a customized error message and a list for possible solutions. The aim of this project is to provide a tool to identify different error contexts, analyze them and assemble a customized response to an application end-user or another application.

The newest version!
/*
 *  Blunder is an automated tool for analyzing chained exceptions.
 *  Copyright (C) 2009 - Ambrosi Lucas 
 *
 *  This file is part of Blunder.
 *
 *  Blunder is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License 
 *  version 3 as published by the Free Software Foundation.
 *
 *  Blunder is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public 
 *  License along with Blunder. If not, see .
 */

package net.sf.blunder.service.persistence;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.blunder.BlunderException;
import net.sf.blunder.model.ExceptionRelation;
import ognl.Ognl;
import ognl.OgnlException;
import org.apache.log4j.Logger;

/**
 * This class provides a basic implementation for in-memory
 * persistent services. All implementations based on files
 * or other could extend from this class instead of extending
 * from {@link net.sf.blunder.service.persistence.BlunderPersistenceService}.
 * 
 * @author Ambrosi Lucas
 * @see net.sf.blunder.service.persistence.BlunderPersistenceService
 */
public abstract class InMemoryPersistenceService implements BlunderPersistenceService {

   private static final Logger log = Logger.getLogger( InMemoryPersistenceService.class );

   /**
    * Precompiled expression for solving lookups.
    */
   private static final Object LOOKUP_EXPRESSION = getLookupExpression();

   private HashMap data;
   private String filePath;

   /**
    * Analize the value and returns it or an empty String if null.
    * @param value
    * @return the value or an empty String.
    */
   protected String getEmptyOrValueString( String value ) {
      return value == null ? "" : value;
   }

   /**
    * @return A precompiled expression for solving queries on
    *         this service.
    */
   private static Object getLookupExpression() {
      StringBuilder sb = new StringBuilder( 100 );
      sb.append( "#relations.{? " );
      sb.append( "#this.getLeafExceptionClassname() == #leafExceptionClassname" );
      sb.append( " and " );
      // TODO: Ognl 2.6.9 doesn't seem to support variable names starting with 'root'!
      sb.append( "#this.getRootExceptionClassname() == #exceptionClassnameRoot" );
      sb.append( " and " );
      sb.append( "#this.getBusinessExceptionClassname() == #businessExceptionClassname" );
      sb.append( " }" );
      try {
         return Ognl.parseExpression( sb.toString() );
      } catch ( OgnlException e ) {
         log.fatal( "Error parsing OGNL expression [" + e.toString() + "]", e );
         return null;
      }
   }

   /**
    * @see net.sf.blunder.service.persistence.BlunderPersistenceService#findBy(String, String, String)
    */
   @SuppressWarnings("unchecked")
   public List findBy( String leafClassname, String rootClassname, String businessClassname ) {
      try {
         Map ctx = new HashMap();
         ctx.put( "relations", getData().values() );
         ctx.put( "businessExceptionClassname", getEmptyOrValueString( businessClassname ) );
         ctx.put( "leafExceptionClassname", getEmptyOrValueString( leafClassname ) );
         // TODO: Ognl 2.6.9 doesn't support keywords starting with 'root'!
         ctx.put( "exceptionClassnameRoot", getEmptyOrValueString( rootClassname ) );

         log.debug( "Running epression [" + LOOKUP_EXPRESSION + "]" );
         return (List)Ognl.getValue( LOOKUP_EXPRESSION, ctx, getData().values() );
      } catch ( OgnlException oe ) {
         log.error( "Error running search: " + oe.toString(), oe );
         return null;
      }
   }

   /**
    * @see net.sf.blunder.service.persistence.BlunderPersistenceService#findByBusiness(String)
    */
   public List findByBusiness( String businessClassname ) {
      return findBy( null, null, businessClassname );
   }

   /**
    * @see net.sf.blunder.service.persistence.BlunderPersistenceService#findByLeaf(String)
    */
   public List findByLeaf( String leafClassname ) {
      return findBy( leafClassname, null, null );
   }

   /**
    * @see net.sf.blunder.service.persistence.BlunderPersistenceService#findByLeafAndBusiness(String,String)
    */
   public List findByLeafAndBusiness( String leafClassname, String businessClassname ) {
      return findBy( leafClassname, null, businessClassname );
   }

   /**
    * @see net.sf.blunder.service.persistence.BlunderPersistenceService#findByLeafAndRoot(String,String)
    */
   public List findByLeafAndRoot( String leafClassname, String rootClassname ) {
      return findBy( leafClassname, rootClassname, null );
   }

   /**
    * @see net.sf.blunder.service.persistence.BlunderPersistenceService#findByRoot(String)
    */
   public List findByRoot( String rootClassname ) {
      return findBy( null, rootClassname, null );
   }

   /**
    * @see net.sf.blunder.service.persistence.BlunderPersistenceService#findDefaultRelation()
    */
   public ExceptionRelation findDefaultRelation() {
      return getData().get( new Long( 0 ) );
   }

   /**
    * @see net.sf.blunder.service.persistence.BlunderPersistenceService#learn(ExceptionRelation)
    */
   public void learn( ExceptionRelation er ) {
      try {
         er.setId( getAvailableId() );
         log.debug( "Id [" + er.getId() + "] assigned to relation [" + er + "]" );
         getData().put( er.getId(), er );
         writeData();
         // Removes all entries so next time we load all from media.
         refresh();
      } catch ( Exception e ) {
         log.error( "Error writing output file [" + e.getMessage() + "]" );
         throw new BlunderException( "Error writing output file", e );
      }
   }

   /**
    * @see net.sf.blunder.service.persistence.BlunderPersistenceService#update(ExceptionRelation)
    */
   public void update( ExceptionRelation er ) {
      if ( getData().containsKey( er.getId() ) ) {
         getData().put( er.getId(), er );
         writeData();
      } else {
         throw new BlunderException( "Can?t update a Relation that does not exists!" );
      }
   }

   /**
    * @see net.sf.blunder.service.persistence.BlunderPersistenceService#delete(ExceptionRelation)
    */
   public void delete( ExceptionRelation er ) {
      if ( getData().containsKey( er.getId() ) ) {
         getData().remove( er.getId() );
         writeData();
      }
      // Removes all entries so next time we load all from media.
      refresh();
   }

   /**
    * @see net.sf.blunder.service.persistence.BlunderPersistenceService#refresh()
    */
   public void refresh() {
      log.debug( "Cache clear..." );
      getData().clear();
   }

   /**
    * Looks for the next available id in the datamap.
    * @return an available id.
    */
   private Long getAvailableId() {
      Long testId = new Long( getData().size() );
      while ( true ) {
         ExceptionRelation result = getData().get( testId );
         if ( result == null ) {
            return testId;
         }
         testId++;
      }
   }

   /**
    * Sets the datamap with the relations.
    * @param data
    */
   public void setData( HashMap data ) {
      this.data = data;
   }

   /**
    * @return Gets the datamap with the relations.
    */
   public HashMap getData() {
      if ( data == null || data.isEmpty() ) {
         setData( readData() );
      }
      return data;
   }

   /**
    * @return Gets the file path with the path to the
    *        datamap file.
    */
   public String getFilePath() {
      return filePath;
   }

   /**
    * Sets the file path with the path to the datamap file.
    * @param filePath
    */
   public void setFilePath( String filePath ) {
      this.filePath = filePath;
   }

   /**
    * Your implementation should write this method. It is 
    * responsible for saving the data to the specified file.
    */
   public abstract void writeData();

   /**
    * Your implementation should write this method. It is 
    * responsible for reading the data to the specified file.
    */
   public abstract HashMap readData();

   /**
    * This method gets a {@link java.io.Reader} for the specified
    * persitence data file.
    * 
    *
  • * A {@link java.io.FileReader} if the file can be * reached from the file system. *
  • *
  • * A {@link java.io.InputStreamReader} if the file * could not be reached from the file system, and * it can be reached from the classpath. *
  • *
* * @return A {@link java.io.Reader} for the persistence * data file. * @throws {@link java.lang.NullPointerException} if the file * can not be reached. */ protected Reader getReader() { Reader reader = null; try { reader = new FileReader( getFilePath() ); } catch ( Exception e ) { reader = new InputStreamReader( ClassLoader.getSystemResourceAsStream( getFilePath() ) ); } if ( reader == null ) { throw new NullPointerException( "Null reader" ); } return reader; } /** * This method gets a {@link java.io.Writer} for the specified * persitence data file. *
    *
  • * A {@link java.io.FileWriter} if the file can be * reached from the file system. *
  • *
  • * A {@link java.io.FileWriter} if the file * could not be reached from the file system, and * it can be reached from the classpath. *
  • *
* * @return A {@link java.io.Writer} for the persistence * data file. * @throws {@link java.lang.NullPointerException} if the file * can not be reached. */ protected Writer getWriter() throws IOException { Writer writer = null; try { writer = new FileWriter( getFilePath() ); } catch ( Exception e ) { writer = new FileWriter( ClassLoader.getSystemResource( getFilePath() ).getPath() ); } if ( writer == null ) { throw new NullPointerException( "Null writer" ); } return writer; } /** * This method gets a {@link java.io.InputStream} for the specified * persitence data file. *
    *
  • * A {@link java.io.FileInputStream} if the file can be * reached from the file system. *
  • *
  • * A {@link java.io.InputStream} if the file * could not be reached from the file system, and * it can be reached from the classpath. *
  • *
* * @return A {@link java.io.InputStream} for the persistence * data file. * @throws {@link java.lang.NullPointerException} if the file * can not be reached. */ protected InputStream getInputStream() { InputStream is = null; try { is = new FileInputStream( getFilePath() ); } catch ( Exception e ) { is = ClassLoader.getSystemResourceAsStream( getFilePath() ); } if ( is == null ) { throw new NullPointerException( "Null input" ); } return is; } /** * This method gets a {@link java.io.OutputStream} for the specified * persitence data file. * @return A {@link java.io.OutputStream} for the persistence * data file. * @throws {@link java.lang.NullPointerException} if the file * can not be reached. */ protected OutputStream getOutputStream() throws FileNotFoundException { OutputStream os = null; try { os = new FileOutputStream( getFilePath() ); } catch ( Exception e ) { os = new FileOutputStream( ClassLoader.getSystemResource( getFilePath() ).getPath() ); } if ( os == null ) { throw new NullPointerException( "Null output" ); } return os; } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy