Showing posts with label example. Show all posts
Showing posts with label example. Show all posts

Thursday, November 9, 2017

Completable future (java 8) simple example

A long long time ago class Future was introduced in Java. Now, with Java 8 we have an "upgraded" version of it.

1. Regular "Future"

Futures are very useful objects: if some task which will be executed in another thread have to return some value - we can use Callable object which returns Futubre object. Later we will be able to get the value returned by task by executing .get method from returned Future. The problem here: when we are executing .get - we are blocked: if the value is not ready yet(long running task) we will be waiting till the value will finally be returned.

Let's write some code to recall our knowledge of Future:

Function for simulation of long running task:

public int longTask(int delay) {
    try {
        Thread.sleep(delay);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return delay;

}

Function for creation Callable from this long task:
public Callable<Integer> longCallable(int delay) {
    Callable<Integer> result = () -> longTask(delay);
    return result;
}


Function for submitting Callable by Executor and creation of Future:

public Future<Integer> longFuture(int delay) {
    return Executors.newWorkStealingPool().submit(longCallable(delay));
}

Debug function to print our Futures:

public void printFuture(Future<Integer> future) {
    try {
        System.out.println(future.get());
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
}

Let's create an array with several futures:

public List<Future<Integer>> getTestFutures() {
    return IntStream.rangeClosed(1, 3)
            .<Future<Integer>>mapToObj(i -> longFuture(i))
            .collect(Collectors.toList());
}

Now we have a Futures, so let's take the values from them:  

public void blockingFutureGet() {
    getTestFutures().forEach(f -> printFuture(f));
}


And, as we mentioned before - we are blocked here. 
After next execution:  

System.out.println("Begin");
app.blockingFutureGet();
System.out.println("End");


Result will be: 
Begin
1
2
3
End

So, the main thread was blocked till we finally got ALL VALUES from the Futures. 
Sometimes such behavior is not acceptable: we may need to execute tasks in totally async way. 
For that purpose we may rewrite previous function this way: 


public void nonBlockingFutureGet() {
    new Thread(this::blockingFutureGet).start();
}

We are running additional thread to get values from the Futures.
The result will be:
Begin
End
1
2
3

-  the main thread was not blocked - it continued execution while another thread was getting values from Futures. But this approach little bit complicated: we have to submit our tasks, collect the futures, run additional thread, pass collected futures there and execute all needed manipulations. To make it simpler we can just use CompletableFutures.

2. CompletableFuture

And now let's compare all the code above with CompletableFuture implementation:

public void completableFuture() {
    IntStream.rangeClosed(1, 3).forEach(i ->
        CompletableFuture.supplyAsync(() -> longTask(i))
           .thenAccept(System.out::println)
    );
}

It's now much easier!  Also results can be forwarded further for additional tasks/operations:

public void completableFuture2() {
    IntStream.rangeClosed(1, 3).forEach(i ->
            CompletableFuture.supplyAsync(() -> longTask(i))
                    .thenApply(v->v*10)
                    .thenApply(v->Integer.toString(v)+"!")
                    .thenAccept(System.out::println)
                    .exceptionally(e-> {
                        System.out.println("We have a problem:"+e.getMessage());
                        return null;
                    })
    );
}

3. Running additional asynchronous tasks using thenCompose

In previous example we used thenApply method which executes tasks in synchronous way. But it can be asynchronous - we can execute thenCompose method and return another async task:

public void cfThenCompose() {
    IntStream.rangeClosed(1, 3)
            .mapToObj(i -> CompletableFuture.supplyAsync(() -> longTask(i * 1000)))
            .forEach(f -> f.thenCompose(j -> {
                             System.out.println(j);
                             return CompletableFuture.supplyAsync(() -> longTask(j + 1));
                         }).thenAccept(System.out::println)
                     );
}


Results of execution:
1000
2000
1001
3000
2001
3001

4. Combining results of 2 independent futures.

In a previous example we were running execution based on previous execution.But what if need result of 2 tasks for further computation? We can use thenCombine method or that:

public void cfThenCombine() {
    CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(()->longTask(1000));
    CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(()->longTask(2000));
    f1.thenCombine(f2, (r1, r2)-> r1+r2).thenAccept(System.out::println);
}

The result is, as expected:
3000

5. The end.

CompletableFutures as the big step forward for java in the direction of functional programming. 

Sunday, June 4, 2017

RxJava simple example



What is RxJava? It's extended implementation of Observer pattern:
It extends the observer pattern to support sequences of data and/or events and adds operators that allow you to compose sequences together declaratively while abstracting away concerns about things like low-level threading, synchronization, thread-safety, concurrent data structures, and non-blocking I/O.
http://reactivex.io/intro.html


1. Observable

In RxJava, Observable - component which emits data.  Subscriber - consumer of these emitted data.
To "send" data to subscriber, observable has to execute "onNext" method on subscriver. When no more available data - observable execute "onComplete" method. If exception has happen - "onError" method.

Let's create a simple class which is taking JSON from rest server, parsing it and on every portion of data - emits it to subscriber. Sample JSON was taken from here. I used GROOVY, because JSON parsing in JAVA much more complicated:

class UsersParser {

    static Observable getObservable(String json) {

        Observable result = Observable.create { subscriber ->

            try {
                def jsonSlurper = new JsonSlurper()
                def usersList = jsonSlurper.parseText(json)
                usersList.each({ e ->
                    def val = "[$e.email] $e.username"                    subscriber.onNext((String) val)
                })
                subscriber.onComplete()
            } catch (Throwable ex) {
                subscriber.onError(ex)
            }
        }

        return result    }

}


JSON contains array of USER objects. For every element in array we are producing result value and "sending" it to subscriber by:  subscriber.onNext((String) val)
When all data are processed, we are executing: subscriber.onComplete()
And if something went wrong: subscriber.onError(ex)


2. Subscriber

Now, to "receive"(consume) data which was "sent"(emitted) by Observable, we need to subscribe (in fact, create Subscriber):   

Observable<String> userObservable = UsersParser.getObservable(json);
userObservable.subscribe(
        t -> System.out.println(t),        e -> e.printStackTrace(),        () -> System.out.println("done")
);


Parameters in "subscribe" method corresponds to methods described above in Observable:

 t -> System.out.println(t)
- corresponds to subscriber.onNext((String) val) - here we just process received object (in current example we just print them)

e -> e.printStackTrace()
- corresponds to subscriber.onError(ex)  - error processing

() -> System.out.println("done")
- corresponds to subscriber.onComplete() - receiving is over(in current example we just print "done")


3. Operations

We can easily transform one observable to another by operator. Why are very similar to STREAMS api from Java 8:

Observable<String> filteredObservable = userObservable        .map(e -> e.toUpperCase())
        .filter(e -> e.indexOf("BIZ") > 0);filteredObservable.subscribe(e -> System.out.println(e));

Also, where are different ways to create Observable from array, callable, future......

Observable.just(1, 2, 3, 4, 2, 1, 3)
        .distinct()
        .subscribe(e -> System.out.print(e));


4. The end

After release of Java 8, RxJava is not really actual for regular java developers, but for Android developers it can be very useful. Full source code can be downloaded from here.

Wednesday, December 28, 2016

Docker for Java development - simple example

1.Intro

Docker site: https://www.docker.com/

From wikipedia:
Docker is an open-source project that automates the deployment of Linux applications inside software containers. Quote of features from Docker web pages:
Docker containers wrap up a piece of software in a complete filesystem that contains everything it needs to run: code, runtime, system tools, system libraries – anything you can install on a server. This guarantees that it will always run the same, regardless of the environment it is running in.[5]
Docker provides an additional layer of abstraction and automation of operating-system-level virtualization on Linux.[6] Docker uses the resource isolation features of the Linux kernel such as cgroups and kernel namespaces, and a union-capable file system such as OverlayFS and others[7] to allow independent "containers" to run within a single Linux instance, avoiding the overhead of starting and maintaining virtual machines.[8]

In shorts, docker is a way of creating containers, deploying applications into containers and  running application inside container. What is container in a docker world? It's a some kind of virtual PC but very lightweight and easy to use.

2. Docker installation

Of course, first of all, docker has to be installed. On official site there are instructions for different operational systems: https://docs.docker.com/engine/installation/

After installation you can run

# docker run hello-world

And result should be something like:

Hello from Docker!
This message shows that your installation appears to be working correctly.
To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.
To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

As you can see, a lot of magic happen by executing just one command.

2. Main concepts/components.

In previous step, Docker's output gave a lot of information how it works:
 - where are docker images which are located in Docker Hub.
 - if we don't have needed image locally - it will be pulled down from Docker Hub
 - based on this image Docker is creating container which it may run

To check list of downloade images we can execute:
# docker images

In result will be present just downloaded hello-world image:

REPOSITORY                TAG                 IMAGE ID            CREATED             SIZE
hello-world               latest              c54a2cc56cbb        6 months ago        1.848 kB


3. Test application for running inside docker container

Now let's create a simple application(in JAR file) which we want to put inside a container. 
I generated simple maven SpringBoot application on http://start.spring.io/ : I selected "Web" in dependencies and pressed button "generate project".

In downloaded project we need just 2 files: 

pom.xml
- I removed test dependency and specified jar file name(MyTestApp):


<?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.demien</groupId>
   <artifactId>demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>

   <name>demo</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.4.2.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>

   </dependencies>

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


</project>

 
And Main application runner DemoApplication.java: 

package com.demien;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController@SpringBootApplicationpublic class DemoApplication {

   @RequestMapping("info")
   public String info() {
      return "Hello world!";
   }

   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
}

- I just added one endpoint:   /info which is returning "Hello world!" message.
We can now run our application by running from command line: mvn spring-boot:run
and open URL: http://localhost:8080/info
 - result should be "Hello world!"

4. Putting test application into container

4.1 Dockerfile

Now we have to create a container. First of all we have to create a file with container description. File name should be "Dockerfile" and it content in this example is:

FROM maven
ADD target/MyTestApp.jar /usr/local/app/MyTestApp.jar
EXPOSE 8080
CMD ["java", "-jar", "/usr/local/app/MyTestApp.jar"]  

Let's explain it step by step:

FROM maven 
- base image for container is MAVEN. List of all imaged can be queried by command "docker search XXX". For example:
# docker search java

NAME                   DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
java                   Java is a concurrent, class-based, and obj...   1246      [OK]      
anapsix/alpine-java    Oracle Java 8 (and 7) with GLIBC 2.23 over...   168                  [OK]
develar/java                                                           53                   [OK]
isuper/java-oracle     This repository contains all java releases...   47                   [OK]
lwieske/java-8         Oracle Java 8 Container - Full + Slim - Ba...   30                   [OK]
nimmis/java-centos     This is docker images of CentOS 7 with dif...   20                   [OK]

Next line  from Dockerfile:
ADD target/MyTestApp.jar /usr/local/app/MyTestApp.jar
- to image from previous step we have to add our application JAR file: file has to be taken from ./target directory and put into /usr/local/app directory in image filesystem

EXPOSE 8080
- our application is using port 8080

CMD ["java", "-jar", "/usr/local/app/MyTestApp.jar"] 
- command which will be executed when we will ask docker to run our container.

4.2 Building new container image

After Dockerfile creation, we can create a new image based on it content:
#docker build -t demien/docker-test1 .

Docker will read Dockerfile in a current directory and create a new image: demien/docker-test1
During build phase, docker will download MAVEN image and all images on which it depends. Now we can execute again:
# docker images
 - to check. New image should be present in result list:

REPOSITORY                TAG                 IMAGE ID            CREATED             SIZE
demien/docker-test1       latest              108d927b5ebb        5 days ago          667.4 MB
<none>                    <none>              ffd0c9386045        5 days ago          667.4 MB
<none>                    <none>              b41d536b6005        5 days ago          667.4 MB
<none>                    <none>              9ce7e4000959        5 days ago          667.4 MB
<none>                    <none>              3a3615d1befb        5 days ago          667.4 MB
<none>                    <none>              f5d4c54045dc        5 days ago          667.4 MB
<none>                    <none>              04dde1d25ea3        6 days ago          707.5 MB
maven                     latest              a90451161cc5        9 days ago          653.2 MB
hello-world               latest              c54a2cc56cbb        6 months ago        1.848 kB


5. The end

We're almost done! Just one thing: we have to run our created image by executing from command line:
#docker run -p 8080:8080 demien/docker-test1

Parameter  "-p 8080:8080" means that we are redirecting our local port 8080 to port 8080 of container.

After start of our application we can open http://localhost:8080/info - result should be again "Hello world!". But this result we got from container: our request to endpoint "/info" on port 8080 was forwarded to port 8080 of our container which is running MyTestApp.jar located at it local directory "/usr/local/app" (we defined it by CMD ["java", "-jar", "/usr/local/app/MyTestApp.jar"]). And all this magic happen by Docker, invisible for us!

All source files can be downloaded from here. 

Thursday, October 8, 2015

Spring data simple example

1.intro

Very often, on DB level there are a lot of classes(DAOs) with similar methods:

To avoid that  - there are  lot of different strategies. In my blog a described some of them : 1. using genericDao    2. EasyJDBC tool
Spring Data - another approach  : you just  have to create an interface (which can be extended from  default CRUD repository) and leave it without implementation. String will generate implementation for you!

2.project structure

Everything is pretty simple : one entity (Category), one dao-repository(CategoryRepository) interface, one config class for spring and application runner(class with main procedure):



3. project pom.xml

Just 3 dependencies here :  spring data, persistence api for annotation support, H2 database.
 
<?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.demien</groupId>
    <artifactId>sdata</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>1.3.4.RELEASE</version>
    </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.2.5.Final</version>
        </dependency>

        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib-nodep</artifactId>
            <version>2.2</version>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.3.173</version>
        </dependency>

    </dependencies>

</project>

4. app.properties

Properties for H2 DB and hibernate
 
#DB properties:db.driver=org.h2.Driverdb.url=jdbc:h2:~/testdb.username=sadb.password=sa
#Hibernate Configuration:db.hibernate.dialect=org.hibernate.dialect.H2Dialectdb.hibernate.show_sql=falsedb.entitymanager.packages.to.scan=com.demien.sdata.domaindb.hibernate.hbm2ddl.auto = create

 

5. test entity

It's a very simple entity with persistence api annotations. 

package com.demien.sdata.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity(name = "CATEGORY")
public class Category {

    @Id    @Column(name = "CATEGORY_ID")
    private Long categoryId;

    @Column(name="CATEGORY_NAME")
    private String categoryName;

    @Column(name = "CATEGORY_DESCRIPTION")
    private String categoryDescription;

    @Column(name="PARENT_CATEGORY_ID")
    private Long parentCategoryId;

    public Category() {}

    public Long getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(Long categoryId) {
        this.categoryId = categoryId;
    }

    public String getCategoryName() {
        return categoryName;
    }

    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }

    public String getCategoryDescription() {
        return categoryDescription;
    }

    public void setCategoryDescription(String categoryDescription) {
        this.categoryDescription = categoryDescription;
    }

    public Long getParentCategoryId() {
        return parentCategoryId;
    }

    public void setParentCategoryId(Long parentCategoryId) {
        this.parentCategoryId = parentCategoryId;
    }

    @Override    public String toString() {
        return "Category{" +
                "categoryId=" + categoryId +
                ", categoryName='" + categoryName + '\'' +
                '}';
    }
}

6. repository

As I mention before, we just have to create interface - implementation will be created by Spring. Interface extended from JpaRepository - it has definition of all base db methods (like save, find, delete...). I added only one custom method to interface, and again : it's just a method without implementation. 


package com.demien.sdata.repository;

import com.demien.sdata.domain.Category;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository(value = "CategoryRepository")
public interface CategoryRepository extends JpaRepository<Category, Long> {

    @Query("FROM CATEGORY where CATEGORY_NAME like %?1% ")
    List<Category> findByPattern(String pattern);
}

7. spring config

XML configs are not very popular at modern time, so I used XML-less Spring configuration. 

package com.demien.sdata;

import org.hibernate.ejb.HibernatePersistence;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Properties;

@Configuration@EnableTransactionManagement@ComponentScan("com.demien.sdata")
@PropertySource("classpath:app.properties")
@EnableJpaRepositories("com.demien.sdata.repository")
public class AppConfig {


private static final String PROP_DATABASE_DRIVER = "db.driver";
private static final String PROP_DATABASE_PASSWORD = "db.password";
private static final String PROP_DATABASE_URL = "db.url";
private static final String PROP_DATABASE_USERNAME = "db.username";
private static final String PROP_HIBERNATE_DIALECT = "db.hibernate.dialect";
private static final String PROP_HIBERNATE_SHOW_SQL = "db.hibernate.show_sql";
private static final String PROP_ENTITYMANAGER_PACKAGES_TO_SCAN = "db.entitymanager.packages.to.scan";
private static final String PROP_HIBERNATE_HBM2DDL_AUTO = "db.hibernate.hbm2ddl.auto";

@Resourceprivate Environment env;

    @Bean    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();

        dataSource.setDriverClassName(env.getRequiredProperty(PROP_DATABASE_DRIVER));
        dataSource.setUrl(env.getRequiredProperty(PROP_DATABASE_URL));
        dataSource.setUsername(env.getRequiredProperty(PROP_DATABASE_USERNAME));
        dataSource.setPassword(env.getRequiredProperty(PROP_DATABASE_PASSWORD));

        return dataSource;
    }

    @Bean    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistence.class);
        entityManagerFactoryBean.setPackagesToScan(env.getRequiredProperty(PROP_ENTITYMANAGER_PACKAGES_TO_SCAN));

        entityManagerFactoryBean.setJpaProperties(getHibernateProperties());

        return entityManagerFactoryBean;
    }

    @Bean    public JpaTransactionManager transactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());

        return transactionManager;
    }

    private Properties getHibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", env.getRequiredProperty(PROP_HIBERNATE_DIALECT));
        properties.put("hibernate.show_sql", env.getRequiredProperty(PROP_HIBERNATE_SHOW_SQL));
        properties.put("hibernate.hbm2ddl.auto", env.getRequiredProperty(PROP_HIBERNATE_HBM2DDL_AUTO));

        return properties;
    }
}
 

8. main runner

I'm starting Spring context and testing main  repository methods here

package com.demien.sdata;

import com.demien.sdata.domain.Category;
import com.demien.sdata.repository.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.Arrays;

/** * Created by dmitry on 05.10.15. */public class App {




    private static ApplicationContext applicationContext;
    public static void main(String args[]) {
        applicationContext=new AnnotationConfigApplicationContext(AppConfig.class);
        new App().test();
    }

    public void test() {
        CategoryRepository categoryRepository=(CategoryRepository)applicationContext.getBean("CategoryRepository");

        Category  category=new Category();
        category.setCategoryId(1l);
        category.setCategoryName("Test 1");
        categoryRepository.save(category);

        category=new Category();
        category.setCategoryId(2l);
        category.setCategoryName("Test 2");

        categoryRepository.save(category);

        System.out.println("\n categoryRepository.findAll()");
        System.out.println(Arrays.toString(categoryRepository.findAll().toArray()));

        System.out.println("\n categoryRepository.findOne(1l)");
        System.out.println(categoryRepository.findOne(1l));


        System.out.println("\n categoryRepository.findByPattern(2)");
        System.out.println(Arrays.toString(categoryRepository.findByPattern("2").toArray()));


        category.setCategoryName("new name");
        categoryRepository.save(category);
        System.out.println("\n UPDATE to new name for element with id=2");
        System.out.println(Arrays.toString(categoryRepository.findAll().toArray()));

        categoryRepository.delete(category);
        System.out.println("\n DELETE of element with id=2");
        System.out.println(Arrays.toString(categoryRepository.findAll().toArray()));


    }
}

9. results 

Everything is working as expected:


 categoryRepository.findAll()
[Category{categoryId=1, categoryName='Test 1'}, Category{categoryId=2, categoryName='Test 2'}]

 categoryRepository.findOne(1l)
Category{categoryId=1, categoryName='Test 1'}

 categoryRepository.findByPattern(2)
[Category{categoryId=2, categoryName='Test 2'}]

 UPDATE to new name for element with id=2
[Category{categoryId=1, categoryName='Test 1'}, Category{categoryId=2, categoryName='new name'}]

 DELETE of element with id=2
[Category{categoryId=1, categoryName='Test 1'}]

Process finished with exit code 0


10. the end

Spring data - very good option to be used on DAO level of application.
Full source code can be downloaded from here.

Saturday, October 3, 2015

Spring boot - simple example

1. Intro

Of course, it's very easy to create rest-web application in java : there are a lot of frameworks and libraries for that, for example Spring MVC, Apache CXF, etc.
But how to test created application ? First of all, you have to build .war file. After that - deploy it to Tomcat. Ok, now application is running, but again : how to test rest services ?  I, for example created for that tool which is using apache.http.client to call rest services. Also I created tool for starting(and testing) application using embedded-jetty, without deploing it to tomcat. And I think, a lot of developers have have such tools.

Spring boot - created to make starting of application and it testing very east out-of-the-box: http://projects.spring.io/spring-boot/


2. Project structure

Project can be generated using online constructor : http://start.spring.io/
 
I created simple project with just one rest-controller, one repository for emulating working with DB, one domain object and one test class. Project was generated by online constructor, I just added new files, renamed main "run" file to App and removed test file.



3. pom.xml

It also was generated by constructor, I just added one more dependency (com.jayway.jsonpath).

<?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.demien</groupId>
   <artifactId>sboot</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>

   <name>demo</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.2.6.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>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>

      <dependency>
         <groupId>com.jayway.jsonpath</groupId>
         <artifactId>json-path</artifactId>
         <scope>test</scope>
      </dependency>

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

</project>



4. Entity

Very simple entity class with just 2 fields.
package com.demien.sboot;

public class TestEntity {
    private Integer entityId;
    private String entityName;

    public TestEntity() {}

    public Integer getEntityId() {
        return entityId;
    }

    public void setEntityId(Integer entityId) {
        this.entityId = entityId;
    }

    public String getEntityName() {
        return entityName;
    }

    public void setEntityName(String entityName) {
        this.entityName = entityName;
    }
}

5. Repository 

- simulation of DB repository. I used static ArrayList for storing elements of TestEntity type. And only 3 operations was implemented : add, getById and getAll.

package com.demien.sboot;

import org.springframework.stereotype.Component;

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


@Componentpublic class TestRepository {
    private static List<TestEntity> storage=new ArrayList<TestEntity>();


    public TestEntity add(TestEntity entity) {
        entity.setEntityId(storage.size()+1);
        storage.add(entity);
        return entity;
    }

    public TestEntity getById(Long entityId) {
        return storage.get(  entityId.intValue()-1);
    }

    public int getMaxId(){
        return storage.size();
    }

    public List<TestEntity> getAll() {
        return storage;
    }



}

6. Controller

Creation of rest-controller is not very hard : just few annotations and calls of repository's methods. 

package com.demien.sboot;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController@RequestMapping("/entity")
public class TestController {

    @Autowired    TestRepository repository;

    @RequestMapping("/hello")
    public String sayHello() {
        return "Hello, world!";
    }

    @RequestMapping(value = "add",  method = RequestMethod.POST)
    public @ResponseBody    TestEntity add(@RequestBody TestEntity entity) {
        TestEntity result=repository.add(entity);
        return result;
    }

    @RequestMapping(value="get/{entityId}", method = RequestMethod.GET)
    public TestEntity get(@PathVariable Long entityId) {
        return repository.getById(entityId);
    }

    @RequestMapping(value="getall", method = RequestMethod.GET)
    public List<TestEntity> getAll() {
        return repository.getAll();
    }

}


7. Application main(starter) file

This file was generated by constructor, I just renamed it. Just after creation of controller we can run App file and it will run our application on embedded-tomcat. And we can test our application by opening in browser URL: http://localhost:8080/entity/hello - it should return "Hello, world!"

As you can see - running of application is VERY easy. It even can be packed into jar file and running using java -jar ...... without tomcat!

package com.demien.sboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplicationpublic class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

8. Test of our controller

Test class class of our controller, from the first look, seems to be complicated - that it just because it has some logic related with json-transformations and some init lines of code for mockMvc. In real life all stuff like this, can be placed in parent test-base-class.
   Logic related with testing itself(methods with @Test annotation) - is very simple and clear.

package com.demien.sboot;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.mock.http.MockHttpOutputMessage;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.hasSize;


@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = App.class)
@WebAppConfigurationpublic class TestControllerTest {

    private MockMvc mockMvc;

    @Autowired    TestRepository repository;


    private MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
            MediaType.APPLICATION_JSON.getSubtype(),
            Charset.forName("utf8"));

    private HttpMessageConverter mappingJackson2HttpMessageConverter;

    @Autowired    void setConverters(HttpMessageConverter<?>[] converters) {

        this.mappingJackson2HttpMessageConverter = Arrays.asList(converters).stream().filter(
                hmc -> hmc instanceof MappingJackson2HttpMessageConverter).findAny().get();

        Assert.assertNotNull("the JSON message converter must not be null",
                this.mappingJackson2HttpMessageConverter);
    }

    @Autowired    private WebApplicationContext webApplicationContext;

    protected String json(Object o) throws IOException {
        MockHttpOutputMessage mockHttpOutputMessage = new MockHttpOutputMessage();
        this.mappingJackson2HttpMessageConverter.write(o, MediaType.APPLICATION_JSON, mockHttpOutputMessage);
        return mockHttpOutputMessage.getBodyAsString();
    }

    @Before    public void init()  {
        this.mockMvc = webAppContextSetup(webApplicationContext).build();
    }

    @Test    public void helloTest() throws Exception {
        mockMvc.perform(get("/entity/hello"))
                .andExpect(status().isOk())
                .andExpect(content().string("Hello, world!"));
    }

    @Test    public void addTest() throws Exception {
        TestEntity entity=new TestEntity();
        entity.setEntityName("Test");

        mockMvc.perform(post("/entity/add/")
                .content(this.json(entity))
                .contentType(contentType))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.entityId", is(repository.getMaxId())))
                .andExpect(jsonPath("$.entityName", is(entity.getEntityName())))
        ;
    }

    @Test    public void getTest() throws Exception {
        TestEntity entity=new TestEntity();
        entity.setEntityName("TestGet");
        entity=repository.add(entity);

        mockMvc.perform(get("/entity/get/" + entity.getEntityId()))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.entityId", is(entity.getEntityId())))
                .andExpect(jsonPath("$.entityName", is(entity.getEntityName())))
        ;

    }

    @Test    public void getAllTest() throws Exception {
        TestEntity entity=new TestEntity();
        entity.setEntityName("TestGetAll");
        entity=repository.add(entity);

        mockMvc.perform(get("/entity/getall"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$", hasSize(repository.getAll().size())))
        ;

    }
}
 

9. The end

Spring boot helped us to create rest application with can be run very easy. And also this application is very easy for testing. Full source code can be downloaded from here.