Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright (c) 2003, 2007 s IT Solutions AT Spardat GmbH . All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/epl-v10.html Contributors: s IT Solutions AT Spardat GmbH - initial API and implementation /
 
 /*
  * Created on : 04.2003
  * Created by : s3595
  */
 package at.spardat.xma.boot.cache;
 
 import java.io.File;
 import java.net.URL;
 
 import  at.spardat.xma.xdelta.JarPatcher;

file cache for resources

Author(s):
s3595 Chris Sch�fer (CGS)
Version:
$Id: FileCache.java 2084 2007-11-27 14:53:31Z s3460 $
 
 public class FileCache implements IFileCache {

    
this is a singleton
 
     private static FileCache instance_;

    
physical file storage
 
     private FileCacheStore store_;

    
logger
 
     private Logger log_;

    
debug file output
 
     private Boolean debug;



    
get the FileCache

Returns:
FileCache Singleton Instance
Throws:
IllegalStateException if not initialized
 
     public static IFileCache getInstance(){
         if( == null)
           throw new IllegalStateException"FileCache not initialized"); //$NON-NLS-1$
         else
           return ;
     }

    
initialize only once before usage

Parameters:
brt the BootRuntime to get the configuration from
Returns:
the new and initialized FileCache
Throws:
IllegalArgumentException if file does not exist.
IOException containing the filename
 
      public static synchronized FileCache initializeBootRuntime brt ) throws IOException {
          if( == null ) {
               = new FileCachebrt );
          }
          return  ;
      }

    
Constructor of the Filecache

Parameters:
brt the BootRuntime to get the configuration from
Throws:
IOException containing the filename
 
     private FileCacheBootRuntime brt ) throws IOException {
         = Logger.getLogger"boot.cache" ); //$NON-NLS-1$
        = brt.getDebug();
        = new FileCacheStore(brt);
    }
    /*
     *  (non-Javadoc)
     * @see at.spardat.xma.boot.cache.IFileCache#openResource(java.net.URL)
     */
    public IFileCacheResource openResourceURL urlRemote ) throws IOException {
        // the default is: load resource-file into memory buffer, and do not force a server update check.
        return openResource(urlRemotetruefalsenull );
    }
    /*
     *  (non-Javadoc)
     * @see at.spardat.xma.boot.cache.IFileCache#openResource(at.spardat.xma.boot.component.IRtXMASessionClient, java.net.URL)
     */
    public IFileCacheResource openResource(IRtXMASessionClient sessionURL urlRemotethrows IOException {
        return openResource(urlRemotetruefalsesession );
    }
    /*
     *  (non-Javadoc)
     * @see at.spardat.xma.boot.cache.IFileCache#openResource(java.net.URL, boolean)
     */
    public IFileCacheResource openResourceURL urlRemoteboolean bmode ) throws IOException {
        // the default is: load resource-file into memory buffer, and do not force a server update check.
        return openResource(urlRemotebmodefalsenull );
    }
    /*
     *  (non-Javadoc)
     * @see at.spardat.xma.boot.cache.IFileCache#openResource(java.net.URL, boolean, boolean)
     */
    public IFileCacheResource openResourceURL urlRemote,  boolean bmodeboolean bforce ) throws IOException {
       return openResource(urlRemotebmodebforcenull );
    }
    /*
     *  (non-Javadoc)
     * @see at.spardat.xma.boot.cache.IFileCache#openResource(java.net.URL, boolean, boolean,at.spardat.xma.boot.component.IRtXMASessionClient)
     */
    public IFileCacheResource openResourceURL urlRemote,
                                            boolean bmodeboolean bforce,
                                            IRtXMASessionClient session )  throws IOException {
        /* locals ---------------------------------- */
          File               file    = null;
          Result             result  = null;
          IFileCacheResource temp    = null;
        /* locals ---------------------------------- */
        if ( urlRemote == null || !isCacheable(urlRemote)) {
           throw new IllegalArgumentException"resource is not cacheable:" + urlRemote); //$NON-NLS-1$
        }
        file = getFile(urlRemote);
        temp = .getResource(file,urlRemote);
        if(temp!=null && !temp.isExpired() && !bforce) {
            try {
                if(session!=null && temp.getProperty(.)!=null) {
                    ((FCResource)temp). = session.inverseTransform(temp.getProperty(.),((FCResource)temp).getBuffer());
                }
                return temp;  // found in cache, resource is not expired and an update force was not requested
            } catch (Exception ex) {  // TODO genaue hash-violation-exception erkennen!
                temp=null// cached version corrupted -> unconditional get needed
                .log(.,"data integrity violated: "+file.getAbsolutePath(),ex);
            }
        }
        // not cached, download it
        result = loadResource(urlRemote,
                              temp!=null ? temp.getLastModified():0L,
                              temp!=null ? temp.getProperty(.):null,
                              session );
        // and save it
        temp = .storeResource(file,result,urlRemote,temp,bmode,bforce);
        if(session!=null && temp.getProperty(.)!=null) {
            ((FCResource)temp). = session.inverseTransform(temp.getProperty(.),((FCResource)temp).getBuffer());
        }
        return temp;
    }
    /* (non-Javadoc)
     * @see at.spardat.xma.boot.cache.IFileCache#openResource(at.spardat.xma.boot.transport.XMA_URI, at.spardat.xma.boot.comp.data.XMAResource, at.spardat.xma.boot.cache.VersionNumber, boolean)
     */
    public IFileCacheResource openResource(XMA_URI appUriXMAResource resourceVersionNumber serverVersboolean bforcethrows IOException {
        String hash = resource.getVersion_().getVersion();
        File file;
        URL urlRemote = appUri.getHTTP_AppUriresource.getHref_() );
        if ( urlRemote == null || !isCacheable(urlRemote)) {
            throw new IllegalArgumentException"resource is not cacheable:" + urlRemote); //$NON-NLS-1$
        }
        if(resource.isShared_()) {
            String filename = resource.getHref_();
            int last = filename.lastIndexOf('/');
            if(last>=0) filename = filename.substring(last);
            file = new File(.getBaseDir(),. + . + VersionNumber.insertHash(filename,hash));
        } else {
            file = getFile(urlRemote);
        }
        FCResource temp = .getResource(file,urlRemote);
        if(temp!=null) {
            String currentHash = temp.getProperty(.);
            if(hash.equals(currentHash)) {
                if(!temp.isExpired() && !bforce) {
                    return temp;  // found in cache, resource is not expired and an update force was not requested
                }
            } else {
                temp=null// wrong version cached -> unconditional get needed
            }
        }
        // not cached, download it
        URL deltaURL = urlRemote;
        FCResource latestVersion=null;
        if(!bforce) {
            latestVersion = .findPreviousVersion(file);
            if(latestVersion!=null) {
                deltaURL = latestVersion.versionNumber.insertAsDelta(urlRemote);
                .log(.,"performing delta download for "+deltaURL.toString());
            }
        }
        URL downloadURL = deltaURL;
        try {
            if(serverVers!=null && serverVers.compareTo(new VersionNumber(1,6,0))>=0) {
                downloadURL = new URL(VersionNumber.insertHash(downloadURL.toExternalForm(),hash));
            } else {
                if(urlRemote.getQuery()==nulldownloadURL = new URL(downloadURL+"?hash="+hash);
                else downloadURL = new URL(downloadURL+"&hash="+hash);
            }
        } catch (MalformedURLException mue) {
            MalformedURLException ne = new MalformedURLException("error constructing download URL "+downloadURL.toString());
            ne.initCause(mue);
            throw ne;
        }
        Result result;
        try {
            result = loadResource(downloadURL,
                                  temp!=null ? temp.getLastModified():0L,
                                  temp!=null ? temp.getProperty(.):null,
                                  null );
        } catch (CommunicationException exc) {
            if(latestVersion!=null) { // if a delta was not found no the server -> full download
                if(exc.getCause() instanceof FileNotFoundException || exc.getReturnCode() == 404) {
                    .log(.,"error downloading "+downloadURL.toString(),exc);
                    .log(.,"performing full download");
                    return openResource(appUri,resource,serverVers,true);
                }
            }
            throw exc;
        }
        // apply delta
        if(latestVersion!=null) {
            try {
                File deltaFile = getFile(deltaURL);
                try {
                    deltaFile.getParentFile().mkdirs();
                    deltaFile.createNewFile();
                    FileOutputStream deltaOut = new FileOutputStream(deltaFile);
                    deltaOut.write(result.getBuffer());
                    deltaOut.close();
                } catch (IOException exc) {
                    IOException ne = new IOException("error storing delta file "+deltaFile.getAbsolutePath());
                    ne.initCause(exc);
                    throw ne;
                }
                ByteArrayOutputStream patched = new ByteArrayOutputStream();
                new JarPatcher().applyDelta(new ZipFile(latestVersion.file_),new ZipFile(deltaFile),new ZipOutputStream(patched));
                temp = .storeResource(file,result,patched.toByteArray(),urlRemote,false);
                if(!resource.isJar()) { temp.setProperty(.,hash); }
                deltaFile.delete();
            } catch(Exception ex) { // if the delta made troubles -> full download
                .log(.,"error applying delta file "+ex);
                return openResource(appUri,resource,serverVers,true);
            }
        } else {
        // and save it
            temp = .storeResource(file,result,urlRemote,temp,false,bforce);
            if(!resource.isJar()) { temp.setProperty(.,hash); }
        }
        return temp;
    }

    
Check the integrity of the given resource.
The given hash value is compared to the stored hash value of the resource. Additionally the hash value is calculated from the resource and compared. This does not only detect a wrong version of the resource. It detects corrupted and manipulated resources, too.

Parameters:
resource to check
hash expected hash value
isJar if the resource is a jar file or not
Returns:
true if the hash matches, false otherwise
Author(s):
s2877
Since:
1.3.0
    public boolean checkHash(IFileCacheResource resourceString hashboolean isJar) {
        try {
            if(hash==nullreturn false;
            if(!hash.equals(resource.getProperty(.))) return false;
            if(isJarreturn hash.equals(HashChecksum.calcJarCheckSum(((FCResource)resource).));
            else return hash.equals(HashChecksum.calcCheckSum(((FCResource)resource).getBuffer()));
        } catch (Exception exc) {
            // if I can't read it, it's corrupted
            .log(.,"file "+((FCResource)resource)..getAbsolutePath()+" corrupted",exc);
            return false;
//        } catch (Throwable exc) {  // java.util.ZipFile wirft auch VirtualMachineErrors !!
//            // if I can't read it, it's corrupted
//            log_.log(LogLevel.WARNING,"file "+((FCResource)resource).file_.getAbsolutePath()+" corrupted",exc);
//            return false;
        }
    }

    
Open a resource from the local cache. No effort is made to download it, if it is not cached null is returned. The resource is not checked for expiration or integrity. This method does not find shared resources.

Parameters:
resource to open
Returns:
the resource from the local cache or null if not cached.
Throws:
IOException containing the filename
Author(s):
s2877
Since:
1.3.0
    public IFileCacheResource openLocalResource(XMA_URI resource) {
        URL urlRemote = resource.getHTTP_URI();
        File file = getFile(urlRemote);
        IFileCacheResource localResource = .getResource(file,urlRemote);
        return localResource;
    }
    /* (non-Javadoc)
     * @see at.spardat.xma.boot.cache.IFileCache#openResource(at.spardat.xma.boot.transport.XMA_URI, java.lang.String, at.spardat.xma.boot.cache.VersionNumber, boolean)
     */
    public IFileCacheResource openResource(XMA_URI resource,String hash,VersionNumber serverVers,boolean bforcethrows IOException {
        URL urlRemote = resource.getHTTP_URI();
        if ( urlRemote == null || !isCacheable(urlRemote)) {
            throw new IllegalArgumentException"resource is not cacheable:" + urlRemote); //$NON-NLS-1$
        }
        File file = getFile(urlRemote);
        IFileCacheResource temp = .getResource(file,urlRemote);
        if(temp!=null) {
            String currentHash = temp.getProperty(.);
            if(hash.equals(currentHash)) {
                if(!temp.isExpired() && !bforce) {
                    return temp;  // found in cache, resource is not expired and an update force was not requested
                }
            } else {
                temp=null// wrong version cached -> unconditional get needed
            }
        }
        // not cached, download it
        URL downloadURL = urlRemote;
        if(hash!=null) {
            try {
                if(serverVers!=null && serverVers.compareTo(new VersionNumber(1,6,0))>=0) {
                    downloadURL = new URL(VersionNumber.insertHash(downloadURL.toExternalForm(),hash));
                } else {
                    if(urlRemote.getQuery()==nulldownloadURL = new URL(downloadURL+"?hash="+hash);
                    else downloadURL = new URL(downloadURL+"&hash="+hash);
                }
            } catch (MalformedURLException mue) {
                MalformedURLException ne = new MalformedURLException("error constructing download URL "+downloadURL.toString());
                ne.initCause(mue);
                throw ne;
            }
        }
        Result result = loadResource(downloadURL,
                              temp!=null ? temp.getLastModified():0L,
                              temp!=null ? temp.getProperty(.):null,
                              null );
        // and save it
        temp = .storeResource(file,result,urlRemote,temp,false,bforce);
        temp.setProperty(.,hash);
        return temp;
    }

    
load resource from server

Parameters:
urlRemote url to load
lastModified info for last modified
Returns:
Result result got from transport
Throws:
CommunicationException by transport
    private Result loadResource(URL urlRemotelong lastModifiedString etagIRtXMASessionClient session  ) throws MalformedURLExceptionCommunicationException {
      /* locals ---------------------------------- */
        Result      result     = null;
        XMA_URI     resource   = new XMA_URI(urlRemote);
        Transport   transport  = (Transport)Transport.getTransport();
      /* end locals ------------------------------ */
       result = transport.getResource(sessionresourcelastModifiedetag);
       ifresult == null ) {
           throw new IllegalStateException"Transport result object must not be null"); //$NON-NLS-1$
       }
      return result;
    } // loadResource
    /*
     *  (non-Javadoc)
     * @see at.spardat.xma.cdb.cache.IFileCache#invalidateResource(java.net.URL)
     */
    public void invalidateResourceURL urlRemote ) {
        File file = this.getFile(urlRemote);
        try {
            .removeResource(file);
        } catch (IOException exc) { // just log and continue
            .log(.,"error removing "+file.getAbsolutePath(),exc);
        }
    }
    /*
     *  (non-Javadoc)
     * @see at.spardat.xma.cdb.cache.IFileCache#invalidateResource(at.spardat.xma.cdb.cache.IFileCacheResource)
     */
    public synchronized void invalidateResourceIFileCacheResource ifcr ) {
        try {
            .removeResource((FCResource)ifcr);
        } catch (IOException exc) { // just log and continue
            .log(.,"error removing "+((FCResource)ifcr)..getAbsolutePath(),exc);
        }
    }

    
Returns whether the resource can be cached.

Parameters:
source url to check
Returns:
true if we can cache this protocoll
    public static boolean isCacheable(URL source) {
      if (source == null)
       return false;
      if (source.getProtocol().equals. ))
        return true;
      if (source.getProtocol().equals.))
        return true;
     return false;
    }

    
check�s if there is already a local copy of this remote URL

Parameters:
urlRemote remote URL to check for a local cached copy
Returns:
returns true if the resource is in the cache
Throws:
IllegalArgumentException if the source is not cacheable
See also:
java.net.URL
    public boolean isCached(URL urlRemote) {
        boolean  isCached = false;
        FCResource fcr = null;
        try {
            File file = this.getFile(urlRemote);
            fcr = new FCResource(urlRemote,filefalse,.booleanValue());
            if(fcr != null) {
                isCached = true;
            }
        } catch(IOException ex ) {
            .log(.,"error checking "+urlRemote.toString(),ex);
            isCached = false;
        }
        return isCached;
    }


    
map�s the remote-url to a file location in the chache directoy.

Parameters:
urlRemote url that should be mapped to a filename
Returns:
File the file representation of this url
    private File getFile(URL urlRemote) {
      /* locals ---------------------------------- */
        StringBuffer path;
        File         lFile;
      /* locals ---------------------------------- */
        path  = Util.getInstance().urlToPath(urlRemote);
        lFile = new File.getBaseDir(), path.toString());
      return lFile;
    }
    /* (non-Javadoc)
     * @see at.spardat.xma.boot.cache.IFileCache#getBaseDir()
     */
    public File getBaseDir() {
        return .getBaseDir();
    }
    /* (non-Javadoc)
     * @see at.spardat.xma.boot.cache.IFileCache#isCachedAndValid(at.spardat.xma.boot.transport.XMA_URI, java.lang.String)
     */
    public boolean isCachedAndValid(XMA_URI uri,String hash) {
        return isCachedAndValid(openLocalResource(uri),hash);
    }
    /* (non-Javadoc)
     * @see at.spardat.xma.boot.cache.IFileCache#isCachedAndValid(at.spardat.xma.boot.cache.IFileCacheResource, java.lang.String)
     */
    public boolean isCachedAndValid(IFileCacheResource resource,String hash) {
        if(resource==nullreturn false;
        if(resource.isExpired()) return false;
        if(hash!=null) {
            String storedHash = resource.getProperty(.);
            return hash.equals(storedHash);
        }
        return true;
    }
// end FileCache
New to GrepCode? Check out our FAQ X