class SshUtil {

    public static boolean addHostKeyInKnownHostFile( Session session, String knownHostsFile )
        throws JSchException
    {
        if ( session == null )
        {
            logger.warn( "In addHostKeyInKnownHostFile, Session is null." );
            return false;
        }
        if ( knownHostsFile == null || knownHostsFile.isEmpty() )
        {
            logger.warn( "In addHostKeyInKnownHostFile, knownHostFile is either null or empty." );
            return false;
        }
        try
        {
            session.connect();
        }
        catch ( JSchException e )
        {
            logger.error( "In addHostKeyInKnownHostFile, error while SSH connection to Host '{}'.", session.getHost(),
                          e );
            throw e;
        }
        finally
        {
            if ( session != null && session.isConnected() )
            {
                session.disconnect();
            }
        }
        HostKeyRepository hostKeyRepository = null;
        try
        {
            hostKeyRepository = getHostKeyRepository( knownHostsFile );
        }
        catch ( JSchException e )
        {
            logger.error( "In addHostKeyInKnownHostFile, error while getting Host Key Repository "
                + "from the known hosts file '{}'.", knownHostsFile, e );
            throw e;
        }

        // get host key of the host
        HostKey hostKey = session.getHostKey();
        if ( hostKeyRepository != null )
        {
            if ( hostKeyRepository.check( hostKey.getHost(),
                                          hostKey.getKey().getBytes() ) == HostKeyRepository.NOT_INCLUDED )
            {
                // Add host key
                hostKeyRepository.add( hostKey, null );
                logger.debug( "In addHostKeyInKnownHostFile, Host key added for host {}.", hostKey.getHost() );
            }
            else
            {
                logger.debug( "In addHostKeyInKnownHostFile, SSH key already exists for host {} "
                    + "in the known hosts file '{}'.", hostKey.getHost(), knownHostsFile );
            }
            return true;
        }
        return false;
    }

}