Tuesday 21 March 2017

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 created user is needed to provide the same to others.


As root, perform 
# useradd sampleuser

Change the password of the user
# passwd sampleuser
New Unix passwd: welcome1

Once a new user is added, it is automatically added to "/etc/passwd" file, if you want to change the default directory for the user , etc please edit that file as root
# cat /etc/hosts
sampleuser:x:54322:59969::/scratch/sampleuser:/bin/bash


Optionally, you can create a user with a specific home directory as 
# useradd -d /home/sampleuser    sampleuser

Add a group,
# groupadd samplegroup


Assign the user to the group
# usermod -g samplegroup   sampleuser

To list all groups,
# groups



Thursday 2 February 2017

Docker : Setting Proxy for Corporate Network

In some of the corporate networks, you will need to set the proxy settings for Docker to be able to communicate with external world. Usually the proxy is of the format 
'http://<username>:<password>@<hostname>:<port>'

For some linux versions on which Docker is installed, the setting can be made in 

mkdir -p /etc/systemd/system/docker.service.d

Create a file called /etc/systemd/system/docker.service.d/http-proxy.conf that adds the HTTP_PROXY environment variable:

[Service]
Environment="HTTP_PROXY=http://proxy.example.com:80/"


If you have internal Docker registries that you need to contact without proxying you can specify them via the NO_PROXY environment variable:
Environment="HTTP_PROXY=http://proxy.example.com:80/" "NO_PROXY=localhost,127.0.0.1,docker-registry.somecorporation.com"

$ sudo systemctl daemon-reload
$ systemctl show --property=Environment docker
Environment=HTTP_PROXY=http://proxy.example.com:80/
$ sudo systemctl restart docker

 


NOTE: For some version of Linux (say Oracle), you will need to set the proxy settings in 
$ cat /etc/sysconfig/docker
# /etc/sysconfig/docker
#
# Other arguments to pass to the docker daemon process
# These will be parsed by the sysv initscript and appended
# to the arguments list passed to docker daemon

other_args=""
export HTTP_PROXY="http://myproxy:80"
export HTTPS_PROXY="http://
myproxy:80"
HTTP_PROXY="http://
myproxy:80"
HTTPS_PROXY="http://
myproxy:80"

Restart the docker service,
# /etc/init.d/docker restart
Stopping docker:                                           [  OK  ]
Starting docker:        .                                  [  OK  ]

 

Wednesday 1 February 2017

Yum with Python 3 : except KeyboardInterrupt, e: SyntaxError: invalid syntax

If your machine has Python 3 installed (or upgraded to Python3), then running yum will fail with below error 

[sbetha@host:pwd]$ yum
  File "/usr/bin/yum", line 30
    except KeyboardInterrupt, e:
                            ^
SyntaxError: invalid syntax

 

This is because, yum doesnt support Python 3 at the moment.
Check which all versions of Python are installed on your machine
$ ls -lrt  /usr/bin/python*
-rwxr-xr-x. 1 root root 1418 Jan 22  2014 /usr/bin/python2.6-config
-rwxr-xr-x  2 root root 9032 Jan 22  2014 /usr/bin/python266
-rwxr-xr-x  2 root root 9032 Jan 22  2014 /usr/bin/python2.6
lrwxrwxrwx. 1 root root    6 Apr 22  2015 /usr/bin/python2 -> python
lrwxrwxrwx. 1 root root   16 Apr 22  2015 /usr/bin/python-config -> python2.6-config
lrwxrwxrwx  1 root root   24 Aug 26 00:18 /usr/bin/python2.7 -> /root/py27/bin/python2.7
lrwxrwxrwx  1 root root   40 Jan 31 22:59 /usr/bin/python -> /scratch/sbetha/python_3.4.6/bin/python3
 

Edit /usr/bin/yum to include on line1 as 
$ cat /usr/bin/yum
#!/usr/bin/python2.6

 
Now yum will work as normal since it uses Python 2.6
$ yum --version
3.2.29
  Installed: rpm-4.8.0-37.el6.x86_64 at 2015-04-22 15:54
  Built    : None at 2013-10-14 13:39
  Committed: Panu Matilainen <pmatilai@redhat.com> at 2013-09-12

  Installed: yum-3.2.29-60.0.1.el6.noarch at 2015-04-22 15:54
  Built    : None at 2014-08-25 14:22
  Committed: Jacob Wang <jacob.wang@oracle.com> at 2014-08-21

  Installed: yum-plugin-aliases-1.1.30-30.0.1.el6.noarch at 2015-04-22 16:11
  Built    : None at 2014-10-15 23:40
  Committed: Curt Carter <curt.carter@oracle.com> at 2014-10-14

  Installed: yum-plugin-fastestmirror-1.1.30-30.0.1.el6.noarch at 2015-04-22 18:24
  Built    : None at 2014-10-15 23:40
  Committed: Curt Carter <curt.carter@oracle.com> at 2014-10-14

 

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

Friday 14 December 2012

JDev Startup Issue



Many times, we may encounter JDev doesnt startup in our linux environment after installation.
The JDev studio when started may throw the below exception as,


oracle.ide.marshal.xml.Object2DomException: Error parsing XML --
/home/user/.jdeveloper/system11.1.1.7.40.64.11/o.jdeveloper/applications.xml
at
oracle.ide.marshal.xml.Object2Dom.newO2DException(Object2Dom.java:1229)
at
oracle.ide.marshal.xml.Object2Dom.getDocument(Object2Dom.java:1189)
at
oracle.ide.marshal.xml.Object2Dom.getDocument(Object2Dom.java:1134)
at oracle.ide.marshal.xml.Object2Dom.open(Object2Dom.java:544)
at oracle.ide.model.DataContainer.loadImpl(DataContainer.java:552)
at oracle.ide.model.Node.load(Node.java:2220)
at oracle.ide.model.Node.open(Node.java:959)
at oracle.ide.model.Node.open(Node.java:922)
Caused by: oracle.xml.parser.v2.XMLParseException: Start of root element
expected.
at oracle.xml.parser.v2.XMLError.flushErrors1(XMLError.java:323)


Its because of an existence of a system directory inside ' /home/user/.jdeveloper' i.e
' /home/user/.jdeveloper/system11.1.1.7.40.64.11'


Resolution: Remove the system directory in /home/user/.jdeveloper and Start the JDev Studio.


Note: the directory ".jdeveloper"is a hidden directory, do
la -latr /home/user
to view the hidden directory

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...