Exemplo n.º 1
0
  /**
   * Create the ftpClient and authenticate with the resource.
   *
   * @throws FileResourceException if an exception occurs during the resource start-up
   */
  public void start()
      throws InvalidSecurityContextException, IllegalHostException, FileResourceException {

    ServiceContact serviceContact = getAndCheckServiceContact();

    String host = getServiceContact().getHost();
    int port = getServiceContact().getPort();
    if (port == -1) {
      port = 21;
    }

    if (getName() == null) {
      setName(host + ":" + port);
    }

    try {
      SecurityContext securityContext = getOrCreateSecurityContext("ftp", serviceContact);

      PasswordAuthentication credentials = getCredentialsAsPasswordAuthentication(securityContext);

      ftpClient = new FTPClient(host, port);

      String username = credentials.getUserName();
      String password = String.valueOf(credentials.getPassword());

      ftpClient.authorize(username, password);
      ftpClient.setType(Session.TYPE_IMAGE);
      setStarted(true);
    } catch (Exception e) {
      throw translateException("Error connecting to the FTP server at " + host + ":" + port, e);
    }
  }
Exemplo n.º 2
0
 /** Equivalent to cp/copy command */
 public void getFile(
     FileFragment remote, FileFragment local, final ProgressMonitor progressMonitor)
     throws FileResourceException {
   if (remote.isFragment() || local.isFragment()) {
     throw new UnsupportedOperationException(
         "The FTP provider does not support partial transfers");
   }
   String currentDirectory = getCurrentDirectory();
   File localFile = new File(local.getFile());
   try {
     ftpClient.setPassive();
     ftpClient.setLocalActive();
     final long size = localFile.length();
     DataSink sink;
     if (progressMonitor != null) {
       // The sink is used to follow progress
       sink =
           new DataSinkStream(new FileOutputStream(localFile)) {
             public void write(Buffer buffer) throws IOException {
               super.write(buffer);
               progressMonitor.progress(offset, size);
             }
           };
     } else {
       sink = new DataSinkStream(new FileOutputStream(localFile));
     }
     ftpClient.get(remote.getFile(), sink, null);
   } catch (Exception e) {
     throw translateException("Cannot retrieve the given file", e);
   }
 }
Exemplo n.º 3
0
  /**
   * Renames the file denoted by this abstract pathname.
   *
   * <p>Whether or not this method can move a file from one filesystem to another is
   * platform-dependent. The return value should always be checked to make sure that the rename
   * operation was successful.
   *
   * @param dest The new abstract pathname for the named file
   * @throws IllegalArgumentException If parameter <code>dest</code> is not a <code>GeneralFile
   *     </code>.
   * @throws NullPointerException - If dest is null
   */
  public boolean renameTo(GeneralFile dest) throws IllegalArgumentException, NullPointerException {
    try {
      if (dest instanceof FTPFile) {
        if (ftpClient.equals(((FTPFile) dest).ftpClient)) {
          ftpClient.rename(getPath(), dest.getPath());
        } else {
          // TODO some ftp to ftp copy...

          if (!dest.exists()) {
            copyTo(dest);
            delete();
          } else return false;
        }
      } else {
        if (!dest.exists()) {
          copyTo(dest);
          delete();
        } else return false;
      }
    } catch (IOException e) {
      return false;
    } catch (FTPException e) {
      return false;
    }

    return true;
  }
Exemplo n.º 4
0
 /** Copy a local file to a remote file. Default option 'overwrite' */
 public void putFile(
     FileFragment local, FileFragment remote, final ProgressMonitor progressMonitor)
     throws FileResourceException {
   if (local.isFragment() || remote.isFragment()) {
     throw new UnsupportedOperationException(
         "The FTP provider does not support partial transfers");
   }
   String currentDirectory = getCurrentDirectory();
   File localFile = new File(local.getFile());
   try {
     ftpClient.setPassive();
     ftpClient.setLocalActive();
     final long size = localFile.length();
     DataSource source;
     if (progressMonitor != null) {
       source =
           new DataSourceStream(new FileInputStream(localFile)) {
             public Buffer read() throws IOException {
               progressMonitor.progress(totalRead, size);
               return super.read();
             }
           };
     } else {
       source = new DataSourceStream(new FileInputStream(localFile));
     }
     ftpClient.put(remote.getFile(), source, null, false);
   } catch (Exception e) {
     throw translateException("Cannot transfer the given file", e);
   }
 }
Exemplo n.º 5
0
 /**
  * Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a
  * directory, then the directory must be empty in order to be deleted.
  */
 public boolean delete() {
   try {
     if (isDirectory()) {
       ftpClient.deleteDir(getPath());
     } else {
       ftpClient.deleteFile(getPath());
     }
   } catch (IOException e) {
     return false;
   } catch (FTPException e) {
     return false;
   }
   return true;
 }
Exemplo n.º 6
0
 /** returns true if the file exists */
 public boolean exists(String filename) throws FileResourceException {
   try {
     return ftpClient.exists(filename);
   } catch (Exception e) {
     throw translateException("Cannot determine the existence of the file", e);
   }
 }
Exemplo n.º 7
0
 /**
  * Return Current path
  *
  * @throws IOException
  * @throws FileResourceException
  */
 public String getCurrentDirectory() throws FileResourceException {
   try {
     return ftpClient.getCurrentDir();
   } catch (Exception e) {
     throw translateException("Cannot get the current directory", e);
   }
 }
Exemplo n.º 8
0
 /** rename a remote file. */
 public void rename(String remoteFileName1, String remoteFileName2) throws FileResourceException {
   try {
     ftpClient.rename(remoteFileName1, remoteFileName2);
   } catch (Exception e) {
     throw translateException("Rename for ftp failed", e);
   }
 }
Exemplo n.º 9
0
 /** Equivalent to rm command on a file */
 public void deleteFile(String file) throws FileResourceException {
   try {
     ftpClient.deleteFile(file);
   } catch (Exception e) {
     throw translateException("Cannot delete the given file", e);
   }
 }
Exemplo n.º 10
0
 /**
  * Equivalent to cd command
  *
  * @throws IOException
  * @throws FileResourceException
  */
 public void setCurrentDirectory(String directory) throws FileResourceException {
   try {
     ftpClient.changeDir(directory);
   } catch (Exception e) {
     throw translateException("Cannot set the current directory", e);
   }
 }
Exemplo n.º 11
0
 /** Equivalent to mkdir */
 public void createDirectory(String directory) throws FileResourceException {
   try {
     ftpClient.makeDir(directory);
   } catch (Exception e) {
     throw translateException("Cannot create the directory", e);
   }
 }
Exemplo n.º 12
0
 /**
  * Stop the ftpClient from connecting to the server
  *
  * @throws IOException
  * @throws FileResourceException
  */
 public void stop() throws FileResourceException {
   try {
     ftpClient.close();
     setStarted(false);
   } catch (Exception e) {
     throw translateException("Error while stopping the FTP server", e);
   }
 }
Exemplo n.º 13
0
 /** Changes the permissions on the file if authorized to do so */
 public void changeMode(String filename, int mode) throws FileResourceException {
   String cmd = "chmod " + mode + " " + filename; // or something else
   try {
     ftpClient.site(cmd);
   } catch (Exception e) {
     throw translateException("Cannot change the file permissions", e);
   }
 }
Exemplo n.º 14
0
  /**
   * Equivalent to ls command in the current directory
   *
   * @throws IOException
   * @throws FileResourceException
   */
  public Collection<GridFile> list() throws FileResourceException {
    List<GridFile> gridFileList = new ArrayList<GridFile>();
    try {
      ftpClient.setPassive();
      ftpClient.setLocalActive();
      ftpClient.setType(Session.TYPE_ASCII);

      Enumeration<?> list = ftpClient.list().elements();
      ftpClient.setType(Session.TYPE_IMAGE);

      while (list.hasMoreElements()) {
        gridFileList.add(createGridFile(list.nextElement()));
      }
      return gridFileList;
    } catch (Exception e) {
      throw translateException("Cannot list the elements of the current directory", e);
    }
  }
Exemplo n.º 15
0
 /**
  * Returns the length of the file denoted by this abstract pathname.
  *
  * @return The length, in bytes, of the file denoted by this abstract pathname, or <code>0L</code>
  *     if the file does not exist
  */
 public long length() {
   try {
     return ftpClient.size(getPath());
   } catch (IOException e) {
     return 0;
   } catch (FTPException e) {
     return 0;
   }
 }
Exemplo n.º 16
0
  /**
   * Equivalent to ls command on the given directory
   *
   * @throws FileResourceException
   */
  public Collection<GridFile> list(String directory) throws FileResourceException {

    // Store currentDir
    String currentDirectory = getCurrentDirectory();
    // Change directory
    setCurrentDirectory(directory);
    Collection<GridFile> list = null;
    try {
      ftpClient.setType(Session.TYPE_ASCII);
      list = list();
      ftpClient.setType(Session.TYPE_IMAGE);
    } catch (Exception e) {
      throw translateException("Error in list directory", e);
    }

    // Come back to original directory
    setCurrentDirectory(currentDirectory);
    return list;
  }
Exemplo n.º 17
0
 /**
  * Tests whether the file denoted by this abstract pathname exists.
  *
  * @return <code>true</code> if and only if the file denoted by this abstract pathname exists;
  *     <code>false</code> otherwise
  */
 public boolean exists() {
   try {
     ftpClient.exists(getPath());
   } catch (IOException e) {
     return false;
   } catch (FTPException e) {
     return false;
   }
   return true;
 }
Exemplo n.º 18
0
 /**
  * Returns the time that the file denoted by this abstract pathname was last modified.
  *
  * @return A <code>long</code> value representing the time the file was last modified, measured in
  *     system-dependent way.
  */
 public long lastModified() {
   try {
     Date date = ftpClient.lastModified(getPath());
     return date.getTime();
   } catch (IOException e) {
     return 0;
   } catch (FTPException e) {
     return 0;
   }
 }
Exemplo n.º 19
0
 /** Creates the directory named by this abstract pathname. */
 public boolean mkdir() {
   try {
     ftpClient.makeDir(getPath());
     return true;
   } catch (IOException e) {
     return false;
   } catch (FTPException e) {
     return false;
   }
 }
Exemplo n.º 20
0
  /**
   * Copies this file to another file. This object is the source file. The destination file is given
   * as the argument. If the destination file, does not exist a new one will be created. Otherwise
   * the source file will be appended to the destination file. Directories will be copied
   * recursively.
   *
   * @param file The file to receive the data.
   * @throws NullPointerException If file is null.
   * @throws IOException If an IOException occurs.
   */
  public void copyTo(GeneralFile file, boolean forceOverwrite) throws IOException {
    if (file == null) {
      throw new NullPointerException();
    }

    if (isDirectory()) {
      // recursive copy
      GeneralFile[] fileList = listFiles();

      file.mkdir();
      if (fileList != null) {
        for (int i = 0; i < fileList.length; i++) {
          fileList[i].copyTo(
              FileFactory.newFile(
                  file.getFileSystem(), file.getAbsolutePath(), fileList[i].getName()),
              forceOverwrite);
        }
      }
    } else {
      if (file.isDirectory()) {
        // change the destination from a directory to a file
        file = FileFactory.newFile(file, getName());
      }
      try {
        if (file instanceof LocalFile) {
          ftpClient.get(getPath(), ((LocalFile) file).getFile());
        } else if (file instanceof FTPFile) {
          ftpClient.transfer(
              getPath(), ((FTPFile) file).getFTPClient(), file.getPath(), !forceOverwrite, null);
        } else {
          super.copyTo(file);
        }
      } catch (FTPException e) {
        IOException io = new IOException();
        io.initCause(e);
        throw io;
      }
    }
  }
Exemplo n.º 21
0
  public OutputStream openOutputStream(String name) throws FileResourceException {
    OutputStreamDataSource source = null;
    try {
      ftpClient.setPassive();
      ftpClient.setLocalActive();

      source = new OutputStreamDataSource(16384);

      TransferState state = ftpClient.asynchPut(name, source, null, false);
      state.waitForStart();

      return source.getOutputStream();
    } catch (Exception e) {
      if (source != null) {
        try {
          source.close();
        } catch (IOException ee) {
          logger.warn("Failed to close FTP source", ee);
        }
      }
      throw translateException("Failed to open FTP stream", e);
    }
  }
Exemplo n.º 22
0
  public InputStream openInputStream(String name) throws FileResourceException {
    InputStreamDataSink sink = null;
    try {
      ftpClient.setPassive();
      ftpClient.setLocalActive();

      sink = new InputStreamDataSink();

      TransferState state = ftpClient.asynchGet(name, sink, null);
      state.waitForStart();

      return sink.getInputStream();
    } catch (Exception e) {
      if (sink != null) {
        try {
          sink.close();
        } catch (IOException ee) {
          logger.warn("Failed to close FTP sink", ee);
        }
      }
      throw translateException("Failed to open FTP stream", e);
    }
  }
Exemplo n.º 23
0
  /** Remove directory and its files if force = true. Else remove directory only if empty */
  public void deleteDirectory(String directory, boolean force) throws FileResourceException {

    if (!isDirectory(directory)) {
      throw new DirectoryNotFoundException(directory + " is not a valid directory");
    }

    try {
      if (force) {
        for (GridFile f : list(directory)) {
          if (f.isFile()) {
            ftpClient.deleteFile(directory + "/" + f.getName());
          } else {
            deleteDirectory(directory + "/" + f.getName(), force);
          }
        }
      }
      if (list(directory).isEmpty()) {
        ftpClient.deleteDir(directory);
      }
    } catch (Exception e) {
      throw translateException("Cannot delete the given directory", e);
    }
  }
Exemplo n.º 24
0
  /**
   * Copies this file to another file. This object is the source file. The destination file is given
   * as the argument. If the destination file, does not exist a new one will be created. Otherwise
   * the source file will be appended to the destination file. Directories will be copied
   * recursively.
   *
   * @param file The file to receive the data.
   * @throws NullPointerException If file is null.
   * @throws IOException If an IOException occurs.
   */
  public void copyFrom(GeneralFile file, boolean forceOverwrite) throws IOException {
    if (file == null) {
      throw new NullPointerException();
    }

    if (file.isDirectory()) {
      // recursive copy
      GeneralFile[] fileList = file.listFiles();

      mkdir();
      if (fileList != null) {
        for (int i = 0; i < fileList.length; i++) {
          FileFactory.newFile(this, fileList[i].getName()).copyFrom(fileList[i], forceOverwrite);
        }
      }
    } else {
      if (isDirectory()) {
        // change the destination from a directory to a file
        GeneralFile subFile = FileFactory.newFile(this, file.getName());
        subFile.copyFrom(file);
        return;
      }
      try {
        if (file instanceof LocalFile) {
          ftpClient.put(((LocalFile) file).getFile(), getPath(), !forceOverwrite);
        } else if (file instanceof FTPFile) {
          ftpClient.transfer(file.getPath(), ftpClient, getPath(), !forceOverwrite, null);
        } else {
          super.copyTo(file);
        }
      } catch (FTPException e) {
        IOException io = new IOException();
        io.initCause(e);
        throw io;
      }
    }
  }
Exemplo n.º 25
0
 /**
  * Returns an array of strings naming the files and directories in the directory denoted by this
  * abstract pathname.
  *
  * <p>There is no guarantee that the name strings in the resulting array will appear in any
  * specific order; they are not, in particular, guaranteed to appear in alphabetical order.
  *
  * <p>If this GeneralFile object denotes a file, the results are unspecified.
  *
  * @return An array of strings naming the files and directories in the directory denoted by this
  *     abstract pathname.
  */
 public String[] list() {
   try {
     // TODO which list?
     Vector list = ftpClient.list(getPath());
     Object[] listO = list.toArray();
     String[] listS = new String[listO.length];
     for (int i = 0; i < listO.length; i++) {
       listS[i] = listO[i].toString();
     }
     return listS;
   } catch (IOException e) {
     return null;
   } catch (FTPException e) {
     return null;
   }
 }