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 String getAbsolutePath() {
   // 如果是根结点
   if (getURL() != null) {
     return getURL().getPath();
   }
   String parentAbsolutePath = getParent().getAbsolutePath();
   if (parentAbsolutePath.endsWith("/")) {
     return parentAbsolutePath + ftpFile.getName();
   } else {
     return parentAbsolutePath + "/" + ftpFile.getName();
   }
 }
  private void traverseDirectory(String directory) throws IOException {
    log.info("---------- Traversing directory '" + directory + "'.");

    ftpc.changeWorkingDirectory(directory);
    printFTPCommandInfo("change directory (" + directory + ")");

    FTPFile[] files = ftpc.listFiles();
    printFTPCommandInfo("list files (" + directory + ")");

    if (!directory.endsWith("/")) {
      directory += "/";
    }

    String fileList = "";
    for (FTPFile file : files) {
      if (!fileList.equals("")) {
        fileList += ",";
      }
      fileList += file.getName();
    }
    log.info("**********     Files: [" + fileList + "].");

    for (FTPFile file : files) {
      String path = directory + file.getName();

      Boolean complete = false;
      if (processedDirectories.containsKey(path)) {
        FTPManifestEntry existingEntry = processedDirectories.get(path);
        complete = existingEntry.getCompleted();
      }

      if (!complete) {
        FTPManifestEntryType type = FTPManifestEntryType.FILE;
        if (file.getType() == FTPFile.DIRECTORY_TYPE) {
          type = FTPManifestEntryType.DIRECTORY;
        }

        FTPManifestEntry entry = new FTPManifestEntry(path, file.getName(), type, false);

        processedDirectories.put(directory + file.getName(), entry);

        if (type.equals(FTPManifestEntryType.DIRECTORY)) {
          traverseDirectory(path);
        }

        log.info("Completed entry '" + path + "'.");
        entry.setCompleted(true);
      }
    }
  }
Exemple #4
0
  public static lucee.runtime.type.Query toQuery(
      FTPFile[] files, String prefix, String directory, String hostName) throws PageException {

    String[] cols =
        new String[] {
          "name",
          "isdirectory",
          "lastmodified",
          "length",
          "mode",
          "path",
          "url",
          "type",
          "raw",
          "attributes"
        };
    String[] types =
        new String[] {
          "VARCHAR", "BOOLEAN", "DATE", "DOUBLE", "VARCHAR", "VARCHAR", "VARCHAR", "VARCHAR",
          "VARCHAR", "VARCHAR"
        };

    lucee.runtime.type.Query query = new QueryImpl(cols, types, 0, "query");

    // translate directory path for display
    if (directory.length() == 0) directory = "/";
    else if (directory.startsWith("./")) directory = directory.substring(1);
    else if (directory.charAt(0) != '/') directory = '/' + directory;
    if (directory.charAt(directory.length() - 1) != '/') directory = directory + '/';

    int row;
    for (int i = 0; i < files.length; i++) {
      FTPFile file = files[i];
      if (file.getName().equals(".") || file.getName().equals("..")) continue;
      row = query.addRow();
      query.setAt("attributes", row, "");
      query.setAt("isdirectory", row, Caster.toBoolean(file.isDirectory()));
      query.setAt("lastmodified", row, new DateTimeImpl(file.getTimestamp()));
      query.setAt("length", row, Caster.toDouble(file.getSize()));
      query.setAt("mode", row, FTPConstant.getPermissionASInteger(file));
      query.setAt("type", row, FTPConstant.getTypeAsString(file.getType()));
      // query.setAt("permission",row,FTPConstant.getPermissionASInteger(file));
      query.setAt("raw", row, file.getRawListing());
      query.setAt("name", row, file.getName());
      query.setAt("path", row, directory + file.getName());
      query.setAt("url", row, prefix + "://" + hostName + "" + directory + file.getName());
    }
    return query;
  }
  protected void getDir(String dirPath) {
    // TODO Auto-generated method stub
    list = FTPConnector.list();
    item = new ArrayList<String>();

    if (!dirPath.equals(root)) {
      item.add(root);
      item.add("../");
    }

    for (int i = 0; i < list.length; i++) {
      FTPFile file = list[i];
      if (file.isDirectory()) item.add(file.getName() + "/");
      else item.add(file.getName());
    }
  }
  /**
   * @param ftpClient
   * @param allowFileTypes
   * @return
   */
  public static void listFiles(
      FTPClient ftpClient,
      List<String> filePath,
      Set<String> allowFileTypes,
      String changeToPath,
      Boolean isFirst) {
    try {
      if (!isFirst) {
        Boolean flag = ftpClient.changeWorkingDirectory(changeToPath);
        if (!flag) {
          return;
        }
      }

      FTPFile[] files = ftpClient.listFiles();
      if (null != files && files.length > 0) {
        for (FTPFile file : files) {
          String name = file.getName();
          if (file.isDirectory()) {
            listFiles(
                ftpClient, filePath, allowFileTypes, changeToPath + "/" + name, Boolean.FALSE);
          } else if (file.isFile()) {
            String extAttr = getExt(name);
            if (allowFileTypes.contains(extAttr)) {
              filePath.add(getAfterUploadUrl(changeToPath + "/", name));
            }
          }
        }
      }

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Exemple #7
0
 /**
  * Convenience method, so that we don't open a new connection when using this method from within
  * another method. Otherwise every API invocation incurs the overhead of opening/closing a TCP
  * connection.
  */
 private FileStatus getFileStatus(FTPClient client, Path file) throws IOException {
   FileStatus fileStat = null;
   Path workDir = new Path(client.printWorkingDirectory());
   Path absolute = makeAbsolute(workDir, file);
   Path parentPath = absolute.getParent();
   if (parentPath == null) { // root dir
     long length = -1; // Length of root dir on server not known
     boolean isDir = true;
     int blockReplication = 1;
     long blockSize = DEFAULT_BLOCK_SIZE; // Block Size not known.
     long modTime = -1; // Modification time of root dir not known.
     Path root = new Path("/");
     return new FileStatus(
         length, isDir, blockReplication, blockSize, modTime, root.makeQualified(this));
   }
   String pathName = parentPath.toUri().getPath();
   FTPFile[] ftpFiles = client.listFiles(pathName);
   if (ftpFiles != null) {
     for (FTPFile ftpFile : ftpFiles) {
       if (ftpFile.getName().equals(file.getName())) { // file found in dir
         fileStat = getFileStatus(ftpFile, parentPath);
         break;
       }
     }
     if (fileStat == null) {
       throw new FileNotFoundException("File " + file + " does not exist.");
     }
   } else {
     throw new FileNotFoundException("File " + file + " does not exist.");
   }
   return fileStat;
 }
 @Override
 public boolean accept(FTPFile file) {
   String name = file.getName();
   Pattern p = Pattern.compile("^" + reg + "$");
   Matcher m = p.matcher(name);
   return m.find();
 }
Exemple #9
0
 /**
  * Convert the file information in FTPFile to a {@link FileStatus} object. *
  *
  * @param ftpFile
  * @param parentPath
  * @return FileStatus
  */
 private FileStatus getFileStatus(FTPFile ftpFile, Path parentPath) {
   long length = ftpFile.getSize();
   boolean isDir = ftpFile.isDirectory();
   int blockReplication = 1;
   // Using default block size since there is no way in FTP client to know of
   // block sizes on server. The assumption could be less than ideal.
   long blockSize = DEFAULT_BLOCK_SIZE;
   long modTime = ftpFile.getTimestamp().getTimeInMillis();
   long accessTime = 0;
   FsPermission permission = getPermissions(ftpFile);
   String user = ftpFile.getUser();
   String group = ftpFile.getGroup();
   Path filePath = new Path(parentPath, ftpFile.getName());
   return new FileStatus(
       length,
       isDir,
       blockReplication,
       blockSize,
       modTime,
       accessTime,
       permission,
       user,
       group,
       filePath.makeQualified(this));
 }
Exemple #10
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);
    }
  }
Exemple #11
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;
  }
 /** @see org.apache.commons.net.ftp.parser.FTPParseTestFramework#testParseFieldsOnDirectory() */
 @Override
 public void testParseFieldsOnDirectory() throws Exception {
   FTPFile dir = getParser().parseFTPEntry("     0           DIR   11-28-97   09:42  PC");
   assertNotNull("Could not parse entry.", dir);
   assertTrue("Should have been a directory.", dir.isDirectory());
   assertEquals(0, dir.getSize());
   assertEquals("PC", dir.getName());
   assertEquals("Fri Nov 28 09:42:00 1997", df.format(dir.getTimestamp().getTime()));
 }
Exemple #13
0
  private static void removeRecursive(AFTPClient client, String path, int type) throws IOException {
    // directory
    if (FTPFile.DIRECTORY_TYPE == type) {
      if (!path.endsWith("/")) path += "/";
      // first we remove the children
      FTPFile[] children = client.listFiles(path);
      for (FTPFile child : children) {
        if (child.getName().equals(".") || child.getName().equals("..")) continue;
        removeRecursive(client, path + child.getName(), child.getType());
      }
      // then the directory itself
      client.removeDirectory(path);

    }
    // file
    else if (FTPFile.FILE_TYPE == type) {
      client.deleteFile(path);
    }
  }
 /** @see org.apache.commons.net.ftp.parser.FTPParseTestFramework#testParseFieldsOnFile() */
 @Override
 public void testParseFieldsOnFile() throws Exception {
   FTPFile file =
       getParser().parseFTPEntry("5000000000      A          11-17-98   16:07  POPUPLOG.OS2");
   assertNotNull("Could not parse entry.", file);
   assertTrue("Should have been a file.", file.isFile());
   assertEquals(5000000000L, file.getSize());
   assertEquals("POPUPLOG.OS2", file.getName());
   assertEquals("Tue Nov 17 16:07:00 1998", df.format(file.getTimestamp().getTime()));
 }
Exemple #15
0
  public FTPProgressPanel(FTPFile file, String sourcePath, DefaultMutableTreeNode parent) {

    this.file = file;
    this.sourcePath = sourcePath;
    if (file != null) {
      label = new JLabel(file.getName() + " " + file.getSize());
    }

    add(label);
  }
  /**
   * @param mask
   * @param remoteFolder
   * @throws SocketException
   * @throws IOException
   */
  public void removeFilesByMask(String mask, String remoteFolder)
      throws SocketException, IOException {
    connect2Server();

    if (oFtp.isConnected()) {
      FTPFile[] fileslist = oFtp.listFiles(remoteFolder);

      Pattern pat = Pattern.compile("^" + mask);

      for (FTPFile file : fileslist) {
        java.util.regex.Matcher m = pat.matcher(file.getName());
        boolean is_pat_file = m.find();

        if (is_pat_file) {
          oFtp.deleteFile(remoteFolder + file.getName());
        }
      }
    }
    this.closeFtpConnection();
  }
  /**
   * download file from remote host and display the downloaded percentage
   *
   * @param folder remote directory
   * @param fileName the file you want to download
   * @param destfolder the destination folder you will store the file
   */
  public void downloadFileInProgress(String folder, String fileName, String destfolder) {
    try {
      ftp.enterLocalPassiveMode();
      ftp.changeWorkingDirectory(folder);
      LogUtils.log("Changing to directory:[" + folder + "]");
      String realFile = destfolder + File.separator + fileName;
      File localFile = new File(realFile);
      FileOutputStream fos = new FileOutputStream(localFile);
      LogUtils.log("Start downloading..");
      FTPFile[] fs = ftp.listFiles();
      DecimalFormat df = new DecimalFormat("#.00%");
      for (FTPFile f : fs) {
        if (f.getName().equals(fileName)) {
          InputStream is = ftp.retrieveFileStream(f.getName());
          BufferedReader br = new BufferedReader(new InputStreamReader(is));
          String line = br.readLine();
          long transfered = 0, total = f.getSize();
          double ratio = 0.0;
          while (line != null) {
            byte[] buff = line.getBytes();
            transfered += buff.length;
            if (transfered * 1.0 / total - ratio >= 0.01) {
              ratio = transfered * 1.0 / total;
              LogUtils.log("Download size : " + df.format(ratio));
            }
            fos.write(buff);
            line = br.readLine();
          }
          is.close();
          ftp.logout();
          ftp.disconnect();

          LogUtils.log("Download done!");
        }
      }
      fos.close();

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 public static FTPStorageDirectory createFromFTPFile(FTPFile file, String path)
     throws FTPStorageNotADirectory {
   if (file.getType() != FTPStorageSystem.FTP_STORAGE_DIRECTORY) {
     throw new FTPStorageNotADirectory();
   }
   FTPStorageDirectory fsd =
       new FTPStorageDirectory(file.getName(), StorageDirectory.buildFromPath(path, "/"));
   fsd.setGroup(file.getGroup());
   fsd.setUser(file.getUser());
   fsd.setCreateDate(file.getTimestamp().getTime());
   return fsd;
 }
Exemple #19
0
  @Override
  protected boolean isMatched(GenericFile<FTPFile> file, String doneFileName, List<FTPFile> files) {
    String onlyName = FileUtil.stripPath(doneFileName);

    for (FTPFile f : files) {
      if (f.getName().equals(onlyName)) {
        return true;
      }
    }

    log.trace("Done file: {} does not exist", doneFileName);
    return false;
  }
Exemple #20
0
  private RemoteFile<FTPFile> asRemoteFile(String absolutePath, FTPFile file, String charset) {
    RemoteFile<FTPFile> answer = new RemoteFile<FTPFile>();

    answer.setCharset(charset);
    answer.setEndpointPath(endpointPath);
    answer.setFile(file);
    answer.setFileNameOnly(file.getName());
    answer.setFileLength(file.getSize());
    answer.setDirectory(file.isDirectory());
    if (file.getTimestamp() != null) {
      answer.setLastModified(file.getTimestamp().getTimeInMillis());
    }
    answer.setHostname(((RemoteFileConfiguration) endpoint.getConfiguration()).getHost());

    // absolute or relative path
    boolean absolute = FileUtil.hasLeadingSeparator(absolutePath);
    answer.setAbsolute(absolute);

    // create a pseudo absolute name
    String dir = FileUtil.stripTrailingSeparator(absolutePath);
    String absoluteFileName = FileUtil.stripLeadingSeparator(dir + "/" + file.getName());
    // if absolute start with a leading separator otherwise let it be relative
    if (absolute) {
      absoluteFileName = "/" + absoluteFileName;
    }
    answer.setAbsoluteFilePath(absoluteFileName);

    // the relative filename, skip the leading endpoint configured path
    String relativePath = ObjectHelper.after(absoluteFileName, endpointPath);
    // skip leading /
    relativePath = FileUtil.stripLeadingSeparator(relativePath);
    answer.setRelativeFilePath(relativePath);

    // the file name should be the relative path
    answer.setFileName(answer.getRelativeFilePath());

    return answer;
  }
 @Override
 public EnumSet<AccessMode> getAccess(final String name) throws IOException {
   try {
     ftpClient.setFileType(FTP.ASCII_FILE_TYPE);
     final FTPFile[] files = ftpClient.listFiles(name);
     if (files.length == 0) throw new NoSuchFileException(name);
     if (files.length == 1) return calculateAccess(files[0]);
     for (final FTPFile file : files) if (".".equals(file.getName())) return calculateAccess(file);
     throw new IllegalStateException();
   } catch (FTPConnectionClosedException e) {
     status = Status.DEAD;
     throw new IOException("service unavailable", e);
   }
 }
  /**
   * @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;
  }
  /**
   * download file from remote host without progress percentage display
   *
   * @param folder remote directory
   * @param fileName the file you want to download
   * @param destfolder the destination folder you will store the file
   */
  public void downloadFile(String folder, String fileName, String destfolder) {
    try {
      ftp.enterLocalPassiveMode();
      ftp.changeWorkingDirectory(folder);
      LogUtils.log("Changing to directory:[" + folder + "]");
      String realFile = destfolder + File.separator + fileName;
      File localFile = new File(realFile);
      FileOutputStream fos = new FileOutputStream(localFile);
      FileInputStream fis = new FileInputStream(localFile);
      LogUtils.log("Start downloading..");
      FTPFile[] fs = ftp.listFiles();
      for (FTPFile f : fs) {
        if (f.getName().equals(fileName)) {
          ftp.retrieveFile(f.getName(), fos);
          LogUtils.log("Download done!");
          break;
        }
      }
      fos.close();

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  /**
   * @param remoteFile
   * @param path
   * @return
   * @throws SocketException
   * @throws IOException
   */
  public boolean isExists(String remoteFile, String path) throws SocketException, IOException {
    this.connect2Server();

    if (this.oFtp.isConnected()) {

      FTPFile[] files = oFtp.listFiles(path);

      for (FTPFile file : files) {
        if (file.getName().equalsIgnoreCase(remoteFile)) {
          return true;
        }
      }
    }
    this.closeFtpConnection();
    return false;
  }
Exemple #25
0
 public String getPath() {
   // 如果没有计算过
   if (path == null) {
     // 如果有父亲
     if (getParent() != null) {
       super.setPath(getParent().getPath() + "/" + getFileName());
     } else {
       if (ftpFile.isDirectory()) {
         return "";
       } else {
         return "/" + ftpFile.getName();
       }
     }
   }
   return getPath();
 }
 @Override
 public List<String> getDirectoryNames(final String dir) throws IOException {
   try {
     ftpClient.setFileType(FTP.ASCII_FILE_TYPE);
     final FTPFile[] files = ftpClient.listFiles(dir);
     if (files.length == 0) throw new NoSuchFileException(dir);
     if (files.length == 1) handleFailedDirectoryList(dir, files[0]);
     final List<String> ret = new ArrayList<>(files.length);
     String name;
     for (final FTPFile file : files) {
       name = file.getName();
       if (!(".".equals(name) || "..".equals(name))) ret.add(name);
     }
     return ret;
   } catch (FTPConnectionClosedException e) {
     status = Status.DEAD;
     throw new IOException("service unavailable", e);
   }
 }
  private void checkAlbumContent(List<ValidationError> errors, String album)
      throws FtpManagerException {
    List<FTPFile> pictures = ftpManager.listFilesFromAlbum(album);

    Set<String> smallNames = new TreeSet<>();
    Set<String> normalNames = new TreeSet<>();
    for (FTPFile ftpFile : pictures) {
      String ftpFileName = FilenameUtils.getBaseName(ftpFile.getName());
      if (ftpFileName.contains(AlbumNamesHelper.PREFIX_SMALL_IMAGE)) {
        smallNames.add(
            StringUtils.remove(ftpFileName, AlbumNamesHelper.PREFIX_SMALL_IMAGE).toLowerCase());
      } else {
        normalNames.add(ftpFileName.toLowerCase());
      }
    }

    // Teste si tuous les normal names sont présents.
    if (smallNames.isEmpty() && normalNames.isEmpty()) {
      errors.add(
          new ValidationError(SeverityErrorEnum.WARNNING, "L'album " + album + " est vide."));
    } else {
      Set<String> differenceNormalNames = Sets.difference(smallNames, normalNames);
      for (String pictureName : differenceNormalNames) {
        errors.add(
            new ValidationError(
                SeverityErrorEnum.ERREUR,
                "La photo " + pictureName + " de l'album " + album + " n'a pas sa mignature."));
      }
      Set<String> differenceSmallNames = Sets.difference(normalNames, smallNames);
      for (String pictureName : differenceSmallNames) {
        errors.add(
            new ValidationError(
                SeverityErrorEnum.ERREUR,
                "La photo small"
                    + pictureName
                    + " de l'album "
                    + album
                    + " n'a pas sa photo taille réelle."));
      }
    }
  }
  /**
   * @param mask
   * @param path
   * @return
   * @throws SocketException
   * @throws IOException
   */
  public List<FTPFile> getFilesByMask(String mask, String path)
      throws SocketException, IOException {
    List<FTPFile> maskFiles = new ArrayList<FTPFile>();
    connect2Server();

    if (oFtp.isConnected()) {
      FTPFile[] fileslist = oFtp.listFiles(path);

      Pattern pat = Pattern.compile("^" + mask);

      for (FTPFile file : fileslist) {
        java.util.regex.Matcher m = pat.matcher(file.getName());
        boolean is_pat_file = m.find();

        if (is_pat_file) {
          maskFiles.add(file);
        }
      }
    }
    this.closeFtpConnection();
    return maskFiles;
  }
  @Override
  public void onListItemClick(ListView l, View v, int position, long id) {
    // TODO Auto-generated method stub
    // super.onListItemClick(l, v, position, id);
    FTPFile file = list[position];
    final File file1 = new File("/" + file.getName());

    if (list[position].isFile()) {
      AlertDialog.Builder alert_confirm = new AlertDialog.Builder(getActivity());
      alert_confirm
          .setTitle("[" + list[position].getName() + "]")
          .setMessage("다운로드")
          .setCancelable(false)
          .setPositiveButton(
              "확인",
              new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                  // 'YES'
                  threadList(file1);
                }
              })
          .setNegativeButton(
              "취소",
              new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                  // 'No'
                  return;
                }
              });
      AlertDialog alert = alert_confirm.create();
      alert.show();
    } else {

    }
  }
Exemple #30
0
  protected boolean doPollDirectory(
      String absolutePath, String dirName, List<GenericFile<FTPFile>> fileList, int depth) {
    log.trace("doPollDirectory from absolutePath: {}, dirName: {}", absolutePath, dirName);

    depth++;

    // remove trailing /
    dirName = FileUtil.stripTrailingSeparator(dirName);

    // compute dir depending on stepwise is enabled or not
    String dir;
    if (isStepwise()) {
      dir = ObjectHelper.isNotEmpty(dirName) ? dirName : absolutePath;
      operations.changeCurrentDirectory(dir);
    } else {
      dir = absolutePath;
    }

    log.trace("Polling directory: {}", dir);
    List<FTPFile> files = null;
    if (isUseList()) {
      if (isStepwise()) {
        files = operations.listFiles();
      } else {
        files = operations.listFiles(dir);
      }
    } else {
      // we cannot use the LIST command(s) so we can only poll a named file
      // so created a pseudo file with that name
      FTPFile file = new FTPFile();
      file.setType(FTPFile.FILE_TYPE);
      fileExpressionResult = evaluateFileExpression();
      if (fileExpressionResult != null) {
        file.setName(fileExpressionResult);
        files = new ArrayList<FTPFile>(1);
        files.add(file);
      }
    }

    if (files == null || files.isEmpty()) {
      // no files in this directory to poll
      log.trace("No files found in directory: {}", dir);
      return true;
    } else {
      // we found some files
      log.trace("Found {} in directory: {}", files.size(), dir);
    }

    for (FTPFile file : files) {

      if (log.isTraceEnabled()) {
        log.trace(
            "FtpFile[name={}, dir={}, file={}]",
            new Object[] {file.getName(), file.isDirectory(), file.isFile()});
      }

      // check if we can continue polling in files
      if (!canPollMoreFiles(fileList)) {
        return false;
      }

      if (file.isDirectory()) {
        RemoteFile<FTPFile> remote = asRemoteFile(absolutePath, file, getEndpoint().getCharset());
        if (endpoint.isRecursive()
            && depth < endpoint.getMaxDepth()
            && isValidFile(remote, true, files)) {
          // recursive scan and add the sub files and folders
          String subDirectory = file.getName();
          String path = absolutePath + "/" + subDirectory;
          boolean canPollMore = pollSubDirectory(path, subDirectory, fileList, depth);
          if (!canPollMore) {
            return false;
          }
        }
      } else if (file.isFile()) {
        RemoteFile<FTPFile> remote = asRemoteFile(absolutePath, file, getEndpoint().getCharset());
        if (depth >= endpoint.getMinDepth() && isValidFile(remote, false, files)) {
          // matched file so add
          fileList.add(remote);
        }
      } else {
        log.debug("Ignoring unsupported remote file type: " + file);
      }
    }

    return true;
  }