Monday, 30 January 2017

Java: Passing Command Line Options

You might want your users to pass command line options and make them human friendly, like the one below,

$java -jar CommandLineOptions -d -e 'myemail@email.com' -h 'hostname' -p 'port' -n 'Sudhakar'

An expanded usage help for the customer will be
$java -jar CommandLineOptions
usage: CommandLineOptions
Note: Pass the arguments correctly
 -d                 Customer has details
 -e,--email <arg>   provide email address
 -h,--host <arg>    provide host address
 -n,--name <arg>    provide name
 -p,--port <arg>    provide port number

Please get in touch with Sudhakar Betha for more options

To Achieve this, you will need to include apache commons=-cli to your project build path - https://mvnrepository.com/artifact/commons-cli/commons-cli/1.2

You might want to go through usage & api for reference prior to this

Below is the Main Class for this implementation,
https://github.com/sudhakarbetha/CoreJava/blob/master/CoreJava/src/first/CommandLineOptions.java


package first;
import org.apache.commons.cli.*;
/** * Created by Sudhakar on 30-01-2017. */public class CommandLineOptions {


    public void printName(String name) {
        System.out.println("Name=" + name);    }

    public void printEmail(String email) {
        System.out.println("Email=" + email);    }

    public void printHost(String host) {
        System.out.println("Host=" + host);    }

    public void printPort(int port) {
        System.out.println("Port=" + port);    }

    public static void main(String args[]) {

        CommandLineOptions object = new CommandLineOptions();
        Options options = new Options();
        Option d = new Option("d", false, "Customer has details");        Option email = new Option("e", "email", true, "provide email address");        Option host = new Option("h", "host", true, "provide host address");        Option port = new Option("p", "port", true, "provide port number");        Option name = new Option("n", "name", true, "provide name");
        options.addOption(d);        options.addOption(email);        options.addOption(host);        options.addOption(port);        options.addOption(name);
        CommandLineParser parser = new BasicParser();

        CommandLine commandLine;        try {
            commandLine = parser.parse(options, args);

            if (commandLine.hasOption("d")
                    && commandLine.hasOption("e")
                    && commandLine.hasOption("n")
                    && commandLine.hasOption("h")
                    && commandLine.hasOption("p")) {

                object.printEmail(commandLine.getOptionValue("e"));                object.printHost(commandLine.getOptionValue("h"));                object.printName(commandLine.getOptionValue("n"));                object.printPort(Integer.parseInt(commandLine.getOptionValue("p")));
            } else {
                HelpFormatter formatter = new HelpFormatter();                String header = "Note: Pass the arguments correctly";                String footer = "Please get in touch with Sudhakar Betha for more options";                formatter.printHelp("CommandLineOptions", header, options, footer);
            }
        } catch (ParseException e) {
            System.out.println("ParseException:" + e);        }


    }


}



Build your project jar with the dependencies (commons-cli)
$ java -jar CommandLineOptions.jar  -d -e myemail@gmail.com -h host-mypc -p 8080 -n 'Sudhakar Betha'

Email=myemail@gmail.com
Host=host-mypc
Name=Sudhakar Betha
Port=8080

Utility Scripts : Starting/Stopping Database or Tomcat

Usually we end up spending a lot of time trying to start/stop the instances and also in referring to the administration docs for the respective components. 
It is always advisable to create start/stop scripts that will make our work much easier. 

Below are the script I created for starting or stopping an instance

Save the files as db.sh and tomcat.sh and run then as $ sh <filename>.sh

Database- db.sh
https://github.com/sudhakarbetha/Utilities/blob/master/control/src/scripts/db.sh

 #This is a Utility for Database instance - start/stop

#Show Usage on Failure
function usage()
{
    echo "Usage:"
    echo "To start, run as $ sh db.sh start"
    echo "To stop, run as $ sh db.sh stop"
    exit 1
}

#Start DB
function start_db()
{
echo "Starting Database"
$ORACLE_HOME/bin/sqlplus 'sys/welcome1 as sysdba'  <<eof
startup
select name from v$services
alter pluggable database all open
quit
eof
}

#Stop DB
function stop_db()
{
echo "Stopping Database"
$ORACLE_HOME/bin/sqlplus 'sys/welcome1 as sysdba'  <<eof
shutdown immediate
quit
eof
}

#Main Program starts here
if [ $# == 0 ]
then
        usage
fi

ACTION=$1
export ORACLE_HOME=/scratch/sbetha/Database/product/12.1.0/dbhome_1
export ORACLE_SID=orcl
export LISTENER=$ORACLE_HOME/bin/lsnrctl

echo "ORACLE_HOME=$ORACLE_HOME"
echo "ORACLE_SID=$ORACLE_SID"

if [ "$ACTION" == "start" ]
 then
        start_db
   
        echo "Starting Listener - $LISTENER start"
        $LISTENER start
        echo "Getting Listener status - $LISTENER status"
        $LISTENER status


elif [ "$ACTION" == "stop" ]
 then
        stop_db
       
        echo "Getting Listener status - $LISTENER status"
        $LISTENER status
        echo "Stopping Listener - $LISTENER stop"
        $LISTENER stop
       
else
        echo "Unknown Operation $ACTION"
    usage
fi

echo "Done Action=$ACTION"




Tomcat - tomcat.sh 

https://github.com/sudhakarbetha/Utilities/blob/master/control/src/scripts/tomcat.sh


# Ths is a Utility to start/stop Tomcat

function usage()
{
    echo "Usage:"
    echo "To start, run as $ sh tomcat.sh start"
    echo "To stop, run as $ sh tomcat.sh stop"
    exit 1
}

if [ $# == 0 ]
then
    usage
fi

ACTION=$1
export JAVA_HOME="/scratch/sbetha/Shiphomes/Java/jdk7"
export CATALINA_HOME="/scratch/sbetha/Tomcat/tomcat_new"
export CATALINA_BASE="/scratch/sbetha/Tomcat/tomcat_new"
export JAVA_OPTIONS="-Xms1024M -Xmx4096M -XX:PermSize=1024M -XX:MaxPermSize=4096M"
if [ "$ACTION" == "start" ]
 then
    echo "$CATALINA_HOME/bin/startup.sh"
    $CATALINA_HOME/bin/startup.sh
elif [ "$ACTION" == "stop" ]
 then
    echo "$CATALINA_HOME/bin/shutdown.sh"
    $CATALINA_HOME/bin/shutdown.sh
else
    echo "Unknown Operation $ACTION"
    usage
fi
echo "Done Action=$ACTION"

HTTP GET vs POST Implementation

HTTP GET vs HTTP POST method
Well HTTP is a communication protocol between the client (browser) and the server(tomcat).
Before that, a few heads up on the HTTP GET & POST METHOD.
a) GET method sends the parameters in the form after "?" symbol and appends the parameters by "&"
b) GET method has a limitation of the number of characters
c) GET method is used to obtain static pages from the server

The html page sends the request to the server with the details of "HTTP Method, Content-Type & Content.
The server will respond with the details of "Response Code, Content-Type, Content"

So lets see the difference with a simple example.
1. Create a "Login.html" file as below and place it in "TOMCAT_HOME/webapps/MySample/" folder
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form method="get" action="Serv1">
<br>Name<input type="text" size="15" name="name">
<br>Passwd<input type="text" size="15" name="passwd"><br>
<input type="submit">
</form></body>
</html>
2. Create a Servlet as below 
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class Ch1Servlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
    doPost(request,response);
    }
    
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        
        PrintWriter out= response.getWriter();
        out.println("<html><body><h1>FirstServlet</h1></body></html>");
 
    }
}
3. Compile the servlet and place the class file in "TOMCAT_HOME/webapps/MySample/WEB-INF/classes" as
$javac -classpath TOMCAT_HOME/lib/servlet-api.jar -d TOMCAT_HOME/webapps/MySample/WEB-INF/classes/           Ch1Servlet.java
4. Create a web.xml file as below under "TOMCAT_HOME/webapps/MySample/WEB-INF" folder
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>FirstServlet</display-name>
 <servlet>
 <servlet-name>Chapter1 Servlet</servlet-name>
 <servlet-class>Ch1Servlet</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>Chapter1 Servlet</servlet-name>
 <url-pattern>/Serv1</url-pattern>
 </servlet-mapping>
</web-app>
5. Start the tomcat server and invoke the application as, http://localhost:8080/MySample/Login.html
6. Change the Login.html to have "POST" instead of "GET" and observe that this time the username & passwd are not sent

Linux : Create a new user for the machine

Creating a new user in linux is sometimes needed, when you want to share the user access with anyone. SSH to the machine over the newly cre...