Package winCommandLine

Source Code of winCommandLine.Execute

package winCommandLine;

import java.awt.Color;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JOptionPane;
import javax.swing.filechooser.FileSystemView;

public class Execute implements Runnable, KeyListener{
 
  //declare private constants
  private volatile Thread thread = null;
  private String command = null;
  private Process process = null;
  private OutputStream out = null;
 
  public Execute(String command){
    this.command = command;
   
    //run each program in a thread, this allows for more programs to be run,
    //and prevents a certain programming from locking the typingSpace
    this.thread = new Thread(this);
    this.thread.start();
   
    //have a keylistener on the outputframe that cancels the thread if ^C is pressed
    //not efficient
    Console.outputArea.addKeyListener(this);
  }
 
  public void run(){
   
    //init simple variables
    String path = null;
    String wstr = null;
    byte[] wbyt = null;
    int pargstep = 0;
   
    //detect where or not there are arguments to the command
    int temp = this.command.indexOf(" ");
    //split the command and argument
    String command, cmdarg;
    if(temp == -1){
      command = this.command;
      cmdarg = "";
    }else{
      command = this.command.substring(0,temp);
      cmdarg = this.command.substring(temp+1);
    }
   
    //get the ending flags (the ones that are supposed to be typed in)
    //not effective
    ArrayList<String> pargs = Res.args(cmdarg, "\\\\\\", " ");
   
    //start pairing up commands that already defined by this program
    //versus defined by the system paths
    if(command.equals("exit")){
      System.exit(0);
    }else if(command.equals("cmd")){ //opens a new window. inefficient
      Loader.main(null);
    }else if(command.equals("scrsize")){
      int x = Toolkit.getDefaultToolkit().getScreenSize().width;
      int y = Toolkit.getDefaultToolkit().getScreenSize().height;
      Console.writeOutput("(" + x + "," + y + ")" + Console.nl);Console.nl();
//    }else if(command.equals("resize")){
//      int a, b, c, d;
//      pargs = Res.args(cmdarg, ",", ",");
//      try{
//        a = Integer.parseInt(pargs.get(0));
//        b = Integer.parseInt(pargs.get(1));
//        c = Integer.parseInt(pargs.get(2));
//        d = Integer.parseInt(pargs.get(3));
//        this.console.resize(a, b, c, d);
//      }catch(Exception e){
//        this.console.writeOutput(e + Console.nl);this.console.nl();
//      }
    }else if(command.equals("clear")){
      Console.clearOutput();
    }else if(command.equals("cd")){
      Console.currentDirectory = cmdarg;
    }else if(command.equals("addpath")){ //add a new path
      if(cmdarg.equals("env")){
        String value = System.getenv("Path"); //get system path
        Scanner scanner = new Scanner(value);
        scanner.useDelimiter(";");
        while(true){
          if(!scanner.hasNext())
            break;
          addPath(scanner.next());
        }
        scanner.close();
      }else
        addPath(cmdarg);
    }else if(command.equals("start")){ //batch runner
      try{
        start(Console.currentDirectory + "\\" + cmdarg);
      }catch(Exception e){
        Console.writeOutput("Error" + Console.nl); Console.nl();
        Console.writeOutput(e + Console.nl); Console.nl();
      }
      Console.writeOutput("Done executing" + Console.nl); Console.nl();
    }else if(command.equals("dir") || command.equals("ls")){
      Console.writeOutput(Console.currentDirectory + Console.nl); Console.nl();
     
      //pseudo equivalent of command line dir
      dir(cmdarg);
    }else if(command.equals("system")){ //get extra info about the system
      String s = null;
      int t = cmdarg.indexOf(":");
      if(t == -1){
        Console.writeOutput("Drive not found" + Console.nl); Console.nl();
      }
      s = cmdarg.substring(t - 1, t);
      hdserial(s);
      system(s);
    }else if(command.equals("mbserial")){
      //the motherboard serial number (aka cpu serial number)
      mbserial();
    }else if(command.equals("env")){
      //get the environment variables
      Map<String, String> map = System.getenv();
      Set<String> keys = map.keySet();
      Iterator<String> iterator = keys.iterator();
      Console.writeOutput("Variable name \t Variable Values" + Console.nl); Console.nl();
      while(iterator.hasNext()){
        String key = (String) iterator.next();
        String value = (String) map.get(key);
        Console.writeOutput(key + "\t" + value + Console.nl); Console.nl();
      }
    }else if(command.equals("bgcolor")){ //change the color of the background
      try{
        int a = 0;
        a = Integer.parseInt(cmdarg);
        Color bg = new Color(a);
        Console.console.setBackground(bg);
      }catch(Exception e){
        Console.writeOutput("Argument not in range");
      }
    }else if(command.equals("fcolor")){ //change the color of the font
      try{
        int a;
        a = Integer.parseInt(cmdarg);
        Color bg = new Color(a);
        Console.outputArea.setDisabledTextColor(bg);
      }catch(Exception e){
        Console.writeOutput("Argument not in range");
      }
    }else if(command.equals("font")){ //change the color and size of font.
      //highly un-user friendly
      pargs = Res.args(cmdarg, "/", "/");
      String name = Font.SERIF;
      int type = Font.PLAIN;
      int size = 12;
      for(int a = 0; a < pargs.size(); a++){
        String s0 = pargs.get(a);
        String s1 = s0.substring(0, 1);
        int i1 = s0.indexOf(" ");
        if(i1 == -1){
          Console.writeOutput(s1 + " has no argument, default will be used" + Console.nl); Console.nl();
          continue;
        }
        String s2 = s0.substring(i1 + 1);
        if(s1.equals("n")){
          name = s2;
        }else if(s1.equals("t")){
          try{
            type = Integer.parseInt(s2);
          }catch(Exception e){
            Console.writeOutput(s0 + " not number" + Console.nl); Console.nl();
          }
        }else if(s1.equals("s")){
          try{
            size = Integer.parseInt(s2);
          }catch(Exception e){
            Console.writeOutput(s0 + " not number" + Console.nl); Console.nl();
          }
        }
      }
      try{
        Font f = new Font(name, type, size);
        Console.outputArea.setFont(f);
      }catch(Exception e){
        Console.writeOutput("Error: " + e + Console.nl); Console.nl();
      }
      //?
    }else if(command.equals("copy")){ //simple copy a file to another file
      pargs = Res.args(cmdarg, " ", " ");
      try{
        File f1 = new File(pargs.get(0));
        File f2 = new File(pargs.get(1));
        InputStream in = new FileInputStream(f1);
        OutputStream out = new FileOutputStream(f2);
        byte buf[]=new byte[1024];
              int len;
              while((len=in.read(buf))>0)
              out.write(buf,0,len);
              out.close();
              in.close();
      }catch(Exception e){
        Console.writeOutput("Error: " + e + Console.nl); Console.nl();
      }
    }else if(command.equals("date") || command.equals("time")){
      //get current system time/date
      Calendar calendar = Calendar.getInstance();
      Console.writeOutput(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(calendar.getTime()) + Console.nl); Console.nl();
    }else if(command.equals("del")){ //simple delete a file
      try{
        File f1 = new File(cmdarg);
        f1.delete();
      }catch(Exception e){
        Console.writeOutput("Error: " + e + Console.nl); Console.nl();
      }
    }else if(command.equals("move")){
      Console.writeOutput("use copy, then delete"); Console.nl();
    }else if(command.equals("rename")){ //simple rename a file
      pargs = Res.args(cmdarg, " ", " "); //parse arguments
      try{
        File f1 = new File(pargs.get(0));
        f1.renameTo(new File(pargs.get(1)));
      }catch(Exception e){
        Console.writeOutput("Error: " + e + Console.nl); Console.nl();
      }
    }else{ //if no pre-defined function is found, run through paths
      for(int a = 0; a < Console.getPaths().length; a++){
        File f = new File(Console.getPaths()[a] + command + ".exe");
        if(f.isFile()){
          path = f.getAbsolutePath();
          break;
        }
      }
      if(path == null){
        Console.writeOutput("Program not found" + Console.nl); Console.nl();
        path = "";
      }
      try{
        //make process, get input/output streams, start outputting to Console
        Process p = Runtime.getRuntime().exec(path + " " + cmdarg);
        InputStream read = p.getInputStream();
        InputStream err = p.getErrorStream();
        this.out = p.getOutputStream();
        while(true){ //read inputstream, output to Console
          temp = read.read();
          if(temp == -1) break;
          String str = "";
          char[] c = Character.toChars(temp);
          for(int a = 0; a < c.length; a++){
            str += Character.toString(c[0]);
          }
          Console.writeOutput(str);
          if(str.equals(":") && pargs.size()>0){
            if(pargs.get(pargstep) == null) wstr = "\n";
            else wstr = pargs.get(pargstep) + "\n";
            wbyt = wstr.getBytes();
            this.out.write(wbyt);
            pargstep++;
          }
          if(temp == 13) Console.nl();
        }
        while(true){ //read errorstream, output to Console
          temp = err.read();
          if(temp == -1) break;
          String str = "";
          char[] c = Character.toChars(temp);
          for(int a = 0; a < c.length; a++){
            str += Character.toString(c[0]);
          }
          Console.writeOutput(str);
          if(str.equals(":") && pargs.size()>0){
            if(pargs.get(pargstep) == null) wstr = "\n";
            else wstr = pargs.get(pargstep) + "\n";
            wbyt = wstr.getBytes();
            this.out.write(wbyt);
            this.out.flush();
            if(pargs.size()>pargstep + 1)
              pargstep++;
          }
          if(temp == 13) Console.nl();
        }
        p.destroy();
        read.close();
        err.close();
        this.out.close();
        //close variables to avoid memory leaks
      }catch(Exception e){
        Console.writeOutput("Error" + Console.nl); Console.nl();
        Console.writeOutput(e + Console.nl); Console.nl();
      }
    }
    Console.writeOutput("Run Complete" + Console.nl + Console.nl); Console.nl();
    Console.outputArea.removeKeyListener(this);
    //remove no-longer funcitonal key listener. thread is already over.
  }
 
  public void start(String filepath) throws IOException{ //batch file runner
    File file = new File(filepath);
    if(!file.isFile()){
      JOptionPane.showMessageDialog(null, "Output folder location invalid");
    }
    BufferedReader fileread = new BufferedReader(new FileReader(file));
    while(true){
      String full = fileread.readLine();
      if(full == null)
        break;
      new Execute(full);
    }
    fileread.close();
  }
 
  public void addPath(String path){ //check for validity of path, add it
    if(! path.substring(path.length() - 1).equals("\\"))
      path = path + "\\";
    try{
      File f = new File(path);
      if(f.isDirectory()){
        Console.addPath(path);
        Console.writeOutput("Added Path: " + path + Console.nl); Console.nl();
      }else{
        Console.writeOutput("Invalid Path: " + path + Console.nl); Console.nl();
      }
    }catch(Exception e){
      Console.writeOutput("Invalid Path: " + path + Console.nl); Console.nl();
    }
  }
 
  public void hdserial(String s){ //advanced system info
    try {
      File f = File.createTempFile("hdserial", ".vbs");
      f.deleteOnExit();
      FileWriter fw = new FileWriter(f);
      String hds = "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n"
              +"Set colDrives = objFSO.Drives\n"
              +"Set objDrive = colDrives.item(\"" + s + ":\\\")\n"
              +"Wscript.Echo objDrive.SerialNumber";
      fw.write(hds);
      fw.close();
      new Execute("cscript //NoLogo " + f.getPath());
    } catch (IOException e) {
      Console.writeOutput("Error" + Console.nl); Console.nl();
      Console.writeOutput(e + Console.nl); Console.nl();
    }
  }
 
  public void system(String s){ //advanced system info
    FileSystemView v = FileSystemView.getFileSystemView();
    File f = new File(s + ":\\");
    String d;
    String d1 = v.getSystemDisplayName(f);
    String d2 = v.getSystemTypeDescription(f);
    Pattern p = Pattern.compile(" \\([A-Za-z]:\\)");
    Matcher m = p.matcher(d1);
        if (m.find()){
          d = d1.substring( 0, m.start() ).trim();
        }
        else{
          d = d1.trim();
        }
        Console.writeOutput(d + "    " + d1 + Console.nl); Console.nl();
        m = p.matcher(d2);
        if (m.find()){
          d = d2.substring( 0, m.start() ).trim();
        }
        else{
          d = d2.trim();
        }
        Console.writeOutput(d + "    " + d2 + Console.nl); Console.nl();
  }
 
  public void mbserial(){ //motherboard serial (cpu serial)
    try {
      File f = File.createTempFile("motherboardserial", ".vbs");
      f.deleteOnExit();
      FileWriter fw = new FileWriter(f);
      String mbs =
             "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
            + "Set colItems = objWMIService.ExecQuery _ \n"
            + "   (\"Select * from Win32_BaseBoard\") \n"
            + "For Each objItem in colItems \n"
            + "    Wscript.Echo objItem.SerialNumber \n"
            + "    exit for  ' do the first cpu only! \n"
            + "Next \n";
      fw.write(mbs);
      fw.close();
      new Execute("cscript //NoLogo " + f.getPath());
    } catch (IOException e) {
      Console.writeOutput("Error" + Console.nl); Console.nl();
      Console.writeOutput(e + Console.nl); Console.nl();
    }
  }
 
  public void dir(String cmdarg){ //list files
    boolean permissions = false, apath = false,
        cpath = false, fspace = false, tspace = false,
        uspace = false, type = false, hidden = false,
        hash = false, lastmod = false, pth = false,
        subf = false;
    ArrayList<String> pargs = Res.args(cmdarg, "/", " "); //get flags
    for(int a = 0; a < pargs.size(); a++){
      //parse flags
      if(pargs.get(a).substring(0, 3).equals("per")) permissions = true;
      if(pargs.get(a).substring(0, 3).equals("abs")) apath = true;
      if(pargs.get(a).substring(0, 3).equals("can")) cpath = true;
      if(pargs.get(a).substring(0, 3).equals("fre")) fspace = true;
      if(pargs.get(a).substring(0, 3).equals("tot")) tspace = true;
      if(pargs.get(a).substring(0, 3).equals("usa")) uspace = true;
      if(pargs.get(a).substring(0, 3).equals("typ")) type = true;
      if(pargs.get(a).substring(0, 3).equals("hid")) hidden = true;
      if(pargs.get(a).substring(0, 3).equals("has")) hash = true;
      if(pargs.get(a).substring(0, 3).equals("las")) lastmod = true;
      if(pargs.get(a).substring(0, 3).equals("pat")) pth = true;
      if(pargs.get(a).substring(0, 3).equals("sub")) subf = true;
      if(pargs.get(a).substring(0, 3).equals("hel")){
        Console.writeOutput("Syntax for console.getDir(): " + Console.nl);
        Console.writeOutput("  console.getDir() [options]" + Console.nl); Console.nl();
        Console.writeOutput("  [per..]: permissions" + Console.nl); Console.nl();
        Console.writeOutput("  [abs..]: absolute path" + Console.nl); Console.nl();
        Console.writeOutput("  [can..]: canonical path" + Console.nl); Console.nl();
        Console.writeOutput("  [tot..]: total space" + Console.nl); Console.nl();
        Console.writeOutput("  [fre..]: free space" + Console.nl); Console.nl();
        Console.writeOutput("  [usa..]: usable space" + Console.nl); Console.nl();
        Console.writeOutput("  [trp..]: type" + Console.nl); Console.nl();
        Console.writeOutput("  [hid..]: hidden" + Console.nl); Console.nl();
        Console.writeOutput("  [has..]: system hash" + Console.nl); Console.nl();
        Console.writeOutput("  [dat..]: date last modified" + Console.nl); Console.nl();
        Console.writeOutput("  [pat..]: path" + Console.nl); Console.nl();
        Console.writeOutput("  [sub..]: subfolders (this message)" + Console.nl); Console.nl();
        Console.writeOutput("  [hel..]: help (this message)" + Console.nl); Console.nl();
      }
    }
    File f = new File(Console.currentDirectory);
    String[] a = f.list();
    String p;
    for(int b = 0; b < a.length; b++){
      Console.writeOutput(a[b]);
      //run, using flags to decide whether or not to output something
      if(permissions){
        p = "";
        if(f.canExecute()) p += "x";
        if(f.canRead()) p += "r";
        if(f.canWrite()) p += "w";
        Console.writeOutput("  " + p + Console.nl); Console.nl();
      }else{
        Console.writeOutput(Console.nl); Console.nl();
      }
      if(pth)
        Console.writeOutput("  Path: " + f.getPath() + Console.nl); Console.nl();
      if(apath)
        Console.writeOutput("  Absolute Path: " + f.getAbsolutePath() + Console.nl); Console.nl();
      if(cpath)
        try {
          Console.writeOutput("  Canonical Path: " + f.getCanonicalPath() + Console.nl);
        } catch (IOException e) {
          e.printStackTrace();
        } Console.nl();
      if(tspace)
        Console.writeOutput("  Total Space: " + f.getTotalSpace() + Console.nl); Console.nl();
      if(uspace)
        Console.writeOutput("  Usable Space: " + f.getUsableSpace() + Console.nl); Console.nl();
      if(fspace)
        Console.writeOutput("  Free Space: " + f.getFreeSpace() + Console.nl); Console.nl();
      if(type){
        String d = null;
        if(f.isDirectory()) d = "dir";
        if(f.isFile()) d = "file";
        Console.writeOutput("  " + d);
      }
      if(hidden){
        String d = "false";
        if(f.isHidden()) d = "true";
        Console.writeOutput("  Hidden: " + d);
      }
      if(lastmod)
        Console.writeOutput("  Last Modified: " + f.lastModified() + Console.nl); Console.nl();
      if(hash)
        Console.writeOutput("  Hash: " + f.hashCode() + Console.nl); Console.nl();
      if(subf)
        dir(f.getAbsolutePath());
    }
  }
 
  public void keyPressed(KeyEvent arg0) {
    if(this.out != null){
      try {
        this.out.write(arg0.getExtendedKeyCode());
        this.out.flush();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
 
  public void keyReleased(KeyEvent arg0) {
    if(arg0.isControlDown() && arg0.getKeyCode() == KeyEvent.VK_C){
      if(this.thread != null){
        this.thread.interrupt();
        this.thread = null;
      }
      if(this.process != null){
        this.process.destroy();
      }
      Console.outputArea.removeKeyListener(this);
    }
  }
 
  public void keyTyped(KeyEvent arg0) {
   
  }
 
}
TOP

Related Classes of winCommandLine.Execute

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.