<commit_before>package brooklyn.util.internal;

import java.io.File
import java.io.IOException
import java.io.InputStream
import java.util.Map

import com.jcraft.jsch.Channel
import com.jcraft.jsch.ChannelExec
import com.jcraft.jsch.ChannelShell
import com.jcraft.jsch.JSch
import com.jcraft.jsch.Session

/** class is a wrapper for jsch session, taken from their examples */
public class SshJschTool {

    String host
    String user = System.getProperty('user.name')
    def port = 22
    def keyFiles = ['~/.ssh/id_dsa','~/.ssh/id_rsa']
    def config = ['StrictHostKeyChecking', 'no']

    private JSch jsch;
    private Session session;

    /**
     * Tidies up fields and config, e.g. replacing leading '~' with
     * System.getProperty('user.home'), replacing 'user@host' in host by setting
     * username.
     */
    public void tidy() {
        initJsch();
        if (host && host==~ /[^@]+@[^@]+/) {
            (user,host) = (host=~/([^@]+)@([^@]+)/)[0][1,2]
        }
        keyFiles = keyFiles.collect { it.startsWith('~')? (System.getProperty('user.home')+it.substring(1)) : it }
    }

    public void initJsch() {
        if (!jsch) jsch=new JSch();
    }

    public JSch getJsch() { jsch }
    public Session getSession() { session }

    public void connect() {
        if (session && session.isConnected()) throw new IllegalStateException("already connected to "+session)
        if (!host) throw new IllegalStateException("host must be specified")

        tidy()

        keyFiles.each { if (new File(it).exists()) { jsch.addIdentity(it) } }

        session = jsch.getSession(user, host, port)
        session.setConfig(config)
        try{
            session.connect()
        } catch (Exception e) {
            throw new IllegalStateException("Cannot connect to $user@$host: " + e);
        }
    }

    public void disconnect() {
        session.disconnect()
        session = null
    }

    public boolean isConnected() {
        session && session.isConnected()
    }

    protected void assertConnected() {
        if (!session) throw new IllegalStateException("no ssh session yet; invoke connect() before using")
        if (!isConnected()) throw new IllegalStateException("ssh session disconnected")
        assert session && session.isConnected() : ""
    }

    public static void block(Channel c, int pollPeriodMillis=50) {
        //TODO would much prefer to join the thread, but that isn't exposed!
        while (!c.isClosed()) synchronized (c) { c.wait(pollPeriodMillis) }
    }

    /**
     * Executes the set of commands in a shell; optional property 'out'
     * should be an output stream. Blocks until completion (unless property
     * 'block' set as false), so you must send an exit command.
     *  returns exit status.
     */
     public int execShell(Map properties=[:], String ...commands) {
         assertConnected()
         ChannelShell channel=session.openChannel("shell");
         lastChannel = channel
         if (properties.out) {
             channel.setOutputStream(properties.out, true)
         }

         StringBuffer sb = []
         commands.each { sb.append(it); sb.append("\n") }
         channel.setInputStream new ByteArrayInputStream(sb.toString().getBytes())

         channel.connect()
         if (properties.block==null || properties.block) {
             block(channel)
         }

         channel.getExitStatus()
    }

   /** convenience for the last channel used, in case it is needed */

   public Channel lastChannel

   /**
    *
* executes the set of commands using ssh exec, ";" separated (overridable
   with property 'separator'; optional properties 'out' and 'err' should be
   streams; * this is generally preferable to shell because it captures both
   streams and doesn't need an explicit exit, * but may cause problems if you
   are doing funny escaping or need env values which are only set on a
   full-fledged shell; * returns exit status (if blocking) */

   public int execCommands(Map properties=[:], String ...commands) {
       assertConnected()
       ChannelExec channel=session.openChannel("exec");
       lastChannel = channel;
       if (properties.out) {
           channel.setOutputStream(properties.out, true)
       }
<commit_msg>More formatting.<commit_after>package brooklyn.util.internal;

import java.io.File
import java.io.IOException
import java.io.InputStream
import java.util.Map

import com.jcraft.jsch.Channel
import com.jcraft.jsch.ChannelExec
import com.jcraft.jsch.ChannelShell
import com.jcraft.jsch.JSch
import com.jcraft.jsch.Session

/** class is a wrapper for jsch session, taken from their examples */
public class SshJschTool {

    String host
    String user = System.getProperty('user.name')
    def port = 22
    def keyFiles = ['~/.ssh/id_dsa','~/.ssh/id_rsa']
    def config = ['StrictHostKeyChecking', 'no']

    private JSch jsch;
    private Session session;

    /**
     * Tidies up fields and config, e.g. replacing leading '~' with
     * System.getProperty('user.home'), replacing 'user@host' in host by setting
     * username.
     */
    public void tidy() {
        initJsch();
        if (host && host==~ /[^@]+@[^@]+/) {
            (user,host) = (host=~/([^@]+)@([^@]+)/)[0][1,2]
        }
        keyFiles = keyFiles.collect { it.startsWith('~')? (System.getProperty('user.home')+it.substring(1)) : it }
    }

    public void initJsch() {
        if (!jsch) jsch=new JSch();
    }

    public JSch getJsch() { jsch }
    public Session getSession() { session }

    public void connect() {
        if (session && session.isConnected()) throw new IllegalStateException("already connected to "+session)
        if (!host) throw new IllegalStateException("host must be specified")

        tidy()

        keyFiles.each { if (new File(it).exists()) { jsch.addIdentity(it) } }

        session = jsch.getSession(user, host, port)
        session.setConfig(config)
        try{
            session.connect()
        } catch (Exception e) {
            throw new IllegalStateException("Cannot connect to $user@$host: " + e);
        }
    }

    public void disconnect() {
        session.disconnect()
        session = null
    }

    public boolean isConnected() {
        session && session.isConnected()
    }

    protected void assertConnected() {
        if (!session) throw new IllegalStateException("no ssh session yet; invoke connect() before using")
        if (!isConnected()) throw new IllegalStateException("ssh session disconnected")
        assert session && session.isConnected() : ""
    }

    public static void block(Channel c, int pollPeriodMillis=50) {
        //TODO would much prefer to join the thread, but that isn't exposed!
        while (!c.isClosed()) synchronized (c) { c.wait(pollPeriodMillis) }
    }

    /**
     * Executes the set of commands in a shell; optional property 'out'
     * should be an output stream. Blocks until completion (unless property
     * 'block' set as false), so you must send an exit command.
     *  returns exit status.
     */
     public int execShell(Map properties=[:], String ...commands) {
         assertConnected()
         ChannelShell channel=session.openChannel("shell");
         lastChannel = channel
         if (properties.out) {
             channel.setOutputStream(properties.out, true)
         }

         StringBuffer sb = []
         commands.each { sb.append(it); sb.append("\n") }
         channel.setInputStream new ByteArrayInputStream(sb.toString().getBytes())

         channel.connect()
         if (properties.block==null || properties.block) {
             block(channel)
         }

         channel.getExitStatus()
    }

   /** convenience for the last channel used, in case it is needed */

   public Channel lastChannel

   /**
    * Executes the set of commands using ssh exec, ";" separated (overridable
    * with property 'separator'.
    *
    * Optional properties 'out' and 'err' should be streams.
    * This is generally preferable to shell because it captures both
    *  streams and doesn't need an explicit exit, * but may cause problems if you
    * are doing funny escaping or need env values which are only set on a
    * full-fledged shell;
    * returns exit status (if blocking)
    */
   public int execCommands(Map properties=[:], String ...commands) {
       assertConnected()
       ChannelExec channel=session.openChannel("exec");
       lastChannel = channel;
       if (properties.out) {
           channel.setOutputStream(properties.out, true)
       }

{'fraction_non_alphanumeric': 0.11759194190676973, 'fraction_numerical': 0.0018739751698289998, 'mean_word_length': 2.6507054296707997, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6645500', 'n_tokens_mistral': 2421, 'n_tokens_neox': 2348, 'n_words': 725}