Esempio n. 1
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();
 }
Esempio n. 2
0
  /**
   * Download a file from the server
   *
   * @param fileName
   * @param isTextFile
   * @return
   */
  public boolean putFile(String remoteFileName, String localFileName, boolean isTextFile)
      throws FtpException {

    try {
      if (isTextFile) {
        ftp.setFileType(FTPClient.ASCII_FILE_TYPE);
      } else {
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
      }

      boolean isValidWrt = ftp.storeFile(remoteFileName, new FileInputStream(localFileName));

      if (!isValidWrt) {
        throw new FtpException("remote file or local file is not exist!");
      }

    } catch (Exception ex) {
      logger.info(
          "\\== ERROR WHILE EXECUTE FTP ==// (File Name:"
              + localFileName
              + " ==> "
              + remoteFileName
              + ") >>>>>>>>>>>>>"
              + ex.getLocalizedMessage());
      close();
      throw new FtpException("ftp file exception:" + ex.getMessage());
    }
    return true;
  }
  /**
   * @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;
  }
Esempio n. 4
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;
 }
Esempio n. 5
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);
    }
  }
Esempio n. 6
0
  public void uploadFile(String name, InputStream input) throws Exception {
    ftp.enterLocalPassiveMode();

    ftp.changeWorkingDirectory(DEFAULT_WORKING_DIR);
    Logger.log("HCS " + hcs.getLabel() + ": Current directory is " + ftp.printWorkingDirectory());

    ftp.enterLocalPassiveMode();

    ftp.storeFile(name, input);
    ftp.logout();
    ftp.disconnect();

    Logger.log("HCS " + hcs.getLabel() + ": Upload of ppEngine.dat complete!");
  }
Esempio n. 7
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());
  }
Esempio n. 8
0
  private static void sendMockFTPScannedImg() throws IOException {
    log.info(String.format("ftp is connected at %s: %s", ftpClient.isConnected(), "IP_FTP_CLIENT"));

    String filename = dateFormat.format(new Date()).replace(' ', '_').replace(':', '_');
    String remote = String.format("%s/%s.jpg", CLIENT_IMG_DIR, filename);

    BufferedInputStream bis = null;
    try {
      bis = new BufferedInputStream(new FileInputStream("test.jpg"));
      ftpClient.storeFile(remote, bis);
      log.info(String.format("Sending file as %s", remote));
      bis.close();

    } catch (FileNotFoundException e) {
      log.info("couldn't find file");
    }
  }
 public void writeTempFile(String fileName, String sessionId, InputStream is) throws FTPException {
   FTPClient ftp = connect();
   try {
     ftp.makeDirectory("temp");
     ftp.changeWorkingDirectory("temp");
     ftp.makeDirectory(sessionId);
     ftp.changeWorkingDirectory(sessionId);
     ftp.storeFile(fileName, is);
     ftp.logout();
   } catch (IOException e) {
     LOGGER.error("Could not write tempfile " + fileName, e);
   } finally {
     try {
       ftp.disconnect();
     } catch (IOException e) {
       // Empty...
     }
   }
 }
Esempio n. 10
0
  /**
   * 하나의 파일을 업로드 한다.
   *
   * @param dir 저장시킬 주소(서버)
   * @param file 저장할 파일
   */
  public void upload(String dir, File file) {

    InputStream in = null;

    try {
      in = new FileInputStream(file);
      client.storeFile(dir + file.getName(), in);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        in.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
Esempio n. 11
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();
    }
    //		}
  }
Esempio n. 12
0
  public static void main(String[] args) {
    String server = "192.168.1.72";
    int port = 21;
    String user = "******";
    String pass = "******";

    FTPClient ftpClient = new FTPClient();
    try {

      ftpClient.connect(server, port);
      ftpClient.login(user, pass);
      ftpClient.enterLocalPassiveMode();

      ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

      // APPROACH #1: uploads first file using an InputStream
      File firstLocalFile = new File("D:/Shridhar/FolderTest/ItmtuResponsestatus_2012_1_18_15");

      String firstRemoteFile = "/home/ftp/";
      InputStream inputStream = new FileInputStream(firstLocalFile);

      System.out.println("Start uploading first file");
      boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
      inputStream.close();
      if (done) {
        System.out.println("The first file is uploaded successfully.");
      }

    } catch (IOException ex) {
      System.out.println("Error: " + ex.getMessage());
      ex.printStackTrace();
    } finally {
      try {
        if (ftpClient.isConnected()) {
          // ftpClient.logout();
          ftpClient.disconnect();
        }
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
  }
Esempio n. 13
0
 /**
  * Uploads a local file to the FTP server.
  *
  * @param remote Name of the remote file
  * @param local Local InputStream
  * @param isBinaryFile Indication iff the file is binary
  * @throws FtpException
  */
 public void upload(String remote, InputStream local, boolean isBinaryFile) throws FtpException {
   if (ftp == null) {
     throw new FtpException(NOT_CONNECTED);
   }
   try {
     if (isBinaryFile) {
       ftp.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
     }
     boolean ok = ftp.storeFile(remote, local);
     if (!ok) {
       String msg = ftp.getReplyString();
       throw new FtpException(msg);
     }
     local.close();
   } catch (FileNotFoundException fnfe) {
     throw new FtpException(fnfe);
   } catch (IOException ioe) {
     throw new FtpException(ioe);
   }
 }
Esempio n. 14
0
 public void testFtpClient() throws Exception {
   // 创建一个FtpClient对象
   FTPClient ftpClient = new FTPClient();
   // 创建ftp连接。默认是21端口
   ftpClient.connect("139.129.95.90", 21);
   // 登录ftp服务器,使用用户名和密码
   ftpClient.login("ftpuser", "yukunpeng");
   // 上传文件。
   // 读取本地文件
   FileInputStream inputStream =
       new FileInputStream(new File("/Users/yukunpeng/Downloads/壁纸/01.jpg"));
   // 设置上传的路径
   ftpClient.changeWorkingDirectory("/www/images");
   // 修改上传文件的格式
   ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
   // 第一个参数:服务器端文档名
   // 第二个参数:上传文档的inputStream
   ftpClient.storeFile("02.jpg", inputStream);
   // 关闭连接
   ftpClient.logout();
 }
  private void storeFile(String ftp, String itemId, File appDir) {
    String scheme;

    try {
      scheme = ftp.substring(0, ftp.indexOf(":"));
      if (scheme.equals("ftp")) {
        FTPLinkTokenizer tokenizer;

        tokenizer = new FTPLinkTokenizer(ftp);

        FTPClient f = new FTPClient();
        f.setDefaultPort(Integer.parseInt(tokenizer.getPort()));
        f.connect(tokenizer.getHost());
        f.setFileType(FTP.BINARY_FILE_TYPE);

        if (tokenizer.getUsername() != null) {
          f.login(tokenizer.getUsername(), tokenizer.getPassword());
        }

        int reply = f.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
          f.disconnect();
          return;
        }

        Properties prop = Prefs.load(appDir);
        File fromFile = new File(prop.getProperty("download.dir"), itemId);

        InputStream stream;
        stream = new FileInputStream(fromFile);
        f.storeFile(tokenizer.getPath(), stream);
        f.logout();

        FTPAccessible.add(itemId, ftp);
      }
    } catch (Exception e) {
      Log.logException(e);
    }
  }
  public static void main(String[] args) throws IOException {

    OLAFile olaFile =
        new OLAFile(
            19,
            56,
            51,
            "1111333355557777",
            "P161486",
            "M",
            "AG",
            "Nanninga",
            "Testweg",
            "12",
            "9439 HW",
            "Achterwoude",
            "987654",
            "Flipje Betuwe");

    String server = "192.168.55.2";

    FTPClient ftp = new FTPClient();
    ftp.connect(server);
    ftp.enterLocalPassiveMode();
    ftp.setFileType(FTP.BINARY_FILE_TYPE);

    System.out.println("Connected to " + server + ".");
    System.out.print(ftp.getReplyString());

    InputStream inputStream = olaFile.getInputStream();
    System.out.println("uploading file");
    boolean done = ftp.storeFile("input/" + olaFile.getRef() + ".ola", inputStream);
    inputStream.close();

    if (done) {
      System.out.println("uploaded file");
    } else {
      System.out.println("upload failed");
    }
  }
Esempio n. 17
0
  private void uploadDir(File directory) throws IOException {

    try {
      String[] children = directory.list();

      if (children == null) {
        // Either dir does not exist or is not a directory
      } else {
        for (String filename : children) {
          File f = new File(directory, filename);
          if (f.isDirectory()) {
            ftpClient.mkd(f.getName());
            ftpClient.changeWorkingDirectory(f.getName());

            uploadDir(f);

            ftpClient.changeToParentDirectory();
          } else {
            if (!uploaded.contains(filename)) {
              LOGGER.debug("uploading file: {}", filename);
              messageListener.addMessage(new Message("uploading file: " + filename));

              ftpClient.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
              ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);

              ftpClient.enterLocalPassiveMode();
              InputStream is =
                  new BufferedInputStream(new FileInputStream(directory + "/" + filename));
              ftpClient.storeFile(filename, is);

              uploaded.add(filename);
            }
          }
        }
      }
    } catch (IOException e) {
      LOGGER.error("Upload failure");
      throw new IOException(e);
    }
  }
Esempio n. 18
0
 public static void upload(
     String server, String username, String password, String remotePath, File file)
     throws IOException {
   FTPClient mFtp = new FTPClient();
   try {
     mFtp.connect(server, FTP.DEFAULT_PORT);
     mFtp.login(username, password);
     mFtp.setFileType(FTP.BINARY_FILE_TYPE);
     mFtp.enterLocalPassiveMode();
     InputStream is = new FileInputStream(file);
     mFtp.storeFile(remotePath, is);
     is.close();
   } finally {
     try {
       if (mFtp.isConnected()) {
         mFtp.logout();
         mFtp.disconnect();
       }
     } catch (IOException ex) {
       ex.printStackTrace();
     }
   }
 }
Esempio n. 19
0
  private static void uploadFileViaFTP(FTPClient ftpClient) throws IOException {
    // TODO Auto-generated method stub
    // APPROACH #1: uploads first file using an InputStream
    File firstLocalFile = new File("D:/ge.txt");

    String firstRemoteFile = "/export/home/fuse/ftttttp.txt";
    ;
    InputStream inputStream = new FileInputStream(firstLocalFile);

    System.out.println("Start uploading first file");
    boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
    inputStream.close();
    if (done) {
      System.out.println("The first file is uploaded successfully.");
    }

    //        // APPROACH #2: uploads second file using an OutputStream
    //        File secondLocalFile = new File("E:/Test/Report.doc");
    //        String secondRemoteFile = "test/Report.doc";
    //        inputStream = new FileInputStream(secondLocalFile);
    //
    //        System.out.println("Start uploading second file");
    //        OutputStream outputStream = ftpClient.storeFileStream(secondRemoteFile);
    //        byte[] bytesIn = new byte[4096];
    //        int read = 0;
    //
    //        while ((read = inputStream.read(bytesIn)) != -1) {
    //            outputStream.write(bytesIn, 0, read);
    //        }
    //        inputStream.close();
    //        outputStream.close();
    //
    //        boolean completed = ftpClient.completePendingCommand();
    //        if (completed) {
    //            System.out.println("The second file is uploaded successfully.");
    //        }
  }
Esempio n. 20
0
  /**
   * Description: 向FTP服务器上传文件
   *
   * @param url FTP服务器
   * @param port FTP服务器端口
   * @param username FTP登录账号
   * @param password FTP登录密码
   * @param path FTP服务器保存目录
   * @param filename 上传到FTP服务器上的文件名
   * @param input 输入流
   * @return 成功返回true,否则返回false
   */
  public static boolean uploadFile(
      String url,
      int port,
      String username,
      String password,
      String path,
      String filename,
      InputStream input) {
    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;
      }
      ftp.changeWorkingDirectory(path);
      ftp.storeFile(filename, input);

      input.close();
      ftp.logout();
      success = true;
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (ftp.isConnected()) {
        try {
          ftp.disconnect();
        } catch (IOException ioe) {
        }
      }
    }
    return success;
  }
Esempio n. 21
0
 public static Map<String, Object> putFile(DispatchContext dctx, Map<String, ?> context) {
   Locale locale = (Locale) context.get("locale");
   Debug.logInfo("[putFile] starting...", module);
   InputStream localFile = null;
   try {
     localFile = new FileInputStream((String) context.get("localFilename"));
   } catch (IOException ioe) {
     Debug.logError(ioe, "[putFile] Problem opening local file", module);
     return ServiceUtil.returnError(
         UtilProperties.getMessage(resource, "CommonFtpFileCannotBeOpen", locale));
   }
   List<String> errorList = new LinkedList<String>();
   FTPClient ftp = new FTPClient();
   try {
     Integer defaultTimeout = (Integer) context.get("defaultTimeout");
     if (UtilValidate.isNotEmpty(defaultTimeout)) {
       Debug.logInfo(
           "[putFile] set default timeout to: " + defaultTimeout.intValue() + " milliseconds",
           module);
       ftp.setDefaultTimeout(defaultTimeout.intValue());
     }
     Debug.logInfo("[putFile] connecting to: " + (String) context.get("hostname"), module);
     ftp.connect((String) context.get("hostname"));
     if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
       Debug.logInfo("[putFile] Server refused connection", module);
       errorList.add(UtilProperties.getMessage(resource, "CommonFtpConnectionRefused", locale));
     } else {
       String username = (String) context.get("username");
       String password = (String) context.get("password");
       Debug.logInfo(
           "[putFile] logging in: username="******", password="******"[putFile] login failed", module);
         errorList.add(
             UtilProperties.getMessage(
                 resource,
                 "CommonFtpLoginFailure",
                 UtilMisc.toMap("username", username, "password", password),
                 locale));
       } else {
         Boolean binaryTransfer = (Boolean) context.get("binaryTransfer");
         boolean binary = (binaryTransfer == null) ? false : binaryTransfer.booleanValue();
         if (binary) {
           ftp.setFileType(FTP.BINARY_FILE_TYPE);
         }
         Boolean passiveMode = (Boolean) context.get("passiveMode");
         boolean passive = (passiveMode == null) ? true : passiveMode.booleanValue();
         if (passive) {
           ftp.enterLocalPassiveMode();
         }
         Debug.logInfo(
             "[putFile] storing local file remotely as: " + context.get("remoteFilename"), module);
         if (!ftp.storeFile((String) context.get("remoteFilename"), localFile)) {
           Debug.logInfo("[putFile] store was unsuccessful", module);
           errorList.add(
               UtilProperties.getMessage(
                   resource,
                   "CommonFtpFileNotSentSuccesfully",
                   UtilMisc.toMap("replyString", ftp.getReplyString()),
                   locale));
         } else {
           Debug.logInfo("[putFile] store was successful", module);
           List<String> siteCommands = checkList(context.get("siteCommands"), String.class);
           if (siteCommands != null) {
             for (String command : siteCommands) {
               Debug.logInfo("[putFile] sending SITE command: " + command, module);
               if (!ftp.sendSiteCommand(command)) {
                 errorList.add(
                     UtilProperties.getMessage(
                         resource,
                         "CommonFtpSiteCommandFailed",
                         UtilMisc.toMap("command", command, "replyString", ftp.getReplyString()),
                         locale));
               }
             }
           }
         }
       }
       ftp.logout();
     }
   } catch (IOException ioe) {
     Debug.logWarning(ioe, "[putFile] caught exception: " + ioe.getMessage(), module);
     errorList.add(
         UtilProperties.getMessage(
             resource,
             "CommonFtpProblemWithTransfer",
             UtilMisc.toMap("errorString", ioe.getMessage()),
             locale));
   } finally {
     try {
       if (ftp.isConnected()) {
         ftp.disconnect();
       }
     } catch (Exception e) {
       Debug.logWarning(e, "[putFile] Problem with FTP disconnect: ", module);
     }
     try {
       localFile.close();
     } catch (Exception e) {
       Debug.logWarning(e, "[putFile] Problem closing local file: ", module);
     }
   }
   if (errorList.size() > 0) {
     Debug.logError(
         "[putFile] The following error(s) (" + errorList.size() + ") occurred: " + errorList,
         module);
     return ServiceUtil.returnError(errorList);
   }
   Debug.logInfo("[putFile] finished successfully", module);
   return ServiceUtil.returnSuccess();
 }
Esempio n. 22
0
  private boolean backupDir(
      FTPClient ftpClient, String localPath, boolean recursive, PrintWriter output)
      throws IOException {
    boolean error = false;

    File localDirFile = new File(localPath);

    if (localDirFile.isDirectory() && (localDirFile.canRead())) {
      File localFileList[] = localDirFile.listFiles();

      if (localFileList != null) {
        for (int i = 0; i < localFileList.length; i++) {
          File localFile = localFileList[i];

          if (localFile.isDirectory()) {
            if (recursive) {
              String subDir = localFile.getName();

              String localPathChild = null;

              if (localPath.endsWith(File.separator)) {
                localPathChild = localPath + subDir;
              } else {
                localPathChild = localPath + File.separator + subDir;
              }

              boolean remoteChdirOk = true;

              if (!ftpClient.changeWorkingDirectory(subDir)) {
                if (!ftpClient.makeDirectory(subDir)) {
                  Logger.getLogger(getClass()).warn("FTP cannot create remote directory " + subDir);
                  remoteChdirOk = false;
                } else {
                  Logger.getLogger(getClass()).debug("FTP created new remote directory " + subDir);

                  if (!ftpClient.changeWorkingDirectory(subDir)) {
                    Logger.getLogger(getClass())
                        .warn("FTP cannot chdir to remote directory " + subDir);
                    remoteChdirOk = false;
                  }
                }
              }

              if (remoteChdirOk) {
                if (!backupDir(ftpClient, localPathChild, recursive, output)) {
                  error = true;
                }

                if (!ftpClient.changeWorkingDirectory("..")) {
                  Logger.getLogger(getClass()).warn("FTP cannot chdir .. from " + subDir);
                  return (false);
                }
              } else {
                error = true;
              }
            }
          } else {
            output.println("<script language=\"javascript\">");
            output.println(
                "document.getElementById('currentFile').innerHTML='"
                    + insertDoubleBackslash(
                        CommonUtils.shortName(
                            localPath.replace('\\', '/') + "/" + localFile.getName(), 64))
                    + "';");
            output.println("</script>");
            try {
              FileInputStream fin = new FileInputStream(localFile);

              if (!ftpClient.storeFile(localFile.getName(), fin)) {
                Logger.getLogger(getClass())
                    .warn("FTP put file " + localPath + "/" + localFile.getName() + " failed");

                error = true;
              } else {
                Logger.getLogger(getClass())
                    .debug(
                        "FTP put of file " + localPath + "/" + localFile.getName() + " successful");

                filesTransferred++;

                bytesTransferred += localFile.length();

                String temp =
                    filesTransferred
                        + " files ("
                        + numFormat.format(bytesTransferred / 1024)
                        + " KB)";

                output.println("<script language=\"javascript\">");
                output.println("document.getElementById('xferStatus').innerHTML='" + temp + "';");
                output.println("</script>");
              }

              output.flush();

              fin.close();
            } catch (IOException ioex) {
              Logger.getLogger(getClass())
                  .warn(
                      "FTP put file " + localPath + "/" + localFile.getName() + " failed: " + ioex);

              output.println(
                  "<br>FTP put file " + localPath + "/" + localFile.getName() + " failed: " + ioex);

              error = true;
            }
          }
        }
      }
    } else {
      Logger.getLogger(getClass()).warn("FTP local directory " + localPath + " is not readable");

      return (false);
    }

    return (!error);
  }
  /**
   * The method that handles file uploading, this method takes the absolute file path of a local
   * file to be uploaded to the remote FTP server, and the remote file will then be transfered to
   * the FTP server and saved as the relative path name specified in method setRemoteFile
   *
   * @param localfilename – the local absolute file name of the file in local hard drive that needs
   *     to FTP over
   */
  public synchronized boolean uploadFile(String localfilename, String remoteFile) {

    final BufferedInputStream bis;
    try {
      // URL url = new URL(this.getRemoteFileUrl(remoteFile));
      // URLConnection urlFtpConnection = url.openConnection();

      InputStream is = new FileInputStream(localfilename);
      bis = new BufferedInputStream(is);

      connect2Server();

      if (oFtp.isConnected()) {
        String fileExtension = localfilename.substring(localfilename.lastIndexOf(".") + 1);

        String[] fileExtensions = {"png", "gif", "bmp", "jpg", "jpeg", "tiff"};

        // If exporting to .csv or .tsv, add the gid parameter to specify which sheet to export
        if (Arrays.asList(fileExtensions).contains(fileExtension)) {
          oFtp.setFileType(FTP.BINARY_FILE_TYPE);
        }

        // OutputStream os = oFtp.storeFileStream(remoteFile);
        // if (os == null)
        // {
        // logError(oFtp.getReplyString());
        // }
        // BufferedOutputStream bos = new BufferedOutputStream(os);
        // byte[] buffer = new byte[1024];
        // int readCount;
        //
        // while ((readCount = bis.read(buffer)) > 0)
        // {
        // bos.write(buffer);
        // // bos.flush();
        // }
        // bos.close();

        if (!oFtp.storeFile(remoteFile, bis)) {
          logError(
              "Can't upload file "
                  + localfilename
                  + " FTP reply code: "
                  + oFtp.getReplyCode()
                  + " Ftp message: "
                  + oFtp.getReplyString());

          bis.close();
          is.close();

          this.closeFtpConnection();
          return false;
        } else {
          logMessage("File `" + localfilename + "` is uploaded!");
        }
      }

      /*
       * urlFtpConnection.getOutputStream();
       * //
       * log.message("File `" + localfilename + "` is uploaded!");
       */

      bis.close();
      is.close();
      // this.closeFtpConnection();
      return true;
    } catch (Exception ex) {
      StringWriter sw0 = new StringWriter();
      PrintWriter p0 = new PrintWriter(sw0, true);
      ex.printStackTrace(p0);
      log.error(sw0.getBuffer().toString());
      log.exception(ex);

      return false;
    }
  }
Esempio n. 24
0
    @Override
    protected Boolean doInBackground(String... arg0) {
      BiereDB biere = new BiereDB();

      String nomBiere = eTnom.getText().toString();
      biere.setNomBiere(nomBiere);

      String paysBiere = eTpays.getText().toString();
      biere.setPaysBiere(paysBiere);

      String degre = eTdegre.getText().toString();

      try {
        if (nomBiere.matches("") || paysBiere.matches("") || degre.matches("")) {
          throw new Exception(
              "Exception personnalisée/"
                  + R.string.e218
                  + "/"
                  + "Tous les champs doivent être remplis !");
        } else {
          float degreBiere = Float.parseFloat(degre);
          biere.setDegreBiere(degreBiere);
        }
      } catch (Exception e) {
        ex = e;
        exc = true;
      }

      if (bitmap != null && exc != null) {
        FTPClient mFtp = new FTPClient();
        try {
          mFtp.connect("ftp.alokar.site90.net", 21); // Using port no=21
          mFtp.login("a7115779", "projet2013");
          mFtp.enterLocalPassiveMode();
          mFtp.setFileType(FTPClient.BINARY_FILE_TYPE);
          ByteArrayOutputStream stream = new ByteArrayOutputStream();
          bitmap.compress(CompressFormat.JPEG, 100, stream);
          InputStream is = new ByteArrayInputStream(stream.toByteArray());
          String cheminBiere = biere.getNomBiere().replace(' ', '_');
          mFtp.storeFile("/public_html/BeerPictures/image_" + cheminBiere + ".jpg", is);
          biere.setCheminImage("/public_html/BeerPictures/image_" + cheminBiere + ".jpg");
          is.close();
          mFtp.disconnect();
        } catch (Exception e) {
          ex = e;
          FTPpbm = true;
        }
      }

      if (!exc) {
        try {
          biere.create();
          HistoriqueDB histo =
              new HistoriqueDB(0, user.getIdPersonne(), biere.getIdBiere(), "ajout");
          histo.create();

        } catch (Exception e) {
          ex = e;
          exc = true;
        }
      }
      return true;
    }
Esempio n. 25
0
  @Override
  public void sendInventoryToTiteLiveServer() {
    if (remoteFileName == null) {
      remoteFileName = "." + titeliveId + "_ART.asc";
    }

    if (decimalFormat == null) {
      decimalFormat = new DecimalFormat("0.00");
      decimalFormat.setDecimalSeparatorAlwaysShown(false);
    }

    FTPClient ftpClient = new FTPClient();
    try (PipedInputStream inPipe = new PipedInputStream(PIPE_BUFFER)) {
      ftpClient.connect(ftpUrl);

      ftpClient.login(ftpUsername, ftpPassword);

      new Thread(
              () -> {
                try (PipedOutputStream outPipe = new PipedOutputStream(inPipe)) {
                  IOUtils.write(
                      "EXTRACTION STOCK DU "
                          + new SimpleDateFormat("dd/MM/YYYY").format(new Date())
                          + "\r\n",
                      outPipe);
                  for (Integer productId : productInventoryService.findProductIdWithInventory()) {
                    Product product = productService.findOne(productId);

                    if (product.getEan13().length() == 13) {
                      IOUtils.write(
                          titeliveId
                              + product.getEan13()
                              + String.format(
                                  "%04d",
                                  new Double(product.getProductInventory().getQuantityOnHand())
                                      .intValue())
                              + StringUtils.leftPad(
                                  decimalFormat
                                      .format(product.getPriceTaxIn())
                                      .replace(
                                          String.valueOf(
                                              decimalFormat
                                                  .getDecimalFormatSymbols()
                                                  .getDecimalSeparator()),
                                          ""),
                                  10,
                                  "0")
                              + "\r\n",
                          outPipe);
                    }
                  }
                } catch (IOException ioEx) {
                  LOGGER.error("Error while writing content to FTP Server", ioEx);
                }
              })
          .start();

      ftpClient.storeFile(remoteFileName, inPipe);

      ftpClient.rename(remoteFileName, titeliveId + "_ART.asc");

      LOGGER.info("Succesfully transfered inventory to Tite");
    } catch (IOException ioEx) {
      throw new RuntimeException(ioEx);
    } finally {
      try {
        ftpClient.disconnect();
      } catch (IOException ioEx) {
        LOGGER.error("Error while closing FTP connection.", ioEx);
      }
    }
  }
 public boolean writeFile(FTPClient client) throws ApplicationException, IOException {
   return client.storeFile(this.destinationFileName, this.inputStream);
 }