Example #1
0
  private static void sftpUpload() {
    JSch.setLogger(new JschLogger());
    Session session = null;
    try {
      JSch jsch = new JSch();
      session = jsch.getSession(USERNAME, HOST, PORT);
      session.setPassword(PASSWORD);
      Properties config = new Properties();
      config.put("StrictHostKeyChecking", "no");
      session.setConfig(config);
      session.connect();

      Channel channel = session.openChannel(PROTOCOL_SFTP);
      channel.connect();

      BufferedInputStream in = new BufferedInputStream(new FileInputStream(SOURCE));
      ChannelSftp channelSftp = (ChannelSftp) channel;
      channelSftp.cd(TARGET);
      channelSftp.put(in, FILE_NAME);

    } catch (JSchException | SftpException | FileNotFoundException ex) {
      Logger.getLogger(JschDemo.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      if (session != null) {
        session.disconnect();
      }
    }
  }
Example #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()));
    }
  }
Example #3
0
  /* (non-Javadoc)
   * @see net.sf.thingamablog.transport.PublishTransport#publishFile(java.lang.String, java.io.File, net.sf.thingamablog.transport.TransportProgress)
   */
  public boolean publishFile(String pubPath, File file, TransportProgress tp) {
    if (sftp == null) {
      failMsg = "SFTP Client not initialized!";
      return false;
    }

    if (!isConnected()) {
      failMsg = "Not Connected!!!";
      return false;
    }

    if (tp.isAborted()) {
      failMsg = "Aborted";
      return false;
    }

    if (!pubPath.endsWith("/")) pubPath += "/"; // append a trailing slash if needed

    try {
      String cwd = sftp.pwd();
      if (!cwd.endsWith("/")) cwd += "/";
      if (!pubPath.equals(cwd)) {
        boolean changedDir = false;
        try {
          sftp.cd(pubPath); // try to change to the pub path
          changedDir = true; // changed dir OK
          System.out.println("Changed to " + pubPath);
        } catch (Exception cdEx) {
          logger.log(Level.WARNING, "Problem changing SFTP dir", cdEx);
        }

        if (!changedDir) {
          // was unable to change dir. the dir likely does not exist
          // so we'll try making the dir structure of pubPath
          mkdirs(pubPath);
          // sftp.cd(pubPath);
        }
      }

      int mode = ChannelSftp.OVERWRITE;
      // String dest = pubPath + file.getName();
      InputStream is = new FileInputStream(file);
      sftp.put(is, file.getName(), new MyProgressMonitor(tp), mode);
      is.close();

      return true;
    } catch (Exception ex) {
      failMsg = "Error publishing file to " + pubPath;
      failMsg += "\n" + ex.getMessage();
      logger.log(Level.WARNING, failMsg, ex);
      ex.printStackTrace();
    }

    return false;
  }
 @Override
 public Void create() throws Exception {
   sftp = acquire(sftpConnection);
   InputStream is = checkNotNull(contents.getInput(), "inputstream for path %s", path);
   try {
     sftp.put(is, path);
   } finally {
     Closeables.closeQuietly(contents);
   }
   return null;
 }
Example #5
0
 @Test(groups = "spring")
 public void testDelete() throws SftpException {
   final Iterable<?> iterable = sftpChannel.ls(".");
   for (Object object : iterable) {
     com.jcraft.jsch.ChannelSftp.LsEntry entry = (LsEntry) object;
     System.out.println(entry.getFilename());
   }
   // assert sftpChannel.lstat("to_delete") == null;
   sftpChannel.put(new ByteArrayInputStream("Hello World!".getBytes()), "to_delete");
   assert sftpChannel.lstat("to_delete") != null;
   sftpChannel.rm("to_delete"); // Will throw exception if fails
 }
Example #6
0
 @Override
 public void send(String path, String filename, Binary content) throws IOException {
   Session session = null;
   Channel channel = null;
   ChannelSftp channelSftp = null;
   logger.debug("preparing the host information for sftp.");
   InputStream data = null;
   try {
     JSch jsch = new JSch();
     session = jsch.getSession(this.username, this.server, this.remotePort);
     if (this.password != null) {
       session.setPassword(this.password);
     }
     java.util.Properties config = new java.util.Properties();
     config.put("StrictHostKeyChecking", "no");
     session.setConfig(config);
     session.connect();
     logger.debug("Host connected.");
     channel = session.openChannel("sftp");
     channel.connect();
     logger.debug("sftp channel opened and connected.");
     channelSftp = (ChannelSftp) channel;
     if (path != null) {
       channelSftp.cd(path);
     }
     File f = new File(filename);
     data = content.getDataAsStream();
     channelSftp.put(data, f.getName());
     logger.info("File transfered successfully to host.");
   } catch (Exception ex) {
     throw new IOException("SFTP problem", ex);
   } finally {
     if (data != null) {
       try {
         data.close();
       } catch (IOException e) {
       }
     }
     if (channelSftp != null) {
       channelSftp.exit();
     }
     logger.info("sftp Channel exited.");
     if (channel != null) {
       channel.disconnect();
     }
     logger.info("Channel disconnected.");
     if (session != null) {
       session.disconnect();
     }
     logger.info("Host Session disconnected.");
   }
 }
Example #7
0
 @Override
 public void put(String path, Payload contents) {
   checkNotNull(path, "path");
   checkNotNull(contents, "contents");
   ChannelSftp sftp = getSftp();
   try {
     sftp.put(contents.getInput(), path);
   } catch (SftpException e) {
     throw new SshException(
         String.format("%s@%s:%d: Error putting path: %s", username, host, port, path), e);
   } finally {
     Closeables.closeQuietly(contents);
   }
 }
Example #8
0
  public void put(InputStream inputStream, String remoteFile) throws KettleJobException {
    int mode = ChannelSftp.OVERWRITE;

    try {
      c.put(inputStream, remoteFile, null, mode);
    } catch (Exception e) {
      throw new KettleJobException(e);
    } finally {
      if (inputStream != null) {
        try {
          inputStream.close();
        } catch (IOException e) {
          throw new KettleJobException(e);
        }
      }
    }
  }
Example #9
0
 public void put(FileObject fileObject, String remoteFile) throws KettleJobException {
   int mode = ChannelSftp.OVERWRITE;
   InputStream inputStream = null;
   try {
     inputStream = KettleVFS.getInputStream(fileObject);
     c.put(inputStream, remoteFile, null, mode);
   } catch (Exception e) {
     throw new KettleJobException(e);
   } finally {
     if (inputStream != null) {
       try {
         inputStream.close();
       } catch (IOException e) {
         throw new KettleJobException(e);
       }
     }
   }
 }
Example #10
0
  // src原文件; dst 目标目录
  public static void putDirectory(String src, String dst, ChannelSftp chSftp, String contain)
      throws SftpException {
    // 如果服务器目录不存在,需要创建目录
    try {
      chSftp.cd(dst);
    } catch (SftpException sException) {
      // sException.printStackTrace();
      if (ChannelSftp.SSH_FX_NO_SUCH_FILE == sException.id) {
        chSftp.mkdir(dst);
      }
    }
    //
    File file = new File(src);
    File[] dir = file.listFiles();
    // file是文件
    if (dir == null) {

      String f_type = getFileType(src);
      // 匹配上传文件类型
      if (contain.indexOf(f_type) > -1) {
        System.out.println(src + " >>> " + dst);
        // 上传
        // long fileSize = file.length();
        // chSftp.put(src, dst, new FileProgressMonitor(fileSize),
        // ChannelSftp.OVERWRITE);
        chSftp.put(src, dst, ChannelSftp.OVERWRITE);
      }
      return;
    }
    // 目录
    for (int i = 0; i < dir.length; i++) {
      File sub_file = dir[i];
      File[] sub_dir = sub_file.listFiles();
      // 文件
      if (sub_dir == null) {
        putDirectory(sub_file.getPath(), dst, chSftp, contain);
        continue;
      }
      // 目录 需要取目录名
      String sub_name = sub_file.getName();
      putDirectory(src + sub_name + "\\", dst + sub_name + "/", chSftp, contain);
      // System.out.println("subDitr:"+subDir);
    }
  }
  @Test
  public void testSendFileWithSftpException() throws Exception {
    mockJSch = createMock(JSch.class);
    mockSession = createMock(Session.class);
    mockChannelSftp = createMock(ChannelSftp.class);
    expect(mockJSch.getSession(USERNAME, HOSTNAME, PORT)).andReturn(mockSession);
    mockSession.setPassword(PASSWORD);
    mockSession.setConfig(STRICTHOSTKEYCHECKING, STRICTHOSTKEYCHECKING_VALUE);
    mockSession.connect();
    expect(mockSession.openChannel("sftp")).andReturn(mockChannelSftp);
    mockChannelSftp.connect();
    mockChannelSftp.put(isA(InputStream.class), eq(FTPDESTINATIONFILENAME));
    expectLastCall().andThrow(new SftpException(1, "Test"));
    replay(mockJSch, mockSession, mockChannelSftp);

    sftpClientImpl.setJsch(mockJSch);

    assertEquals(false, sftpClientImpl.sendFile(FILE_CONTENT));
    assertEquals("Error in SftpClient\n", logFactoryMock.getError(true));
  }
  /**
   * Executes a the given command inside a short-lived channel in the session.
   *
   * <p>Performance could be likely improved by reusing a single channel, though the gains would be
   * minimal compared to sharing the Session.
   *
   * @param session Session in which to create the channel
   * @return All standard output from the command
   * @throws JSchException
   * @throws SftpException
   * @throws IOException
   */
  private String doFileTransfer(Session session, String src, String dst, SampleResult res)
      throws JSchException, SftpException, IOException {
    StringBuilder sb = new StringBuilder();
    ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");

    res.sampleStart();
    channel.connect();

    if (SFTP_COMMAND_GET.equals(action)) {

      if (!printFile) {
        channel.get(src, dst);
      } else {
        BufferedReader br = new BufferedReader(new InputStreamReader(channel.get(src)));
        for (String line = br.readLine(); line != null; line = br.readLine()) {
          sb.append(line);
          sb.append("\n");
        }
      }

    } else if (SFTP_COMMAND_PUT.equals(action)) {
      channel.put(src, dst);
    } else if (SFTP_COMMAND_LS.equals(action)) {
      List<ChannelSftp.LsEntry> ls = channel.ls(src);
      for (ChannelSftp.LsEntry line : ls) {
        sb.append(line.getLongname());
        sb.append("\n");
      }
    } else if (SFTP_COMMAND_RM.equals(action)) {
      channel.rm(src);
    } else if (SFTP_COMMAND_RMDIR.equals(action)) {
      channel.rmdir(src);
    } else if (SFTP_COMMAND_RENAME.equals(action)) {
      channel.rename(src, dst);
    }

    res.sampleEnd();

    channel.disconnect();
    return sb.toString();
  }
Example #13
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;
   }
 }
 @Before
 public void setup() throws JSchException, SftpException {
   mockJSch = createMock(JSch.class);
   mockSession = createMock(Session.class);
   mockChannelSftp = createMock(ChannelSftp.class);
   expect(mockJSch.getSession(USERNAME, HOSTNAME, PORT)).andReturn(mockSession);
   mockSession.setPassword(PASSWORD);
   mockSession.setConfig(STRICTHOSTKEYCHECKING, STRICTHOSTKEYCHECKING_VALUE);
   mockSession.connect();
   expect(mockSession.openChannel("sftp")).andReturn(mockChannelSftp);
   mockChannelSftp.connect();
   mockChannelSftp.put(isA(InputStream.class), eq(FTPDESTINATIONFILENAME));
   mockChannelSftp.disconnect();
   mockSession.disconnect();
   replay(mockJSch, mockSession, mockChannelSftp);
   sftpClientImpl.setJsch(mockJSch);
   sftpClientImpl.setFtpDestinationFileName(FTPDESTINATIONFILENAME);
   sftpClientImpl.setHostname(HOSTNAME);
   sftpClientImpl.setPassword(PASSWORD);
   sftpClientImpl.setUsername(USERNAME);
   sftpClientImpl.setPort(PORT);
   logFactoryMock.getError(true);
 }
Example #15
0
  private static void testUploadStp() throws JSchException, SftpException {
    Channel channel = null;
    Session session = null;

    try {
      JSch jsch = new JSch();

      // jsch.setKnownHosts("/home/foo/.ssh/known_hosts");

      String user = "******";
      String host = "10.238.226.75";

      session = jsch.getSession(user, host, 22);

      String passwd = "sdpuser";
      session.setPassword(passwd);

      UserInfo ui =
          new MyUserInfo() {
            public void showMessage(String message) {
              //	          JOptionPane.showMessageDialog(null, message);
            }

            public boolean promptYesNo(String message) {
              //	          Object[] options={ "yes", "no" };
              //	          int foo=JOptionPane.showOptionDialog(null,
              //	                                               message,
              //	                                               "Warning",
              //	                                               JOptionPane.DEFAULT_OPTION,
              //	                                               JOptionPane.WARNING_MESSAGE,
              //	                                               null, options, options[0]);
              return true;
            }

            // If password is not given before the invocation of Session#connect(),
            // implement also following methods,
            //   * UserInfo#getPassword(),
            //   * UserInfo#promptPassword(String message) and
            //   * UIKeyboardInteractive#promptKeyboardInteractive()

          };

      session.setUserInfo(ui);

      // It must not be recommended, but if you want to skip host-key check,
      // invoke following,
      // session.setConfig("StrictHostKeyChecking", "no");

      // session.connect();
      session.connect(30000); // making a connection with timeout.

      channel = session.openChannel("sftp");

      channel.connect(3 * 1000);

      ChannelSftp sftp = (ChannelSftp) channel;

      sftp.cd("/var/opt/fds/logs");
      File f = new File("D:/Doneeeeeeeee.java");
      FileInputStream uploadStream = new FileInputStream(f);
      sftp.put(uploadStream, f.getName());

      System.out.println("Done :) ");
      //		    System.out.println(sftp.getHome());
      //		    for (Object o : sftp.ls("")) {
      //		        System.out.println(((ChannelSftp.LsEntry)o).getFilename());
      //		    }
    } catch (Exception e) {
      System.out.println(e);
    } finally {
      //	      Session session=jsch.getSession("usersdp","10.238.226.75",22);

      channel.disconnect();
      session.disconnect();
    }
  }
Example #16
0
  private boolean doStoreFile(String name, String targetName, Exchange exchange)
      throws GenericFileOperationFailedException {
    LOG.trace("doStoreFile({})", targetName);

    // if an existing file already exists what should we do?
    if (endpoint.getFileExist() == GenericFileExist.Ignore
        || endpoint.getFileExist() == GenericFileExist.Fail
        || endpoint.getFileExist() == GenericFileExist.Move) {
      boolean existFile = existsFile(targetName);
      if (existFile && endpoint.getFileExist() == GenericFileExist.Ignore) {
        // ignore but indicate that the file was written
        LOG.trace("An existing file already exists: {}. Ignore and do not override it.", name);
        return true;
      } else if (existFile && endpoint.getFileExist() == GenericFileExist.Fail) {
        throw new GenericFileOperationFailedException(
            "File already exist: " + name + ". Cannot write new file.");
      } else if (existFile && endpoint.getFileExist() == GenericFileExist.Move) {
        // move any existing file first
        doMoveExistingFile(name, targetName);
      }
    }

    InputStream is = null;
    if (exchange.getIn().getBody() == null) {
      // Do an explicit test for a null body and decide what to do
      if (endpoint.isAllowNullBody()) {
        LOG.trace("Writing empty file.");
        is = new ByteArrayInputStream(new byte[] {});
      } else {
        throw new GenericFileOperationFailedException("Cannot write null body to file: " + name);
      }
    }

    try {
      if (is == null) {
        String charset = endpoint.getCharset();
        if (charset != null) {
          // charset configured so we must convert to the desired
          // charset so we can write with encoding
          is =
              new ByteArrayInputStream(
                  exchange.getIn().getMandatoryBody(String.class).getBytes(charset));
          LOG.trace("Using InputStream {} with charset {}.", is, charset);
        } else {
          is = exchange.getIn().getMandatoryBody(InputStream.class);
        }
      }

      final StopWatch watch = new StopWatch();
      LOG.debug("About to store file: {} using stream: {}", targetName, is);
      if (endpoint.getFileExist() == GenericFileExist.Append) {
        LOG.trace("Client appendFile: {}", targetName);
        channel.put(is, targetName, ChannelSftp.APPEND);
      } else {
        LOG.trace("Client storeFile: {}", targetName);
        // override is default
        channel.put(is, targetName);
      }
      watch.stop();
      if (LOG.isDebugEnabled()) {
        LOG.debug(
            "Took {} ({} millis) to store file: {} and FTP client returned: true",
            new Object[] {TimeUtils.printDuration(watch.taken()), watch.taken(), targetName});
      }

      // after storing file, we may set chmod on the file
      String mode = endpoint.getConfiguration().getChmod();
      if (ObjectHelper.isNotEmpty(mode)) {
        // parse to int using 8bit mode
        int permissions = Integer.parseInt(mode, 8);
        LOG.trace("Setting chmod: {} on file: {}", mode, targetName);
        channel.chmod(permissions, targetName);
      }

      return true;

    } catch (SftpException e) {
      throw new GenericFileOperationFailedException("Cannot store file: " + name, e);
    } catch (InvalidPayloadException e) {
      throw new GenericFileOperationFailedException("Cannot store file: " + name, e);
    } catch (UnsupportedEncodingException e) {
      throw new GenericFileOperationFailedException("Cannot store file: " + name, e);
    } finally {
      IOHelper.close(is, "store: " + name, LOG);
    }
  }
 public void put(InputStream in, String remote) throws JSchException, SftpException {
   channel.put(in, remote);
 }
  /**
   * 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);
  }
 /**
  * push des fichiers sur serveur return liste des anomalies.
  *
  * @return issues list
  */
 public List<IssueBean> pushFilesOnSent() {
   List<IssueBean> issues = new ArrayList<IssueBean>();
   String path = exportFolder;
   if (path == null) {
     issues.add(
         new IssueBean(
             IssueBean.Severity.error, "path d export is null", Categorie.transportSFTP));
     return issues;
   }
   if (path.isEmpty()) {
     issues.add(
         new IssueBean(
             IssueBean.Severity.error, "path d export is empty", Categorie.transportSFTP));
     return issues;
   }
   File folder = new File(path);
   if (!folder.isDirectory()) {
     if (path.isEmpty()) {
       issues.add(
           new IssueBean(
               IssueBean.Severity.error,
               "path d export n est pas un repertoire:<" + path + ">",
               Categorie.transportSFTP));
       return issues;
     }
   }
   if (!folder.exists()) {
     issues.add(
         new IssueBean(
             IssueBean.Severity.error,
             "folder d export n existe pas:<" + path + ">",
             Categorie.transportSFTP));
     return issues;
   }
   // list files and folder
   File[] files = folder.listFiles();
   if (files != null) {
     if (files.length > 0) {
       try {
         ChannelSftp c = createSession();
         c.cd(workingDirectory);
         try {
           int fileCount = 0;
           for (File f : files) {
             if (f.isFile()) {
               fileCount++;
               FileInputStream fis = new FileInputStream(f);
               try {
                 c.put(fis, f.getName());
               } finally {
                 fis.close();
               }
               // move des fichiers envoyes dans le repertoire
               // d envoi
               StringFileTools.moveFile(f, sentFolder);
             }
           }
           if (fileCount == 0) {
             issues.add(
                 new IssueBean(
                     IssueBean.Severity.error,
                     "aucun fichier trouvé dans le dossier  dexport:" + path,
                     Categorie.transportSFTP));
           }
         } catch (Exception e) {
           issues.add(
               new IssueBean(
                   IssueBean.Severity.error,
                   "exception in put file:" + e.getMessage(),
                   Categorie.transportSFTP));
         }
         try {
           destroySession(c);
         } catch (Exception exc) {
           issues.add(
               new IssueBean(
                   IssueBean.Severity.error,
                   " Unable to disconnect exception:" + exc.getMessage(),
                   Categorie.transportSFTP));
         }
       } catch (Exception e) {
         LOGGER.error("unable to connect :" + e.getLocalizedMessage());
         issues.add(
             new IssueBean(
                 IssueBean.Severity.error,
                 " Unable to connect with u="
                     + ftpUserName
                     + ",h="
                     + ftpHost
                     + ",wdir="
                     + workingDirectory
                     + " exception:"
                     + e.getMessage(),
                 Categorie.transportSFTP));
       }
     } else {
       issues.add(
           new IssueBean(
               IssueBean.Severity.error,
               "aucun fichier a envoyer par sftp, size=0",
               Categorie.transportSFTP));
     }
   } else {
     issues.add(
         new IssueBean(
             IssueBean.Severity.error,
             "files is null on folder:" + path,
             Categorie.transportSFTP));
   }
   return issues;
 }
Example #20
-1
  public static void main(String[] arg) {
    try {
      JSch jsch = new JSch();

      String user = "******";
      String host = "hddev-c01-edge-01";
      int port = 22;
      String privateKey = "src/main/resources/id_rsa";

      jsch.addIdentity(privateKey);

      System.out.println("identity added ");

      Session session = jsch.getSession(user, host, port);
      System.out.println("session created.");

      // disabling StrictHostKeyChecking may help to make connection but makes it insecure
      // see
      // http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
      //
      java.util.Properties config = new java.util.Properties();
      config.put("StrictHostKeyChecking", "no");
      session.setConfig(config);

      session.connect();
      System.out.println("session connected.....");

      Channel channel = session.openChannel("sftp");
      channel.setInputStream(System.in);
      channel.setOutputStream(System.out);
      channel.connect();
      System.out.println("shell channel connected....");

      ChannelSftp c = (ChannelSftp) channel;

      String fileName = "src/main/resources/test.txt";
      c.put(fileName, "./in/");
      c.exit();
      System.out.println("done");

    } catch (Exception e) {
      System.err.println(e);
    }
  }