Exemple #1
11
  /**
   * Description: 从FTP服务器下载指定文件夹下的所有文件
   *
   * @param url FTP服务器hostname
   * @param port FTP服务器端口
   * @param username FTP登录账号
   * @param password FTP登录密码
   * @param remotePath FTP服务器上的相对路径
   * @param localPath 下载后保存到本地的路径
   * @param fileName 保存为该文件名的文件
   * @return
   */
  public static boolean downFile(
      String url,
      int port,
      String username,
      String password,
      String remotePath,
      String localPath,
      String fileName) {
    boolean success = false;
    FTPClient ftp = null;
    try {
      int reply;
      ftp = getConnection(url, port, username, password);
      reply = ftp.getReplyCode();
      if (!FTPReply.isPositiveCompletion(reply)) {
        ftp.disconnect();
        return success;
      }
      boolean changeWorkDirState = false;
      changeWorkDirState = ftp.changeWorkingDirectory(remotePath); // 转移到FTP服务器目录
      System.out.println(changeWorkDirState == true ? "切换FTP目录 成功" : "切换FTP目录 失败");
      if (changeWorkDirState == false) return false;
      FTPFile[] fs = ftp.listFiles();
      for (FTPFile ff : fs) {
        if (ff.getName().equals(fileName)) {
          File localFile = new File(localPath + "/" + ff.getName());

          OutputStream is = new FileOutputStream(localFile);
          ftp.retrieveFile(ff.getName(), is);
          is.close();
        }
      }

      ftp.logout();
      success = true;
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (ftp.isConnected()) {
        try {
          ftp.disconnect();
        } catch (IOException ioe) {
        }
      }
    }
    return success;
  }
Exemple #2
0
  public void uploadFile(String filePath, byte[] data) throws IOException {
    login();

    OutputStream os = ftpClient.storeFileStream(filePath);
    int ftpUploadReplyCode = ftpClient.getReplyCode();

    if (FTPReply.isNegativePermanent(ftpUploadReplyCode)) {
      throw new IOException("SERVER FTP:REQUEST DENIED");
    } else if (FTPReply.isNegativeTransient(ftpUploadReplyCode)) {
      uploadFile(filePath, data);
    }

    ByteArrayInputStream bais = new ByteArrayInputStream(data);
    IOUtils.copy(bais, os);

    bais.close();
    os.flush();
    os.close();

    if (!ftpClient.completePendingCommand()) {
      uploadFile(filePath, data);
    }

    logout();
  }
Exemple #3
0
  /**
   * Method that downloads a file from the FTP server.
   *
   * @param filepath is the absolute path of the file in the FTP server
   * @return the file content as byte[]
   * @throws IOException if an i/o error occurs.
   */
  public byte[] downloadFile(String filepath) throws IOException {
    login();

    FTPFile ftpFile = ftpClient.listFiles(filepath)[0];

    // file exists on FTP server?
    if (ftpFile == null) {
      throw new IOException("NULL FILE POINTER IN THE FTP SERVER");
    }

    // file is a directory?
    if (ftpFile.isDirectory()) {
      throw new IOException("FILE POINTER IS A DIRECTORY");
    }

    // its a file and exists. start download stream...
    InputStream is = ftpClient.retrieveFileStream(filepath);

    // how the server replied to the fetch command?
    int ftpReplyCode = ftpClient.getReplyCode();

    // denied?
    if (FTPReply.isNegativePermanent(ftpReplyCode)) {
      throw new IOException("SERVER FTP:REQUEST DENIED");

      // can we try again?
    } else if (FTPReply.isNegativeTransient(ftpReplyCode)) {
      // close the already open stream before try again...
      if (is != null) {
        is.close();
      }
      return downloadFile(filepath);
    }

    // server accepted the command
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // copying the file
    IOUtils.copy(is, baos);

    // closing open streams
    is.close();
    baos.flush();
    baos.close();

    // transaction is successful?
    boolean transactionCompleted = ftpClient.completePendingCommand();
    if (!transactionCompleted) {
      return downloadFile(filepath);
    }

    // we got the file
    logout();
    return baos.toByteArray();
  }
Exemple #4
0
  @Override
  public void send(Message message, TestContext context) {
    FtpMessage ftpMessage;
    if (message instanceof FtpMessage) {
      ftpMessage = (FtpMessage) message;
    } else {
      ftpMessage = new FtpMessage(message);
    }

    String correlationKeyName =
        getEndpointConfiguration().getCorrelator().getCorrelationKeyName(getName());
    String correlationKey =
        getEndpointConfiguration().getCorrelator().getCorrelationKey(ftpMessage);
    correlationManager.saveCorrelationKey(correlationKeyName, correlationKey, context);

    log.info(
        String.format(
            "Sending FTP message to: ftp://'%s:%s'",
            getEndpointConfiguration().getHost(), getEndpointConfiguration().getPort()));

    if (log.isDebugEnabled()) {
      log.debug("Message to be sent:\n" + ftpMessage.getPayload().toString());
    }

    try {
      connectAndLogin();

      int reply = ftpClient.sendCommand(ftpMessage.getCommand(), ftpMessage.getArguments());

      if (!FTPReply.isPositiveCompletion(reply) && !FTPReply.isPositivePreliminary(reply)) {
        throw new CitrusRuntimeException(
            String.format(
                "Failed to send FTP command - reply is: %s:%s", reply, ftpClient.getReplyString()));
      }

      log.info(
          String.format(
              "FTP message was successfully sent to: '%s:%s'",
              getEndpointConfiguration().getHost(), getEndpointConfiguration().getPort()));

      correlationManager.store(
          correlationKey,
          new FtpMessage(ftpMessage.getCommand(), ftpMessage.getArguments())
              .replyCode(reply)
              .replyString(ftpClient.getReplyString()));
    } catch (IOException e) {
      throw new CitrusRuntimeException("Failed to execute ftp command", e);
    }
  }
  @Override
  public PropertyList executeCallback(Metadata metadata, PropertyList properties)
      throws FTPException {

    try {
      int port = getPort(metadata.getPropertyList());
      String servername = getServername(metadata.getPropertyList());

      info("Connecting to FTP-Server: " + servername + ":" + port);
      start();
      getFTPClient().connect(servername, port);
      int reply = getFTPClient().getReplyCode();
      stop();

      if (!FTPReply.isPositiveCompletion(reply)) {
        getFTPClient().disconnect();
        throw new FTPException("FTP server refused connection");
      }
      return null;
    } catch (SocketException ex) {
      setException(ex);
      throw new FTPCommunicationException("Could not connect to FTP-Server", ex);
    } catch (IOException ex) {
      setException(ex);
      throw new FTPCommunicationException("Could not connect to FTP-Server", ex);
    }
  }
  private FTPFile[] listFilesInDirectory(String relPath) throws IOException {
    FTPFile[] files;

    // VFS-307: no check if we can simply list the files, this might fail if there are spaces in the
    // path
    files = getFtpClient().listFiles(relPath);
    if (FTPReply.isPositiveCompletion(getFtpClient().getReplyCode())) {
      return files;
    }

    // VFS-307: now try the hard way by cd'ing into the directory, list and cd back
    // if VFS is required to fallback here the user might experience a real bad FTP performance
    // as then every list requires 4 ftp commands.
    String workingDirectory = null;
    if (relPath != null) {
      workingDirectory = getFtpClient().printWorkingDirectory();
      if (!getFtpClient().changeWorkingDirectory(relPath)) {
        return null;
      }
    }

    files = getFtpClient().listFiles();

    if (relPath != null && !getFtpClient().changeWorkingDirectory(workingDirectory)) {
      throw new FileSystemException(
          "vfs.provider.ftp.wrapper/change-work-directory-back.error", workingDirectory);
    }
    return files;
  }
  public void run() {
    try {
      FTPClient c = new FTPClient();
      c.configure(ftpConfig);

      logger.debug("Trying to connect");
      c.connect("127.0.0.1", 21211);
      logger.debug("Connected");

      c.setSoTimeout(5000);

      if (!FTPReply.isPositiveCompletion(c.getReplyCode())) {
        logger.debug("Houston, we have a problem. D/C");
        c.disconnect();
        throw new Exception();
      }

      if (c.login("drftpd", "drftpd")) {
        logger.debug("Logged-in, now waiting 5 secs and kill the thread.");
        _sc.addSuccess();
        Thread.sleep(5000);
        c.disconnect();
      } else {
        logger.debug("Login failed, D/C!");
        throw new Exception();
      }
    } catch (Exception e) {
      logger.debug(e, e);
      _sc.addFailure();
    }

    logger.debug("exiting");
  }
  /**
   *
   *
   * <pre>
   * <b>Description:</b>
   * Function remove folder from ftp
   * <b>Creation date: </b>02.05.08
   * <b>Modification date: </b>02.05.08
   * </pre>
   *
   * @param String sDirPath � removed directory
   * @author Vitalii Fedorets
   * @return boolean � true if success
   */
  public boolean removeFolder(String sDirPath) throws Exception {
    try {
      File oDir = new File(sDirPath);

      FTPClient oFtp = this.initFtpClientLoginChangeWorkingDirectory(sDirPath);

      oFtp.changeWorkingDirectory(oDir.getParent().replace("\\", "/"));
      int iReply = oFtp.getReplyCode();

      if (!FTPReply.isPositiveCompletion(iReply)) {
        log.setError("Not change work directory to `" + oDir.getParent().replace("\\", "/") + "`");
        oFtp.disconnect();
        return false;
      }

      if (!oFtp.removeDirectory(sDirPath)) {
        log.setError("Could not remove directory `" + sDirPath + "`");
        oFtp.disconnect();
        return false;
      }

      return true;
    } catch (Exception oEx) {
      throw oEx;
    }
  }
Exemple #9
0
 public Object makeObject() throws Exception {
   FTPClient client = new FTPClient();
   try {
     if (uri.getPort() > 0) {
       client.connect(uri.getHost(), uri.getPort());
     } else {
       client.connect(uri.getHost());
     }
     if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
       throw new IOException("Ftp error: " + client.getReplyCode());
     }
     if (!client.login(uri.getUsername(), uri.getPassword())) {
       throw new IOException("Ftp error: " + client.getReplyCode());
     }
     if (!client.setFileType(FTP.BINARY_FILE_TYPE)) {
       throw new IOException("Ftp error. Couldn't set BINARY transfer type.");
     }
   } catch (Exception e) {
     if (client.isConnected()) {
       client.disconnect();
     }
     throw e;
   }
   return client;
 }
Exemple #10
0
 public FSDataInputStream open(Path file, int bufferSize) throws IOException {
   FTPClient client = connect();
   Path workDir = new Path(client.printWorkingDirectory());
   Path absolute = makeAbsolute(workDir, file);
   FileStatus fileStat = getFileStatus(client, absolute);
   if (fileStat.isDirectory()) {
     disconnect(client);
     throw new IOException("Path " + file + " is a directory.");
   }
   client.allocate(bufferSize);
   Path parent = absolute.getParent();
   // Change to parent directory on the
   // server. Only then can we read the
   // file
   // on the server by opening up an InputStream. As a side effect the working
   // directory on the server is changed to the parent directory of the file.
   // The FTP client connection is closed when close() is called on the
   // FSDataInputStream.
   client.changeWorkingDirectory(parent.toUri().getPath());
   InputStream is = client.retrieveFileStream(file.getName());
   FSDataInputStream fis = new FSDataInputStream(new FTPInputStream(is, client, statistics));
   if (!FTPReply.isPositivePreliminary(client.getReplyCode())) {
     // The ftpClient is an inconsistent state. Must close the stream
     // which in turn will logout and disconnect from FTP server
     fis.close();
     throw new IOException("Unable to open file: " + file + ", Aborting");
   }
   return fis;
 }
  /**
   * @param path ex:/upload/2023
   * @param filename xxx.jpg
   * @param input 输入流
   * @return
   */
  public static boolean uploadFile(String path, String filename, InputStream input) {
    boolean success = false;
    FTPClient ftpClient = null;
    try {
      ftpClient = getFTPClient();
      int reply = ftpClient.getReplyCode();
      if (!FTPReply.isPositiveCompletion(reply)) {

        return success;
      }
      // 使用二进制上传
      ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
      ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
      ftpClient.enterLocalPassiveMode();
      ftpCreateDirectoryTree(ftpClient, path);
      success = ftpClient.storeFile(filename, input);
      input.close();
      ftpClient.logout();

    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (null != ftpClient && ftpClient.isConnected()) {
        try {
          ftpClient.disconnect();
        } catch (IOException ioe) {
        }
      }
    }
    return success;
  }
  public static FTPClient getFTPClient() {
    FTPClient client = ftpClientThreadLocal.get();
    if (client != null && client.isConnected()) {
      return client;
    }
    ftpClientThreadLocal.remove();
    FTPClient ftpClient = new FTPClient(); // 创建ftpClient
    ftpClient.setControlEncoding("UTF-8"); // 设置字符编码
    Boolean isConnect = connectFtp(ftpClient);

    ftpClient.enterLocalPassiveMode();
    try {
      ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
      ftpClient.setSoTimeout(1000 * 30);
    } catch (Exception e) {
      e.printStackTrace();
    }
    // 得到返回答复码
    int reply = ftpClient.getReplyCode();

    if (!FTPReply.isPositiveCompletion(reply)) {
      try {
        ftpClient.disconnect();
      } catch (IOException e) {
        e.printStackTrace();
      }

    } else {
      ftpClientThreadLocal.set(ftpClient);
    }
    return ftpClient;
  }
  @Deprecated
  private FTPClient initFtpClientAndLogin() throws SocketException, IOException {
    if (oFtp != null) {
      return oFtp;
    }

    FTPClient oFtp = new FTPClient();

    int iReply;

    oFtp.connect(_sFtpHost);

    iReply = oFtp.getReplyCode();

    if (!FTPReply.isPositiveCompletion(iReply)) {
      log.setError("Could not connect to ftp host" + _sFtpHost);
      return null;
    }

    if (!oFtp.login(_sFtpUserName, _sFtpPassword)) {
      log.error(
          "Could not login with user `" + _sFtpUserName + "` and password `" + _sFtpPassword + "`");
      oFtp.disconnect();
      return null;
    }
    oFtp.enterLocalPassiveMode();
    return oFtp;
  }
Exemple #14
0
  /**
   * Opens a new connection and performs login with user name and password if set.
   *
   * @throws IOException
   */
  protected void connectAndLogin() throws IOException {
    if (!ftpClient.isConnected()) {
      ftpClient.connect(getEndpointConfiguration().getHost(), getEndpointConfiguration().getPort());

      log.info("Connected to FTP server: " + ftpClient.getReplyString());

      int reply = ftpClient.getReplyCode();

      if (!FTPReply.isPositiveCompletion(reply)) {
        throw new CitrusRuntimeException("FTP server refused connection.");
      }

      log.info("Successfully opened connection to FTP server");

      if (getEndpointConfiguration().getUser() != null) {
        log.info(String.format("Login as user: '******'", getEndpointConfiguration().getUser()));
        boolean login =
            ftpClient.login(
                getEndpointConfiguration().getUser(), getEndpointConfiguration().getPassword());

        if (!login) {
          throw new CitrusRuntimeException(
              String.format(
                  "Failed to login to FTP server using credentials: %s:%s",
                  getEndpointConfiguration().getUser(), getEndpointConfiguration().getPassword()));
        }
      }
    }
  }
Exemple #15
0
 /**
  * Description: 向FTP服务器上传文件
  *
  * @param host FTP服务器hostname
  * @param port FTP服务器端口
  * @param username FTP登录账号
  * @param password FTP登录密码
  * @param basePath FTP服务器基础目录
  * @param filePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath
  * @param filename 上传到FTP服务器上的文件名
  * @param input 输入流
  * @return 成功返回true,否则返回false
  */
 public static boolean uploadFile(
     String host,
     int port,
     String username,
     String password,
     String basePath,
     String filePath,
     String filename,
     InputStream input) {
   boolean result = false;
   FTPClient ftp = new FTPClient();
   try {
     int reply;
     ftp.connect(host, port); // 连接FTP服务器
     // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
     ftp.login(username, password); // 登录
     reply = ftp.getReplyCode();
     if (!FTPReply.isPositiveCompletion(reply)) {
       ftp.disconnect();
       return result;
     }
     // 切换到上传目录
     if (!ftp.changeWorkingDirectory(basePath + filePath)) {
       // 如果目录不存在创建目录
       String[] dirs = filePath.split("/");
       String tempPath = basePath;
       for (String dir : dirs) {
         if (null == dir || "".equals(dir)) continue;
         tempPath += "/" + dir;
         if (!ftp.changeWorkingDirectory(tempPath)) {
           if (!ftp.makeDirectory(tempPath)) {
             return result;
           } else {
             ftp.changeWorkingDirectory(tempPath);
           }
         }
       }
     }
     // 设置上传文件的类型为二进制类型
     ftp.setFileType(FTP.BINARY_FILE_TYPE);
     // 上传文件
     if (!ftp.storeFile(filename, input)) {
       return result;
     }
     input.close();
     ftp.logout();
     result = true;
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     if (ftp.isConnected()) {
       try {
         ftp.disconnect();
       } catch (IOException ioe) {
       }
     }
   }
   return result;
 }
Exemple #16
0
  /**
   * A stream obtained via this call must be closed before using other APIs of this class or else
   * the invocation will block.
   */
  public FSDataOutputStream create(
      Path file,
      FsPermission permission,
      boolean overwrite,
      int bufferSize,
      short replication,
      long blockSize,
      Progressable progress)
      throws IOException {
    final FTPClient client = connect();
    Path workDir = new Path(client.printWorkingDirectory());
    Path absolute = makeAbsolute(workDir, file);
    if (exists(client, file)) {
      if (overwrite) {
        delete(client, file);
      } else {
        disconnect(client);
        throw new IOException("File already exists: " + file);
      }
    }

    Path parent = absolute.getParent();
    if (parent == null || !mkdirs(client, parent, FsPermission.getDefault())) {
      parent = (parent == null) ? new Path("/") : parent;
      disconnect(client);
      throw new IOException("create(): Mkdirs failed to create: " + parent);
    }
    client.allocate(bufferSize);
    // Change to parent directory on the server. Only then can we write to the
    // file on the server by opening up an OutputStream. As a side effect the
    // working directory on the server is changed to the parent directory of the
    // file. The FTP client connection is closed when close() is called on the
    // FSDataOutputStream.
    client.changeWorkingDirectory(parent.toUri().getPath());
    FSDataOutputStream fos =
        new FSDataOutputStream(client.storeFileStream(file.getName()), statistics) {

          public void close() throws IOException {
            super.close();
            if (!client.isConnected()) {
              throw new FTPException("Client not connected");
            }
            boolean cmdCompleted = client.completePendingCommand();
            disconnect(client);
            if (!cmdCompleted) {
              throw new FTPException(
                  "Could not complete transfer, Reply Code - " + client.getReplyCode());
            }
          }
        };
    if (!FTPReply.isPositivePreliminary(client.getReplyCode())) {
      // The ftpClient is an inconsistent state. Must close the stream
      // which in turn will logout and disconnect from FTP server
      fos.close();
      throw new IOException("Unable to create file: " + file + ", Aborting");
    }
    return fos;
  }
  @Override
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String[] args = null;
    String nomeArquivo = null;
    FTPClient ftp = new FTPClient();
    try {
      ftp.connect("ftp.provedor.com.br");

      // verifica se conectou com sucesso!
      if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
        ftp.login("usuario", "senha");
      } else {
        // erro ao se conectar
        ftp.disconnect();
        System.out.println("Conex�o recusada");
        System.exit(1);
      }

      ftp.changeWorkingDirectory("C:/Editorias/Futebol - CLASSIFICA��O");
      // para cada arquivo informado...
      for (int i = 0; i < args.length; i++) {
        // abre um stream com o arquivo a ser enviado
        InputStream is = new FileInputStream(args[i]);
        // pega apenas o nome do arquivo
        int idx = args[i].lastIndexOf(File.separator);
        if (idx < 0) idx = 0;
        else idx++;
        nomeArquivo = args[i].substring(idx, args[i].length());

        // ajusta o tipo do arquivo a ser enviado
        if (args[i].endsWith(".txt")) {
          ftp.setFileType(FTPClient.ASCII_FILE_TYPE);
        } else if (args[i].endsWith(".jpg")) {
          ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        } else {
          ftp.setFileType(FTPClient.ASCII_FILE_TYPE);
        }
        System.out.println("Enviando arquivo " + nomeArquivo + "...");

        // faz o envio do arquivo
        ftp.storeFile(nomeArquivo, is);
        System.out.println("Arquivo " + nomeArquivo + " enviado com sucesso!");
      }

      ftp.disconnect();
      System.out.println("Fim. Tchau!");
    } catch (Exception e) {
      System.out.println("Ocorreu um erro: " + e);
      System.exit(1);
    }
  }
Exemple #18
0
  public void connectFtp() throws Exception {
    ftp.setDefaultTimeout(1500);
    ftp.connect(hcs.getAddress());
    ftp.login(hcs.getUsername(), hcs.getPassword());
    int reply = ftp.getReplyCode();

    if (FTPReply.isPositiveCompletion(reply)) {
      System.out.println("HCS " + hcs.getLabel() + ": Connected successfully");
    } else {
      System.out.println("HCS " + hcs.getLabel() + ": Connection failed");
      ftp.disconnect();
    }
  }
Exemple #19
0
  public boolean test() {

    int base = 0;
    boolean error = false;
    FTPFile[] ftpFiles;

    testMsg = null;

    try {
      int reply;
      ftpClient.connect(ftpVO.getServer(), ftpVO.getPortasInteger());

      // Check connection
      reply = ftpClient.getReplyCode();
      if (!FTPReply.isPositiveCompletion(reply)) {
        ftpClient.disconnect();
        testMsg = Resource.getString("ftpchooser.msg.noconnect");
        return false;
      }

      // Login
      if (!ftpClient.login(ftpVO.getUser(), ftpVO.getPassword())) {
        ftpClient.logout();
        testMsg = Resource.getString("ftpchooser.msg.nologin");
        return false;
      }

      ftpClient.syst();

      // Change directory
      if (!ftpClient.changeWorkingDirectory(ftpVO.getDirectory())) {
        testMsg = Resource.getString("ftpchooser.msg.nodirectory");
        return false;
      }

      testMsg = Resource.getString("ftpchooser.msg.success");
      ftpClient.logout();

    } catch (IOException ex) {
      testMsg = ex.getLocalizedMessage();
      error = true;
    } finally {
      if (ftpClient.isConnected()) {
        try {
          ftpClient.disconnect();
        } catch (IOException f) {
        }
      }
    }
    return !error;
  }
  /**
   * @param remotePath 远程文件路径ַ ex:/upload/2012/xxxx.jpg
   * @param out 文件输出流
   * @return
   */
  public static boolean downFile(String remotePath, OutputStream out) {
    Boolean flag = Boolean.FALSE;
    // 得到文件名 ex: xxxx.jpg
    String fileName = getLastName(remotePath);
    // 得到文件存储路径 ex:/upload/2012
    String remoteStorePath = getFilePath(remotePath);
    FTPClient ftpClient = null;
    try {
      ftpClient = getFTPClient();
      // 得到返回答复码
      int reply = ftpClient.getReplyCode();

      if (!FTPReply.isPositiveCompletion(reply)) {
        try {
          ftpClient.disconnect();
          return flag;
        } catch (IOException e) {
          e.printStackTrace();
          return flag;
        }
      }

      ftpClient.changeWorkingDirectory(remoteStorePath);

      // ftpClient.setFileType(FTP.BINARY_FILE_TYPE);//

      FTPFile[] fs = ftpClient.listFiles();
      for (FTPFile file : fs) {
        if (fileName.equalsIgnoreCase(file.getName())) {
          flag = ftpClient.retrieveFile(fileName, out);

          break;
        }
      }
      ftpClient.logout();
    } catch (IOException e) {
      e.printStackTrace();

    } finally {
      if (null != ftpClient && ftpClient.isConnected()) {
        try {
          ftpClient.disconnect();
        } catch (IOException ioe) {
        }
      }
    }

    return flag;
  }
Exemple #21
0
 public static boolean mkdir(FTPClient ftp, String path) throws IOException {
   String[] pathNames = path.split("/");
   ftp.changeWorkingDirectory("/");
   for (int i = 0; i < pathNames.length; i++) {
     if (!ftp.changeWorkingDirectory(pathNames[i])) {
       if (FTPReply.isPositiveCompletion(ftp.mkd(pathNames[i]))) {
         ftp.changeWorkingDirectory(pathNames[i]);
       } else {
         FTPLogger.error("Make dir failed with path: " + pathNames[i]);
         return false;
       }
     }
   }
   return true;
 }
Exemple #22
0
  private void connect() throws SocketException, IOException {
    // send the command..
    ftpClient.connect(host, hostPort);

    // check reply code...
    int replyCode = ftpClient.getReplyCode();
    boolean sucess = FTPReply.isPositiveCompletion(replyCode);

    // sucess?
    if (!sucess) {
      ftpClient.disconnect();
      throw new IOException("FTP server refused connection.");
    }

    setConnected(sucess);
  }
Exemple #23
0
 @Override
 public void connect() {
   LOGGER.info("Connecting to " + username() + "@" + host() + ":" + String.valueOf(port()));
   reconnect = true;
   try {
     ftpClient.connect(host(), port());
   } catch (IOException e) {
     throw new VirtualFileException(e);
   }
   if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
     disconnect();
     return;
   }
   login();
   setFileType(FTP.BINARY_FILE_TYPE);
 }
Exemple #24
0
  public boolean open() {
    boolean isSuccessful = false;

    if (isOpen) {
      throw new IllegalStateException("Is already open, must be closed before!");
    }

    try {
      int reply;
      ftpClient.connect(ftpVO.getServer(), ftpVO.getPortasInteger());

      reply = ftpClient.getReplyCode();

      if (!FTPReply.isPositiveCompletion(reply)) {
        ftpClient.disconnect();
        throw new IOException("Can't connect!");
      }

      if (!ftpClient.login(ftpVO.getUser(), ftpVO.getPassword())) {
        ftpClient.logout();
        throw new IOException("Can't login!");
      }

      if (!ftpClient.changeWorkingDirectory(ftpVO.getDirectory())) {
        ftpClient.logout();
        throw new IOException("Can't change directory!");
      }

      ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
      ftpClient.enterLocalPassiveMode();

      isSuccessful = true;

    } catch (Exception e) {
      if (ftpClient.isConnected()) {
        try {
          ftpClient.disconnect();
        } catch (IOException f) {
          // do nothing
        }
      }
      isSuccessful = false;
    }
    isOpen = isSuccessful;
    return isSuccessful;
  }
Exemple #25
0
  /**
   * Description: 从FTP服务器下载文件
   *
   * @param host FTP服务器hostname
   * @param port FTP服务器端口
   * @param username FTP登录账号
   * @param password FTP登录密码
   * @param remotePath FTP服务器上的相对路径
   * @param fileName 要下载的文件名
   * @param localPath 下载后保存到本地的路径
   * @return
   */
  public static boolean downloadFile(
      String host,
      int port,
      String username,
      String password,
      String remotePath,
      String fileName,
      String localPath) {
    boolean result = false;
    FTPClient ftp = new FTPClient();
    try {
      int reply;
      ftp.connect(host, port);
      // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
      ftp.login(username, password); // 登录
      reply = ftp.getReplyCode();
      if (!FTPReply.isPositiveCompletion(reply)) {
        ftp.disconnect();
        return result;
      }
      ftp.changeWorkingDirectory(remotePath); // 转移到FTP服务器目录
      FTPFile[] fs = ftp.listFiles();
      for (FTPFile ff : fs) {
        if (ff.getName().equals(fileName)) {
          File localFile = new File(localPath + "/" + ff.getName());

          OutputStream is = new FileOutputStream(localFile);
          ftp.retrieveFile(ff.getName(), is);
          is.close();
        }
      }

      ftp.logout();
      result = true;
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (ftp.isConnected()) {
        try {
          ftp.disconnect();
        } catch (IOException ioe) {
        }
      }
    }
    return result;
  }
Exemple #26
0
  private void login(String host, String login, String password) throws IOException {
    ftpClient.connect(host);
    ftpClient.login(login, password);

    int reply = ftpClient.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
      ftpClient.disconnect();

      LOGGER.error(
          "ftp server {} refused connection, reply string: {}", host, ftpClient.getReplyString());

      throw new RuntimeException("ftp server " + host + " refused connection");
    }

    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Connected to {}, reply string: {}", host, ftpClient.getReplyString());
    }
  }
  /**
   * @param sDirPath
   * @return
   * @throws SocketException
   * @throws IOException
   */
  private FTPClient initFtpClientLoginChangeWorkingDirectory(String sDirPath)
      throws SocketException, IOException {
    if (oFtp != null) {
      return oFtp;
    }

    oFtp = initFtpClientAndLogin();
    int iReply;
    oFtp.changeWorkingDirectory(sDirPath);
    iReply = oFtp.getReplyCode();

    if (!FTPReply.isPositiveCompletion(iReply)) {
      log.setError("Not change work directory to `" + sDirPath + "`");
      oFtp.disconnect();
      return null;
    }
    return oFtp;
  }
  /**
   * Connect to ftp server
   *
   * @param server the host you connect
   * @param user the user account to login [anonymous as default]
   * @param passwd the password according to you account, and if the account is anonymous "" as
   *     default
   */
  public void initConnection(String server, String user, String passwd) {
    ftp = new FTPClient();
    try {
      ftp.connect(server);
      ftp.login(user, passwd);
      int reply = ftp.getReplyCode();
      if (!FTPReply.isPositiveCompletion(reply)) {
        ftp.disconnect();
        LogUtils.log("disconnect after login");
      }
      LogUtils.log("Connected to " + server + " with name [" + user + "]");
    } catch (SocketException e) {

      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 public static void main(String[] args) {
   String server = "localhost";
   int port = 16885;
   String user = "******";
   String pass = "******";
   FTPClient ftpClient = new FTPClient();
   try {
     ftpClient.connect(server, port);
     showServerReply(ftpClient);
     int replyCode = ftpClient.getReplyCode();
     if (!FTPReply.isPositiveCompletion(replyCode)) {
       System.out.println("Operation failed. Server reply code: " + replyCode);
       return;
     }
     boolean success = ftpClient.login(user, pass);
     ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
     showServerReply(ftpClient);
     if (!success) {
       System.out.println("Could not login to the server");
       return;
     } else {
       System.out.println("LOGGED IN SERVER");
       ftpClient.changeWorkingDirectory("C:\\Users\\Dileep\\Desktop\\temp");
       // File outFile = new File("C:\\Users\\Dileep\\Desktop\\temp\\newFolder","NewFile.txt");
       ftpClient.enterLocalPassiveMode();
       // FileOutputStream outputStream = new FileOutputStream(outFile);
       InputStream fileInputStream = ftpClient.retrieveFileStream("Dileep.txt");
       manipulateFile(fileInputStream);
       /*if (ftpClient.retrieveFile("Dileep.txt", outputStream)){
       	outputStream.close();
       }*/
     }
     ftpClient.logout();
   } catch (IOException ex) {
     System.out.println("Oops! Something wrong happened");
     ex.printStackTrace();
   } finally {
     try {
       ftpClient.disconnect();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
  private FTPClient connect() throws FTPException {
    try {
      FTPClient ftp = new FTPClient();
      ftp.connect(host, port);
      int reply = ftp.getReplyCode();

      if (!FTPReply.isPositiveCompletion(reply)) {
        ftp.disconnect();
        System.err.println("FTP server refused connection.");
      }
      ftp.login(userName, password);
      ftp.setFileType(FTP.BINARY_FILE_TYPE);
      return ftp;
    } catch (SocketException e) {
      throw new FTPException("Failed to connect to server", e);
    } catch (IOException e) {
      throw new FTPException("Failed to connect to server", e);
    }
  }