Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 262
  • Last Modified:

Programming in Java Shell

I want to program a SIMPLE java shell for my own practice. So far Ive seen a few on the internet but everything seems way to complicated. I want it to be very basic and readable project so i can get some ideas for programming in java. i want to create a few commands.

1) one to list the directories
2) one to display the recently entered directories, and a cd command
4) a date command
3) of course a quit.

I want these to run as INTERNAL commands and not to spawn child processes. I also want to have a history list of commands in the cache that can be accessed in the csh style of !# of command. Also. cd# should go to that number directory in the cache, directories listed in reverse order, also to do a cd ~ will take you to yor home dir. Error handling will have to be there if commands are not matched to the ones I've created.

Here is come source code I found and played with to meet some of my requirements, it seems like a basic framework, but it is written to run all commands not recognized as internal as child processes. I want to know if I should use this as a base or start over and either way where I could get started.

<source code here>


import java.io.*;
import java.util.StringTokenizer;

class Shell {
    public static boolean runFlag = false;
   
    public static void main(String argv[]) {
        // main  variables
        BufferedReader in = null;
        String cmdLine;
        String [] progArgv;
        String verbose = System.getProperty("user.verbose");
        String path = System.getProperty("user.shellpath");
        //history number
        int hisnum=1;    
        // check argument
        if( argv.length > 1 ) {
            // error on the command line
            System.out.println("Error: wrong arg");
            System.exit(0);

        }

        // connect the input, ie open file input if batch mode or
        // connect to stadard input if interactive mode
        try {
            if( argv.length == 1 ) {
                // batch mode
                in = new BufferedReader(new FileReader(argv[0]));
            } else {
                // interactive mode
                in = new BufferedReader(new InputStreamReader(System.in));
            }
        } catch (IOException e) {
            System.err.println("Error: " + e);
            System.exit(-1);
        }

        // begin the shell
        try {
            while(true) {
                runFlag = false;
                // print prompt
                System.out.print("> " + hisnum +  System.getProperty("user.name") +"> " );
                num++;  
                System.out.flush();

                // get line input
                cmdLine = in.readLine();
                if(cmdLine == null) {

                    System.out.flush();
                    System.exit(0);
                }

                if( verbose != null ) {
                    System.out.println( cmdLine );
                }



                // split into tokens
                if(cmdLine != null) {

                    StringTokenizer cmdTokens = new StringTokenizer(cmdLine, " \t");
                    int tokenNum = cmdTokens.countTokens();
                    progArgv = new String[tokenNum];
                    for(int i = 0; i < tokenNum; i++) {
                        progArgv[i] = cmdTokens.nextToken();
                    }
                   
                    if(tokenNum == 0) {

                    }
                     // check if command is "exit"
                    else if(progArgv[0].equals("exit") && tokenNum == 1)
                        System.exit(0);
                   
                    else if(tokenNum != 0) {
                        // fork a new process
                        Runnable cmdRun = null;
                        Thread t = null;
                        String firstArgv = progArgv[0];
                        String pathPrefix;


                        if(path == null ||
                           progArgv[0].charAt(0) == '/' || progArgv[0].charAt(0) == '.') {
                            cmdRun = new CommandRun(progArgv);
                            t = new Thread(cmdRun);

                            t.start();
                            try {
                                t.join();
                            } catch(InterruptedException e) {

                            }
                        } else {


                            StringTokenizer pathToken = new StringTokenizer(path, ":");


                            while(pathToken.hasMoreTokens() == true) {


                                pathPrefix = pathToken.nextToken();
                                progArgv[0] =  pathPrefix + "/" + firstArgv;

                                cmdRun = new CommandRun(progArgv);
                                t = new Thread(cmdRun);

                                t.start();
                                try {
                                    t.join();
                                } catch(InterruptedException e) {
                                   
                                }
                                if(runFlag == true) {
                                    break;
                                }
                            }
                        }

                        if(runFlag == false) {
                            System.out.println(progArgv[0]+ ": Command not found.");    
                        }
                    }
                }
            }
        } catch (IOException e) {
            // in.readLine fail!
            System.out.println("Error: " + e);
            System.exit(-1);
        }

    }
}


Any and all input will be appreicated and I will use it to increase my knowledge of the java language.

Thanking you in advance,



0
edeita2
Asked:
edeita2
  • 2
2 Solutions
 
durgaprasad_jCommented:
hi,
i think you didn't declare a variable num // check this.

For executing a command -> you have to create a CommandRun class which looks like this.

class  CommandRun implements Runnable
{
           String args[]; //initialize here with proper size
           CommandRun(String args[])
           {
                        this.args=args;
           }
           public void start()
           {
            try
                    {            
                         Runtime rt = Runtime.getRuntime();
               
                         Process proc = rt.exec(args);
                         InputStream stderr = proc.getErrorStream();
                         InputStreamReader isr = new InputStreamReader(stderr);
                         BufferedReader br = new BufferedReader(isr);
                         String line = null;

                         while ( (line = br.readLine()) != null)
                              System.out.println(line);
                         
                         int exitVal = proc.waitFor();
                         System.out.println("Process exitValue: " + exitVal);
                    }
                    catch (Throwable t)
                    {
                         t.printStackTrace();
                    }
        }
}

Hope this helps
0
 
durgaprasad_jCommented:
hi,
In the above program .

public void start()
should be
public void run()

In the main program . You are setting runFlag=false. You never assigned true to that... Check this
0
 
tomboshellCommented:
Just to help your thinking while learning Java.  Careful with abusing the main method.  The main method is static to allow for an easy standardized entry point into java programs.  It is the way to enter into your program, set your program so that it can run (ie check command-line arguements, and to declare the classes to run).  If you start to find yourself writing a huge main class that does everything then your design is starting to slip.  Try to think along the lines that each of your class does about ONE specific thing, one may be controlling, one for reacting, one for errors, one for data storage, later maybe one for gui, one for input, one for output.  Your main then should then call the controlling constructor and hand controll over to that, here your Shell class.  That will start you thinking more object-oriented.  Later you will find that once you have designed how the classes will interact with one-another that you will be able to implement changes in a much more structured manner.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now