AddFileProcess.java :  » Source-Control » sourcejammer » org » sourcejammer » client » gui » process » Java Open Source

Java Open Source » Source Control » sourcejammer 
sourcejammer » org » sourcejammer » client » gui » process » AddFileProcess.java
/*
 *  Copyright (C) 2001, 2002 Robert MacGrogan
 *
 *  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 (at your option) 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 *
 * $Archive: SourceJammer$
 * $FileName: AddFileProcess.java$
 * $FileID: 4143$
 *
 * Last change:
 * $AuthorName: Rob MacGrogan$
 * $Date: 7/26/03 1:59 AM$
 * $Comment: Allow user to configure certain types of files to be
 *          ignored by SJ (not added or shown in "sync view") by adding
 *          extensions to ignore section of filehist.props.$
 */

package org.sourcejammer.client.gui.process;

import org.sourcejammer.client.gui.process.info.AddFileProcessInfo;
import org.sourcejammer.client.plugin.EventTimingType;
import org.sourcejammer.client.gui.action.ActionCentral;
import java.io.File;
import org.sourcejammer.client.gui.CommandCentral;
import org.sourcejammer.client.gui.GUICommandException;
import org.sourcejammer.client.gui.MessageBoxUtil;
import org.sourcejammer.util.SourceJammerConnectionException;
import java.awt.Cursor;
import javax.swing.JOptionPane;
import org.sourcejammer.project.view.Project;
import org.sourcejammer.project.view.SJRequest;
import org.sourcejammer.project.Node;
import org.sourcejammer.project.NodeDoesNotExistException;
import org.sourcejammer.project.NodeIterator;
import java.util.Hashtable;
import java.util.Vector;
import java.util.Iterator;
import org.sourcejammer.client.filesys.FileDirectoryFilter;
import org.sourcejammer.project.view.NodeInfo;
import org.sourcejammer.client.HistoryTypeMapper;
import org.sourcejammer.client.SourceJammerClient;
import org.sourcejammer.util.AppConfig;
import org.sourcejammer.client.DisplayTextLibrary;

/**
 * Title: $FileName: AddFileProcess.java$
 * @version $VerNum: 7$
 * @author $AuthorName: Rob MacGrogan$<br><br>
 * 
 * $Description: $
 * $KeyWordsOff: $<br><br>
 */
public class AddFileProcess extends AbstractProcess {

  public static final long MAX_FILE_SIZE_FOR_DIFF = 1024 * 500; //500k

  private static final int SKIP_FILE = 0;
  private static final int SKIP_ALL = 1;
  private static final int DONT_SKIP = 2;
  private static final int SKIP_NONE = 3;

  private boolean mbSkipAll = false;
  private boolean mbSkipNone = false;

  public AddFileProcess() {
  }
  public void process(Object info) {
    CommandCentral oCommand = CommandCentral.getInstance();
    try{
      if (info instanceof AddFileProcessInfo){
        AddFileProcessInfo addInfo = (AddFileProcessInfo)info;
        oCommand.getRootAppFrame().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        if (! addInfo.getRecursive()){
          if (addInfo.getSelectedFiles() != null && addInfo.getSelectedFiles().length > 0 ){
            for (int i =  0; i < addInfo.getSelectedFiles().length; i++){
              File fl = new File(addInfo.getDefaultDirectory(), addInfo.getSelectedFiles()[i]);

              if (! fl.exists()){
                //Could be a directory.
                fl = new File(fl.getParentFile(), fl.getName().substring(3));
              }

              if (fl.isFile()){
                addFile(addInfo.getParentProjectID(), addInfo.getSelectedFiles()[i],
                            fl.getAbsolutePath(), addInfo.getFileType(),
                            addInfo.getHistoryType(), addInfo.getDescription(),
                            addInfo.isOverrideDefaultHistTypes(), addInfo.getAfterAddAction(),
                            addInfo.getRequest());
              }
              else{
                //it's a directory.
                addDirectoryContents(addInfo.getParentProjectID(), fl, 
                                     addInfo.getFileType(), addInfo.getHistoryType(),
                                     addInfo.getDescription(), addInfo.isOverrideDefaultHistTypes(),
                                     addInfo.getAfterAddAction(), addInfo.getRequest());
              }
            }//end for
            ActionCentral.getInstance().fireActionInvokeLater(ActionCentral.act_REFRESH_PROJECT);
          }//end if user selected some files
        }//end if not recursive
        else{
          addAllContents(addInfo.getParentProjectID(), addInfo.getDefaultDirectory(),
                          addInfo.getFileType(), addInfo.getHistoryType(),
                          addInfo.getDescription(), addInfo.isOverrideDefaultHistTypes(),
                          addInfo.getAfterAddAction(), addInfo.getRequest());
          ActionCentral.getInstance().fireActionInvokeLater(ActionCentral.act_REFRESH_PROJECT);
        }//end else is recursive
        oCommand.out.println("--->" + DisplayTextLibrary.displayText(DisplayTextLibrary.MSG_ADD_COMPLETE) + "<---");

        //Notify file listeners
        SourceJammerClient.getInstance().getFileListeners().
                notifyFileAdded(addInfo.getRequest(), null,
                                EventTimingType.AFTER_EVENT, null);

      }//end if AddFileProcessInfo
    }
    catch (Throwable ex){
      ex.printStackTrace();
      MessageBoxUtil.displayErrorMessage(ex.getMessage());
    }
    finally {
      CommandCentral.getInstance().getRootAppFrame().setCursor(Cursor.getDefaultCursor());
    }
  }

  private void addDirectoryContents(long parentID, java.io.File dir, int fileType,
              int historyType, String description, boolean isOverride,
              String afterAddAction, SJRequest request)
         throws java.io.IOException, GUICommandException, SourceJammerConnectionException{

    Project proj = CommandCentral.getInstance().retrieveProject(parentID);
    String newProjName = dir.getName();
    long newProjUniqueID = -1;
    try{
      Node nd = proj.childList().getNode(newProjName);
      newProjUniqueID = nd.getUniqueID();
    }
    catch (NodeDoesNotExistException ex){
      //need to make project.
      newProjUniqueID = CommandCentral.getInstance().makeProject(parentID, newProjName);
    }
    addAllContents(newProjUniqueID, dir, fileType, historyType, description, isOverride, afterAddAction, request);
  }              
  

   private void addAllContents(long parentID, java.io.File fl, int fileType,
              int historyType, String description, boolean isOverride,
              String afterAddAction, SJRequest request)
         throws java.io.IOException, GUICommandException, SourceJammerConnectionException{
    if (! fl.isDirectory()){
      throw new java.io.IOException("Non-directory passed in to addAllContents()");
    }

    CommandCentral oCommand = CommandCentral.getInstance();

    //Get project so we can add only files/projects that don't already exist.
    Project proj = oCommand.retrieveProject(parentID);

    Iterator newFiles = getNewFiles(fl, proj);
    while(newFiles.hasNext()){
      File child = (File)newFiles.next();
      String fileName = child.getName();
      if (child.isFile()){
        addFile(parentID, child.getName(), child.getAbsolutePath(), fileType, historyType, description, isOverride, afterAddAction, request );
      }
      else if (child.isDirectory()){
        long lProjectID = oCommand.makeProject(parentID, child.getName());
        //This looks pretty weird and there might be a better way, but this works.
        NodeInfo nd = new NodeInfo();
        nd.setNodeName(child.getName());
        nd.setUniqueID(lProjectID);
        try{
          proj.childList().addNode(nd);
        }
        catch (org.sourcejammer.project.NodeExistsException ex){
          throw new GUICommandException("Can't add project node to local list--" + child.getName() + ".");
        }
      }
    }//end while more children to add.

    //Now go through all sub-directories (not just new ones) and try to add contents.
    File[] subdirs = fl.listFiles(new FileDirectoryFilter());
    if (subdirs != null && subdirs.length > 0){
      for (int i = 0; i < subdirs.length; i++){
        String dirName = subdirs[i].toString();
        dirName = extractFileName(dirName);
        try{
          long lNextProjID = proj.childList().getNode(dirName).getUniqueID();
          addAllContents(lNextProjID, subdirs[i], fileType, historyType, description, isOverride, afterAddAction, request);
        }//end try
        catch (org.sourcejammer.project.NodeDoesNotExistException ex){
          throw new GUICommandException("Can't find expected project--" + dirName + ".", ex);
        }
      }//end for
    }//end if

  }

  private Iterator getNewFiles(File dir, Project proj){
    Vector newFiles = new Vector();
    NodeIterator itr = proj.childNodes();
    Hashtable hshExistingNodes = new Hashtable();
    while(itr.hasMoreNodes()){
      hshExistingNodes.put(itr.getNextNode().getNodeName(), "placeholder");
    }
    //These lines ensures that the .source.jam file and the old source.jam file will not be added.
    hshExistingNodes.put(org.sourcejammer.client.filesys.SourceVersionChecker.LOCAL_FILE_INFO_FILE_NAME, "placeholder");
    hshExistingNodes.put(org.sourcejammer.client.filesys.SourceVersionChecker.OLD_FILE_INFO_FILE_NAME, "placeholder");

    //At this point, we have a hashtable with a "key" for each project/file
    //in the project.

    if (dir.exists() && dir.isDirectory() ){
      File[] flChildren = dir.listFiles();
      for (int i = 0; i < flChildren.length; i++){
        String fileName = flChildren[i].toString();
        fileName = extractFileName(fileName);
        if ((hshExistingNodes.get(fileName)) == null){
          newFiles.addElement(flChildren[i]);
        }
      }//end for
    }//end if is directory
    return newFiles.iterator();
  }

  private String extractFileName(String fileName){
    String sName = fileName;
    int index = fileName.lastIndexOf(File.separator);
    if (index != -1 && index != fileName.length() - 1){
      sName = fileName.substring(index+1);
    }
    return sName;
  }

  private void addFile(long lParentProjectID, String sFileName, String filePath,
                       int fileType, int historyType, String description,
                       boolean overrideHistoryType, String afterAddFileAction,
                       SJRequest request )
          throws java.io.IOException, SourceJammerConnectionException, GUICommandException{
    CommandCentral oCommand = CommandCentral.getInstance();
    oCommand.getRootAppFrame().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    boolean skipFile = false;
    if (! overrideHistoryType ){
      HistoryTypeMapper typeMapper = HistoryTypeMapper.getInstance();
      String sType = typeMapper.getDefaultHistoryTypeForFile(sFileName);
      //Interpret type to file type and history type.
      if (sType.equals(HistoryTypeMapper.TEXT_LIST)){
        fileType = AppConfig.FileTypes.TEXT;
        historyType = AppConfig.FileHistoryStorageTypes.DIFF;
      }
      else if(sType.equals(HistoryTypeMapper.IGNORE_LIST)){
        skipFile = true;
      }
      else{
        fileType = AppConfig.FileTypes.BINARY;
        if (sType.equals(HistoryTypeMapper.BIN_COMPRESSED_LIST)){
          historyType = AppConfig.FileHistoryStorageTypes.ZIP;
        }
        else if(sType.equals(HistoryTypeMapper.BIN_CURR_ONLY_LIST)){
          historyType = AppConfig.FileHistoryStorageTypes.CURR_VERSION_SOURCE_ONLY;
        }
        else if(sType.equals(HistoryTypeMapper.BIN_DIFF_LIST)){
          historyType = AppConfig.FileHistoryStorageTypes.DIFF;
        }
        else if(sType.equals(HistoryTypeMapper.BIN_FULL_LIST)){
          historyType = AppConfig.FileHistoryStorageTypes.FULL_SOURCE;
        }
        else{
          throw new org.sourcejammer.util.BadMethodArgumentException("Unrecognized history type: " + sType);
        }
      }
    }
    else{
      //Let's also check here if file should be skiped.
      HistoryTypeMapper typeMapper = HistoryTypeMapper.getInstance();
      String sType = typeMapper.getDefaultHistoryTypeForFile(sFileName);
      if (sType.equals(HistoryTypeMapper.IGNORE_LIST))
        skipFile = true;
    }
    if (! skipFile && isTypeAcceptable(filePath, historyType)){
      oCommand.addFile(lParentProjectID, sFileName, filePath, fileType, historyType, description, afterAddFileAction, request);
    }
    oCommand.getRootAppFrame().setCursor(Cursor.getDefaultCursor());
    //oCommand.getRootAppFrame().update(oCommand.getRootAppFrame().getGraphics());
  }

  private boolean isTypeAcceptable(String filePath, int historyType){
    boolean bOKToAdd = true;
    if (historyType == org.sourcejammer.util.AppConfig.FileHistoryStorageTypes.DIFF){
      java.io.File fl = new java.io.File(filePath);
      long lFileSize = fl.length();
      if ( lFileSize > MAX_FILE_SIZE_FOR_DIFF){
        if (! mbSkipAll && ! mbSkipNone){
          DisplayTextLibrary textLib = DisplayTextLibrary.getInstance();
          String[] msg2 = textLib.getDisplayTextArray(DisplayTextLibrary.MSG_TOO_BIG_2);
          String[] messages = new String[msg2.length + 4];
          messages[0] = textLib.getDisplayText(DisplayTextLibrary.MSG_TOO_BIG_1);
          messages[1] = " ";
          messages[2] = filePath;
          messages[3] = " ";
          for (int i = 0; i < msg2.length; i++){
            messages[i + 4] = msg2[i];
          }

          String[] options = {textLib.getDisplayText(DisplayTextLibrary.BTN_SKIP),
                              textLib.getDisplayText(DisplayTextLibrary.BTN_SKIP_ALL),
                              textLib.getDisplayText(DisplayTextLibrary.BTN_DONT_SKIP),
                              textLib.getDisplayText(DisplayTextLibrary.BTN_SKIP_NONE)};

          int iResponse = JOptionPane.showOptionDialog(CommandCentral.getInstance().getRootAppFrame(),
                            messages,
                            textLib.getDisplayText(DisplayTextLibrary.LBL_SKIP),
                            JOptionPane.DEFAULT_OPTION,
                            JOptionPane.WARNING_MESSAGE,
                            null,
                            options,
                            textLib.getDisplayText(DisplayTextLibrary.BTN_SKIP));
          //Check which button user clicked.
          switch(iResponse){
            case SKIP_FILE:
              bOKToAdd = false;
              break;
            case SKIP_ALL:
              bOKToAdd = false;
              mbSkipAll = true;
              break;
            case DONT_SKIP:
              bOKToAdd = true;
              break;
            case SKIP_NONE:
              bOKToAdd = true;
              mbSkipNone = true;
              break;
          }//end switch
        }//end if not skip all and not skip none.
        else if (mbSkipAll){
          bOKToAdd = false;
        }
        else if(mbSkipNone){
          bOKToAdd = true;
        }
      }//end if greater than max size for diff.
    }//end if history type is diff.
    return bOKToAdd;
  }

  public static void main(String[] args){
    try{
        String[] messages = {"The following file may be too big to add with Diff history storage type:",
                             " ", "/usr/local/path/file.fi", " ",
                             "SourceJammer recommends that you select a different storage type option",
                             "for this file. You can skip this file now and add it later using a different",
                             "option.",
                             " ", "Do you want to skip this file?"};

        String[] options = {"skip", "skip all like this", "don't skip", "skip none like this"};

                int iResponse = JOptionPane.showOptionDialog(CommandCentral.getInstance().getRootAppFrame(),
                                    messages,
                                    "Skip file?",
                                    JOptionPane.DEFAULT_OPTION,
                                    JOptionPane.WARNING_MESSAGE,
                                    null,
                                    options,
                                    "skip");
      System.out.println(iResponse);
    }
    catch (Throwable thr){
      thr.printStackTrace();
    }

  }

}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.