Skip to main content

Posts

Showing posts from 2017

Introduction to Apache Ignite

This is an introduction series to Apache Ignite. We will discuss about Apache Ignite, its features, usage as in-memory data grid, compute grid, distributed caching, near real-time caching and persistence distributed database. What is Ignite? It is in-memory compute platform . It is in-memory data grid . Durable , strongly consistent and highly available. Providing option to run SQL like queries on cache (Providing JDBC API to support this). Durable memory Apache Ignite is memory-centric platform based on durable memory architecture. It allows you to store and processing data on in-memory(RAM) and on disk (If Ignite Native persistence is enabled). When the Ignite native persistence is enabled, it will treat disk as superset of data, which is cable of surviving crash and restarts. In-memory features RAM is always treated as first memory tier, all the processing happens there. It has following characteristics. Off-heap based: All the data and indexes are stored outs

Spring Security - Form based authentication

In this post, we will use Spring security to handle form based authentication. You can also read my previous posts on Basic Authentication and Digest Authentication . Technologies/ Frameworks used Spring Boot, Spring Security, Thymeleaf, AngularJS, Bootstrap Adding depedencies in pom.xml In the example, we will use Spring Boot, Spring Security, Undertow and thymeleaf and will add their starters as shown below. <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-undertow</artifactId> <

Spring Core - PropertyPlaceHolderConfigurer example

In this post, we will externalize the properties used in the application in a property file and will use PropertyPlaceHolderConfigurer to resolve the placeholder at application startup time. Java Configuration for PropertyPlaceHolderConfigurer @Configuration public class AppConfig { @Bean public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer(); propertySourcesPlaceholderConfigurer.setLocations(new ClassPathResource("application-db.properties")); //propertySourcesPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(true); //propertySourcesPlaceholderConfigurer.setIgnoreResourceNotFound(true); return propertySourcesPlaceholderConfigurer; } } We created object of PropertySourcesPlaceholderConfigurer and set the Locations to search. In this example we used ClassPathResource to resolve the properti

Spring Security: Digest Authentication example

In this post, we will discuss about Digest Authentication with Spring Security. You can also read my previous post on Basic Authentication with Spring Security . What is Digest Authentication? This authentication method makes use of a hashing algorithms to encrypt the password (called password hash) entered by the user before sending it to the server. This, obviously, makes it much safer than the basic authentication method, in which the user’s password travels in plain text (or base64 encoded) that can be easily read by whoever intercepts it. There are many such hashing algorithms in java also, which can prove really effective for password security such as MD5, SHA, BCrypt, SCrypt and PBKDF2WithHmacSHA1 algorithms. Please remember that once this password hash is generated and stored in database, you can not convert it back to original password. Each time user login into application, you have to regenerate password hash again, and match with hash stored in database. So, if user

Spring Security: Basic Authentication example

In this post we will discuss about Basic Authentication and how to use it using Spring Security. BASIC Authentication It’s simplest of all techniques and probably most used as well. You use login/password forms – it’s basic authentication only. You input your username and password and submit the form to server, and application identify you as a user – you are allowed to use the system – else you get error. The main problem with this security implementation is that credentials are propagated in a plain way from the client to the server. Credentials are merely encoded with Base64 in transit, but not encrypted or hashed in any way. This way, any sniffer could read the sent packages over the network. HTTPS is, therefore, typically preferred over or used in conjunction with Basic Authentication which makes the conversation with the web server entirely encrypted. The best part is that nobody can even guess from the outside that Basic Auth is taking place. Let's create a simple S

Spring Data JPA with embedded database and Spring Boot

In this post, we will create a Restful web-services which will use JPA to persist the data in the embedded database(h2). Also, you can read more on Restful web-services . Adding pom.xml dependencies We will add spring-boot-starter-jpa to manage dependencies. We will use h2 embedded database server for persistence. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> Creating entities We have three entities in the example project viz. Product, Rating, User. @Entity @Table(name = "product_ratings", schema = "product") public class Rating { @Id @GeneratedValue @Column(name="rating_id") private Long ratingId; private double rating; @Column(name="product_

Spring Boot - Restful webservices with Jersey

In the previous posts, we have created a Spring Boot QuickStart , customized the embedded server and properties and running specific code after spring boot application starts . Now in this post, we will create Restful webservices with Jersey deployed on Undertow as a Spring Boot Application. Adding dependencies in pom.xml We will add spring-boot-starter-parent as parent of our maven based project. The added benefit of this is version management for spring dependencies. <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.0.RELEASE</version> </parent> Adding spring-boot-starter-jersey dependency This will add/ configure the jersey related dependencies. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jersey</artifactId> </dependency> Adding spring-boot-starter-undertow depend

Spring Boot - ApplicationRunner and CommandLineRunner

Spring Boot provides two interfaces CommandLineRunner and ApplicationRunner to run specific piece of code when application is fully started. These interfaces get called just before run() on SpringApplication completes. CommandLineRunner This interface provides access to application arguments as string array. Let's see the example code for more clarity. @Component public class CommandLineAppStartupRunner implements CommandLineRunner { private static final Logger logger = LoggerFactory.getLogger(CommandLineAppStartupRunner.class); @Override public void run(String... args) throws Exception { logger.info("Application started with command-line arguments: {} . \n To kill this application, press Ctrl + C.", Arrays.toString(args)); } } ApplicationRunner ApplicationRunner wraps the raw application arguments and exposes interface ApplicationArguments which have many convinent methods to get arguments like getOptionNames() return all the arguments names

Spring Boot - changing/ configuring default embedded server

In the previous post , we have created a web-based Spring Boot application which uses Embedded Tomcat as the default server running on default port 8080 . Spring Boot supports Tomcat, Undetow and Jetty as embedded servers. Now, we will change and/ or configure the default embedded server and common properties to all the available servers. Spring Boot provides convenient way of configuring dependencies with its starters. For changing the embedded server, we will user its spring-boot-starter-undertow . Adding dependencies <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-undertow</artifactId> </dependency> spring-boot-starter-web comes with Embedded Tomcat. We need to exclude this dependency. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.s

Spring Boot - A quick start

In this post, we will create a simple Spring Boot application which will run on embedded Apache Tomcat. What is Spring Boot? Spring Boot helps in creating stand-alone, production-grade application easily with minimum fuss. It is the opinionated view of Spring framework and other third party libraries which believes in convenient configuration based setup. Let's start building Spring Boot Application. Adding dependencies in pom.xml We will first add spring-boot-starter-parent as parent of our maven based project. <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.1.RELEASE</version> </parent> The benefit of adding spring-boot-starter-parent is that version managing of dependency is easy. You can omit the required version on the dependency. It will pick the one configured the parent pom or from starters pom. Also, it conveniently setup the build r

Spring Core - Bean scopes (Prototype vs Singleton)

In this post, we will discuss about various bean scopes and their differences. Bean scopes There are seven bean scopes Spring supports out of which five are only available if your ApplicationContext is web-aware. # Scope Explanation 1 singleton There will be single object of the bean per Spring IoC Container (Default). 2 prototype Scope beans to any number of object instances. Every time you get object of prototype bean from context, it will be brand new. 3 request Scope of the bean definition mapped to the lifecycle of HTTP Request. This is only available web-aware ApplicationContext . 4 session Scope of the bean definition mapped to the lifecycle of HTTP session. This is only available to web-aware ApplicationContext . 5 globalSession Scope of the bean definition mapped to the lifecycle of HTTP session usually used within Portlet context. This is only available to web-aware ApplicationContext . 6 application Scope of the bean definition mapp

Spring Core - Dependency Injection

What is Dependency Injection? Dependency injection is a process in which objects define their dependencies i.e. other objects they require to work, through a constructor, setter methods, factory methods. The container responsibility is to inject those while creating beans. With Dependency inject in place, we have cleaner code and clear way of decoupling. There are two prominent variants of Dependency Injection. Constructor based Dependency Injection Setter based Dependency Injection Constructor based Dependency Injection When you express your dependencies through constructor arguments and your container invoke your constructor with number of arguments, type of arguments expected by the constructor. Let's jump to one quick example. @Component public class ConstructorBasedFileParser { private Parser parser; @Autowired public ConstructorBasedFileParser(Parser parser) { this.parser = parser; } public void setParser(Parser parser) { this.parser = parser;

Spring Core - @Import annotation

In this post, we will learn about @Import annotation and its usage. You can see my previous post on how to create a simple spring core project. What is @Import annotation and usage? @Import annotation is equivalent to <import/> element in Spring XML configuration. It helps in splitting the single Java based configuration file into small, modular, maintainable and component based configuration. Let's see it with example. @Configuration @Import(value = { DBConfig.class, WelcomeGbConfig.class }) public class HelloGbAppConfig { } In above code snippet, we are importing two different configuration files viz. DBConfig , WelcomeGbConfig in application level configuration file HelloGbAppConfig . The above code is equivalent to Spring XML based configuration below. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/bean

Spring Core - Java configuration example

In this post, we will create a spring context and will register bean via Java configuration file. You can see my previous post on how to create a simple spring core project. What is @Configuration annotation? @Configuration annotation indicates that there is one or more bean methods and spring containers can process to generate bean definitions at runtime. Also, @Bean annotation is used at method level to signifies that this will be registered as bean in spring context. Let's create a quick configuration class. @Configuration public class WelcomeGbConfig { @Bean GreetingService greetingService() { return new GreetingService(); } } Now, we will create spring context as follows. // using try with resources so that this context closes automatically try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( WelcomeGbConfig.class);) { GreetingService greetingService = context.getBean(GreetingService.class); greetingService.gre

Spring Core - A quick start

In this post, we will create a Spring context and will get a bean object from it. What is Spring context? Spring context is also termed as Spring IoC container which is responsible for instantiate, configure and assemble the beans by reading configuration meta data from XML, Java annotations and/ or Java code in configuration files. Technologies used Spring 4.3.6.RELEASE, Maven Compiler 3.6.0 and Java 1.8 We will first create a simple maven project. You can select the maven-archtype-quickstart as archtype. Adding dependencies in pom.xml We will add spring-framework-bom in the dependency management. <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-framework-bom</artifactId> <version>4.3.6.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </depe

Java 8 - Method references

This article is in continuation to my other posts on Functional Interfaces , static and default methods and Lambda expressions . Method references are the special form of Lambda expression . When your lambda expression are doing nothing other than invoking existing behaviour (method), you can achieve same by referring it by name. :: is used to refer to a method. Method type arguments are infered by JRE at runtime from context it is defined. Types of method references Static method reference Instance method reference of particular object Instance method reference of an arbitrary object of particular type Constructor reference Static method reference When you refer static method of Containing class. e.g. ClassName::someStaticMethodName class MethodReferenceExample { public static int compareByAge(Employee first, Employee second) { return Integer.compare(first.age, second.age); } } Comparator compareByAge = MethodReferenceExample::compareByAge; Instanc

Java 8 - Streams in Action

In this post, we will cover following topics. What are Streams? What is a pipeline? Key points to remember for Streams. How to create Streams? What are Streams? Java 8 introduced new package java.util.stream which contains classes to perform SQL-like operations on elements. Stream is a sequence of elements on which you can perform aggregate operations (reduction, filtering, mapping, average, min, max etc.). It is not a data structure that stores elements like collection but carries values often lazily computed from source through pipeline . What is a pipeline? A pipeline is sequence of aggregate (reduction and terminal) operations on the source. It has following components. A source: Collections, Generator Function, array, I/O channel etc. zero or more intermediate operations: filter, map, sequential, sorted, distinct, limit, flatMap, parallel etc. Intermediate operations returns/produces stream. a termination operation: forEach, reduction, noneMatch, allMatch, c

Java 8 - Aggregate operations on Streams

This post is in continuation with my earlier posts on Streams . In this post we will discuss about aggregate operations on Streams. Aggregate operations on Streams You can perform intermediate and terminal operations on Streams. Intermediate operations result in a new stream and are lazily evaluated and will start when terminal operation is called. persons.stream().filter(p -> p.getGender() == Gender.MALE).forEach(System.out::println); In the snippet above, filter() doesn't start filtering immediately but create a new stream. It will only start when terminal operation is called and in above case when forEach() . Intermediate operations There are many intermediate operations that you can perform on Streams. Some of them are filter() , distinct() , sorted() , limit() , parallel() , sequential , map() , flatMap . filter() operation This takes Predicate functional interface as argument and the output stream of this operation will have only those elements which pass th

Apache Avro - RPC framework

This post is in continuation to my previous posts on Apache Avro - Introduction , Apache Avro - Generating classes from Schema and Apache Avro - Serialization . In this post, we will share insights on using Apache Avro as RPC framework. We first need to define a protocol to use Apache Avro as RPC framework. Before going into depth of this topic, let's discuss What protocol is? Avro protocols describes RPC interfaces. They are defined as JSON similar to Schema . A protocol has following attributes protocol : a string, defining name of the protocol. namespace : an optional that qualifies the name. types : an optional list of definitions of named types (like record, enum, fixed and errors). messages : an optional JSON object whose keys are method names of protocoland whose values are objects whose attributes are described below. No two messages may have the same name. Further, Message have following attributes request : a list of named, typed parameter schemas. respon

Java 8 - Lambda expressions

In this post, we will cover following topics. What are Lambda expressions? Syntax for Lambda expression. How to define no parameter Lambda expression? How to define single/ multi parameter Lambda expression? How to return value from Lambda expression? Accessing local variables in Lambda expression. Target typing in Lambda expression. What are Lambda expressions? Lambda expressions are the first step of Java towards functional programming. Lambda expressions enable us to treat functionality as method arguments, express instances of single-method classes more compactly. Syntax for Lambda expression Lambda has three parts: comma separated list of formal parameters enclosed in parenthesis. arrow token -> . and, body of expression (which may or may not return value). (param) -> { System.out.println(param); } Lambda expression can only be used where the type they are matched are functional interfaces . How to define no parameter Lambda expression? If the la

Java 8 - What are functional interfaces in Java?

Java 8 reincarnated SAM interfaces and termed them Functional interfaces. Functional interfaces have single abstract method and are eligible to be represented with Lambda expression . @FunctionalInterface annotation is introduced in Java 8 to mark an interface as functional. It ensures at compile-time that it has only single abstract method, otherwise it will throw compilation error. Let's define a functional interface. @FunctionalInterface public interface Spec<T> { boolean isSatisfiedBy(T t); } Functional interfaces can have default and static methods in them and still remains functional interface. @FunctionalInterface public interface Spec<T> { boolean isSatisfiedBy(T t); default Spec<T> not() { return (t) -> !isSatisfiedBy(t); } default Spec<T> and(Spec<T> other) { return (t) -> isSatisfiedBy(t) && other.isSatisfiedBy(t); } default Spec<T> or(Spec<T> other) { return (t) -> isSa

Comparing Java Default Serialization with Apache Avro serialization

I did a comparison of Java default serialization and Apache Avro serialization of data and results were very astonishing. You can read my older posts for Java serialization process and Apache Avro Serialization . Apache Avro consumed 15-20 times less memory to store the serialized data. I created a class with three fields (two String and one enum and serialized them with Avro and Java. The memory used by Avro is 14 bytes and Java used 231 bytes (length of byte[] ) Reason for generating less bytes by Avro Java Serialization The default serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields. References to other objects (except in transient or static fields) cause those objects to be written also. Multiple references to a single object are encoded using a reference sharing mechanism so that graphs of objects can be restored to the same shape as when the original was written. Apac

Apache Avro - Serialization and Deserialization

This post is in continuation with my earlier posts on Apache Avro - Introduction and Apache Avro - Generating classes from Schema . In this post, we will discuss about reading (deserialization) and writing(serialization) of Avro generated classes. "Apache Avro™ is a data serialization system." We use DatumReader<T> and DatumWriter<T> for de-serialization and serialization of data, respectively. Apache Avro formats Apache Avro supports two formats, JSON and Binary . Let's move to an example using JSON format. Employee employee = Employee . newBuilder (). setFirstName ( "Gaurav" ). setLastName ( "Mazra" ). setSex ( SEX . MALE ). build (); DatumWriter < Employee > employeeWriter = new SpecificDatumWriter <>( Employee . class ); byte [] data ; try ( ByteArrayOutputStream baos = new ByteArrayOutputStream ()) { Encoder jsonEncoder = EncoderFactory . get (). jsonEncoder ( Employee . getClassSchema (), baos