Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   *  jDTAUS - DTAUS fileformat.
   *  Copyright (c) 2005 Christian Schulte <cs@schulte.it>
   *
   *  This library is free software; you can redistribute it and/or
   *  modify it under the terms of the GNU Lesser General Public
   *  License as published by the Free Software Foundation; either
   *  version 2.1 of the License, or any later version.
   *
  *  This library 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 this library; if not, write to the Free Software
  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
  *
  */
 package org.jdtaus.core.io.util;
 
 import  org.jdtaus.core.container.ContainerFactory;
 import  org.jdtaus.core.container.ContextFactory;
 import  org.jdtaus.core.container.ContextInitializer;
 import  org.jdtaus.core.container.Implementation;
 import  org.jdtaus.core.container.ModelFactory;
 import  org.jdtaus.core.container.Properties;
 import  org.jdtaus.core.container.Property;
 import  org.jdtaus.core.container.PropertyException;
 import  org.jdtaus.core.io.FileOperations;
 import  org.jdtaus.core.lang.spi.MemoryManager;
 import  org.jdtaus.core.logging.spi.Logger;

Implementation of elementary I/O operations in heap memory.

This implementation performs I/O in memory. The value of property length is limited to a maximum of Integer.MAX_VALUE (4 GB).

Author(s):
Christian Schulte
Version:
$Id: MemoryFileOperations.java 4650 2008-03-10 04:25:23Z schulte2005 $
 
 public final class MemoryFileOperations implements
     FileOperations, SerializableCloneable
 {
     //--Fields------------------------------------------------------------------
 
    
Data to operate on.

Serial:
 
     private byte[] data = { ( byte ) 0 };

    
FilePointer.

Serial:
 
     private long filePointer = 0L;

    
Actual length.

Serial:
 
     private int length = 0;

    
Default temporary buffer.

Serial:
 
     private byte[] defaultBuffer;
 
     //------------------------------------------------------------------Fields--
     //--Implementation----------------------------------------------------------
 
 // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:jdtausImplementation
     // This section is managed by jdtaus-container-mojo.
 
    
Meta-data describing the implementation.
 
     private static final Implementation META =
         ModelFactory.getModel().getModules().
         getImplementation(MemoryFileOperations.class.getName());
 // </editor-fold>//GEN-END:jdtausImplementation
 
     //----------------------------------------------------------Implementation--
     //--Constructors------------------------------------------------------------
 
 // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:jdtausConstructors
     // This section is managed by jdtaus-container-mojo.
 
    
Initializes the properties of the instance.

Parameters:
meta the property values to initialize the instance with.
Throws:
NullPointerException if meta is null.
    private void initializeProperties(final Properties meta)
    {
        Property p;
        if(meta == null)
        {
            throw new NullPointerException("meta");
        }
        p = meta.getProperty("bufferSize");
        this. = ((java.lang.Integerp.getValue()).intValue();
    }
// </editor-fold>//GEN-END:jdtausConstructors
    //------------------------------------------------------------Constructors--
    //--Properties--------------------------------------------------------------
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:jdtausProperties
    // This section is managed by jdtaus-container-mojo.

    
Property bufferSize.

Serial:
    private int pBufferSize;

    
Gets the value of property bufferSize.

Returns:
the value of property bufferSize.
    private int getBufferSize()
    {
        return this.;
    }
// </editor-fold>//GEN-END:jdtausProperties
    //--------------------------------------------------------------Properties--
    //--Dependencies------------------------------------------------------------
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:jdtausDependencies
    // This section is managed by jdtaus-container-mojo.

    
Configured MemoryManager implementation.
    private transient MemoryManager dMemoryManager;

    
Gets the configured MemoryManager implementation.

Returns:
the configured MemoryManager implementation.
    private MemoryManager getMemoryManager()
    {
        MemoryManager ret = null;
        if(this. != null)
        {
            ret = this.;
        }
        else
        {
            ret = (MemoryManager) ContainerFactory.getContainer().
                getDependency(MemoryFileOperations.class,
                "MemoryManager");
            if(ModelFactory.getModel().getModules().
                getImplementation(MemoryFileOperations.class.getName()).
                getDependencies().getDependency("MemoryManager").
                isBound())
            {
                this. = ret;
            }
        }
        if(ret instanceof ContextInitializer && !((ContextInitializer) ret).
            isInitialized(ContextFactory.getContext()))
        {
            ((ContextInitializer) ret).initialize(ContextFactory.getContext());
        }
        return ret;
    }
    
Configured Logger implementation.
    private transient Logger dLogger;

    
Gets the configured Logger implementation.

Returns:
the configured Logger implementation.
    private Logger getLogger()
    {
        Logger ret = null;
        if(this. != null)
        {
            ret = this.;
        }
        else
        {
            ret = (Logger) ContainerFactory.getContainer().
                getDependency(MemoryFileOperations.class,
                "Logger");
            if(ModelFactory.getModel().getModules().
                getImplementation(MemoryFileOperations.class.getName()).
                getDependencies().getDependency("Logger").
                isBound())
            {
                this. = ret;
            }
        }
        if(ret instanceof ContextInitializer && !((ContextInitializer) ret).
            isInitialized(ContextFactory.getContext()))
        {
            ((ContextInitializer) ret).initialize(ContextFactory.getContext());
        }
        return ret;
    }
// </editor-fold>//GEN-END:jdtausDependencies
    //------------------------------------------------------------Dependencies--
    //--FileOperations----------------------------------------------------------
    public long getLength()
    {
        return this.;
    }

    

Throws:
IllegalArgumentException if newLength is negative or greater than Integer.MAX_VALUE.
    public void setLengthfinal long newLength )
    {
        if ( newLength < 0L || newLength > . )
        {
            throw new IllegalArgumentException( Long.toStringnewLength ) );
        }
        this.resize( ( int ) newLength );
        this. = ( int ) newLength;
        if ( this. > this. )
        {
            this. = this.;
        }
    }
    public long getFilePointer()
    {
        return this.;
    }
    public void setFilePointerfinal long pos )
    {
        // Preconditions.
        if ( pos < 0L || pos > . )
        {
            throw new IllegalArgumentException( Long.toStringpos ) );
        }
        this. = pos;
    }
    public int readfinal byte[] buffinal int offfinal int len )
    {
        final int ret;
        // Preconditions.
        if ( buf == null )
        {
            throw new NullPointerException"buf" );
        }
        if ( off < 0 )
        {
            throw new ArrayIndexOutOfBoundsExceptionoff );
        }
        if ( len < 0 )
        {
            throw new ArrayIndexOutOfBoundsExceptionlen );
        }
        if ( off + len > buf.length )
        {
            throw new ArrayIndexOutOfBoundsExceptionoff + len );
        }
        if ( this. + len > . )
        {
            throw new ArrayIndexOutOfBoundsException. );
        }
        if ( len == 0 )
        {
            ret = 0;
        }
        else if ( this. >= this. )
        {
            // EOF
            ret = FileOperations.EOF;
        }
        else if ( this. + len > this. )
        {
            // less than len byte before EOF
            final int remaining = ( int ) ( this. - this. );
            System.arraycopythis., ( int ) this.bufoff,
                              remaining );
            this. += remaining;
            ret = remaining;
        }
        else
        {
            // copy len byte into buf.
            System.arraycopy(
                this., ( int ) this.bufofflen );
            this. += len;
            ret = len;
        }
        return ret;
    }
    public void writefinal byte[] buffinal int offfinal int len )
    {
        // Preconditions.
        if ( buf == null )
        {
            throw new NullPointerException"buf" );
        }
        if ( off < 0 )
        {
            throw new ArrayIndexOutOfBoundsExceptionoff );
        }
        if ( len < 0 )
        {
            throw new ArrayIndexOutOfBoundsExceptionlen );
        }
        if ( off + len > buf.length )
        {
            throw new ArrayIndexOutOfBoundsExceptionoff + len );
        }
        final long newLen = this. + len;
        if ( newLen > . )
        {
            throw new ArrayIndexOutOfBoundsException. );
        }
        if ( newLen > this. )
        {
            this.setLengthnewLen );
        }
        System.arraycopybufoffthis., ( int ) this.len );
        this. += len;
    }
    public void readfinal OutputStream out ) throws IOException
    {
        if ( out == null )
        {
            throw new NullPointerException"out" );
        }
        out.writethis., 0, this. );
        this. = this.;
    }
    public void writefinal InputStream in ) throws IOException
    {
        if ( in == null )
        {
            throw new NullPointerException"in" );
        }
        int read;
        final byte[] buf = this.getDefaultBuffer();
        while ( ( read = in.readbuf, 0, buf.length ) ) != FileOperations.EOF )
        {
            this.writebuf, 0, read );
        }
    }

    

Since this implementation does not use any system resources to release, this method does nothing. In contrast to other FileOperations implementations the instance can still be used after calling this method. It would be a mistake to write an application which relies on this behaviour, however.

    public void close()
    {
    }
    //----------------------------------------------------------FileOperations--
    //--MemoryFileOperations----------------------------------------------------

    
Creates a new MemoryFileOperations instance of no length.
    public MemoryFileOperations()
    {
        this.initializeProperties.getProperties() );
        this.assertValidProperties();
    }

    
Creates a new MemoryFileOperations instance of no length taking an initial capacity.

Parameters:
initialCapacity the number of bytes to pre-allocate when creating the new instance.
Throws:
OutOfMemoryError if not enough memory is available to create a buffer with a length of initialCapacity.
    public MemoryFileOperationsfinal int initialCapacity )
    {
        this.initializeProperties.getProperties() );
        this.assertValidProperties();
        this. = this.getMemoryManager().allocateBytes( initialCapacity );
    }

    
Creates a new MemoryFileOperations instance holding buf.

Parameters:
buf bytes to initialize the instance with.
Throws:
NullPointerException if buf is null.
    public MemoryFileOperationsfinal byte[] buf )
    {
        this();
        if ( buf == null )
        {
            throw new NullPointerException"buf" );
        }
        this. = buf;
        this. = buf.length;
        this. = 0L;
    }

    
Gets the file contents.

Returns:
the file contents of the instance.
Throws:
OutOfMemoryError if not enough memory is available.
    public byte[] getData()
    {
        final int length = ( int ) this.getLength();
        final byte[] ret = this.getMemoryManager().allocateBytes( length );
        System.arraycopythis., 0, ret, 0, length );
        return ret;
    }

    
Checks configured properties.

Throws:
PropertyException if property bufferSize is negative or 0.
    private void assertValidProperties()
    {
        if ( this.getBufferSize() <= 0 )
        {
            throw new PropertyException( "bufferSize",
                                         new Integerthis.getBufferSize() ) );
        }
    }

    
Getter for property defaultBuffer.

Returns:
a buffer for operations which need temporary memory.
    private byte[] getDefaultBuffer()
    {
        if ( this. == null )
        {
            this. = this.getMemoryManager().
                allocateBytes( this.getBufferSize() );
        }
        return this.;
    }

    
Resizes the internal buffer.

Parameters:
newSize maximum size the internal buffer needs to hold.
    private void resizeint newSize )
    {
        final int oldLength = this..length;
        while ( this..length < newSize )
        {
            final byte[] newData = this.getMemoryManager().allocateBytes(
                this..length * 2 >= newSize
                ? this..length * 2
                : newSize );
            Arrays.fillnewData, ( byte ) 0 );
            System.arraycopythis., 0, newData, 0, this..length );
            this. = newData;
        }
        if ( oldLength != this..length &&
            this.getLogger().isDebugEnabled() )
        {
            final MessageFormat fmt = MemoryFileOperationsBundle.getInstance().
                getLogResizeMessage( Locale.getDefault() );
            this.getLogger().debug(
                fmt.formatnew Object[] { new Longthis..length ) } ) );
        }
    }
    //----------------------------------------------------MemoryFileOperations--
    //--Object------------------------------------------------------------------

    
Indicates whether some other object is equal to this one by comparing the contents from memory.

Parameters:
o the reference object with which to compare.
Returns:
true if this object is the same as o; false otherwise.
    public boolean equalsfinal Object o )
    {
        boolean ret = o == this;
        final MemoryFileOperations that;
        if ( !ret && o instanceof MemoryFileOperations )
        {
            that = ( MemoryFileOperations ) o;
            ret = Arrays.equalsthis.getData(), that.getData() );
        }
        return ret;
    }

    
Returns a hash code value for this object.

Returns:
a hash code value for this object.
    public int hashCode()
    {
        return this.getData().hashCode();
    }

    
Creates and returns a deep copy of this object.

Returns:
a clone of this instance.
    public Object clone()
    {
        try
        {
            return super.clone();
        }
        catch ( CloneNotSupportedException e )
        {
            throw new AssertionErrore );
        }
    }
    //------------------------------------------------------------------Object--
New to GrepCode? Check out our FAQ X