<commit_before>package se.sics.mspsim.cli;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Map;

import se.sics.mspsim.util.ActiveComponent;
import se.sics.mspsim.util.ComponentRegistry;
import se.sics.mspsim.util.MapTable;

public class CommandHandler implements ActiveComponent, Runnable {

  private Hashtable<String, Command> commands = new Hashtable<String, Command>();
  private boolean exit;
  private boolean workaround = false;

  private ArrayList<CommandContext[]> currentAsyncCommands = new ArrayList<CommandContext[]>();
  private BufferedReader inReader;
  private InputStream in;
  private PrintStream out;
  private PrintStream err;
  private MapTable mapTable;
  private ComponentRegistry registry;
  private int pid = 1;
  
  public CommandHandler() {
    exit = false;
    inReader = new BufferedReader(new InputStreamReader(in = System.in));
    out = System.out;
    err = System.err;

    registerCommands();
  }

  // Add it to the hashtable (overwriting anything there)
  public void registerCommand(String cmd, Command command) {
    commands.put(cmd, command);
  }


  private String readLine(BufferedReader inReader2) throws IOException {
    if (workaround) {
      StringBuilder str = new StringBuilder();
      while(true) {
        if (inReader2.ready()) {
          int c = inReader2.read();
          if (c == '\n') {
            return str.toString();
          }
          if (c != '\r') {
            str.append((char)c);
          }
        } else {
          try {
            Thread.sleep(500);
          } catch (InterruptedException e) {
            throw new InterruptedIOException();
          }
        }
      }
    } else {
      return inReader2.readLine();
    }
  }

  public void run() {
    while(!exit) {
      try {
        out.print(">");
        out.flush();
        String line = readLine(inReader);//.readLine();
        if (line != null && line.length() > 0) {
          String[][] parts = CommandParser.parseLine(line);
          if(parts.length > 0 && checkCommands(parts) == 0) {
            CommandContext[] commands = new CommandContext[parts.length];
            for (int i = 0; i < parts.length; i++) {
              String[] args = parts[i];
              Command cmd = getCommand(args[0]);
              commands[i] = new CommandContext(mapTable, args, 0, cmd);
              if (i > 0) {
                PrintStream po = new PrintStream(new LineOutputStream((LineListener) commands[i].getCommand()));
                commands[i - 1].setOutput(po, err);
              }
              // Last element also needs output!
              if (i == parts.length - 1) {
                commands[i].setOutput(out, err);
              }
              // TODO: Check if first command is also LineListener and set it up for input!!
            }
            // Execute when all is set-up in opposite order...
            for (int i = parts.length - 1; i >= 0; i--) {
              try {
                commands[i].getCommand().executeCommand(commands[i]);
              } catch (Exception e) {
                err.println("Error: Command failed: " + e.getMessage());
                e.printStackTrace(err);
              }
            }
            if (commands[0].getCommand() instanceof AsyncCommand) {
              commands[0].setPID(pid++);
              currentAsyncCommands.add(commands);
            }
          }
        }
      } catch (IOException e) {
        e.printStackTrace();
        err.println("Command line tool exiting...");
        exit = true;
      }
    }
  }

  // This will return an instance that can be configured -
  // which is basically not OK... TODO - fix this!!!
  private Command getCommand(String cmd)  {
    try {
      return (Command) commands.get(cmd).clone();
    } catch (CloneNotSupportedException e) {
      e.printStackTrace();
    }
    return null;
  }
    
  private int checkCommands(String[][] cmds) {
    for (int i = 0; i < cmds.length; i++) {
      Command command = commands.get(cmds[i][0]);
      if (command == null) {
        System.out.println("CLI: Command not found: " + cmds[i]);
        return -1;
      }
      if (i > 0 && !(command instanceof LineListener)) {
        System.out.println("CLI: Error " + cmds[i][0] + " does not take input");<commit_msg>fixed to show command name<commit_after>package se.sics.mspsim.cli;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Map;

import se.sics.mspsim.util.ActiveComponent;
import se.sics.mspsim.util.ComponentRegistry;
import se.sics.mspsim.util.MapTable;

public class CommandHandler implements ActiveComponent, Runnable {

  private Hashtable<String, Command> commands = new Hashtable<String, Command>();
  private boolean exit;
  private boolean workaround = false;

  private ArrayList<CommandContext[]> currentAsyncCommands = new ArrayList<CommandContext[]>();
  private BufferedReader inReader;
  private InputStream in;
  private PrintStream out;
  private PrintStream err;
  private MapTable mapTable;
  private ComponentRegistry registry;
  private int pid = 1;
  
  public CommandHandler() {
    exit = false;
    inReader = new BufferedReader(new InputStreamReader(in = System.in));
    out = System.out;
    err = System.err;

    registerCommands();
  }

  // Add it to the hashtable (overwriting anything there)
  public void registerCommand(String cmd, Command command) {
    commands.put(cmd, command);
  }


  private String readLine(BufferedReader inReader2) throws IOException {
    if (workaround) {
      StringBuilder str = new StringBuilder();
      while(true) {
        if (inReader2.ready()) {
          int c = inReader2.read();
          if (c == '\n') {
            return str.toString();
          }
          if (c != '\r') {
            str.append((char)c);
          }
        } else {
          try {
            Thread.sleep(500);
          } catch (InterruptedException e) {
            throw new InterruptedIOException();
          }
        }
      }
    } else {
      return inReader2.readLine();
    }
  }

  public void run() {
    while(!exit) {
      try {
        out.print(">");
        out.flush();
        String line = readLine(inReader);//.readLine();
        if (line != null && line.length() > 0) {
          String[][] parts = CommandParser.parseLine(line);
          if(parts.length > 0 && checkCommands(parts) == 0) {
            CommandContext[] commands = new CommandContext[parts.length];
            for (int i = 0; i < parts.length; i++) {
              String[] args = parts[i];
              Command cmd = getCommand(args[0]);
              commands[i] = new CommandContext(mapTable, args, 0, cmd);
              if (i > 0) {
                PrintStream po = new PrintStream(new LineOutputStream((LineListener) commands[i].getCommand()));
                commands[i - 1].setOutput(po, err);
              }
              // Last element also needs output!
              if (i == parts.length - 1) {
                commands[i].setOutput(out, err);
              }
              // TODO: Check if first command is also LineListener and set it up for input!!
            }
            // Execute when all is set-up in opposite order...
            for (int i = parts.length - 1; i >= 0; i--) {
              try {
                commands[i].getCommand().executeCommand(commands[i]);
              } catch (Exception e) {
                err.println("Error: Command failed: " + e.getMessage());
                e.printStackTrace(err);
              }
            }
            if (commands[0].getCommand() instanceof AsyncCommand) {
              commands[0].setPID(pid++);
              currentAsyncCommands.add(commands);
            }
          }
        }
      } catch (IOException e) {
        e.printStackTrace();
        err.println("Command line tool exiting...");
        exit = true;
      }
    }
  }

  // This will return an instance that can be configured -
  // which is basically not OK... TODO - fix this!!!
  private Command getCommand(String cmd)  {
    try {
      return (Command) commands.get(cmd).clone();
    } catch (CloneNotSupportedException e) {
      e.printStackTrace();
    }
    return null;
  }
    
  private int checkCommands(String[][] cmds) {
    for (int i = 0; i < cmds.length; i++) {
      Command command = commands.get(cmds[i][0]);
      if (command == null) {
        System.out.println("CLI: Command not found: " + cmds[i][0]);
        return -1;
      }
      if (i > 0 && !(command instanceof LineListener)) {
        System.out.println("CLI: Error " + cmds[i][0] + " does not take input");
{'fraction_non_alphanumeric': 0.12255338078291815, 'fraction_numerical': 0.005894128113879004, 'mean_word_length': 2.134541652143604, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 23, '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': '6800515', 'n_tokens_mistral': 2543, 'n_tokens_neox': 2498, 'n_words': 671}