Java, Maven

How to install Maven on Windows?

1. Install Java Development Kit (JDK)

The most recent version of JDK can be downloaded from Oracle’s website.

Once you have downloaded and installed JDK on your machine, set the ‘JAVA_HOME’ environment variable.


Modify the ‘Path’ environment variable to include ‘JAVA_HOME’


Verify that the Java was installed correctly, by opening the command prompt and running ‘java -version’. This should print the version of Java you have just installed on your machine.

2. Download Apache Maven

Download the most recent version of Maven from the Apache’s site.

Extract the downloaded zip file in the appropriate folder.
Example: C:\Program Files\Apache Software Foundation\apache-maven-3.2.1

3. Set Maven Environment Variables

Set ‘MAVEN_HOME’ environment variable.


Modify the ‘Path’ environment variable to include ‘MAVEN_HOME’


4. Verify

Verify that the Maven is installed correctly, by opening the command prompt and running ‘mvn -version’. This should print the version of Maven you have just installed on your machine.

Java, Logging, Maven

How to configure log4j in Java

Log4j is a simple and flexible logging framework. This post demonstrates how to configure log4j in your application using the XML file. The log4j can also be configured using the properties file. However, now a days configuring log4j using the properties file is considered to be outdated, and it is recommended to use XML file.

Step 1:If you are using Maven, add appropriate log4j dependency in pom.xml.


Step 2:Create log4j.xml file

This is the main config file having all run time configuration used by log4j. This file will have appenders information, log level information and output file names for file appenders.

This file goes into the \resources directory of your project.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC
  "-//APACHE//DTD LOG4J 1.2//EN" "">
<log4j:configuration xmlns:log4j=""

	<appender name="file" class="org.apache.log4j.RollingFileAppender">
		<param name="File" value="../logs/SampleApp.log" />
		<param name="Append" value="true" />
		<param name="Threshold" value="INFO" />
		<param name="MaxFileSize" value="1MB" />
		<param name="MaxBackupIndex" value="1" />
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%-5p %d [%t] %c: %m%n" />

	<appender name="console" class="org.apache.log4j.ConsoleAppender">
		<param name="Threshold" value="INFO" />
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%d{ABSOLUTE} %-5p [%c{1}] %m%n" />

		<appender-ref ref="file" />
		<appender-ref ref="console" />


Step 3:Add loggers in the code

	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(WelcomeServlet.class);
	protected void doGet(
			HttpServletRequest request,
			HttpServletResponse response
	) throws ServletException, IOException {"Welcome in doGet!");

Now when you hit this servlet, you will see ‘Welcome in doGet!’ on your console. Also, when you deploy the application on server and hit the servlet, you will notice a file being created in your server \logs directory with the name ‘SampleApp.log’.

Java, Maven

How to schedule a job using Quartz in Java

Quartz is a richly featured, open source job scheduling library that can be integrated within virtually any Java application. More information about Quartz can be found at this link.


If you are using Maven, add the Quartz dependency to your pom.xml file.


Quartz Job:

Quartz is the job that you want to run after some specific time interval. A sample job class looks like this:

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class QuartzJob implements Job {

	public void execute(JobExecutionContext context) throws JobExecutionException {
		System.out.println("Executing Quartz Job..");

Quartz Trigger/Scheduler:

Quartz Trigger/Scheduler will run your job after specific time interval. A sample trigger/scheduler servlet looks like this:


import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.ScheduleBuilder;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

public class QuartzScheduler extends GenericServlet {

	public void init(ServletConfig config) throws ServletException {


		Scheduler sched;
		try {
			sched = StdSchedulerFactory.getDefaultScheduler();

			JobDetail job = JobBuilder.newJob(QuartzJob.class).withIdentity("QuartzJob").build();
			ScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
			Trigger trigger = TriggerBuilder.newTrigger()

			sched.scheduleJob(job, trigger);
		} catch (SchedulerException e) {

	public void service(
			ServletRequest arg0, 
			ServletResponse arg1
	) throws ServletException, IOException {


The above trigger/scheduler servlet runs the job after every 10 seconds.

We are mostly there. Our job is all set to execute every 10 secs now. Just one last but not least thing. We will have to modify our web.xml file to load our QuartzScheduler servlet on the startup of the application. The web.xml file looks like this:


		<display-name>Quartz Initializer Servlet</display-name>
		<servlet-name>Quartz Scheduler</servlet-name>
		<display-name>Quartz Scheduler Servlet</display-name>
Java, JDBC, Maven, MySQL

MySQL Connection in Java

Here is an example to show how to connect to MySQL database in Java.

First things first. If you are using Maven, please add the MySQL dependency in your pom.xml file. The dependency looks like this:


If you are NOT using Maven, you need to download the MySQL JDBC driver. The driver can be found here. The download contains a JAR file which you need to add to your classpath.

That is it! Here is the code to connect to MySQL database in Java:

    public Connection getMySqlConnection() {
    	String url = "jdbc:mysql://YourHostName:3306/";
		String database = "YourDatabaseName";
		String username = "YourUsername";
		String password = "YourPassword";
		Connection conn = null;
    	try {
    		try {
    			conn = DriverManager.getConnection(url+database, username, password);
    		} catch (SQLException e) {
    	} catch (ClassNotFoundException e) {

    	return conn;
Java, Maven

Managing multiple deployment environments using Maven

In this post, we will discuss how we can manage multiple deployment environments using Maven Profiles and Resource Filtering. Most well organized projects have at least 3 deployment environments – Development, QA and Production. Each environment has its own configurations, such as database connections, resource contents, web service urls, etc. Maven can help to make the deployment for each of the environments very easy.

Maven Profiles

A Profile is the centralized place when you can define your environment specific variables that apply only to one environment but not to others. For example, the table names can be environment specific, that is, the same table can have different names for different environments. For example, the PERSON table can have names like DEV.PERSON, QA.PERSON and PROD.PERSON for Dev, QA and Prod environments, respectively.

Profiles can be specified in pom.xml file or in a separate profile.xml file. For simplicity purposes, we will specify profiles in our pom.xml file.

The pom.xml file looks like this:


In the pom.xml file above, we have defined 3 profiles, namely DEV, QA and PROD. Each profile has environment specific variables and their values.

Resource Filtering

Resource Filtering is nothing but including variables in your resources. These variables, denoted by the ${…} delimiters, can come from the system properties, your project properties, from your filter resources and from the command line. In our case, it will come from pom.xml as we have defined our environment specific variables there.

Maven’s resources plugin takes care of filtering and it must be configured like this in your pom.xml:


Also, we must tell the plugin where the resources are located, add a <filtering> tag to our POM and set it to true like this:


We have set up everything in pom.xml file. Now let’s look at the file where resource filtering will take place. Create a file with the name in src/main/resources. Now modify the file to include the variables that we defined in pom.xml. The modified file will look like this:


Please notice that db.tablename, db.username and db.password are the exact same properties we have defined in the profiles section of pom.xml. Wrapping these properties inside the ${..} notation instructs the resource plugin to perform a substitution of values.

That’s it! We are done, and now we are ready to build our project. Let’s run our project for QA profile. Use

mvn clean install -P QA 

to build your project for QA profile. Make sure you get BUILD SUCCESS message. Now, in order to verify whether the resource filtering was successful or not, go to


If everything was set up correctly, the contents of the file must look like this: