Create Build Run Project Batch File

Create Build Run Project Batch File

This is one of the big task in any project which perform by Senior member in the team. Here Senior member of the team is responsible for set up project from scratch one set up is done he will create build script, deploy script and run script to make project run live on different environment. I never saw no where on the internet which can teach us how to perform this task and writing here to help how this works:

Steps:

Note: We will use Spring framework for this demo with Maven.

  • Create maven project name: RunProjectBatchFile below is complete details of the project:

Create Build Run Project Batch File

  • pom.xml: Look this file seriously everything seems OK except build tag where we are using plug-in which will copy all jar file to lib folder.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.javahonk</groupId>
	<artifactId>RunProjectBatchFile</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>RunProjectBatchFile</name>
	<url>http://maven.apache.org</url>

	<properties>
		<org.springframework.version>4.1.5.RELEASE</org.springframework.version>
		<org.apache.log4j.version>2.1</org.apache.log4j.version>
	</properties>

	<dependencies>

		<!-- Application Context (depends on spring-core, spring-expression, spring-aop, 
			spring-beans) This is the central artifact for Spring's Dependency Injection 
			Container and is generally always defined -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.9</version>
		</dependency>

		<!-- Log4j -->
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-api</artifactId>
			<version>${org.apache.log4j.version}</version>
		</dependency>

		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<version>${org.apache.log4j.version}</version>
		</dependency>

	</dependencies>

	<build>

		<resources>
			<resource>
				<directory>src/main/config</directory>
				<excludes>
					<exclude>*.xml</exclude>
					<exclude>*.properties</exclude>
				</excludes>
			</resource>
			<resource>
				<directory>src/main/resources</directory>
				<excludes>
					<exclude>*.xml</exclude>
					<exclude>*.properties</exclude>
				</excludes>
			</resource>
		</resources>

		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-dependency-plugin</artifactId>
				<version>2.8</version>
				<executions>
					<execution>
						<id>copy-dependencies</id>
						<phase>package</phase>
						<goals>
							<goal>copy-dependencies</goal>
						</goals>
						<configuration>
							<outputDirectory>${project.build.directory}/lib</outputDirectory>
							<overWriteReleases>false</overWriteReleases>
							<overWriteSnapshots>false</overWriteSnapshots>
							<overWriteIfNewer>true</overWriteIfNewer>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>

	</build>

</project>
  • build.sh: This is also very important we will use this file to build project from command line:
#!/bin/sh

#echo "**************************Purging local maven repo**********************"
#mvn dependency:purge-local-repository

echo "**************************Installing Mercury pom/jar on local maven repo example**********************"
#mvn install:install-file -Dfile=./lib/datafabric-common-1.0-SNAPSHOT.jar  -DpomFile=./lib/datafabric-common-1.0-SNAPSHOT.pom 

#mvn install:install-file -Dpackaging=pom -Dfile=./lib/parent-1.0-SNAPSHOT.pom  -DpomFile=./lib/parent-1.0-SNAPSHOT.pom 

echo "**************************Building Some Project where is with different pom name**********************"
#cd ../OTCParent
#mvn -f parent-pom.xml clean compile install

echo "*************************Building RunProjectBatchFile***********************"
#If you want to move one foler up to Common project folder cd ../CommonProject 
mvn clean compile install
  • deployment.sh: This file will be use for deployment to deployment folder:
#! /bin/sh

cd ../../..
WORK_DIR=`pwd`
echo "working directory $WORK_DIR"

# pass this as argument
DEPLOYMENT_DIR=$WORK_DIR/../deployment	
echo "deployment directory $DEPLOYMENT_DIR"

 if [ -d "$DEPLOYMENT_DIR" ]
  then
   echo "folder $DEPLOYMENT_DIR exists. deleting it for clean deployment"   
   rm -rf  $DEPLOYMENT_DIR
fi

mkdir $DEPLOYMENT_DIR


# Multiple proejct example: PROJECT_LIST=(Project1 Project2 Project2)
PROJECT_LIST=(RunProjectBatchFile)

for PROJECT_NAME in  ${PROJECT_LIST[@]}
do 

	echo "Project Name >> $PROJECT_NAME"
		
	mkdir $DEPLOYMENT_DIR/$PROJECT_NAME
	mkdir $DEPLOYMENT_DIR/$PROJECT_NAME/lib
	mkdir $DEPLOYMENT_DIR/$PROJECT_NAME/scripts/
	mkdir $DEPLOYMENT_DIR/$PROJECT_NAME/runWindow/
	mkdir $DEPLOYMENT_DIR/$PROJECT_NAME/logs
	mkdir $DEPLOYMENT_DIR/$PROJECT_NAME/config
	
	echo "copying jar into $DEPLOYMENT_DIR/$PROJECT_NAME/lib/ ..."
	cp $PROJECT_NAME/target/lib/* $DEPLOYMENT_DIR/$PROJECT_NAME/lib/
	cp $PROJECT_NAME/target/*.jar $DEPLOYMENT_DIR/$PROJECT_NAME/lib/
	
	echo "copying scripts into $DEPLOYMENT_DIR/$PROJECT_NAME/scripts/ ..."
	cp $PROJECT_NAME/scripts/deployment/* $DEPLOYMENT_DIR/$PROJECT_NAME/scripts/
	
	echo "copying xml and properties file to $DEPLOYMENT_DIR/$PROJECT_NAME/config/ ..."
	cp $PROJECT_NAME/src/main/config/* $DEPLOYMENT_DIR/$PROJECT_NAME/config/
	cp $PROJECT_NAME/src/main/resources/* $DEPLOYMENT_DIR/$PROJECT_NAME/config/
	
	echo "copying runtime window file to  $DEPLOYMENT_DIR/$PROJECT_NAME/runWindow/"
	cp $PROJECT_NAME/scripts/runWindow/* $DEPLOYMENT_DIR/$PROJECT_NAME/runWindow/	
	
	echo "copying runtime file to  $DEPLOYMENT_DIR/$PROJECT_NAME/runWindow/"
	#Other folder copy example: cp Parent/scripts/runtime/* $DEPLOYMENT_DIR/$PROJECT_NAME/scripts/
	
done;


echo "copying windows task file to $DEPLOYMENT_DIR/window_task/"
mkdir $DEPLOYMENT_DIR/window_task/
# Window take copy example: cp -r Parent/scripts/window_task/* $DEPLOYMENT_DIR/window_task/

echo "exiting after completion of deployment"
exit 0
  • run-script.bat: Batch file which will be use to run the project:
@echo off

set CURRENT_DIR="%~dp0"
cd  %CURRENT_DIR%
echo %JAVA_HOME%

set LOGGING_DIR=..\
set APP_NAME=JavaHonk
set ENV=UAT
set PROCESS_NAME=RunProjectBatchFile

rem VM arguments 
set VMARGS=-Dlogging.dir=%LOGGING_DIR% -Dapp.name=%APP_NAME% -Denvironment.target=%ENV% -DPROCESS_NAME=%PROCESS_NAME%

set CLASSPATH=..\config\;..\lib\*

rem launcher class for application
set JAVA_MAIN=com.javahonk.RunApplication

set CMD=%JAVA_HOME%\bin\java %VMARGS% -cp %CLASSPATH% %JAVA_MAIN%
echo %CMD%

"%JAVA_HOME%"\bin\java %VMARGS% -cp %CLASSPATH% %JAVA_MAIN%

As you see in the project structure we have very simple maven project with two class: RunApplication.java main file to run the application and ValidateBuild where we have one method which will print “Build is working!!!” on th console to verify the application if everything is working as expected. Please have these class below:

  • RunApplication.java:
package com.javahonk;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class RunApplication {
	
	private static final Logger LOGGER = LogManager.getLogger(RunApplication.class.getName());

	public static void main(String[] args){
		
		ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
		
		ValidateBuild validateBuild = (ValidateBuild)context.getBean(ValidateBuild.class);
		
		LOGGER.info(validateBuild.isBuildWorking());
		
		((AbstractApplicationContext)context).close();
		
	}
	
}
  • ValidateBuild.java:
package com.javahonk;

import org.springframework.beans.factory.annotation.Value;

public class ValidateBuild {
	
	@Value("${build.working}")
	private String buildWorking;

	public String isBuildWorking() {
		return buildWorking;
	}

}

As you see in above class we have one method where it read variable value from message.properties file.

  • message.properties: To keep message in use in classes
build.working=Build is working!!!
  • log4j2.xml: For logging
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">

	<Properties>
		<Property name="envrionment.target">DEV</Property>
	</Properties>

	<Properties>
		<Property name="logging.dir">./</Property>
	</Properties>

	<Appenders>
		<Console name="Console" target="SYSTEM_OUT">
			<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
		</Console>

		<RollingFile name="RollingFile"
			fileName="./log/rolling-file.log"	filePattern="${sys:logging.dir}/logs/rolling-file-%d{yyyy-MM-dd}-%i.log">
			<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
			<!-- TODO:Change to time based policy -->
			<Policies>
				<TimeBasedTriggeringPolicy interval="1"	modulate="true" />
				<SizeBasedTriggeringPolicy size="100 MB" />
			</Policies>
			<DefaultRolloverStrategy max="4" />
		</RollingFile>
	</Appenders>

	<Loggers>
		<Root level="info">
			<AppenderRef ref="Console" />
			<!-- <AppenderRef ref="file" /> -->
			<AppenderRef ref="RollingFile" />
		</Root>
	</Loggers>
</Configuration>
  • spring-context.xml: As we are using Spring as framework for this application so this is main file which works as container:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">
	
	<context:annotation-config />
	<context:component-scan base-package="com.javahonk" />
	
	<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:message/message.properties</value>
				<value>test.properties</value>	
				<!-- <value>${environment.target}.properties</value> -->			
			</list>
		</property>
		<property name="ignoreUnresolvablePlaceholders" value="true"/>
	</bean>
	
	<bean id="validateBuild" class="com.javahonk.ValidateBuild"/>
	
</beans>

That’t it. Now go to command prompt CD to you project location then to to deployemnt directory and in my case it’s as below and type below command and press enter maven will start building the project:

eclipse-jee-luna-R-win32\eclipse\workspace\RunProjectBatchFile>build.sh

  • Once its done you will see below success message on the console:
[INFO] Copying spring-beans-4.1.5.RELEASE.jar to C:\Users\Java\JavaHonk\eclipse-jee-luna-R-win32\eclipse\workspace\RunProjectBatchFile\t
arget\lib\spring-beans-4.1.5.RELEASE.jar
[INFO] Copying log4j-core-2.1.jar to C:\Users\Java\JavaHonk\eclipse-jee-luna-R-win32\eclipse\workspace\RunProjectBatchFile\target\lib\lo
g4j-core-2.1.jar
[INFO] Copying log4j-api-2.1.jar to C:\Users\Java\JavaHonk\eclipse-jee-luna-R-win32\eclipse\workspace\RunProjectBatchFile\target\lib\log
4j-api-2.1.jar
[INFO]
[INFO] --- maven-install-plugin:2.4:install (default-install) @ RunProjectBatchFile ---
[INFO] Installing C:\Users\Java\JavaHonk\eclipse-jee-luna-R-win32\eclipse\workspace\RunProjectBatchFile\target\RunProjectBatchFile-0.0.1
-SNAPSHOT.jar to C:\Users\Java\.m2\repository\com\javahonk\RunProjectBatchFile\0.0.1-SNAPSHOT\RunProjectBatchFile-0.0.1-SNAPSHOT.jar

[INFO] Installing C:\Users\Java\JavaHonk\eclipse-jee-luna-R-win32\eclipse\workspace\RunProjectBatchFile\pom.xml to C:\Users\Java\.m2\
repository\com\javahonk\RunProjectBatchFile\0.0.1-SNAPSHOT\RunProjectBatchFile-0.0.1-SNAPSHOT.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4.276 s
[INFO] Finished at: 2015-08-20T01:17:32-04:00
[INFO] Final Memory: 16M/38M
[INFO] ------------------------------------------------------------------------

C:\Users\Java\JavaHonk\eclipse-jee-luna-R-win32\eclipse\workspace\RunProjectBatchFile>
  • Now cd to deployment folder and execute below command:

eclipse-jee-luna-R-win32\eclipse\workspace\RunProjectBatchFile\scripts\deployment>deployment.sh

  • This will deploy files to the deployment directory and it’s location will be one folder up from project location.
  • Now we are all done cd to below folder and execute below command you will see “Build is working!!!” message on the console:

eclipse-jee-luna-R-win32\eclipse\deployment\RunProjectBatchFile\runWindow>run-script.bat

download Download Project: RunProjectBatchFile

Leave a Reply

Your email address will not be published. Required fields are marked *