{"id":3527,"date":"2014-09-04T07:31:01","date_gmt":"2014-09-03T23:31:01","guid":{"rendered":"http:\/\/rmohan.com\/?p=3527"},"modified":"2014-09-04T07:31:01","modified_gmt":"2014-09-03T23:31:01","slug":"tomcat-server","status":"publish","type":"post","link":"https:\/\/mohan.sg\/?p=3527","title":{"rendered":"TOMCAT SERVER"},"content":{"rendered":"<p>Reasons for Using a Web Server Apache<br \/>\nYou may be wondering why a separate Web server is needed when Tomcat already has an HTTP<br \/>\nConnector. Following are some reasons:<br \/>\n? Performance\u2014Tomcat is inherently slower than a Web server. Therefore, it is better for the<br \/>\nWeb server to serve up static content, while Tomcat handles the dynamic content (JSPs<br \/>\nand Servlets). Passing requests for static HTML pages, images, and style sheets through a<br \/>\nServlet container written in Java is not as efficient compared to a Web server.<br \/>\n? Security\u2014AWeb server such as Apache has been around for much longer than Tomcat,<br \/>\nand has far fewer security holes.<br \/>\n? Stability\u2014Apache is much more stable than Tomcat. In the event of a Tomcat crash, the entire<br \/>\nWeb site will not come down. Only the dynamic content served by Tomcat would be unavailable.<br \/>\n? Configurability\u2014Apache is also far more configurable than Tomcat. Using Apache as a front end<br \/>\nenables you to take advantage of its rich functionality.<br \/>\n? Legacy support\u2014Web sites often have legacy code in the form of CGI programs. They might<br \/>\nalso use scripting languages (such as Perl or Python) to implement specific functionality. Web<br \/>\nservers such as Apache have modules for Perl and Python, whereas Tomcat does not. Tomcat<br \/>\ndoes have limited support for CGI, however, using a special CGIServlet that mimics the CGI<br \/>\nfunctionality.<br \/>\n___________________________________________________________________________________________________<br \/>\nTOMCAT INSTALLATION:<br \/>\nDownload  apache-tomcat-7.0.28.tar.gz and  jdk-7u3-linux-i586.tar.gz<br \/>\n# Tar  \u2013xvzf apache-tomcat-7.0.28.tar.gz   \u2013C  \/opt<br \/>\n# Tar -xvzf jdk-7u3-linux-i586.tar.gz  \u2013C  \/opt<br \/>\n# vi .bash_profile<br \/>\nexport JAVA_HOME=\/opt\/jdk1.7.0_03<br \/>\nexport CATALINA_HOME=\/opt\/apache-tomcat-7.0.28<br \/>\n# source .bash_profile<br \/>\n# echo $JAVA_HOME; echo $CATALINA_HOME<br \/>\n\/opt\/jdk1.7.0_03<br \/>\n\/opt\/apache-tomcat-7.0.28<br \/>\n&#8212; > http:\/\/localhost:8080\/<br \/>\nAapche &#038; Tomcat with Mod_jk<br \/>\n# tar \u2013xvzf  tomcat-connectors-1.2.37-src.tar.gz  -C  \/opt\/<br \/>\n# cd \/opt\/tomcat-connectors-1.2.37-src\/native<br \/>\n# .\/configure   &#8211;with-apxs=\/opt\/apache2\/bin\/apxs<br \/>\n# make<br \/>\n# make install<br \/>\n# ls  \u2013l \/opt\/apache2\/modules   &#8212; > Check mod_jk.so module in apache<br \/>\n# vi \/opt\/apache2\/conf\/workers.properties<br \/>\nworker.list=node1<br \/>\nworker.node1.port=8009<br \/>\nworker.node1.host=localhost<br \/>\nworker.node1.type=ajp13<br \/>\nworker.node1.lbfactor=1<\/p>\n<p># vi \/opt\/apache2\/conf\/httpd.conf<br \/>\nLoadModule    jk_module     modules\/mod_jk.so<br \/>\n JKWorkersFile    conf\/workers.properties<br \/>\n<VirtualHost *:83><br \/>\n     ServerName test.sapient.com<br \/>\n     DocumentRoot \/opt\/apache2\/htdocs\/test<br \/>\n     JKLogFile logs\/mod_jk.log<br \/>\n     JKLogLevel error<br \/>\n     JKMount \/*  node1<br \/>\n<\/VirtualHost><\/p>\n<p> # \/opt\/apache-tomcat-7.0.28\/bin\/startup.sh<\/p>\n<p>UserHit \u00e0 http:\/\/test.sapient.com:83\/  \u00e0 We can see tomcat welcome page<\/p>\n<p><a href=\"http:\/\/rmohan.com\/wp-content\/uploads\/2014\/09\/Mod_jk.png\"><img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/rmohan.com\/wp-content\/uploads\/2014\/09\/Mod_jk.png\" alt=\"Mod_jk\" width=\"550\" height=\"393\" class=\"aligncenter size-full wp-image-3528\" srcset=\"https:\/\/mohan.sg\/wp-content\/uploads\/2014\/09\/Mod_jk.png 550w, https:\/\/mohan.sg\/wp-content\/uploads\/2014\/09\/Mod_jk-300x214.png 300w, https:\/\/mohan.sg\/wp-content\/uploads\/2014\/09\/Mod_jk-150x107.png 150w, https:\/\/mohan.sg\/wp-content\/uploads\/2014\/09\/Mod_jk-400x285.png 400w\" sizes=\"(max-width: 550px) 100vw, 550px\" \/><\/a><\/p>\n<p>Multiple instances of Tomcat<br \/>\n# cp  \u2013r  apache-tomcat-7.0.28   apache-tomcat-7.0.28 _1<br \/>\n# vi \/opt\/ apache-tomcat-7.0.28 _1\/conf\/server.xml<br \/>\napache-tomcat-7.0.28 (server.xml)<br \/>\napache-tomcat-7.0.28 _1 (server.xml)<br \/>\n<Server port=\"8005\" shutdown=\"SHUTDOWN\"><br \/>\n<Server port=\"8006\" shutdown=\"SHUTDOWN\"><br \/>\n<Connector port=\"8080\" protocol=\"HTTP\/1.1\"\n<Connector port=\"8081\" protocol=\"HTTP\/1.1\"\n<Connector port=\"8009\" protocol=\"AJP\/1.3\"\n<Connector port=\"8010\" protocol=\"AJP\/1.3\"\n\n# \/opt\/ apache-tomcat-7.0.28\/bin\/catalina.sh;  tail  \u2013f ..\/logs\/catalina.out\n#\/opt\/ apache-tomcat-7.0.28_1\/bin\/catalina.sh ;  tail  \u2013f ..\/logs\/catalina.out\n\n# ps \u2013ef | grep java\nroot     3535     1 44 14:37 pts\/2    00:00:01 \/opt\/jdk1.7.0_03\/bin\/java -         Djava.util.logging.config.file=\/opt\/apache-tomcat-7.0.28\/conf\/logging.properties\nroot     3509     1 41 14:37 pts\/2    00:00:01 \/opt\/jdk1.7.0_03\/bin\/java -Djava.util.logging.config.file=\/opt\/apache-tomcat-7.0.28_1\/conf\/logging.properties -\n\nTo check which tomcat is running on which port\n# netstat -antp|grep 8080\ntcp        0      0 :::8080                     :::*                        LISTEN      3535\/java\n# netstat -antp|grep 8081\ntcp        0      0 :::8081                     :::*                        LISTEN      3509\/java\n\n# vi \/opt\/apache2\/conf\/workers.properties\nworker.list=node1,node2, loadbalancer,status\nworker. node1.port=8009\nworker. node1.host=localhost\nworker. node1.type=ajp13\nworker.node1.lbfactor=100\nworker. node2.port=8010\nworker. node2.host=localhost\nworker. node2.type=ajp13\nworker.node2.lbfactor=100\nworker.loadbalancer.balance_workers=node1,node2    \/\/ Load-balancing behaviour\nworker.loadbalancer.sticky_session=1\nworker.status.type=status      \/\/ Status worker for managing load balancer\n\n# vi \/opt\/apache2\/conf\/httpd.conf\nListen 83\nListen 84\nJKWorkersFile    conf\/workers.properties\n<VirtualHost *:83><br \/>\n     ServerName test.sapient.com<br \/>\n     DocumentRoot \/opt\/apache2\/htdocs\/test<br \/>\n     JKLogFile logs\/mod_jk.log<br \/>\n     JKLogLevel error<br \/>\n     JKMount \/*  node1<br \/>\n<\/VirtualHost><br \/>\n<VirtualHost *:84><br \/>\n     ServerName test.sapient.com<br \/>\n     DocumentRoot \/opt\/apache2\/htdocs\/<br \/>\n     JKLogFile logs\/mod_jk.log<br \/>\n     JKLogLevel error<br \/>\n     JKMount \/*  node2<br \/>\n<\/VirtualHost><br \/>\n# \/opt\/apache2\/bin\/apachectl -k restart<br \/>\nhttp:\/\/test.sapient.com:83\/  \u00e0 connect to tomcat_1<br \/>\nhttp:\/\/test.sapient.com:84\/  \u00e0 connect to tomcat_2<\/p>\n<p>Workers Properties File<br \/>\nworker.list=tomcat<\/p>\n<p>worker.reference.socket_timeout=10000<br \/>\nworker.reference.socket_keepalive=true<br \/>\nworker.reference.connect_timeout=5000<br \/>\nworker.reference.connection_pool_size=30<br \/>\nworker.reference.cachesize=1<br \/>\nworker.template.prepost_timeout=10000<br \/>\nworker.template.connect_timeout=10000<br \/>\nworker.template.connection_pool_size=30<br \/>\nworker.template.socket_timeout=10<br \/>\nworker.template.retries=20<\/p>\n<p># Define App1<br \/>\n# modify the host as your host IP or DNS name.<\/p>\n<p>worker.tomcat.reference=worker.reference<br \/>\nworker.tomcat.port=8009          # This Value should be an AJP Port No<br \/>\nworker.tomcat.host=172.17.100.213<br \/>\nworker.tomcat.type=ajp13<br \/>\nworker.tomcat.lbfactor=1<br \/>\n#worker.tomcat.cachesize=10<br \/>\nworker.tomcat.connection_pool_timeout=20<\/p>\n<p>Connection Directive:<br \/>\nHost = localhost  \/\/name of the appserver hostname or ip<br \/>\nPort=8009<br \/>\nsocket_timeout=0  \/\/Socket timeout (in sec) used between JK and remote host. If remote host does not respond in this time, JK will generate an error, and retry again. If set to zero (default) JK will wait for an infinite amount of time on all socket operations.<br \/>\nsocket_connect_timeout = socket_timeout*1000 (in millisec)<br \/>\nsocket_keepalive=False<br \/>\n____________________________________________________________________________________________________<br \/>\nVirtual Hosting in Tomcat<br \/>\n[root@test tomcat_1]# cp -r webapps host1<br \/>\n[root@test tomcat_1]# cp -r webapps host2<br \/>\n# vi \/opt\/tomcat_1\/conf\/server.xml<br \/>\n<Engine name=\"Catalina\" defaultHost=\"localhost\"><br \/>\n  <Host name=\"localhost\"  appBase=\"webapps\"\/><br \/>\n  <Host name=\"www.host1.com\"  appBase=\"host1\"\n            unpackWARs=\"true\" autoDeploy=\"true\"><br \/>\n     <\/Host><br \/>\n   <Host name=\"www.host2.com\"  appBase=\"host2\"\n            unpackWARs=\"true\" autoDeploy=\"true\"><br \/>\n      <\/Host><br \/>\n <\/Engine><br \/>\n# vi \/opt\/tomcat_1\/host1\/ROOT\/host1.html<br \/>\n<html><body> This is virtual host1<\/body><\/html><br \/>\n# vi \/opt\/tomcat_1\/host2\/ROOT\/host2.html<br \/>\n<html><body> This is virtual host2<\/body><\/html><\/p>\n<p># vi \/etc\/hosts<br \/>\n192.168.10.102  www.host1.com www<br \/>\n192.168.10.102  www.host2.com www<\/p>\n<p>http:\/\/www.host1.com:8080\/host1.html<br \/>\nhttp:\/\/www.host1.com:8080\/host2.html<br \/>\n____________________________________________________________________________________________________<br \/>\nJNDI: The Java Naming and Directory Interface (JNDI) is an application programming interface (API) for accessing different kinds of naming like CORBA, Java RMI, and EJB; and directory services like LDAP,NIS+.<br \/>\nThe most common use case is to set up a database connection pool on a Java EE application server<br \/>\nDifference between ear,war,jar files<br \/>\nEAR is an EEnterprise Aapplication archive and may contain ejb JAR files, WAR files, and RAR (connector) files. They may also contain third-party libraries &#8211; but you have to know how to manipulate the Java extension facilities (e.g. MANIFEST.MF Class-Path directive) to make that work well.<\/p>\n<p>WAR is an Web Aapplication archive and contains JSPs, &#8220;normal&#8221; HTTP served files (HTML, images, etc.), servlets, tag libraries, and such.<br \/>\nJAR is the &#8220;normal&#8221; Java Aapplication archive, but in this context it usually contains EJBs instead of code libraries or runnable (e.g. from outside an application container) applications.<br \/>\nJAR : JAVA Archives and it allows aggregating many files into One.It usually hold java classes in lib.<br \/>\nWAR : Web Application Archives and it stores xml,Java Classes and JSP for Web Application.<br \/>\nEAR : Enterprise Archives it combines JAR and WAR files into combined Archive<\/p>\n<p>JDBC connection pooling (DBCP)<br \/>\n1. MySQL configuration<br \/>\nmysql> GRANT ALL PRIVILEGES ON *.* TO javauser@localhost IDENTIFIED BY &#8216;javadude&#8217; WITH GRANT OPTION;<br \/>\nmysql> create database javatest;<br \/>\nmysql> use javatest;<br \/>\nmysql> create table testdata (id int not null auto_increment primary key, foo varchar(25), bar int);<br \/>\nNote: the above user should be removed once testing is complete!<br \/>\nmysql> insert into testdata values(null, &#8216;hello&#8217;, 12345);<br \/>\nmysql> select * from testdata;<br \/>\n+&#8212;-+&#8212;&#8212;-+&#8212;&#8212;-+<br \/>\n| ID | FOO   | BAR   |<br \/>\n+&#8212;-+&#8212;&#8212;-+&#8212;&#8212;-+<br \/>\n|  1 | hello | 12345 |<br \/>\n+&#8212;-+&#8212;&#8212;-+&#8212;&#8212;-+<br \/>\nmysql><br \/>\n2. Context configuration : Configure the JNDI DataSource to Context.<br \/>\n    maxActive: Maximum number of database connections in pool.. Set to -1 for no limit.<br \/>\n    maxIdle: Maximum number of idle database connections to retain in pool. Set to -1 for no limit.<br \/>\n    maxWait: Maximum time to wait for a database connection to become available in ms, ex. 10 sec.     An Exception is thrown if this timeout is exceeded.  Set to -1 to wait indefinitely.<br \/>\n#vi  Server.xml<br \/>\n<Context><br \/>\n  <Resource name=\"jdbc\/TestDB\" auth=\"Container\" type=\"javax.sql.DataSource\"\n               maxActive=\"100\" maxIdle=\"30\" maxWait=\"10000\"\n               username=\"javauser\" password=\"javadude\" driverClassName=\"com.mysql.jdbc.Driver\"\n               url=\"jdbc:mysql:\/\/localhost:3306\/javatest\"\/><br \/>\n<\/Context><br \/>\n3. web.xml configuration<br \/>\nNow create a WEB-INF\/web.xml for this test application.<br \/>\n<web-app xmlns=http:\/\/java.sun.com\/xml\/ns\/j2ee\nxmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\"\n    xsi:schemaLocation=\"http:\/\/java.sun.com\/xml\/ns\/j2ee\nhttp:\/\/java.sun.com\/xml\/ns\/j2ee\/web-app_2_4.xsd\"\n    version=\"2.4\"><br \/>\n  <description>MySQL Test App<\/description><br \/>\n  <resource-ref><br \/>\n      <description>DB Connection<\/description><br \/>\n      <res-ref-name>jdbc\/TestDB<\/res-ref-name><br \/>\n      <res-type>javax.sql.DataSource<\/res-type><br \/>\n      <res-auth>Container<\/res-auth><br \/>\n  <\/resource-ref><br \/>\n<\/web-app><br \/>\n4. Now create a simple test.jsp page for use later.<br \/>\n<%@ taglib uri=\"http:\/\/java.sun.com\/jsp\/jstl\/sql\" prefix=\"sql\" %><br \/>\n<%@ taglib uri=\"http:\/\/java.sun.com\/jsp\/jstl\/core\" prefix=\"c\" %><br \/>\n<sql:query var=\"rs\" dataSource=\"jdbc\/TestDB\"><br \/>\nselect id, foo, bar from testdata<br \/>\n<\/sql:query><br \/>\n<html> <head> <title>DB Test<\/title> <\/head><br \/>\n  <body> <\/p>\n<h2>Results<\/h2>\n<p><c:forEach var=\"row\" items=\"${rs.rows}\"><br \/>\n    Foo ${row.foo}<br \/>\n    Bar ${row.bar}<br \/>\n<\/c:forEach><br \/>\n<\/body><\/html><br \/>\n____________________________________________________________________________________________________<br \/>\nTomcat follow symbolic links<br \/>\nallowLinking=&#8221;true&#8221;<br \/>\n# vi context.xml<br \/>\n<?xml version=\"1.0\" encoding=\"UTF-8\"?><br \/>\n<Context path=\"\/myapp\" allowLinking=\"true\"><br \/>\n<\/Context><\/p>\n<p>Allow or deny virtual hosting to accessible by users in tomcat<br \/>\nUse a valve to filter by IP or hostname to only allow a subset of machines to connect.<br \/>\n# vi Server.xml<br \/>\n<Valve className=\"org.apache.catalina.valves.RemoteAddrValve\" allow=\"192.168.1.*\"><\/Valve><\/p>\n<p>Log path setting in Tomcat<br \/>\n# vi server.xml<br \/>\n<Host name=\"localhost\"  appBase=\"webapps\" unpackWARs=\"true\" autoDeploy=\"true\"><br \/>\n        <Valve className=\"org.apache.catalina.valves.AccessLogValve\" directory=\"logs\"\n          prefix=\"localhost_access_log.\" suffix=\".txt\" pattern=\"%h %l %u %t &quot;%r&quot; %s %b\" \/><br \/>\n <\/Host><\/p>\n<p>Response time logging in Tomcat<br \/>\n<Valve className=\"org.apache.catalina.valves.AccessLogValve\"\n                 directory=\"logs\" prefix=\"timing.\" suffix=\".log\"\n                 pattern=\"%t %U %s %D\" resolveHosts=\"false\" \/><\/p>\n<p>Turn on Servlet Reloading<br \/>\n# vim $CATLINA_HOME\/conf\/server.xml<br \/>\nbelow  <Host name=\"localhost\" debug=\"0\" appBase=\"webapps\" \/><br \/>\n                <DefaultContext reloadable=\"true\"\/><\/p>\n<p>Implement custom error pages<br \/>\n# vi web.xml<br \/>\nerror-page><br \/>\n   <error-code>404<\/error-code><br \/>\n   <location>\/error\/404.html<\/location><br \/>\n<\/error-page><br \/>\nTo allow directory browsing via Apache Tomcat<br \/>\nchange the parameter &#8220;listings&#8221; in the file conf\/web.xml from false to true.<br \/>\n# vim $CATLINA_HOME\/conf\/web.xml<br \/>\nsearch by \/listings<br \/>\n<servlet><br \/>\n        <servlet-name>default<\/servlet-name><br \/>\n        <servlet-class>org.apache.catalina.servlets.DefaultServlet<\/servlet-class><br \/>\n        <init-param>\n            <param-name>listings<\/param-name>\n            <param-value>true<\/param-value>\n        <\/init-param><br \/>\n        <load-on-startup>1<\/load-on-startup><br \/>\n    <\/servlet><br \/>\nNote: To Secure directory listings &#8212; > listing value should be false<\/p>\n<p>Session Timeout Configuration<br \/>\n# vi web.xml<br \/>\n<session-config><br \/>\n<session-timeout>30<\/session-timeout><br \/>\n<\/session-config><br \/>\n____________________________________________________________________________________________________<br \/>\nTomcat Logging<br \/>\nUsing logging.properties  ( To debug more logs)<br \/>\n# vi logging.properties<br \/>\norg.apache.catalina.core.ContainerBase.[Catalina].level = INFO<br \/>\norg.apache.catalina.core.ContainerBase.[Catalina].handlers = java.util.logging.ConsoleHandler<\/p>\n<p>Using Log4j: Tomcat 6.0 uses Commons Logging throughout its internal code allowing the developer to choose a logging configuration. If we want to collect the detailed logging of tocat then we need to configure the external logging api like log4j<br \/>\nCreate a file called log4j.properties with the following content and save it into $CATALINA_BASE\/lib<br \/>\nlog4j.rootLogger=INFO, CATALINA   (\/\/ DEBUG)<br \/>\n# Define all the appenders<br \/>\nlog4j.appender.CATALINA=org.apache.log4j.DailyRollingFileAppender<br \/>\nlog4j.appender.CATALINA.File=${catalina.base}\/logs\/catalina.<br \/>\nlog4j.appender.CATALINA.Append=true<br \/>\nlog4j.appender.CATALINA.MaxFileSize=10MB<\/p>\n<p>log4j.appender.CATALINA.MaxBackupIndex=10<br \/>\nlog4j.appender.CATALINA.Encoding=UTF-8<br \/>\n# Roll-over the log once per day<br \/>\nlog4j.appender.CATALINA.DatePattern=&#8217;.&#8217;yyyy-MM-dd&#8217;.log&#8217;<br \/>\nlog4j.appender.CATALINA.layout = org.apache.log4j.PatternLayout<br \/>\nlog4j.appender.CATALINA.layout.ConversionPattern = %d [%t] %-5p %c- %m%n<\/p>\n<p># same for<br \/>\nlog4j.appender.LOCALHOST=org.apache.log4j.DailyRollingFileAppender<br \/>\n\u2026\u2026<br \/>\nlog4j.appender.MANAGER=org.apache.log4j.DailyRollingFileAppender<br \/>\n\u2026\u2026<br \/>\nlog4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender<br \/>\nlog4j.appender.CONSOLE.Encoding=UTF-8<br \/>\nlog4j.appender.CONSOLE.layout = org.apache.log4j.PatternLayout<br \/>\nlog4j.appender.CONSOLE.layout.ConversionPattern = %d [%t] %-5p %c- %m%n<\/p>\n<p># Configure which loggers log to which appenders<br \/>\nlog4j.logger.org.apache.catalina.core.ContainerBase.[Catalina].[localhost]=INFO, LOCALHOST<br \/>\nlog4j.logger.org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[\/manager]=\\<br \/>\n  INFO, MANAGER<br \/>\nlog4j.logger.org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[\/host-manager]=\\<br \/>\n  INFO, HOST-MANAGER<br \/>\nDownload Log4J (v1.2 or later).<br \/>\n3.       Download or build tomcat-juli.jar and tomcat-juli-adapters.jar that are available as an &#8220;extras&#8221; component for Tomcat. See Additional Components documentation for details.<br \/>\n4.       This tomcat-juli.jar differs from the default one. It contains the full Apache Commons Logging implementation and thus is able to discover the presense of log4j and configure itself.<br \/>\n5.       Put log4j.jar and tomcat-juli-adapters.jar from &#8220;extras&#8221; into $CATALINA_HOME\/lib.<br \/>\n6.       Replace $CATALINA_HOME\/bin\/tomcat-juli.jar with tomcat-juli.jar from &#8220;extras&#8221;.<br \/>\n7.       Create $CATALINA_BASE\/bin and $CATALINA_BASE\/lib directories if they do not exist.<br \/>\n8.       Put log4j.jar and tomcat-juli-adapters.jar from &#8220;extras&#8221; into $CATALINA_BASE\/lib<br \/>\n9.       Put tomcat-juli.jar from &#8220;extras&#8221; as $CATALINA_BASE\/bin\/tomcat-juli.jar<br \/>\n10.   If you are running with a security manager, you would need to edit the$CATALINA_BASE\/conf\/catalina.policy file to adjust it to using a different copy of tomcat-juli.jar.<br \/>\n11.   Delete $CATALINA_BASE\/conf\/logging.properties to prevent java.util.logging generating zero length log files.<br \/>\n12.   Start Tomcat<br \/>\n____________________________________________________________________________________________________<br \/>\nTomcat Security<br \/>\n# vi \/opt\/tomcat_1\/conf\/tomcat-users.xml<br \/>\n<?xml version='1.0' encoding='utf-8'?><br \/>\n<tomcat-users><br \/>\n  <role rolename=\"manager\"\/><br \/>\n  <role rolename=\"admin\"\/><br \/>\n  <user username=\"vivek\" password=\"vivek\" roles=\"manager,admin\"\/><br \/>\n<\/tomcat-users><br \/>\n____________________________________________________________________________________________________<br \/>\nConfiguring Tomcat for SSL<br \/>\n1. Generating the KeyStore file<br \/>\n#  \/usr\/java\/jdk1.7.0\/bin\/keytool -genkey  -keyalg RSA -alias tomcat -keystore \/opt\/apache-tomcat-7.0.28\/keys\/tomcat.jks<br \/>\nEnter keystore password: sapient<br \/>\nRe-enter new password: sapient<br \/>\nWhat is your first and last name? [Unknown]:  vivek srivastav<br \/>\nWhat is the name of your organizational unit? [Unknown]:  ISST<br \/>\nWhat is the name of your organization?  [Unknown]:  sapient<br \/>\nWhat is the name of your City or Locality? [Unknown]:  Gurgoan<br \/>\nWhat is the name of your State or Province? [Unknown]:  Haryana<br \/>\nWhat is the two-letter country code for this unit?  [Unknown]:  IN<br \/>\nIs CN=vivek srivastav, OU=ISST, O=sapient, L=Gurgoan, ST=Haryana, C=IN correct? [no]:  yes<br \/>\nEnter key password for <tomcat><br \/>\n        (RETURN if same as keystore password): sapient<br \/>\nRe-enter new password: sapient<\/p>\n<p>2. Configuring Tomcat for using the Keystore file<br \/>\n# vi \/opt\/apache-tomcat-7.0.28\/conf\/server.xml<br \/>\n<Connector port=\"8443\" protocol=\"HTTP\/1.1\" SSLEnabled=\"true\"\n               maxThreads=\"150\" scheme=\"https\" secure=\"true\"\n               clientAuth=\"false\" sslProtocol=\"TLS\"\n               keystoreFile=\"\/opt\/apache-tomcat-7.0.28\/keys\/tomcat.jks\" keystorePass=\"sapient\" \/><br \/>\n&#8212; >  https:\/\/localhost:8443\/<\/p>\n<p>If getting \u201cSecure Connection Failed (Error code: sec_error_ca_cert_invalid)\u201d<br \/>\n\u00e8 Click on \u201cyou can add an exception\u201d<br \/>\n\u00e8 Click on \u201cAdd Exception\u201d<br \/>\n\u00e8 Get Certificate<br \/>\n\u00e8 Confirm Security Exception<\/p>\n<p>3. Import an certificate (e.g. server.crt)<br \/>\n# mv \/opt\/apache2\/conf\/server.crt   \/opt\/apache-tomcat-7.0.28\/keys\/.<br \/>\n# cd \/opt\/apache-tomcat-7.0.28\/keys\/<br \/>\n# \/usr\/java\/jdk1.7.0\/bin\/keytool -import -trustcacerts -alias cert -file server.crt -keystore tomcat.jks<br \/>\nEnter keystore password: sapient<br \/>\nRe-enter new password: sapient<br \/>\nOwner: CN=o2vb, OU=ISST, O=O2, L=DL, ST=GGN, C=IN<br \/>\nIssuer: CN=o2vb, OU=ISST, O=O2, L=DL, ST=GGN, C=IN<br \/>\nSerial number: fb3b6d2ecd8932db<br \/>\nValid from: Tue Oct 09 23:49:00 IST 2012 until: Wed Oct 09 23:49:00 IST 2013<br \/>\nCertificate fingerprints:<br \/>\n         MD5:  4C:4C:9C:93:F5:93:57:ED:2B:9D:B3:CA:CB:1D:97:C8<br \/>\n         SHA1: 3B:70:18:A2:0D:4B:59:FF:4E:5C:64:6D:11:28:BA:49:BA:BA:BD:E2<br \/>\n         SHA256: 3A:57:76:74:79:52:B7:81:FD:6F:2A:3D:A1:F0:FD:3C:36:C9:E9:F5:BD:B1:D5:6B:E5:15:09:73:63:3F:5D:D2<br \/>\n         Signature algorithm name: SHA1withRSA<br \/>\n         Version: 1<br \/>\nTrust this certificate? [no]:  yes<br \/>\nCertificate was added to keystore<br \/>\nKeystore certificates list<br \/>\n# \/usr\/java\/jdk1.6.0_06\/bin\/keytool -list -v -keystore tomcat.jks<br \/>\nGenerate a certificate signing request (CSR) for an existing Java keystore<br \/>\n# keytool -certreq -alias mydomain -keystore keystore.jks -file mydomain.csr<br \/>\nCheck a stand-alone certificate<br \/>\n# keytool -printcert -v -file mydomain.crt<br \/>\nCheck a particular keystore entry using an alias<br \/>\n# keytool -list -v -alias mydomain -keystore keystore.jks<br \/>\nDelete a certificate from a Java Keytool keystore<br \/>\n# keytool -delete -alias mydomain -keystore keystore.jks<br \/>\nChange a Java keystore password<br \/>\n# keytool -storepasswd -new new_storepass -keystore keystore.jks<br \/>\nExport a certificate from a keystore<br \/>\n# keytool -export -alias mydomain -file mydomain.crt -keystore keystore.jks<br \/>\nList Trusted CA Certs<br \/>\n# keytool -list -v -keystore $JAVA_HOME\/jre\/lib\/security\/cacerts<br \/>\nImport New CA into Trusted Certs<br \/>\n# keytool -import -trustcacerts -file \/path\/to\/ca\/ca.pem -alias CA_ALIAS -keystore $JAVA_HOME\/jre\/lib\/security\/cacerts<br \/>\nSource: https:\/\/www.sslshopper.com\/article-most-common-java-keytool-keystore-commands.html<br \/>\nTo check certificates validity<br \/>\n[tomcat@app4r]$ \/usr\/java\/jdk1.6.0_06\/bin\/keytool -list -v -keystore Be.jks > abc<br \/>\n[tomcat@app4r]$ cat abc|grep -e &#8220;Alias&#8221; -e &#8220;Valid&#8221;<br \/>\nAlias name: o2_snowpatrol<br \/>\nValid from: Fri Oct 08 10:25:11 BST 2010 until: Fri Apr 06 10:25:11 BST 2012<br \/>\nAlias name: tomcat<br \/>\nValid from: Tue Nov 23 12:30:01 GMT 2010 until: Wed Nov 23 12:30:01 GMT 2011<br \/>\nAlias name: new_dsl_cert<br \/>\nValid from: Mon Sep 15 01:00:00 BST 2008 until: Fri Sep 16 00:59:59 BST 2011<br \/>\nAlias name: imt_stage_snowpetrol<br \/>\nCertificate Handshake failure Issue<br \/>\n[tomcat@app4r certificates]$ wget &#8216;https:\/\/sdpapi.ref.o2.co.uk\/services\/ViewPostalAddress_1_0&#8217;<br \/>\n&#8211;2013-05-10 14:37:17&#8211;  https:\/\/sdpapi.ref.o2.co.uk\/services\/ViewPostalAddress_1_0%20%3Chttps:\/\/sdpapi.ref.o2.co.uk\/services\/ViewPostalAddress_1_0%3E<br \/>\nResolving sdpapi.ref.o2.co.uk&#8230; 82.132.158.136<br \/>\nConnecting to sdpapi.ref.o2.co.uk|82.132.158.136|:443&#8230; connected.<br \/>\nOpenSSL: error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure<br \/>\nUnable to establish SSL connection.<br \/>\nHow to check<br \/>\n[tomcat@app4r certificates]$ openssl s_client -connect 82.132.158.136:443<br \/>\nCONNECTED(00000003)<br \/>\ndepth=3 \/C=US\/O=VeriSign, Inc.\/OU=Class 3 Public Primary Certification Authority<br \/>\nverify return:1<br \/>\ndepth=2 \/C=US\/O=VeriSign, Inc.\/OU=VeriSign Trust Network\/OU=(c) 2006 VeriSign, Inc. &#8211; For authorized use only\/CN=VeriSign Class 3 Public Primary Certification Authority &#8211; G5<br \/>\nverify return:1<br \/>\ndepth=1 \/C=US\/O=Thawte, Inc.\/CN=Thawte SGC CA &#8211; G2<br \/>\nverify return:1<br \/>\ndepth=0 \/C=GB\/ST=England\/L=Berkshire\/O=TELEFONICA UK LIMITED\/OU=Operations\/CN=sdpapi.ref.o2.co.uk<br \/>\nverify return:1<br \/>\n7172:error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure:s3_pkt.c:1086:SSL alert number 40<br \/>\n7172:error:140790E5:SSL routines:SSL23_WRITE:ssl handshake failure:s23_lib.c:188:<br \/>\n____________________________________________________________________________________________________<br \/>\n# sh catalina.sh run<br \/>\nHow to take thread dump<br \/>\n# kill -3 java_pid ; tail \u2013f catalina.out<\/p>\n<p>HEAP<a href=\"http:\/\/rmohan.com\/wp-content\/uploads\/2014\/09\/jvm.png\"><img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/rmohan.com\/wp-content\/uploads\/2014\/09\/jvm.png\" alt=\"jvm\" width=\"612\" height=\"319\" class=\"aligncenter size-full wp-image-3530\" srcset=\"https:\/\/mohan.sg\/wp-content\/uploads\/2014\/09\/jvm.png 612w, https:\/\/mohan.sg\/wp-content\/uploads\/2014\/09\/jvm-300x156.png 300w, https:\/\/mohan.sg\/wp-content\/uploads\/2014\/09\/jvm-150x78.png 150w, https:\/\/mohan.sg\/wp-content\/uploads\/2014\/09\/jvm-400x208.png 400w\" sizes=\"(max-width: 612px) 100vw, 612px\" \/><\/a><\/p>\n<p>JCONSOLE ( Monitoring Heap Size &#038; Garbage collector)<br \/>\n# ps -ef | grep java &#8212; > get Java_PID<br \/>\n# \/opt\/jdk1.7.0_03\/bin\/jconsole Java_PID<br \/>\n# pkill jconsole<\/p>\n<p>For the HotSpot Java VM:  The memory pools for serial garbage collection are the following.<br \/>\nEden Space (heap): The pool from which memory is initially allocated for most objects.<br \/>\nSurvivor Space (heap): The pool containing objects that have survived garbage collection of Eden space.<br \/>\nTenured Generation or old Gen(heap): The pool containing objects that have existed for some time in the survivor space.<br \/>\nPermanent Generation (non-heap): The pool containing all the reflective data of the virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas.<br \/>\nCode Cache (non-heap): The HotSpot Java VM also includes a code cache, containing memory that is used for compilation and storage of native code.<\/p>\n<p>Garbage collection : In Java, the unused objects remain in memory until a garbage collection occurs and frees up the memory used by the objects.The garbage collection process is primarily governed by the configuration parameters of the heap. (Heap is that part of the physical memory which is used by the JVM to create objects).<\/p>\n<p><a href=\"http:\/\/rmohan.com\/wp-content\/uploads\/2014\/09\/jconsole.png\"><img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/rmohan.com\/wp-content\/uploads\/2014\/09\/jconsole.png\" alt=\"jconsole\" width=\"639\" height=\"504\" class=\"aligncenter size-full wp-image-3529\" srcset=\"https:\/\/mohan.sg\/wp-content\/uploads\/2014\/09\/jconsole.png 639w, https:\/\/mohan.sg\/wp-content\/uploads\/2014\/09\/jconsole-300x236.png 300w, https:\/\/mohan.sg\/wp-content\/uploads\/2014\/09\/jconsole-150x118.png 150w, https:\/\/mohan.sg\/wp-content\/uploads\/2014\/09\/jconsole-400x315.png 400w\" sizes=\"(max-width: 639px) 100vw, 639px\" \/><\/a><\/p>\n<p>Major GC vs Minor GC:<br \/>\nYoung Generation is the pool of temporary objects which are not fully garbage collected initially. When these objects become old, they become part of the Old generation (This is referred as Minor GC) which are then fully garbage collected (referred as Major GC).<br \/>\nHow to identify Major\/Minor GC?<br \/>\nsuppose you start your application as \u2013<br \/>\n# java HelloWorld<br \/>\nto determine garbage collection, start your app as \u2013<br \/>\n# java \u2013verbose:gc HelloWorld<br \/>\nThe output of above change should be something like \u2013<br \/>\nGC 325407K-> 83000K (776768K), 0.2300771 secs<br \/>\nGC \u2013 Indicates that it was a minor collection (young generation).  If it had said Full GC then that indicates that it was a major collection (tenured generation).<br \/>\n325407K \u2013  The combined size of live objects before garbage collection.<br \/>\n83000K \u2013  The combined size of live objects after garbage collection.<br \/>\n(776768K) \u2013  the total available space, not counting the space in the permanent generation, which is the total heap minus one of the survivor spaces.<br \/>\n0.2300771 secs \u2013 time it took for garbage collection to occur.<\/p>\n<p>How to increase heap size in tomcat<br \/>\nHeap Size:  A Java Virtual Machine on 32-bit operating systems typically has a maximum heap size of 64Mb. The JVM heap space is where all Java objects are stored, as well as memory used by the garbage collector.<br \/>\nTo increase min( -Xms) and max (-Xmx)  heap size, set the JAVA_OPTS<br \/>\n# vi \/opt\/tomcat_1\/bin\/catalina.sh<br \/>\nexport JAVA_OPTS= -Xms256m -Xmx512m<br \/>\nHow the things are in Production environment<br \/>\n# vi \/app\/tomcat-6.0.18\/bin\/catalina.sh<br \/>\nexport JAVA_OPTS=&#8221;-server -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=\/app\/tomcat-6.0.18\/tomcat.hprof -Xms6144m -Xmx6144m -XX:MaxPermSize=512m -XX:NewRatio=2 -XX:SurvivorRatio=6 -Dcs.useEhcache=true -Dnet.sf.ehcache.enableShutdownHook=true -DnumOfDiskStores=10 -Dfile.encoding=UTF-8 -Dinsite.saveslotsonly=true -Dinsite.usemarkerassets=true&#8221;<\/p>\n<p>How to monitor java heap configuration by Jmap<br \/>\n# ps -ef |grep java   &#8212; >  root    6092     1  0 17:28 pts\/3    00:00:01 \/opt\/jdk1.7.0_03\/bin\/java<br \/>\n# \/opt\/jdk1.7.0_03\/bin\/jmap -heap  6092<br \/>\nAttaching to process ID 6092, please wait&#8230;<br \/>\nMark Sweep Compact GC<br \/>\nHeap Configuration:<br \/>\n   MinHeapFreeRatio = 40<br \/>\n   MaxHeapFreeRatio = 70<br \/>\n   MaxHeapSize      = 266338304 (254.0MB)<br \/>\n   NewSize          = 1048576 (1.0MB)<br \/>\n   MaxNewSize       = 4294901760 (4095.9375MB)<br \/>\n   OldSize          = 4194304 (4.0MB)<br \/>\n   NewRatio         = 2<br \/>\n   SurvivorRatio    = 8<br \/>\n   PermSize         = 12582912 (12.0MB)<br \/>\n   MaxPermSize      = 67108864 (64.0MB)<br \/>\nHeap Usage:<br \/>\nNew Generation (Eden + 1 Survivor Space):<br \/>\n   capacity = 4980736 (4.75MB)<br \/>\n   used     = 1721760 (1.641998291015625MB)<br \/>\n   free     = 3258976 (3.108001708984375MB)<br \/>\n   34.56838507401316% used<br \/>\nEden Space:<br \/>\n   capacity = 4456448 (4.25MB)<br \/>\n   used     = 1201520 (1.1458587646484375MB)<br \/>\n   free     = 3254928 (3.1041412353515625MB)<br \/>\n   26.961382697610293% used<br \/>\nFrom Space:<br \/>\n   capacity = 524288 (0.5MB)<br \/>\n   used     = 520240 (0.4961395263671875MB)<br \/>\n   free     = 4048 (0.0038604736328125MB)<br \/>\n   99.2279052734375% used<br \/>\nTo Space:<br \/>\n   capacity = 524288 (0.5MB)<br \/>\n   used     = 0 (0.0MB)<br \/>\n   free     = 524288 (0.5MB)<br \/>\n   0.0% used<br \/>\ntenured generation:<br \/>\n   capacity = 11075584 (10.5625MB)<br \/>\n   used     = 8240504 (7.858757019042969MB)<br \/>\n   free     = 2835080 (2.7037429809570312MB)<br \/>\n   74.40243331638314% used<br \/>\nPerm Generation:<br \/>\n   capacity = 12582912 (12.0MB)<br \/>\n   used     = 9002088 (8.585060119628906MB)<br \/>\n   free     = 3580824 (3.4149398803710938MB)<br \/>\n   71.54216766357422% used<br \/>\nJinfo<br \/>\n# \/opt\/jdk1.7.0_03\/bin\/jinfo  6092<br \/>\nAttaching to process ID 6092, please wait&#8230;<br \/>\nJVM version is 22.1-b02<br \/>\nsun.boot.library.path = \/opt\/jdk1.7.0_03\/jre\/lib\/i386<br \/>\njava.vm.vendor = Oracle Corporation<br \/>\nos.version = 2.6.18-164.el5<br \/>\nuser.home = \/root<br \/>\nuser.timezone = Asia\/Kolkata<br \/>\njava.specification.version = 1.7<br \/>\ncatalina.home = \/opt\/tomcat_2<br \/>\njava.class.path = \/opt\/tomcat_2\/bin\/bootstrap.jar:\/opt\/tomcat_2\/bin\/tomcat-juli.jar<br \/>\nuser.name = root<br \/>\n-Djava.util.logging.config.file=\/opt\/tomcat_2\/conf\/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager &#8211;<\/p>\n<p>Automatically Generating a Heap Dump when OutOfMemory(OOM) Error<br \/>\n# vi \/app\/tomcat-6.0.18\/bin\/catalina.sh<br \/>\nexport JAVA_OPTS=&#8221;-server -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=\/app\/tomcat-6.0.18\/tomcat.hprof<\/p>\n<p>Manually Generating a Heap Dump<br \/>\n# .\/jmap  \u2013dump:file=<file_name>  <pid>\n# .\/jmap \u2013dump:file=\/opt\/tomcat_2\/tomcat.hprof  6092<\/p>\n<p>Heap dump analysis by jhat<br \/>\n# cd \/opt\/jdk1.7.0_03\/bin<br \/>\n# .\/jhat -port 7000 \/opt\/tomcat_2\/tomcat.hprof<br \/>\nReading from \/opt\/tomcat_2\/tomcat.hprof&#8230;<br \/>\nStarted HTTP server on port 7000<br \/>\nServer is ready.<br \/>\nhttp:\/\/localhost:7000\/<br \/>\nWe can analysis heap dump on browser<\/p>\n<p>Option and Default Value<br \/>\nDescription<br \/>\n-XX:+AggressiveOpts<br \/>\nTurn on point performance compiler optimizations that are expected to be default in upcoming releases. (Introduced in 5.0 update 6.)<br \/>\n-XX:CompileThreshold=10000<br \/>\nNumber of method invocations\/branches before compiling [-client: 1,500]<br \/>\n-XX:MaxHeapFreeRatio=70<br \/>\nMaximum percentage of heap free after GC to avoid shrinking.<br \/>\n-XX:MaxNewSize=size<br \/>\nMaximum size of new generation (in bytes). Since 1.4, MaxNewSize is computed as a function of NewRatio. [1.3.1 Sparc: 32m; 1.3.1 x86: 2.5m.]<br \/>\n-XX:MaxPermSize=64m<br \/>\nSize of the Permanent Generation.  [5.0 and newer: 64 bit VMs are scaled 30% larger; 1.4 amd64: 96m; 1.3.1 -client: 32m.]<br \/>\n-XX:MinHeapFreeRatio=40<br \/>\nMinimum percentage of heap free after GC to avoid expansion.<br \/>\n-XX:NewRatio=2<br \/>\nRatio of new\/old generation sizes. [Sparc -client: 8; x86 -server: 8; x86 -client: 12.]-client: 4 (1.3) 8 (1.3.1+), x86: 12]<br \/>\n-XX:NewSize=2.125m<br \/>\nDefault size of new generation (in bytes) [5.0 and newer: 64 bit VMs are scaled 30% larger; x86: 1m; x86, 5.0 and older: 640k]<br \/>\n-XX:SurvivorRatio=8<br \/>\nRatio of eden\/survivor space size [Solaris amd64: 6; Sparc in 1.3.1: 25; other Solaris platforms in 5.0 and earlier: 32]<br \/>\n-XX:TargetSurvivorRatio=50<br \/>\nDesired percentage of survivor space used after scavenge.<br \/>\n-XX:-UseISM<br \/>\nUse Intimate Shared Memory<br \/>\n-XX:+UseLargePages<br \/>\nUse large page memory.<br \/>\n-XX:+UseStringCache<br \/>\nEnables caching of commonly allocated strings.<br \/>\n-XX:AllocatePrefetchLines=1<br \/>\nNumber of cache lines to load after the last object allocation using prefetch instructions generated in JIT compiled code. Default values are 1 if the last allocated object was an instance and 3 if it was an array.<br \/>\nPause Time in GC: The length of time during which application execution is stopped while garbage<br \/>\ncollection is occurring.<br \/>\nDesign Choices<br \/>\n\u2022 Serial versus Parallel<br \/>\nWith serial collection, while multiple CPUs are available, only one is utilized to perform the collection. When parallel collection is used, the task of garbage collection is split into parts and those subparts are executed simultaneously, on different CPUs. The simultaneous operation enables the collection to be done more quickly.<br \/>\n\u2022 Concurrent versus Stop-the-world<br \/>\nWhen stop-the-world garbage collection is performed, execution of the application is completely<br \/>\nsuspended during the collection. Alternatively, one or more garbage collection tasks can be executed<br \/>\nconcurrently, that is, simultaneously, with the application. Typically, a concurrent garbage collector<br \/>\ndoes most of its work concurrently, but may also occasionally have to do a few short stop-the-world<br \/>\npauses. Stop-the-world garbage collection is simpler than concurrent collection, since the heap is<br \/>\nfrozen and objects are not changing during the collection. Its disadvantage is that it may be<br \/>\nundesirable for some applications to be paused. Correspondingly, the pause times are shorter when<br \/>\ngarbage collection is done concurrently, but the collector must take extra care, as it is operating over<br \/>\nobjects that might be updated at the same time by the application. This adds some overhead to<br \/>\nconcurrent collectors that affects performance and requires a larger heap size.<br \/>\n\u2022 Compacting versus Non-compacting versus Copying<br \/>\nAfter a garbage collector has determined which objects in memory are live and which are garbage, it<br \/>\ncan compact the memory, moving all the live objects together and completely reclaiming the<br \/>\nremaining memory. After compaction, it is easy and fast to allocate a new object at the first free<br \/>\nlocation. A simple pointer can be utilized to keep track of the next location available for object<br \/>\nallocation. In contrast with a compacting collector, a non-compacting collector releases the space<br \/>\nutilized by garbage objects in-place, i.e., it does not move all live objects to create a large reclaimed<br \/>\nregion in the same way a compacting collector does. The benefit is faster completion of garbage<br \/>\ncollection, but the drawback is potential fragmentation. In general, it is more expensive to allocate<br \/>\nfrom a heap with in-place deallocation than from a compacted heap. It may be necessary to search the<br \/>\nheap for a contiguous area of memory sufficiently large to accommodate the new object. A third<br \/>\nalternative is a copying collector, which copies (or evacuates) live objects to a different memory area.<br \/>\nThe benefit is that the source area can then be considered empty and available for fast and easy<br \/>\nsubsequent allocations, but the drawback is the additional time required for copying and the extra<br \/>\nspace that may be required.<\/p>\n<p>GC Logs<br \/>\n8746.664: [GC 8746.664: [ParNew: 1118528K->6000K(1258304K), 0.0692770 secs] 1118528K->6000K(4054528K), 0.0693720 secs] [Times: user=0.13 sys=0.01, real=0.08 secs]<br \/>\n19625.935: [Full GC 19625.935: [CMS: 0K->5886K(2796224K), 0.1273050 secs] 244248K->5886K(4054528K), [CMS Perm : 21247K->21092K(21248K)], 0.1274740 secs] [Times: user=0.10 sys=0.02, real=0.13 secs]<br \/>\n19626.075: [GC [1 CMS-initial-mark: 5886K(2796224K)] 17295K(4054528K), 0.0008640 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]<br \/>\n19626.076: [CMS-concurrent-mark-start]<br \/>\n19627.828: [Full GC 19627.828: [CMS19627.890: [CMS-concurrent-mark: 0.062\/1.814 secs] [Times: user=2.69 sys=0.07, real=1.82 secs]<br \/>\n21155.807: [CMS-concurrent-mark-start]<br \/>\n21155.912: [CMS-concurrent-mark: 0.105\/0.105 secs] [Times: user=0.20 sys=0.01, real=0.10 secs]<br \/>\n21155.912: [CMS-concurrent-preclean-start]<br \/>\n21155.962: [CMS-concurrent-preclean: 0.047\/0.050 secs] [Times: user=0.09 sys=0.00, real=0.05 secs]<br \/>\n21155.962: [CMS-concurrent-abortable-preclean-start]<br \/>\n CMS: abort preclean due to time 21160.988: [CMS-concurrent-abortable-preclean: 0.421\/5.026 secs] [Times: user=0.90 sys=0.02, real=5.03 secs]<br \/>\n21160.988: [GC[YG occupancy: 530699 K (1258304 K)]21160.988: [Rescan (parallel) , 0.1831550 secs]21161.172: [weak refs processing, 0.0000470 secs] [1 CMS-remark: 9334K(2796224K)] 540034K(4054528K), 0.1833000 secs] [Times: user=0.19 sys=0.00, real=0.18 secs]<br \/>\n21161.172: [CMS-concurrent-sweep-start]<br \/>\n21161.178: [CMS-concurrent-sweep: 0.006\/0.006 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]<br \/>\n21161.178: [CMS-concurrent-reset-start]<br \/>\n21161.184: [CMS-concurrent-reset: 0.006\/0.006 secs] [Times: user=0.01 sys=0.00, real=0.01 secs]<br \/>\nHeap<br \/>\n par new generation   total 1258304K, used 733988K [0x00000006e0000000, 0x0000000735550000, 0x0000000735550000)<br \/>\n  eden space 1118528K,  65% used [0x00000006e0000000, 0x000000070ccc9318, 0x0000000724450000)<br \/>\n  from space 139776K,   0% used [0x000000072ccd0000, 0x000000072ccd0000, 0x0000000735550000)<br \/>\n  to   space 139776K,   0% used [0x0000000724450000, 0x0000000724450000, 0x000000072ccd0000)<br \/>\n concurrent mark-sweep generation total 2796224K, used 9285K [0x0000000735550000, 0x00000007e0000000, 0x00000007e0000000)<br \/>\n concurrent-mark-sweep perm gen total 94332K, used 62446K [0x00000007e0000000, 0x00000007e5c1f000, 0x0000000800000000)<\/p>\n<p>Enable GC (Garbage Collector) in Tomcat<br \/>\n# vi catalina.sh<br \/>\nExport JAVA_OPTS= -Xloggc: \/app\/tomcat-6.0.18\/CS7.0\/cs_tomcat\/logs\/gc.log  -verbose:gc -XX:+PrintGCDetails  -XX:+PrintGCTimeStamps<br \/>\nHere -Xloggc: is path of GC logs<br \/>\n-verbose:gc<br \/>\nPrints some GC info<br \/>\n-XX:+PrintHeapAtGC<br \/>\nPrints detailed GC info including heap occupancy before and after GC<br \/>\n-XX:+PrintGC<br \/>\nOutputs basic information at every garbage collection<br \/>\n-XX:+PrintGCDetails<br \/>\nProvide information such as the size of live objects before and after garbage collection for the various generations, the total available space for each generation, and the length of time the collection took.<br \/>\n-XX:+PrintGCTimeStamps<br \/>\nPrints the garbage collection time stamps to help with debugging.<\/p>\n<p>Partial garbage collection:<br \/>\n1.612: [GC [PSYoungGen: 12998K->1568K(18496K)] 12998K->1568K(60864K),0.0054130 secs] [Times: user=0.01 sys=0.00, real=0.00 secs]<br \/>\nFull garbage collection:<br \/>\n1.617: [Full GC (System) [PSYoungGen: 1568K->0K(18496K)] [PSOldGen: 0K->1483K(42368K)] 1568K->1483K(60864K) [PSPermGen: 9458K->9458K(21248K)],0.0294590 secs] [Times: user=0.02 sys=0.00, real=0.03 secs]<\/p>\n<p>Types of Garbage Collector<br \/>\nThe Serial Collector: -XX:+UseSerialGC<br \/>\n(default  &#038; stop-the-world collector)<br \/>\n1. Uses only one GC thread for the GC operation<br \/>\n2. Used for small application.<br \/>\n3. Tenured Generation GC done in serial threads.<br \/>\nThe Parallel Collector(Throughput Collector): -XX:+UseParallelGC<br \/>\n(stop-the-world collector)<br \/>\n1. Uses multiple GC threads for the GC operation .<br \/>\n2. Young Generation GC done in parallel threads<br \/>\nParallel Old Generation Collector:                                   -XX:+UseParallelOldGC<br \/>\n1. This garbage collector is set for high throughput<br \/>\n2. Certain phases of an \u2018Old Generation\u2019 collection can be performed in parallel, speeding up a old generation collection..<br \/>\nThe Concurrent Low Pause Collector(CMS):                            -XX:+UseConcMarkSweepGC<br \/>\nSteps of GC: &#8211; initial mark, &#8211; concurrent marking, &#8211; remark, &#8211; concurrent sweeping<br \/>\n1. Uses only one GC thread for the GC operation<br \/>\n2. This garbage collector is set for low pause time. It will result in a Java application that has a lower average throughput, but much   shorter CPU-intensive garbage collections. This option is required in environments that have response time constraints.<br \/>\nIncremental Low Pause Collector: -XX:+UseTrainGC<br \/>\nSerial vs Parallel collector<br \/>\n\u00d8  Both the serial and parallel collectors cause a stop-the-world during the GC.  A serial collector is a default copying collector which uses only one GC thread for the GC operation, while a parallel collector uses multiple GC threads for the GC operation.<br \/>\nParallel vs CMS collectors:<br \/>\n\u00d8  The parallel is a &#8216;stop-the-world&#8217; collector, while the CMS stops the world only during the initial mark and remark phases. During the concurrent marking and sweeping phases, the CMS thread runs along with the application&#8217;s threads.<\/p>\n<p>if you wish to combine both parallelism and concurrency in your GC, you can use the following:<br \/>\n-XX:UserParNewGC for the new generation (multiple GC threads)<br \/>\n-XX:+UseConcMarkSweepGC for the old generation (one GC thread, freezes the JVM only during the initial mark and remark phases)<\/p>\n<p>Collectors operate on the young generation: -XX:+UseSerialGC, -XX:+UseParallelGC, XX:+UseParNewGC<br \/>\nCollectors operate on the old generation: -XX:+UseParallelOldGC, -XX:+UseConcMarkSweepGC<br \/>\nhttp:\/\/robaustin.wikidot.com\/jvm-garbage-collector-overview<\/p>\n<p>Java Thread Dump Analyser<br \/>\nThread States: There are 6 thread states<br \/>\nNEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED<br \/>\nDownload jtda-cli.jar<br \/>\nTo see the usage: \/usr\/java\/jdk1.6.0_06\/bin\/java -jar jtda-cli.jar \u2013help<br \/>\nTo Analyze thread tump: # cat catalina.out_23_05_2013_02 | \/usr\/java\/jdk1.6.0_06\/bin\/java -jar jtda-cli.jar<br \/>\nSource: http:\/\/mchr3k.github.io\/javathreaddumpanalyser\/<br \/>\n____________________________________________________________________________________________________<br \/>\nTomcat with LDAP integration<br \/>\n# vi \/opt\/apache-tomcat-7.0.28\/conf\/server.xml<br \/>\n  <Realm className=\"org.apache.catalina.realm.JNDIRealm\" debug=\"99\"\n       connectionName=\"cn=Manager,dc=example,dc=com\"\n       connectionPassword=\"vivek\"\n       connectionURL=\"ldap:\/\/localhost:389\"\n       userPattern=\"uid={0},dc=example,dc=com\"\n       roleBase=\"dc=example,dc=com\"\n       roleName=\"cn\"\n       roleSearch=\"memberUid={1}\"\/><\/p>\n<p># vi ..\/webapps\/ROOT\/WEB-INF\/web.xml<br \/>\n<web-app xmlns=\"http:\/\/java.sun.com\/xml\/ns\/javaee\"\n  xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\"\n  xsi:schemaLocation=\"http:\/\/java.sun.com\/xml\/ns\/javaee\n  http:\/\/java.sun.com\/xml\/ns\/javaee\/web-app_3_0.xsd\" version=\"3.0\" metadata-complete=\"true\"><br \/>\n  <display-name>Welcome to Tomcat<\/display-name><br \/>\n  <description> Welcome to Tomcat<\/description><br \/>\n<security-constraint><br \/>\n    <web-resource-collection><br \/>\n          <web-resource-name>Logging Area<\/web-resource-name><br \/>\n          <description><br \/>\n              Authentication for registered users.<br \/>\n          <\/description><br \/>\n          <url-pattern>\/*<\/url-pattern><br \/>\n          <http-method>GET<\/http-method><br \/>\n          <http-method>POST<\/http-method><br \/>\n    <\/web-resource-collection><br \/>\n        <auth-constraint> <role-name>*<\/role-name> <\/auth-constraint><br \/>\n    <\/security-constraint><br \/>\n<security-role>  <role-name>*<\/role-name>  <\/security-role><br \/>\n    <login-config><br \/>\n          <auth-method>BASIC<\/auth-method><br \/>\n        <realm-name>Please enter your Username<\/realm-name><br \/>\n<\/login-config><br \/>\n<\/web-app><\/p>\n<p># .\/catalina.sh start; tail -f ..\/logs\/catalina.out<br \/>\nNow once we start the Tomcat and visit your website, following popup will be shown.<br \/>\nhttp:\/\/localhost:8080\/<br \/>\n____________________________________________________________________________________________________<br \/>\nSingle Sign-On Implementation<br \/>\nUsing Single Sign-on, it is possible to eliminate this annoying repetition (provided the user name and password are identical for each sign-on, and usually authenticating against the same Tomcat Realm).<br \/>\nThe Single Sign-on Valve caches credentials (passwords) on the server side, and will invisibly authenticate users as they traverse between Web applications on a given virtual host. Without activating this Valve, the user will be prompted to authenticate for each and every protected Web application<\/p>\n<p><Host name=\"localhost\" ...><br \/>\n  &#8230;<br \/>\n  <Valve className=\"org.apache.catalina.authenticator.SingleSignOn\" \/><br \/>\n  &#8230;<br \/>\n<\/Host><br \/>\nAttribute<br \/>\nDescription<br \/>\nclassName<br \/>\nJava class name of the implementation to use. This MUST be set toorg.apache.catalina.authenticator.SingleSignOn.<br \/>\nrequireReauthentication<br \/>\nDefault false. Flag to determine whether each request needs to be reauthenticated to the securityRealm. If &#8220;true&#8221;, this Valve uses cached security credentials (username and password) to reauthenticate to the Realm each request associated with an SSO session. If &#8220;false&#8221;, the Valve can itself authenticate requests based on the presence of a valid SSO cookie, without rechecking with the Realm.<br \/>\ncookieDomain<br \/>\nSets the host domain to be used for sso cookies.<\/p>\n<p>How SSO work in two applications<\/p>\n<p>Web Application A (http:\/\/WebApplicationA\/)<br \/>\nWeb Application B (http:\/\/WebApplicationB\/)<\/p>\n<p>User logs into Web Application A. He clicks on a link inside Web Application A page (of the kind): http:\/\/WebApplicationB\/go?sessionId=ABC&#038;user=me@me.com<\/p>\n<p>When Application B receives this request, it makes a http call to Application A to verify this information.<br \/>\nIn other words it sends a http request (server to server) like: http:\/\/WebApplicationA\/verifyUserSession?sessionId=ABC&#038;user=me@me.com. WebApplication A checks its list of logged-in users\/sessions and responds with a VERIFIED or FAILURE.<\/p>\n<p>If the response was VERIFIED, WebApplicationB knows this is a logged in user inside WebApplicationA &#8211; and it proceeds to create a session for the user, and allows him in. <\/p>\n<p>Configuring Customized User Directories<br \/>\nSome sites like to allow individual users to publish a directory of web pages on the server. For example, a university department might want to give each student a public area, or an ISP might make some web space available on one of its servers to customers that don&#8217;t have a virtually hosted web server. In such cases, it is typical to use the tilde character (~) plus the user&#8217;s name as the virtual path of that user&#8217;s web site:<br \/>\nhttp:\/\/www.cs.myuniversity.edu\/~username<br \/>\nhttp:\/\/members.mybigisp.com\/~username<br \/>\nTomcat gives you two ways to map this on a per-host basis, using a couple of special Listener elements. The Listener&#8217;sclassName attribute should be org.apache.catalina.startup.UserConfig, with the userClass attribute specifying one of several mapping classes. If your system runs Unix, has a standard \/etc\/passwd file that is readable by the account running Tomcat, and that file specifies users&#8217; home directories, use the PasswdUserDatabase mapping class:<br \/>\n<Listener className=\"org.apache.catalina.startup.UserConfig\"\ndirectoryName=\"public_html\"\nuserClass=\"org.apache.catalina.startup.PasswdUserDatabase\"\/><br \/>\nWeb files would need to be in directories such as \/home\/users\/ian\/public_html or \/users\/jbrittain\/public_html. Of course, you can change public_html to be whatever subdirectory into which your users put their personal web pages.<br \/>\nIn fact, the directories don&#8217;t have to be inside of a user&#8217;s home directory at all. If you don&#8217;t have a password file but want to map from a user name to a subdirectory of a common parent directory such as \/home, use the HomesUserDatabase class:<br \/>\n<Listener className=\"org.apache.catalina.startup.UserConfig\"\ndirectoryName=\"public_html\" homeBase=\"\/home\"\nuserClass=\"org.apache.catalina.startup.HomesUserDatabase\"\/><br \/>\nIn this case, web files would be in directories such as \/home\/ian\/public_html or \/home\/jasonb\/public_html. This format is more useful on Windows, where you&#8217;d likely use a directory such as C:\\home.<br \/>\nThese Listener elements, if present, must be inside of a Host element, but not inside of a Context element, as they apply to theHost itself.<\/p>\n<p>Tomcat Interview Questions Link<\/p>\n<p>http:\/\/www.pagalbytes.com\/?q=node\/535&#038;page=show<br \/>\nhttp:\/\/www.javaexperience.com\/category\/tomcat\/<br \/>\nhttp:\/\/allinoneissues.blogspot.in\/2012\/07\/tomcat-interview-questions-answers.html<br \/>\n# vi .bash_profile<br \/>\nexport ANT_HOME=\/opt\/apache-ant-1.9.1\/<br \/>\nexport PATH=$ANT_HOME\/bin:$PATH<br \/>\nexport JAVA_HOME=\/usr\/jdk1.7.0_03\/<\/p>\n<p># vi \/opt\/build\/build.xml<br \/>\n<?xml version=\"1.0\"?>\n<project name=\"my-app\" basedir=\".\" default=\"usage\">\n  <property file=\"build.properties\"\/>\n<path id=\"catalina-ant-classpath\">\n    <fileset dir=\"${tomcat.lib}\"><br \/>\n        <include name=\"catalina-ant.jar\"\/><br \/>\n        <include name=\"tomcat-coyote.jar\"\/><br \/>\n        <include name=\"tomcat-util.jar\"\/><br \/>\n    <\/fileset><br \/>\n    <fileset dir=\"${tomcat.bin}\"><br \/>\n                <include name=\"tomcat-juli.jar\"\/><br \/>\n    <\/fileset>\n<\/path>\n<taskdef name=\"deploy\" classname=\"org.apache.catalina.ant.DeployTask\"><br \/>\n       <classpath refid=\"catalina-ant-classpath\"\/><br \/>\n    <\/taskdef><br \/>\n<target name=\"deploy\"><br \/>\n<copy file=\"sample.war\" todir=\"${tomcat.deployment}\"\/><br \/>\n<antcall target=\"startTomcat\"\/><br \/>\n<\/target><br \/>\n<target name=\"startTomcat\"><br \/>\n<exec executable=\"${tomcat.bin}\/startup.sh\"\/><br \/>\n<\/target><br \/>\n<target name=\"stopTomcat\"><br \/>\n<exec executable=\"${tomcat.bin}\/shutdown.sh\"\/><br \/>\n<\/target>\n<\/project>\n<p># vi \/opt\/build\/build.properties<br \/>\ntomcat=\/opt\/apache-tomcat-7.0.40\/<br \/>\ntomcat.lib=${tomcat}\/lib<br \/>\ntomcat.deployment=${tomcat}\/webapps<br \/>\ntomcat.bin=${tomcat}\/bin<\/p>\n<p>Put sample.war into \/opt\/build\/<br \/>\n# ant deploy<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Reasons for Using a Web Server Apache You may be wondering why a separate Web server is needed when Tomcat already has an HTTP Connector. Following are some reasons: ? Performance\u2014Tomcat is inherently slower than a Web server. Therefore, it is better for the Web server to serve up static content, while Tomcat handles the [&#8230;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[21],"tags":[],"_links":{"self":[{"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/posts\/3527"}],"collection":[{"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mohan.sg\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=3527"}],"version-history":[{"count":1,"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/posts\/3527\/revisions"}],"predecessor-version":[{"id":3531,"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/posts\/3527\/revisions\/3531"}],"wp:attachment":[{"href":"https:\/\/mohan.sg\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=3527"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mohan.sg\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=3527"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mohan.sg\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=3527"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}