Archive | January 2017

Building Docker Images – Maven

Summary:
Step 1: Create a Dockerfile Step 2: Build the image Step 3: List the images: Step 4: Tag the images Step 5: Login to docker Step 6: Push the Image

Detailed Steps:
After creating your web application till Controller Layer,
Step 1: Add Dockerfile(file) in src -> main -> Dockerfile

FROM java:8
VOLUME /tmp
ADD lmsapp-web-0.0.1-SNAPSHOT.jar app.jar
ADD setenv.sh setenv.sh
ADD setenv2.sh setenv2.sh
CMD ./setenv.sh
RUN bash -c ‘touch /app.jar’
ENTRYPOINT [“java”,”-Djava.security.egd=file:/dev/./urandom”,”-jar”,”/app.jar”]

Step 2: Changes in properties of pom.xml

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
		<docker.image.prefix>lmsapp</docker.image.prefix>
	</properties>

Step 3: Changes in plugin of pom.xml

<plugin>
				<groupId>com.spotify</groupId>
				<artifactId>docker-maven-plugin</artifactId>
				<version>0.4.13</version>
				<configuration>
					<serverId>docker-hub</serverId>
					<imageName>${docker.image.prefix}/${project.artifactId}</imageName>
					<dockerDirectory>src/main/docker</dockerDirectory>
					<resources>
						<resource>
							<targetPath>/</targetPath>
							<directory>${project.build.directory}</directory>
							<include>${project.build.finalName}.jar</include>
						</resource>
					</resources>
				</configuration>
			</plugin>

Note : After changes, pom.xml looks like,

<?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.lmsapp</groupId>
	<artifactId>lmsapp-web</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>lmsapp-web</name>
	<description>leave management system</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.4.3.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
		<docker.image.prefix>lmsapp</docker.image.prefix>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>


		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-dbcp2</artifactId>

		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>6.0.5</version>
		</dependency>



	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>com.spotify</groupId>
				<artifactId>docker-maven-plugin</artifactId>
				<version>0.4.13</version>
				<configuration>
					<serverId>docker-hub</serverId>
					<imageName>${docker.image.prefix}/${project.artifactId}</imageName>
					<dockerDirectory>src/main/docker</dockerDirectory>
					<resources>
						<resource>
							<targetPath>/</targetPath>
							<directory>${project.build.directory}</directory>
							<include>${project.build.finalName}.jar</include>
						</resource>
					</resources>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

Step 4: Right click project -> Run as -> Maven install

Step 5: Right click project -> Run as -> Maven Build(2nd option)

Step 6: In goals, type -> clean package docker:build -> Click Run

Step 7: Once BUILD SUCCESS, open command prompt and execute,

C:\Users\EP>docker images

C:\Users\EP>docker system df

C:\Users\EP>docker system prune

C:\Users\EP>docker run -p 8080:8080 -t lmsapp/lmsapp-web

Step 8: Access localhost:8080/employees/(url returning JSON)

Step 9: To list containers,
C:\Users\EP>docker ps
Note the Container Id(525ed17a65d3)

Step 10: To stop one or more containers,
C:\Users\EP>docker stop 525ed17a65d3

Step 11: To remove one or more containers,
C:\Users\EP>docker rm 525ed17a65d3

Step 12: C:\Users\EP>docker tag 525ed17a65d3 jananiv/lmsapp-web:latest

Step 13: C:\Users\EP>docker login

Step 14: docker push jananiv/lmsapp-web

Advertisements

Convert Sql Time and Date from/to Java LocalTime and LocalDate

Food

package com.revature.model;

import java.time.LocalDate;
import java.time.LocalTime;

import lombok.Data;

@Data
public class Food {

	private int id;
	private String type;
	private LocalDate createdDate;
	private LocalTime startTime;
	private LocalTime endTime;

}

FoodDAO

package com.revature.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;

import com.revature.model.Food;
import com.revature.util.ConnectionUtil;

public class FoodDAO {
	JdbcTemplate jdbcTemplate = ConnectionUtil.getJdbcTemplate();

	public void save(Food food) {

		String sql = "insert into food(type,created_date,start_time,end_time) values(?,?,?,?)";
		Object[] params = { food.getType(), food.getCreatedDate(), food.getStartTime(), food.getEndTime() };
		int rows = jdbcTemplate.update(sql, params);
		System.out.println("No of rows inserted: " + rows);

	}

	public List<Food> list() {

		String sql = "select id,type,created_date,start_time,end_time from food";
		List<Food> list = jdbcTemplate.query(sql, (rs, rowNum) -> {
			Food food = convert(rs);
			return food;
		});
		return list;

	}

	static Food convert(ResultSet rs) throws SQLException {
		Food food = new Food();
		food.setId(rs.getInt("id"));
		food.setType(rs.getString("type"));
		food.setCreatedDate(rs.getDate("created_date").toLocalDate());
		food.setStartTime(rs.getTime("start_time").toLocalTime());
		food.setEndTime(rs.getTime("end_time").toLocalTime());
		return food;
	}
}

TestFoodDAO

package com.revature.dao;

import java.time.LocalDate;
import java.time.LocalTime;
import java.util.List;

import com.revature.model.Food;

public class TestFoodDAO {
	public static void main(String[] args) {
		Food food = new Food();
		food.setType("LUNCH");
		food.setCreatedDate(LocalDate.now());
		food.setStartTime(LocalTime.parse("11:15:00"));
		food.setEndTime(LocalTime.parse("15:00:00"));

		FoodDAO foodDAO = new FoodDAO();
		foodDAO.save(food);

		List<Food> foodList = foodDAO.list();
		for (Food f : foodList) {
			System.out.println(f);
		}

	}
}

Spring JdbcTemplate – Calling Procedure

Procedure

DROP PROCEDURE IF EXISTS pr_check_menu_availability;

DELIMITER $$

CREATE PROCEDURE pr_check_menu_availability(IN in_name VARCHAR(20), OUT out_status VARCHAR(20))
BEGIN
 SET out_status='Not Available';
 IF in_name IN(SELECT NAME FROM menu)
 THEN 
  SET out_status='Available';
 END IF;
 END $$
 
 DELIMITER;
 
 CALL pr_check_menu_availability('Idli',@status);
 
 SELECT @status;

DAO

public String checkMenuAvailability(String name) {
		SimpleJdbcCall call = new SimpleJdbcCall(jdbcTemplate).withProcedureName("pr_check_menu_availability")
				.declareParameters(new SqlParameter("in_name", Types.VARCHAR),
						new SqlOutParameter("out_status", Types.VARCHAR));
		call.setAccessCallParameterMetaData(false);
		SqlParameterSource in = new MapSqlParameterSource().addValue("in_name", name);
		Map<String, Object> execute = call.execute(in);
		String status = (String) execute.get("out_status");
		return status;

	}

TestDAO

MenuDAO dao = new MenuDAO();
String status = dao.checkMenuAvailability("idli");
System.out.println(status);

Spring JdbcTemplate – Single/Multiple Column Result

Single Column Result

Find The Number of Menu Items
DAO

public Long findCount() {
Long menuCount = jdbcTemplate.queryForObject("SELECT COUNT(*) FROM menu", Long.class);
return menuCount;
}

TestDAO

MenuDAO dao = new MenuDAO();
Long count = dao.findCount();
System.out.println(count);

Multiple Column Result

List of Menu Names
DAO

public List<String> findMenuNames() {
List<String> menuNameList = jdbcTemplate.queryForList("SELECT name FROM menu", String.class);
return menuNameList;
}

TestDAO

List<String> menuNames = dao.findMenuNames();
for (String menuName : menuNames) {
	System.out.println(menuName);
}

Spring JdbcTemplate – Call Function

Function

DROP FUNCTION IF EXISTS fn_is_menu_present;

DELIMITER $$

CREATE FUNCTION fn_is_menu_present(in_name VARCHAR(20))
RETURNS BOOLEAN
    
    BEGIN
	RETURN EXISTS(SELECT 1 FROM menu WHERE NAME=in_name);
    END$$

DELIMITER ;

SELECT fn_is_menu_present('idli');

DAO

public Boolean validateMenu(String name) {
String sql = "select fn_is_menu_present(?)";
Boolean isAvailable= jdbcTemplate.queryForObject(sql, new Object[] { name },    Boolean.class);
return isAvailable;
}

TestDAO

MenuDAO dao = new MenuDAO();
Boolean isValid = dao.validateMenu("idli");
System.out.println(isValid);

Lombok Jar Fix

Step 1: Run lombok jar in eclipse workspace

Step 2: Project -> clean and Maven -> Update Project

step 3: Exit and Open Eclipse

 

JDBC – ConnectionUtil

package com.revature.util;

import java.sql.Connection;
import java.sql.DriverManager;

public class ConnectionUtil {
public static Connection getConnection() throws Exception {
String driverName = “com.mysql.jdbc.Driver”;
String url = “jdbc:mysql://localhost:3306/kvcet_db”;
String user = “kvcet_user”;
String password = “kvcet_123456$”;
Class.forName(driverName);
Connection con = DriverManager.getConnection(url, user, password);
return con;
}

}