Java Ehcache Simple Example

Ehca  che is an open source framework for caching objects. It is very simple and most widely used.
Here we will see one simple example to put one Student object in to cache and using that object from cache.
See more about Ehcache
1. Add below maven dependency
<dependency>
<groupid>net.sf.ehcache</groupid>
<artifactid>ehcache</artifactid>
<version>2.8.0</version>
</dependency>
2. Create a Pojo class
public class Student implements Serializable {

private static final long serialVersionUID = -8642556460186434431L;
private Integer studId;
private String firstName;
private String lastname;

public Student(
Integer emplId, String firstName, String lastname) {
super();
this.studId = emplId;
this.firstName = firstName;
this.lastname = lastname;
}
// Getters and setters
3. Create ehcache.xml configuration
This file needs to be placed in your resources folder (src/main/resources)
<ehcache name="StudentCache">
<defaultcache diskexpirythreadintervalseconds="120" diskpersistent="false"
diskspoolbuffersizemb="30" eternal="false" maxelementsinmemory="10000"
maxelementsondisk="10000000" memorystoreevictionpolicy="LRU" overflowtodisk="true"
timetoidleseconds="120" timetoliveseconds="120">
<cache eternal="false" maxelementsinmemory="100" maxelementsondisk="0"
memorystoreevictionpolicy="LFU" name="students" timetoidleseconds="120"
timetoliveseconds="0"></cache>
</defaultcache>
</ehcache>
3. Create a class to load cache configuration
package com.vinod.ehcache;

import java.io.InputStream;

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;

/**
 *@authorvinod.kumaran
 *
 */
public class StudentEHCache {

private static final CacheManager cacheManager;
private Ehcache studentCache;

// Loading ehcache config file and creating CacheManager.
static {

ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
InputStream resourceAsStream = contextClassLoader.getResourceAsStream("ehcache.xml");
cacheManager = CacheManager.create(resourceAsStream);
}

public StudentEHCache() {
studentCache = cacheManager.getEhcache("students");
}

/**
    * Creating new Element to hold student object
    *
    *@param id
    *@param student
    */
public void addStudent(Integer id, Student student) {
Element element = new Element(id, student);
studentCache.put(element);
}

/**
    * Method to get Student object using id.
    *
    *@param id
    *@return
    */
public Student getStudent(Integer id) {
Element element = studentCache.get(id);
if (element != null) {
return (Student) element.getValue();
}
return null;
}
}
4. Create a main class to test cache

package com.vinod.ehcache;

/**
 *@authorvinod.kumaran
 *
 */
public class StudentCacheTest {
private StudentEHCache simpleEHCacheExample;

public StudentCacheTest() {
simpleEHCacheExample = new StudentEHCache();
simpleEHCacheExample.addStudent(1, new Student(1, "Vinod", "Bangalore"));

System.out.println(simpleEHCacheExample.getStudent(1));

}

public static void main(String[] args) {
new StudentCacheTest();
}

}
5. Output  
Student [studId=1, firstName=Vinod, lastname=Bangalore]

 

Association/Aggregation/Composition/Generalization simple example

Association

Relationship between two objects (one to one, one to many, many to many etc)

Aggregation

Aggregation is a kind of association, which refers Has a relationships.

Example: Building has a room

 Composition

It is a kind of Aggregation but when an object contains another object the contained object cannot exists without the container object
Example: Room cannot exist without building

Generalization

Generalization refers to Is a relation ship (Inheritance)
Example, Car is a Vehicle, Bus is a Vehicle

 

Email validation using Java Regex

📧 Email Validation Using Java Regular Expressions (Regex)

Topic: Java Regex Pattern for Email Validation


🧩 Overview

In this post, we’ll explore how to validate email addresses in Java using Regular Expressions (Regex).
The regex pattern enforces strict rules for valid email structures — ensuring only properly formatted email IDs are accepted.


🧠 Regex Pattern

^[A-Z0-9._]+@[A-Z0-9-]+\.[A-Z]{2,6}$

🔍 Pattern Breakdown

SymbolMeaningDescription
^Start of the patternEnsures the match begins from the start of the string
[A-Z0-9._]+First partThe local part (before @) must contain uppercase letters (A-Z), digits (0-9), and . or _
@SeparatorSeparates the username and domain parts
[A-Z0-9-]+Second partThe domain name (after @) must contain letters, digits, or hyphens (-)
\.[A-Z]{2,6}Third partThe domain extension must begin with a . followed by 2 to 6 letters (A-Z)
$End of the patternEnsures the match ends at the end of the string

🧩 In simple terms:

The email must look like USERNAME@DOMAIN.TLD,
where:

  • Username = letters, numbers, dots, or underscores

  • Domain = letters or numbers

  • TLD (Top-Level Domain) = 2–6 letters only (e.g., .com, .org, .co.in)


🧰 Java Implementation

Here’s the complete Java example to validate emails using this regex pattern.

package com.vinod.test; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author vinod.kumaran * * Simple email validator using Java Regular Expressions. * * Pattern: ^[A-Z0-9._]+@[A-Z0-9-]+\.[A-Z]{2,6}$ * * ^ = Start of pattern * [A-Z0-9._] = First part: allowed characters before '@' * @[A-Z0-9-] = Second part: allowed characters after '@' * \.[A-Z]{2,6} = Third part: domain extension with 2–6 letters * $ = End of pattern */ public class EmailValidator { // Compile the regex pattern (case-insensitive) public static final Pattern EMAIL_REGEX = Pattern.compile("^[A-Z0-9._]+@[A-Z0-9-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE); public static void main(String[] args) { // Valid email System.out.println(validate("kkvinod@pretechsol.com")); // Invalid email: first part contains '%' System.out.println(validate("kkvin%od@pretechsol.com")); // Invalid email: second part contains '_' System.out.println(validate("kkvinod@prete_chsol.com")); // Invalid email: domain extension > 6 characters System.out.println(validate("kkvinod@pretechsol.comcomcom")); } // Validation method public static boolean validate(String emailAddress) { Matcher matcher = EMAIL_REGEX.matcher(emailAddress); return matcher.find(); } }

🧪 Sample Output

true false false false

✅ Explanation of Results

EmailExpected ResultReason
kkvinod@pretechsol.com✅ trueValid format
kkvin%od@pretechsol.com❌ false% not allowed before @
kkvinod@prete_chsol.com❌ false_ not allowed in domain name
kkvinod@pretechsol.comcomcom❌ falseTLD (extension) exceeds 6 letters 


How to get current GMT and Current Local time in java?

Example

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class GMTExample {
public static void main(String[] args) throws ParseException {

SimpleDateFormat gmtDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss.SSS Z");
gmtDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
String currentGMTDateString = gmtDateFormat.format(new Date());

SimpleDateFormat gmtDateFormat1 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss.SSS Z");
String currentDateString = gmtDateFormat1.format(new Date());

System.out.println("Current GMT=" + currentGMTDateString
+ " Current Local" + currentDateString);

}

}

Output

Current GMT=04-06-2014 07:18:25.939 +0000 Current Local04-06-2014 12:48:25.940 +0530
 

Spring Asynchronous Execution Example

Some situations we required asynchronous executions in our applications, for example sending an email, file transfer these kind of scenarios we no need to wait until all the process are completed. In order to achieve this spring provides API to execute methods asynchronously .
In this example we will use @Async annotations to execute method asynchronously.

1. Create a Component class

package com.vinod.test;

import java.util.concurrent.TimeUnit;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class SendEmail {
@Async
public void sendEmail() {
System.out.println("Send email started::::");
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Send email completed::::");

}
}

2. Create a Service class

package com.vinod.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class EmailService {
@Autowired
private SendEmail sendEmail;

public void sendEmailviaService() {
sendEmail.sendEmail();
}
}

3.Spring configuration xml

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd">

4.Create a Main class

package com.vinod.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AsynchTest {

public static void main(String[] args) {

ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
"springcontext.xml");
System.out.println("Calling send mail bean");
EmailService es = ctx.getBean(EmailService.class);
es.sendEmailviaService();
System.out.println("Called send mail bean and request for send email");

}

}

4.Output

Calling send mail beanCalled send mail bean and request for send emailSend email started::::Send email completed::::

Spring NamedParameterJdbcTemplate Example

NamedParameterJdbcTemplate has basic set of JDBC operations and allowing the use of named parameters rather than traditional '?' placeholders.
We have to set all params in a map and pass the param map while executing the query.

Spring configuration

 	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName"  value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://localhost:3306/springschema"></property>
		<property name="username" value="root"></property>
		<property name="password" value="root"></property>
	</bean>
	
  	<bean id="namdjdbctemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
     <constructor-arg>
        <ref bean="dataSource"/>
     </constructor-arg>    
     </bean>

Main class

package com.pretech.jdbc;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
public class NamedParameterJdbcTemplateExample {
	public static void main(String args[]) {
		ApplicationContext appContext = new ClassPathXmlApplicationContext(
				"SpringConfig.xml");
		NamedParameterJdbcTemplate namdjdbctemplate = (NamedParameterJdbcTemplate) appContext
				.getBean("namdjdbctemplate");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("name", "Shiva");
		paramMap.put("standard", "2st standard");
		List<Map<String, Object>> students = namdjdbctemplate
				.queryForList(
						"select * from student where name=:name and standard=:standard",
						paramMap);
		System.out.println(students);
	}
}

Spring BeanPropertyRowMapper Example

BeanPropertyRowMapper implementation that converts a row into a new instance of the specified mapped target class. The mapped target class must be a top-level class and it must have a default or no-arg constructor.

Spring configuration

	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName"  value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://localhost:3306/springschema"></property>
		<property name="username" value="root"></property>
		<property name="password" value="root"></property>
	</bean>
 	<bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
     <constructor-arg>
        <ref bean="dataSource"/>
     </constructor-arg>    
     </bean>

Main class


ApplicationContext appContext = new ClassPathXmlApplicationContext(
"SpringConfig.xml");
JdbcTemplate template = (JdbcTemplate) appContext
.getBean("jdbctemplate");
Student st = template.queryForObject(
"select * from student where name=?",
new BeanPropertyRowMapper<Student>(Student.class), "Shiva");
System.out.println(st);

Confusion Matrix + Precision/Recall (Super Simple, With Examples)

  Confusion Matrix + Precision/Recall (Super Simple, With Examples) 1) Binary Classification Setup Binary classification means the model p...

Featured Posts