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.

JAVA_HOME

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

Path

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.

MAVEN_HOME

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

Path2

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.

		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>

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.

log4j.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC
  "-//APACHE//DTD LOG4J 1.2//EN" "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"
	debug="false">

	<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" />
		</layout>
	</appender>

	<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" />
		</layout>
	</appender>

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

</log4j:configuration>

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 {
		logger.info("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.

Dependency:

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


		<dependency>
			<groupId>org.quartz-scheduler</groupId>
			<artifactId>quartz</artifactId>
			<version>2.1.6</version>
		</dependency> 

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 {

	@Override
	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 java.io.IOException;

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 {

		super.init(config);

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

			JobDetail job = JobBuilder.newJob(QuartzJob.class).withIdentity("QuartzJob").build();
			ScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
												.withIntervalInSeconds(10).repeatForever();
			Trigger trigger = TriggerBuilder.newTrigger()
								.withIdentity("QuartzTrigger")
								.withSchedule(scheduleBuilder).startNow().build();

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

	@Override
	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:

web.xml:


	<servlet>
		<servlet-name>QuartzInitializer</servlet-name>
		<display-name>Quartz Initializer Servlet</display-name>
		<servlet-class>org.quartz.ee.servlet.QuartzInitializerServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet>
		<servlet-name>Quartz Scheduler</servlet-name>
		<display-name>Quartz Scheduler Servlet</display-name>
		<servlet-class>com.devesh.QuartzApp.server.QuartzScheduler</servlet-class>		
		<load-on-startup>2</load-on-startup>
	</servlet>
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:

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.25</version>
		</dependency>

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 {
    		Class.forName("com.mysql.jdbc.Driver");
    		
    		try {
    			conn = DriverManager.getConnection(url+database, username, password);
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
    	} catch (ClassNotFoundException e) {
    		e.printStackTrace();
    	}

    	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:


	<profiles>
  		<profile>
    		<id>DEV</id>
    		<properties>
    			<db.tablename>DEV.PERSON</db.tablename>
    			<db.username>DEV_USERNAME</db.username>
    			<db.password>DEV_PASSWORD</db.password>
  			</properties>
  		</profile>
  		<profile>
    		<id>QA</id>
    		<properties>
    			<db.tablename>QA.PERSON</db.tablename>
    			<db.username>QA_USERNAME</db.username>
    			<db.password>QA_PASSWORD</db.password>
  			</properties>
  		</profile>
  		<profile>
    		<id>PROD</id>
    		<properties>
    			<db.tablename>PROD.PERSON</db.tablename>
    			<db.username>PROD_USERNAME</db.username>
    			<db.password>PROD_PASSWORD</db.password>
  			</properties>
  		</profile>
	</profiles>

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:


			<plugin>
 				<groupId>org.apache.maven.plugins</groupId>
 				<artifactId>maven-resources-plugin</artifactId>
 				<version>2.3</version>
 				<configuration>
   					<encoding>UTF-8</encoding>
 				</configuration>
			</plugin> 				
			

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:

    
	<build>	
		<resources>
	    	<resource>
   				<directory>src/main/resources</directory>
   				<filtering>true</filtering>
 			</resource>
		</resources>
	</build>

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 config.properties in src/main/resources. Now modify the file to include the variables that we defined in pom.xml. The modified config.properties file will look like this:


DatabaseTableName=${db.tablename}
DatabaseUsername=${db.username}
DatabasePassword=${db.password}

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


target/yourwebapp/WEB-INF/classes/config.properties

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


DatabaseTableName=QA.PERSON
DatabaseUsername=QA_USERNAME
DatabasePassword=QA_PASSWORD