Example #1
0
 /**
  * Checks the existence for a remote file
  *
  * @param file to check
  * @param channel to use
  * @returns true if file exists, false otherwise
  * @throws IOException
  * @throws SftpException
  */
 private boolean checkExistence(String file, ChannelSftp channel)
     throws IOException, SftpException {
   try {
     return channel.stat(file) != null;
   } catch (SftpException ex) {
     return false;
   }
 }
Example #2
0
  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();
      }
    }
  }
Example #3
0
 private void mkdirs(String directory, ChannelSftp c) throws IOException, SftpException {
   try {
     SftpATTRS att = c.stat(directory);
     if (att != null) {
       if (att.isDir()) {
         return;
       }
     }
   } catch (SftpException ex) {
     if (directory.indexOf('/') != -1) {
       mkdirs(directory.substring(0, directory.lastIndexOf('/')), c);
     }
     c.mkdir(directory);
   }
 }
Example #4
0
  public boolean folderExists(String foldername) {
    boolean retval = false;
    try {
      SftpATTRS attrs = c.stat(foldername);
      if (attrs == null) {
        return false;
      }

      if ((attrs.getFlags() & SftpATTRS.SSH_FILEXFER_ATTR_PERMISSIONS) == 0) {
        throw new KettleJobException("Unknown permissions error");
      }

      retval = attrs.isDir();
    } catch (Exception e) {
      // Folder can not be found!
    }
    return retval;
  }
Example #5
0
  public FileType getFileType(String filename) throws KettleJobException {
    try {
      SftpATTRS attrs = c.stat(filename);
      if (attrs == null) {
        return FileType.IMAGINARY;
      }

      if ((attrs.getFlags() & SftpATTRS.SSH_FILEXFER_ATTR_PERMISSIONS) == 0) {
        throw new KettleJobException("Unknown permissions error");
      }

      if (attrs.isDir()) {
        return FileType.FOLDER;
      } else {
        return FileType.FILE;
      }
    } catch (Exception e) {
      throw new KettleJobException(e);
    }
  }
Example #6
0
 @Test(groups = "spring")
 public void testCantWriteToCwd() throws SftpException {
   SftpATTRS attrs = sftpChannel.stat(".");
   assert attrs.getPermissionsString().contains("r");
   assert attrs.getPermissionsString().contains("w");
 }
Example #7
0
 @Test(groups = "spring")
 public void testCannotWriteNonFolderObject() throws SftpException {
   SftpATTRS attrs = sftpChannel.stat("HUMAN");
   assert attrs.getPermissionsString().contains("r");
   assert !attrs.getPermissionsString().contains("w");
 }
Example #8
0
 @Test(groups = "spring")
 public void testCannotWriteExistingFile() throws SftpException {
   SftpATTRS attrs = sftpChannel.stat("Test Folder/Subfile");
   assert attrs.getPermissionsString().contains("r");
   assert !attrs.getPermissionsString().contains("w");
 }
  @Test
  public void testIntegration() throws Exception {
    final JSch mockJsch = mock(JSch.class);
    final Session mockSession = mock(Session.class);
    final ChannelSftp mockSftp = mock(ChannelSftp.class);
    final int port = 28;
    final int timeout = 3000;
    final BapSshHostConfiguration testHostConfig =
        new BapSshHostConfiguration(
            "testConfig",
            "testHostname",
            "testUsername",
            "",
            "/testRemoteRoot",
            port,
            timeout,
            false,
            "",
            "",
            false) {
          @Override
          public JSch createJSch() {
            return mockJsch;
          }
        };
    final BapSshCommonConfiguration commonConfig =
        new BapSshCommonConfiguration("passphrase", "key", "", false);
    new JenkinsTestHelper().setGlobalConfig(commonConfig, testHostConfig);
    final String dirToIgnore = "target";
    final int execTimeout = 10000;
    final BapSshTransfer transfer =
        new BapSshTransfer(
            "**/*",
            null,
            "sub-home",
            dirToIgnore,
            false,
            false,
            "",
            execTimeout,
            false,
            false,
            false,
            null);
    final BapSshPublisher publisher =
        new BapSshPublisher(
            testHostConfig.getName(),
            false,
            new ArrayList<BapSshTransfer>(Collections.singletonList(transfer)),
            false,
            false,
            null,
            null,
            null);
    final BapSshPublisherPlugin plugin =
        new BapSshPublisherPlugin(
            new ArrayList<BapSshPublisher>(Collections.singletonList(publisher)),
            false,
            false,
            false,
            "master",
            null);

    final FreeStyleProject project = createFreeStyleProject();
    project.getPublishersList().add(plugin);
    final String buildDirectory = "build-dir";
    final String buildFileName = "file.txt";
    project
        .getBuildersList()
        .add(
            new TestBuilder() {
              @Override
              public boolean perform(
                  final AbstractBuild<?, ?> build,
                  final Launcher launcher,
                  final BuildListener listener)
                  throws InterruptedException, IOException {
                final FilePath dir = build.getWorkspace().child(dirToIgnore).child(buildDirectory);
                dir.mkdirs();
                dir.child(buildFileName).write("Helloooooo", "UTF-8");
                build.setResult(Result.SUCCESS);
                return true;
              }
            });

    when(mockJsch.getSession(
            testHostConfig.getUsername(), testHostConfig.getHostname(), testHostConfig.getPort()))
        .thenReturn(mockSession);
    when(mockSession.openChannel("sftp")).thenReturn(mockSftp);
    final SftpATTRS mockAttrs = mock(SftpATTRS.class);
    when(mockAttrs.isDir()).thenReturn(true);
    when(mockSftp.stat(anyString())).thenReturn(mockAttrs);

    assertBuildStatusSuccess(project.scheduleBuild2(0).get());

    verify(mockJsch)
        .addIdentity("TheKey", BapSshUtil.toBytes("key"), null, BapSshUtil.toBytes("passphrase"));
    verify(mockSession).connect(timeout);
    verify(mockSftp).connect(timeout);
    verify(mockSftp).cd(transfer.getRemoteDirectory());
    verify(mockSftp).cd("build-dir");
    verify(mockSftp).put((InputStream) anyObject(), eq(buildFileName));
  }