示例#1
0
  public Boolean fileExists(ServerDetailsDTO conDetails, String filePath) {

    FileObject fileObject = null;
    StandardFileSystemManager manager = null;
    try {

      manager = new StandardFileSystemManager();
      manager.init();
      UserAuthenticator auth =
          new StaticUserAuthenticator(null, conDetails.getUserName(), conDetails.getPassword());
      FileSystemOptions opts = new FileSystemOptions();

      DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
      SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");

      String fileUri = buildUri(conDetails, filePath);
      fileObject = manager.resolveFile(fileUri, opts);
      return fileObject.exists() && fileObject.isReadable();
    } catch (FileSystemException e) {
      log.error("cannot access the server", e);
    } finally {
      try {
        if (fileObject != null) {
          ((SftpFileSystem) fileObject.getFileSystem()).closeCommunicationLink();
          FileSystem fs = null;
          fs = fileObject.getFileSystem();
          manager.closeFileSystem(fs);
        }
      } finally {
      }
    }

    return null;
  }
示例#2
0
  public boolean deleteFile(ServerDetailsDTO conDetails, String filePath) throws IOException {

    FileObject fileObject = null;
    StandardFileSystemManager manager = null;
    try {
      manager = new StandardFileSystemManager();
      manager.init();

      UserAuthenticator auth =
          new StaticUserAuthenticator(null, conDetails.getUserName(), conDetails.getPassword());
      FileSystemOptions opts = new FileSystemOptions();

      DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
      SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");

      String fileUri = buildUri(conDetails, filePath);
      fileObject = manager.resolveFile(fileUri, opts);
      return fileObject.delete();
    } finally {
      try {

        if (fileObject != null) {
          ((SftpFileSystem) fileObject.getFileSystem()).closeCommunicationLink();
          FileSystem fs = null;
          fs = fileObject.getFileSystem();
          manager.closeFileSystem(fs);
        }
      } finally {
      }
    }
  }
示例#3
0
  public boolean zipFiles(
      ServerDetailsDTO conDetails, String outputFileName, List<String> fileNames, String filePath) {
    UserAuthenticator auth =
        new StaticUserAuthenticator(null, conDetails.getUserName(), conDetails.getPassword());
    FileSystemOptions opts = new FileSystemOptions();
    FileObject fileObject = null;
    StandardFileSystemManager manager = null;
    manager = new StandardFileSystemManager();
    try {
      manager.init();
    } catch (FileSystemException e1) {
      e1.printStackTrace();
      return false;
    }
    try {
      DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
      SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
    } catch (FileSystemException e) {
      e.printStackTrace();
      return false;
    }
    try {
      System.out.println("Output to Zip : " + outputFileName);
      String fileUri = buildUri(conDetails, filePath + outputFileName);
      fileObject = manager.resolveFile(fileUri, opts);
      OutputStream os = fileObject.getContent().getOutputStream();
      ZipOutputStream zos = new ZipOutputStream(os);
      for (String file : fileNames) {
        System.out.println("File Added : " + file);
        ZipEntry ze = new ZipEntry(file);
        zos.putNextEntry(ze);
        zos.write(readFile(conDetails, filePath + file));
      }
      zos.closeEntry();
      // remember close it
      zos.close();
      return true;
    } catch (IOException ex) {
      ex.printStackTrace();
      return false;
    } finally {
      try {

        FileSystem fs = null;

        if (fileObject != null) {
          fs = fileObject.getFileSystem();
          manager.closeFileSystem(fs);
        }
      } finally {
      }
    }
  }
示例#4
0
  public List<String> getDirContent(
      ServerDetailsDTO conDetails, String filePath, String... extentions) throws IOException {
    FileObject fileObject = null;
    StandardFileSystemManager manager = null;
    try {

      manager = new StandardFileSystemManager();
      manager.init();

      UserAuthenticator auth =
          new StaticUserAuthenticator(null, conDetails.getUserName(), conDetails.getPassword());
      FileSystemOptions opts = new FileSystemOptions();

      DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
      SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");

      String fileUri = buildUri(conDetails, filePath);

      fileObject = manager.resolveFile(fileUri, opts);
      if (!fileObject.exists()) {
        return null;
      }
      List<String> fileNames = new ArrayList<String>();
      FileObject[] children = fileObject.getChildren();
      if (children != null) {
        for (FileObject child : children) {
          String fileName = child.getName().getBaseName();
          if (extentions.length > 0) {
            for (String extention : extentions) {
              if (fileName.endsWith(extention)) {
                fileNames.add(fileName);
              }
            }
          } else {
            fileNames.add(fileName);
          }
        }
      }
      return fileNames;
    } finally {
      try {
        if (fileObject != null) {
          ((SftpFileSystem) fileObject.getFileSystem()).closeCommunicationLink();
          FileSystem fs = null;
          fs = fileObject.getFileSystem();
          manager.closeFileSystem(fs);
        }
      } finally {
      }
    }
  }
示例#5
0
 protected AbstractFileSystem(
     final FileName rootName,
     final FileObject parentLayer,
     final FileSystemOptions fileSystemOptions) {
   // this.parentLayer = parentLayer;
   this.parentLayer = parentLayer;
   this.rootName = rootName;
   this.fileSystemOptions = fileSystemOptions;
   FileSystemConfigBuilder builder = DefaultFileSystemConfigBuilder.getInstance();
   String uri = builder.getRootURI(fileSystemOptions);
   if (uri == null) {
     uri = rootName.getURI();
   }
   this.rootURI = uri;
 }
示例#6
0
  public byte[] readFile(ServerDetailsDTO conDetails, String filePath) throws IOException {

    FileObject fileObject = null;
    StandardFileSystemManager manager = null;
    try {

      manager = new StandardFileSystemManager();
      manager.init();

      UserAuthenticator auth =
          new StaticUserAuthenticator(null, conDetails.getUserName(), conDetails.getPassword());
      FileSystemOptions opts = new FileSystemOptions();

      DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
      SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");

      String fileUri = buildUri(conDetails, filePath);

      fileObject = manager.resolveFile(fileUri, opts);
      if (fileObject.isReadable()) {
        InputStream is = fileObject.getContent().getInputStream();
        int size = (int) fileObject.getContent().getSize();
        byte[] fileContent = new byte[size];
        for (int index = 0; size > 0; index += 4000, size -= 4000) {
          is.read(fileContent, index, size < 4000 ? size : 4000);
          if (Thread.currentThread().isInterrupted()) {
            return null;
          }
        }
        return fileContent;
      }
      return null;
    } finally {
      try {
        if (fileObject != null) {
          fileObject.getContent().close();
          ((SftpFileSystem) fileObject.getFileSystem()).closeCommunicationLink();
          FileSystem fs = null;
          fs = fileObject.getFileSystem();
          manager.closeFileSystem(fs);
        }
      } finally {
      }
    }
  }
示例#7
0
  public boolean moveFile(ServerDetailsDTO conDetails, String filePath1, String filePath2)
      throws IOException {
    FileObject fileObject2 = null;
    FileObject fileObject1 = null;
    StandardFileSystemManager manager = null;
    try {

      manager = new StandardFileSystemManager();
      manager.init();
      UserAuthenticator auth =
          new StaticUserAuthenticator(null, conDetails.getUserName(), conDetails.getPassword());
      FileSystemOptions opts = new FileSystemOptions();
      DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
      SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");

      String fileUri1 = buildUri(conDetails, filePath1);
      fileObject1 = manager.resolveFile(fileUri1, opts);
      String fileUri2 = buildUri(conDetails, filePath2);
      fileObject2 = manager.resolveFile(fileUri2, opts);
      fileObject1.moveTo(fileObject2);

      ((SftpFileSystem) fileObject2.getFileSystem()).closeCommunicationLink();
      ((SftpFileSystem) fileObject1.getFileSystem()).closeCommunicationLink();

    } catch (IOException e) {
      throw e;
    } finally {
      try {
        FileSystem fs = null;
        if (fileObject2 != null) {
          fs = fileObject2.getFileSystem();
          manager.closeFileSystem(fs);
        }

        fs = null;
        if (fileObject1 != null) {
          fs = fileObject1.getFileSystem();
          manager.closeFileSystem(fs);
        }
      } finally {
      }
    }

    return true;
  }
示例#8
0
  public boolean writeFile(ServerDetailsDTO conDetails, String filePath, byte[] fileContent)
      throws IOException {
    FileObject fileObject2 = null;
    FileObject fileObject = null;
    StandardFileSystemManager manager = null;
    try {

      manager = new StandardFileSystemManager();
      manager.init();
      UserAuthenticator auth =
          new StaticUserAuthenticator(null, conDetails.getUserName(), conDetails.getPassword());
      FileSystemOptions opts = new FileSystemOptions();
      DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
      SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");

      String fileUri = buildUri(conDetails, filePath);
      fileObject = manager.resolveFile(fileUri + ".tmp", opts);
      OutputStream os = fileObject.getContent().getOutputStream();
      int size = fileContent.length;
      try {
        for (int index = 0; index < fileContent.length; index += 4000, size -= 4000) {
          os.write(fileContent, index, size > 4000 ? 4000 : size);
          if (Thread.currentThread().isInterrupted()) {
            fileObject.getContent().close();
            fileObject.delete();
            return false;
          }
        }
        os.flush();
      } finally {
        fileObject.getContent().close();
      }

      fileObject2 = manager.resolveFile(fileUri, opts);
      fileObject.moveTo(fileObject2);
      ((SftpFileSystem) fileObject2.getFileSystem()).closeCommunicationLink();
      ((SftpFileSystem) fileObject.getFileSystem()).closeCommunicationLink();

    } catch (IOException e) {
      throw e;
    } finally {
      try {

        FileSystem fs = null;

        if (fileObject2 != null) {
          fs = fileObject2.getFileSystem();
          manager.closeFileSystem(fs);
        }

        fs = null;
        if (fileObject != null) {
          fs = fileObject.getFileSystem();
          manager.closeFileSystem(fs);
        }
      } finally {
        // Just ignore the exception
      }
    }
    return true;
  }
  public FileObject open(
      Shell applicationShell,
      String[] schemeRestrictions,
      String initialScheme,
      boolean showFileScheme,
      String fileName,
      String[] fileFilters,
      String[] fileFilterNames,
      boolean returnUserAuthenticatedFile,
      int fileDialogMode,
      boolean showLocation,
      boolean showCustomUI) {

    this.fileDialogMode = fileDialogMode;
    this.fileFilters = fileFilters;
    this.fileFilterNames = fileFilterNames;
    this.applicationShell = applicationShell;
    this.showFileScheme = showFileScheme;
    this.initialScheme = initialScheme;
    this.schemeRestrictions = schemeRestrictions;
    this.showLocation = showLocation;
    this.showCustomUI = showCustomUI;

    FileObject tmpInitialFile = initialFile;

    if (defaultInitialFile != null && rootFile == null) {
      try {
        rootFile = defaultInitialFile.getFileSystem().getRoot();
        initialFile = defaultInitialFile;
      } catch (FileSystemException ignored) {
        // well we tried
      }
    }

    createDialog(applicationShell);

    if (!showLocation) {
      comboPanel.setParent(fakeShell);
    } else {
      comboPanel.setParent(customUIPanel);
    }

    if (!showCustomUI) {
      customUIPanel.setParent(fakeShell);
    } else {
      customUIPanel.setParent(dialog);
    }

    // create our file chooser tool bar, contains parent folder combo and various controls
    createToolbarPanel(dialog);
    // create our vfs browser component
    createVfsBrowser(dialog);
    populateCustomUIPanel(dialog);
    if (fileDialogMode == VFS_DIALOG_SAVEAS) {
      createFileNamePanel(dialog, fileName);
    } else {
      // create file filter panel
      createFileFilterPanel(dialog);
    }
    // create our ok/cancel buttons
    createButtonPanel(dialog);

    initialFile = tmpInitialFile;
    // set the initial file selection
    try {
      if (initialFile != null || rootFile != null) {
        vfsBrowser.selectTreeItemByFileObject(initialFile != null ? initialFile : rootFile, true);
        updateParentFileCombo(initialFile != null ? initialFile : rootFile);
        setSelectedFile(initialFile != null ? initialFile : rootFile);
        openFileCombo.setText(
            initialFile != null ? initialFile.getName().getURI() : rootFile.getName().getURI());
      }
    } catch (FileSystemException e) {
      MessageBox box = new MessageBox(dialog.getShell());
      box.setText(Messages.getString("VfsFileChooserDialog.error")); // $NON-NLS-1$
      box.setMessage(e.getMessage());
      box.open();
    }

    // set the size and show the dialog
    int height = 550;
    int width = 800;
    dialog.setSize(width, height);
    Rectangle bounds = dialog.getDisplay().getPrimaryMonitor().getClientArea();
    int x = (bounds.width - width) / 2;
    int y = (bounds.height - height) / 2;
    dialog.setLocation(x, y);
    dialog.open();

    if (rootFile != null && fileDialogMode == VFS_DIALOG_SAVEAS) {
      if (!rootFile.getFileSystem().hasCapability(Capability.WRITE_CONTENT)) {
        MessageBox messageDialog = new MessageBox(dialog.getShell(), SWT.OK);
        messageDialog.setText(Messages.getString("VfsFileChooserDialog.warning")); // $NON-NLS-1$
        messageDialog.setMessage(
            Messages.getString("VfsFileChooserDialog.noWriteSupport")); // $NON-NLS-1$
        messageDialog.open();
      }
    }

    vfsBrowser.fileSystemTree.forceFocus();
    while (!dialog.isDisposed()) {
      if (!dialog.getDisplay().readAndDispatch()) dialog.getDisplay().sleep();
    }

    // we just woke up, we are probably disposed already..
    if (!dialog.isDisposed()) {
      hideCustomPanelChildren();
      dialog.dispose();
    }
    if (okPressed) {
      FileObject returnFile = vfsBrowser.getSelectedFileObject();
      if (returnFile != null && fileDialogMode == VFS_DIALOG_SAVEAS) {
        try {
          if (returnFile.getType().equals(FileType.FILE)) {
            returnFile = returnFile.getParent();
          }
          returnFile = returnFile.resolveFile(enteredFileName);
        } catch (FileSystemException e) {
          e.printStackTrace();
        }
      }

      // put user/pass on the filename so it comes out in the getUri call.
      if (!returnUserAuthenticatedFile) {
        // make sure to put the user/pass on the url if it's not there
        if (returnFile != null && returnFile.getName() instanceof URLFileName) {
          URLFileName urlFileName = (URLFileName) returnFile.getName();
          if (urlFileName.getUserName() == null || urlFileName.getPassword() == null) {
            // set it
            String user = "";
            String pass = "";

            UserAuthenticator userAuthenticator =
                DefaultFileSystemConfigBuilder.getInstance()
                    .getUserAuthenticator(returnFile.getFileSystem().getFileSystemOptions());

            if (userAuthenticator != null) {
              UserAuthenticationData data =
                  userAuthenticator.requestAuthentication(AUTHENTICATOR_TYPES);
              user = String.valueOf(data.getData(UserAuthenticationData.USERNAME));
              pass = String.valueOf(data.getData(UserAuthenticationData.PASSWORD));
              try {
                user = URLEncoder.encode(user, "UTF-8");
                pass = URLEncoder.encode(pass, "UTF-8");
              } catch (UnsupportedEncodingException e) {
                // ignore, just use the un encoded values
              }
            }

            // build up the url with user/pass on it
            int port = urlFileName.getPort();
            String portString = (port < 1) ? "" : (":" + port);
            String urlWithUserPass =
                urlFileName.getScheme()
                    + "://"
                    + user
                    + ":"
                    + pass
                    + "@"
                    + urlFileName.getHostName()
                    + portString
                    + urlFileName.getPath();

            try {
              returnFile = currentPanel.resolveFile(urlWithUserPass);
            } catch (FileSystemException e) {
              // couldn't resolve with user/pass on url??? interesting
              e.printStackTrace();
            }
          }
        }
      }
      return returnFile;
    } else {
      return null;
    }
  }
示例#10
0
  public String getFileContent(String fileName) throws Exception {
    FileSystemManager fsManager = null;
    FileObject sftpFile = null;
    FileObject src = null; // used for cleanup in release()
    String fileContent = null;

    try {
      System.out.println("SFTP download");
      FileSystemOptions opts = null;
      // app.initialize();
      try {
        fsManager = VFS.getManager();
      } catch (FileSystemException ex) {
        throw new RuntimeException("failed to get fsManager from VFS", ex);
      }

      UserAuthenticator auth = new StaticUserAuthenticator(null, this.user, this.password);
      opts = new FileSystemOptions();
      try {
        DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
        SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
      } catch (FileSystemException ex) {
        throw new RuntimeException("setUserAuthenticator failed", ex);
      }

      // app.process();
      String startPath =
          "sftp://"
              + this.user
              + ":"
              + this.password
              + "@"
              + this.host
              + ":22"
              + this.remoteDir
              + fileName;

      // Set starting path on remote SFTP server.
      try {
        sftpFile = fsManager.resolveFile(startPath, opts);

        System.out.println("SFTP connection successfully established to " + startPath);
      } catch (FileSystemException ex) {
        throw new RuntimeException("SFTP error parsing path " + this.remoteDir, ex);
      }

      if (sftpFile.exists()) {
        FileContent fc = sftpFile.getContent();
        StringWriter writer = new StringWriter();
        IOUtils.copy(fc.getInputStream(), writer, encoding);
        String theString = writer.toString();
        //	         	System.out.println(theString);
        fileContent = theString;
      }

    } finally {
      // app.release();
      /** Release system resources, close connection to the filesystem. */
      try {
        FileSystem fs = null;
        if (sftpFile != null) {
          fs = sftpFile.getFileSystem(); // This works even if the src is closed.
          fsManager.closeFileSystem(fs);
        } // TODO if sftpFile != null
      } catch (Exception e) {
        System.out.println(e);
      }
    }
    return fileContent;
  }