CommandLineInterpreter.java :  » Source-Control » sourcejammer » org » sourcejammer » client » commandline » Java Open Source

Java Open Source » Source Control » sourcejammer 
sourcejammer » org » sourcejammer » client » commandline » CommandLineInterpreter.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: CommandLineInterpreter.java$
 * $FileID: 4198$
 *
 * Last change:
 * $AuthorName: Rob MacGrogan$
 * $Date: 8/10/03 1:37 AM$
 * $Comment: Use new SourceJammerClient propery names.$
 */


package org.sourcejammer.client.commandline;

import org.sourcejammer.project.view.*;
import org.sourcejammer.util.AppConfig;
import org.sourcejammer.util.ConfigurationException;
import org.sourcejammer.project.Node;
import org.sourcejammer.project.NodeExistsException;
import org.sourcejammer.project.NodeIterator;
import org.sourcejammer.client.SOAPPortal;
import org.sourcejammer.util.RepeatingResponse;
import org.sourcejammer.util.SourceJammerConnectionException;
import org.sourcejammer.util.BadMethodArgumentException;
import org.sourcejammer.util.ZipUtil;
import java.util.StringTokenizer;
import java.io.*;
import java.util.Vector;
import java.util.Enumeration;
import org.sourcejammer.util.StringUtil;
import org.sourcejammer.project.controller.LabelVersionMappingBean;
import org.sourcejammer.client.filesys.*;
import org.sourcejammer.client.SourceJammerClient;
import org.sourcejammer.project.view.DownloadFileIdentifier;
import org.sourcejammer.util.TempDirectoryManager;
import org.sourcejammer.client.FileTransport;
import org.sourcejammer.client.NoSessionException;
import org.sourcejammer.client.UploaderProxy;

/**
 * Title:        $FileName: CommandLineInterpreter.java$
 * @author $AuthorName: Rob MacGrogan$
 * @version $VerNum: 3$<br>
 * 
 * $Description: $<br>
 * $KeyWordsOff: $<br><br>
 * 
 * 
 * Primary class for interpreting and executing command line commands.
 */
public class CommandLineInterpreter implements SJResponseParams, SJRequestParams{

  public static final class Delimiters{
    public static final String SPACE = " ";
    public static final String PROJECT_DELIM = "/";
    public static final String QUOTE_MARK = "\"";
    public static final char C_SPACE = ' ';
    public static final char C_QUOTE_MARK = '\"';
  }

  public static final String TERM_MESSAGE = "goodbyecruelworld";
  public static final String TO_PARENT_DIR = "..";
  public static final String ALL_FILES_IN_DIR = "*";

  /**
   * jbm change start
   * jbm
   * jbm add getproj command
   * jbm
   *
   * Constants for getproj command
   */
  public static final String GETPROJ_CURRENT_PROJECT = ".";
  public static final String GETPROJ_RECURSE_PROJECT = "r";
  public static final String GETPROJ_NO_RECURSE_PROJECT = "nr";
  public static final String GETPROJ_MAKE_LOCAL_DIRS = "d";
  public static final String GETPROJ_NO_MAKE_LOCAL_DIRS = "nd";
  public static final String GETPROJ_VERIFY_CHECKIN = "v";
  public static final String GETPROJ_NO_VERIFY_CHECKIN = "nv";
  /**
   * jbm
   * jbm change end
   * jbm
   */


  public static final class FileTypes {
    public static String BINARY = "b";
    public static String TEXT = "t";
  }

  public static final class Implementations {
    public static String FILESYS = "f";
  }

  private String msUserName;
  private String msPassword;
  private String msArchiveName = null;
  private long mlSessionID = -1;
  private ViewNode ndProjectPointer = null;
  private java.io.File flLocalDirectory = null;
  private SOAPPortal moPortal = null;
  private String msCurrentPath = null;
  private String msUrl = null;
  private CLCommands cmdList = null;

  /**
   * This constructor always throws an exception.
   */
  public CommandLineInterpreter(){
    throw new ConfigurationException("Only the constructor CommandLineInterpreter(String) is allowed.");
  }

  public CommandLineInterpreter(String sURL) {
    //Set local directory to root.
    flLocalDirectory = new java.io.File("");
    flLocalDirectory = new java.io.File(flLocalDirectory.getAbsolutePath());
    //System.out.println("cl path - " + flLocalDirectory.getAbsolutePath());
    msUrl = sURL;
    moPortal = new SOAPPortal();
    try {
      moPortal.setURL(sURL);
    }
    catch (java.net.MalformedURLException ex){
      throw new ConfigurationException("The URL passed in is malformed.", ex);
    }
    cmdList = new CLCommands(this);
  }

  public String sendCommand(String command){
    //Lst's get rid of all end of line and carriage return characters.
    command = StringUtil.replaceSubstring(command, "\r", "");
    command = StringUtil.replaceSubstring(command, "\n", "");

    String sReturnMessage = null;
    if (! command.equals("")){
      String[] args = tokenizeCommand(command);
      String sCommand = args[0];
      sCommand = sCommand.trim();
//System.out.println("+ got command: " + sCommand);

      SJResponse response = null;
      if (msArchiveName == null &&
          ! sCommand.equals(CLCommands.Commands.CONNECT) &&
          ! sCommand.equals(CLCommands.Commands.HELP) &&
          ! sCommand.equals(CLCommands.Commands.EXIT) &&
          ! sCommand.equals(CLCommands.Commands.CHANGE_LOCAL_DIRECTORY) &&
          ! sCommand.equals(CLCommands.Commands.LIST_LOCAL_DETAILS) &&
          ! sCommand.equals(CLCommands.Commands.MAKE_ARCHIVE_DISCONNECTED )){
        sReturnMessage = "Not currently connected to an archive. Use con command.";
      }
      else{
        try {
          CLCommandResponse res = cmdList.executeCommand(sCommand, args);
          response = res.getResponse();
          if (response != null){
            sReturnMessage = updateStatusFromResponse(response, res.isUpdateProjectPointer());
          }
          else {
            sReturnMessage = res.getMessage();
          }
        }
        catch (CLCommandException ex){
          sReturnMessage = ex.getMessage();
        }
        catch (IOException ex){
          sReturnMessage = "Error:\r\nUnable to find or access local file.";
        }
        catch (ArrayIndexOutOfBoundsException ex){
          sReturnMessage = "Error: \r\nWrong number of arguments for command.\r\nFor a list of commands, type help.";
        }
        catch (SourceJammerConnectionException ex){
          sReturnMessage = "Error: \r\nSOAP error.\r\n" + ex.toString();
        }
        catch (Exception ex){
          sReturnMessage = "Error: \r\n" + ex.getMessage();
        }
      }
    }
    return sReturnMessage;
  }

  SJResponse getFile(String sjFileNameLocation)
        throws IOException, SourceJammerConnectionException {
    return getFile(sjFileNameLocation, null, AppConfig.getInstance().getDefaultEOLType());
  }

  String viewRemoved() throws SourceJammerConnectionException {
    SJRequest request = getBaseRequest();
    request.putLong(REQUESTED_NODE_UNIQUE_ID, ndProjectPointer.getUniqueID());
    SJResponse response = sendRequest(request, SOAPPortal.MCPMethodNames.VIEW_REMOVED_NODES);
    Object[] nodes = (Object[])response.objectValue(OBJECT_ARRAY);
    StringBuffer strRemovedNodes = new StringBuffer("Nodes removed from ");
    strRemovedNodes.append(ndProjectPointer.getNodeName())
                   .append(":\r\n");
    for (int iCounter = 0; iCounter < nodes.length; iCounter++){
      NodeInfo ndRem = (NodeInfo)nodes[iCounter];
      strRemovedNodes.append(iCounter)
                     .append("   ")
                     .append(ndRem.toString())
                     .append("\r\n");
    }
    updateStatusFromResponse(response, false);
    return strRemovedNodes.toString();
  }

  SJResponse getFile(String sjFileNameLocation, String localFileNameLocation, int eolType)
        throws IOException, SourceJammerConnectionException  {

    long lFileID = getFileUniqueID(sjFileNameLocation);
    long lLatestVersionID = getFileLatestVersionID(lFileID);
    String sFileName = null;
    if (localFileNameLocation == null){
      sFileName = getFileNameFromNameLocation(sjFileNameLocation);
      localFileNameLocation = flLocalDirectory.getAbsolutePath() +
            java.io.File.separator + sFileName;
    }

    //See if we need the file.
    java.io.File flLocation = new java.io.File(localFileNameLocation);
    SourceVersionChecker checker = getChecker(flLocation);

    SJResponse response = null;
    if (! checker.isFileCurrent(sFileName, lLatestVersionID)){
      SJRequest request = getBaseRequest();
      request.putLong(REQUESTED_NODE_UNIQUE_ID, lFileID);
      request.putInt(REQUESTED_EOL_TYPE, eolType);
      request.putInt(ZIP_BINARIES_LARGER_THAN, SourceJammerClient.getInstance().getZipIfLargerThan());
      response = sendRequest(request, SOAPPortal.MCPMethodNames.GET_FILE_LATEST_VERSION);
      if ( ! response.getErrorEncountered() ){

        DownloadFileIdentifier downloadId = response.downloadFileIdentifierValue();
        long lTempFileId = retrieveFileFromServer(downloadId, response);

        checker.saveFile(flLocation.getName(), lLatestVersionID, lTempFileId, true, new RepeatingResponse());
        response.setMessage("Got file " + sFileName + " to " + flLocation + ".");
      }
    }
    else{
      response = getFakeResponse();
      response.setMessage("Local version of " + sFileName + " is current. Did not download file.");
    }
    return response;
  }

  SJResponse checkInFile(String sjFileNameLocation, String comment)
        throws IOException, SourceJammerConnectionException  {


    long lFileID = getFileUniqueID(sjFileNameLocation);

    String sFileName = getFileNameFromNameLocation(sjFileNameLocation);
    String localFileNameLocation = flLocalDirectory.getAbsolutePath() +
            java.io.File.separator + sFileName;

    java.io.File flLocation = new java.io.File(localFileNameLocation);

    SJRequest request = getBaseRequest();
    java.io.File fl = new java.io.File(localFileNameLocation);
    long lFileUploadId = sendFileToServer(fl, request);
    request.putLong(FILE_UPLOAD_ID, lFileUploadId);

    request.putLong(REQUESTED_NODE_UNIQUE_ID, lFileID);
    if (comment == null){
      comment = "";
    }
    request.putString(COMMENT, comment);

    SJResponse response = sendRequest(request, SOAPPortal.MCPMethodNames.CHECK_IN_FILE);
    if ( ! response.getErrorEncountered() ){
      long lNewVerID = response.longValue(NODE_UNIQUE_ID);
      SourceVersionChecker checker = getChecker(flLocation);
      checker.updateLocalInfo(sFileName, lNewVerID);
      flLocation.setReadOnly();
    }
    updateProjectPointer();
    return response;
  }

  SJResponse checkOutFile(String sjFileNameLocation)
        throws IOException, SourceJammerConnectionException {
    return checkOutFile(sjFileNameLocation, AppConfig.getInstance().getDefaultEOLType());
  }

  SJResponse checkOutFile(String sjFileNameLocation, int eolType)
        throws IOException, SourceJammerConnectionException {

    long lFileID = getFileUniqueID(sjFileNameLocation);
    long lLatestVer = getFileLatestVersionID(lFileID);
    String sFileName = getFileNameFromNameLocation(sjFileNameLocation);
    SourceVersionChecker checker = getChecker(flLocalDirectory);
    boolean bExclude = checker.isFileCurrent(sFileName, lLatestVer);

    SJRequest request = getBaseRequest();
    request.putLong(REQUESTED_NODE_UNIQUE_ID, lFileID);
    request.putString(CHECK_OUT_PATH, flLocalDirectory.getAbsolutePath() + java.io.File.separator + sFileName);
    request.putInt(REQUESTED_EOL_TYPE, eolType);
    request.putBoolean(EXCLUDE_FILE, bExclude);
    if (! bExclude){
      request.putInt(ZIP_BINARIES_LARGER_THAN, SourceJammerClient.getInstance().getZipIfLargerThan());
    }

    SJResponse response = sendRequest(request, SOAPPortal.MCPMethodNames.CHECK_OUT_FILE);
    if ( ! response.getErrorEncountered() ){
      if (! bExclude){
        DownloadFileIdentifier downloadId = response.downloadFileIdentifierValue();
        long lTempFileId = retrieveFileFromServer(downloadId, response);

        checker.saveFile(sFileName, lLatestVer, lTempFileId, false, new RepeatingResponse());
      }
      else {
        FileSysUtil.makeFileWritable(new java.io.File(flLocalDirectory, sFileName));
      }
    }
    updateProjectPointer();
    return response;
  }

  SJResponse addFile(String newFileNameLocation, String fileType)
        throws IOException, SourceJammerConnectionException  {

    return addFile(newFileNameLocation, null, fileType);

  }

  String addAllFiles(String fileType)
        throws IOException, SourceJammerConnectionException {
    //Add all files in current local directory to current sj project.
    StringBuffer strMessage = new StringBuffer();
    SJResponse response = null;
    java.io.File[] flChildren = flLocalDirectory.listFiles();
    for (int i = 0; i < flChildren.length; i++){
      if (flChildren[i].isFile()){
        String sFileName = flChildren[i].getName();
        if (!sFileName.equals(ALL_FILES_IN_DIR)){
          response = addFile(sFileName, fileType);
          strMessage.append(updateStatusFromResponse(response, true)).append("\r\n");
        }
      }
    }
    return strMessage.toString();
  }

  String getAllFiles()
        throws IOException, SourceJammerConnectionException {
    //Get all files in current sj project to current local directory.
    StringBuffer strMessage = new StringBuffer();
    SJResponse response = null;
    Project ndCurrentProject = (Project)ndProjectPointer;
    NodeIterator oChildren = ndCurrentProject.childNodes();
    while (oChildren.hasMoreNodes()){
      NodeInfo ndChild = (NodeInfo)oChildren.getNextNode();
      if (ndChild.getNodeType() == AppConfig.NodeTypes.FILE) {
        String sName = ndChild.getNodeName();
        response = getFile(sName);
        strMessage.append(updateStatusFromResponse(response, false)).append("\r\n");
      }
    }
    return strMessage.toString();
  }

  SJResponse addFile(String newFileNameLocation, String localFileNameLocation,
                             String fileType)
        throws IOException, SourceJammerConnectionException  {
    //Look for and read in local file.
    String sFileName = null;
    if (localFileNameLocation == null){
      sFileName = getFileNameFromNameLocation(newFileNameLocation);
      localFileNameLocation = flLocalDirectory.getAbsolutePath() +
            java.io.File.separator + sFileName;
    }
    java.io.File fl = new java.io.File(localFileNameLocation);

    SJRequest request = getBaseRequest();
    long lFileUploadId = sendFileToServer(fl, request);
    request.putLong(FILE_UPLOAD_ID, lFileUploadId);
    request.putLong(REQUESTED_NODE_UNIQUE_ID, ndProjectPointer.getUniqueID());
    request.putString(REQUESTED_NODE_NAME, sFileName);
    int iFileType = -1;
    if (fileType.equals(FileTypes.BINARY) ){
      iFileType = AppConfig.FileTypes.BINARY;
    }
    else {
      iFileType = AppConfig.FileTypes.TEXT;
    }
    FileProperties props = new FileProperties();
    props.setFileType(iFileType);
    request.putObject(FILE_PROPERTIES, props);
//System.out.println("+ calling MCP");
    SJResponse response = sendRequest(request, SOAPPortal.MCPMethodNames.ADD_FILE);
//System.out.println("+ got response");
    if ( ! response.getErrorEncountered() ){
      java.io.File flFile = new java.io.File(localFileNameLocation);
      long lNewVerID = response.longValue(NODE_UNIQUE_ID);
      SourceVersionChecker checker = getChecker(flFile);
      checker.updateLocalInfo(sFileName, lNewVerID);
      flFile.setReadOnly();
      updateProjectPointer();
    }

    return response;
  }

  private void writeLocalFile(String sFullPathAndName, byte[] file)
        throws IOException{

    java.io.File fileWrite = new java.io.File(sFullPathAndName);
    //make any required directories. Maybe prompt for this some day. . .
    java.io.File parent = fileWrite.getParentFile();
    if (! parent.exists() ){
      parent.mkdirs();
    }

    FileOutputStream stmFileOut = new FileOutputStream(fileWrite);
    try{
      stmFileOut.write(file);
      stmFileOut.flush();
    }
    finally {
      stmFileOut.close();
    }
  }

  private byte[] readLocalFile(String sFullPathAndName)
        throws IOException {

    java.io.File fileRead = new java.io.File(sFullPathAndName);
    FileInputStream oFileIn = new FileInputStream(fileRead);
    ByteArrayOutputStream oByOut = new ByteArrayOutputStream();
    byte [] byFile = null;
    try {
      boolean bKeepReadingBytes = true;
      while (bKeepReadingBytes){
      int iByte = oFileIn.read();
      if (iByte == -1){
        bKeepReadingBytes = false;
      }
      else {
        oByOut.write(iByte);
        }
      }
      byFile = oByOut.toByteArray();
    }
    finally{
      oByOut.close();
      oFileIn.close();
    }
    return byFile;


  }

  SJResponse makeProject(String path) throws SourceJammerConnectionException {
    SJRequest request = getBaseRequest();
    path = path.trim();
    long lProjectID = ndProjectPointer.getUniqueID();
    request.putLong(REQUESTED_NODE_UNIQUE_ID, lProjectID);
    request.putString(REQUESTED_NODE_NAME, path);
    SJResponse response = sendRequest(request, SOAPPortal.MCPMethodNames.ADD_PROJECT);
    updateProjectPointer();
    return response;
  }

  SJResponse listDetails(String path) throws SourceJammerConnectionException {
    SJResponse response = null;
    if (path == null){
      response = getFakeResponse();
      response.setMessage(ndProjectPointer.toString());
    }
    else {
      long lProjectID = getProjectUniqueID(path);
      SJRequest request = getBaseRequest();
      request.putLong(REQUESTED_NODE_UNIQUE_ID, lProjectID);
      response = sendRequest(request, SOAPPortal.MCPMethodNames.GET_PROJECT_INFO);
      if (! response.getErrorEncountered()){
        Project proj = response.projectValue();
        try{
          proj.buildChildrenFromStrings();
        }
        catch (NodeExistsException ex){
          throw new ConfigurationException(ex.getMessage(), ex);
        }
        response.setMessage(proj.toString());
      }
    }
    return response;
  }

  private SJResponse getFakeResponse(){
    SJResponse response = new SJResponse();
    response.setSessionID(mlSessionID);
    response.putProject((Project)ndProjectPointer);
    return response;
  }

  private String updateStatusFromResponse(SJResponse response, boolean updateProjectPointer){
    StringBuffer strMessage = new StringBuffer();
    if (response != null){
      if (! response.getErrorEncountered() ){
        mlSessionID = response.getSessionID();
        if (updateProjectPointer && response.projectValue() != null){
          Project proj = response.projectValue();
          try{
            proj.buildChildrenFromStrings();
          }
          catch (NodeExistsException ex){
            throw new ConfigurationException(ex.getMessage(), ex);
          }
          ndProjectPointer = proj;
        }
      }
      else {
        strMessage.append("Error encountered:\r\n");
      }
      strMessage.append(response.getMessage());
    }
    return strMessage.toString();
  }

  private static String[] tokenizeCommand(String command){

    StringTokenizer oTokenizer = new StringTokenizer(command, Delimiters.SPACE);

    char[] caCommand = command.toCharArray();
    Vector vecCommands = new Vector();
    char cPrevChar;
    int iBegNewCommand = 0;
    boolean bInsideQuotes = false;
    for (int i = 0; i < caCommand.length; i++){
      int iChar = caCommand[i];
      if (caCommand[i] == Delimiters.C_QUOTE_MARK) {
        bInsideQuotes = (! bInsideQuotes);
      }
      if ( (caCommand[i] == Delimiters.C_SPACE && ! bInsideQuotes ) ||
            i == (caCommand.length - 1) ){
        //Build an element string

        String sElement = null;
        if (i < caCommand.length - 1 ){
          sElement = new String(caCommand, iBegNewCommand, i - iBegNewCommand);
        }
        else {
          sElement = new String(caCommand, iBegNewCommand, (i + 1) - iBegNewCommand);
        }

        sElement = StringUtil.replaceSubstring(sElement, Delimiters.QUOTE_MARK, "");
        vecCommands.add(sElement);
        iBegNewCommand = i + 1;
      }
    }

    String[] args = new String[vecCommands.size()];
    Enumeration enm = vecCommands.elements();
    int iCounter = 0;
    while (enm.hasMoreElements()){
      args[iCounter] = (String)enm.nextElement();
      iCounter++;
    }
    return args;
  }

  SJResponse changeProject(String path) throws SourceJammerConnectionException {
    path = path.trim();
    SJRequest request = getBaseRequest();
    long lProjectID = getProjectUniqueID(path);
    request.putLong(REQUESTED_NODE_UNIQUE_ID, lProjectID);
    SJResponse response = sendRequest(request, SOAPPortal.MCPMethodNames.GET_PROJECT_INFO);
    response.setMessage("");
    return response;
  }

  private SJResponse sendRequest(SJRequest request, String method)
          throws SourceJammerConnectionException{
    SJResponse response = null;
    try{
      response = moPortal.sendRequest(request, method);
    }
    catch (NoSessionException ex){
      //Try connecting and try again.
      try{
        connect(msArchiveName, msUserName, msPassword);
      }
      catch(SourceJammerConnectionException ex2){
        throw new SourceJammerConnectionException("Your session has timed out and SourceJammer is unable to reconnect you automatically. Try disconnecting and reconnecting.", ex2);
      }
      catch(NoSessionException ex2){
        throw new SourceJammerConnectionException("Your session has timed out and SourceJammer is unable to reconnect you automatically. Try disconnecting and reconnecting.", ex2);
      }
    }
    return response;
  }

  SJResponse connect(String sArchive, String userName, String password)
          throws SourceJammerConnectionException, NoSessionException {
    SJRequest request = new SJRequest();
    request.setArchiveName(sArchive);
    request.setUserName(userName);
    request.setPassword(password);

    //set binary file to a 1-item byte array to make SOAP happy in case
    //there is no binary file involved in the request. SOAP has trouble
    //with empty byte arrays for some reason.
    byte[] byArray = {1};
    //request.setBinaryFile(byArray);

    SJResponse response = moPortal.sendRequest(request, SOAPPortal.MCPMethodNames.CONNECT);
    if (! response.getErrorEncountered() ){
      msUserName = userName;
      msPassword = password;
      msArchiveName = sArchive;
    }
    return response;
  }

  SJResponse disconnect() throws SourceJammerConnectionException {
    SJRequest request = getBaseRequest();
    SJResponse response = sendRequest(request, SOAPPortal.MCPMethodNames.DISCONNECT);
    msArchiveName = null;
    return response;
  }

  private SJRequest getBaseRequest(){
    SJRequest request = new SJRequest();
    request.setArchiveName(msArchiveName);
    request.setUserName(msUserName);
    request.setPassword(msPassword);
    //request.setZipBinariesLargerThan(SourceJammerClient.getInstance().getZipBinariesLargerThan());


    if (mlSessionID != -1){
      request.setSessionID(mlSessionID);
    }
    return request;
  }

  String changeLocalDirectory(String path){
    String sMessage = null;

    java.io.File flTemp = getFileFromString(path);

    if (flTemp.exists()){
      if (flTemp.isDirectory() ){
        flLocalDirectory = flTemp;
        sMessage = "Local directory now " + flTemp.getPath();
      }
      else {
        sMessage = "Not a directory.";
      }
    }
    else {
      sMessage = "Not a valid local path.";
    }
    return sMessage;
  }

  private java.io.File getFileFromString(String path){
    StringTokenizer oTokenizer = new StringTokenizer(path, java.io.File.separator, false);

    java.io.File flTemp = null;
    if (path.startsWith(java.io.File.separator)){
      flTemp = new java.io.File(java.io.File.separator);
    }
    else {
      flTemp = flLocalDirectory;
    }
    while (oTokenizer.hasMoreTokens()){
      String s = oTokenizer.nextToken();
      if (! s.equals(TO_PARENT_DIR) ){
        flTemp = new java.io.File(flTemp, s);
      }
      else {
        flTemp = flTemp.getParentFile();
      }
    }
    return flTemp;
  }

  String listLocalDetails(){
    String[] sDetails = flLocalDirectory.list();
    StringBuffer strList = new StringBuffer("Contents of ");
    strList.append(flLocalDirectory.getPath())
           .append(":\r\n");

    for (int i = 0; i < sDetails.length; i++){
      strList.append("    ")
             .append(sDetails[i])
             .append("\r\n");
    }
    return strList.toString();
  }

  SJResponse viewVersionInfo(String sjFileNameLocation) throws SourceJammerConnectionException {

    SJRequest request = getBaseRequest();
    long lFileID = getFileUniqueID(sjFileNameLocation);
    org.sourcejammer.project.view.File fl = getFileInfo(lFileID);
    SJResponse response = getFakeResponse();
    response.putFile(fl);
    return response;
  }


  SJResponse getFileVersion(String sjFileNameLocation, String version)
        throws IOException, SourceJammerConnectionException {
    return getFileVersion(sjFileNameLocation, version, null);
  }

  /**
   * Get file info
   */
  private org.sourcejammer.project.view.File getFileInfo(long lFileID)
      throws SourceJammerConnectionException{
    org.sourcejammer.project.view.File oReturn = null;
    SJRequest request = getBaseRequest();
    request.putLong(REQUESTED_NODE_UNIQUE_ID, lFileID);
    SJResponse response = sendRequest(request, SOAPPortal.MCPMethodNames.GET_FILE_INFO);
    if (response.getErrorEncountered()){
      throw new BadMethodArgumentException(response.getMessage());
    }
    oReturn = response.fileValue();

    try{
      oReturn.buildChildrenFromStrings();
    }
    catch (NodeExistsException ex){
      throw new ConfigurationException(ex.getMessage(), ex);
    }
    return oReturn;
  }



  SJResponse getFileVersion(String sjFileNameLocation, String version, String localFileNameLocation)
        throws IOException, SourceJammerConnectionException {
    long lFileID = getFileUniqueID(sjFileNameLocation);

    String sFileName = getFileNameFromNameLocation(sjFileNameLocation);
    if (localFileNameLocation == null){
      localFileNameLocation = flLocalDirectory.getAbsolutePath() +
              java.io.File.separator + sFileName;
    }
    else {
      localFileNameLocation = flLocalDirectory.getAbsolutePath() +
              java.io.File.separator + localFileNameLocation;
    }
    int iVersion = Integer.parseInt(version.trim());
    long lVersionID = getVersionUniqueID(lFileID, iVersion);

    java.io.File flLocation = new java.io.File(localFileNameLocation);

    SJResponse response = getFileVersionFromServer(lFileID, iVersion, lVersionID, sFileName, flLocation);
    return response;
  }

  private String getFileNameFromNameLocation(String nameLocation){
    String sDirSwitch = AppConfig.getInstance().getSourceJammerSwitch();
    String sFileName = null;
    int iLastSwitch = nameLocation.lastIndexOf(sDirSwitch);
    if (iLastSwitch != -1 ){
      sFileName = nameLocation.substring(iLastSwitch + 1);
    }
    else {
      sFileName = nameLocation;
    }
    return sFileName;
  }

  SJResponse remove(String sNodeName) throws SourceJammerConnectionException {
    long lNodeID = getFileUniqueID(sNodeName);
    boolean bIsFile = false;
    try {
      org.sourcejammer.project.view.File fl = getFileInfo(lNodeID);
      bIsFile = true;
    }
    catch (BadMethodArgumentException ex){
      bIsFile = false;
    }

    String sMethod = null;
    if (bIsFile){
      sMethod = SOAPPortal.MCPMethodNames.REMOVE_FILE;
    }
    else {
      sMethod = SOAPPortal.MCPMethodNames.REMOVE_PROJECT;
    }

    SJRequest request = getBaseRequest();
    request.putLong(REQUESTED_NODE_UNIQUE_ID, lNodeID);
    request.putLong(PARENT_NODE_UNIQUE_ID, ndProjectPointer.getUniqueID());
    SJResponse response = sendRequest(request, sMethod);
    updateProjectPointer();
    return response;
  }

  SJResponse undoCheckOut(String sjFileNameLocation) throws SourceJammerConnectionException, IOException {
    SJRequest request = getBaseRequest();
    long lFileID = getFileUniqueID(sjFileNameLocation);
    request.putLong(REQUESTED_NODE_UNIQUE_ID, lFileID);
    SJResponse response = sendRequest(request, SOAPPortal.MCPMethodNames.UNDO_CHECKOUT);
    String sFileName = getFileNameFromNameLocation(sjFileNameLocation);
    java.io.File flFile = new java.io.File(flLocalDirectory, sFileName);
    if (flFile.exists()){
      flFile.setReadOnly();
    }
    else{
      response.setMessage(response.getMessage() + "\r\nCould not locate local version of file, " + sjFileNameLocation + ". Local file may still be writable.");
    }
    updateProjectPointer();
    return response;
  }

  SJResponse rollback(String sjFileNameLocation, String version)
        throws IOException, SourceJammerConnectionException {

    SJRequest request = getBaseRequest();
    long lFileID = getFileUniqueID(sjFileNameLocation);
    int iVersion = Integer.parseInt(version.trim());
    long lVersionID = getVersionUniqueID(lFileID, iVersion);

    request.putLong(REQUESTED_NODE_UNIQUE_ID, lVersionID);
    request.putLong(PARENT_NODE_UNIQUE_ID, lFileID);
    SJResponse response = sendRequest(request, SOAPPortal.MCPMethodNames.ROLLBACK_TO_VERSION);
    return response;
  }

  private long getVersionUniqueID(long fileID, int versionNumber) throws SourceJammerConnectionException{
    org.sourcejammer.project.view.File fl = getFileInfo(fileID);
    
    Node[] vers = fl.childList().getContentsAsArray();
    if (versionNumber < 1 ||  vers.length < versionNumber){
      throw new BadMethodArgumentException("That is not a valid version number for this file.");
    }
    long lVersionID = vers[versionNumber - 1].getUniqueID();
    return lVersionID;
  }

  SJResponse rename(String sjName, String newName)
        throws SourceJammerConnectionException{
    long lNodeID = getFileUniqueID(sjName);
    boolean bIsFile = false;
    try {
      org.sourcejammer.project.view.File fl = getFileInfo(lNodeID);
      bIsFile = true;
    }
    catch (BadMethodArgumentException ex){
      bIsFile = false;
    }

    String sMethod = null;
    if (bIsFile){
      sMethod = SOAPPortal.MCPMethodNames.RENAME_FILE;
    }
    else {
      sMethod = SOAPPortal.MCPMethodNames.RENAME_PROJECT;
    }

    SJRequest request = getBaseRequest();
    request.putLong(PARENT_NODE_UNIQUE_ID, ndProjectPointer.getUniqueID());
    request.putLong(REQUESTED_NODE_UNIQUE_ID, lNodeID);
    request.putString(REQUESTED_NODE_NAME, newName);
    SJResponse response = sendRequest(request, sMethod);
    updateProjectPointer();
    return response;
  }

  SJResponse viewVersionComment(String sjFileNameLocation, String version)
        throws SourceJammerConnectionException {
    SJRequest request = getBaseRequest();
    long lFileID = getFileUniqueID(sjFileNameLocation);
    int iVersion = Integer.parseInt(version.trim());
    long lVersionID = getVersionUniqueID(lFileID, iVersion);
    request.putLong(REQUESTED_NODE_UNIQUE_ID, lVersionID);
    SJResponse response = sendRequest(request, SOAPPortal.MCPMethodNames.VIEW_VERSION_COMMENT);
    return response;
  }

  SJResponse restoreRemoved(String itemNumber, String newName)
        throws SourceJammerConnectionException {
    SJRequest request = getBaseRequest();
    int iItemNumber = -1;
    try{
      iItemNumber = Integer.parseInt(itemNumber.trim());
    }
    catch (NumberFormatException ex){
      throw new BadMethodArgumentException("The [NUM] value you entered is not a number. Please user the viewrm command to find the removed number of the item you want to restore.", ex);
    }
    request.putInt(VERSION_NUMBER, iItemNumber);
    request.putLong(REQUESTED_NODE_UNIQUE_ID, ndProjectPointer.getUniqueID());
    if (newName != null){
      request.putString(REQUESTED_NODE_NAME, newName);
    }
    SJResponse response = sendRequest(request, SOAPPortal.MCPMethodNames.RESTORE_REMOVED_NODE);
    updateProjectPointer();
    return response;
  }

  SJResponse deleteRemoved(String itemNumber)
        throws SourceJammerConnectionException {
    SJRequest request = getBaseRequest();
    int iItemNumber = Integer.parseInt(itemNumber.trim());
    request.putInt(VERSION_NUMBER, iItemNumber);
    request.putLong(REQUESTED_NODE_UNIQUE_ID, ndProjectPointer.getUniqueID());
    SJResponse response = sendRequest(request, SOAPPortal.MCPMethodNames.PERMANENTLY_DELETE_NODE);
    return response;
  }

  SJResponse makeArchive(String name, String implementation, String path)
        throws SourceJammerConnectionException {
    SJRequest request = getBaseRequest();
    Integer intImplementation = null;
    if (implementation != null){
      if (implementation.equals(Implementations.FILESYS) ){
        intImplementation = new Integer(0);
      }
    }
    request.putString(NEW_ARCHIVE_NAME, name);
    if (intImplementation != null){
      request.putInt(NEW_ARCHIVE_IMPLEMENTATION, intImplementation.intValue());
    }
    if (path != null){
      request.putString(NEW_ARCHIVE_ROOT_PATH, path);
    }
    SJResponse response = sendRequest(request, SOAPPortal.MCPMethodNames.ADD_ARCHIVE);
    return response;
  }

  SJResponse makeUser(String userName, String password, String fullName)
        throws SourceJammerConnectionException {
    SJRequest request = getBaseRequest();
    request.putString(NEW_USER_NAME, userName);
    request.putString(NEW_USER_PASSWORD, password);
    request.putString(NEW_USER_FULL_NAME, fullName);
    SJResponse response = sendRequest(request, SOAPPortal.MCPMethodNames.ADD_USER);
    return response;
  }

  SJResponse changePassword(String password)
        throws SourceJammerConnectionException {
    SJRequest request = getBaseRequest();
    request.putString(NEW_USER_PASSWORD, password);
    SJResponse response = sendRequest(request, SOAPPortal.MCPMethodNames.CHANGE_PASSWORD);
    return response;
  }

  SJResponse makeArchiveDisconnected(String userName, String password,
                                    String name, String implementation,
                                    String path)
        throws SourceJammerConnectionException{
    if (msArchiveName != null){
      throw new BadMethodArgumentException("This command should only be " +
                      "used when not connected to an archive. Use discon to disconnect.");
    }
    SJRequest request = getBaseRequest();
    request.setUserName(userName);
    request.setPassword(password);
    SJResponse loginResponse = sendRequest(request, SOAPPortal.MCPMethodNames.LOG_IN);
    SJResponse response = null;
    if(! loginResponse.getErrorEncountered()){
      request.setSessionID(loginResponse.getSessionID());
      Integer intImplementation = null;
      if (implementation != null){
        if (implementation.equals(Implementations.FILESYS) ){
          intImplementation = new Integer(0);
        }
      }
      request.putString(NEW_ARCHIVE_NAME, name);
      if (intImplementation != null){
        request.putInt(NEW_ARCHIVE_IMPLEMENTATION, intImplementation.intValue());
      }
      if (path != null){
        request.putString(NEW_ARCHIVE_ROOT_PATH, path);
      }
      response = sendRequest(request, SOAPPortal.MCPMethodNames.ADD_ARCHIVE);
      sendRequest(request, SOAPPortal.MCPMethodNames.DISCONNECT);
    }
    else {
      response = loginResponse;
    }
    return response;
  }

  SJResponse makeLabel(String labelName, String description)
          throws SourceJammerConnectionException{
    SJRequest request = getBaseRequest();
    request.putString(REQUESTED_NODE_NAME, labelName);
    request.putString(COMMENT, description);
    request.putLong(REQUESTED_NODE_UNIQUE_ID, ndProjectPointer.getUniqueID());
    SJResponse response = sendRequest(request, SOAPPortal.MCPMethodNames.MAKE_LABEL);
    return response;
  }

  private SJResponse getFileVersionFromServer(long fileID, int versionNum, long versionID,
                                        String fileName, java.io.File toDir)
        throws SourceJammerConnectionException, IOException {
    SJResponse response = null;
    SourceVersionChecker checker = getChecker(toDir);
    if (! checker.isFileCurrent(fileName, versionID)){
      SJRequest request = getBaseRequest();
      request.putLong(REQUESTED_NODE_UNIQUE_ID, fileID);
      request.putInt(VERSION_NUMBER, versionNum);
      request.putInt(REQUESTED_EOL_TYPE, AppConfig.getInstance().getDefaultEOLType());
      System.out.println("Getting version " + versionNum + " of " + fileName + " to " + toDir + ".");
      response = sendRequest(request, SOAPPortal.MCPMethodNames.GET_FILE_VERSION);
      if ( ! response.getErrorEncountered() ){
        DownloadFileIdentifier downloadId = response.downloadFileIdentifierValue();
        long lTempFileId = retrieveFileFromServer(downloadId, response);

        checker.saveFile(fileName, versionID, lTempFileId, true, new RepeatingResponse());
      }
      else{
        throw new BadMethodArgumentException(response.getMessage());
      }
    }
    else{
      response = getFakeResponse();
      response.setMessage("Local version of " + fileName + " is current. Did not download file.");
System.out.println("Local version of " + fileName + " is current. Did not download file.");
    }
    return response;
  }

  SJResponse getLabel(String sjFileNameLocation, int verNum)
          throws IOException, SourceJammerConnectionException{

    long lLabelID = getFileUniqueID(sjFileNameLocation);
    if (verNum < 0){
      //need to look up version number.
      org.sourcejammer.project.view.File fl = getFileInfo(lLabelID);
      verNum = fl.childCount();
    }


    SJRequest request = getBaseRequest();
    request.putLong(REQUESTED_NODE_UNIQUE_ID, lLabelID);
    request.putInt(VERSION_NUMBER, verNum);
    SJResponse response = sendRequest(request, SOAPPortal.MCPMethodNames.GET_LABEL);

    //Now we need to get all the files in the label.
    if (! response.getErrorEncountered()){
      long lRootProject = response.longValue(NODE_UNIQUE_ID);
      Object[] versionMappings = (Object[])response.objectValue(OBJECT_ARRAY);
      for (int i = 0; i < versionMappings.length; i++){
        LabelVersionMappingBean bnVersion = (LabelVersionMappingBean)versionMappings[i];
        //The path below is actually relative to the root project.
        String sSJPath = bnVersion.getFullPathToFile();
        long lFileID = bnVersion.getFileUniqueID();
        int iVersion = bnVersion.getVersionNumber();
        long lVersionID = bnVersion.getVersionUniqueID();

        int iLastSwitch = sSJPath.lastIndexOf(AppConfig.getInstance().getSourceJammerSwitch());
        String sParent = sSJPath.substring(0, iLastSwitch);
        String sFileName = sSJPath.substring(iLastSwitch + 1);

        java.io.File flTargetDir = new java.io.File(flLocalDirectory, sParent);
        if (! flTargetDir.exists()){
          flTargetDir.mkdirs();
          System.out.println("Making directory: " + flTargetDir.getAbsolutePath());
        }
        if (flTargetDir.exists() &&
            flTargetDir.isDirectory()){
          getFileVersionFromServer(lFileID, iVersion, lVersionID, sFileName, flTargetDir);
        }
        else{
          System.out.println("Unable to create directory: " + flTargetDir.getAbsoluteFile());
          System.out.println("Skipping project " + sParent + " in label.");
        }
      }//end for
    }
    return response;

  }



  String getHelpText(){
    return CLHelp.getText();
  }


  /**
   * jbm change start
   * jbm
   * jbm add getproj command
   * jbm
   *
   * Get All Project Files
   *   command format:  getproj { [project name] { [r|nr] { [d|nd] {v|nv} } ] }
   *
   *   function:
   *
   *   parms:
   *      project name -- absolute, relative or current project name.  An absolute
   *                   project name starts with a slash "/".  Use a single period "."
   *                   to use the current project. Anything else is considered a relative
   *                   project
   *
   *      r|nr -- recurse, no-recurse.  Recurse means to retrieve all the files from all the
   *              projects below the starting project.
   *
   *      d|nd -- when recursing projects, make or don't make the local directory
   *              structure match the project name structure.
   *
   *      v|nv -- before a file is retrieved, verify or don't verify that the file is checked in.
   *              If verifying, then if a file is checked out then do not retrieve the file
   *              and terminate the command.  If not verifying, then don't check, don't tell,
   *              don't stop.
   *
   *   all parms are optional and default (if not specified) to:
   *     current project -- "."
   *     recurse projects -- "r"
   *     make directories -- "d"
   *     don't verify check in -- "nv"
   *
   *     note: The parms must appear in the order specified, if they appear at all.  If
   *           the recurse option is wanted, then the project name must be present.  If the
   *           directory options is wanted, then the recurse option must be present. And if
   *           the verify option is wanted, then the directory option must be present.
   *
   */
  SJResponse getAllProjectFiles(String projectNameParm,
                                       String recurseProjectParm,
                                       String makeDirectoriesParm,
                                       String verifyCheckInParm)
          throws IOException, SourceJammerConnectionException, CLCommandException
  {
    SJResponse response = null;

    // default paramters for getproj command
    boolean recurseProject = true;
    boolean makeDirectories = true;
    boolean verifyCheckIn = false;

    // save the current environment so it can be restored when finished.
    Project currentProject = (Project) ndProjectPointer;
    String currentProjectName = currentProject.getNodeName();
    java.io.File currentLocalDirectory = flLocalDirectory;

    Project projectToGet = null;

    if (projectNameParm.equals(CommandLineInterpreter.GETPROJ_CURRENT_PROJECT))
    {
      projectToGet = currentProject;
    }
    else
    {
      updateStatusFromResponse(changeProject(projectNameParm), true);
      projectToGet = (Project) ndProjectPointer;

      System.out.println("Current Project set to (" + projectToGet.getNodeName() + ")");
    }

    // check recurseProjectParm for r|nr
    if (recurseProjectParm.toLowerCase().startsWith(CommandLineInterpreter.GETPROJ_NO_RECURSE_PROJECT))
    {
      recurseProject = false;
    }

    // check makeDirectoriesParm for d|nd
    if (makeDirectoriesParm.toLowerCase().startsWith(CommandLineInterpreter.GETPROJ_NO_MAKE_LOCAL_DIRS))
    {
      makeDirectories = false;
    }

    // check verifyCheckInParm for v|nv
    if (verifyCheckInParm.toLowerCase().startsWith(CommandLineInterpreter.GETPROJ_VERIFY_CHECKIN))
    {
      verifyCheckIn = true;
    }

    response = getFakeResponse();
    StringBuffer msg = new StringBuffer("Get Project (" + projectToGet.getNodeName() +
                                             ") Recurse (" + recurseProject +
                                             ") mkdir (" + makeDirectories +
                                             ") vfyChkIn (" + verifyCheckIn + ")\n\r");

    try
    {
      StringBuffer cmdResp = getAllFilesAndChildren(currentLocalDirectory,
                                                    projectToGet,
                                                    recurseProject,
                                                    makeDirectories,
                                                    verifyCheckIn);
      msg.append(cmdResp);
    }
    catch (CLCommandException ex)
    {
      throw ex;
    }
    catch (Exception ex)
    {
      msg.append("Error occured retrieving from project (" + projectToGet.getNodeName() +
                        "). Exception (" + ex.toString() + ")\r\n");
    }
    finally
    {
      response.setMessage(msg.toString());
    }

    return response;
  }

  /**
   * retrieves all files and projects into the specified directory.  Makes directories
   * to match the project sturcture if specified.  Recurse the project sturcture if specified.
   */
  private StringBuffer getAllFilesAndChildren(java.io.File destDir,
                                      Project proj,
                                      boolean recurseProject,
                                      boolean makeDirectories,
                                      boolean vfyChkIn)
        throws IOException, SourceJammerConnectionException, CLCommandException
  {
    StringBuffer progressResponseBuffer = new StringBuffer("");
    String trcmsg = "getAllFilesAndChildren(" + destDir.getName() + ", " +
                                              proj.getNodeName() + ", " +
                                              recurseProject + ", " +
                                              makeDirectories + ", " +
                                              vfyChkIn + ")";

    String projectNodeName = proj.getNodeName();
    String destDirName = destDir.getName();

    //System.out.println(trcmsg);
    //System.out.println("proj (" + proj.toString() + ")");

    if (!destDir.exists())
    {
      if (makeDirectories)
      {
        destDir.mkdir();
        System.out.println("Local Directory (" + destDir.getName() + ") created.");
      }
      else
      {
        String msg = "Directory, " + destDir.getAbsolutePath() +
                                 ", does not exist. Halting project get . . .";
        throw new IOException (msg);
      }
    }

    Vector fileNodes = new Vector();
    Vector projectNodes = new Vector();

    NodeIterator children = proj.childNodes();
    while(children.hasMoreNodes())
    {
      NodeInfo childNode = (NodeInfo) children.getNextNode();
      String childNodeName = childNode.getNodeName();

      //System.out.println("childNode: (" + childNode.toString() + ")");
      //System.out.println("childNodeName: (" + childNodeName + ")");

      if (childNode.getNodeType() == AppConfig.NodeTypes.FILE)
      {
        if (vfyChkIn && childNode.isCheckedOut())
        {
          String msg = "File (" + childNode.getNodeName() + ") is checked out to user (" +
                       childNode.getCheckedOutToUser() + ") on date (" +
                       childNode.getCheckedOutDate().toString() + ").  Halting project get...";
          throw new CLCommandException(msg);
        }

        fileNodes.add(childNode);
      }
      else if (childNode.getNodeType() == AppConfig.NodeTypes.PROJECT)
      {
        if (recurseProject)
        {
          projectNodes.add(childNode);
        }
      }
      else
      {
        // (not a project) and (not a file)
        System.out.println("ChildNode (" + childNodeName + ") is not a project or a file");
        System.out.println("ChildNode (" + childNode.toString() + ")");
      }
    }

    Enumeration fileNodeEnum = fileNodes.elements();
    System.out.println("Retrieving all file objects from project (" + projectNodeName + ")");

    while (fileNodeEnum.hasMoreElements())
    {
      NodeInfo fileNode = (NodeInfo) fileNodeEnum.nextElement();
      String fileNodeName = fileNode.getNodeName();

      try
      {
        //System.out.println("getFile(" + fileNodeName + ")");
        //System.out.println("From Current Project (" + ndProjectPointer.toString() + ")");
        /**/
        flLocalDirectory = destDir;
        SJResponse response = getFile(fileNodeName);
        System.out.println("-> " + response.getMessage());
        progressResponseBuffer.append(updateStatusFromResponse(response, false));
        progressResponseBuffer.append("\r\n");
        /**/
      }
      catch (Exception ex)
      {
        String msg = "Error occured retrieving file (" + fileNodeName + ") from project (" + projectNodeName +
                            ") to destination directory (" + destDirName +
                            "). Exception (" + ex.toString() + ")";
        System.out.println(msg);
        progressResponseBuffer.append(msg + "\n\r");
      }
    }

    Enumeration projectNodeEnum = projectNodes.elements();
    if (recurseProject)
    {
      System.out.println("Retrieving all project objects from project (" + projectNodeName + ")");
    }

    while (projectNodeEnum.hasMoreElements())
    {
      NodeInfo childProjectNode = (NodeInfo) projectNodeEnum.nextElement();
      String childProjectNodeName = childProjectNode.getNodeName();

      try
      {
        java.io.File childProjectDestDir = destDir;
        if (makeDirectories)
        {
          // setup receiving Directory
          childProjectDestDir = new java.io.File(destDir, childProjectNodeName);
        }

        //System.out.println("changing current project to (" + childProjectNodeName + ")");
        //System.out.println("from Current Project (" + ndProjectPointer.toString() + ")");

        String rspMsg = updateStatusFromResponse(changeProject(childProjectNodeName), true);
        Project childProject = (Project) ndProjectPointer;

        //System.out.println("childProjectNode: (" + childProjectNode.toString() + ")");

        getAllFilesAndChildren(childProjectDestDir,
                                childProject,
                                recurseProject,
                                makeDirectories,
                                vfyChkIn);

        //System.out.println("Resetting current project to (" + proj.getNodeName() + ")");
        //System.out.println("from Current Project (" + ndProjectPointer.getNodeName() + ")");
        //System.out.println("Resetting current project to (" + proj.toString() + ")");
        //System.out.println("from Current Project (" + ndProjectPointer.toString() + ")");
        ndProjectPointer = proj;
        updateProjectPointer();
        //System.out.println("Current project reset to (" + ndProjectPointer.getNodeName() + ")");
        //System.out.println("Current project reset to (" + ndProjectPointer.toString() + ")");
        flLocalDirectory = destDir;
      }
      catch (CLCommandException ex)
      {
        throw ex;
      }
      catch (Exception ex)
      {
        String msg = "Error occured processing project (" + childProjectNodeName +
                            "). Exception (" + ex.toString() + ")";
        System.out.println(msg);
        progressResponseBuffer.append(msg + "\r\n");
      }
    }
    return progressResponseBuffer;
  }

  /**
   * jbm
   * jbm change end
   * jbm
   */





  private void makeFileReadable(String sFullPath) throws IOException{

    SourceJammerClient config = SourceJammerClient.getInstance();

    String[] saWritableHack = config.getMakeWritableCommand();
    String[] saCommand = new String[saWritableHack.length + 1];
    for (int i = 0; i < saWritableHack.length; i++){
      saCommand[i] = saWritableHack[i];
    }
    saCommand[saWritableHack.length] = sFullPath;

    Process proc = Runtime.getRuntime().exec(saCommand);

    try {
      proc.waitFor();
    }
    catch (InterruptedException ex){
    }
  }

  private SourceVersionChecker getChecker(java.io.File path)
        throws IOException{
    if (! path.isDirectory()){
      path = path.getParentFile();
    }
    return new SourceVersionChecker(path, msUrl, msArchiveName);
  }

  private long getFileLatestVersionID(long lFileID) throws SourceJammerConnectionException{
    long lReturn = -1;
    SJRequest request = getBaseRequest();
    request.putLong(REQUESTED_NODE_UNIQUE_ID, lFileID);
    SJResponse resID = sendRequest(request, SOAPPortal.MCPMethodNames.GET_LATEST_VERSION_ID);
    if (!resID.getErrorEncountered()){
      lReturn = resID.longValue(NODE_UNIQUE_ID);
    }
    else {
      throw new BadMethodArgumentException("Cannot retrieve latest version id. " + resID.getMessage());
    }
    return lReturn;
  }

  private long getProjectUniqueID(String sjPath)
        throws SourceJammerConnectionException{
    return getFileUniqueID(sjPath);
  }

  /**
   * Gets unique ID of specified file from the server.
   */
  private long getFileUniqueID(String sjPath)
        throws SourceJammerConnectionException{
    long lFileID = -1;
    SJRequest request = getBaseRequest();
    //First get the file ID.
    request.putLong(REQUESTED_NODE_UNIQUE_ID, ndProjectPointer.getUniqueID());
    request.putString(REQUESTED_NODE_NAME, sjPath);
    SJResponse response = sendRequest(request, SOAPPortal.MCPMethodNames.GET_UNIQUE_ID_FROM_PATH);
    if ( ! response.getErrorEncountered() ){
      lFileID = response.longValue(NODE_UNIQUE_ID);
    }
    else {
      throw new BadMethodArgumentException("Cannot retrieve file id. " + response.getMessage());
    }
    return lFileID;
  }

  /**
   * Checks if a byte array about to be sent is larger than the minimum
   * unzipped file size. If so, zips the file and sets the flag in the SJRequest.
   */
  protected byte[] zipByteArrayIfNeeded(byte[] file, SJRequest request)
          throws IOException{
    byte[] byReturn = null;
    int iSize = file.length;
    int iMinZipSize = SourceJammerClient.getInstance().getZipIfLargerThan();
    if (iSize > iMinZipSize){
      byReturn = ZipUtil.zipByteArray(file);
      request.putBoolean(BINARY_ZIPPED, true);
    }//end if needs to be zipped.
    else {
      byReturn = file;
    }
    return byReturn;
  }

  protected void updateProjectPointer() throws SourceJammerConnectionException{
    if (ndProjectPointer != null){
      long lProjectID = ndProjectPointer.getUniqueID();
      SJRequest request = getBaseRequest();
      request.putLong(REQUESTED_NODE_UNIQUE_ID, lProjectID);
      SJResponse response = sendRequest(request, SOAPPortal.MCPMethodNames.GET_PROJECT_INFO);
      Project proj = response.projectValue();
      try{
        proj.buildChildrenFromStrings();
      }
      catch (NodeExistsException ex){
        throw new ConfigurationException(ex.getMessage(), ex);
      }
      ndProjectPointer = proj;
    }
  }


  /**
   * Returns temp file id.
   */
  protected long retrieveFileFromServer(DownloadFileIdentifier id, SJResponse response)
          throws IOException, SourceJammerConnectionException{
    long lTempId = TempDirectoryManager.getNextID();
    java.io.File flTemp = TempDirectoryManager.getNewTempFile(lTempId);
    FileTransport.downloadFileFromServer(id, flTemp, msUrl);
    //Unzip if needed.
    if (response.booleanValue(res_BINARY_ZIPPED)){
      long lUnzipId = TempDirectoryManager.getNextID();
      java.io.File flUnzip = TempDirectoryManager.getNewTempFile(lUnzipId);
      ZipUtil.unzipFileToFile(flTemp, flUnzip);
      TempDirectoryManager.deleteTempFile(lTempId);
      lTempId = lUnzipId;
      flTemp = flUnzip;
    }
    return lTempId;
  }

  protected long sendFileToServer(java.io.File fl, SJRequest request)
          throws IOException, SourceJammerConnectionException{
    //First zip file if required.
    java.io.File flSend = null;
    int iSize = (int)fl.length();
    int iMinZipSize = SourceJammerClient.getInstance().getZipIfLargerThan();
    long lTempID = -1;
    if (iSize > iMinZipSize && ZipUtil.canZip(fl.getName())){
      lTempID = TempDirectoryManager.getNextID();
      java.io.File flZip = TempDirectoryManager.getNewTempFile(lTempID);
      ZipUtil.zipFileToFile(fl, flZip);
      flSend = flZip;
      request.putBoolean(BINARY_ZIPPED, true);
    }
    else {
      flSend = fl;
    }
    long lSendID = FileTransport.sendFileToServer(flSend, msUrl);
    if (request.booleanValue(BINARY_ZIPPED)){
      //remove temp file.
      TempDirectoryManager.deleteTempFile(lTempID);
    }
    return lSendID;
  }

  /*
  public static void main (String[] args){
    try {
      org.sourcejammer.util.CommandLine oCommand = new org.sourcejammer.util.CommandLine();
      String sCommand = oCommand.getUserInput("Enter command");
      String[] cmd = tokenizeCommand(sCommand);
      oCommand.println("" + cmd.length);
      for (int i = 0; i < cmd.length; i++){
        oCommand.println(i + ": " + cmd[i]);
      }

    }
    catch (Exception ex){
      ex.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.