title: Getting session and SFTP channel in Java using JSch library
body: <p>I am using JSch library for SFTP. I need to do several operations on SFTP server like move remote files in other directory, pull files, etc. For all these operations I need <code>Session</code> and from it I get <code>Channel</code> an then cast it to <code>ChannelSftp</code>. This is redundant step. So I thought of abstracting it into a <code>private</code> method.</p>
  
  <pre><code>private ChannelSftp getChannelSftp() throws JSchException
      {
          java.util.Properties config = new java.util.Properties();
          config.put("StrictHostKeyChecking", "no");
          JSch jsch = new JSch();
          Session session;
          session = jsch.getSession(VENDOR1_USERID, VENDOR1_SERVER, VENDOR1_PORT);
          session.setPassword(VENDOR1_PASSWORD);
  
          session.setConfig(config);
          session.connect();
  
          ChannelSftp channelSftp = null;
  
          Channel channel = session.openChannel("sftp");
          channel.connect();
          channelSftp = (ChannelSftp) channel;
  
          return channelSftp;
      }
  </code></pre>
  
  <p>But after the SFTP operation I need to disconnect from channel and session <strong>both</strong>.
  With above method, though I can disconnect from <code>Channel</code> in the calling method but I can't disconnect from <code>Session</code> as I don't have its instance which might be a leak so I now separated that into <code>getSession()</code> method and now <code>ChannelSftp</code> creation is duplicated in all methods. </p>
  
  <p>What is better way to <strong><em>design/refactor</em></strong> it?</p>
  
  <pre><code>private Session getSession() throws JSchException
      {
          java.util.Properties config = new java.util.Properties();
          config.put("StrictHostKeyChecking", "no");
          JSch jsch = new JSch();
          Session session;
          session = jsch.getSession(VENDOR1_USERID, VENDOR1_SERVER, VENDOR1_PORT);
          session.setPassword(VENDOR1_PASSWORD);
          session.setConfig(config);
          session.connect();
          return session;
      }
  </code></pre>
  
  <p><strong>Calling Method example:</strong> - <em>Duplicated code indicated</em></p>
  
  <pre><code>public void sftp(File file) throws  SftpException, FileNotFoundException, JSchException
      {
          Session session = getSession();
  /* Duplicate code START*/
          if ( session == null ) throw new SftpException(0 , "Service: Session is NULL"); 
  
          ChannelSftp channelSftp = null;
  
          Channel channel = session.openChannel("sftp");
          channel.connect();
          channelSftp = (ChannelSftp) channel;
  /* Duplicate code END*/
          channelSftp.cd(VENDOR1_PATH);
          channelSftp.put(new FileInputStream(file), file.getName());
  
          channelSftp.disconnect();
          session.disconnect();
      }
  </code></pre>