Showing posts with label resource. Show all posts
Showing posts with label resource. Show all posts

Tuesday, 12 July 2022

Closeable vs AutoCloseable in Java


a.   Closeable interface is introduced in Java 1.5, where as AutoCloseable interface is introduced in Java 1.7.

 

b.   Closeable interface extends AutoCloseable interface.

 

AutoCloseable.java

public interface AutoCloseable {

    void close() throws Exception;

}

 

Closeable.java

public interface Closeable extends AutoCloseable {

    public void close() throws IOException;

}

 

c.    Closeable.close method is restricted to throw IOException, where as AutoCloseable.close method can throw any Exception.

 

d.   calling this AutoCloseable.close method more than once may have some visible side effect, unlike Closeable.close which is required to have no effect if called more than once.

 


 

Closeable, AutoCloseable and try-with-resources statement

 

What is a resource?

Any object that implements java.lang.AutoCloseable interface is a Resource.

 

When you declare the resources using try with resources statement, then the resources will be closed at the end of try-with-resources statement. Following application confirms the same.

 

ResourcesDemo.java

package com.sample.app;

import java.io.Closeable;
import java.io.IOException;

public class ResourcesDemo {

	private static class MyCloseable implements Closeable {

		@Override
		public void close() throws IOException {
			System.out.println("Closing MyCloseable object");
		}

	}

	private static class MyAutoCloseable implements AutoCloseable {

		@Override
		public void close() throws Exception {
			System.out.println("Closing MyAutoCloseable object");
		}

	}

	public static void main(String[] args) {

		System.out.println("Start Execution........");

		try (MyCloseable myCloseable = new MyCloseable(); 
				MyAutoCloseable myAutoCloseable = new MyAutoCloseable();) {
			// Do some work

		} catch (Exception e) {
			e.printStackTrace();
		}

		System.out.println("End Execution........");

	}

}

 

Output

Start Execution........
Closing MyAutoCloseable object
Closing MyCloseable object
End Execution........

 

   

You may like

Interview Questions

How to call super class method from sub class overriding method?

Can an enum has abstract methods in Java?

Can enum implement an interface in Java?

What happen to the threads when main method complete execution

Why System.out.println() is not throwing NullPointerException on null references?

Why should we restrict direct access to instance properties?

Wednesday, 8 April 2020

Junit: Read resource file from src/test/resources

Below snippet is used to read a file from src/test/resources folder.

public File getResourceFile(String fileName) {
         ClassLoader classLoader = getClass().getClassLoader();
         return new File(classLoader.getResource(fileName).getFile());
}

For example, create config.properties file under src/test/resources folder.

config.properties
appVersion=1.23
appName=Chat Server

TestClass.java

package com.sample.app.utils;

import static org.junit.Assert.assertEquals;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

import org.junit.Test;

public class TestClass {

 public File getResourceFile(String fileName) {
  ClassLoader classLoader = getClass().getClassLoader();
  return new File(classLoader.getResource(fileName).getFile());
 }

 @Test
 public void test1() throws IOException {
  File file = getResourceFile("config.properties");

  FileInputStream fin = new FileInputStream(file);

  Properties properties = new Properties();
  properties.load(fin);

  String version = properties.getProperty("appVersion");
  String applicationName = properties.getProperty("appName");

  assertEquals("1.23", version);
  assertEquals("Chat Server", applicationName);
 }
}





Previous                                                    Next                                                    Home

Monday, 16 December 2019

Spring Data Rest: Change the name of Rest Resource

By default, spring data rest follows below pattern while exposing the data from repositories.

http(s)://server:port/baseURI/{plural_form_of_model_class}

For example, if
protocol is http
server is "localhost",
port is 8080
baseURI is "/api", and
model class is "Employee", then below uri is generated by spring data rest.

http://localhost:8080/api/employees

How to change the name of REST resource?
Use @RepositoryRestResource annotation to change the path.

Example
@RepositoryRestResource(path="myemployees")
public interface EmployeeRepository extends CrudRepository<Employee, Integer> {
  .....
  .....
}

Update EmployeeRepository like below.

EmployeeRepository.java
package com.sample.app.repository;

import java.util.List;

import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

import com.sample.app.model.Employee;

@RepositoryRestResource(path="myemployees")
public interface EmployeeRepository extends CrudRepository<Employee, Integer> {

  // SELECT * FROM employee WHERE salary=X
  public List<Employee> findBySalary(double salary);

  // SELECT * FROM employee WHERE lastName=X
  public List<Employee> findByLastName(String lastName);

  // SELECT * FROM employee WHERE age>X
  public List<Employee> findByAgeGreaterThan(int age);

  // SELECT * FROM employee WHERE age=X AND salary=Y
  public List<Employee> findByAgeAndSalary(int age, double salary);

}

Total project structure looks like below.

Run App.java, you can see below messages in console.
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.6.RELEASE)

Hibernate: 
    
    drop table employee if exists
Hibernate: 
    
    drop sequence if exists hibernate_sequence
Hibernate: create sequence hibernate_sequence start with 1 increment by 1
Hibernate: 
    
    create table employee (
       employee_id integer not null,
        age integer,
        first_name varchar(255),
        last_name varchar(255),
        salary double,
        primary key (employee_id)
    )
2019-07-10 11:35:24.618  WARN 11920 --- [           main] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
Hibernate: 
    call next value for hibernate_sequence
Hibernate: 
    insert 
    into
        employee
        (age, first_name, last_name, salary, employee_id) 
    values
        (?, ?, ?, ?, ?)
Hibernate: 
    call next value for hibernate_sequence
Hibernate: 
    insert 
    into
        employee
        (age, first_name, last_name, salary, employee_id) 
    values
        (?, ?, ?, ?, ?)
Hibernate: 
    call next value for hibernate_sequence
Hibernate: 
    insert 
    into
        employee
        (age, first_name, last_name, salary, employee_id) 
    values
        (?, ?, ?, ?, ?)
Hibernate: 
    call next value for hibernate_sequence
Hibernate: 
    insert 
    into
        employee
        (age, first_name, last_name, salary, employee_id) 
    values
        (?, ?, ?, ?, ?)
Hibernate: 
    call next value for hibernate_sequence
Hibernate: 
    insert 
    into
        employee
        (age, first_name, last_name, salary, employee_id) 
    values
        (?, ?, ?, ?, ?)


Open the url "http://localhost:8080/api/myemployees" in browser, you can see all the employee details.


You can download complete working application from this link.

Previous                                                    Next                                                    Home