alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

What this is

This file is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Other links

The source code

/*
 *                 Sun Public License Notice
 *
 * The contents of this file are subject to the Sun Public License
 * Version 1.0 (the "License"). You may not use this file except in
 * compliance with the License. A copy of the License is available at
 * http://www.sun.com/
 *
 * The Original Code is NetBeans. The Initial Developer of the Original
 * Code is Sun Microsystems, Inc. Portions Copyright 1997-2000 Sun
 * Microsystems, Inc. All Rights Reserved.
 */

package org.netbeans.modules.javacvs.caching;

/**
 *
 * @author  mkleint
 */
import org.netbeans.modules.javacvs.JavaCvsFileSystem;
import org.netbeans.modules.javacvs.commands.*;
import org.openide.util.*;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.AbstractFileSystem;
import java.util.*;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
import java.io.*;
import java.lang.ref.*;
import java.text.MessageFormat;
import org.netbeans.modules.vcscore.cache.*;


public class CvsFsCache extends java.lang.Object  implements CachedFileSystem {

    private static CommandLocker refreshLocker = new CommandLocker();
    
    private static String OLD_CACHEFILE = "CVS/netbeans.cache"; //NOI18N
    private static String NEW_CACHEFILE = "CVS/javacvs.cache"; //NOI18N
    
    protected AbstractFileSystem cvsfs;    
//    private HashMap fileStatuses = new HashMap();
    
//    protected static JavaCvsCache cacheObject = null;
    
    private PropertyChangeListener list;
    
    protected boolean offLine;
    protected boolean hideShadowFiles;
    protected int autoRefresh;
    protected File fsRootFile;
    
    
    /** Creates new CvsFsCache */
    public CvsFsCache(AbstractFileSystem fs, File homeDirectory) {
        cvsfs = fs;
        list = new PropertyChangeListener() {
            public void propertyChange(final PropertyChangeEvent event) {            
                propertiesChanged(event.getPropertyName(), event.getOldValue(), event.getNewValue());
            }            
        };
        fs.addPropertyChangeListener(WeakListener.propertyChange(list, fs));
   //     initFileStatuses();
//        JavaCvsCache cachObj = getCacheObject();
//        cachObj.setHomeDirectory(homeDirectory);
    }
    
    public void setOffLine(boolean offLine) {
        this.offLine = offLine;
    }
    
    public void setAutoRefresh(int refresh) {
        autoRefresh = refresh;
    }
    
    public void setHideShadowFiles(boolean hide) {
        hideShadowFiles = hide;
    }
    
    public void setFsRootFile(File fsRoot) {
        this.fsRootFile = fsRoot;
    }
    
    public static JavaCvsCache getCacheObject() {
        JavaCvsCache cacheObject;
        FileSystemCache cache = CacheHandler.getInstance().getCache(JavaCvsCache.JAVA_CACHE_NAME);
        if (cache == null) {
            cacheObject = new JavaCvsCache();
        } else {
            cacheObject = (JavaCvsCache)cache;
        }
        return cacheObject;
    }
    
    protected JavaCvsStatusManager getStatusManager() {
        return JavaCvsStatusManager.getInstance();
    }
    
    private void propertiesChanged(String propName, Object oldValue, Object newValue) {
        if (propName == null) return;
        if (propName.equals(JavaCvsFileSystem.PROP_OFF_LINE)) {
            Boolean off = (Boolean)newValue;
            offLine = off.booleanValue();
        }
        if (propName.equals(JavaCvsFileSystem.PROP_AUTO_REFRESH)) {
            Integer in = (Integer)newValue;
            autoRefresh = in.intValue();
        }
        if (propName.equals(JavaCvsFileSystem.PROP_HIDE_SHADOW_FILES)) {
            Boolean off = (Boolean)newValue;
            hideShadowFiles = off.booleanValue();
        }
        if (propName.equals(JavaCvsFileSystem.PROP_ROOT)) {
            FileObject foRoot = (FileObject)newValue;
            File rootFile = FileSystemCommand.toFile(foRoot);
            fsRootFile = rootFile;
        }
        
    }

    /** for strategies higher than STRAT_DISK, does adjustation depending 
     * on the value of filesystem's offLine property
     */
    protected int adjustStrategy (int reqStrategy) {
        if (reqStrategy > CacheHandler.STRAT_DISK) {
            if (offLine) return CacheHandler.STRAT_DISK;
        }
        return reqStrategy;
    }
    /** for strategies higher than STRAT_DISK, permit intended action depending
     * on the value of filesystem's offLine property
     */
    
    protected boolean permitAction(int reqStrategy) {
        if (reqStrategy > CacheHandler.STRAT_DISK) {
            if (offLine) return false;
        }
        return true;
    }

    protected void checkDirectoryAutorefresh(File directory, boolean waitForRefresh) {
        File cacheDir = new File(directory.getPath(), "CVS");  //NOI18N
        File cacheFile = new File(directory.getPath(), OLD_CACHEFILE); 
        File newCacheFile = new File(directory.getPath(), NEW_CACHEFILE); 
        if (cacheDir.exists() && !(cacheFile.exists() || newCacheFile.exists())) {
            try   {
//                System.out.println("refreshing=" + directory.getAbsolutePath());
                newCacheFile.createNewFile();
                doRefresh(new File[] {directory},  false, waitForRefresh);
            } catch (java.io.IOException exc) {}
        }
        
    }
    
    public String getFileStatusOnly(Vector importantFiles) {
        int currentStrategy;
/*        if (autoRefresh == JavaCvsFileSystem.AUTO_SIMPLE) {
            currentStrategy = CacheHandler.STRAT_DISK_OR_REFRESH;
        } else {
 */
            currentStrategy = CacheHandler.STRAT_DISK;
//        }
        int len = importantFiles.size();
        CacheFile file=null;
        String name;
        String fullName;
        String stat;

        //D.deb("len="+len); // NOI18N
        if( len < 1 ){
            return JavaCvsStatusManager.UNKNOWN;
        }
        else {
            if (autoRefresh == JavaCvsFileSystem.AUTO_SIMPLE) {
                name = (String) importantFiles.elementAt(0);
                File fl = new File(fsRootFile.getPath(), name);
                if (fl.getParent() != null) {
                    fl = fl.getParentFile();
                    checkDirectoryAutorefresh(fl, false);
                }
            }
            
            if( len==1 ){
                name = (String) importantFiles.elementAt(0);
                File fl = new File(fsRootFile.getPath(), name);
                //            System.out.println("filestatonly for=" + fl.getAbsolutePath());
                if (fl != null) {
                    file = CacheHandler.getInstance().getCacheFile(fl, adjustStrategy(currentStrategy), this);
                }
                if (file != null)  {
                    stat = file.getStatus();
                    //                System.out.println("fo=" + file.getName() + " stat=" + file.getStatus());
                }
                else stat = ""; // NOI18N
                return stat;
            }
        }
        // for multidata objects do the following
        //D.deb("status="+status); // NOI18N
        String result = JavaCvsStatusManager.NOT_IN_SYNCH;
        name = (String) importantFiles.elementAt(0);
//        String rootDir = cvsfs.getRootDirectory().getAbsolutePath();
//        fullName = rootDir + File.separator + name;
        File fl = new File(fsRootFile.getPath(), name);
        if (fl != null) {
            file = CacheHandler.getInstance().getCacheFile(fl, adjustStrategy(currentStrategy), this);
        }
        if (file != null) stat = file.getStatus();
        else stat = ""; // NOI18N
//        stat = file.getStatus();
        
        for(int i=1;i needs to be root!
                // do remove it manually..
                CacheDir dir = (CacheDir)file;
                CacheHandler.getInstance().getCache(this).unregisterDir(dir);
                return;
            }
            parentCache.removeChildDir(file.getName(), true);
        }
        else {
            if (parentCache != null) {
                parentCache.removeFile(file.getName(), true);
            }
        }
        //parentCache.setComplete(false);
    }

    
    public void renameTo(File oldFile, File newFile) {
        //TODO rewrite
        
        // first let's do remove old node in cache
        File parent = oldFile.getParentFile();
        CacheDir parentCache = (CacheDir)CacheHandler.getInstance().getCacheFile(parent, CacheHandler.STRAT_LOCAL, this);
        if (parentCache == null) { //root node.. is dir..cannot be renamed..
            return;
        }
        if (newFile.isDirectory()) { // the renamed node was a directory - do recursive rename
            CacheDir renamedCache = (CacheDir)parentCache.getSubDir(oldFile.getName());
            parentCache.removeChildDir(renamedCache.getName(),false);
            renamedCache.rename(new File(parentCache.getFilePath() + File.separator + newFile.getName()));
            parentCache.addChildDir(renamedCache,false);
            renamedCache.renameChildDirs(renamedCache,false);
        }
        else { // just a file - lets rename it in the paarent directory.. and it's done :)
            parentCache.removeFile(oldFile.getName(), true);
            CacheFile newCache = new CvsCacheFile(getCacheId(), newFile.getName());
            parentCache.addFile(newCache, true);
            return;
        }
        parentCache.setModifiedContent(true);
        parentCache.writeToDisk(); //write to disk immediately..
    }
    
/*    public CacheFile[] convertToCacheFiles(File[] files) {
        CacheFile[] cvsFiles = new CacheFile[files.length];
        for (int index = 0; index < files.length; index++) {
            cvsFiles[index] = handler.getCacheFile(files[index], CacheHandler.STRAT_DISK, this);
        }
        return cvsFiles;
    }
 */

    
    public String getLocker(Vector importantFiles) {
     //TODO   
      return ""; // NOI18N
    }


    /* checks if the Cache instance has all objects written to the disk. 
     * Is checked only when serializing the filesystems.
     * We need this check to aboid duplicate saving - since there's just one cache for all filesystems.
     */
    public void saveToDisk() {
       if (!CacheHandler.getInstance().getCache(this).isWrittenToDisk()) {
          CacheHandler.getInstance().getCache(this).writeAllToDisk(); 
       }
    }
    
    public void saveToDiskFromNode(String path) {
         File fl = new File(fsRootFile.getPath(), path);
         CacheDir dir = (CacheDir)CacheHandler.getInstance().getCacheFile(fl, CacheHandler.STRAT_NONE, this);
         if (dir != null) {
             dir.writeToDiskRecursively();
         }
    }
    
    
    public void fileModified(File modified, boolean fireEvent) {
        CacheFile cFile = CacheHandler.getInstance().getCacheFile(modified,CacheHandler.STRAT_NONE, this);
        if (cFile != null) { // should never be null.. just a I-want-to-be-sure check.
           String oldStatus = cFile.getStatus();
           if     (oldStatus.equals(JavaCvsStatusManager.LOCAL) 
                || oldStatus.equals(JavaCvsStatusManager.UNKNOWN)
                || oldStatus.equals(JavaCvsStatusManager.LOCALLY_REMOVED)
                || oldStatus.equals(JavaCvsStatusManager.NEEDS_MERGE)) return;
           if (oldStatus.equals(JavaCvsStatusManager.NEEDS_PATCH)) {
               cFile.setStatus(JavaCvsStatusManager.NEEDS_MERGE);
           } 
           else {
               cFile.setStatus(JavaCvsStatusManager.LOCALLY_MODIFIED);
           }
           cFile.getParent().writeToDisk();
           if (fireEvent) {
               getCacheObject().fireCacheHandlerEvent(JavaCvsCache.EVENT_CHANGED, cFile);
           }
        }
    }
    
    public void addRefreshDisplayers(CvsStatus comm) {
//        System.out.println("doing nothing here..");
    }    
    
    /**
     * Performs a refresh on the specified files.
     * @param files - expects either only files or only directories.
     * @param recursive performs recursive refresh or only in the directory.
     * 
     */
    public void doRefresh(File[] files, boolean recursive) {
      JavaCvsFileSystem fs = (JavaCvsFileSystem)cvsfs;
      if (fs == null) return;
      FileSystemCommandImpl statusComImpl = (FileSystemCommandImpl)fs.createRefresh();
      CvsStatus com = (CvsStatus)statusComImpl.getOuterClassInstance();
      com.setRecursive(recursive);
      com.setRefreshing(false);
      if (files != null && files.length > 0 && files[0].isDirectory()) {
          com.setRefreshing(true);
      }
      com.setFiles(files);
      addRefreshDisplayers((CvsStatus)com);
      refreshLocker.addToQueueAndRun(com);
/*        
        int  strategy = (recursive ? CacheHandler.STRAT_REFRESH_RECURS : CacheHandler.STRAT_REFRESH);
            // in this case, just apply a dir reading strategy that will handle that do us
             for (int index = 0; index < files.length; index++) {
               //REDO - once more commands on one connection -> use just one client 
               CacheFile cFile = handler.getCacheFile(files[index], strategy, this);        
             }
 */
/*
        int  strategy = (recursive ? CacheHandler.STRAT_REFRESH_RECURS : CacheHandler.STRAT_REFRESH);
        if (recursive) {
            files = findRelevantDirs(files);
            // 
            for (int i = 0; i < files.length; i++) {
                System.out.println("REFRESHED DIR=" + files[i]);
            }
            // 
        }
        // in this case, just apply a dir reading strategy that will handle that do us
        for (int index = 0; index < files.length; index++) {
            //REDO - once more commands on one connection -> use just one client
            File refFile = files[index];
            
            CacheFile cFile = handler.getCacheFile(files[index], strategy, this);
            E.err("CvsFsCache: ------- refresh started------" + files[index].getAbsolutePath());
        }
         */
    }
    
    public void doRefresh(File[] files, boolean recursive, boolean waitToFinish) {
        JavaCvsFileSystem fs = (JavaCvsFileSystem)cvsfs;
        if (fs == null) return;
        FileSystemCommandImpl statusComImpl = (FileSystemCommandImpl)fs.createRefresh();
        CvsStatus com = (CvsStatus)statusComImpl.getOuterClassInstance();
        com.setRecursive(recursive);
        com.setRefreshing(false);
        if (files != null && files.length > 0 && files[0].isDirectory()) {
            com.setRefreshing(true);
        }
        com.setFiles(files);
        final Object finishLock = new Object();
        if (waitToFinish) {
            com.addDisplayerListener(new org.netbeans.modules.javacvs.events.CommandDisplayerListener() {
                public void showBeforeEachExecute(org.netbeans.lib.cvsclient.command.Command currentCommand) {}
                public void showAfterEachExecute() {}
                public void showExecutionFailed(Exception exception) {
                    synchronized (finishLock) {
                        finishLock.notifyAll();
                    }
                }
                public void showFileInfoGenerated(org.netbeans.lib.cvsclient.command.FileInfoContainer info) {}
                public void showFinishedCommand() {
                    synchronized (finishLock) {
                        finishLock.notifyAll();
                    }
                }
                public void showStartCommand() {}
                public void messageGenerated(org.netbeans.lib.cvsclient.event.MessageEvent message) {}
            });
        }
        addRefreshDisplayers((CvsStatus)com);
        refreshLocker.addToQueueAndRun(com);
        if (waitToFinish) {
            synchronized (finishLock) {
                try {
                    finishLock.wait();
                } catch (InterruptedException intex) {}
            }
        }
    }
    
    
    public String getCacheId() {
        return JavaCvsCache.JAVA_CACHE_NAME;
    }    
    
    public Reference createReference(FileObject fo) {
        File file = new File(fsRootFile.getPath(), fo.getPackageNameExt(File.separatorChar,'.'));
        return CacheHandler.getInstance().createReference(fo, file, getCacheId());

    }
    
    public void removeNotify() {
        getCacheObject().unregisterFileSystem(cvsfs);
        list = null;
        cvsfs = null;
//        cvsfs.removePropertyChangeListener(list);
    }
    
    public void addNotify(AbstractFileSystem fs) {
        if (cvsfs == null) {
            cvsfs = fs;
            list = new PropertyChangeListener() {
                public void propertyChange(final PropertyChangeEvent event) {            
                    propertiesChanged(event.getPropertyName(), event.getOldValue(), event.getNewValue());
                }            
            };
            fs.addPropertyChangeListener(WeakListener.propertyChange(list, fs));
            getCacheObject().registerFileSystem(cvsfs);
        }
    }
    
}
... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.