findAll()

This method will find all the items in the groovy collection that matches the IDENTITY closure.

collect()

This method iterates through a collection and transforms each entry element to a new element using IDENTITY closure as a transformer. It returns a new collection of elements copied from the original collection.

Difference between finalAll() and collect() methods


findAll()collect()
findAll() will return the collection or subset of collection that satisfy the Identity closure or a condition collect() will return a new collection or sub set of collection.
findAll() will not modify the entry elements of the collection collect() will modify the elements by Identity closure.
findAll() will return the elements that matches the condition or Identity closure. collect() will return all the elements of the collection based on the transformation specified by the closure.

  1. ​def list = [1,2,3,4,5];    
  2.     
  3. println list.findAll{it==3}     // [3]  
  4. println list.findAll{it>3}      // [4, 5]  
  5. println list.findAll{it*2}      // [1, 2, 3, 4, 5]  
  6.   
  7. println list.collect{it%2==0}   // [false, true, false, true, false]  
  8. println list.collect{it==2}     // [false, true, false, false, false]  
  9. println list.collect{it*2}      // [2, 4, 6, 8, 10]  
  10. ​  

Points To Remember


  • Implement the class Filter.
  • Add @Configuration annotation to the class to register it as a filter bean.
  • Call method 
    • filterChain.doFilter(resquest,response) to continue the request flow
    • Call method sendError to send error,
      ((HttpServletResponse)response).sendError(HttpServletResponse.SC_BAD_REQUEST);
    • Call method sendRedirect to redirect request to error handler
      ((HttpServletResponse)response).sendRedirect("/errorUrl");

How to create a Filter in Spring Boot Application

IN order to make a filter, we have create a class SecurityFilter
  1. package com.ekiras.filter;  
  2.   
  3. import org.springframework.core.Ordered;  
  4. import org.springframework.core.annotation.Order;  
  5. import org.springframework.stereotype.Component;  
  6.   
  7. import javax.servlet.*;  
  8. import javax.servlet.http.HttpServletResponse;  
  9. import java.io.IOException;  
  10.   
  11. /** 
  12.  * @author ekansh 
  13.  */  
  14. @Component  
  15. @Order(Ordered.HIGHEST_PRECEDENCE)  
  16. public class SecurityFilter implements Filter {  
  17.   
  18.     private static final boolean CONDITION = true;  
  19.   
  20.     @Override  
  21.     public void init(FilterConfig filterConfig) throws ServletException {  
  22.   
  23.     }  
  24.   
  25.     @Override  
  26.     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {  
  27.         if(CONDITION==true)  
  28.             chain.doFilter(request,response);  
  29.         else{  
  30.             ((HttpServletResponse)response).setStatus(HttpServletResponse.SC_BAD_REQUEST);  
  31.         }  
  32.   
  33.     }  
  34.   
  35.     @Override  
  36.     public void destroy() {  
  37.   
  38.     }  
  39. }  

This is how you can create the filter and register it in the Spring Boot Application.

Spring Boot : Introduction

Spring Boot can be referred as Spring on Steroids. Spring boot is a wrapper written over spring modules to allow users to create fast paced spring applications without doing the redundent configurations needed to setup the application.

Features provided by Spring Boot

  • CLI applications - enables to create a single class application.
  • Embedded Tomcat and Jetty
  • Auto configurations for most of the libraries like mysql, mongo, amqp etc
  • No Xml required for setup or configurations.
  • Ability to package the application as both war and jar.
  • Dependency Management using starter projects and BOM's.
For example,

When you create a spring application that needs Mysql database. We had to 
  1. declare the mysql connector dependency in build file.
  2. add the component scan to search the classes for mappings.
  3. map each entity/domain in xml files.
  4. Read data base configurations and create DataSource bean.
  5. add resource handlers to serve static content like css, js, images etc.
After doing all these steps, if you did not miss any and all your configurations are good, you will be able to run your application properly. But with spring boot all you need to do is,

  1. Add Spring boot dependency
  2. add data base configurations in a properties file or yaml file.
  3. run application
Here in spring boot, Auto configuration is already done to load your database credentials from a properties file and create datasource bean.

The first case might take 1-2 days or even a week if your a newbie in spring world. However when you do that same thing in Spring Boot, you will be able to launch the application in a few hours or even less.

This is how Spring Boot has made the Spring configurations so easy and has removed all the Boiler plate code.


How to get list of all plugins installed for Ionic App


You can get a list of all plugins that you have installed on for your ionic app by the following command


  cordova plugin list

Make sure you are in your app directory.

Output of the above command will result as follows.

cordova-plugin-admob 2.2.0 "AdMob"
cordova-plugin-admobpro 2.18.0 "AdMob Plugin Pro"
cordova-plugin-device 1.1.2 "Device"
cordova-plugin-extension 1.5.1 "Cordova Plugin Extension"
cordova-plugin-google-analytics 0.8.1 "Google Universal Analytics Plugin"
cordova-plugin-splashscreen 3.2.2 "Splashscreen"
cordova-plugin-statusbar 2.1.3 "StatusBar"
cordova-plugin-whitelist 1.2.3-dev "Whitelist"
cordova-plugin-x-socialsharing 5.1.2 "SocialSharing"
cordova-plugin-x-toast 2.5.2 "Toast"
cordova-sqlite-storage 1.4.2 "Cordova sqlite storage plugin"
ionic-plugin-keyboard 2.2.0 "Keyboard"

Also you can view the file android.json inside the folder path-to-app/plugins/ and you will find all the plugins configured by ionic.

{
    "prepare_queue": {
        "installed": [],
        "uninstalled": []
    },
    "config_munge": {
        "files": {}
    },
    "installed_plugins": {
        "cordova-plugin-device": {
            "PACKAGE_NAME": "com.ekiras.demo"
        },
        "cordova-plugin-statusbar": {
            "PACKAGE_NAME": "com.ekiras.demo"
        },
        "cordova-plugin-whitelist": {
            "PACKAGE_NAME": "com.ekiras.demo"
        }
    },
    "dependent_plugins": {
        "cordova-plugin-extension": {
            "PACKAGE_NAME": "com.ekiras.demo"
        }
    }
}

Note :
You can remove the plugins by using command

cordova plugin remove <plugin-name> 
You can add the plugins by using command

cordova plugin add <plugin-name> 

Problem Statement

You are given an array where each element follows the rule that given any index, the number at that index will either be 
  • +1 of the number at that index.
  • +0 of the number at that index.
  • -1 of the number at that index.
Suppose the array is 

Sample Input


arr       = {1,2,3,2,3,4,5,6,7,6,5,4,5,6,4,4,4,4};
search = 5

Sample Output


6  (First occurrence of search )


Sample Input


arr       = {1,2,1,2,1,2,1,2,1,2};
search = 5

Sample Output


1  ( Element is not found in the array)

Algorithm


  1. Star iterating from start of the array.
  2. Check if the value at the index is same as the search value
    1. if yes, then return the index
    2. if no, then increment the index counter by modulus of difference of value to search and value at index
  3. return -1 if value to search does not exist in the array.

Java Program


  1. package com.ekiras.arrays;  
  2.   
  3. public class SearchElement {  
  4.   
  5.     private static final int[] arr = {1,2,3,2,3,4,5,6,7,6,5,4,5,6,4,4,4,4};  
  6.       
  7.     public static void main(String args[]){  
  8.         System.out.println("elemet found at :: " + find(5) + "th index");  
  9.           
  10.     }  
  11.       
  12.     public static int find(int search){  
  13.         int cntr=0;  
  14.         while(cntr<arr.length){  
  15.             if(arr[cntr]==search)  
  16.                 return cntr;  
  17.             else{  
  18.                 cntr += Math.abs(search - arr[cntr]);  
  19.             }  
  20.         }  
  21.         return -1;  
  22.     }  
  23.       
  24. }  

Points To Remember


  • @Inject is not a spring feature you need to include javax inject dependency in order to use @Inject.
  • @Autowired is Spring annotation used to inject dependency just like @Inject. It use @Qualifier annotation to differentiate between the beans.
  • @Resource is also Spring annotation, but it uses bean name to inject dependencies and differentiate between beans.

Problem Statement :: Structure

In order to show how @Autowired @Inject and @Resource annotations work  we will create 3 services

  • Interface PersonService, this is the interface for all person related operations.
  • Class EngineerService, this is the service that will do operations for engineer.
  • Class ManagerService, this is the service that will do operations for manager.
Here, both EngineerService and ManagerService implements PersonService. Now we will try to add the services to a controller by different  ways to test how @Autowire, @Inject and @Resource will work.

So the above structure looks like as shown in the code below.
  1. public interface PersonService {  
  2.   
  3.     public String getName();  
  4. }  
  5.   
  6.   
  7. @Service  
  8. public class EngineerService implements PersonService {  
  9.   
  10.     @Override  
  11.     public String getName() {  
  12.         return "EngineerService";  
  13.     }  
  14.   
  15. }  
  16.   
  17. @Service  
  18. public class ManagerService implements PersonService {  
  19.   
  20.     @Override  
  21.     public String getName() {  
  22.         return "ManagerService";  
  23.     }  
  24. }  

Test with @Autowired annotations

  1. Parent Reference Type and name

    1. @RestController  
    2. public class PersonController {  
    3.   
    4.     @Autowired  
    5.     private PersonService personService;  
    6.   
    7.     @Resource  
    8.     private PersonService personService;  
    9.   
    10.     @Inject  
    11.     private PersonService personService;  
    12. }  
    In this case @Autowired @Inject and @Resource all will throw the following exception.
    Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException

  2. Parent Reference Type and Child Reference Name

    1. @RestController  
    2. public class PersonController {  
    3.   
    4.     @Autowired  
    5.     private PersonService engineerService;  
    6.   
    7.     @Resource  
    8.     private PersonService engineerService;  
    9.   
    10.     @Inject  
    11.     private PersonService engineerService;  
    12.   
    13. }  
    In this case, all @Autowired, @Inject and @Resource annotations will inject EngineerService, and getName() will return "EngineerService".
    Note :: When beans are created, they are created by name of the class, EngineerService will resolve to engineerService and its bean will be resolved by name engineerService. Hence when we try to use it with PersonService engineerService , this will inject engineerService bean.
    1. public interface PersonService {  
    2.   
    3.     public String getName();  
    4. }  
    5.   
    6. @Service  
    7. @Qualifier(value = "engineer")  
    8. public class EngineerService implements PersonService {  
    9.   
    10.     @Override  
    11.     public String getName() {  
    12.         return "EngineerService";  
    13.     }  
    14.   
    15. }  
    16.   
    17. @Service  
    18. @Qualifier(value = "manager")  
    19. public class ManagerService implements PersonService {  
    20.   
    21.     @Override  
    22.     public String getName() {  
    23.         return "ManagerService";  
    24.     }  
    25. }  
    26.   
    27. @RestController  
    28. public class PersonController {  
    29.   
    30.     @Autowired  
    31.     @Qualifier(value = "engineer")  
    32.     private PersonService personService;  
    33.   
    34.     @Resource  
    35.     @Qualifier(value = "engineer")  
    36.     private PersonService personService;  
    37.   
    38.     @Inject  
    39.     @Qualifier(value = "engineer")  
    40.     private PersonService personService;  
    41.   
    42. }  
    In this case, all will inject the EngineerService bean to the PersonCOntroller. This is because we have given names to beans using @Qualifier annotation and then used them with the same name.
  3. Ambiguous Qualifiers with Parent Reference Type and name

    1. public interface PersonService {  
    2.   
    3.     public String getName();  
    4. }  
    5.   
    6. @Service  
    7. @Qualifier(value = "person")  
    8. public class EngineerService implements PersonService {  
    9.   
    10.     @Override  
    11.     public String getName() {  
    12.         return "EngineerService";  
    13.     }  
    14.   
    15. }  
    16.   
    17. @Service  
    18. @Qualifier(value = "person")  
    19. public class ManagerService implements PersonService {  
    20.   
    21.     @Override  
    22.     public String getName() {  
    23.         return "ManagerService";  
    24.     }  
    25. }  
    26.   
    27. @RestController  
    28. public class PersonController {  
    29.   
    30.     @Autowired  
    31.     @Qualifier(value = "person")  
    32.     private PersonService personService;  
    33.   
    34.     @Resource  
    35.     @Qualifier(value = "person")  
    36.     private PersonService personService;  
    37.   
    38.     @Inject  
    39.     @Qualifier(value = "person")  
    40.     private PersonService personService;  
    41.   
    42. }  
    In this case, since the qualifiers are ambiguous, all the three will result in the exception.
    Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException

    This is because spring will not be able to find a unique bean with the qualifier "person".
  4. Ambiguous Qualifiers with Parent Reference type and Child Reference name

    1. public interface PersonService {  
    2.   
    3.     public String getName();  
    4. }  
    5.   
    6. @Service  
    7. @Qualifier(value = "engineer")  
    8. public class EngineerService implements PersonService {  
    9.   
    10.     @Override  
    11.     public String getName() {  
    12.         return "EngineerService";  
    13.     }  
    14.   
    15. }  
    16.   
    17. @Service  
    18. @Qualifier(value = "manager")  
    19. public class ManagerService implements PersonService {  
    20.   
    21.     @Override  
    22.     public String getName() {  
    23.         return "ManagerService";  
    24.     }  
    25. }  
    26.   
    27. @RestController  
    28. public class PersonController {  
    29.   
    30.     @Autowired  
    31.     @Qualifier(value = "engineer")  
    32.     private PersonService engineerService;  
    33.   
    34.     @Resource  
    35.     @Qualifier(value = "engineer")  
    36.     private PersonService engineerService;  
    37.   
    38.     @Inject  
    39.     @Qualifier(value = "engineer")  
    40.     private PersonService engineerService;  
    41.   
    42. }  
    In this case, @Autowired and @Inject will throw the following exception
    Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException
    But, @Resouce will still inject the EngineerService bean.


Hence following conclusion can be made on the basis of the above test scenario's

  • All, @Autowired, @Inject and @Resource throws exception with Ambiguous Bean names.
  • If Unique Qualifiers are used, all will inject the specified beans.
  • If Ambiguous beans are there only @Resouce can inject beans based on names of Bean name.

What are Profiles in Spring Boot

Profiles can be seen as different environments in spring boot application. Suppose you are working on an application where you have different staging environments like Dev, QA, UAT, Production etc. So you will have different configurations for each environment, for this kind of applications what you need is having different values that can be switched depending upon some flags.

In early days, people used to write configurations for all environments and comment the unused environments. But with Spring Boot we can do this without commenting any code by use of Profiles.

Suppose we have database name configurations for our application as follows

  • Dev   - ekiras_dev
  • QA    - ekiras_qa
  • UAT  - ekiras_uat
  • Prod  - ekiras

Now, we can use profiling in this case. How we will do it ? lets see

Creating Profiles in Spring Boot 

We will create different files for different environments and call then as profile in rest of the blog.
e.g

application-dev.properties
db.name=ekiras_dev

application-qa.properties
db.name=ekiras_qa

All the application files should either be under the resources folder or any folder that is in classpath. (resources/ is in class path by default).

Similarly you can have properties file for different profiles in the same folder. Each profile should be as application-{env}.properties

How Spring Boot Load Profiles

Spring boot by default loads application.properties from classpath if no profile is selected or specified. If you want to load profile specific properties then you need to tell spring boot application to load that profile, you can define this by the following ways

  • Specify the profile in application.properties as spring.profiles.active=dev this will enable the dev profile.
  • Specify the profile at run time as -Dspring.profiles.active=dev this will enable dev profile, also this will override any profile specified using step 1.

Spring looks for properties files as application-{profile}.properties where {profile} will be any profile you specify by using any of the steps mentioned above.