Pages

java coding-convention and cleancode

This document consolidates the best practices and recommendations of the Java developers community gained from the past ten years of language use.




Rule 1. a) Don't use the wildcard character in package import statement. Always use the qualified name of package with import statement.

Ex. import java.io.* // wrong
     import java.io.File; //Right
     
       b) Import statement should be alphabetically sorted, separated in groups with a blank line.
         .static import
         .java, javax , then org and com package
         .others imports

  Ex. import static java.lang.Math.min;

      import java.io.File
      import java.io.FileReader
      
      import javax.servlet.GenericServlet
     
      import org.springframework.context.ApplicationContext;

      import com.google.gwt.user.server.rpc.RemoteServiceServlet;
     
      import backtype.storm.tuple.Values;

Rule 2. One class per file. The Name of the file must be the same as the class name.

Rule 3. Avoid deep Nesting: Too many levels of nesting can make code harder to read and follow.

Rule 4.Class names should be nouns unless you have a good reason for it not to be a noun. First letter of the class name should be in capital letter.

      Ex class MTBolt{
         // code goes here
                      }

Rule 5. Name of the methods using verb-object pair, such as
            Ex. readTranslatedFile();

Rule 6. Methods or functions returning a boolean type should generally start with verb is, or alternatives that fits better in   some   situations like has/have, can or should, etc.
 Ex:
     isValid(); isOpen();

Rule 7. a) Variables should be named so that they make it clear what it contains.
Variable names should always be easy-to-read, be short yet meaningful, mixed case with a lower-case first letter English words.

        b)Use plural names for arrays/collections of objects.
        c) Constant (static final) variable names should be in all capital letters and separate words in the name with the underscore, i.e.,   PRIORITY_NORMAL,

Clean code rules

1. Keep code where it belongs.

2. Keep methods short. single responsibility for a single function. means function    should do one thing. don't use boolean arguments because    they cause confusion. Boolean (flag) arguments loudly declare that the function does more than one thing.

3. Avoid OS dependent behavior, e.g., Unix-centric constants "\n", "/", etc.

4. Make all fields private. provide public get and set method to read and write properties. it restricts the direct access to properties and field and using get and set you can validate your data.

5. Declare a local variable as close as possible to its first use.

6. Document all your methods even the private ones if they are complex.

7. Every class should inside a package

8. Private class variables should have underscore suffix.
underscore  nicely resolves the problem of finding reasonable variable names for setter and getter methods: 

ex.
void setName(String name)
  {
    name = name;
  }
 
9. The term compute can be used in methods where something is computed.
    valueSet.computeAverage();

10. Array specifiers must be attached to the type not the variable.
    ex int a[] = new int[10] //wrong
         int[] a = new int[10]//Right

References;

1.http://www.oracle.com/technetwork/java/index.html

2. Clean Code: A Handbook of Agile Software Craftsmanship:
Robert C. Martin

Running storm cluster in production mode


Running storm cluster in production mode-

Follow the given steps to run storm cluster in production mode-

a) Run zookepper on nimbus machine.
     To run zookeeper follow the given steps-

          $ cd /usr/share/zookeeper/bin
          $ sudo ./zkServer.sh start

If yo see the output something like this, it means your zooleeper is running.

         JMX enabled by default
         Using config: /etc/zookeeper/conf/zoo.cfg
         Starting zookeeper ... STARTED

you can also weather zookeooper is started or not-

           $ sudo ./zkServer.sh status

b) Start the nimbus daemon on master machine. To start the
     nimbus daemon type the following command on terminal-

      $ storm nimbus

This should start the  "nimbus" daemon on your master node.

c) Run "jps' command and check the output of jps, to check wheather nimbus
    daemon is started or not.

      $ jps nimbus

      5501 Jps
      5396 nimbus


d)  Start the supervisor daemon on worker machine. To start the supervisor
   daemon on worker machine type the following command on terminal-

     $ storm supervisor

e) Run "jps' command and check the output of jps, to check wheather nimbus
    daemon is started or not.

      $ jps nimbus

      5501 Jps
      5200supervisor
f) Run storm ui (a site you can access from the browser that gives diagnostics on the cluster and   topologies)

      $ storm ui
      Type the url in your web browser http://{nimbus host}:8080

Here is a screenshot of the Storm UI as of version 0.8.2

storm ui

Adding New supervisor(worker node) on existing storm cluster


 Follow the given steps to add supervisor(worker node) 

a) Install Java ( same version as your existing cluster)

Note: To install java on linux/ubuntu folllow the given link
http://www.techie-knowledge.co.in/2013/08/installing-java-on-linuxubuntu.html
b) Install storm(storm-0.8.2 , same version as your existing cluster)

 

 Install the following native library-


a) To install ZeroMQ type the following command
 
  • make sure that libtool, autoconf, automake, g++ is installed on your machine
  •  wget http://download.zeromq.org/zeromq-2.1.7.tar.gz
  • tar -xvzf zeromq-2.1.7.tar.gz
  •  cd zeromq-2.1.7
  • ./configure 
   NOTE: If you see this error mesage on your terminal
   configure: error: cannot link with -luuid, install uuid-dev, then install theuuid-dev
   by using the command
    sudo apt -get install uuid-dev  
  • make
  • sudo make install

b) To install JZMQ,

  • git clone https://github.com/nathanmarz/jzmq.git
  • cd jzmq
  • ./autogen.sh
  • ./configure
  • make
  • sudo make install

c) set the storm.yaml file.

#storm.yaml
 // name of the machine where you install zookeeper in my case this is nimbus

storm.zookeeper.servers:
       - "nimbus"
#     - "server2" // name of the machine which you make your nimbus or master
#          machine in my case this is also "nimbus"

nimbus.host: "nimbus"

supervisor.slots.ports:
# - 6700
#- 6701 java.library.path: "/usr/local/lib:/opt/local/lib:/usr/lib"

 d) Add /etc/hosts file.

set up storm cluster(twitter storm) in local mode

Setup Storm Cluster In Local Mode 

Introduction

Storm is a free and open source distributed realtime computation system. 

1. INSTALLING STORM CLUSTER IN LOCAL MODE:

In this tutorial, I will tell you how to set up storm cluster in local mode(single machine). To set up and execute topology in local mode, we are going to use Maven. There is another way to set up storm in local mode, but I preferd maven.

Local mode simulates a Storm cluster in process and is useful for developing and testing topologies. Running topologies in local mode is similar to running topologies on a cluster.

2. SOFTWARE ENVIRONMENT :

Here the software platform which We used-

  •    Operating System: Ubuntu 12.04
  •    Java: Oracle/SUN , version:1.7.0_25
  •    Maven: Maven2
  •    Storm-0.8.2


3. Prerequisits:

  • Install latest version of JAVA(1.7.0_25) 
  • Set PATH Environment variable for java.
  • Set JAVA_HOME
note: click on this link to know how to install java on Ubuntu/Linux

http://www.techie-knowledge.co.in/2013/08/installing-java-on-linuxubuntu.html

4. How to Install Maven:

TO install Maven on ubuntu check the given link-


5. Check weather maven is installed or not using the command-

                  $ mvn -version

6. Install storm storm-0.8.2:

1. Download storm release (in my case storm-0.8.2) from the following link-

    https://github.com/nathanmarz/storm

2. Extract the downloaded storm release using the following command

$ tar -xvzf ~/Downloads/storm-0.8.2/ -C /usr/local

 

3. Set the path of bin directory of storm release to access the storm command from anywhere,
without typing the full path

Now your storm cluster is ready form local mode. Now can run a sample program to check it Where it is working or not.



7. Now  download the storm example from the given link-

    https://codeload.github.com/storm-book/examples-ch02-getting_started/legacy.zip/master
 
go to download zip button


8. Now go to the directory where you downloded the example and extract it, and change the directory to your project directory.

                $ cd ~/path-to-downloaded-directory/project-name


9. Now compile the project using maven. To compile project just type the following commnd on terminal prompt-

                $ mvn -e compile

After the "build successfull" go to next step.

10. Now type the following command on terminal to run the project to run

 mvn -e exec:java -Dexec.mainClass="TopologyMain" -Dexec.args="src/main/resources/words.txt"

Maven Installation and configuration in Ubuntu

Hello Friends,

In this tutorial I will show you how to install and configure MAVEN in Ubuntu.

Maven is a Java tool for Project Management to make build process easier. I used the maven to compile and package my storm topology to run on storm cluster both in production mode and local mode. 

Storm is a Apache framework for real time computation.



Prerequisites:

JAVA 1.5 or above. follow the following link to see how to install java and set environment for java.

http://ashuuni123.blogspot.com/2013/08/installing-java-on-linuxubuntu.html

Installation of Maven on ubuntu can be pretty straightforward 

$ sudo apt-get install maven2
Files should be installed in /usr/share/maven2

Verification

Type “mvn -version” to verify the installation.

$ mvn -version
Output should something like this-

Apache Maven 2.2.1 (rdebian-8)
Java version: 1.7.0_25
Java home: /usr/local/jdk1.7.0_25/jre
Default locale: en_IN, platform encoding: UTF-8
OS name: "linux" version: "3.2.0-52-generic-pae" arch: "i386" Family: "unix

Where the Maven installed?

The Apt-get installation will install all the required files in the following folder structure-
  1. /usr/bin/mvn
  2. /usr/share/maven2/
  3. /etc/maven2 

Pom File: 

POM is stands for project object model , is an xml file which contains information about the project which you want to build and configuration details used by MAVEN to build the project.
For example it define the directory structure for your source file and your class file. and also define the location where dependencies related to your project is stored.





Maven uses Convention over Configuration which means developers are not required to create build process themselves. Developers do not have to mention each and every configuration details.


Maven provides developers ways to manage following −
  • Builds
  • Documentation
  • Reporting
  • Dependencies
  • SCMs
  • Releases
  • Distribution
  • mailing list

SNAPSHOT is a special version that indicates a current development copy. Unlike regular versions, Maven checks for a new SNAPSHOT version in a remote repository for every build.


Transitive dependency means to avoid needing to discover and specify the libraries that your own dependencies require, and including them automatically.






The various dependency scope used in Maven are:

Compile: It is the default scope, and it indicates what dependency is available in the classpath of the project

Provided: It indicates that the dependency is provided by JDK or web server or container at runtime

Runtime: This tells that the dependency is not needed for compilation but is required during execution

Test: It says dependency is available only for the test compilation and execution phases

System: It indicates you have to provide the system path

Import: This indicates that the identified or specified POM should be replaced with the dependencies in that POM’s section





For more detail follow the given link-

Default structure create by maven for a project


 

Sample of pom.xml file 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org  /2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>esc</groupId>
    <artifactId>storm-experiment-2</artifactId>
    <version>0.0.1-SNAPSHOT</version>


    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <compilerVersion>1.7</compilerVersion>
                </configuration>
            </plugin>

            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    <archive>
                        <manifest>
                            <mainClass>com.path.to.main.Class</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <repositories>

        <!-- Repository where we can found the storm dependencies -->
        <repository>
            <id>clojars.org</id>
            <url>http://clojars.org/repo</url>
        </repository>

    </repositories>

    <dependencies>

        <!-- Storm Dependency -->
        <dependency>
            <groupId>storm</groupId>
            <artifactId>storm</artifactId>
            <version>0.8.2</version>
        </dependency>

    </dependencies>



</project>

 

* project – root element
* modelVersion – should be set to 4.0.0
* groupId – the id of the project’s group.
* artifactId – the id of the artifact (project) or project name
* version – the version of the artifact under the specified group 

 

Maven life cycle

Every build follows a specified life cycle. Maven comes with a default life cycle that includes the most common build phases like compiling, testing and packaging.
The following lists gives an overview of the important Maven life cycle phases.
  • validate - checks if the project is correct and all information is available
  • compile - compiles source code in binary artifacts
  • test - executes the tests
  • package - takes the compiled code and package it, for example into a JAR file.
  • integration-test - takes the packaged result and executes additional tests, which require the packaging
  • verify - performs checks if the package is valid
  • install - install the result of the package phase into the local Maven repository
  • deploy - deploys the package to a target, i.e. remote repository

 

Maven Repository

There are 2 types of repository in maven
  1. Local Repository 
  2. Remote Repository

Local Repository:  When you install and run maven first time, it will create a .m2 directory on your home directory, which contains a another directory name repository like- 

$HOME/.m2/repository
This the default location for the jar which maven check. If the particular jar is not in local repository then it will be downloaded from the remote repository which is set by maven when we installed the maven.
Remote Repository: This is the location where maven search for the dependency jar and download it in local repository if the jar is not in the local repository. We can set the location of remote repository.

  Using maven behind proxy

To use maven behind the proxy we have to define the proxy setting in setting.xml  file inside the proxy element.
The setting file is found in /etc/maven2/setting.xml
Add the following line under proxy element

<settings>
<proxies>
<proxy>
<active>true</active>
<protocol>http</protocol>
<host>192.168.1.100</host>
<port>3128</port>
<username>your-username</username>
<password>your-password</password>
</proxy>
</proxies>
</settings>

Submitting topology on storm cluster in production mode on linux(ubuntu)

Installing storm client

To submit Topology on production mode we need a storm client.
To install the storm-client on a machine follows the following steps -

1. Download storm release (in my case storm-0.8.2) from the following link-
    https://github.com/nathanmarz/storm

 Note: Skip steps 2,3 and 4, if you have already installed storm client-
           

2. Extract the downloaded storm release using the following command

         $ tar -xvzf ~/Downloads/storm-0.8.2/ -C /usr/local

3. Set the path of bin directory of storm relase to access the storm command from anywhere, without typing the full path.

4. Create  a local , storm configuration, where we will tell about our nimbus host. To do it follow these steps-

       $ mkdir -p ~/.storm
       $ cat > storm.yaml
       $ nimbus.host: "192.168.1.99" // ip of your nimbus host

Creation of jar file containig your code and all the dependencies of your code

1. Type following command for compiling your code using maven. First change your current directory to your project base directory.

        $ mvn -f  pom.xml compile

3. create a jar containing you code 

       $ mvn -e package

 // this command create jar file of your project under target directory of your project

Submitting jar file to your storm cluster

To submit the jar of your code(toplogy) in cluster type the following command -

$ storm jar  full-path-of-you-jar  name-of-your-main- class  arguments


Environment variable in unix(ubuntu)

An Environment variable is a dynamic "object" on a computer that stores a value, which in turn can be referenced by one or more software programs.

 The value of an environmental variable can the location of all executable files in the file system, the default editor that should be used, or the system local settings.

 An environment variable defines some aspect of a user's or a program's environment that can vary.

 Environment variables are dynamic because they can change. The values they store can be changed to match the current computer system's setup and design (environment). They can also differ between computer systems because each computer can have a different setup and design (environment).

List of some well known environment variables on Ubuntu

  • PATH Contains a colon-separated list of directories in which our system looks for executable files and commands. When we execute a command, the shell searches through each of these directories, one by one, until it finds a directory where the executable exists. A command whose path added to the PATH environment variable can be access directly without typing the full path. Here is the sample of PATH environment variable.
$ echo $PATH
                /usr/local/bin:/bin:/usr/bin:/sbin:/usr/sbi

  • HOME Contains the path to the home directory of the current user. 
  • PWD Contains the path to your current working directory. 
               $ echo $PWD
                 /home/techie/Desktop/storm-jar
  • TERM Contains the name of the running terminal, i.e xterm
  • EDITOR Contains the path to the lightweight program used for editing files, i.e. /usr/bin/nano, or an interactive switch (between gedit under X or nano in this example):
 export EDITOR="$(if [[ -n $DISPLAY ]]; then echo 'gedit'; else echo 'nano'; fi)"
  • VISUAL Contains the path to full-fledged editor that is used for more demanding tasks, such as editing mail; e.g., vi, vim, emacs, etc.
  • MAIL Contains the location of incoming email. The traditional setting is /var/spool/mail/$LOGNAME.
  • ftp_proxy Contains FTP  proxy server,
  • http_proxy Contains HTTP proxy server, 
  • HISTFILE This environment variable contains the location and name of the file in which command typed in terminal prompt saved.
  • HISTFILESIZE Maximun no of line contain in history file
  • HOSTNAME Contains system's host name
  • USER Contains login user name
  • OSTYPE : Contains description about OS.
  • LD_LIBRARY_PATH Contains colon separated list of directory where libraries should be searched for.
  • LOGNAME : contains login name

NOTE: Use printenv command to see the current environment variable and those value

echo $ printev
SSH_AGENT_PID=1702
GPG_AGENT_INFO=/tmp/keyring-nnUEcy/gpg:0:1
TERM=xterm
SHELL=/bin/bash
XDG_SESSION_COOKIE=a84bfeb2ec960f26863997bc0000000d-1379048055.358900-1791728848
WINDOWID=54525958

Find Ip Adreess of a WebSite


Hello Friends,

In this Post I will tell you about How to know the IP address of a website. As we know that Every Machine on a network (internet) has unique IP address to identify the machine on network. Ip address stands for internet protocol. As every website hosted on a server so we can also know that IP address of a website.

To know the IP address of a website on Ubuntu machine type the following command on terminal prompt:

$ ping www.facebook.com



 This sends a signal out to URL, Which then bounce back with website information.

This command is similar on Windows.

To know the IP address of a website on windows just open the command prompt and type the command
 ping www.facebook.com


Use Web Browser As Text Editor





Hello Friends,

In this post I will describe about How to use Web Browser as a text editor. This trick works on any modern browser like Chrome, Firefox.


Steps to do this-

1. copy the below text on your browser addressbar

data:text/html, <html contenteditable>

   2. Now Press Enter.
   3. Now you can type anything as would do on any other text editor like Notepad.
   4. To save your text file Press Ctrl + S and save it as anything.txt (.txt Is Must) - See more at: http://www.coolhackingtrick.com/2013/03/simple-trick-to-use-web-browsers-as.html#sthash.1Fmndm4z.dpuf
.
2. Press the Enter button.

3. Enter the text which you want to write.

4. To save this press Ctrl+S

5. Save the file with extenstion .txt (.txt is must)

   2. Now Press Enter.
   3. Now you can type anything as would do on any other text editor like Notepad.
   4. To save your text file Press Ctrl + S and save it as anything.txt (.txt Is Must) - See more at: http://www.coolhackingtrick.com/2013/03/simple-trick-to-use-web-browsers-as.html#sthash.1Fmndm4z.dp
 data:text/html, <html contenteditab
 data:text/html, <html contenteditable>


  

Install linux on usb drive

Hello Friends,

In this tutorial I will tell you about How to install Ubuntu on pen-drive using Windows.



Steps to install Linux onto your pen-drive


Step1-> Firstly download the .iso file of  linux distribution which you want to install.

Step2->  Download the "Universal USB Installer" on your system.

Step3-> Run the  exe of  Universal USB Installer.

Step4-> Select your linux distribution from the drop down list.


Step5-> GO to browse button and browse the .iso files from your hard disk.



Step6->Select your usb device onto which you want to install Linux.



Step7-> In the last step click on create button  it will open a black window(command prompt) and it will take some time to install the Linux OS onto your pen drive.

Setup eclipse ide for Java application


Setup Eclipse IDE for Java on Ubuntu

hello friends,

In this tutorial I will tell you about How to setup eclipse IDE for developing Java application.

prerequisites:

1. Install Java on your Ubuntu machine.

To install and configure  the Java  follow the given link -

After installing java, check for Java by using following command
$ java -version

Steps to install and configure eclipse for java on ubuntu/linux


1. Download the eclipse IDE for Java using the following link-
2. extract the downloaded tar ball using the following command to  /usr/local

$ sudo tar  -xvzf  eclipse-jee-kepler-R-linux-gtk.tar.gz  -C  /usr/local
3. To execute the eclipse from any directory type the following command on terminal prompt.

4. To run the eclipse type eclipse on terminal prompt and a Workspace Launcher dialog will appear. Select "Use this as the default and do not ask again" and click OK.

5. Eclipse will start up. Either explore the Overview, Tutorials, etc. or close the
    Welcome page by clicking on the white X to reveal the Java perspective, where you will do your programming.


Set up Eclipse to use the latest version of Java for compiling and running your Java programs

1. Set the default installed JRE to java 1.7.0_25  To do this follow the steps-
  • Run the eclipse using eclipse command on terminal.
  • Open the preference pane by going Window->Preferences-->Java-->InstalledJREs
  • Select the java 1.7.0_25 as the default
  • Click OK to save the setting.
2. Set the Java compiler to java1.7.0_25, To do this follow the steps-
  • open eclipse preference pane by going to Window-->Preferences-->Java-->Compiler
  • select the compilation level to 1.7
  • click OK to save the setting
Now the platform is ready to create Java application using Eclipse IDE. Now you can create Java project using eclipse.

Installing Java on Ubuntu

Hello friends,

In this post I will tell you about  How to install the Java on Ubuntu system. Many new user feel difficulty to install Java on Ubuntu system.In this post I will tell you some easy steps to install Java on Ubuntu. 




Note: The following command is tested on bash shell.

1. First step is to check the bit version of your Ubuntu operating system
    by typing the following command on your terminal -

            $ uname -a

If the output of commnad is like-

Linux pointer 3.2.0-51-generic-pae #77-Ubuntu SMP Wed Jul 24 20:40:32 UTC 2013 i686 i686 i386 GNU/Linux

Then you have 32bit version of Ubuntu.

And if the output of command something like-

Linux pointer 3.2.0-51-generic-pae #77-Ubuntu SMP Wed Jul 24 20:40:32 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux

Then you have 64-bit version of Ubuntu.

2. Download the tar ball of your Java version according to your bit version (32 bit vesion 0r 64 bit version of Java) of Ubuntu.

from the given URL -



3. Extract the Java using the command
$ tar -xvzf/Download/jdk1.7.0_25.tar.gz -C /usr/local
//change the location of ~/Download/jdk1.7.0_25.tar.gz from your downloaded location of Java.

4. Set the location of bin directory of Java to PATH environment variable. This step is necessary to make command like java, javac, javadoc executables from any directory without having to type the full path of command,otherwise you will have to write full path to access these command like -
$ /usr/local/jdk1.7.0_25/bin/java
To set the path type the following command on terminal-
sudo gedit /etc/environment
And add the the path of bin directory like
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/local/jdk1.7.0_25/bin"

5.Set JAVA_HOME variable in /etc/profile file.
$ sudo gedit /etc/profile
Add the following line at the and of the file,
               JAVA_HOME=/usr/local/jdk1.7.0_25


6. Source the file /etc/profile and /etc/environment to make change effective

      $  source /etc/profile 
     $ source /etc/environment  

7. Now type java and javac command from any directory to check weather Java is successfully install or not.

Installing the Tomcat 7 on linux/ubuntu 12.04


Hello friends,

In this post I will tell you about How to setup Tomcat7 in Ubuntu. The version of  Ubuntu which I used to setup tomcat7 is  12.04.



a) Installing tomcat7 server on ubuntu 12.04 using "apt-get"

 1. To install the Tomcat server on your machine, just type the following command in Terminal prompt -

sudo apt-get install tomcat7          

This will install a Tomcat server on your machine.

2. To install Tomcat documentation : The tomcat7-docs package contains Tomcat documentation, packaged as a webapp that you can access by default at http://yourserver:8080/docs. You can install it by entering the following command in the terminal prompt:

sudo apt-get install tomcat7-docs
3. To install Tomcat examples webapps : The tomcat7-examples package  webapps that can be used to test or demonstrate Servlets and JSP features, which you can access them by default at http://yourserver:8080/examples. You can install them by entering the following command in the terminal prompt:

sudo apt-get install tomcat7-examples
4.Tomcat administration webapps : The tomcat7-admin package contains two webapps that can be used to administer the Tomcat server using a web interface. You can install them by entering the following command in the terminal prompt:

sudo apt-get install tomcat7-admin

The first one is the manager webapp, which you can access by default at http://yourserver:8080/manager/html. It is primarily used to get server status and restart webapps.

Access to the manager application is protected by default: you need to define a user with the role "manager-gui" in /etc/tomcat7/tomcat-users.xml before you can access it.

The second one is the host-manager webapp, which you can access by default at http://yourserver:8080/host-manager/html. It can be used to create virtual hosts dynamically.

Access to the host-manager application is also protected by default: you need to define a user with the role "admin-gui" in /etc/tomcat7/tomcat-users.xml before you can access it.


b) Configuration settings of Tomcat server:

Configuration:

Tomcat configuration files can be found in /etc/tomcat7. Only a few common configuration tweaks will be described here, please see Tomcat 7.0 documentation for more.
Changing default ports

1. Port Configuration : By default Tomcat runs a HTTP connector on port 8080 and an AJP connector on port 8009. You might want to change those default ports to avoid conflict with another application on the system. This is done by changing the following lines in /etc/tomcat7/server.xml:


<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
...
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />

2. JAVA Configuration : By default Tomcat will run preferably with OpenJDK JVMs, But we can change this default JVM and can set it with SUN JAVA or Oracle JAVA. WE can force Tomcat to use a specific JVM by setting JAVA_HOME in /etc/default/tomcat7:

JAVA_HOME=/usr/lib/jvm/java-6-sun
 or
JAVA_HOME=/usr/local/jdk1.7.0_25/jre

3. Configuring users role : User names, passwords and roles (groups) can be defined centrally in a Servlet container. This is done in the /etc/tomcat7/tomcat-users.xml file:

<role rolename="admin"/>
<user username="tomcat" password="passwd" roles="admin"/>


After installing the tomcat7 using "apt-get" tomcat create following directory on Ubuntu:

1. /etc/tomcat7/  /contains configuration files., tomcat-users.xml ,server.xml catalina.policy */

2. /usr/share/tomcat7 /* Main Tomcat folder containing scripts and links to other directories* /

3. /usr/share/tomcat7-root/

4. /usr/share/doc/tomcat7

5. /usr/share/tomcat7-examples /* contains some built in exaple for testing            purpose */

6. /var/cache/tomcat7  /* contains catalina and catalina.policy. */

7. /var/lib/tomcat7/webapps /* where we deploy our web app. */

8. /var/log/tomcat7  /* contains log file related to tomcat server */

9. /usr/share/tomcat7/bin contains many binary like startup.sh, shutdown.sh ,version.sh

The tomcat comes with alredy deployed 5 app:
    The default home page: http://localhost:8080/
    Tomcat 7's local documentation: http://localhost:8080/docs/
    Examples of Servlets and JSP: http://localhost:8080/examples/
    The host-manager to handle virtual hosts: http://localhost:8080/host-manager/
    The manager to administer web applications: http://localhost:8080/manager/html



Deploy and handle web applications :

 The GUI way:

 The easiest way is to use the manager webapp http://localhost:8080/manager/html. Use the username/password you defined as manager in tomcat-users.xml. Once logged in you can see five already deployed web applications. Add yours through the "Deploy" area and then stop/start/undeploy it with the "Applications" area.


Directory Structure in linux system

Hello friends,

In this post I will tell you about  directory structure on Linux OS. Because user comes from Windows environment have some problem to understand what the different directory stands for in Linux.  since every standard directory in the Linux have special meaning and it store data according to its meaning. 

There is a list of different standard Linux directory with it's meaning.
  1. /- The Root directory
  2. /bin Directory
  3. /usr/bin
  4. /boot
  5. /dev
  6. /etc
  7. /lib
  8. /mnt
  9. /root
  10. /sbin
  11. /tmp
  12. /usr
  13. /usr/local 
Linux File System



/ – The Root Directory : Everything on your Linux system is located under the "/" directory, known as the root directory. This is where the Linux system begins. Every other file and directory on your system is under the root directory.

/bin – Essential Binaries : The /bin directory contains the essential user binaries (programs) that must be present when the system is mounted in single-user mode. The /bin directory contains the most important programs that the system needs to operate, such as the shells, kill,mv,rmdir,ls,grep  and other essential things.
/usr/bin : The /usr/bin contains applications for the system's users. like installed application java, eclipse,
  
/boot : The /boot directory contains the files needed to boot the system – for example, the GRUB boot loader’s files and your Linux kernels are stored here
This is the place where linux kernel loaded. when you try to list /boot partion in 
ubuntu you see vmlinuz, which is kernel image.

/dev – Device Files : Since in linux everything is file. so in linux device is also file and the /dev directory contains a number of special files that represent devices. These are not actual files as we know them, but they appear as files – for example, /dev/sda represents the first SATA drive in the system. If you wanted to partition it, you could start a partition editor and tell it to edit /dev/sda.

/etc – Configuration Files : The /etc directory contains configuration files. Note that the /etc/ directory contains system-wide configuration files.
for example
 /etc/passwd file : A file that contains various pieces of information for each user account. This is where the users are defined.

/etc/environment file:The /etc/environment file contains variables specifying the basic environment for all processes.  

/lib : The shared libraries for programs that are dynamically linked. The shared libraries are similar to DLL's on Winblows.The /lib directory contains libraries needed by the essential binaries in the /bin and /sbin folder. Libraries needed by the binaries in the /usr/bin folder are located in /usr/lib.

/mnt : The /mnt directory and its subdirectories are intended for use as the temporary mount points for mounting storage devices, such as CDROMs, floppy disks and USB (universal serial bus) key drives.

/root – Root Home Directory : The /root directory is the home directory of the root user or super user. Instead of being located at /home/root, it’s located at /root.

/sbin : The /sbin directory is similar to the /bin directory. It contains essential binaries that are generally intended to be run by the root user for system administration.

/tmp : This partition store temporary files in the /tmp directory. These files are generally deleted whenever the system is restarted.

/usr : The /usr directory contains applications and files used by users.

/usr/local : This is where we install apps and other files for use on the local machine

some commonly used regular expression every one should know

1. Regular Expression for matching Email
^([a-z0-9_-\.]+)@([a-z0-9-_\.]+)\.([a-z\.]{2,6})$

2. Regular Expression matching User Name

^[a-z0-9-_]{3,16}$

3. Regular Expression for matching URL

^(https?:\ /\ /)([\da-z\._/]+)\??[a-zA-z-0-9\._=&/]*$




4. Regular Expression matching IPv4

^([0-1][0-9]?[0-9]?|2[0-5]?[0-4]?|([3-9])[0-9]?)\.([0-1][0-9]?[0-9]?|2[0-5]?[0-5]?|([3-9])[0-9]?)\.([0-1][0-9]?[0-9]?|2[0-5]?[0-5]?|([3-9])[0-9]?)\.([0-1][0-9]?[0-9]?|2[0-5]?[0-5]?|([3-9])[0-9]?)$

                                     or

^([0-1][0-9]?[0-9]?|2[0-5]?[0-4]?|([3-9])[0-9]?)\.(([0-1][0-9]?[0-9]?|2[0-5]?[0-5]?|([3-9])[0-9]?)\.){2}([0-1][0-9]?[0-9]?|2[0-5]?[0-5]?|([3-9])[0-9]?)$

Matching HTML/XHTML/XML Tag using RegularExpression

Punctuation Character in ASCII Encoding

The punctuation characters in the ASCII table are:
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~.
Some character have special meaning in regular expression. These character are given below-
$()*+.?[\^{|  /*These 12 punctuation character known as "metacharacter " in regular expression */

special meaning of these character in regular expression are given in Tabular form-
Regular Expression Basic Syntax Reference
Characters
CharacterDescriptionExample
Any character except [\^$.|?*+()All characters except the listed special characters match a single instance of themselves. { and } are literal characters, unless they're part of a valid regular expression token (e.g. the {n} quantifier).a matches a
\ (backslash) followed by any of [\^$.|?*+(){}A backslash escapes special characters to suppress their special meaning.\+ matches +
\Q...\EMatches the characters between \Q and \E literally, suppressing the meaning of special characters.\Q+-*/\E matches +-*/
\xFF where FF are 2 hexadecimal digitsMatches the character with the specified ASCII/ANSI value, which depends on the code page used. Can be used in character classes.\xA9 matches © when using the Latin-1 code page.
\n, \r and \tMatch an LF character, CR character and a tab character respectively. Can be used in character classes.\r\n matches a DOS/Windows CRLF line break.
\a, \e, \f and \vMatch a bell character (\x07), escape character (\x1B), form feed (\x0C) and vertical tab (\x0B) respectively. Can be used in character classes.
\cA through \cZMatch an ASCII character Control+A through Control+Z, equivalent to \x01 through \x1A. Can be used in character classes.\cM\cJ matches a DOS/Windows CRLF line break.
Character Classes or Character Sets [abc]
CharacterDescriptionExample
[ (opening square bracket)Starts a character class. A character class matches a single character out of all the possibilities offered by the character class. Inside a character class, different rules apply. The rules in this section are only valid inside character classes. The rules outside this section are not valid in character classes, except for a few character escapes that are indicated with "can be used inside character classes".
Any character except ^-]\ add that character to the possible matches for the character class.All characters except the listed special characters.[abc] matches a, b or c
\ (backslash) followed by any of ^-]\A backslash escapes special characters to suppress their special meaning.[\^\]] matches ^ or ]
- (hyphen) except immediately after the opening [Specifies a range of characters. (Specifies a hyphen if placed immediately after the opening [)[a-zA-Z0-9] matches any letter or digit
^ (caret) immediately after the opening [Negates the character class, causing it to match a single character not listed in the character class. (Specifies a caret if placed anywhere except after the opening [)[^a-d] matches x (any character except a, b, c or d)
\d, \w and \sShorthand character classes matching digits, word characters (letters, digits, and underscores), and whitespace (spaces, tabs, and line breaks). Can be used inside and outside character classes.[\d\s] matches a character that is a digit or whitespace
\D, \W and \SNegated versions of the above. Should be used only outside character classes. (Can be used inside, but that is confusing.)\D matches a character that is not a digit
[\b]Inside a character class, \b is a backspace character.[\b\t] matches a backspace or tab character
Dot
CharacterDescriptionExample
. (dot)Matches any single character except line break characters \r and \n. Most regex flavors have an option to make the dot match line break characters too.. matches x or (almost) any other character
Anchors
CharacterDescriptionExample
^ (caret)Matches at the start of the string the regex pattern is applied to. Matches a position rather than a character. Most regex flavors have an option to make the caret match after line breaks (i.e. at the start of a line in a file) as well.^. matches a in abc\ndef. Also matches d in "multi-line" mode.
$ (dollar)Matches at the end of the string the regex pattern is applied to. Matches a position rather than a character. Most regex flavors have an option to make the dollar match before line breaks (i.e. at the end of a line in a file) as well. Also matches before the very last line break if the string ends with a line break..$ matches f in abc\ndef. Also matches c in "multi-line" mode.
\AMatches at the start of the string the regex pattern is applied to. Matches a position rather than a character. Never matches after line breaks.\A. matches a in abc
\ZMatches at the end of the string the regex pattern is applied to. Matches a position rather than a character. Never matches before line breaks, except for the very last line break if the string ends with a line break..\Z matches f in abc\ndef
\zMatches at the end of the string the regex pattern is applied to. Matches a position rather than a character. Never matches before line breaks..\z matches f in abc\ndef
Word Boundaries
CharacterDescriptionExample
\bMatches at the position between a word character (anything matched by \w) and a non-word character (anything matched by [^\w] or \W) as well as at the start and/or end of the string if the first and/or last characters in the string are word characters..\b matches c in abc
\BMatches at the position between two word characters (i.e the position between \w\w) as well as at the position between two non-word characters (i.e. \W\W).\B.\B matches b in abc
Alternation
CharacterDescriptionExample
| (pipe)Causes the regex engine to match either the part on the left side, or the part on the right side. Can be strung together into a series of options.abc|def|xyz matches abc, def or xyz
| (pipe)The pipe has the lowest precedence of all operators. Use grouping to alternate only part of the regular expression.abc(def|xyz) matches abcdef or abcxyz
Quantifiers
CharacterDescriptionExample
? (question mark)Makes the preceding item optional. Greedy, so the optional item is included in the match if possible.abc? matches ab or abc
??Makes the preceding item optional. Lazy, so the optional item is excluded in the match if possible. This construct is often excluded from documentation because of its limited use.abc?? matches ab or abc
* (star)Repeats the previous item zero or more times. Greedy, so as many items as possible will be matched before trying permutations with less matches of the preceding item, up to the point where the preceding item is not matched at all.".*" matches "def" "ghi" in abc "def" "ghi" jkl
*? (lazy star)Repeats the previous item zero or more times. Lazy, so the engine first attempts to skip the previous item, before trying permutations with ever increasing matches of the preceding item.".*?" matches "def" in abc "def" "ghi" jkl
+ (plus)Repeats the previous item once or more. Greedy, so as many items as possible will be matched before trying permutations with less matches of the preceding item, up to the point where the preceding item is matched only once.".+" matches "def" "ghi" in abc "def" "ghi" jkl
+? (lazy plus)Repeats the previous item once or more. Lazy, so the engine first matches the previous item only once, before trying permutations with ever increasing matches of the preceding item.".+?" matches "def" in abc "def" "ghi" jkl
{n} where n is an integer >= 1Repeats the previous item exactly n times.a{3} matches aaa
{n,m} where n >= 0 and m >= nRepeats the previous item between n and m times. Greedy, so repeating m times is tried before reducing the repetition to n times.a{2,4} matches aaaa, aaa or aa
{n,m}? where n >= 0 and m >= nRepeats the previous item between n and m times. Lazy, so repeating n times is tried before increasing the repetition to m times.a{2,4}? matches aa, aaa or aaaa
{n,} where n >= 0Repeats the previous item at least n times. Greedy, so as many items as possible will be matched before trying permutations with less matches of the preceding item, up to the point where the preceding item is matched only n times.a{2,} matches aaaaa in aaaaa
{n,}? where n >= 0Repeats the previous item n or more times. Lazy, so the engine first matches the previous item n times, before trying permutations with ever increasing matches of the preceding item.
Regular Expression related to html/xml/xhtml Document.
a) Quick and Dirty: This is the most comman , simple and widely used regular expression to match (x)html and xml tags
          <[^>]*>
b) Allows '>'  in attributes value :It’s advantage over the previous regex is that it correctly passes over > charactersthat appear within attribute values:
<(?:[^>"']|"[^"]*"|'[^']*')*>
It’s time for a few examples. The “Quick and dirty” regex matches each of the following
lines in full:
• <div>
• </div>
• <div>
• <div id="pandoras-box" />
• <!-- comment -->
• <!DOCTYPE html>
• << < w00t! >
• <>
But what about the  the lines which are given below:
<input type="button" value=">>">
OR
<input type="button" onclick="alert(2>1)">.
This type of  problem can solved by (b)Allow > in attributes value