JAX-RS RESTFul Service with Jetty server

In this example we will see simple JAX-RS restful web service using Jetty service and Jersey implementaion of JAX-RS API

1. Create a maven project using the quick start archetype.

2. Add below dependencies in your pom.xml file
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>9.2.3.v20140905</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>9.2.3.v20140905</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-jetty-http</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>2.7</version>
</dependency>
3. Create a simple service class which returns Hello world
package com.vinod.vinod_rest_examples;


import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/MyFirstRest")
public class MyFirstRest {

@GET
@Path("helloworld")
@Produces(MediaType.APPLICATION_JSON)
public String test() {
return "Hello world";
}
}
4. Create a java class to start jetty server
package com.vinod.vinod_rest_examples;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

/**
 * Hello world!
 *
 */
public class App {
public static void main(String[] args) {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");

Server jettyServer = new Server(8080);
jettyServer.setHandler(context);

ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);

// Setting pacakge name over here to load services
jerseyServlet.setInitParameter("jersey.config.server.provider.packages",
"com.vinod.vinod_rest_examples");
try {
jettyServer.start();
jettyServer.join();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
jettyServer.destroy();
}
}
}
5. Hit the url
 
6. Output
Hello world

 
8. What is next?.. let us see how to add Request Filter over here.
Filters can modify inbound and outbound requests and responses such as modification of headers, entity and other request/response parameters
package com.vinod.vinod_rest_examples;

import java.io.IOException;

import javax.annotation.Priority;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.ext.Provider;

@Provider
@Priority(value = 1)
public class MyRequestFilter implements ContainerRequestFilter {

public void filter(ContainerRequestContext requestContext) throws IOException {
System.out.println("Executing request filter" + requestContext.getUriInfo().getPath());
}

}
filter output

Executing request filter/MyFirstRest/helloworld

 

Spring Validation Framework Example

Spring provides an api to validate data using its validation framework. There is an interface org.springframework.validation.Validator will handles the data validation. Here is one simple example to validate user details.
1. Create a User bean
package com.vinod.spring;

import org.springframework.stereotype.Component;

@Component
public class User {
private String userName;
private String password;

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

}
 
1. Create a Validator class
package com.vinod.spring;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

@Component
public class UserValidator implements Validator {

public boolean supports(Class clazz) {
return User.class.equals(clazz);
}

public void validate(Object target, Errors errors) {
User user = (User) target;

ValidationUtils.rejectIfEmpty(errors, "userName", "UserNamerequired",
"UserName should not be blank");
ValidationUtils.rejectIfEmpty(errors, "password", "PasswordRequired",
"password should not be blank");
if (user.getUserName() != null && user.getUserName().length() < 4) {
errors.rejectValue("UserName", "errormsg.UserName",
"UserName should not be less than 4 characteros");
}
if (user.getPassword() != null && user.getPassword().length() < 4) {
errors.rejectValue("password", "errormsg.password",
"Password should not be less then 4 characters");
}
}

}

3. Spring Configuration

<beans xmlns:context="http://www.springframework.org/schema/context" 
xmlns:p="http://www.springframework.org/schema/p"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans" 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">

<context:component-scan base-package="com.vinod">
<task:annotation-driven>
</task:annotation-driven></context:component-scan></beans>

4. Main class

package com.vinod.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.validation.ValidationUtils;

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

public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext(
"spring-context.xml");
User user = (User) context.getBean(User.class);
user.setUserName("Vin");
user.setPassword("Pas");
UserValidator userValidator = (UserValidator) context
.getBean(UserValidator.class);
BindException errors = new BindException(user, User.class.getName());

ValidationUtils.invokeValidator(userValidator, user, errors);

if (errors.hasErrors()) {
System.out.println("Errors: " + errors.getErrorCount());
for (ObjectError objectErrors : errors.getAllErrors()) {
System.out.println(objectErrors.getDefaultMessage());
}
}

}

}

5. Output

Errors: 2
UserName should not be less than 4 characteros

Password should not be less then 4 characters

Log4j Simple xml configuration example

1. Add below dependency in your project

<dependency>
<groupid>log4j</groupid>
<artifactid>log4j</artifactid>
<version>1.2.17</version>
</dependency>

2. Create a log4j.xml file

<log4j:configuration debug="true" xmlns:log4j="http://jakarta.apache.org/log4j/">

<appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{dd MMM yyyy HH:mm:ss} %5p %c{1} - %m%n">
</layout>
</appender>

<appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
<param name="append" value="false">
<param name="file" value="mylog.log">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ABSOLUTE} %-5p [%c{1}] %m%n">
</layout>
</appender>

<root>
<level value="INFO">
<appender-ref ref="consoleAppender">
<appender-ref ref="fileAppender">
</appender-ref></appender-ref></level></root>
</log4j:configuration>
This should place in your resource folder

3. Create a main class to test

package com.vinod.test;

import org.apache.log4j.Logger;
public class Log4jTest {
static Logger logger = Logger
.getLogger(Log4jTest.class.getName());
public static void main(String[] args) {
logger.info("Info test");
logger.debug("Debug test");
}

}

4. Ouput - mylog.log

 23:32:01,101 INFO [Log4jTest] Info test

 

Spring Quartz Scheduler- Wiring up jobs using triggers and the SchedulerFactoryBean

Spring provides the feature of scheduling task. In this example we will see how to create a simple helloworld task and schedule it using Spring.

Dependencies

<dependency>
<groupid>org.quartz-scheduler</groupid>
<artifactid>quartz</artifactid>
<version>1.8.5</version>
</dependency>
<!-- QuartzJobBean in spring-context-support.jar -->
<dependency>
<groupid>org.springframework</groupid>
<artifactid>spring-context-support</artifactid>
<version>3.0.4.RELEASE</version>
</dependency>

<dependency>
<groupid>org.springframework</groupid>
<artifactid>spring-tx</artifactid>
<version>3.0.4.RELEASE</version>
</dependency>

<dependency>
<groupid>org.springframework</groupid>
<artifactid>spring-core</artifactid>
<version>3.2.4.RELEASE</version>
</dependency>
<dependency>
<groupid>org.springframework</groupid>
<artifactid>spring-context</artifactid>
<version>3.2.4.RELEASE</version>
</dependency>
JobDetail class
package com.vinod.spring;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class HelloworldJob extends QuartzJobBean {

@Override
protected void executeInternal(JobExecutionContext arg0)
throws JobExecutionException {
System.out.println("Executing helloworld job.......");
}

}


Spring Configuration

<bean class="org.springframework.scheduling.quartz.JobDetailBean" id="helloworldjob">
<property name="jobClass" value="com.vinod.spring.HelloworldJob">
</property></bean>


<bean class="org.springframework.scheduling.quartz.CronTriggerBean" id="helloWorldJobTrigger">
<property name="jobDetail" ref="helloworldjob">
<property name="cronExpression" value="0 0/1 * 1/1 * ? *">
</property></property></bean>


<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean" id="schedulerFactoryBean">
<property name="jobDetails">
<list>
<ref bean="helloworldjob">
</ref></list>
</property>
<property name="triggers">
<list>
<ref bean="helloWorldJobTrigger">
</ref></list>
</property>
</bean>
Note: Use http://www.cronmaker.com/ to generate cron expressions (in this example task scheduled for every minutes)


Main class

package com.vinod.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

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

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"spring-job-context.xml");
}

}
Output
Executing helloworld job.......
Executing helloworld job.......
Executing helloworld job.......
Executing helloworld job.......
Executing helloworld job.......
Executing helloworld job.......
Executing helloworld job.......
Executing helloworld job.......
Executing helloworld job.......
Executing helloworld job.......
Executing helloworld job.......
Executing helloworld job.......
Executing helloworld job.......
Executing helloworld job.......
Executing helloworld job.......
Executing helloworld job.......
Executing helloworld job.......
Executing helloworld job.......
Executing helloworld job.......
Executing helloworld job.......
Executing helloworld job.......
Executing helloworld job.......
Executing helloworld job.......
Executing helloworld job.......
Executing helloworld job.......
Executing helloworld job.......
Executing helloworld job.......

 

Java concurrent lock example

🔐 Understanding Java Concurrent Locks (java.util.concurrent.locks.Lock)

When writing multi-threaded programs in Java, thread safety becomes a key concern.
Traditionally, developers have used the synchronized keyword to protect critical sections.
However, Java’s java.util.concurrent.locks.Lock interface offers greater flexibility and control for concurrency management.


⚙️ What Is a Lock?

A Lock is a more advanced synchronization mechanism than the synchronized block.
It allows explicit acquisition and release of locks and supports features unavailable in synchronized blocks, such as:

  • Timed and interruptible lock acquisition,

  • Separate lock/unlock methods across scopes,

  • Fairness policies, and

  • Better performance in high-contention scenarios.

Since Lock is an interface, you must use one of its implementations —
most commonly ReentrantLock.


🔁 Lock vs. synchronized — Key Differences

FeaturesynchronizedLock (e.g., ReentrantLock)
ScopeMust be fully contained within one method or blocklock() and unlock() can be called in different methods
TimeoutCannot wait with timeouttryLock(long time, TimeUnit unit) allows timeout
InterruptibilityCannot be interrupted while waitingLock acquisition can be interrupted
Fairness PolicyNot configurableCan specify fairness (FIFO order)
PerformanceSimpler but less flexibleBetter for highly concurrent applications

💻 Example — Using ReentrantLock for Thread Safety

Let’s see how to use a concurrent lock to safely simulate email sending from multiple threads.

📁 Code Example

package com.vinod.thread; import java.util.Date; import java.util.concurrent.*; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Demonstrates how to use ReentrantLock for thread-safe operations. * * @author vinod */ public class ConcurrentLockExample { public static void main(String[] args) { EmailProcessor emailProcessor = new EmailProcessor(); int n = 25; ExecutorService exec = Executors.newFixedThreadPool(n); for (int i = 0; i < n; ++i) { exec.submit(new SendEmailThread(emailProcessor)); } exec.shutdown(); } } /** * Service that simulates sending emails using a shared resource. */ class EmailProcessor { private final Lock emailLock = new ReentrantLock(); public void sendEmail() { emailLock.lock(); // Acquire lock before entering critical section try { System.out.println(Thread.currentThread().getName() + " - Sending email at " + new Date()); Thread.sleep(1000); // Simulate email sending delay } catch (InterruptedException e) { Thread.currentThread().interrupt(); System.err.println("Email sending interrupted"); } finally { System.out.println(Thread.currentThread().getName() + " - Email sending completed"); emailLock.unlock(); // Always release lock in finally block } } } /** * Callable task that sends an email via EmailProcessor. */ class SendEmailThread implements Callable<String> { private final EmailProcessor emailProcessor; public SendEmailThread(EmailProcessor processor) { this.emailProcessor = processor; } @Override public String call() { emailProcessor.sendEmail(); return "Success"; } }

🧾 Example Output

pool-1-thread-1 - Sending email at Sat Nov 02 12:35:21 PST 2025 pool-1-thread-1 - Email sending completed pool-1-thread-2 - Sending email at Sat Nov 02 12:35:22 PST 2025 pool-1-thread-2 - Email sending completed pool-1-thread-3 - Sending email at Sat Nov 02 12:35:23 PST 2025 pool-1-thread-3 - Email sending completed ...

Each thread waits for the lock to be released before sending its email, ensuring thread safety even when multiple threads try to access the shared resource simultaneously.


🧠 How It Works — Step by Step

  1. Main thread creates an ExecutorService with 25 threads.

  2. Each thread submits a SendEmailThread task.

  3. Every task calls emailProcessor.sendEmail().

  4. Inside sendEmail(), the ReentrantLock ensures only one thread executes the email-sending block at a time.

  5. After sending, the lock is released in the finally block, allowing another thread to proceed.


🧩 Why Use Locks Instead of synchronized

While synchronized is simpler for basic use cases, Lock provides:

  • More precise control over locking and unlocking.

  • Ability to back off after waiting (e.g., using tryLock()).

  • Better visibility and diagnostics for debugging concurrent issues.


🧱 Example with Timeout (Optional Enhancement)

Here’s how you can use tryLock() with a timeout:

if (emailLock.tryLock(2, TimeUnit.SECONDS)) { try { // Perform safe operations } finally { emailLock.unlock(); } } else { System.out.println("Could not acquire lock, skipping..."); }

This avoids blocking indefinitely if another thread holds the lock for too long.


🧭 Key Takeaways

ConceptSummary
Lock InterfaceProvides explicit locking control
ReentrantLockMost commonly used Lock implementation
Best PracticeAlways unlock in a finally block
tryLock()Enables timeout-based lock attempts
When to UseHigh concurrency scenarios where synchronized is too restrictive


 

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