Exemple #1
0
 public void get(String source, File destination) throws IOException {
   fireTransferInitiated(getResource(source), TransferEvent.REQUEST_GET);
   ChannelSftp c = getSftpChannel(source);
   try {
     String path = getPath(source);
     c.get(path, destination.getAbsolutePath(), new MyProgressMonitor());
   } catch (SftpException e) {
     IOException ex =
         new IOException(
             "impossible to get "
                 + source
                 + " on "
                 + getHost()
                 + (e.getMessage() != null ? ": " + e.getMessage() : ""));
     ex.initCause(e);
     throw ex;
   } catch (URISyntaxException e) {
     IOException ex =
         new IOException(
             "impossible to get "
                 + source
                 + " on "
                 + getHost()
                 + (e.getMessage() != null ? ": " + e.getMessage() : ""));
     ex.initCause(e);
     throw ex;
   }
 }
Exemple #2
0
  private void copyFile(String sourcePath, String absoluteTargetPath, ChannelSftp channelSftp)
      throws MachineException {
    try {
      channelSftp.put(sourcePath, absoluteTargetPath);

      // apply permissions
      File file = new File(sourcePath);
      // read
      int permissions = 256;
      // execute
      if (file.canExecute()) {
        permissions += 64;
      }
      // write
      if (file.canWrite()) {
        permissions += 128;
      }
      channelSftp.chmod(permissions, absoluteTargetPath);
    } catch (SftpException e) {
      throw new MachineException(
          format(
              "Sftp copying of file %s failed. Error: %s",
              absoluteTargetPath, e.getLocalizedMessage()));
    }
  }
Exemple #3
0
 public InputStream openStream(SFTPResource resource) throws IOException {
   ChannelSftp c = getSftpChannel(resource.getName());
   try {
     String path = getPath(resource.getName());
     return c.get(path);
   } catch (SftpException e) {
     IOException ex =
         new IOException(
             "impossible to open stream for "
                 + resource
                 + " on "
                 + getHost()
                 + (e.getMessage() != null ? ": " + e.getMessage() : ""));
     ex.initCause(e);
     throw ex;
   } catch (URISyntaxException e) {
     IOException ex =
         new IOException(
             "impossible to open stream for "
                 + resource
                 + " on "
                 + getHost()
                 + (e.getMessage() != null ? ": " + e.getMessage() : ""));
     ex.initCause(e);
     throw ex;
   }
 }
  /** Returns last line of output from the command */
  public SampleResult sample(Entry e) {
    SampleResult res = new SampleResult();
    res.setSampleLabel(
        getName() + ":(" + getUsername() + "@" + getHostname() + ":" + getPort() + ")");

    // Set up sampler return types
    res.setSamplerData(action + " " + source);

    res.setDataType(SampleResult.TEXT);
    res.setContentType("text/plain");

    String response;
    if (getSession() == null) {
      connect();
    }

    try {
      if (getSession() == null) {
        log.error(
            "Failed to connect to server with credentials "
                + getUsername()
                + "@"
                + getHostname()
                + ":"
                + getPort()
                + " pw="
                + getPassword());
        throw new NullPointerException("Failed to connect to server: " + getFailureReason());
      }

      response = doFileTransfer(getSession(), source, destination, res);
      res.setResponseData(response.getBytes());

      res.setSuccessful(true);

      res.setResponseMessageOK();
    } catch (JSchException e1) {
      res.setSuccessful(false);
      res.setResponseCode("JSchException");
      res.setResponseMessage(e1.getMessage());
    } catch (SftpException e1) {
      res.setSuccessful(false);
      res.setResponseCode("SftpException");
      res.setResponseMessage(e1.getMessage());
    } catch (IOException e1) {
      res.setSuccessful(false);
      res.setResponseCode("IOException");
      res.setResponseMessage(e1.getMessage());
    } catch (NullPointerException e1) {
      res.setSuccessful(false);
      res.setResponseCode("Connection Failed");
      res.setResponseMessage(e1.getMessage());
    } finally {
      // Try a disconnect/sesson = null here instead of in finalize.
      disconnect();
      setSession(null);
    }
    return res;
  }
  public static void main(String[] args) {
    SFTPGetTest test = new SFTPGetTest();

    Map<String, String> sftpDetails = new HashMap<String, String>();
    // 设置主机ip,用户名,密码,端口
    sftpDetails.put(SFTPConstants.SFTP_REQ_HOST, IP);
    sftpDetails.put(SFTPConstants.SFTP_REQ_PORT, PORT);
    sftpDetails.put(SFTPConstants.SFTP_REQ_USERNAME, USERNAME);
    sftpDetails.put(SFTPConstants.SFTP_REQ_PASSWORD, PASSWOED);

    // 创建下载通道。以及超时时长,单位是毫秒
    SFTPChannel channel = test.getSFTPChannel();
    ChannelSftp chSftp = null;
    try {
      chSftp = channel.getChannel(sftpDetails, delayTime);
    } catch (JSchException e1) {
      System.out.println("error:创建下载通道失败!failed to creat a channel!");
      e1.printStackTrace();
    }

    SftpATTRS attr = null;
    try {
      attr = chSftp.stat(FILE_PATH_SFTP);
    } catch (SftpException e1) {
      System.out.println("error:获取文件大小失败失败!failed to get the size of the file!");
      e1.printStackTrace();
    }
    long fileSize = attr.getSize();
    System.out.println("fileSize=" + fileSize);
    try {

      chSftp.get(FILE_PATH_SFTP, DESTINATION_LOCAL, new MyProgressMonitor(fileSize)); // 代码段1

      //            OutputStream out = new FileOutputStream(DESTINATION_LOCAL);//这是采用文件输入流方式下载文件
      //             chSftp.get(FILE_PATH_SFTP, out, new FileProgressMonitor(fileSize)); // 代码段2

      /**
       * 代码段3
       *
       * <p>OutputStream out = new FileOutputStream(DESTINATION_LOCAL);//这是采用文件输入流方式下载文件 InputStream
       * is = chSftp.get(FILE_PATH_SFTP, new MyProgressMonitor()); byte[] buff = new byte[1024 * 2];
       * int read; if (is != null) { System.out.println("Start to read input stream"); do { read =
       * is.read(buff, 0, buff.length); if (read > 0) { out.write(buff, 0, read); } out.flush(); }
       * while (read >= 0); System.out.println("input stream read done."); }
       */
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      chSftp.quit();
      try {
        channel.closeChannel();
      } catch (Exception e) {
        System.out.println("error:关闭下载通道失败!failed to close the channel!");
        e.printStackTrace();
      }
    }
  }
Exemple #6
0
 protected boolean fastExistsFile(String name) throws GenericFileOperationFailedException {
   LOG.trace("fastExistsFile({})", name);
   try {
     @SuppressWarnings("rawtypes")
     Vector files = channel.ls(name);
     if (files == null) {
       return false;
     }
     return files.size() >= 1;
   } catch (SftpException e) {
     // or an exception can be thrown with id 2 which means file does not exists
     if (ChannelSftp.SSH_FX_NO_SUCH_FILE == e.id) {
       return false;
     }
     // otherwise its a more serious error so rethrow
     throw new GenericFileOperationFailedException(e.getMessage(), e);
   }
 }
  static void downloadFileByName(String filename) {
    try {
      System.out.println("Downloading file : " + filename);
      int mode = ChannelSftp.OVERWRITE;
      sftpChannel.get(filename, localDirectory, null, mode);
      downloadedFileCount++;
      System.out.println("Download Completed.");

      // file moving to processed folder
      moveFileToProcessedFolder(filename);
    } catch (SftpException e) {
      System.out.println("Exception in downloadFileByName(" + filename + "): " + e.toString());
      errorMessage += "Exception in downloadFileByName(" + filename + "): " + e.toString() + "\n";
    } catch (Exception e) {
      System.out.println("Exception in downloadFileByName(" + filename + "): " + e.toString());
      errorMessage += "Exception in downloadFileByName(" + filename + "): " + e.toString() + "\n";
    }
  }
Exemple #8
0
  public boolean existsFile(String name) throws GenericFileOperationFailedException {
    LOG.trace("existsFile({})", name);
    if (endpoint.isFastExistsCheck()) {
      return fastExistsFile(name);
    }
    // check whether a file already exists
    String directory = FileUtil.onlyPath(name);
    if (directory == null) {
      // assume current dir if no path could be extracted
      directory = ".";
    }
    String onlyName = FileUtil.stripPath(name);

    try {
      @SuppressWarnings("rawtypes")
      Vector files = channel.ls(directory);
      // can return either null or an empty list depending on FTP servers
      if (files == null) {
        return false;
      }
      for (Object file : files) {
        ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) file;
        String existing = entry.getFilename();
        LOG.trace("Existing file: {}, target file: {}", existing, name);
        existing = FileUtil.stripPath(existing);
        if (existing != null && existing.equals(onlyName)) {
          return true;
        }
      }
      return false;
    } catch (SftpException e) {
      // or an exception can be thrown with id 2 which means file does not exists
      if (ChannelSftp.SSH_FX_NO_SUCH_FILE == e.id) {
        return false;
      }
      // otherwise its a more serious error so rethrow
      throw new GenericFileOperationFailedException(e.getMessage(), e);
    }
  }
Exemple #9
0
 public void put(File source, String destination, boolean overwrite) throws IOException {
   fireTransferInitiated(getResource(destination), TransferEvent.REQUEST_PUT);
   ChannelSftp c = getSftpChannel(destination);
   try {
     String path = getPath(destination);
     if (!overwrite && checkExistence(path, c)) {
       throw new IOException("destination file exists and overwrite == false");
     }
     if (path.indexOf('/') != -1) {
       mkdirs(path.substring(0, path.lastIndexOf('/')), c);
     }
     c.put(source.getAbsolutePath(), path, new MyProgressMonitor());
   } catch (SftpException e) {
     IOException ex = new IOException(e.getMessage());
     ex.initCause(e);
     throw ex;
   } catch (URISyntaxException e) {
     IOException ex = new IOException(e.getMessage());
     ex.initCause(e);
     throw ex;
   }
 }
Exemple #10
0
  public String commandLs(String dir) {
    String token = "{\"ls\": [{";
    String[] files;

    try {
      files = this.sftp.ls(dir);
    } catch (SftpException e) {
      files = new String[0];
      e.printStackTrace();
    }

    for (String filename : files) {
      String type = filename.substring(0, 1);
      token +=
          "\"name\": \""
              + filename.substring(1)
              + "\", \"isdir\": "
              + String.valueOf(type.equals("d"))
              + "}, {";
    }
    token = token.substring(0, token.length() - 3) + "]}";

    return token;
  }
  public String downloadFile(
      String host,
      int port,
      String username,
      String password,
      String filePath,
      String fileFormat,
      String fileType) {
    Session session = null;
    Channel channel = null;
    String homeDirectory = System.getProperty("user.home");
    String localDownloadRootDir = homeDirectory + File.separatorChar + host;
    String localDownloadDir = localDownloadRootDir + File.separatorChar + fileType;
    try {
      JSch jsch = new JSch();
      session = jsch.getSession(username, host, port);
      session.setPassword(password);
      java.util.Properties config = new java.util.Properties();
      config.put("StrictHostKeyChecking", "no");
      session.setConfig(config);
      session.connect();
      System.out.println("Host connected.");
      channel = session.openChannel("sftp");
      channel.connect();
    } catch (JSchException e) {
      System.out.println("Could not connect: " + e.toString());
    }

    if (channel.isConnected()) {

      int grabCount = 0;
      try {
        ChannelSftp c = (ChannelSftp) channel;
        c.cd(filePath);
        File rootPath = new File(localDownloadRootDir);
        File downloadPath = new File(localDownloadDir);
        if (!rootPath.exists()) {
          rootPath.mkdir();
        }
        if (!downloadPath.exists()) {
          downloadPath.mkdir();
        }
        c.lcd(localDownloadDir);
        System.out.println("lcd " + c.lpwd());

        // Get a listing of the remote directory
        @SuppressWarnings("unchecked")
        Vector<ChannelSftp.LsEntry> list = c.ls(".");

        // iterate through objects in list, identifying specific file names
        for (ChannelSftp.LsEntry oListItem : list) {
          // output each item from directory listing for logs

          if (oListItem.getFilename().contains(fileFormat)) {
            System.out.println(oListItem.toString());
            // If it is a file (not a directory)
            if (!oListItem.getAttrs().isDir()) {
              // Grab the remote file ([remote filename], [local path/filename to write file to])

              System.out.println("get " + oListItem.getFilename());
              c.get(
                  oListItem.getFilename(),
                  oListItem
                      .getFilename()); // while testing, disable this or all of your test files will
                                       // be grabbed

              grabCount++;

              // Delete remote file
              if (!fileFormat.equalsIgnoreCase(".der")) {
                c.rm(
                    oListItem
                        .getFilename()); // Note for SFTP grabs from this remote host, deleting the
                                         // file is unnecessary,
                //   as their system automatically moves an item to the 'downloaded' subfolder
                //   after it has been grabbed.  For other target hosts, un comment this line to
                // remove any downloaded files from the inbox.
              }
            }
          }
        }

        // Report files grabbed to log
        if (grabCount == 0) {
          System.out.println("Found no new files to grab.");
        } else {
          System.out.println("Retrieved " + grabCount + " new files.");
        }
      } catch (SftpException e) {
        System.out.println(e.toString());
      } finally {
        // disconnect session.  If this is not done, the job will hang and leave log files locked
        session.disconnect();
        System.out.println("Session Closed");
      }
    }
    return localDownloadDir;
  }
  /**
   * This method should only be run when a new version of the Manager will be released. It tries to
   * make the process more automatic. Currently: - Writes in the Version file in LOCAL DISK (Dropbox
   * folder, so Dropbox must be running!) - Uploads the file to the correct folder tree in the
   * SourceForge project, creating all needed folder on the way.
   */
  public static void main(String[] args) throws ZipException, IOException, JSchException {

    /*
     * IMPORTANT
     *
     * Before releasing a new version of the Manager, please, follow these instructions:
     * 0 - Update the Changelog.txt and Version.txt files
     * 1 - Check if the older version is fully compatible with this one after an update. managerOptions.xml shall not be lost by any reasons.
     * 2 - Check if the file paths below are correct.
     * 3 - Clean and build the project, then Package-for-store the Manager.jar
     * 4 - Goto Sourceforge.net and update the LABEL and the OS supported for the new Manager file.
     * 5 - Update in the HoN forums page (changelog, topic title and version in first line)
     */

    // First step is to get the version we want to release.
    String targetVersion = ManagerOptions.getInstance().getVersion();
    // Get the old jar
    File oldJarVersion =
        new File(
            "C:\\Users\\Shirkit\\Dropbox\\HonModManager\\Dropbox\\Public\\versions\\Manager.jar");
    // And the newly generated one
    File newJarVersion = new File("store\\Manager.jar");
    // Target output for where the differences will be generated
    String verionsFile =
        "C:\\Users\\Shirkit\\Dropbox\\HonModManager\\Dropbox\\Public\\versions.txt";
    File rootVersionsFolder =
        new File("C:\\Users\\Shirkit\\Dropbox\\HonModManager\\Dropbox\\Public\\versions\\");
    File output = new File(rootVersionsFolder, targetVersion + ".jar");

    System.out.println("Version to be released=" + targetVersion);
    System.out.println("Old version file=" + oldJarVersion.getAbsolutePath());
    System.out.println("New version file=" + newJarVersion.getAbsolutePath());
    System.out.println();

    if (calculate(oldJarVersion, newJarVersion, output.getAbsolutePath())) {
      System.out.println(
          "Output file generated.\nPath="
              + output.getAbsolutePath()
              + "\nSize="
              + output.length() / 1024
              + "KB");

      // Read the current versions file and store it for later
      FileInputStream fis = new FileInputStream(verionsFile);
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      copyInputStream(fis, baos);
      String s = baos.toString();
      fis.close();
      baos.close();

      System.out.println(s);

      if (!s.trim().isEmpty()) {
        if (s.contains("\n")) {
          System.out.println("Older version=" + s.substring(0, s.indexOf("\n")));
        } else {
          System.out.println("Older version=" + s);
        }
        s = targetVersion + "\n" + s;
      } else {
        System.out.println("First version!");
        s = targetVersion;
      }

      if (JOptionPane.showConfirmDialog(
              null, "Confirm upload?", "Confirmation", JOptionPane.YES_NO_OPTION)
          != 0) {
        System.exit(0);
      }

      // Write new versions file with the new released version
      FileWriter fw = new FileWriter(verionsFile);
      fw.write(s);
      fw.flush();
      fw.close();
      System.out.println("Versions file written with sucess!");

      fis = new FileInputStream(newJarVersion);
      FileOutputStream fos =
          new FileOutputStream(rootVersionsFolder + File.separator + "Manager.jar");
      copyInputStream(fis, fos);
      fis.close();
      fos.close();
      System.out.println("Manager.jar file written!");

      System.out.println();
    } else {
      System.err.println("No differences file. Output file not generated.");
      System.exit(0);
    }

    JSch jsch = new JSch();
    Session session = null;
    try {
      System.out.println("Connecting to SF");

      session =
          jsch.getSession(
              JOptionPane.showInputDialog("SourceForge Username") + ",all-inhonmodman",
              "frs.sourceforge.net",
              22);
      session.setConfig("StrictHostKeyChecking", "no");
      session.setPassword(JOptionPane.showInputDialog("SourceForge Password"));
      session.connect();

      Channel channel = session.openChannel("sftp");
      channel.connect();
      ChannelSftp sftpChannel = (ChannelSftp) channel;
      System.out.println("Connected!");
      String root = "/home/frs/project/a/al/all-inhonmodman";
      sftpChannel.cd(root);
      StringTokenizer versionTokens = new StringTokenizer(targetVersion, " ");
      boolean flag = true;
      while (versionTokens.hasMoreTokens()) {
        String s = versionTokens.nextToken();
        if (!cdExists(sftpChannel, s)) {
          sftpChannel.mkdir(s);
          flag = false;
        }
        sftpChannel.cd(s);
      }
      if (flag) {
        System.err.println("Version already exists!");
        sftpChannel.exit();
        session.disconnect();
        System.exit(0);
      }
      System.out.println("Uploading file");
      OutputStream out = sftpChannel.put("Manager.jar");
      FileInputStream fis = new FileInputStream(newJarVersion);
      copyInputStream(fis, out);
      out.close();
      fis.close();
      System.out.println("Upload complete");
      sftpChannel.exit();
      session.disconnect();
      System.out.println("SUCESS!");
    } catch (JSchException e) {
      e.printStackTrace();
    } catch (SftpException e) {
      e.printStackTrace();
    }

    System.exit(0);
  }