Tuesday, June 30, 2015

Tomcat 7 Additional features

Here are the some of the additional features of Tomcat 7 with previous versions

1) Embeddeding tomcat has become more easier than 6. This helps in integration tests

2) Tomcat cache control - Tomcat 7 provides you a ExpiresFilter that will determine the caching behavior of the clients. This filter controls the setting of the Expires HTTP header and the max-age directive of the Cache-Control HTTP header in server responses.

3) Tomcat 7 has the Servlet 3 specs. This allows the programmatic configuration includeing for elements in web.xml

4) error-on-undeclared-namespace - The default behavior when a tag with unknown namespace is used in a JSP page (regular syntax) is to silently ignore it. If this is set to true then an error must be raised during the translation time.

5) MemoryLeak protection -  It’s implemented as a listener which tries to detect and fix the possible memory leaks whenever it can

6) Tomcat 7 provides new aliases that allow storing static content outside the WAR File.

7) A new security feature for Apache Tomcat 7 is Session Fixation Protection. Essentially, when a user authenticates their session, Tomcat will change the session ID. It does not destroy the previous session , rather it renames it so it is no longer found by that ID. 

8) One of the new features with Tomcat 7 is a replacement to the commons-dbcp connection pool. While the commons-dbcp connection pool works fine for small or low traffic applications, it is known to have problems in highly concurrent environments .It is a completely new connection pool which has been written from the ground up, with a focus on highly concurrent environments and performance.

9) The Apache JServ Protocol (AJP) , is a binary protocol that can proxy inbound requests from a web server. Typically used in load balanced web applications where the web server has to pass requests to multiple application servers. New I/O, usually shortened to NIO, is a set of Java APIs that allow for more scalable I/O operations. Among other things, NIO provides support for non-blocking of data connections which ensures a response from the application server. Without NIO, admins must configure their web servers and application servers to match the number of threads between the web server and application server.

10) Adding of Crawler Session Manager Valve

11) Parallel deployment is supported

14) Use a LockOutRealm. Now standard by default in Tomcat 7, this realm simply protects your application from brute force attacks by locking out the offending account after a number of unsuccessful attempts.

14) Access log enabled by default

15) Instead of using a path of "/foo" like Tomcat 6 did, Tomcat 7 will add a trailing slash to the cookie path, or "/foo/".  This can be disabled, it turns out, by setting the sessionCookiePathUsesTrailingSlash flag to "false" on the <Context> element –

16) Jarscanner element was added which will scan all the jars in the web application lib location. This can be disabled by adding scanpath=false in context.xml

17) useHttpOnly set to false in 6 and true in 7

18)  Tomcat 7 has File upload support will enable Tomcat users to use file upload functionality within their web applications with the need for additional libraries

19) Tomcat 7 manager application has a ‘find Leak’ Button which enables a Full GC and also finds the leaks.

20) Deploying from Command line is changed by adding a “text” like
http://{host}:{port}/manager/text/{command}?{parameters}


Hope this Helps, More to come.
Read More

Linux- Physical Cable Communication

Many cases we will try using google.com in order to find out about our network connections. Linux provides us various ways in order to check whether there exists a physical cable connection. In this article we will see how we can find out this

Check for the available networks,
[root@localhost work]# cat /sys/class/net/
enp2s0/ lo/     virbr0/

Check whether Physical connection is available,
[root@localhost work]# cat /sys/class/net/enp2s0/carrier
1

[root@localhost work]# cat /sys/class/net/lo/carrier
1
[root@localhost work]# cat /sys/class/net/virbr0/carrier
0

“1” indicates physical connection availability and “0” none.

We can also use the below commands to check the same
[root@localhost work]# cat /sys/class/net/enp2s0/operstate
up

[root@localhost work]# cat /sys/class/net/virbr0/operstate
down


Hope this tip helps,
Read More

Clone – Permissions in Linux

Security is one of the important features of linux. Linux allows us to clone permissions from one file to other. Lets see how we can clone permissions from one file to other

[root@localhost work]# touch hai1
[root@localhost work]# chmod -R 600 hai1 

[root@localhost work]# stat hai1
  File: ‘hai1’
  Size: 0             Blocks: 0          IO Block: 4096   regular empty file
Device: 807h/2055d    Inode: 432         Links: 1
Access: (0600/-rw-------)  Uid: (    0/    root)   Gid: (    0/    root)
Context: unconfined_u:object_r:etc_runtime_t:s0
Access: 2015-06-29 16:37:24.768551308 +0530
Modify: 2015-06-29 16:37:24.768551308 +0530
Change: 2015-06-29 16:37:28.648463096 +0530

[root@localhost work]# touch hai2
[root@localhost work]# chmod -R 755 hai2

[root@localhost work]# stat hai2
  File: ‘hai2’
  Size: 0             Blocks: 0          IO Block: 4096   regular empty file
Device: 807h/2055d    Inode: 433         Links: 1
Access: (0755/-rwxr-xr-x)  Uid: (    0/    root)   Gid: (    0/    root)
Context: unconfined_u:object_r:etc_runtime_t:s0
Access: 2015-06-29 16:37:37.904252603 +0530
Modify: 2015-06-29 16:37:37.904252603 +0530
Change: 2015-06-29 16:37:43.383127957 +0530
 Birth: -

[root@localhost work]# chmod --reference=hai1 hai2

[root@localhost work]# stat hai2
  File: ‘hai2’
  Size: 0             Blocks: 0          IO Block: 4096   regular empty file
Device: 807h/2055d    Inode: 433         Links: 1
Access: (0600/-rw-------)  Uid: (    0/    root)   Gid: (    0/    root)
Context: unconfined_u:object_r:etc_runtime_t:s0
Access: 2015-06-29 16:37:37.904252603 +0530
Modify: 2015-06-29 16:37:37.904252603 +0530
Change: 2015-06-29 16:38:46.278689779 +0530

Read More

Apache – SSL Configuration

SSL is a protocol for cryptographically securing transactions between a web browser and a web server. In most cases, only the server end is authenticated, which means that the client has a guarantee that the server is who it claims to be. However, once the connection is established, both ends are secure, as only the client and the server have access to the key material. This makes sense since for many transactions, the server doesn't care who the client is, as long as it stays the same client throughout the transaction. In this article we will see how we can configure Apache with SSL Configuration

1) Create the Server Key, CSR, and Certificate

[root@localhost work]# openssl req -new -key ca.key -out ca.csr
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:IN
State or Province Name (full name) []:AP
Locality Name (eg, city) [Default City]:HYD
Organization Name (eg, company) [Default Company Ltd]:NOVA
Organizational Unit Name (eg, section) []:IT
Common Name (eg, your name or your server's hostname) []:Common Name
Email Address []:common@gmail.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:jagadesh1982
An optional company name []:MOVA

Now we can see ca.csr, ca.key, domain.key created.

2) Create a Certificate

[root@localhost work]# openssl x509 -req -days 365 -in ca.csr -signkey ca.key -out ca.crt
Signature ok
subject=/C=IN/ST=AP/L=HYD/O=NOVA/OU=IT/CN=Common Name/emailAddress=common@gmail.com
Getting Private key

Now we can ca.crt being created.

3) copy the files
[root@localhost work]# cp ca.crt /etc/pki/tls/certs/
[root@localhost work]# cp ca.key /etc/pki/tls/private/ca.key
[root@localhost work]# cp ca.key /etc/pki/tls/private/ca.csr

4) Now make the changes to the Apache configuration file httpd.conf as

https://myproject.local:2443/
Listen 2443

LoadModule ssl_module modules/mod_ssl.so
<VirtualHost *:2443>
 
    SSLEngine on
    SSLCertificateFile /etc/pki/tls/certs/ca.crt
    SSLCertificateKeyFile /etc/pki/tls/private/ca.key
  
    DocumentRoot /var/www/virtual/www.sam1.com/html/
    ServerName myproject.local
    ErrorLog logs/dummy-www.sam1.com-error_log
    CustomLog logs/dummy-www.sam1.com-access_log common

    <Directory "/var/www/virtual/www.sam1.com/html/">
        Options None
        Options -Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require all granted
        Allow from all
    </Directory>

</VirtualHost>

The most important line below which tells Apache about the Key and certificate files.
    SSLEngine on
    SSLCertificateFile /etc/pki/tls/certs/ca.crt
    SSLCertificateKeyFile /etc/pki/tls/private/ca.key

The other important lines are
LoadModule ssl_module modules/mod_ssl.so

Make sure we load the module before doing any thing. Now restart the Apache server and access https://myproject.local:2443/ Which will show for a Confirm Certificate on the Browser. Accept certificate to connect to the server.

Hope this helps, More to come
Read More

Identify Tomcat version

While working with Tomcat server, there are needs where we need to check for the version of the Tomcat. We will see how many ways available for finding the version of the tomcat.

1)  [root@localhost bin]# ./catalina.sh version
Using CATALINA_BASE:   /work/tomcat
Using CATALINA_HOME:   /work/tomcat
Using CATALINA_TMPDIR: /work/tomcat/temp
Using JRE_HOME:        /root/jrockit/
Using CLASSPATH:       /work/tomcat/bin/bootstrap.jar:/work/tomcat/bin/tomcat-juli.jar
Server version: Apache Tomcat/7.0.62
Server built:   May 7 2015 17:14:55 UTC
Server number:  7.0.62.0
OS Name:        Linux
OS Version:     3.10.0-123.el7.x86_64
Architecture:   amd64
JVM Version:    1.6.0_45-b06
JVM Vendor:     Oracle Corporation

2) [root@localhost lib]# java -cp catalina.jar org.apache.catalina.util.ServerInfo
Server version: Apache Tomcat/7.0.62
Server built:   May 7 2015 17:14:55 UTC
Server number:  7.0.62.0
OS Name:        Linux
OS Version:     3.10.0-123.el7.x86_64
Architecture:   amd64
JVM Version:    1.7.0_51-mockbuild_2014_04_04_16_39-b00
JVM Vendor:     Oracle Corporation

3) [root@localhost bin]# ./version.sh
Using CATALINA_BASE:   /work/tomcat
Using CATALINA_HOME:   /work/tomcat
Using CATALINA_TMPDIR: /work/tomcat/temp
Using JRE_HOME:        /root/jrockit/
Using CLASSPATH:       /work/tomcat/bin/bootstrap.jar:/work/tomcat/bin/tomcat-juli.jar
Server version: Apache Tomcat/7.0.62
Server built:   May 7 2015 17:14:55 UTC
Server number:  7.0.62.0
OS Name:        Linux
OS Version:     3.10.0-123.el7.x86_64
Architecture:   amd64
JVM Version:    1.6.0_45-b06
JVM Vendor:     Oracle Corporation

Read More

Serving Static Content in Apache

Static content (not regularly Changed) is one of the important elements in a Web application. As a part of serving static content we use Apache server by placing it as a Front-end Server. Apache server performs better when serving static content when compared with other servers.

In this article we will see how we can configure Apache server for serving static content.

1) Create a directory called static that we use to place the static files we wish to serve

For example, the URL http://localhost/static/logo.png will send the image ./static/logo.png to the client.

2) Configure the Apache server configuration file httpd.conf with the below details

ServerName 172.16.202.95
ServerName localhost

Listen 8180

<VirtualHost *:8180>
    DocumentRoot /var/www/virtual/www.sam1.com/html/
    ServerName myproject.local
    ErrorLog logs/dummy-www.sam1.com-error_log
    CustomLog logs/dummy-www.sam1.com-access_log common

    Alias /static   /var/www/virtual/www.sam1.com/html/static/

    <Directory "/var/www/virtual/www.sam1.com/html/">
        Options None
        Options -Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require all granted  
     Allow from all
    </Directory>

</VirtualHost>

The main line that needs attention is
Alias /static   /var/www/virtual/www.sam1.com/html/static/

The alias directive element allows documents to be stored in the local file system other than under the DocumentRoot. URLs with a path beginning with URL-path will be mapped to local files beginning with the directory-path.

Access the URL using myproject.local:8180/static/<Static File>
Read More

Saturday, June 20, 2015

Python - Dictionary


As the name suggests a Dictionary contains a Key and a associated value to the key. The Item (Key: Value) are separated by commas and whole thing is enclosed in a Curly Braces. While other compound data types have only value as an element, a dictionary has a key: value pair.

Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

An empty dictionary without any items is written with just two curly braces, like this: {}.

A Dictionary can be created as,
dictionary = {'key': value, 'key': value, 'key': value}

>>> car = {'make': 'Toyota', 'door': 4, 'color': 'white'}
>>> car
{'color': 'white', 'door': 4, 'make': 'Toyota'}

>>> my_dict = {} # Empty Dictionary

Accessing – A element of a Dictionary can be accessed using the key available. It can be done as

>>> car['make']
'Toyota'

>>> car['door']
4

Updating - A Dictionary can be updated or extended as

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

dict['Age'] = 8; # update existing entry
dict['School'] = " School"; # Add new entry

Dictionary is mutable. We can add new items or change the value of existing items using assignment operator. If the key is already present, value gets updated, else a new key: value pair is added to the dictionary.

Deletion – Elements in the Dictionary or the entire Dict can be deleted using the del keyword as

del dict['Name']; # remove entry with key 'Name'
dict.clear();     # remove all entries in dict
Read More

Thursday, June 4, 2015

JBoss 7 – Change Port Number on Runtime

There may be cases some times to change the Port number when Server is running. This may be due to an external service trying to access a JBoss service running on a port which was is configured on different port. During this case it will help if we change the port number running the service to the one that the external service uses. This article tells you on how to change the port during runtime

C:\Users\mjagadish\EAP-6.4.0\bin>jboss-cli.bat
You are disconnected at the moment. Type 'connect' to connect to the server or '
help' for the list of supported commands.
 [disconnected /] connect localhost:10999

[standalone@localhost:10999 /] cd /socket-binding-group=standard-sockets/socket-binding=http

[standalone@localhost:10999 socket-binding=http] ls -l
ATTRIBUTE VALUE TYPE
bound true BOOLEAN
bound-address 127.0.0.1 STRING
bound-port 9080 INT
client-mappings undefined LIST
fixed-port false BOOLEAN
interface undefined STRING
multicast-address undefined STRING
multicast-port undefined INT
name http STRING
port 8080 INT

Gives us the details of the HTTP port and services that are running.

[standalone@localhost:10999 socket-binding=http] :write-attribute(name="port",value="8180")
{
"outcome" => "success",
"response-headers" => {
"operation-requires-reload" => true,
"process-state" => "reload-required"
}
}

We use the write attribute to change the Port number from 8080 to 8180.Once done use the list command to see the changed values

[standalone@localhost:10999 socket-binding=http] ls -l
ATTRIBUTE VALUE TYPE
bound true BOOLEAN
bound-address 127.0.0.1 STRING
bound-port 9080 INT
client-mappings undefined LIST
fixed-port false BOOLEAN
interface undefined STRING
multicast-address undefined STRING
multicast-port undefined INT
name http STRING
port 8180 INT

Now once the changes are done, they will not be reflected until we reload the configuration. This is done using the reload command as

[standalone@localhost:10999 socket-binding=http] cd /
[standalone@localhost:10999 /] reload


Now check the Port by accessing an application running on that.
Read More

JBoss 7 – Changing Port Number

As a system admin it is very important to identify the details of the running ports on a JBoss server. On some cases we need to change the port numbers since some other service may be running on that Port. This article tells you on how to change Port numbers in JBoss 7

Way -1
Change the port manually , the port details are handled on the configuration file ( for stand-alone the file is standalone.xml )

Go to $JBOSS_HOME/standalone/configuration/standalone.xml.
Open the file and search for <socket-binding-group>

The <socket-binding-group/> element contains all the details of the running process and the ports they run on. Change the port details here and restart the machine. It looks like this

<socket-binding-group name="standard-sockets" default-interface="public" port-offset="${jboss.socket.binding.port-offset:0}">
<socket-binding name="management-native" interface="management" port="${jboss.management.native.port:9999}"/>
<socket-binding name="management-http" interface="management" port="${jboss.management.http.port:9990}"/>
<socket-binding name="management-https" interface="management" port="${jboss.management.https.port:9443}"/>
<socket-binding name="ajp" port="8009"/>
<socket-binding name="http" port="8080"/>
<socket-binding name="https" port="8443"/>
<socket-binding name="remoting" port="4447"/>
<socket-binding name="txn-recovery-environment" port="4712"/>
<socket-binding name="txn-status-manager" port="4713"/>
<outbound-socket-binding name="mail-smtp">
<remote-destination host="localhost" port="25"/>
</outbound-socket-binding>
</socket-binding-group>

Way-2
Start the standalone server by passing the socket.binding parameter as
standalone.bat -Djboss.socket.binding.port-offset=1000

Way -3
Once the server is started , access the socket-binding URL using this link
and we can change the port details from here

Hope this helps , more to come J
Read More

JBoss 7 – admin password recovery

During the installation of the JBoss 7 in windows, we are asked to enter the username and password that can be used as admin account. In this article we will see how to recover the password for admin account,

1) Remove the admin account details from mgmt-user.properties file in the $JBOSS_HOME/standalone/configuration location

2) Once the details are removed run the add-user.bat file from the $JBOSS_HOME/bin location as

C:\Users\mjagadish\EAP-6.4.0\bin>add-user.bat
JAVA_HOME is not set. Unexpected results may occur.
Set JAVA_HOME to the directory of your local JDK to avoid this message.

What type of user do you wish to add?
a) Management User (mgmt-users.properties)
b) Application User (application-users.properties)
(a): a

Enter the details of the new user to add.
Realm (ManagementRealm) :
Username : admin
User 'admin' already exits, would you like to update the existing user password and roles
Is this correct yes/no? yes
Password requirements are listed below. To modify these restrictions edit the add-user.properties configuratio
n file.
- The password must not be one of the following restricted values {root, admin, administrator}
- The password must contain at least 8 characters, 1 alphabetic character(s), 1 digit(s), 1 non-alphanumeric
symbol(s)
- The password must be different from the username
Password :
Re-enter Password :
What groups do you want this user to belong to? (Please enter a comma separated list, or leave blank for none)
[ ]:
Updated user 'admin' to file 'C:\Users\mjagadish\EAP-6.4.0\standalone\configuration\mgmt-users.properties'
Updated user 'admin' to file 'C:\Users\mjagadish\EAP-6.4.0\domain\configuration\mgmt-users.properties'

Updated user 'admin' with groups to file 'C:\Users\mjagadish\EAP-.4.0\standalone\configuration\mgmt-groups.properties'

Updated user 'admin' with groups to file 'C:\Users\mjagadish\EAP-.4.0\domain\configuration\mgmt-groups.properties'
Is this new user going to be used for one AS process to connect to another AS process?
e.g. for a slave host controller connecting to the master or for a Remoting connection for server to server EJB calls. yes/no? yes
To represent the user add the following to the server-identities definition <secret value="amFnYWRlc2gxOTgyQA==" />
Press any key to continue . . .

Once this process is complete, you can login to the admin console using the new credentials.


NOTE - If you get JBAS015243: The user ‘admin’ already exists in at least one properties file. error, then you didn't complete steps 1.
Read More

JBoss 7 Version

Most times it is very important to know the version of the server we are running in order to install patches and perform other updated. This snippet tells you the ways of finding the version of JBoss that we are running

Way -1
Run the command
C:\Users\mjagadish\EAP-6.4.0\bin>standalone.bat --version
Calling "C:\Users\mjagadish\EAP-6.4.0\bin\standalone.conf.bat"
JAVA_HOME is not set. Unexpected results may occur.
Set JAVA_HOME to the directory of your local JDK to avoid this message.
===============================================================================

JBoss Bootstrap Environment
JBOSS_HOME: "C:\Users\mjagadish\EAP-6.4.0"
JAVA: "java"

JAVA_OPTS: "-XX:+UseCompressedOops -Dprogram.name=standalone.bat -Xms1G -Xmx1G -XX:MaxPermSize=256M -Djava.n
et.preferIPv4Stack=true -Djboss.modules.policy-permissions=true -Djboss.modules.system.pkgs=org.jboss.byteman"

=========================================================

10:03:24,185 INFO [org.jboss.modules] (main) JBoss Modules version 1.3.6.Final-redhat-1
JBoss EAP 6.4.0.GA (AS 7.5.0.Final-redhat-21)
Press any key to continue . . .

Way -2
Start the Stand-alone process and at the bottom we can see the version of the running Server

10:03:58,620 INFO [org.jboss.as] (Controller Boot Thread) JBAS015874: JBoss EAP 6.4.0.GA (AS 7.5.0.Final-redhat-21) started in 2318ms - Started 153 of 191 services (57 services are lazy, passive or on-demand)

Way -3
Once the server is started we can use the URL
to see the various HTTP management interface with all details including the release-version


Hope this helps, More articles coming J
Read More

Tuesday, June 2, 2015

Embedded Tomcat

We know how to install a Tomcat server, deploy applications to that and work with them. In this article we will see how we can use all of the tomcat features in a independent Java application by embedding tomcat into that.

Why do we need to embed the Tomcat?
During cases where we need to test out application, we need run the test cases where tomcat is installed. One more case where we need to include a servlet container run with in out stand-alone java application so that we can run the web application on only user local machine. During these cases with Tomcat 7 we don’t need a install a separate tomcat, we just need to embed them into our code and ship it as one integral piece of software.

Elements
In order to embed the tomcat server into our java application, we need to use some of the libraries that help in the integration.

Apache Tomcat 7 has a special version for embedding purpose. This can be downloaded from http://tomcat.apache.org/download-70.cgi. Once we un-pack that we will see multiple jars which help in the integration of the embed tomcat.

Ecj.jar - Eclipse JSP compiler, this will be used by the Jasper Engine to compile JSP files
Tomcat-embed-core.jar – Core Tomcat classes, this contain the main implementation of the tomcat server
Tomct-dbcp.jar – Apache DBCP integration classes, this is used for JDBC integration with in the embed tomcat instance
Tomcat-embed-jasper.jar – Tomcat JSP Engine
Tomcat-embed-logging-juli.jar – JULI logging library integration
Tomcat-embed-logging-log4j.jar – Log4j logging library integration

The main classes for embedding tomcat 7 with in your application are the tomcat-embed-core.jar file. This contains implementation of all the architectural concepts of Apache tomcat such as Server Engine, Service , Connector and Host. The main class that we use is the org.apache.cataline.startup.Tomcat which provides the embedded server wrapper. This is found in tomcat-embed-core.jar file.

In addition to these we need at least one logging integration library to enable logging of our embedded tomcat instance. And also a JSP compiler to server JSP classes for our stand-alone Tomcat. The Jasper engine can be found in the tomcat-embed-jasper.jar library. This jar file contains JSP API interfaces and classes as well, so there is no need to include jsp-api.jar library separately.

Along with this we need to have a JSP compiler for compiling the code. Tomcat 7 ships with
A Eclipse JSP engine “ecj” library. This can be usedt to compile JSP files (*.jsp) to standard Java binary compiled files (*.class) that can be executed by JVM. The other jar files will be used in integrating JDBC code with our embed tomcat instance. We will not be using this in our example.

Embed Components
When using Tomcat server, we do have a server.xml which defines the way the server will run. This file contains elements that we configure for the working of the server. When using embed tomcat instance, the file will not be available and it is the responsibility of the developer to assemble components.

The tomcat-embed-core.jar files contains the main classes that correspond to the tomcat architectural components and they are

Interface                                   Component     Description
Org.apache.catalina.Server            Server             Entire Tomcat Instance
Org.apache.catalina.Service           Service           Holder for Engine,accessed by Connector
Org.apache.catalina.Connector       Connector       Connections for Tomcat Instance
Org.apache.cataline.Engline            Engine            Servlet Engine
Org.apache.catalina.Host                Host               Host where application runs
Org.apache.catalina.Context           Context           application context to be accessed

Tomcat helps developers by providing a implementation of these interfaces that we can use directly into our application. This is done by using org.apache.catalina.core.StandardServer which is a standard implementation of the Server interface and also org.apache.catalina.core.StandardEngine which is a standard implementation of Tomcat’s servlet engine.

Most often you need to embed a single Tomcat instance, with a single Server, single Service, and single Engine to your Java application, and run one or more web applications in it. For that purpose, Tomcat’s embedded distribution comes with the convenient class org.apache.catalina.startup.Tomcat, which contains this minimal set up out of the box. All you have to do is instantiate this class, and start using embedded Tomcat server in your Java application.

Implementation
Now we will see how we can implement a sample java application with an embed Tomcat Instance.

package com.embedTomcat;

import javax.servlet.ServletException;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.core.AprLifecycleListener;
import org.apache.catalina.core.StandardServer;
import org.apache.catalina.startup.Tomcat;

 public class StandaloneEmbedTomcat {
   Tomcat tomcat;
     private void startTomcat() throws ServletException, LifecycleException {
        this.tomcat = new Tomcat();                                    
        this.tomcat.setPort(8080);                                     
        this.tomcat.setBaseDir(".");                                   

        String contextPath = "/DemoExample";
        String appBase = "C:/Users/xprk477/Desktop/AppsWork/New folder";
        this.tomcat.addWebapp(contextPath, appBase);       

        this.tomcat.start();                                           
       
        //http://localhost:8080/DemoExample
    }

  void stopTomcat() throws LifecycleException {
       this.tomcat.stop();                                            
   }

    public static void main(String args[]) {
      try {
          StandaloneEmbedTomcat tomcat=new StandaloneEmbedTomcat();
          tomcat.startTomcat();
          Thread.sleep(100000);
          tomcat.stopTomcat();
  } catch (Exception e){
          e.printStackTrace();
   }
 }
}

     
The code written is simple and self-explanatory. First, we instantiated the org.apache.catalina.startup.Tomcat class. As we said earlier this will take care of the components in Tomcat. Next we set the port, base directory, context path, and appbase.

Though the tomcat instance will be instantiated in memory, we don’t need to set the real base directory (CATALINA_HOME) but since we are using JSP we need a temp location to store compiled JSP’s and it’s set relative to the base directory configured. We set it to the project’s working directory (".").

Now that we have a configured an embedded Tomcat instance, let’s start the Tomcat instance, using Tomcat.start() method.

Now we have embedded Tomcat up and running and listening for a shutdown command. But it won’t shut down itself – that’s why we implemented stop()method, which simply invokes Tomcat.stop(), which in turn issues the shutdown command that our server expects (because of previous await()).

In our example we have used sleep() method to keep tomcat instance running for some time but in real world we don’t need to do that since we can call the Server.await() method on the Server instance configured for the embedded Tomcat we’re using. Calling await() on the server tells Tomcat to keep running, but listen to any shutdown command issued. That way, when the shutdown command is issued (by the same or another process or thread), the server will shut down gracefully. Here is the line of code to achieve this:
this.tomcat.getServer().await();

Demo
Once we start the java application we can see logs as,

Jun 1, 2015 11:39:24 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.6.0_25\bin;.;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Program Files\HP_Fortify\HP_Fortify_SCA_and_Apps_3.80\bin;c:\oracle\ora-10.02.00.04\bin;C:\software\Perl\site\bin;C:\software\Perl\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Teradata\Client\13.0\ODBC Driver for Teradata\Lib\;C:\Program Files (x86)\Teradata\Client\13.0\Shared ICU Libraries for Teradata\lib\;C:\Program Files (x86)\Java\jdk1.6.0_10\bin;C:\Program Files (x86)\TortoiseSVN\bin;c:\software\maven\2.0.11\bin
Jun 1, 2015 11:39:25 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Jun 1, 2015 11:39:25 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Tomcat
Jun 1, 2015 11:39:25 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.62
Jun 1, 2015 11:39:25 PM org.apache.catalina.startup.ContextConfig getDefaultWebXmlFragment
INFO: No global web.xml found
Jun 1, 2015 11:39:25 PM org.apache.catalina.startup.TldConfig execute
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Jun 1, 2015 11:39:25 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]

The last line tells the Tomcat Instance is started. Access the application using


More to Come, Happy learning J  
Read More