Reading/Writing Files using FileChannel

Posted on

6db3a-download

There are multiple ways to reading/writing a file in Java. Usually, we used java.lang.IO package to read/write a file but as my last experience with copying a large file size (>256 MB ) into some other file location or on a network.

 

As we also tried to used java.lang.io package to get this job done but we were unable to copy the file in a Network location, there were performance issues.

http://stackoverflow.com/questions/1605332/java-nio-filechannel-versus-fileoutputstream-performance-usefulness

And finally, I got an alternative way to copy a file into a Network location  i.e FileChannel . its provide a better performance than InputStream/OutputStream.

Some interesting points about java.nio or FileChannel:-

  1. it’s a buffer-oriented, means- same Buffer is used to reading / writing so you can move back or forth in the Buffer as you need to.  usee flip() method to get the pointer to next position.
  2. It’s a non-blocking, i.e means a Thread request to reading data from Channel then only get what is currently available in a buffer, if data is not available then rather than blocking until data get available in buffer, Thread goes on and do something else in meantime. The same is true for non-blocking writing. A thread can request that some data be written to a channel, but not wait for it to be fully written. The thread can then go on and do something else in the mean time.
  3. Concurrent processing can be done in FileChannel which is safe for use.
  4. Channels can be read and written asynchronously.

Below example demonstrated how to write into a file using FileChannel.


 import java.io.File;
        import java.io.FileNotFoundException;
        import java.io.IOException;
        import java.io.RandomAccessFile;
        import java.nio.ByteBuffer;
        import java.nio.channels.FileChannel;
        import java.nio.channels.WritableByteChannel;
        
        /**
         * Created by kumajye on 10/01/2017.
         */
        public class FileChannelTest {
            // This is a Filer location where write operation to be done.
            private static final String FILER_LOCATION = "C:\\documents\\test";
            // This is a text message that to be written in filer location file.
            private static final String MESSAGE_WRITE_ON_FILER = "Operation has been committed.";
        
            public static void main(String[] args) throws FileNotFoundException {
                // Initialized the File and File Channel
                RandomAccessFile randomAccessFileOutputFile = null;
                FileChannel outputFileChannel = null;
                try {
                    // Create a random access file with 'rw' permission..
                    randomAccessFileOutputFile = new RandomAccessFile(FILER_LOCATION + File.separator + "readme.txt", "rw");
                    outputFileChannel = randomAccessFileOutputFile.getChannel();
                    //Read line of code one by one and converted it into byte array to write into FileChannel.
                    final byte[] bytes = (MESSAGE_WRITE_ON_FILER + System.lineSeparator()).getBytes();
                    // Defined a new buffer capacity.
                    ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
                    // Put byte array into butter array.
                    buffer.put(bytes);
                    // its flip the buffer and set the position to zero for next write operation.
                    buffer.flip();
                    /**
                     * Writes a sequence of bytes to this channel from the given buffer.
                     */
                    outputFileChannel.write(buffer);
                    System.out.println("File Write Operation is done!!");
        
                } catch (IOException ex) {
                    System.out.println("Oops Unable to proceed file write Operation due to ->" + ex.getMessage());
                } finally {
                    try {
                        outputFileChannel.close();
                        randomAccessFileOutputFile.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
        
                }
        
            }
        
        }


What is requireJS

Posted on

What is RequireJS?

Modular Programming is used to break a large application into smaller blocks of manageable code which are always easy to maintain, readable and reusable, But it’s high cost of managing the dependencies between modules are always a major concern of developers face throughout the application development process.

So RequireJS is one of the most popular Javascript API to manage dependencies between modules and it supports AMD ( Asynchronous Module Definition  ) approach to load the modules and resolved their dependencies.

Benefits of RequireJS.

  • Easy to use and maintain than traditional ways of developing a web application.
  • Minimize the code repetition, Block of code can be easy to reused between the modules.
  • Hassle free of maintaining and keeping the scripts file in correct order.
  • Lazy loading ( Only load what you need, on demand and asynchronously )

Let’s check, how to use RequireJs

Project Hierarchy

 

 

 

 

 

 

Define an Entry point of RequireJS

First, download the latest requirejs library from here and keep it inside lib folder. Now we need to define a html file and could named index.html where RequireJS is loading as shown below.

Here, data-main is a meta attribute for requireJs that defines the initialization point of the application. it’s defined a relative path for the file where to load the RequireJS configuration.

RequireJS also assumes by default that all dependencies are scripts, so it does not expect to see a trailing “.js” suffix on module IDs. RequireJS will automatically add it when translating the module ID to a path.

 

Configure RequireJS

In the file app.js we defined the RequireJS config options and all files are locate under baseUrl, Since baseUrl is a current directory in this demo example but You can define the baseUrl in your application where all scripts files are placed.

How to create modules

Three modules are defined here;

message.js

print.js

aboutus.js

Execute code RequireJS

Once, modules are defined then need to inject the dependencies and call the function.

main.js

Result

We can see the output in the web console.

 

 

Hope you like it. Thanks

Configure an H2 in memory Database in Spring Boot.

Posted on

Spring Boot has great build in support for H2 database so here we will see how to configured in-memory database H2 using Spring Boot.

H2 is an open source embedded database built on java ships in a single .jar file. Therefore you can easily embed an h2 database into your application. H2 Database has a built in the web based console that you can use to interact with the database. You can use H2 database as an in-memory database, embedded database or network database. You can file more details from here.

It’s often convenient to develop applications using an in-memory embedded database. Obviously, in-memory databases do not provide persistent storage; you will need to populate your database when your application starts and be prepared to throw away data when your application ends.

First of all here are the maven dependencies for spring boot to use H2 Database. pom.xml

<?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.spring.boot.example</groupId>
    <artifactId>Spring_H2_Example</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>spring_boot</name>
    <description>Demo project for Spring Boot</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>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.194</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

Here, we created a SQL Schema file and dummy file under resource folder ( main/java/resources ), When our application gets started then it creates table and inserts into it.

sql/schema.sql file

DROP TABLE IF EXISTS User_Details;
create table User_Details (id integer not null auto_increment,
 email varchar(255),
 first_Name varchar(255),
 last_Name varchar(255),
 password varchar(255), primary key (id)
);

sql/data.sql file

INSERT INTO User_Details(email,first_Name,last_Name,password) VALUES ('admin@admin.com','admin','admin','admin');

INSERT INTO User_Details(email,first_Name,last_Name,password) VALUES ('rahul@gmail.com','Rahul','sharma','rahul@ku123123!');

INSERT INTO User_Details(email,first_Name,last_Name,password) VALUES ('shyam_babul@yahoo.com','Sham','babul','shyam#babul!2123');

Since Spring boot can auto configure in-memory database ( h2 ) so you don’t need to provide configuration details unless the application has been configured in other ways. If you see in below application.properties file where it has been configured from where Schema and SQL file should be picked up from resources folder.

application.properties file contains all the required configurations to connect h2 database and run Spring Boot.

# Spring Boot can auto-configured H2 database.

spring.jpa.database=H2
spring.datasource.url=jdbc:h2:mem:test;MODE=Oracle
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.max-active=1
spring.jpa.hibernate.ddl-auto=false
spring.h2.console.enabled=true
spring.h2.console.settings.trace=true
spring.h2.console.settings.web-allow-others=true
spring.h2.console.path=/h2
spring.datasource.schema=classpath*:sql/schema.sql
spring.datasource.data=classpath*:sql/data.sql


# Here, We create a new "local" Datasource for our application using it we can perform 'ddl' and 'dml' operations.
# Hence, it's redundant but we enabled spring data source.

local.datasource.url=jdbc:h2:mem:test;MODE=Oracle
local.datasource.username=sa
local.datasource.password=
local.datasource.driver-class-name=org.h2.Driver
local.datasource.max-active=1

Model Class

package com.spring.boot.example.domain;

public class UserDetails {

    private long id;
    private String email;
    private String first_name;
    private String last_name;
    private String password;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getFirst_name() {
        return first_name;
    }

    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }

    public String getLast_name() {
        return last_name;
    }

    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }

    public String getPassword() {
        return password;
    }

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

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("UserDetails{");
        sb.append("id=").append(id);
        sb.append(", email='").append(email).append('\'');
        sb.append(", first_name='").append(first_name).append('\'');
        sb.append(", last_name='").append(last_name).append('\'');
        sb.append(", password='").append(password).append('\'');
        sb.append('}');
        return sb.toString();
    }
}

Repository Class


package com.spring.boot.example.repo;

import com.spring.boot.example.domain.UserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

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

@Repository
public class UserDetailsRepository {

@Autowired
private JdbcTemplate jdbcTemplate;

public List printUserDetailsData(){
return jdbcTemplate.query("SELECT * FROM USER_DETAILS",new UserDetailsRowMapper());
}

class UserDetailsRowMapper implements RowMapper{

@Override
public UserDetails mapRow(ResultSet resultSet, int i) throws SQLException {
UserDetails userDetails = new UserDetails();
userDetails.setId(resultSet.getInt("id"));
userDetails.setEmail(resultSet.getString("email"));
userDetails.setFirst_name(resultSet.getString("first_Name"));
userDetails.setLast_name(resultSet.getString("last_Name"));
userDetails.setPassword(resultSet.getString("password"));
return userDetails;
}
}
}

Main Class

package com.spring.boot.example;

import com.spring.boot.example.domain.UserDetails;
import com.spring.boot.example.repo.UserDetailsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.List;

@SpringBootApplication(exclude = JmsAutoConfiguration.class)
public class H2MainApp {

    public static void main(String[] args) {
        ConfigurableApplicationContext context =  SpringApplication.run(H2MainApp.class, args);
        List<UserDetails> userDetailsList = context.getBean(UserDetailsRepository.class).printUserDetailsData();
        for(UserDetails userDetails : userDetailsList){
            System.out.println(userDetails);
        }
    }

    @Bean
    @ConfigurationProperties(prefix = "local.datasource")
    public DataSource getDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public JdbcTemplate getJdbcTemplate(@Autowired DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }
}

Output:-

2017-08-12 15:11:57.899 INFO 4956 — [ main] com.spring.boot.example.H2MainApp : Started H2MainApp in 7.839 seconds (JVM running for 8.638)
UserDetails{id=1, email=’admin@admin.com’, first_name=’admin’, last_name=’admin’, password=’admin’}
UserDetails{id=2, email=’rahul@gmail.com’, first_name=’Rahul’, last_name=’sharma’, password=’rahul@ku123123!’}
UserDetails{id=3, email=’shyam_babul@yahoo.com’, first_name=’Sham’, last_name=’babul’, password=’shyam#babul!2123′}

Also, H2 Web Console can be enabled by enabling these properties in application.properties. It is a convenient way to view the tables created and run queries against the in memory database.  Here is an example of the H2 database console.

Keep these properties in your application.properties to enable H2 Web Console.

spring.h2.console.enabled=true

spring.h2.console.settings.web-allow-others=true

spring.h2.console.path=/h2

 

How to load Profile Specific Properties files in Spring Boot

Posted on

In this articles, we will see how to load Profile specific properties files from resource directory in Spring Boot application.

Here, we set up a sample Spring Boot Project and maintains set of configuration files specific to the Profile which would be loaded when the Application runs.

Total four configuration files are created in this sample Project:-

application.properties – Which is a parent property that always loaded first before Profile specific properties file.

application.${spring.profiles.active}.properties – This is a Profile specific properties file where ${spring.profiles.active} is a placeholder of any Env i.e DEV/UAT/PROD. This property file will be loaded right after parent properties. We can keep all Profile related configuration here additionally we can overwrite derived properties of parent property file.

spring.profiles.active – Spring provides this property to enabled active Profile which you have to provide in VM argument with Environment name.

-Dspring.profiles.active=dev

 

 

 

 

Here, we see Project setup hierarchy and configuration files created under resource folder ( /src/main/resources ).

 

 

 

 

 

 

 

 

 

application.properties file is parent properties file that contains all common properties which will be derived by Profile specifies properties file.

file.upload.size.limit =  1024
remote.connection.url=localhost
remote.connection.port=8080
remote.connection.username=user123
remote.connection.password=Pa$$wOrd


remote.https.enabled = false
remote.connection.auth=false

application-dev.properties  ( When application runs on DEV Profile then load all derived properties of application.properties file as well as it own properties )

env.name=dev

application-uat.properties ( When application runs on UAT Profile then Load and Overwrite properties value if it exists in parent properties file  )

file.upload.size.limit =  102400
remote.connection.url=220.120.56.80
remote.connection.port=9090
remote.connection.username=uatUser
remote.connection.password=UAT$123#

remote.https.enabled = true

env.name=UAT

application-prod.properties

file.upload.size.limit =  102400
remote.connection.url=220.110.56.63
remote.connection.port=9090
remote.connection.username=prodAdmin
remote.connection.password=Pa$$wOrd@233$

remote.https.enabled = true
env.name=PROD
remote.connection.auth=true

PropertiesUtils.Java:- This Utilities Class load all properties file in specified order means first it loads application.properties then load Profile specifies properties ( application.${spring.profiles.active}.properties ).

/**
 * Created by MYPC on 8/4/2017.
 */

package com.spring.example.utils;

        import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
        import org.springframework.core.io.ClassPathResource;
        import org.springframework.core.io.Resource;

        public class PropertiesUtils {

            public static final String SPRING_PROFILES_ACTIVE = "spring.profiles.active";

            public static void initProperties() {
                String activeProfile = System.getProperty(SPRING_PROFILES_ACTIVE);
                if (activeProfile == null) {
                    activeProfile = "dev";
                }
                PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer
                        = new PropertySourcesPlaceholderConfigurer();
                Resource[] resources = new ClassPathResource[]
                        {new ClassPathResource("application.properties"),
                                new ClassPathResource("application-" + activeProfile + ".properties")};
                propertySourcesPlaceholderConfigurer.setLocations(resources);

            }
        }

Finally, Main class which read all properties file and print on the Console.


package com.spring.example;

import com.spring.example.utils.PropertiesUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

/**
 * list
 * Created by AJAY KUMAR on 1/9/2017.
 */
@SpringBootApplication
public class MainApplication {

    @Value("${file.upload.size.limit}")
    private long size;

    @Value("${remote.connection.url}")
    private String remoteConnectionUrl;

    @Value("${remote.connection.port}")
    private int remoteConnectionPort;

    @Value("${remote.connection.username}")
    private String remoteConnectionUsername;

    @Value("${remote.connection.password}")
    private String remoteConnectionPassword;

    @Value("${remote.https.enabled}")
    private String remoteHttpsEnabled;

    @Value("${env.name}")
    private String envName;

    @Value("${remote.connection.auth}")
    private String remoteConnectionAuth;

    public static void main(String[] args) {
        PropertiesUtils.initProperties();
        ConfigurableApplicationContext context = SpringApplication.run(MainApplication.class, args);
        MainApplication mainApplication = context.getBean(MainApplication.class);
        printEnvironmentsProperties(mainApplication);
    }

    private static void printEnvironmentsProperties(MainApplication MainApplication) {
        StringBuilder stringBuilder = new StringBuilder("Properties Files ......\n");

        stringBuilder.append("env.name").append(" : ").append(MainApplication.envName).append("\n")
                .append("file.upload.size.limit").append(" : ").append(MainApplication.size).append("\n")
                .append("remote.connection.url").append(" : ").append(MainApplication.remoteConnectionUrl).append("\n")
                .append("remote.connection.port").append(" : ").append(MainApplication.remoteConnectionPort).append("\n")
                .append("remote.connection.username").append(" : ").append(MainApplication.size).append("\n")
                .append("remote.connection.password").append(" : ").append(MainApplication.remoteConnectionPassword).append("\n")
                .append("remote.connection.auth").append(" : ").append(MainApplication.remoteConnectionAuth).append("\n")
                .append("remote.https.enabled").append(" : ").append(MainApplication.remoteHttpsEnabled).append("\n");
        System.out.println(stringBuilder.toString());
    }
}

By default, spring-profiles-active is dev Profile either you set active profile to dev or not, it loads application-dev.properties and give below output-

2017-08-05 17:37:35.068 INFO 11548 — [ main] com.spring.example.MainApplication : Started MainApplication in 4.457 seconds (JVM running for 5.036)
Properties Files ……
env.name : dev
file.upload.size.limit : 1024
remote.connection.url : localhost
remote.connection.port : 8080
remote.connection.username : 1024
remote.connection.password : Pa$$wOrd
remote.connection.auth : false
remote.https.enabled : false

When you set spring-profiles-active is PROD  in VM options then you will get below output.

2017-08-05 17:41:06.539 INFO 10184 — [ main] com.spring.example.MainApplication : Started MainApplication in 4.095 seconds (JVM running for 4.783)
Properties Files ……
env.name : PROD
file.upload.size.limit : 102400
remote.connection.url : 220.110.56.63
remote.connection.port : 9090
remote.connection.username : 102400
remote.connection.password : Pa$$wOrd@233$
remote.connection.auth : true
remote.https.enabled : true

I hope this article would be helpful!! Thanks.

ThreadLocal Example with Java 8

Posted on Updated on

What is ThreadLocal in Java?

ThreadLocal is a specially provisioned functionality by JVM to provide an isolated storage space for threads only. like the value of instance scoped variable are bound to a given instance of a class only. each object has its only values and they can not see each other value. so is the concept of ThreadLocal variables, they are local to the thread in the sense of object instances other thread except for the one which created it, can not see it.

Like request, session and application scope of any Object, We can define a Thread Scope of any Object thus Object visibility would be only within the Thread and Every Thread has it execution life cycle, After a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).

Although we usually create a Synchronize  Object for Thread safety in MultiThread application therefore only one Thread can be obtained a monitor to access shared Object Since shared Object is not thread safe.

In Java 8, A new method is introdued  to determine the initial value.

public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
    return new SuppliedThreadLocal<>(supplier);
}

Here, a simple ThreadLocal example of Java 8 is demonstrated that how each Thread gets own ThreadLocal copy of variable and value remain same even in Iteration process and each thread are executing separately on the ThreadLocal variable.

 

import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

/**
 * Created by MYPC on 5/29/2017.
 */
public class ThreadLocalExample {
    private static final AtomicInteger transactionId = new AtomicInteger(10000);
    private static final ThreadLocal threadLocal = ThreadLocal.withInitial(() -> transactionId.getAndIncrement());

    public static void main(String[] args) {

        // Thread 1 executing and getting same Transaction Id for all iteration
        new Thread(() -> IntStream.range(0, 3).forEach(val -> {
            System.out.println(Thread.currentThread().getName() + " > " + threadLocal.get());
        })).start();

        // Thread 2 executing and getting same Transaction Id for all iteration
        new Thread(() -> IntStream.range(0, 3).forEach(val -> {
            System.out.println(Thread.currentThread().getName() + " > " + threadLocal.get());
        })).start();
        // Thread 3 executing and getting same Transaction Id for all iteration
        new Thread(() -> IntStream.range(0, 3).forEach(val -> {
            System.out.println(Thread.currentThread().getName() + " > " + threadLocal.get());
        })).start();

    }
}
Execution Output :-

Thread-1 > 10001
Thread-1 > 10001
Thread-1 > 10001
Thread-0 > 10000
Thread-0 > 10000
Thread-0 > 10000
Thread-2 > 10002
Thread-2 > 10002
Thread-2 > 10002

Java 8 : How to calculate difference between two Dates.

Posted on

Java-8

 

 

 

Java 8 introduced Date and Time API that represents the principle date-time concepts, including instants, durations, dates, times, timezones and periods. They are also based on the ISO Calendar system and unlike their predecessor, class in java.time packages are both immutable and thread-safe. New date and time API is located inside java.time package and some of the key classes are following :

 

  • Instant – It represents a timestamp
  • LocalDate – a date without time e.g. 2014-01-14. It can be used to store birthday, anniversary, date of joining etc.
  • LocalTime – represents time without a date
  • LocalDateTime – is used to combine date and time, but still without any offset or time-zone
  • ZonedDateTime – a complete date-time with time-zone and resolved offset from UTC/Greenwich

 

 

Below are the complete example of calculating seconds/minutes/hours/week between two given dates alone with JUtil Testcase.

package com.example1;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.stream.Stream;

/**
 * Created by MYPC on 1/15/2017.
 */
public class DateUtils {

    /**
     * Calculated Nos of Days between given two Date.
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public static long DaysBetween(LocalDate startDate, LocalDate endDate) {
        return ChronoUnit.DAYS.between(startDate, endDate);
    }

    /**
     * Calculated Nos. of hours between given two Date.
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public static long HoursBetween(LocalDateTime startDate, LocalDateTime endDate) {
        return ChronoUnit.HOURS.between(startDate, endDate);
    }

    /**
     * Calculated Nos. of Minutes between given two Date
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public static long MinsBetween(LocalDateTime startDate, LocalDateTime endDate) {
        return ChronoUnit.MINUTES.between(startDate, endDate);
    }

    /**
     * Calculated Nos. of Seconds between given two Date
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public static long SecondsBetween(LocalDateTime startDate, LocalDateTime endDate) {
        return ChronoUnit.SECONDS.between(startDate, endDate);
    }

    /**
     * Calculated Nos. of weeks between given two Date
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public static long WeeksBetween(LocalDate startDate, LocalDate endDate) {
        return ChronoUnit.WEEKS.between(startDate, endDate);
    }

    /**
     * It will return days between two Dates with excluding given days in ignore list.
     * and return calculated Days between which is not included the end Date.
     * Example :-
     * LocalDate startDate = LocalDate.parse("2017-01-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
     * LocalDate endDate = LocalDate.parse("2017-01-15", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
     * System.out.println(DaysBetween(startDate,endDate,Stream.of(DayOfWeek.SATURDAY,DayOfWeek.SUNDAY).collect(Collectors.toList())));
     *
     * @param startDate
     * @param endDate
     * @param skipDays
     * @return
     */
    public static long DaysBetween(LocalDate startDate, LocalDate endDate, List skipDays) {
        return Stream.iterate(startDate, d -> d.plusDays(1))
                .limit(startDate.until(endDate, ChronoUnit.DAYS))
                .filter(d -> !skipDays.contains(d.getDayOfWeek()))
                .count();
    }
    
}

JUnit test

package com.example1;

import org.junit.Assert;
import org.junit.Test;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Month;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by MYPC on 1/15/2017.
 */
public class DateUtilsTest {

    LocalDate startDate = LocalDate.of(2017, Month.JANUARY, 01);
    LocalDate endDate = LocalDate.of(2017, Month.JANUARY, 15);

    LocalDateTime startDt = LocalDateTime.now().minusHours(23);
    LocalDateTime endDt = LocalDateTime.now();

    @Test
    public void DaysBetweenDateTest() {
        Assert.assertEquals(DateUtils.DaysBetween(startDate, endDate), 14);
    }

    @Test
    public void HoursBetweenDateTest() {
        Assert.assertEquals(DateUtils.HoursBetween(startDt, endDt), 23);
    }

    @Test
    public void MinutesBetweenDateTest() {
        Assert.assertEquals(DateUtils.MinsBetween(startDt, endDt), 1380);
    }

    @Test
    public void SecondsBetweenDateTest() {
        Assert.assertEquals(DateUtils.SecondsBetween(startDt, endDt), 82800);
    }

    @Test
    public void WeeksBetweenDateTest() {
        Assert.assertEquals(DateUtils.WeeksBetween(startDate, endDate), 2);
    }

    @Test
    public void DaysBetweenDateByIgnoreSundayAndSaturdayTest() {
        List ignoreDays = Stream.of(DayOfWeek.SATURDAY, DayOfWeek.SUNDAY).collect(Collectors.toList());
        Assert.assertEquals(DateUtils.DaysBetween(startDate, endDate, ignoreDays), 10);
    }
}

Testcases snapshots here :-

datetimejunit

Spock Framework with Groovy Example

Posted on

Spock is a testing and specification framework for Java and Groovy application.

http://spockframework.org/

 

Spock Framework with Groovy Example:-

Spock Framework gives you a highly expressive test cases in you test module. It is inspired from several existing testing framework like JUnit, RSpec, jMock, Mockito, Groovy, Scala, Vulcans.

Before starting Spock Framework in your project, you should have at least basic knowledge of Groovy, It’s not very hard to learn even it similar to Java – [ What is Groovy ].

Let start with Spock Specification which describes expected features ( Properties, Aspect ) . A Specification represented by Groovy Class that extends from import spock.lang.Specification. 

Class Specification contains a number of useful methods for writing specifications.

As JUnit, Spock also provides some predefined method for setup and cleanup method as given below:-

def setup() {}          // run before every feature method
def cleanup() {}        // run after every feature method
def setupSpec() {}     // run before the first feature method
def cleanupSpec() {}   // run after the last feature method

@shared:

Sometimes an object needs to be shared between features methods rather than creating it every time in features method level which may be expensive to recreate every time. so we need to share that object between features therefore, @Shared  annotation helps us to do this job.

Objects stored into instance fields are not shared between feature methods. Instead, every feature method gets its own object. This helps to isolate feature methods from each other, which is often a desirable goal.

@shared
def connection = new DBConnection();

Block : –

Block is a predefined set of a label that supported by Spock Framework. Usually, Block is an area where a setup, stimulus, response, condition, expectation and cleanup is described.

Blocks2Phases

below are the complete example of Spock specification that would help us to understand.

@Unroll :-

As you can see in below Spock Test example, @Unroll annotation are used in some features, By putting @Unroll annotation on the feature. it means an iteration is required on feature and on each iteration values given in where block get substituted by its value and leading hash sign (#), to refer to data variables.

@Unroll
def "Power(#base,#exponent) == #result1 and Power(#base,2) == #result2"() {
    expect:
    Math.pow(base, exponent) == result1
    and:
    Math.pow(base, 2) == result2
    where:
    base | exponent || result1 | result2
    1    | 2        || 1 | 1
    2    | 3        || 8 | 4
    3    | 4        || 81 | 9
    4    | 5        || 1024 | 16
}

Prerequisites

  • JDK 5 or higher
  • Ant 1.7 or higher (for Ant build)
  • Maven 2.x (for Maven build)

Creating an IDEA Project:-

  • Create a Java project in IntellJ and set up project source folder and testing source folder under the project.

 

 

 

 

 

 

 

  • Create a pom.xml file under root folder and copy and paste below contents and build this project by command line or IntelliJ.
<?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.spock.example</groupId>
    <artifactId>GroovySpockExample</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>spring_boot</name>
    <description>Demo Example of Groovy with Spock</description>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.spockframework</groupId>
            <artifactId>spock-core</artifactId>
            <version>1.0-groovy-2.4</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>2.4.4</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.18.1</version>
                <configuration>
                    <includes>
                        <include>**/*Test.java</include>
                        <include>**/*Spec.java</include>
                    </includes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

 

  • Create a Groovy Test file under test folder
import spock.lang.Specification
import spock.lang.Unroll

/**
 * Created by Ajay Kumar on 4/7/2017.
 */
class GroovyTest extends Specification {

    def "Testing:- Null is not allowed in Synchronized Hashtable Collection"() {
        given: "Initialize a Hashtable Connection "
        def table = new Hashtable()
        when: " When an element insert into it"
        table.put("One", "One")
        then: "Size is One"
        table.size() == 1
        when: " When insert a null value"
        table.put(null, null)
        then: "NullPointerException thrown"
        thrown(NullPointerException)
    }

    def "Testing:- Only One null value is allowed in Set Collection"() {
        given: "Initialize a HashSet Connection "
        def set = new HashSet()
        when: " When an element insert into it"
        set.add("One")
        and: " And add a Null element into it"
        set.add(null)
        and: "And add another null value"
        set.add(null)
        then: "Size is One"
        set.size() == 2
    }

    def "Testing ArrayList"() {
        given:
        def array = new ArrayList();
        when: "Push an element into Array"
        array.add("Hello")
        then: "One element is expected in Array"
        array.size() == 1
        array.isEmpty() == false
        when: "Pop out element from Array"
        array.remove(0)
        then:
        array.size() == 0
        when: "When we get elements from Array"
        array.get(0)
        then:
        thrown(IndexOutOfBoundsException)
    }

    @Unroll
    def "Power of #val is #result"() {
        expect:
        Math.pow(val, 2) == result
        where:
        val || result
        1   || 1
        2   || 4
        3   || 9
        4   || 16
    }

    @Unroll
    def "Power(#base,#exponent) is #result"() {
        expect:
        Math.pow(base, exponent) == result
        where:
        base | exponent || result
        1    | 2        || 1
        2    | 3        || 8
        3    | 4        || 81
        4    | 5        || 1024
    }

    @Unroll
    def "Power(#base,#exponent) == #result1 and Power(#base,2) == #result2"() {
        expect:
        Math.pow(base, exponent) == result1
        and:
        Math.pow(base, 2) == result2
        where:
        base | exponent || result1 | result2
        1    | 2        || 1 | 1
        2    | 3        || 8 | 4
        3    | 4        || 81 | 9
        4    | 5        || 1024 | 16
    }

    @Unroll
    def "Computing the maximum of (#a,#b) is #c"() {
        expect:
        Math.max(a, b) == c

        where:
        a << [5, 3]
        b << [1, 9]
        c << [5, 9]
    }

    @Unroll
    def " #name should have length #length "() {
        expect:
        name.length() == length
        where:
        name << ["Computing", "Should", "Have", "Name"]
        length << [9, 6, 4, 4]
    }
}

Here is Test output:-

 

Thanks

Create a new Groovy project using maven

Posted on Updated on

This is a first exercise of writing a groovy program in IntelliJ IDE. See the first post of What is Groovy here?

Below is the complete example of Groovy using maven setup.

  • Create a folder as Project name i.e GroovyExample in your project folder.
  • Create an XML ( pom.xml )file under GroovyExample folder and named it as pom.xml.
  • Copy and paste the content of pom.xml as given inline below.
  • Open IntelliJ IDE and Click on File-> Open and select pom.xml file under GroovyExample folder by navigating it through.
  •  While importing all dependencies in given pom.xml into your project then you can start writing Groovy program.
  • Right click on Project and Create a directory i.e /src/main/groovy under which all groovy file will be placed.
  • Next, Select /groovy folder and right-click to create a new Groovy file.
  • Give proper groovy file name and click OK.
  • A Groovy file will be open then continue with Groovy code as given.

Maven POM.xml file

<?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.example</groupId>
    <artifactId>GroovyExample</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <!--http://start.spring.io/-->
    <name>GroovyExample</name>
    <description>Demo project for Groovy Example</description>


    <dependencies>
        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>2.4.3</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerId>groovy-eclipse-compiler</compilerId>
                    <verbose>true</verbose>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.codehaus.groovy</groupId>
                        <artifactId>groovy-eclipse-compiler</artifactId>
                        <version>2.7.0-01</version>
                    </dependency>
                </dependencies>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.eclipse.jdt.groovy.core.groovyNature</projectnature>
                    </additionalProjectnatures>
                    <sourceIncludes>
                        <sourceInclude>**/*.groovy</sourceInclude>
                    </sourceIncludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Groovy file here :-

groovy-first-example