?
Solved

Programming in Java Shell

Posted on 2005-02-27
3
Medium Priority
?
259 Views
Last Modified: 2010-03-31
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
Comment
Question by:edeita2
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 6

Accepted Solution

by:
durgaprasad_j earned 750 total points
ID: 13417627
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
 
LVL 6

Expert Comment

by:durgaprasad_j
ID: 13417761
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
 
LVL 7

Assisted Solution

by:tomboshell
tomboshell earned 750 total points
ID: 13417911
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

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Suggested Courses
Course of the Month14 days, 10 hours left to enroll

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question