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

Advertisements

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

What is Groovy?

Posted on Updated on

 

What is Groovy?

Groovy is an optionally Typed, Dynamically language that runs on JVM. It is tightly integrated with the Java Language and its feature is enabled as rich and  Java friendly.

Groovy supports standard Java constructs including annotations, generics, static imports, enums, varargs and lambda expression.

Groovy source code is compiled into Java byte-code by the Groovy compiler. To run Groovy code in a Java virtual machine, only the Groovy JAR file must be present in the classpath at runtime.

A Groovy source files ends with the .groovy extension. This file can contain a Groovy script or a Groovy class.

Compatibility with Java

Groovy runs on the JVM and can use Java libraries. Every Groovy type is a subclass ofjava.lang.Object.

Groovy does currently not support Java 8 lambda expressions.

Reasons to use Groovy

Groovy focus on simplicity and very productive.

  • Simplification : – Groovy does not require a semicolon to terminate the line. return type can be omitted, by default Groovy return the last expression of the line as return type. public keyword can be omitted, it is a Default in Groovy, Also it allows optional typing.
  • Ease of use – Groovy has list, maps and regular expressions directly build into the language.
  • Simplification in I/O – parsing and creating XML, JSON and files are very simple with Groovy.
  • Flexibility – Groovy allows to change classes and methods at runtime, e.g. if a method is called which does not exist on a class, the class can intercept this call and react to it. This allows for example that Groovy provides a very flexible builder pattern.
  • Easy to use : – Groovy has list, maps and regular expressions directly build into the language.
  • Simplification in I/O – parsing and creating XML, JSON and files are very simple with Groovy.

Setup Groovy in IntelliJ:-

Steps to follow to install Groovy in you IntelliJ.

  • Open IntellJ IDE.
  • Go to File->Settings -> plugin
  •  Choose Groovy in plugin Text box and install.
  • Once Groovy get installed in your IDE, then you will able to create a Groovy file and run it.
  • groovy-setup

 

Exercise :-

 

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();
                    }
        
                }
        
            }
        
        }


Developing a RESTful Web Service Using Spring Boot 1.4

Posted on

spring_mvc_rest

 

 

 

In this article, we will see the full example of developing an application using Spring boot 1.4.3 Release version. Along with MVC RESTFul example to accomplish a CURD operation.

Before we kick off in example details, we would give you some insight about Spring.boot

What is Spring Boot ?

It is a framework for developing a stand-alone application, Its provide defaults for code and annotation configuration that help us to quickly start new Spring project.

Spring Boot is nothing but a top up on existing Spring Framework with embedded Server ( Jetty + Tomcat ). The goal of Spring Boot Framework is to minimize the development and Testing ( JUnit & Integration ) time and provide production ready features like a metrics, health, logs and externalized configuration.

Features

  • Create stand-alone Spring applications
  • Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
  • Provide opinionated ‘starter’ POMs to simplify your Maven configuration
  • Automatically configure Spring whenever possible
  • Provide production-ready features such as metrics, health checks and externalized configuration
  • Absolutely no code generation and no requirement for XML configuration.

Advantages of Spring Boot:

  • It is very easy to develop Spring Based applications with Java or Groovy.
  • It reduces lots of development time and increases productivity.
  • It avoids writing lots of boilerplate Code, Annotations and XML Configuration.
  • It is very easy to integrate Spring Boot Application with its Spring Ecosystem like Spring JDBC, Spring ORM, Spring Data, Spring Security etc.
  • It follows “Opinionated Defaults Configuration” Approach to reduce Developer effort
  • It provides Embedded HTTP servers like Tomcat, Jetty etc. to develop and test our web applications very easily.
  • It provides CLI (Command Line Interface) tool to develop and test Spring Boot(Java or Groovy) Applications from command prompt very easily and quickly.
  • It provides lots of plugins to develop and test Spring Boot Applications very easily using Build Tools like Maven and Gradle
  • It provides lots of plugins to work with embedded and in-memory Databases very easily.

Let start with Spring Boot Example Step by Step :-

It’s is recommended to start spring.boot application using dependency management system like Maven or Gradle. Here we use Maven to build a Spring Boot application. Below are dependencies in pom.xml which can be created manually or created by SPRING INITIALIZR – recommended to use it to develop a simple Spring Boot Application.

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_Boot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <!--http://start.spring.io/-->
    <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>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <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>
    </dependencies>

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

Create a RESTFul Controller that handle CURD operation using endpoints. Spring 4.3 introduced new annotations which serve the same purpose as @RequestMapping having predefined ‘method’ (HTTP verb) value. These annotations are actually themselves annotated with @RequestMapping with the related value of ‘method’ element.

Followings are those annotations:

  • @GetMapping
  • @PostMapping
  • @PutMapping
  • @DeleteMapping
  • @PatchMapping

DevOpsController.java

package com.spring.example.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by MYPC on 1/9/2017.
 */
@RestController
public class DevOpsController {

    @GetMapping
    public ResponseEntity<?> sayHello() {
        return ResponseEntity.status(HttpStatus.OK).body("Welcome to my first Sprint boot example");
    }

    @PutMapping
    public ResponseEntity<?> putMethod(@RequestBody String payload) {
        System.out.println(" Put Method Call :-> Payload " + payload);
        return ResponseEntity.ok("OK");
    }

    @PostMapping
    public ResponseEntity<?> postMethod(@RequestBody String payload) {
        System.out.println(" POST Method Call :-> Payload " + payload);
        return ResponseEntity.ok("OK");
    }

    @DeleteMapping
    public ResponseEntity<?> deleteMethod(@RequestBody String payload) {
        System.out.println(" DELETE Method Call :-> Payload " + payload);
        return ResponseEntity.ok("OK");
    }

    @GetMapping(path = "/list")
    public ResponseEntity<?> getList() {
        List list = new ArrayList<>();
        list.add("One");
        list.add("Two");
        list.add("Three");
        list.add("Four");
        return ResponseEntity.status(HttpStatus.OK).body(list);
    }
}

And Main Application class to start Spring-Boot application along with Server.


package com.spring.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

/**
 * list
 * Created by AJAY KUMAR on 1/9/2017.
 */
@EnableAutoConfiguration
@ComponentScan(basePackages = "com.spring.example.controller")
public class SpringBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootApplication.class, args);
    }
}


 

Run SpringBootApplication.java as normal java program, It will start embedded Tomcat on port no 8080. Below are output’s snapshot.
springboot-rest

How to Schedule Future Task Using java.util.Timer

Posted on Updated on

java.util.Timer

6db3a-downloadA java.util.Timer class provides a facility to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals. Timer class uses java.util.TaskQueue to add tasks at given regular interval and at any time there can be only one thread running the TimerTask.

TimerTask :-

java.util.TimerTask is an abstract class that implements Runnable interface and we need to extend this class to create our own TimerTask that can be scheduled using java Timer class.

Key points :-

  • java.util.Timer is a thread safe – means, multiple threads can share a single Timer object without the need for external synchronization.
  • This class schedules tasks for one-time execution, or for repeated execution at regular intervals.
  • All constructors start a timer thread.
  • This class does not offer real-time guarantees: it schedules tasks using the Object.wait(long) method.

Class Constructors :-

  • Timer() – Create a new Timer
  • Timer(boolean isDaemon) – Creates a new timer whose associated thread may be specified to run as a daemon.
  • Timer(String name) – Creates a new timer whose associated thread has the specified name.
  • Timer(String name, boolean isDaemon) – Creates a new timer whose associated thread has the specified name, and may be specified to run as a daemon.

Class Methods :-

  • cancel() – Terminates this timer, discarding any currently scheduled tasks.
  • purge() – Removes all cancelled tasks from this timer’s task queue.
  • schedule(TimerTask task,Date time) –  Schedules the specified task for execution at the specified time.
  • schedule(TimerTask task,Date firstTime,long period) – Schedules the specified task for repeated fixed-delay execution, beginning at the specified time.
  • schedule(TimerTask task,long delay) – Schedules the specified task for execution after the specified delay.
  • schedule(TimerTask task,long delay,long period) – Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay.
  • scheduleAtFixedRate(TimerTask task, Date firstTime, long period) – Schedules the specified task for repeated fixed-rate execution, beginning at the specified time.
  • scheduleAtFixedRate(TimerTask task, long delay, long period) – Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay.

Example :-

Here, we scheduled a non-repeated future task that will be print on a Console after the delay of 10 min. TimerTask is a task that can be scheduled for one-time or repeated execution by a Timer and it is a sub-class of Runnable Interface.


import java.util.Timer;
import java.util.TimerTask;
/**
 * Created by MYPC on 10/8/2016.
 */
public class FutureExecutionExample {
    public static void main(String[] args) {
        Timer t = new Timer();
        t.schedule(new TimerTask() {
                  @Override
                  public void run() {
                  // Execute given scheduled task after 10 min.
                  System.out.println(" Run specific task at given time." + System.currentTimeMillis());
               }
             }
         , 10 * 60 * 1000);  // 10 mins
    }
}


Let assume, we create a Timer to run every 2 seconds interval but the execution of Thread takes 3 seconds then Timer keeping adding a schedule task in queue and as soon as Thread execution get finished then, it’s notify to queue to execute next one.


Timer t = new Timer();
t.schedule(new TimerTask() {
       @Override
       public void run() {
           System.out.println(" Run specific task at given time." + System.currentTimeMillis());
           try {
               Thread.sleep(3000);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }
   }

, 1000,2000);  // After 1 second given task will be executed and every 2 second given task execution repeat.
}