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 /
 
 
 /*
  * @(#) $Id: FileCacheStore.java 2084 2007-11-27 14:53:31Z s3460 $
  */
 package at.spardat.xma.boot.cache;
 
 import java.io.File;
 import java.net.URL;
 import java.util.Date;
 import java.util.Set;
 
file storage of the file cache

Author(s):
s2877
Since:
1.3.0
 
 public class FileCacheStore {

    
logger
 
     private Logger log_;

    
debug file output
 
     private Boolean debug;

    
file lock timeout (milliseconds)
 
     private static int lockTimeout  = 30000;
     private static int sleepOnLock  =  150;

    
The root directory for this file cache. it is defined as <xma-basedir>/<cachedir-name>/
 
     private File baseDir_;

    
used to format if-modified-since correctly
 
     private DateFormat formater;


    

Throws:
java.io.IOException containing the filename
 
     FileCacheStore(BootRuntime brtthrows IOException {
          = Logger.getLogger"boot.cache" ); //$NON-NLS-1$
         setBaseDirbrt.getDataDirectory());
          = brt.getDebug();
          = new SimpleDateFormat"EEE, dd MMM yyyy HH:mm:ss zzz". );            //$NON-NLS-1$
         .setTimeZone(new SimpleTimeZone(0, "GMT")); //$NON-NLS-1$
     }


    

Returns:
the directory for this cache.
 
     File getBaseDir() {
         return ;
     }

    
sets the root directory

Parameters:
fbaseDir the base directory for the boot runtime.
Throws:
java.io.IOException containing the filename
 
     private void setBaseDir(File fbaseDirthrows IOException {
         if( !fbaseDir.exists())
           throw new IllegalArgumentException"base directory' "+fbaseDir.getAbsolutePath()+" 'for file-cache does not exist"); //$NON-NLS-1$
 
       File fCacheDir = new FilefbaseDir.);
       if( !fCacheDir.exists()) {
           boolean success = fCacheDir.mkdirs();
           if(!successthrow new IOException("error creating "+fCacheDir.getAbsolutePath());
       }
       this. = fCacheDir;
    }

    
Retrieve a resource from the cache.

Parameters:
resourceFile the File to retrieve
urlRemote the ULR of the resource on the server
Returns:
the found resource or null if it is not allready cached.
    public FCResource getResource(File resourceFile,URL urlRemote) {
        try {
            return new FCResource(urlRemoteresourceFilefalse.booleanValue());
        } catch (FileNotFoundException ex) {
            .log(."file not cached: \"{0}\""resourceFile.toString()); //$NON-NLS-1$
        } catch (IOException ioe) { // if we can't read it, we don't have it
            .log(."error reading "+resourceFile.getAbsolutePath(),ioe);
        }
        return null;
    }

    
Put a resource into the cache.

Parameters:
file to write the content into
result content of the resource as received from the server
urlRemote of the content on the server
temp old expired version of the resource if exists in the cache
bmode if true the content of the resource file is read into memory imeditately
bforce indicates if an update of the resource was forced
Throws:
java.io.IOException containing the filename
    public FCResource storeResource(File file,Result result,URL urlRemote,IFileCacheResource temp,boolean bmodeboolean bforcethrows IOException {
        FCResource fcr;
        File flock = lock(file);
        try {
            if(result.isModified() && temp!=null && ( temp.isExpired() || bforce == true) ) {
                iffile.delete() == false ) {
                    .log(."file could not be deleted: \"{0}\""file.toString() );                 //$NON-NLS-1$
                }
            }
            /* the resource was updated and a modified resource was loaded */
            ifresult!=null && result.isModified()) {
                saveContent(file,result.getBuffer());
                createPropertyFile(file,result,urlRemote);
            }
            fcr = new FCResource(urlRemote,filebmode,.booleanValue());
            /* the resource was checked for an updated, but was not modified */
            if(!result.isModified()) {
                fcr.setLastUpdated( System.currentTimeMillis() );
                fcr.setExpiration(result.getExpirationDate());
                fcr.store();
            }
        } finally {
           unlock(flock);
        }
        return fcr;
    }
    
Put a resource into the cache.

Parameters:
file to write the content into
result the resource as received from the server
content to store into the file
urlRemote of the content on the server
bmode if true the content of the resource file is read into memory imeditately
Throws:
java.io.IOException containing the filename
    public FCResource storeResource(File fileResult resultbyte[] contentURL urlRemoteboolean bmodethrows IOException {
        FCResource fcr;
        File flock = lock(file);
        try {
            saveContent(file,content);
            createPropertyFile(file,result,urlRemote);
            fcr = new FCResource(urlRemote,filebmode,.booleanValue());
        } finally {
            unlock(flock);
        }
        return fcr;
    }

    
lock a resource by creating a lock file for the resource fres .

this is done by creating a new file with createNewFile. If an existing lockfile is already found, it checks its validity. that means, the file must not be older than lockTimeout . Older lockfiles are removed.

As other processes will not notify this process about lockfile changes, this process will poll for changes. It waits sleepOnLock between each retry.

After a lockfile is remove by one process, another process may create a new lockfile in between the delete and our retry for creation. Therefore it only tries and waits for unlocking 3 times.

Parameters:
fres the resource to lock. this is the base resource, without lock extension
Returns:
File the lock-file
Throws:
java.io.IOException containing the filename
    File lockFile fres ) throws IOException {
        int tryLocking = 0;
        File lock = new Filefres.getPath() + . ); // lockfile
        if( !lock.exists()) lock.getParentFile().mkdirs();
        try {
            whiletryLocking < 3 && lock.createNewFile() == false ) {
            // already existing lock-file. wait for unlock
                long fTime = 0L;
                long cTime;
                tryLocking++;
               do {
                 // check if the lockfile is already too old
                 long ltime = lock.lastModified();
                 if (ltime == 0L )    break;         // 0 if it does not exist anymore
                 iffTime == 0L )    fTime = ltime// save the current file-time
                 ifltime != fTime ) break;         // if this new time differs, a new file has been created.
                 cTime = System.currentTimeMillis();
                 if( (cTime-fTime) >= this.getLockTimeout() ) { // too old; invalid; cleanup
                   lock.delete(); // this may also fail, if meanwhile another process has deleted this file.
                   break;
                 }
                try { Thread.sleepgetSleepOnLock() );
                 } catch (InterruptedException e) { }
               } while( ((cTime-fTime) < this.getLockTimeout()) && lock.exists() );
          } // while createNewFile
      } catchIOException e ) {
          IOException ne = new IOException("error creating lock file "+lock.getAbsolutePath());
          ne.initCause(e);
          throw ne;
      }
      return lock;
    }

    
unlock a resource

Parameters:
file the lockfile
Returns:
void
    void unlockFile file ) {
        if( !file.exists()) {
            // throw new IllegalArgumentException("lockfile does not exist");
        }
        .log(."locked for: {0} ms; file: {1}",  new Object[] { new Long( System.currentTimeMillis()-file.lastModified()), file.getName() }); //$NON-NLS-1$
        iffile.delete() == false )
          .log(."lockfile delete failed: \"{0}\""file.getName() );         //$NON-NLS-1$
    }// unlock

    

Returns:
long lock timeout
    private long getLockTimeout() {
        return ;
    }

    
returns the sleep time in between file-lock polling

Returns:
int sleep time
    private static int getSleepOnLock() {
        return ;
    }

    
saves transport result to disk.

Parameters:
file file to save information to
result transport result
Throws:
java.io.IOException containing the filename
    void saveToDisk(File fileResult resultURL urlthrows IOException {
       saveContent(file,result.getBuffer());
       createPropertyFile(file,result,url);
    }

    
Stores the given data into the given file. If the file does not exist, it is created together with needed parent directories. If it exists it is overwritten.

Parameters:
file to write
data to write into the file
Throws:
java.io.IOException containing the filename if an I/O Error occures
    void saveContent(File filebyte[] datathrows IOException {
        OutputStream os = null;
        try {
            if (!file.exists()) {
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            os = new FileOutputStream(file);
            os.write(data);
            Util.close(os,file.getAbsolutePath());
        } catch (IOException exc) {
            Util.close(os,file.getAbsolutePath());
            if (file.exists()) file.delete();
            IOException ne = new IOException("saving of '"+file.getAbsolutePath()+"' failed.");
            ne.initCause(exc);
            throw ne;
        }
    }

    
Creates the .ifo file corresponding to the given file and writes the properties of the FCResource into it. These are the http-headers contained in 'result', the url and for .jar files the Hashvalue.

Parameters:
file data file
result data received from the server
url of the corresponding resource on the server
Throws:
java.io.IOException containing the filename
    void createPropertyFile(File file,Result resultURL urlthrows IOException {
        PropertyFile pf = null;
        try {
          // make shure, no old file lies around.
          File ifoFile = new Filefile.getPath() + .);
          if(ifoFile.exists()) ifoFile.delete();
          pf = new PropertyFilenew Filefile.getPath() + .) ,.booleanValue());
          pf.setPropertyNoflush.,      Long.toString(result.getExpirationDate() ));
          if(.booleanValue()) {
             pf.setPropertyNoflush(. + ".STR".format(new Date(result.getExpirationDate())) );
          }
          pf.setPropertyNoflush., Long.toString(result.getLastModified()   ));
          if(.booleanValue()) {
             pf.setPropertyNoflush(. + ".STR".format(new Date(result.getLastModified())) );
          }
          pf.setPropertyNoflush(., Long.toString(result.getContentLength()  ));
          long lLastUpdated = System.currentTimeMillis();
          pf.setPropertyNoflush(.,   Long.toString(lLastUpdated));
          if(.booleanValue()) {
             pf.setPropertyNoflush(. + ".STR".format(new Date(lLastUpdated)) );
          }
          pf.setPropertyNoflush(.,         url.toExternalForm() );
          if(result.getEtag() != null ) pf.setPropertyNoflush.result.getEtag());
          .log."cached new resource: \"{0}\""url.toExternalForm()); //$NON-NLS-1$
          ifurl.getQuery() == null && file.toString().endsWith".jar") ) {
              JarFile jarfile = new JarFile(file);
              try {
                  Manifest manifest = jarfile.getManifest();
                  Attributes attributes = manifest.getMainAttributes();
                  if(attributes!=null) {
                    String strApplicationDigest = attributes.getValue(.);
                    ifstrApplicationDigest!=null) {
                        pf.setPropertyNoflush.strApplicationDigest);
                    }else {
                        .log(."Missing XMA-Digest for jarfile: " + url.toExternalForm() );
                    }
                  } else {
                      .log(."Attributes missing for jarfile:" + url.toExternalForm() );
                  }
              } finally {
                  try {
                      jarfile.close();
                  } catch (IOException arg) {
                      .log(.,"error closing "+file.getAbsolutePath(),arg);
                  }
              }
          }
          ifurl.getQuery()==null && ( file.toString().endsWith".jar") || file.toString().endsWith".xml")) ) {
              pf.setPropertyNoflush(."0" );
          }
          if(result.getTransformations()!=null) {
              pf.setPropertyNoflush(.,result.getTransformations());
          }
          pf.store();
       /* cleanup all file resources on any error */
       } catchException exc ) {
           iffile.exists()) file.delete();
           ifpf!=null) {
               File f = pf.getStoreFile();
               iff!=null && f.exists()) {
                   f.delete();
               }
           }
           IOException ne = new IOException("saving of '"+file.getAbsolutePath()+"' failed.");
           ne.initCause(exc);
           throw ne;
       }
    }

    
deletes both files of the given FCResouce.

Parameters:
res to delete
Throws:
java.io.IOException containing the filename if the file locking failed
    void removeResource(FCResource resthrows IOException {
        remove(res.getResourceFile(),res.getProperties());
    }

    
deltes the given file and its corresponding .ifo file.

Parameters:
file to delete
Throws:
java.io.IOException containing the filename if the file locking failed
Since:
1.3.1
    void removeResource(File filethrows IOException {
        remove(file,new Filefile.getPath() + .));
    }

    
Removes a file together with its .ifo file.

Parameters:
fRes resource file to delete
fProp corresponding .ifo file to delete
Throws:
java.io.IOException containing the filename
    private void remove(File fRes,File fPropthrows IOException {
        File lock = lock(fRes);
        try {
            iffRes.delete() == false) {
                .log(."delete of resource failed: {0}",  fRes.getAbsolutePath() ); //$NON-NLS-1$
            }
            iffProp.delete() == false ) {
                .log(."delete of property failed: {0}",  fProp.getAbsolutePath() ); //$NON-NLS-1$
            }
        } finally {
            unlock(lock);
        }
    }

    
Find the latest previous version of the given file. This is the file with the same name containing the greatest version number less than the the version of the given file. If the name of the file does not contain a valid version number, nothing will be found. If there are more than one file with the same version number but different hash values, they will be ignored.

Parameters:
file for which to search the previous version
Returns:
the found resource or null.
    public FCResource findPreviousVersion(final File file) {
        File dir = file.getParentFile();
        VersionNumber currentVersion = VersionNumber.parse(file.getName());
        if(currentVersion==nullreturn null;
        FilenameFilter filter = new FilenameFilter() {
            final Pattern pattern = VersionNumber.searchPattern(file.getName());
            public boolean accept(File dirString name) {
                return .matcher(name).matches();
            }
        };
        String[] oldNames = dir.list(filter);
        // find newest version older than current version
        // if there are more than on file for a version this particual version must be ignored!
        Set duplicates = new HashSet();
        VersionNumber oldVersion = null;
        int index = -1 ;
        if(oldNames!=null) {
            boolean found=false;
label:      do {
                oldVersion = null;
                index = -1;
                for(int i=oldNames.length-1;i>=0;i--) {
                    VersionNumber version = VersionNumber.parse(oldNames[i]);
                    if(currentVersion.compareTo(version)<=0) continue// newer or equal current version
                    if(duplicates.contains(version)) continue// known duplicate -> ignore
                    if(version.equals(oldVersion)) {  // new duplicate found
                        duplicates.add(version);      // -> add to known dupplicates
                        continue label;               // and restart search
                    }
                    if((oldVersion==null || oldVersion.compareTo(version)<0)) {
                        oldVersion=version;
                        index=i;
                    }
                }
                found=true;
            } while(!found);
        }
        if(oldVersion!=null) { // previous version found load and return it
            try {
                FCResource res = new FCResource(null,new File(dir,oldNames[index]),false,.booleanValue());
                res.versionNumber=oldVersion;
                return res;
            } catch (IOException e) {
                .log(.,"error reading "+dir.getAbsolutePath()+.+oldNames[index]+": ",e);
                return null;
            }
        } else {
            return null;
        }
    }
New to GrepCode? Check out our FAQ X