@Test
  public void testFileStoreReport() throws Exception {
    Path targetPath = detectTargetFolder().toPath();
    Path lclSftp =
        Utils.resolve(
            targetPath,
            SftpConstants.SFTP_SUBSYSTEM_NAME,
            getClass().getSimpleName(),
            getCurrentTestName());
    Path parentPath = targetPath.getParent();
    FileStore store = Files.getFileStore(lclSftp.getRoot());
    final String queryPath = Utils.resolveRelativeRemotePath(parentPath, lclSftp);
    final SpaceAvailableExtensionInfo expected = new SpaceAvailableExtensionInfo(store);
    sshd.setSubsystemFactories(
        Arrays.<NamedFactory<Command>>asList(
            new SftpSubsystemFactory() {
              @Override
              public Command create() {
                return new SftpSubsystem(
                    getExecutorService(), isShutdownOnExit(), getUnsupportedAttributePolicy()) {
                  @Override
                  protected SpaceAvailableExtensionInfo doSpaceAvailable(int id, String path)
                      throws IOException {
                    if (!queryPath.equals(path)) {
                      throw new StreamCorruptedException(
                          "Mismatched query paths: expected=" + queryPath + ", actual=" + path);
                    }

                    return expected;
                  }
                };
              }
            }));

    try (SshClient client = SshClient.setUpDefaultClient()) {
      client.start();

      try (ClientSession session =
          client
              .connect(getCurrentTestName(), "localhost", port)
              .verify(7L, TimeUnit.SECONDS)
              .getSession()) {
        session.addPasswordIdentity(getCurrentTestName());
        session.auth().verify(5L, TimeUnit.SECONDS);

        try (SftpClient sftp = session.createSftpClient()) {
          SpaceAvailableExtension ext = assertExtensionCreated(sftp, SpaceAvailableExtension.class);
          SpaceAvailableExtensionInfo actual = ext.available(queryPath);
          assertEquals("Mismatched information", expected, actual);
        }
      } finally {
        client.stop();
      }
    }
  }
  @Test
  public void testGitPgm() throws Exception {
    Path targetParent = detectTargetFolder().getParent();
    Path serverDir = getTempTargetRelativeFile(getClass().getSimpleName());

    //
    // TODO: the GitpgmCommandFactory is kept in the test tree
    // TODO: because it's quite limited for now
    //

    try (SshServer sshd = setupTestServer()) {
      sshd.setSubsystemFactories(Arrays.<NamedFactory<Command>>asList(new SftpSubsystemFactory()));
      sshd.setCommandFactory(
          new GitPgmCommandFactory(Utils.resolveRelativeRemotePath(targetParent, serverDir)));
      sshd.start();

      int port = sshd.getPort();
      try {
        Utils.deleteRecursive(serverDir);

        try (SshClient client = setupTestClient()) {
          client.start();

          try (ClientSession session =
              client
                  .connect(getCurrentTestName(), SshdSocketAddress.LOCALHOST_IP, port)
                  .verify(7L, TimeUnit.SECONDS)
                  .getSession()) {
            session.addPasswordIdentity(getCurrentTestName());
            session.auth().verify(5L, TimeUnit.SECONDS);

            Path repo = serverDir.resolve(getCurrentTestName());
            Git.init().setDirectory(repo.toFile()).call();
            Git git = Git.open(repo.toFile());
            git.commit()
                .setMessage("First Commit")
                .setCommitter(getCurrentTestName(), "*****@*****.**")
                .call();

            Path readmeFile = Files.createFile(repo.resolve("readme.txt"));
            String commandPrefix = "git --git-dir " + repo.getFileName();
            execute(session, commandPrefix + " add " + readmeFile.getFileName());
            execute(session, commandPrefix + " commit -m \"readme\"");
          } finally {
            client.stop();
          }
        }
      } finally {
        sshd.stop();
      }
    }
  }
Example #3
0
  @Override
  public void download(String remote, String local, Collection<Option> options) throws IOException {
    local = ValidateUtils.checkNotNullAndNotEmpty(local, "Invalid argument local: %s", local);

    ClientSession session = getClientSession();
    FactoryManager manager = session.getFactoryManager();
    FileSystemFactory factory = manager.getFileSystemFactory();
    FileSystem fs = factory.createFileSystem(session);
    try {
      download(remote, fs, fs.getPath(local), options);
    } finally {
      try {
        fs.close();
      } catch (UnsupportedOperationException e) {
        // Ignore
      }
    }
  }
Example #4
0
  protected ChannelExec openCommandChannel(ClientSession session, String cmd) throws IOException {
    long waitTimeout =
        PropertyResolverUtils.getLongProperty(
            session, SCP_EXEC_CHANNEL_OPEN_TIMEOUT, DEFAULT_EXEC_CHANNEL_OPEN_TIMEOUT);
    ChannelExec channel = session.createExecChannel(cmd);

    long startTime = System.nanoTime();
    try {
      channel.open().verify(waitTimeout);
      long endTime = System.nanoTime();
      long nanosWait = endTime - startTime;
      if (log.isTraceEnabled()) {
        log.trace(
            "openCommandChannel("
                + session
                + ")["
                + cmd
                + "]"
                + " completed after "
                + nanosWait
                + " nanos out of "
                + TimeUnit.MILLISECONDS.toNanos(waitTimeout));
      }

      return channel;
    } catch (IOException | RuntimeException e) {
      long endTime = System.nanoTime();
      long nanosWait = endTime - startTime;
      if (log.isTraceEnabled()) {
        log.trace(
            "openCommandChannel("
                + session
                + ")["
                + cmd
                + "]"
                + " failed ("
                + e.getClass().getSimpleName()
                + ")"
                + " to complete after "
                + nanosWait
                + " nanos out of "
                + TimeUnit.MILLISECONDS.toNanos(waitTimeout)
                + ": "
                + e.getMessage());
      }

      channel.close(false);
      throw e;
    }
  }
  private void execute(ClientSession session, String command) throws Exception {
    try (ChannelExec channel = session.createExecChannel(command)) {
      channel.setOut(System.out);
      channel.setErr(System.err);
      channel.open().verify(11L, TimeUnit.SECONDS);

      Collection<ClientChannelEvent> result =
          channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.MINUTES.toMillis(1L));
      assertTrue(
          "Command '" + command + "'not completed on time: " + result,
          result.contains(ClientChannelEvent.CLOSED));

      Integer status = channel.getExitStatus();
      if (status != null) {
        assertEquals("Failed (" + status + ") " + command, 0, status.intValue());
      }
    }
  }