Monday, May 26, 2014

Creating a sample dynamic web project without IDE

Creating a dynamic web project without IDE:

Step 1:

"WebProjectGenerator.bat"
Copy the below given code to notepad and save it as a batch file (WebProjectGenerator.bat )
----------------------------------------------------------------------------------------------------------------------------------
@ECHO OFF
::%USERNAME will pick the system user name.
ECHO ############################## Welcome %USERNAME% ##############################

::ECHO. will print a new line here.
ECHO.
::Get the project name from user as an input, declaring a 'Create' function
:Create
SET /P projectName=Please enter a new project name:
ECHO.

::Check if user provided project name is blank or not.If blank then error else create the project.
::Note- In batch programming we can use only 'IF' statement, it does'nt support 'IF-ELSE' statements.
IF "%projectName%"=="" ECHO You did not enter a project name! & GOTO Error
ECHO Hello, you have entered new project name as: '%projectName%'
ECHO.

::Check if user provided project name already exists or not.If exist then ask to provide the project name again
@ECHO off
IF EXIST %projectName% ECHO The name of project ('%projectName%') you have entered is already exists! & GOTO CreateAgain

SET metainf="META-INF"
SET webinf="WEB-INF"
SET indexjsp="index.jsp"
SET indexhtml="index.html"
SET webxml="web.xml"
SET lib="lib"
SET classes="classes"


ECHO Creating %projectName% ...
MKDIR %projectName%
CHDIR %projectName%

ECHO Creating %metainf% ...
MKDIR %metainf%

ECHO Creating %webinf% ...
MKDIR %webinf%

::^ Character is used to ignore checking of '<' and '>' symbols by batch compiler.
ECHO Creating %indexjsp% ...
ECHO ^<html^>^<head^>^<title^>Write your title of the page here^</title^>^</head^>^<body^>Write your code here...^</body^>^</html^> >> %indexjsp%

::^ Character is used to ignore checking of '<' and '>' symbols by batch compiler.
ECHO Creating %indexhtml% ...
ECHO  ^<html^>^<head^>^<title^>Write your title of the page here^</title^>^</head^>^<body^>Write your code here...^</body^>^</html^> >> %indexhtml%

CHDIR %webinf%

ECHO Creating %lib% ...
MKDIR %lib%

ECHO Creating %classes% ...
MKDIR %classes%

ECHO Creating %webxml% ...
ECHO ^<web-app^>^<display-name^>Name of your project^</display-name^>^<description^>Description about your project^</description^>^<welcome-file-list^>^<welcome-file^>index.html^</welcome-file^>^<welcome-file^>index.jsp^</welcome-file^>^</welcome-file-list^>^</web-app^> >> %webxml%

CD ../../

ECHO Copying ServletCompilerHelper file ...
COPY ServletCompilerHelper.bat %projectName%\%webinf%\%classes%\

GOTO Success

::Declaring a 'Error' function
:Error
ECHO.
SET /P flag=Do you want to create new project (Y/N)? or type 'exit' to exit from here:
::These multiple if statements represents OR conditions, In batch programming this is the way to check "OR" condition.
IF "%flag%"=="exit" ECHO. & GOTO EXIT 
IF "%flag%"=="EXIT" ECHO. & GOTO EXIT   
IF "%flag%"=="" ECHO Entered option is invalid! & GOTO End  
IF "%flag%"=="Y" ECHO. & GOTO Create   
IF "%flag%"=="y" ECHO. & GOTO Create  
IF "%flag%"=="N" ECHO. & GOTO End  
IF "%flag%"=="n" ECHO. & GOTO End  
IF NOT "%flag%"=="Y" ECHO Entered option is invalid, Please select (Y/N)! & GOTO Error 
IF NOT "%flag%"=="y" ECHO Entered option is invalid, Please select (Y/N)! & GOTO Error   
IF NOT "%flag%"=="N" ECHO Entered option is invalid, Please select (Y/N)! & GOTO Error  
IF NOT "%flag%"=="n" ECHO Entered option is invalid, Please select (Y/N)! & GOTO Error   

::Declaring a 'CreateAgain' function
:CreateAgain
ECHO.
SET /P createflag=Do you want to create new project (Y/N)? or type 'exit' to exit from here:
::These multiple if statements represents OR conditions, In batch programming this is the way to check "OR" condition.
IF "%createflag%"=="exit" ECHO. & GOTO EXIT 
IF "%createflag%"=="EXIT" ECHO. & GOTO EXIT   
IF "%createflag%"=="" ECHO Entered option is invalid! & GOTO End  
IF "%createflag%"=="Y" ECHO. & GOTO Create  
IF "%createflag%"=="y" ECHO. & GOTO Create  
IF "%createflag%"=="N" ECHO. & GOTO End  
IF "%createflag%"=="n" ECHO. & GOTO End  
IF NOT "%createflag%"=="Y" ECHO Entered option is invalid, Please select (Y/N)! & GOTO Error 
IF NOT "%createflag%"=="y" ECHO Entered option is invalid, Please select (Y/N)! & GOTO Error   
IF NOT "%createflag%"=="N" ECHO Entered option is invalid, Please select (Y/N)! & GOTO Error  
IF NOT "%createflag%"=="n" ECHO Entered option is invalid, Please select (Y/N)! & GOTO Error

::Declaring a 'Success' function
:Success
ECHO.
ECHO Directory structure of your project is ready,configure it as per your need, Thanks!!

::Declaring a 'End' function
:End
ECHO.
ECHO Bye Bye!!

::Declaring a 'EXIT' function
:EXIT
ECHO.
ECHO Exiting the command prompt, Bye Bye!!

EXIT
----------------------------------------------------------------------------------------------------------------------------------
Step 2:

"ServletCompilerHelper.bat"

Copy the below given code to notepad and save it as a batch file (ServletCompilerHelper.bat )

---------------------------------------------------------------------------------------------------------------------------------
@echo off
echo ############################### Welcome, %USERNAME% ###############################

:: Command to insert a line break on the screen is>> 'echo.'
echo.

echo Setting java path...
:: Command to set the bin path of jdk set in environment variables is>> 'set PATH=%JAVA_HOME%\bin;%PATH%'
set PATH=%JAVA_HOME%\bin;%PATH%
echo Java path is set successfully!
echo.
echo Below is the version of jdk installed in your machine:::::::
:: Command to display java version installed in your machine>> 'java -version'
java -version
echo.

:CompileJavaCode
SET /P flag=Do you want to compile java source code (Y/N)?
::These multiple if statements represents OR conditions, In batch programming this is the way to check "OR" condition.
IF "%flag%"=="" ECHO. & GOTO End   
IF "%flag%"=="Y" ECHO. & GOTO Compile  
IF "%flag%"=="y" ECHO. & GOTO Compile  
IF "%flag%"=="N" ECHO. & GOTO End  
IF "%flag%"=="n" ECHO. & GOTO End  
IF NOT "%flag%"=="Y" ECHO Entered option is invalid & GOTO End 
IF NOT "%flag%"=="y" ECHO Entered option is invalid & GOTO End
IF NOT "%flag%"=="N" ECHO Entered option is invalid & GOTO End
IF NOT "%flag%"=="n" ECHO Entered option is invalid & GOTO End

::Declaring a 'Compile' function
:Compile
javac -classpath %CATALINA_HOME%\lib\servlet-api.jar *.java

::Declaring a 'End' function
:End
ECHO.

ECHO Bye Bye!! 

*********************************************************************************

Step 3:

Put WebProjectGenerator.bat and ServletCompilerHelper.bat files in webapps directory/folder of Apache tomcat.

Step 4:
Run WebProjectGenerator.bat file and follow the instructions. It will create the sample web project based on the given inputs.

Step 4:
To compile the class files i.e. Java Servlets use ServletCompilerHelper.bat file. It will compile all the servlet source files into class files.

Saturday, May 17, 2014

Integrating tomcat plug-in with Eclipse [Debug web applications without restarting the server]

Installing tomcat plug-in>>


Benefit: >>  Web projects can be debugged without restarting the server. 
If  Eclipse version is grater than  4.2 (Eclipse Luna)>>> then use following plugin:



"Uqbar Tomcat XT Eclipse Plug-in"

If tomcat version is below 4.2 then use "tomcatPluginV33">>>>>>>>>>>>>>>
  1. Download the plugin from "http://www.eclipsetotale.com/tomcatPlugin.html"
  2. Unzip the tomcatPluginV33.zip in dropins or plugin folder of eclipse.



  1.  Start eclipse
  2.  Go to Window>Preferences>Tomcat
-          Set the path of tomcat server.

-          In Advance section, Unmark "Launch tomcat using security manager"

-          In JVM Settings section, Check JVM Settings are in place or not?
    


-          In Source path section, Check "Automatically compute source path"
      


-          In Tomcat manager app section, 
          ManagerApp url: http://localhost:8080/manager
          ManagerApp username: admin
          ManagerApp password:  admin

          
       

5. Click 'Apply' button.
6. Click 'Ok' button.

Integrating WebProject with tomcat>>

1      1.  Create a web project e.g. DemoServletProject
-       Directory structure of project should be like this (same should be provided in context setting below):


-       .classpath file should have following properties.

 <?xml version="1.0" encoding="UTF-8"?>
<classpath>
           <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
           <classpathentry kind="var" path="TOMCAT_HOME/lib/servlet-api.jar"/>
           <classpathentry kind="var" path="TOMCAT_HOME/lib/jasper.jar"/>
           <classpathentry kind="var" path="TOMCAT_HOME/lib/jsp-api.jar"/>
           <classpathentry kind="var" path="TOMCAT_HOME/lib/el-api.jar"/>
           <classpathentry kind="var" path="TOMCAT_HOME/lib/annotations-api.jar"/>
           <classpathentry kind="src" path="webapps/WEB-INF/src"/>
           <classpathentry kind="output" path="webapps/WEB-INF/classes"/>
</classpath>

1    2. Put the following mapping in the server.xml under <Host> element of TOMCAT_HOME.

<Context path="/DemoServletProject" reloadable="true" docBase="D:\Personal\Study\MyStuffs\Dropbox\EclipseWorkSpace\DemoServletProject\webapps"/>

2    3.  
Start tomcat from eclipse. Now you can easily debug without restarting the server.





Leave your comments/suggestions below, Otherwise the next time:)







JDBC Connection pooling with Tomcat configuration

STEPS for configuring pool....

PREREQUSITE:
Ø  APACHE-COMMONS-DBCP.JAR
Ø  APACHE-COMMONS-CONNECTION-POOL.JAR

STEP 1:  Configure DataSource

We can configure DataSource in Context.xml or Server.xml

Configuration for Context.xml

<context>
<resource auth="Container" driverclassname="com.mysql.jdbc.Driver" maxactive="20" maxidle="30" maxwait="-1" name="jdbc/mysqldb" password="root" type="javax.sql.DataSource" url="jdbc:mysql://localhost:3306/users?autoReconnect=true" username="root">
</resource>
</context>

OR Configuration for Server.xml

<host>
<context docbase="Struts2SpringDemo" path="/Struts2SpringDemo" reloadable="true" source="org.eclipse.jst.jee.server:Struts2SpringDemo">
<resource auth="Container" driverclassname="com.mysql.jdbc.Driver" maxactive="20" maxidle="30" maxwait="-1" name="jdbc/mysqldb" password="root" type="javax.sql.DataSource" url="jdbc:mysql://localhost:3306/users?autoReconnect=true" username="root">
</resource>
</context>
</host>

Configuration for Web.xml

<resource-ref>
<description>MySQL Connection Pool</description>
<res-ref-name>jdbc/mysqldb</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>



#####################################################################
STEP 2: GETTING CONNECTION

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;

import javax.naming.NamingException;
import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The Class ConnectionManager.
 */
public class ConnectionManager {

/** The LOGGER. */
private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionManager.class);

/** The context, kept for better performance */
private static javax.naming.Context ctx;

/**
* Constructs the singleton, also obtaining the context.
*/
private static void init() throws NamingException {
ctx = new javax.naming.InitialContext();
}

/**
* Gets the connection from pool.
*
* @param dataSourceName the data source name
* @return the connection from pool
* @throws NamingException the naming exception
* @throws SQLException the SQL exception
*/
public static Connection getConnectionFromPool(String dataSourceName)
throws NamingException, SQLException {
if (dataSourceName== null) {
return null;
}

if (ctx == null) {
init();
}

final DataSource dataSrc = (DataSource) ctx.lookup("java:comp/env/"+dataSourceName);
return dataSrc.getConnection();
}

/**
* Gets the mysql connection via pool.
*
* @return the connection via pool
* @throws NamingException the naming exception
* @throws SQLException the sQL exception
*/
public static Connection getMySqlConnectionViaPool()
               throws NamingException, SQLException{
return getConnectionFromPool("jdbc/mysqldb");
}

/**
* De register database drivers.
*/
public static void deRegisterDatabaseDrivers(){
Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements()) {
Driver driver = drivers.nextElement();
try {           
DriverManager.deregisterDriver(driver); 
LOGGER.info(String.format("Deregistering jdbc driver: %s", driver));
} catch (SQLException e) {         
LOGGER.info(String.format("Error deregistering driver %s", driver), e);
}     
}
}
}

*********************************************************************************
STEP 3: USING CONNECTION

final Connection con= ConnectionManager.getConnection();
final PreparedStatement preStmt= con.prepareStatement("select * from user_profile");

final ResultSet rs=preStmt.executeQuery();

if(rs.next()){
   for(int i=1;i<=rsm.getColumnCount();i++){
       System.out.println("RECORDS: "+rsm.getColumnName(i).toLowerCase()+" |        "+rs.getString(rsm.getColumnName(i)));
    }
}


How to configure 'shared' loader directory in TOMCAT 6.x/7.x/8.x

Follow the below given steps to configure the 'shared' directory in TOMCAT 6.x/7.x/8.x :::

Shared loader config can be found in: <TomcatHome>\conf\catalina.properties. Follow the steps given below to update and configure shared loader.

Follow the steps given below:

1- Create 'shared' directory in tomcat parallel to webapps, bin, logs, conf. etc. directories.

2- Create 'classes' & 'lib' directories inside 'shared' directory.

3- Go to 'conf' directory and open 'catalina.properties' file and modify the value of 'shared.loader' to below given value.

   shared.loader=${catalina.base}/shared/classes,${catalina.base}/shared/lib/*.jar

4- Shared directory is ready to use, no you can directly add your jar files in 'lib' directory and     properties files, configs etc in 'classes' directory.

It will be automatically loaded to the classpath when server will run.

If you are using tomcat within eclipse or any other IDE, then you need to update the 'catalina.properties' found in the eclipse under "Servers" project. See the screen shot below:












Update the "shared.loader" value with full path in the "catalina.properties". See example below:

shared.loader=C:/Personal/EclipseWorkspace/Servers/Tomcat v8.0 Server at localhost-config/shared/classes,C:/Personal/EclipseWorkspace/Servers/Tomcat v8.0 Server at localhost-config/shared/lib/*.jar

Once you are done with above step then created the directories as mentioned above and place the config files which you want to load in classpath. See screen shot below: