예제 #1
1
 private void connectFtpServer() {
   try {
     ftpClient = new FTPClient();
     FTPClientConfig ftpClientConfig = new FTPClientConfig();
     ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
     ftpClient.configure(ftpClientConfig);
     URL url = getURL();
     if (url.getPort() <= 0) {
       ftpClient.connect(url.getHost());
     } else {
       ftpClient.connect(url.getHost(), url.getPort());
     }
     if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
       throw new VFSRuntimeException("连接失败!");
     }
     if (url.getUserInfo() != null) {
       String userInfo[] = url.getUserInfo().split(":");
       String userName = null;
       String password = null;
       if (userInfo.length >= 1) {
         userName = userInfo[0];
       }
       if (userInfo.length >= 2) {
         password = userInfo[1];
       }
       if (!ftpClient.login(userName, password)) {
         throw new VFSRuntimeException("登录失败:" + url.toString());
       }
       if (!ftpClient.setFileType(FTP.BINARY_FILE_TYPE)) {
         throw new VFSRuntimeException("设置二进制类型失败");
       }
       ftpClient.setBufferSize(BUF_SIZE);
       ftpClient.setControlEncoding("utf-8");
     }
   } catch (Exception e) {
     throw new VFSRuntimeException(e);
   }
 }
예제 #2
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;
 }
예제 #3
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()));
        }
      }
    }
  }
예제 #4
0
  /**
   * @param host
   * @param port
   * @param ftpUser
   * @param ftpPassword
   * @throws FtpException
   */
  private void conn(String host, int port, String ftpUser, String ftpPassword) throws FtpException {
    try {
      ftp.connect(host, port);

      boolean islogin = ftp.login(ftpUser, ftpPassword);
      if (!islogin) {
        close();
        throw new FtpException("Login Host Fail!");
      }

      String passiveMode = CIAConfig.get("FTPPASSIVEMODE");

      if (passiveMode != null && passiveMode.equals("remote")) {
        ftp.enterRemotePassiveMode();
      }
      if (passiveMode != null && passiveMode.equals("local")) {
        ftp.enterLocalPassiveMode();
      }

      System.out.println(
          host + " Login Host Succ,Current Path[ " + ftp.printWorkingDirectory() + "]");
    } catch (FtpException ex) {
      close();
      logger.info("FTP server initializtion error." + host);
      throw new FtpException("ftp init error!!" + ex.getMessage());
    } catch (Exception ex) {
      close();
      logger.info("FTP server initializtion error." + host);
      throw new FtpException("ftp init error!!" + ex.getMessage());
    }
  }
  @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;
  }
예제 #6
0
  /**
   * @param host
   * @param ftpUser
   * @param ftpPassword
   * @throws FtpException
   */
  private void conn(String host, String ftpUser, String ftpPassword) throws FtpException {
    try {
      ftp.connect(host);

      boolean islogin = ftp.login(ftpUser, ftpPassword);
      if (!islogin) {
        throw new FtpException("login FTP Host Fail!");
      }

      String passiveMode = CIAConfig.get("FTPPASSIVEMODE");

      if (passiveMode != null && passiveMode.equals("remote")) {
        ftp.enterRemotePassiveMode();
      }
      if (passiveMode != null && passiveMode.equals("local")) {
        ftp.enterLocalPassiveMode();
      }

    } catch (FtpException ex) {
      close();
      logger.info("FTP server initializtion error." + host);
      throw new FtpException("ftp init error!!" + ex.getMessage());
    } catch (Exception ex) {
      close();
      logger.info("FTP server initializtion error." + host);
      throw new FtpException("ftp init error!!" + ex.getMessage());
    }
  }
  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");
  }
예제 #8
0
 /** @return Si la conexión fue establecida o no */
 public boolean estabilishConnection() throws SocketException, IOException {
   boolean isConected = false;
   cliente.connect(this.server);
   isConected = cliente.login(username, password);
   cliente.changeWorkingDirectory(remoteDirectory);
   return isConected;
 }
예제 #9
0
  public static String downloadFromFTP(String url, String jarPath) {
    String[] splits = url.split("/");
    String filename = splits[splits.length - 1];
    FTPClient client = new FTPClient();
    FileOutputStream fos = null;

    try {
      client.connect(host);
      client.login(username, passwd);

      //
      // The remote filename to be downloaded.
      //
      fos = new FileOutputStream(jarPath + "/" + filename);
      //
      // Download file from FTP server
      //
      client.retrieveFile(url, fos);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if (fos != null) {
          fos.close();
        }
        client.disconnect();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return filename;
  }
예제 #10
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;
 }
예제 #11
0
  @Test
  public void loginFail() throws Exception {
    startServer(new String[] {"port=3131", "id=jxs", "password=1234", "home=" + home});
    client.connect("127.0.0.1", 3131);

    // login
    boolean authorized = client.login("jxs", "13234");
    assertFalse(authorized);
  }
예제 #12
0
  private void ftpFile(OrdersDocument ordsDoc, String filename, String warehouse) {
    //		if (ordsDoc.validate()) {
    // FTP
    try {
      FTPClient ftp = new FTPClient();
      if (isTest) {
        ftp.connect(Messages.getString(warehouse + "_testftp")); // $NON-NLS-1$
        ftp.login(
            Messages.getString(warehouse + "_testusername"),
            Messages.getString(warehouse + "_testpassword")); // $NON-NLS-1$ //$NON-NLS-2$
      } else {
        ftp.connect(Messages.getString(warehouse + "_ftp")); // $NON-NLS-1$
        ftp.login(
            Messages.getString(warehouse + "_username"),
            Messages.getString(warehouse + "_password")); // $NON-NLS-1$ //$NON-NLS-2$
      }

      System.out.println("Reply Code: " + ftp.getReplyCode()); // $NON-NLS-1$
      if ("ACTIVE".equalsIgnoreCase(Messages.getString(warehouse + "_mode"))) {
        ftp.enterLocalActiveMode();
      } else {
        ftp.enterLocalPassiveMode();
      }

      ftp.changeWorkingDirectory("ship"); // $NON-NLS-1$

      boolean success =
          ftp.storeFile(
              filename,
              new FileInputStream(Messages.getString("directory") + filename)); // $NON-NLS-1$
      System.out.println("FTP Success? " + success); // $NON-NLS-1$

      ftp.disconnect();
      System.out.println("Complete"); // $NON-NLS-1$

    } catch (SocketException e1) {
      e1.printStackTrace();
    } catch (IOException e1) {
      e1.printStackTrace();
    }
    //		}
  }
예제 #13
0
  @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);
    }
  }
예제 #14
0
 public void ftpconnect() throws FileNotFoundException, IOException {
   if (files.isEmpty()) {
     listFilesForFolder(new File("D:/gw2/static/"));
   }
   try {
     client.connect("ftp.atw.hu");
   } catch (SocketException ex) {
     Logger.getLogger(FTPUploader.class.getName()).log(Level.SEVERE, null, ex);
   } catch (IOException ex) {
     Logger.getLogger(FTPUploader.class.getName()).log(Level.SEVERE, null, ex);
   }
   try {
     client.login("peterimiki", "910506");
     // System.out.println("Kapcsolódás");
   } catch (IOException ex) {
     Logger.getLogger(FTPUploader.class.getName()).log(Level.SEVERE, null, ex);
   }
   // File index = new File("index.html");
   // FileWriter fw = new FileWriter(index);
   // fw.write("<html><body  style=\"font-color:black;\">\n<p>");
   for (File f : files) {
     try {
       fis = new FileInputStream(f);
       // System.out.println(f.getParent());
       if (f.getParent().length() == 13) {
         // fw.write("<a href=\"http://peterimiki.atw.hu/"
         //        +f.getParent().substring(7, f.getParent().length())
         // +f.getName()+"\">"+f.getParent().substring(7, f.getParent().length())
         // +f.getName()+"</a><br>\n");
         client.storeFile(f.getParent().substring(7, f.getParent().length()) + f.getName(), fis);
       } else if (f.getParent().length() > 13) {
         // fw.write("<a href=\"http://peterimiki.atw.hu/"
         //        +f.getParent().substring(22, f.getParent().length())
         // +f.getName()+"\">"+f.getParent().substring(22, f.getParent().length())
         // +f.getName()+"</a><br>\n");
         client.storeFile(f.getParent().substring(22, f.getParent().length()) + f.getName(), fis);
       }
       // System.out.println("Feltöltés");
       // client.storeFile(f.getParent().substring(7, f.getParent().length()) +f.getName(), fis);
       fis.close();
     } catch (Exception e) {
       e.printStackTrace();
       break;
     }
   }
   // Date d = new Date();
   // d.getTime();
   // fw.write("</p><p>last updated: "+d.toString()+"</p>\n");
   // fw.write("</body></html>");
   // fw.close();
   // client.storeFile("index.html", new FileInputStream(index));
   client.logout();
 }
예제 #15
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();
    }
  }
예제 #16
0
  private synchronized void connect2Server() throws SocketException, IOException {
    if (oFtp == null) {
      this.oFtp = new FTPClient();
    }

    if (log != null) {
      if (LogLevel.getValue(log.getLogLevel()).ordinal() > LogLevel.DEBUG.ordinal()) {
        oFtp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.err)));
      }
    }

    if (_port == 0) {
      oFtp.connect(this._sFtpHost, 21);
    } else {
      oFtp.connect(this._sFtpHost, _port);
    }
    if (!oFtp.login(this._sFtpUserName, this._sFtpPassword)) {
      logError("Can't login to server. FTP responce: " + oFtp.getReplyString());
    }

    oFtp.enterLocalPassiveMode();
  }
예제 #17
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;
  }
예제 #18
0
 public static FTPClient getConnection(String ip, int port, String username, String password) {
   FTPClient ftp = new FTPClient();
   try {
     ftp.connect(ip, port);
     // 连接FTP服务器
     // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
     ftp.login(username, password); // 登录
   } catch (SocketException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return ftp;
 }
예제 #19
0
  /**
   * 서버와 연결에 필요한 값들을 가져와 초기화 시킴
   *
   * @param host 서버 주소
   * @param userName 접속에 사용될 아이디
   * @param password 비밀번호
   * @param port 포트번호
   */
  public void init(String host, String userName, String password, int port) {
    client = new FTPClient();
    client.setControlEncoding("UTF-8"); // 한글 encoding....

    FTPClientConfig config = new FTPClientConfig();
    client.configure(config);
    try {
      client.connect(host, port);
      client.login(userName, password);
    } catch (SocketException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
예제 #20
0
 @Override
 public void connect() throws IOException {
   if (status == Status.CONNECTED) return;
   try {
     ftpClient.connect(cfg.getHostname(), cfg.getPort());
     if (!ftpClient.login(cfg.getUsername(), cfg.getPassword()))
       throw new IOException("cannot login to server (server reply: " + ftpClient.getReplyCode());
   } catch (FTPConnectionClosedException e) {
     status = Status.DEAD;
     throw new IOException("service unavailable", e);
   } catch (IOException e) {
     status = Status.DEAD;
     throw e;
   }
   status = Status.CONNECTED;
 }
예제 #21
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);
 }
예제 #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);
  }
예제 #23
0
  private static void ftpStuff() {
    try {

      FTPClient ftp = new FTPClient();
      ftp.connect("ftp.ncbi.nih.gov");

      System.out.println(ftp.getReplyString());

      ftp.login("anonymous", "*****@*****.**");

      System.out.println("before list files...");

      // ftp.li

      FTPFile[] files = ftp.listFiles(BASE_FOLDER);

      System.out.println(files.length);

      for (FTPFile file : files) {

        if (file.getName().endsWith(".gbff.gz")) {

          StringWriter writer = null;
          String charset = "ASCII";

          GZIPInputStream inputStream =
              new GZIPInputStream(ftp.retrieveFileStream(BASE_FOLDER + "/" + file.getName()));

          System.out.println("ftp.getControlEncoding() = " + ftp.getControlEncoding());

          Reader decoder = new InputStreamReader(inputStream, charset);
          BufferedReader buffered = new BufferedReader(decoder);

          String line = null;

          while ((line = buffered.readLine()) != null) {
            System.out.println("line = " + line);
          }

          System.exit(0);
        }
      }

    } catch (Exception ex) {
      Logger.getLogger(ImportGenBank.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
예제 #24
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;
  }
예제 #25
0
  @Test
  public void loginAnonymousAndUpload() throws Exception {
    startServer(new String[] {"home=" + home});
    client.connect("127.0.0.1", 2121);

    // login
    boolean authorized = client.login("anonymous", "*****@*****.**");
    assertTrue(authorized);

    // upload
    String fileName = "test.txt";
    InputStream content = openStreamFromClassPath(fileName);
    boolean stored = client.storeFile(fileName, content);
    assertTrue(stored);
    String savedFile = folder.getRoot().getAbsolutePath() + "/" + fileName;
    assertTrue(new File(savedFile).exists());
  }
예제 #26
0
  public static void main(String[] args) throws IOException {
    serverSocket = new ServerSocket(SERVER_PORT);

    ftpClient = new FTPClient();
    ftpClient.connect(IP_FTP_CLIENT);
    ftpClient.login(USERNAME, PASSWORD);
    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
    ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);

    while (true) {
      clientSocket = serverSocket.accept();
      log.info("Client is connected: " + clientSocket.isConnected());

      sendMockJSONScannedData();
      sendMockFTPScannedImg();
    }
  }
예제 #27
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;
  }
예제 #28
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());
    }
  }
  /**
   * 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();
     }
   }
 }