<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: irshad sheikh</title>
    <description>The latest articles on DEV Community by irshad sheikh (@irshsheik).</description>
    <link>https://dev.to/irshsheik</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F182518%2Fe44e7c89-59f5-4f69-abeb-5025297e83ca.jpg</url>
      <title>DEV Community: irshad sheikh</title>
      <link>https://dev.to/irshsheik</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/irshsheik"/>
    <language>en</language>
    <item>
      <title>Accessing Child Component Refs in React-A Step-by-Step Guide using forwardRef</title>
      <dc:creator>irshad sheikh</dc:creator>
      <pubDate>Sat, 27 Jan 2024 00:00:00 +0000</pubDate>
      <link>https://dev.to/irshsheik/accessing-child-component-refs-in-react-a-step-by-step-guide-using-forwardref-h2b</link>
      <guid>https://dev.to/irshsheik/accessing-child-component-refs-in-react-a-step-by-step-guide-using-forwardref-h2b</guid>
      <description>&lt;p&gt;As a developer, you’ve likely encountered situations where you need to access the reference of a child component. Managing component references is a crucial aspect of building robust and efficient React applications. Let’s explore how to access child component refs using the &lt;code&gt;forwardRef&lt;/code&gt; feature in React. This step-by-step tutorial aims to provide clarity and beginner-friendliness while addressing common challenges faced by developers.&lt;/p&gt;

&lt;h2&gt;
  
  
  Understanding the Basics of Refs in React
&lt;/h2&gt;

&lt;p&gt;Refs in React allow us to access and interact with the DOM directly. They are particularly useful when you need to grab a reference to a React component and perform imperative actions. While using refs is straightforward, accessing refs of child components can be a bit tricky.&lt;/p&gt;

&lt;h3&gt;
  
  
  Challenges Faced in Accessing Child Component Refs
&lt;/h3&gt;

&lt;p&gt;When dealing with child components, the typical approach of using &lt;code&gt;this.refs&lt;/code&gt; or &lt;code&gt;React.createRef()&lt;/code&gt; might fall short. Enter &lt;code&gt;forwardRef&lt;/code&gt;, a feature introduced in React to pass refs down to child components.&lt;/p&gt;

&lt;h2&gt;
  
  
  Getting Started with forwardRef
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Step 1: Importing React and forwardRef
&lt;/h3&gt;

&lt;p&gt;Let’s start by importing the necessary modules:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { forwardRef } from 'react';

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Step 2: Creating a Child Component with forwardRef
&lt;/h3&gt;

&lt;p&gt;Define your child component using &lt;code&gt;forwardRef&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const ChildComponent = forwardRef((props, ref) =&amp;gt; {
  // Your component logic here

  return &amp;lt;div ref={ref}&amp;gt;Child Component Content&amp;lt;/div&amp;gt;;
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note the &lt;code&gt;(props, ref)&lt;/code&gt; parameters in the function. This is where the &lt;code&gt;ref&lt;/code&gt; will be passed to the child component.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 3: Using the Child Component in a Parent Component
&lt;/h3&gt;

&lt;p&gt;Now, in your parent component, use the &lt;code&gt;ChildComponent&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useRef, useEffect } from 'react';

const ParentComponent = () =&amp;gt; {
  const childRef = useRef();

  useEffect(() =&amp;gt; {
    console.log(childRef.current);
  }, []);

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;ChildComponent ref={childRef} /&amp;gt;
      {/* Additional parent component content */}
    &amp;lt;/div&amp;gt;
  );
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Step 4: Accessing the Child Component Ref
&lt;/h3&gt;

&lt;p&gt;With this setup, you can now access the child component’s ref in the parent component:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useRef, useEffect } from 'react';

const ParentComponent = () =&amp;gt; {
  const childRef = useRef();

  useEffect(() =&amp;gt; {
    console.log(childRef.current);
  }, []);

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;ChildComponent ref={childRef} /&amp;gt;
      {/* Additional parent component content */}
    &amp;lt;/div&amp;gt;
  );
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Practical Examples and Best Practices
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Example 1: Modifying Child Component Styles
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useRef, useEffect } from 'react';

const ParentComponent = () =&amp;gt; {
  const childRef = useRef();

  useEffect(() =&amp;gt; {
    const childElement = childRef.current;
    childElement.style.color = 'red';
  }, []);

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;ChildComponent ref={childRef} /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Example 2: Triggering Child Component Methods
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useRef, useEffect } from 'react';

const ParentComponent = () =&amp;gt; {
  const childRef = useRef();

  useEffect(() =&amp;gt; {
    const childElement = childRef.current;
    childElement.someMethod();
  }, []);

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;ChildComponent ref={childRef} /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;By using &lt;code&gt;forwardRef&lt;/code&gt; with functional components, you can seamlessly access and manipulate the refs of child components in React.&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>typescript</category>
    </item>
    <item>
      <title>Different Ways to Implement Thread-Safe Singleton Pattern in Java</title>
      <dc:creator>irshad sheikh</dc:creator>
      <pubDate>Sat, 26 Aug 2023 15:00:00 +0000</pubDate>
      <link>https://dev.to/irshsheik/different-ways-to-implement-thread-safe-singleton-pattern-in-java-2com</link>
      <guid>https://dev.to/irshsheik/different-ways-to-implement-thread-safe-singleton-pattern-in-java-2com</guid>
      <description>&lt;p&gt;The Singleton design pattern is a well-known creational pattern that ensures a class has only one instance while providing a global point of access to that instance. However, ensuring thread safety in a Singleton is crucial, especially in multi-threaded environments. In this blog post, we will explore various techniques to implement a thread-safe Singleton pattern in Java, and we’ll discuss the pros and cons of each approach.&lt;/p&gt;

&lt;h2&gt;
  
  
  Understanding the Singleton Pattern
&lt;/h2&gt;

&lt;p&gt;Before diving into different ways of achieving thread-safe Singletons, let’s recap the basics of the Singleton pattern:&lt;/p&gt;

&lt;p&gt;The Singleton pattern is designed to guarantee a single instance of a class, and it typically involves three key components:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Private Constructor&lt;/strong&gt; : To prevent external instantiation of the class.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Private Static Instance&lt;/strong&gt; : To hold the single instance of the class.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Public Static Method&lt;/strong&gt; : To provide global access to the instance.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Different Ways to Implement Thread-Safe Singleton Patterns
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. Eager Initialization
&lt;/h3&gt;

&lt;p&gt;In the eager initialization approach, the Singleton instance is created at the time of class loading. This ensures thread safety but may not be memory-efficient if the Singleton is not used immediately.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class EagerInitializedSingleton {
    private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();

    private EagerInitializedSingleton() { }

    public static EagerInitializedSingleton getInstance() {
        return instance;
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;While this approach is Simple and thread-safe but it may create the instance even if it’s not needed.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Lazy Initialization (Synchronized Method)
&lt;/h3&gt;

&lt;p&gt;In this approach, the Singleton instance is created only when it’s requested for the first time. It uses a synchronized method to ensure thread safety.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class LazyInitializedSingleton {
    private static LazyInitializedSingleton instance;

    private LazyInitializedSingleton() { }

    public static synchronized LazyInitializedSingleton getInstance() {
        if (instance == null) {
            instance = new LazyInitializedSingleton();
        }
        return instance;
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This approach uses Lazy initialization, and is thread-safe but the synchronization can introduce performance overhead.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Double-Checked Locking
&lt;/h3&gt;

&lt;p&gt;This technique combines lazy initialization and double-checked locking to improve performance by avoiding synchronization once the instance is created.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class DoubleCheckedLockingSingleton {
    private static volatile DoubleCheckedLockingSingleton instance;

    private DoubleCheckedLockingSingleton() { }

    public static DoubleCheckedLockingSingleton getInstance() {
        if (instance == null) {
            synchronized (DoubleCheckedLockingSingleton.class) {
                if (instance == null) {
                    instance = new DoubleCheckedLockingSingleton();
                }
            }
        }
        return instance;
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This technique uses Lazy initialization and provides improved performance but it requires careful implementation to avoid subtle issues.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. Bill Pugh Singleton
&lt;/h3&gt;

&lt;p&gt;The Bill Pugh Singleton, also known as the Initialization-on-demand holder idiom, is a clever way to ensure thread safety in a Singleton without requiring explicit synchronization. It leverages the fact that static nested classes are not loaded until they are referenced, ensuring safe lazy initialization. Here’s how it works:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Inner Static Class&lt;/strong&gt; : In the Bill Pugh Singleton pattern, the Singleton instance is nested within a private static inner class. This inner class is not loaded until it is referenced.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Lazy Initialization&lt;/strong&gt; : The Singleton instance is created when the inner class is first referenced. This ensures that the instance is only created when it is needed, which is a form of lazy initialization.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Static Final Instance&lt;/strong&gt; : The Singleton instance is declared as a &lt;code&gt;static final&lt;/code&gt; variable in the inner class. This guarantees that it is initialized only once, and subsequent access to it returns the same instance.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Here’s a simplified example of the Bill Pugh Singleton pattern:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class BillPughSingleton {
    // Private constructor to prevent external instantiation
    private BillPughSingleton() {
        // Initialization code here
    }

    // Inner static class responsible for lazy initialization
    private static class SingletonHelper {
        // Static final instance of the Singleton
        private static final BillPughSingleton INSTANCE = new BillPughSingleton();
    }

    // Public method to access the Singleton instance
    public static BillPughSingleton getInstance() {
        return SingletonHelper.INSTANCE;
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Thread safety is guaranteed in this pattern because:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The Singleton instance is only created when the &lt;code&gt;getInstance&lt;/code&gt; method is called, ensuring lazy initialization.&lt;/li&gt;
&lt;li&gt;Static initialization guarantees that the instance is created only once, even in a multi-threaded environment.&lt;/li&gt;
&lt;li&gt;There is no need for explicit synchronization since the JVM handles the class loading and instance creation in a thread-safe manner.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The Bill Pugh Singleton pattern is a recommended way to create thread-safe singletons in Java, and it avoids synchronization overhead until the Singleton instance is actually needed.&lt;/p&gt;

&lt;h3&gt;
  
  
  5. Singleton Using Enum
&lt;/h3&gt;

&lt;p&gt;Enums in Java are more than constants because they can encapsulate behavior, making them versatile.&lt;/p&gt;

&lt;p&gt;The Java enum type itself provides inherent thread-safety, as enum values are effectively singletons by design. They are initialized once, when the enum class is loaded, and they cannot be instantiated again.&lt;/p&gt;

&lt;p&gt;Using an enum for Singleton patterns is not only concise but also more resistant to several Singleton-related issues, such as reflection-based attacks and serialization problems, which other Singleton implementations may require additional effort to address.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import java.security.SecureRandom;

public enum OtpService {
    INSTANCE;

    // Inner OTPService class
    private static class OTPService {
        private final SecureRandom random = new SecureRandom();
        private final int otpLength = 6;

        public String generateOtp() {
            StringBuilder otp = new StringBuilder();
            for (int i = 0; i &amp;lt; otpLength; i++) {
                otp.append(random.nextInt(10)); // Generates a random digit (0-9)
            }
            return otp.toString();
        }

        public boolean verifyOtp(String providedOtp, String expectedOtp) {
            return providedOtp.equals(expectedOtp);
        }
    }

    private final OTPService otpService = new OTPService();

    // Delegate methods to the inner OTPService
    public String generateOtp() {
        return otpService.generateOtp();
    }

    public boolean verifyOtp(String providedOtp, String expectedOtp) {
        return otpService.verifyOtp(providedOtp, expectedOtp);
    }
}

public class Main {
    public static void main(String[] args) {
        // Get an instance of the OTP service
        OtpService otpService = OtpService.INSTANCE;

        // Generate an OTP
        String otp = otpService.generateOtp();
        System.out.println("Generated OTP: " + otp);

        // Simulate OTP verification
        String userEnteredOtp = "123456"; // Replace with user input
        boolean isOtpValid = otpService.verifyOtp(userEnteredOtp, otp);

        if (isOtpValid) {
            System.out.println("OTP is valid.");
        } else {
            System.out.println("OTP is invalid.");
        }
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;We create an inner class called &lt;strong&gt;&lt;code&gt;OTPService&lt;/code&gt;&lt;/strong&gt; within the &lt;strong&gt;&lt;code&gt;OtpService&lt;/code&gt;&lt;/strong&gt; enum. This inner class encapsulates the OTP generation and verification logic.&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;&lt;code&gt;otpService&lt;/code&gt;&lt;/strong&gt; field within the enum is an instance of &lt;strong&gt;&lt;code&gt;OTPService&lt;/code&gt;&lt;/strong&gt; , and it is used to delegate OTP-related operations to the inner class.&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;&lt;code&gt;generateOtp&lt;/code&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;code&gt;verifyOtp&lt;/code&gt;&lt;/strong&gt; methods within the enum delegate their operations to the corresponding methods in the &lt;strong&gt;&lt;code&gt;OTPService&lt;/code&gt;&lt;/strong&gt; inner class.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Conclusion&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Each of the methods discussed has its own merits and use cases. The choice of which approach to use depends on your specific requirements and the trade-offs you are willing to make between eager or lazy initialization, synchronization overhead, and code complexity.&lt;/p&gt;

</description>
      <category>designpattern</category>
      <category>java</category>
      <category>threadsafe</category>
    </item>
    <item>
      <title>write join queries using jpa criteria queries</title>
      <dc:creator>irshad sheikh</dc:creator>
      <pubDate>Sun, 13 Aug 2023 00:00:00 +0000</pubDate>
      <link>https://dev.to/irshsheik/write-join-queries-using-jpa-criteria-queries-157d</link>
      <guid>https://dev.to/irshsheik/write-join-queries-using-jpa-criteria-queries-157d</guid>
      <description>&lt;p&gt;In this blog post, we’ll explore how to effectively use JPA’s criteria API to combine information from different database tables, enhancing your ability to retrieve and work with interconnected data.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Essence of Joins
&lt;/h3&gt;

&lt;p&gt;At its core, a join merges rows from two or more tables based on a related column between them. This operation provides a link between data that would otherwise exist in isolated silos. By seamlessly integrating information from different tables, joins facilitate comprehensive data analysis and enhance the granularity of queries.&lt;/p&gt;

&lt;h3&gt;
  
  
  Left Joins: Bridging the Data Divide
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Scenario: Customer-Order Association&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Consider a situation where you’re managing a database of customers and their corresponding orders. In some instances, customers may not have placed any orders yet. To retrieve a list of all customers and their orders, regardless of whether orders exist, a left join comes to the rescue.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery&amp;lt;Customer&amp;gt; query = cb.createQuery(Customer.class);
Root&amp;lt;Customer&amp;gt; customerRoot = query.from(Customer.class);
Join&amp;lt;Customer, Order&amp;gt; orderJoin = customerRoot.join("orders", JoinType.LEFT);
query.select(customerRoot).distinct(true);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this code snippet:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;orderJoin: Join&amp;lt;Customer, Order&amp;gt;&lt;/code&gt;&lt;/strong&gt; establishes a left join between the &lt;strong&gt;&lt;code&gt;Customer&lt;/code&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;code&gt;Order&lt;/code&gt;&lt;/strong&gt; entities, ensuring customers are fetched alongside their orders.&lt;/li&gt;
&lt;li&gt;The argument &lt;strong&gt;&lt;code&gt;'orders'&lt;/code&gt;&lt;/strong&gt; passed to &lt;strong&gt;&lt;code&gt;join()&lt;/code&gt;&lt;/strong&gt; identifies the property on the &lt;strong&gt;&lt;code&gt;Customer&lt;/code&gt;&lt;/strong&gt; entity representing the relationship with the &lt;strong&gt;&lt;code&gt;Order&lt;/code&gt;&lt;/strong&gt; entity.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;JoinType.LEFT&lt;/code&gt;&lt;/strong&gt; specifies a left join operation.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;query.select(customerRoot).distinct(true)&lt;/code&gt;&lt;/strong&gt; signifies the selection of &lt;strong&gt;&lt;code&gt;Customer&lt;/code&gt;&lt;/strong&gt; entities and the utilization of the &lt;strong&gt;&lt;code&gt;distinct&lt;/code&gt;&lt;/strong&gt; modifier to eliminate duplicate customers from the result set.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The generated SQL query resembles this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT DISTINCT c.*
FROM customer c
LEFT JOIN order o ON c.id = o.customer_id;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Right Joins: Shifting the Focus
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Scenario: Product-Order Association&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Imagine a scenario where you’re interested in determining products that have yet to receive any orders. This situation calls for a right join, focusing on data from the associated table to lead the way.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery&amp;lt;Product&amp;gt; query = cb.createQuery(Product.class);
Root&amp;lt;Product&amp;gt; productRoot = query.from(Product.class);
Join&amp;lt;Product, Order&amp;gt; orderJoin = productRoot.join("orders", JoinType.RIGHT);
query.select(productRoot).distinct(true);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, the spotlight shifts to products, and the right join captures products that are yet to find placement within an order. The corresponding SQL query takes form:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT DISTINCT p.*
FROM product p
RIGHT JOIN order o ON p.id = o.product_id;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Full Joins: Embracing Data Wholeness
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Scenario: Author-Book Relationship&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Imagine a situation where you’re examining the relationship between authors and their published books. A full join brings together the benefits of left and right joins, combining information from both tables to provide a comprehensive overview.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery&amp;lt;Author&amp;gt; query = cb.createQuery(Author.class);
Root&amp;lt;Author&amp;gt; authorRoot = query.from(Author.class);
Join&amp;lt;Author, Book&amp;gt; bookJoin = authorRoot.join("books", JoinType.FULL);
query.select(authorRoot).distinct(true);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With a full join, the endeavor of gathering insights about authors and their books encompasses both published and unpublished works. The SQL counterpart takes shape:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT DISTINCT a.*
FROM author a
FULL JOIN book b ON a.id = b.author_id;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://www.initgrep.com/posts/java/jpa/select-values-in-criteria-queries"&gt;Write programmatic criteria queries&lt;/a&gt;. It explains the JPA Criteria Api.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.initgrep.com/posts/java/jpa/select-values-in-criteria-queries"&gt;how to select values in criteria Queries&lt;/a&gt;. This post explains various methods provided in Criteria API to select single or multiple values. It also explains tuple criteria queries.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>jpa</category>
      <category>java</category>
    </item>
    <item>
      <title>Spring Security Oauth2- JWT Authentication in a resource server</title>
      <dc:creator>irshad sheikh</dc:creator>
      <pubDate>Wed, 29 Sep 2021 00:00:00 +0000</pubDate>
      <link>https://dev.to/irshsheik/spring-security-oauth2-jwt-authentication-in-a-resource-server-1gk6</link>
      <guid>https://dev.to/irshsheik/spring-security-oauth2-jwt-authentication-in-a-resource-server-1gk6</guid>
      <description>&lt;p&gt;Oauth2 is an industry-standard protocol for authorization. &lt;/p&gt;

&lt;p&gt;As per Oauth2 specification(&lt;a href="https://datatracker.ietf.org/doc/html/rfc6749"&gt;RFC-6749&lt;/a&gt;) —&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;The OAuth 2.0 authorization framework enables a third-party application to obtain limited access to an HTTP service, either on behalf of a resource owner by orchestrating an approval interaction between the resource owner and the HTTP service, or by allowing the third-party application to obtain access on its own behalf.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The following diagram illustrates the working of an Oauth2 authentication request with an &lt;strong&gt;Authorization Code Grant flow&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;There are four parties involved —&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Client&lt;/strong&gt;  is a third party Application that wants access to the protected resource from a resource server.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Authentication Server&lt;/strong&gt;  is the server which helps to authenticate a Resource Owner.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Resource Owner&lt;/strong&gt;  is the user that owns the protected resource.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Resource Server&lt;/strong&gt; is the server which serves the protected resources owned by Resource Owner.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--frgCWjH2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/http://www.initgrep.com/assets/images/oauth2-auth-code-grant.svg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--frgCWjH2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/http://www.initgrep.com/assets/images/oauth2-auth-code-grant.svg" alt="Oauth2 -Auth code grant diagram.drawio.svg" width="523" height="563"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;First of all, the client sends an authorization request to Resource Owner so that on behalf of the Resource Owner, it can access the protected resource(s).&lt;/li&gt;
&lt;li&gt;If the &lt;em&gt;Authorization-code-grant&lt;/em&gt; is used, the Authorization code is returned to the client. It means the Resource owner has given access to the client for protected resources.&lt;/li&gt;
&lt;li&gt;The client sends this Authorization code to the Authentication Server, which in return provides an Authentication token — typically a JWT token.&lt;/li&gt;
&lt;li&gt;Once the client has the authentication token, It use it to &lt;strong&gt;access&lt;/strong&gt; the &lt;strong&gt;protected resources&lt;/strong&gt; from a &lt;strong&gt;resource server.&lt;/strong&gt; The token expires after a set timeout.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;In this post, we will focus on the 4th step&lt;/strong&gt; i.e. &lt;em&gt;How a Resource Server validates a JWT token provided by any third party client&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;First let us understand, what is JWT and what API’s are provided by spring security to implement Jwt Authentication.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is JWT?
&lt;/h2&gt;

&lt;p&gt;👉🏼 Checkout the complete introduction at &lt;a href="https://jwt.io/introduction"&gt;jwt.io&lt;/a&gt; 😜&lt;/p&gt;

&lt;h2&gt;
  
  
  Spring Security API for JWT Authentication
&lt;/h2&gt;

&lt;p&gt;The below diagram provides a thorough overview of Spring security API Specs for JWT Authentication.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--uYO6LCYl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/http://www.initgrep.com/assets/images/spring-security-Oauth2-api-specs.svg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--uYO6LCYl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/http://www.initgrep.com/assets/images/spring-security-Oauth2-api-specs.svg" alt="Spring-security-Oauth2.svg" width="736" height="1127"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;When a client submits a request along with bearer token. It is passed through the security filter chain. The &lt;code&gt;BearerTokenAuthenticationFilter&lt;/code&gt; creates a &lt;code&gt;BearerTokenAuthenticationToken&lt;/code&gt; of the type &lt;code&gt;Authentication&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Next, The &lt;code&gt;AuthenticationManagerResolver&lt;/code&gt; resolves the &lt;code&gt;AuthenticationManager&lt;/code&gt; which in turn selects the specific &lt;code&gt;AuthenticationProvider&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;code&gt;BearerTokenAuthenticationToken&lt;/code&gt; is passed to &lt;code&gt;AuthenticationProvider&lt;/code&gt; by &lt;code&gt;ProviderManager&lt;/code&gt;( the default Implementation of &lt;code&gt;AuthenticationManager&lt;/code&gt;)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;For JWT authentication, &lt;code&gt;JwtAuthenticationProvider&lt;/code&gt; is selected. It &lt;em&gt;decodes&lt;/em&gt;, &lt;em&gt;verifies&lt;/em&gt; and &lt;em&gt;validates&lt;/em&gt; the &lt;strong&gt;&lt;code&gt;Jwt&lt;/code&gt;&lt;/strong&gt; using &lt;code&gt;JwtDecoder&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If the authentication succeeds, the Authentication is set on the &lt;code&gt;SecurityContextHolder&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If the Authentication fails, &lt;code&gt;SecurityContextHolder&lt;/code&gt; is cleared.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Finally, Let move ahead with implementing the JWT Authentication.&lt;/p&gt;

&lt;h2&gt;
  
  
  JWT Authentication in Spring Security
&lt;/h2&gt;

&lt;p&gt;In order to implement it, we would require the following components —&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Authentication server&lt;/strong&gt; - we will use &lt;a href="https://www.keycloak.org/getting-started"&gt;Keycloak&lt;/a&gt;. It supports Oauth2.0.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Resource Server&lt;/strong&gt; - We will create one using a spring-boot application.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Client&lt;/strong&gt; - We can use &lt;a href="https://www.postman.com/"&gt;Postman API client&lt;/a&gt; as the client.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;User&lt;/strong&gt; - we will setup one user in Keycloak server.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Authentication server via Keycloak
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Follow this link to quickly &lt;a href="https://www.keycloak.org/getting-started/getting-started-docker"&gt;setup a Keycloak server via Docker.&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Follow this &lt;a href="https://www.appsdeveloperblog.com/keycloak-authorization-code-grant-example/"&gt;tutorial to setup Keycloak Authorization code grant&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;While you are at it, &lt;em&gt;here are few things, you would require once the Keycloak server is setup.&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;issuer uri&lt;/strong&gt; — &lt;em&gt;&lt;a href="http://localhost:8080/auth/realms/realm"&gt;http://&lt;/a&gt;&lt;/em&gt;&lt;a href="http://localhost:8080/auth/realms/dev/.well-known/openid-configuration"&gt;authserver.com&lt;/a&gt;&lt;em&gt;&lt;a href="http://localhost:8080/auth/realms/realm"&gt;/auth/realms/{realm}&lt;/a&gt;&lt;/em&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;jwks-uri&lt;/strong&gt; — &lt;a href="http://localhost:8080/auth/realms/dev/protocol/openid-connect/certs"&gt;http://&lt;/a&gt;&lt;a href="http://localhost:8080/auth/realms/dev/.well-known/openid-configuration"&gt;authserver.com/&lt;/a&gt;&lt;a href="http://localhost:8080/auth/realms/dev/protocol/openid-connect/certs"&gt;auth/realms/{realm}/protocol/openid-connect/certs&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Metadata endpoint&lt;/strong&gt; —To use the &lt;code&gt;issuer-uri&lt;/code&gt; property, the Authorization server should support either one of the below URLs as the metadata endpoint : 

&lt;ul&gt;
&lt;li&gt;
&lt;a href="http://localhost:8080/auth/realms/dev/.well-known/openid-configuration"&gt;http://authserver.com/auth/realms/{realm}/.well-known/openid-configuration&lt;/a&gt;. (Keycloak supports this one)&lt;/li&gt;
&lt;li&gt;&lt;a href="https://idp.example.com/.well-known/openid-configuration/issuer"&gt;https://auth-server.com/.well-known/openid-configuration/issuer&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://idp.example.com/.well-known/oauth-authorization-server/issuer"&gt;https://auth-server.com/.well-known/oauth-authorization-server/issuer&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Make sure to replace &lt;a href="http://authserver.com"&gt;authserver.com&lt;/a&gt; with valid domain. Also make sure to provide the value value for &lt;code&gt;realm&lt;/code&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Once you have the &lt;code&gt;Keycloak&lt;/code&gt; server ready — Let’s go ahead and create a resource server.&lt;/p&gt;

&lt;h2&gt;
  
  
  Resource Server
&lt;/h2&gt;

&lt;p&gt;The resource server will be the simplest one and will contain only one secure rest API.&lt;/p&gt;

&lt;h3&gt;
  
  
  Dependencies:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;spring-security-oauth2-resource-server&lt;/code&gt; &lt;em&gt;**&lt;/em&gt;— Most of the resource server support is collected here.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;spring-security-oauth2-jose&lt;/code&gt; — provides support for decoding and verifying JWT.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;spring-boot-starter-web&amp;lt;/artifactId&amp;gt;
&amp;lt;/dependency&amp;gt;

&amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;spring-boot-starter-oauth2-resource-server&amp;lt;/artifactId&amp;gt;
&amp;lt;/dependency&amp;gt;
&amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;org.springframework.security&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;spring-security-oauth2-jose&amp;lt;/artifactId&amp;gt;
&amp;lt;/dependency&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  API Endpoint
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;GET /api/v1/users&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@RestController
@RequestMapping("/api/v1")
public class UserController {

    @GetMapping("/users")
    public List&amp;lt;User&amp;gt; getUsers(){
        return Arrays.asList(
                new User("john doe", 100),
                new User("jane doe",300)
        );
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since we have Spring security in the class path, every route will be private.&lt;/p&gt;

&lt;h3&gt;
  
  
  Setup JWT issuer URL
&lt;/h3&gt;

&lt;p&gt;This is minimal setup required to implement the JWT authentication. The &lt;code&gt;issuer-url&lt;/code&gt; provided is used by Resource Server to discover public keys of authorization server and validate the token. It is also the same URL present in &lt;strong&gt;&lt;code&gt;iss&lt;/code&gt;&lt;/strong&gt; claim.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-url: http://localhost:8080/auth/realms/{realm}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;When the Resource server is starts up&lt;/strong&gt; , it will automatically configure itself to validate JWT encoded Bearer Token. It achieves this querying the Authorization Server &lt;em&gt;metadata endpoint&lt;/em&gt; for &lt;code&gt;jwks_url&lt;/code&gt; property. This provides access to supported algorithm and its valid public keys.&lt;/p&gt;

&lt;p&gt;The Only drawback to this setup is that it would fail if the Authentication server is not already up. To void startup failure, we would need to add the &lt;code&gt;jwk-set-uri&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Spring:
    security:
        oauth2:
            resourceserver:
                jwt:
                    issuer-url: http://localhost:8080/auth/realms/dev
                    jwk-set-uri: http://localhost:8080/auth/realms/{realm}/protocol/openid-connect/certs

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, the Resource Server will not ping the authorization server at startup. However, &lt;code&gt;issuer-uri&lt;/code&gt; is still kept to validate the JWT &lt;code&gt;iss&lt;/code&gt; claim on incoming token.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Spring Security provides extension points to override or customize the default behavior of the implementation. We will look into customizing some of the default features&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;…But before that, Let’s test the default implementation.&lt;/p&gt;

&lt;h2&gt;
  
  
  Time to Test the Implementation 💎
&lt;/h2&gt;

&lt;p&gt;If you recall, the resource server contains one endpoint with path &lt;code&gt;/api/v1/users&lt;/code&gt;. If we call it without providing an authentication token, it will return &lt;code&gt;401 - Unauthorized&lt;/code&gt; status. That is due absence of authorization token.&lt;/p&gt;

&lt;p&gt;Let’s see how we can can use &lt;em&gt;authorization code grant&lt;/em&gt; to fetch a token from the &lt;code&gt;Keycloak&lt;/code&gt; server and use it to access the &lt;code&gt;API&lt;/code&gt; provided by the resource server.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Step - 1: Request OAuth Authorization Code&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;At this point, we would need a client to request the Authorization code. However to make it easier to test, we can run the following URL in the browser. It should redirect you to the login page and you will have to provide the credentials of the user.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;http://authserver.com/auth/realms/{realm}/protocol/openid-connect/auth
?client_id=your-client-id&amp;amp;response_type=code&amp;amp;state=app-state

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After the successful completion, it will redirect you to the &lt;code&gt;redirect-url&lt;/code&gt; with the values similar to below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;http://{redirect-url}/?state=appstate
&amp;amp;session_state=d7c5d4de-c883-494a-a2a2-e5108062830c
&amp;amp;code=f5935f66-88e0-4085-80aa-000b2a6b2b51.d7c5d4de-c883-494a-a2a2-e5108062830c.bf89a5ff-5703-42d6-9534-ca59f667f81f

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We would require &lt;code&gt;code&lt;/code&gt; to fetch the actual token.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step - 2: Fetch the Authentication Token
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;curl -L -X POST "http://localhost:8080/auth/realms/dev/protocol/openid-connect/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-H "Cookie: JSESSIONID=E8D36F0DBCBF7E33130B9125F8795CAC.9b51ecd0cc5c; JSESSIONID=8E34666DECDB395B1754FD08C5B385F2" \
--data-urlencode "client_id=client-id-value" \
--data-urlencode "client_secret=client-secret-uuid" \
--data-urlencode "grant_type=authorization_code" \
--data-urlencode "code=92236b97-c48f-4827-ae80-80a46e39a0f2.d7c5d4de-c883-494a-a2a2-e5108062830c.bf89a5ff-5703-42d6-9534-ca59f667f81f" \
--data-urlencode "redirect-uri=http://localhost:8085"

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;client-id&lt;/code&gt;, &lt;code&gt;client-secret&lt;/code&gt; can be fetched from the client credentials in &lt;code&gt;Keycloak&lt;/code&gt; server.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;grant_type = authorization_code&lt;/code&gt; describes the grant type used.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;code&lt;/code&gt; fetched in the Step-1.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;redirect-url&lt;/code&gt; should be same as configured for client in &lt;code&gt;Keycloak&lt;/code&gt; server.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The response returned would look similar to the below example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
    "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI0S1ZQNGVhRVdjdno4ZjRndXlPd05XTE9GWFEzYWo0b1I0eWx0dkFSZldFIn0.eyJleHAiOjE2MzI5MzMzOTksImlhdCI6MTYzMjkzMzA5OSwiYXV0aF90aW1lIjoxNjMyOTMzMDgyLCJqdGkiOiIzZTk1NGRkMi0zMjhhLTQ3NzItYWQ2NS0xOWQ3NGM2MGZjZGEiLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvYXV0aC9yZWFsbXMvZGV2IiwiYXVkIjoiYWNjb3VudCIsInN1YiI6ImMzNjFkMGVjLWM1MWItNGRmNy05MTA1LTVhOWUyZGViMmRjOCIsInR5cCI6IkJlYXJlciIsImF6cCI6InJlc291cmNlc2VydmVyIiwic2Vzc2lvbl9zdGF0ZSI6ImMyYWRiODIyLWQwY2ItNDY3MC1iYmNjLWU3NWJlOTkyYzg5OSIsImFjciI6IjEiLCJyZWFsbV9hY2Nlc3MiOnsicm9sZXMiOlsiZGVmYXVsdC1yb2xlcy1kZXYiLCJvZmZsaW5lX2FjY2VzcyIsInVtYV9hdXRob3JpemF0aW9uIl19LCJyZXNvdXJjZV9hY2Nlc3MiOnsicmVzb3VyY2VzZXJ2ZXIiOnsicm9sZXMiOlsiVVNFUiJdfSwiYWNjb3VudCI6eyJyb2xlcyI6WyJtYW5hZ2UtYWNjb3VudCIsIm1hbmFnZS1hY2NvdW50LWxpbmtzIiwidmlldy1wcm9maWxlIl19fSwic2NvcGUiOiJlbWFpbCBwcm9maWxlIiwic2lkIjoiYzJhZGI4MjItZDBjYi00NjcwLWJiY2MtZTc1YmU5OTJjODk5IiwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJ1c2VyX25hbWUiOiJ1c2VyIiwicHJlZmVycmVkX3VzZXJuYW1lIjoidXNlciJ9.A66uqbRwsUL36GSGozZ7FC3x-M4SCYYLaABMdps-XneseP1saIjsTbHO2QrYq2HbD9jl6nKTYxJHjMdbsRJyY3VtM2mf1D8W24-u8y8qmGf1YNbtFfSTZyrUmwiACEv17onAT8wKgR0C4sdbVFETpRY12f2qQb0mM4ZkT9QQ5DYPBu6dnwyBVXLYJzn8kfmp7JB0OR6LsBTTtyh03t_xiRwb1nSALbUmwq7iUk9lTFEUuUZ182p05q3TKxy9b_kxrCh91EYoYWUdBEhRM4yHjrvN99T-MFpRVaCadyn2YibFbCeZHpsqUmgi-ghR3I70U70HGsL22FEAE4N9X5y_pg",
    "expires_in": 300,
    "refresh_expires_in": 1800,
    "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICIzZGU1NjBjZi1kMDZlLTRiZmItODY2Yi1mNzJhYjk0YjA0NGMifQ.eyJleHAiOjE2MzI5MzQ4OTksImlhdCI6MTYzMjkzMzA5OSwianRpIjoiODQ5OWNmY2QtZjY1Yy00YzdhLThhNDctMzdhNjg4ZGZjMjU0IiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL2F1dGgvcmVhbG1zL2RldiIsImF1ZCI6Imh0dHA6Ly9sb2NhbGhvc3Q6ODA4MC9hdXRoL3JlYWxtcy9kZXYiLCJzdWIiOiJjMzYxZDBlYy1jNTFiLTRkZjctOTEwNS01YTllMmRlYjJkYzgiLCJ0eXAiOiJSZWZyZXNoIiwiYXpwIjoicmVzb3VyY2VzZXJ2ZXIiLCJzZXNzaW9uX3N0YXRlIjoiYzJhZGI4MjItZDBjYi00NjcwLWJiY2MtZTc1YmU5OTJjODk5Iiwic2NvcGUiOiJlbWFpbCBwcm9maWxlIiwic2lkIjoiYzJhZGI4MjItZDBjYi00NjcwLWJiY2MtZTc1YmU5OTJjODk5In0.747XKhyNqZCDEzSfLV4K96sgAW0daN1C1ROUr5L_s_E",
    "token_type": "Bearer",
    "not-before-policy": 0,
    "session_state": "c2adb822-d0cb-4670-bbcc-e75be992c899",
    "scope": "email profile"
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Step - 3: Run the API with
&lt;/h3&gt;

&lt;p&gt;We will use the &lt;code&gt;access_token&lt;/code&gt; value from previous response as the bearer token to run the private API — (&lt;code&gt;api/v1/users&lt;/code&gt;) provided by resource server.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;curl -L -X GET "http://localhost:8090/api/v1/users" \
-H "Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI0S1ZQNGVhRVdjdno4ZjRndXlPd05XTE9GWFEzYWo0b1I0eWx0dkFSZldFIn0.eyJleHAiOjE2MzI5MzMzOTksImlhdCI6MTYzMjkzMzA5OSwiYXV0aF90aW1lIjoxNjMyOTMzMDgyLCJqdGkiOiIzZTk1NGRkMi0zMjhhLTQ3NzItYWQ2NS0xOWQ3NGM2MGZjZGEiLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvYXV0aC9yZWFsbXMvZGV2IiwiYXVkIjoiYWNjb3VudCIsInN1YiI6ImMzNjFkMGVjLWM1MWItNGRmNy05MTA1LTVhOWUyZGViMmRjOCIsInR5cCI6IkJlYXJlciIsImF6cCI6InJlc291cmNlc2VydmVyIiwic2Vzc2lvbl9zdGF0ZSI6ImMyYWRiODIyLWQwY2ItNDY3MC1iYmNjLWU3NWJlOTkyYzg5OSIsImFjciI6IjEiLCJyZWFsbV9hY2Nlc3MiOnsicm9sZXMiOlsiZGVmYXVsdC1yb2xlcy1kZXYiLCJvZmZsaW5lX2FjY2VzcyIsInVtYV9hdXRob3JpemF0aW9uIl19LCJyZXNvdXJjZV9hY2Nlc3MiOnsicmVzb3VyY2VzZXJ2ZXIiOnsicm9sZXMiOlsiVVNFUiJdfSwiYWNjb3VudCI6eyJyb2xlcyI6WyJtYW5hZ2UtYWNjb3VudCIsIm1hbmFnZS1hY2NvdW50LWxpbmtzIiwidmlldy1wcm9maWxlIl19fSwic2NvcGUiOiJlbWFpbCBwcm9maWxlIiwic2lkIjoiYzJhZGI4MjItZDBjYi00NjcwLWJiY2MtZTc1YmU5OTJjODk5IiwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJ1c2VyX25hbWUiOiJ1c2VyIiwicHJlZmVycmVkX3VzZXJuYW1lIjoidXNlciJ9.A66uqbRwsUL36GSGozZ7FC3x-M4SCYYLaABMdps-XneseP1saIjsTbHO2QrYq2HbD9jl6nKTYxJHjMdbsRJyY3VtM2mf1D8W24-u8y8qmGf1YNbtFfSTZyrUmwiACEv17onAT8wKgR0C4sdbVFETpRY12f2qQb0mM4ZkT9QQ5DYPBu6dnwyBVXLYJzn8kfmp7JB0OR6LsBTTtyh03t_xiRwb1nSALbUmwq7iUk9lTFEUuUZ182p05q3TKxy9b_kxrCh91EYoYWUdBEhRM4yHjrvN99T-MFpRVaCadyn2YibFbCeZHpsqUmgi-ghR3I70U70HGsL22FEAE4N9X5y_pg" \
-H "Cookie: JSESSIONID=8E34666DECDB395B1754FD08C5B385F2"

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Response:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[
    {
        "name": "John Doe",
        "age": 100
    },
    {
        "name": "Jane Doe",
        "age": 300
    }
]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next steps in this implementation are to customize the default such as &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Added a different timeout value to avoid any issues in distributed systems.&lt;/li&gt;
&lt;li&gt;Configure GrantedAuthority mapping&lt;/li&gt;
&lt;li&gt;.. and much more.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I have written a comprehensive tutorial about it.&lt;br&gt;
You can check it out &lt;a href="https://www.initgrep.com/posts/java/spring/spring-security-oauth2-jwt-authentication-resource-server"&gt;here&lt;/a&gt;&lt;/p&gt;

</description>
      <category>spring</category>
      <category>java</category>
      <category>all</category>
    </item>
    <item>
      <title>Spring Bean Scopes and Lookup method injection</title>
      <dc:creator>irshad sheikh</dc:creator>
      <pubDate>Wed, 01 Sep 2021 00:00:00 +0000</pubDate>
      <link>https://dev.to/irshsheik/spring-bean-scopes-and-lookup-method-injection-3h45</link>
      <guid>https://dev.to/irshsheik/spring-bean-scopes-and-lookup-method-injection-3h45</guid>
      <description>&lt;p&gt;Spring Bean Scope defines the lifecycle and the visibility of the instances created from the bean definitions.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;This article is focused on — &lt;strong&gt;&lt;em&gt;how to inject a bean with a shorter-lived scope such as a &lt;code&gt;prototype&lt;/code&gt; into another bean with a longer-lived scope such as a &lt;code&gt;singleton&lt;/code&gt;.&lt;/em&gt;&lt;/strong&gt; we will briefly discuss relevant bean scopes.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Below are various scopes provided by the Spring framework :&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;singleton&lt;/strong&gt;  — Only one instance of the bean is created per ApplicationContext. It lives and dies with ApplicationContext — thus, It provides the longest life span. This is the default scope and every Spring-managed bean has it unless another scope is provided.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;prototype&lt;/strong&gt;  — New bean instance is created every time a request for the specific bean is made. Thus it has a shorter lifecycle.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The below scopes are relevant only for web-aware Spring &lt;code&gt;ApplicationContext&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;request&lt;/strong&gt;  — A new instance of the bean is created for every HTTP request from a single bean definition.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;session&lt;/strong&gt;  — A new instance of the bean is created for an HTTP session.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Spring also provides &lt;strong&gt;&lt;code&gt;globalSession&lt;/code&gt;&lt;/strong&gt; , &lt;strong&gt;&lt;code&gt;application&lt;/code&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;code&gt;websocket&lt;/code&gt;&lt;/strong&gt; scopes as well.&lt;/p&gt;

&lt;p&gt;we can use &lt;code&gt;@Scope&lt;/code&gt; annotation to provide the scope to the bean.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Scope("prototype")
public class Command {
...
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For XML configuration, we have to add a &lt;code&gt;scope&lt;/code&gt; attribute to the bean definition.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;bean id="appCommand" class="com.initgrep.demos.Command" scope="prototype"/&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now that we have a little background of how Spring Bean Scopes work. Let’s analyze the below code snippets 😎:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Component
@Scope("singleton") //default
public class CommandProcessor {

    @Autowired
    private Command command;

    public void processCommand() {
        command.run();
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;CommandProcessor.java&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Component
@Scope("prototype")
public class Command {
    public void run(){
        System.out.println("Command Run for hashCode - "+this.hashCode());
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Command.java&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Component
public class ProcessorApplication{

    @Autowired
    CommandProcessor processor;

    @Override
    public void run() {
        processor.processCommand();
        processor.processCommand();
        processor.processCommand();
        processor.processCommand();

    }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;ProcessorApplication.java&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;let’s see what we have here —&lt;/p&gt;

&lt;p&gt;A Singleton Scoped Bean - &lt;code&gt;CommandProcessor&lt;/code&gt; and a Prototype Scoped Bean — &lt;code&gt;Command&lt;/code&gt;. The &lt;code&gt;CommandProcessor&lt;/code&gt; bean also has a dependency on &lt;code&gt;Command&lt;/code&gt; Bean and invokes the &lt;code&gt;Command.run()&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;We also have a singleton scoped bean — &lt;code&gt;ProcessorApplication&lt;/code&gt; bean which invokes &lt;code&gt;CommandProcessor.process()&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;In terms of the number of instances, two singleton bean instances for &lt;code&gt;CommandProcessor&lt;/code&gt; and &lt;code&gt;ProcessorApplication&lt;/code&gt; are created .&lt;/p&gt;

&lt;p&gt;Since the &lt;code&gt;Command&lt;/code&gt; bean has the prototype scope. I am assuming, we should have multiple instances of it.&lt;/p&gt;

&lt;p&gt;If you run the above code, the output will be similar to the below. The hash code of the &lt;code&gt;Command&lt;/code&gt; bean instance returned is the same for all invocations of the &lt;code&gt;run()&lt;/code&gt; method. That means, only one bean instance of &lt;code&gt;Command&lt;/code&gt; is created even though it has the &lt;code&gt;prototype&lt;/code&gt; scope.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Command Run for hashCode - 1155862258
Command Run for hashCode - 1155862258
Command Run for hashCode - 1155862258
Command Run for hashCode - 1155862258

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Wait 🤔— Shouldn’t the prototype scope generate multiple instances since it is being called multiple times? The answer is No.&lt;/p&gt;

&lt;p&gt;Despite the fact, the dependency has a &lt;strong&gt;Prototype&lt;/strong&gt; scope, the &lt;strong&gt;Singleton&lt;/strong&gt; bean is created once and all of its dependencies are resolved at that time. Hence, even though &lt;code&gt;Command&lt;/code&gt; has a prototype scope, it would still have only one instance of it present in the &lt;code&gt;CommandProcessor&lt;/code&gt; bean.&lt;/p&gt;

&lt;p&gt;Now the obvious question here is — &lt;strong&gt;&lt;em&gt;what if I want to inject a prototype bean in a singleton but still want multiple instances to be created, much like prototypal behavior&lt;/em&gt;&lt;/strong&gt;?&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Well, Spring framework provides multiple options to help with that. We will go through each one of them in detail below.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;This article was orginally posted @ initgrep.com.&lt;/em&gt;&lt;br&gt;
You can check the &lt;a href="https://www.initgrep.com/posts/java/spring/spring-bean-scopes-lookup-method-injection"&gt;detailed post here&lt;/a&gt;&lt;/p&gt;

</description>
      <category>spring</category>
      <category>java</category>
      <category>all</category>
    </item>
    <item>
      <title>@Transactional Rollback options in Spring Data</title>
      <dc:creator>irshad sheikh</dc:creator>
      <pubDate>Tue, 24 Aug 2021 00:00:00 +0000</pubDate>
      <link>https://dev.to/irshsheik/transactional-rollback-options-in-spring-data-3dnh</link>
      <guid>https://dev.to/irshsheik/transactional-rollback-options-in-spring-data-3dnh</guid>
      <description>&lt;p&gt;Transactions manage the changes that are performed in a system. The main purpose of transactions is to provide &lt;a href="https://en.wikipedia.org/wiki/ACID"&gt;ACID&lt;/a&gt; characteristics to guarantee data validity.&lt;/p&gt;

&lt;p&gt;Spring provides a consistent programming model for transactions. &lt;code&gt;@EnableTransactionManagement&lt;/code&gt; is used to enable transaction management for the spring application. Spring boot enables it by default.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://docs.oracle.com/javaee/7/api/javax/transaction/Transactional.html"&gt;&lt;code&gt;@Transactional&lt;/code&gt;&lt;/a&gt; annotation is used to designate the transaction boundary.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If this annotation is provided on the class then all the methods of the class have transactions enabled.&lt;/li&gt;
&lt;li&gt;If no annotation is provided on the class, then the individual methods will require the explicit &lt;code&gt;@Transactional&lt;/code&gt; annotation - if required.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;code&gt;@Transactional&lt;/code&gt; annotation provides various options to control the behavior of the transaction. We will only focus on two options that help in defining the rollback behavior of the transaction.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The default behavior of the transactions is to rollback for the runtime exceptions and the errors. You wouldn’t need to change the defaults in most of the scenarios. However, there are some cases, where you might care about whether the transaction should rollback or not.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let’s consider the below example —&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
class ProductService{

    @Transactional
    public void processProducts(){

            saveAllProducts(...products); // saves the data in the database
            sendNotification();
    }

    /*
    * sendNotification throws an exception
    */
    private void sendNotification() throws NotificationException{
        //sending the notification
    }

}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;processProducts()&lt;/code&gt; method supports the transaction.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;saveAllProducts()&lt;/code&gt; saves the product data in the database.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;sendNotification()&lt;/code&gt; sends the notification through some external system. It throws &lt;code&gt;NotificationException&lt;/code&gt; for any failure.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This code will work just fine. The products will be saved and after that, the notifications will be sent.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;However, if the external system is down and we are unable to send the notifications, &lt;code&gt;NotificationException&lt;/code&gt; will happen and the transaction will rollback all the changes. This means, due to the notification failure, we are unable to save the products in the database.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now, if we want to save the data &lt;em&gt;irrespective of the notification operation success or failure&lt;/em&gt;. We would need to modify the default transaction rollback behavior. &lt;/p&gt;

&lt;p&gt;&lt;code&gt;@Transactional&lt;/code&gt; annotation provides two options &lt;code&gt;dontRollbackOn&lt;/code&gt; and &lt;code&gt;rollbackOn&lt;/code&gt; for the same.&lt;/p&gt;

&lt;p&gt;You can check the complete post at &lt;a href="https://www.initgrep.com/posts/java/spring/Spring-data-transactional-rollback"&gt;here&lt;/a&gt; &lt;/p&gt;

</description>
      <category>spring</category>
      <category>java</category>
      <category>all</category>
    </item>
    <item>
      <title>Spring Security Architecture fundamentals</title>
      <dc:creator>irshad sheikh</dc:creator>
      <pubDate>Tue, 17 Aug 2021 00:00:00 +0000</pubDate>
      <link>https://dev.to/irshsheik/spring-security-architecture-fundamentals-19gg</link>
      <guid>https://dev.to/irshsheik/spring-security-architecture-fundamentals-19gg</guid>
      <description>&lt;p&gt;Authentication and authorization are fundamental to the security of a web applications. While authentication &lt;em&gt;determines&lt;/em&gt; if the user can be identified by the system, Authorization determines if the user has the access to the specific resource.&lt;/p&gt;

&lt;p&gt;Authentication as well as authorization design paradigm is continuously evolving. The main reason behind it is the continuous evolution in different methods of exploits used against the applications.&lt;/p&gt;

&lt;p&gt;Spring security tries to solve this problem by packaging all the possible solutions together.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;The purpose of this article is to provide a high level understanding of spring security architecture for Servlet applications. It may not help you to immediately implement spring security in your application but it would definitely help you in the subsequent steps when you dive deeper.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Filter pattern in spring security
&lt;/h2&gt;

&lt;p&gt;Spring security for the web applications use the filter pattern to implement different type of security solution. At the very core of it are Servlet &lt;a href="https://docs.oracle.com/javaee/7/api/javax/servlet/Filter.html"&gt;filters&lt;/a&gt;. Spring framework provides &lt;code&gt;DelegatingFilterProxy&lt;/code&gt; filter and Spring security adds &lt;code&gt;FilterChainProxy&lt;/code&gt; filter on top of it. Both these filters are pivotal in Spring security.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--rUMMvRAP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/http://www.initgrep.com/assets/images/spring-security-filter.svg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--rUMMvRAP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/http://www.initgrep.com/assets/images/spring-security-filter.svg" alt="Spring Security filter architecture" width="717" height="550"&gt;&lt;/a&gt;&lt;em&gt;Spring Security Filter architecture&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  DelegatingFilterProxy Filter
&lt;/h3&gt;

&lt;p&gt;Similar to the Servlet filters, the Spring security filters are implement&lt;code&gt;Filter&lt;/code&gt; interface but they are also Spring beans which means they are managed by Spring &lt;code&gt;ApplicationContext&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Since these filters are not registered via Servlet container standards(configured in web.xml), the servlet Container is not aware of them.&lt;/p&gt;

&lt;p&gt;Spring provides &lt;code&gt;DelegatingFilterProxy&lt;/code&gt; filter which sits in the filter chain. It bridges the &lt;strong&gt;Servlet containers&lt;/strong&gt; lifecycle and Spring &lt;code&gt;ApplicationContext&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;When a request is delegated to &lt;code&gt;DelegatingFilterProxy&lt;/code&gt;. It looks up bean filters from the application context and then invokes the relevant bean filter. &lt;code&gt;DelegatingFilterProxy&lt;/code&gt; filter also allows for delayed bean Filter lookup.&lt;/p&gt;

&lt;h3&gt;
  
  
  FilterChainProxy Filter
&lt;/h3&gt;

&lt;p&gt;Spring security provides a special bean filter named as &lt;code&gt;FilterChainProxy&lt;/code&gt;. This filter is a single entry point which enables spring security for a web application.&lt;/p&gt;

&lt;p&gt;It allows delegating request through a set of filters bundled as &lt;code&gt;SecurityFilterChain&lt;/code&gt;. In order to determine which Spring Security Filter’s should be invoked, &lt;code&gt;FilterChainProxy&lt;/code&gt; uses &lt;code&gt;SecurityFilterChain&lt;/code&gt;. There could be multiple &lt;code&gt;SecurityFilterChains&lt;/code&gt; present.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;FilterChainProxy&lt;/code&gt; is also used to perform some security specific task such as clearing &lt;code&gt;SecurityContext&lt;/code&gt;. &lt;code&gt;FilterChainProxy&lt;/code&gt; is more flexible than traditional Servlet Filters. It can determine which &lt;code&gt;securityFilterchain&lt;/code&gt; to invoke by leveraging the &lt;code&gt;RequestMatcher&lt;/code&gt; interface.&lt;/p&gt;

&lt;h3&gt;
  
  
  SecurityFilterChain
&lt;/h3&gt;

&lt;p&gt;It is a list of security filters which are also Spring managed beans. These are registered with FilterChainProxy. The advantage of being registered with &lt;code&gt;SecurityFilterChain&lt;/code&gt; are following:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;FilterChainProxy&lt;/code&gt; leverages &lt;code&gt;RequestMatcher&lt;/code&gt; interface to determine invocation based upon anything in &lt;code&gt;ServletRequest&lt;/code&gt; including the URL. Incase of multiple &lt;code&gt;SecurityFilterChains&lt;/code&gt;, &lt;code&gt;FilterChainProxy&lt;/code&gt; can determine which &lt;code&gt;SecurityFilterChain&lt;/code&gt; should be used. It also clears &lt;code&gt;SecurityContext&lt;/code&gt; to avoid any memory leaks.&lt;/p&gt;

&lt;h3&gt;
  
  
  Customizing the default SecurityFilterChain
&lt;/h3&gt;

&lt;p&gt;Spring security creates an instance of &lt;code&gt;WebSecurity&lt;/code&gt; via &lt;code&gt;WebSecurityConfiguration&lt;/code&gt;. &lt;code&gt;WebSecurity&lt;/code&gt; is responsible for creating an instance of &lt;code&gt;FilterChainProxy&lt;/code&gt; filter.&lt;/p&gt;

&lt;p&gt;We can create customizations to the built-in functionality by —&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Either extending &lt;code&gt;WebSecurityConfigurerAdapter&lt;/code&gt; and exposing it as a Configuration&lt;/li&gt;
&lt;li&gt;Or implementing &lt;code&gt;WebSecurityConfigurer&lt;/code&gt; and exposing it as a Configuration.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;This configuration is imported when using &lt;code&gt;@EnableWebSecurity&lt;/code&gt; annotation.&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  AuthenticationEntryPoint
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;When a client sends a request without authentication credentials, an implementation of &lt;code&gt;AuthenticationEntryPoint&lt;/code&gt; will be used to send the response to the client to ask for credentials.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The &lt;code&gt;AuthenticationEntryPoint&lt;/code&gt; implementation might perform a &lt;strong&gt;redirect to a log in page&lt;/strong&gt; , respond with an &lt;strong&gt;WWW-Authenticat&lt;/strong&gt; e header, etc.&lt;/p&gt;

&lt;h3&gt;
  
  
  AbstractAuthenticationProcessingFilter
&lt;/h3&gt;

&lt;p&gt;This is the base filter used for authenticating the requests. When the user request comes in&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If it has credentials pre-populated, the implementation of &lt;code&gt;AbstractAuthenticationProcessingFilter&lt;/code&gt; is directly called.&lt;/li&gt;
&lt;li&gt;If the credentials are not populated, the implementation of &lt;code&gt;AuthenticationEntryPoint&lt;/code&gt; is called first to request credentials from the client 

&lt;ul&gt;
&lt;li&gt;After that &lt;code&gt;AbstractAuthenticationProcessingFilter&lt;/code&gt; is directly called.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Authentication Architecture API
&lt;/h2&gt;

&lt;h3&gt;
  
  
  AuthenticationManager
&lt;/h3&gt;

&lt;p&gt;This is a strategy interface which provides the API to perform authentication. It is invoked by spring security filters. The &lt;code&gt;authentication&lt;/code&gt; object that is returned is set on &lt;code&gt;SecurityContextHolder&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;It basically checks the authentication and decides&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If the principle is valid&lt;/li&gt;
&lt;li&gt;If the principle is invalid&lt;/li&gt;
&lt;li&gt;If the authentication is null&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Incase, Security Filters are not used such as when using user-defined filters, &lt;code&gt;Authentication&lt;/code&gt; can be set on &lt;code&gt;SecurityContextHolder&lt;/code&gt; manually.&lt;/p&gt;

&lt;h3&gt;
  
  
  ProviderManager
&lt;/h3&gt;

&lt;p&gt;It is common implementation of &lt;code&gt;AuthenticationManager&lt;/code&gt;. It delegates to a list of &lt;code&gt;AuthenticationProvider&lt;/code&gt;s. Each &lt;code&gt;AuthenticationProvider&lt;/code&gt; has the opportunity to authenticate as well as to show that it can not.&lt;/p&gt;

&lt;p&gt;It also allows an optional parent &lt;code&gt;AuthenticationManager&lt;/code&gt;. If no &lt;code&gt;AuthenticationProvider&lt;/code&gt; are provided, the parent &lt;code&gt;AuthenticationManager&lt;/code&gt; is consulted for authentication.&lt;/p&gt;

&lt;p&gt;If no &lt;code&gt;authenticationProviders&lt;/code&gt; can authenticate, authentication fails.&lt;/p&gt;

&lt;h3&gt;
  
  
  AuthenticationProvider
&lt;/h3&gt;

&lt;p&gt;Its implementations performs a specific type of authentication. For example, &lt;code&gt;DaoAuthenticationProvider&lt;/code&gt; supports username/password based authentication while &lt;code&gt;JwtAuthenticationProvider&lt;/code&gt; supports authenticating a JWT token.&lt;/p&gt;

&lt;h3&gt;
  
  
  SecurityContextHolder
&lt;/h3&gt;

&lt;p&gt;This object contains the authentication information about a request.&lt;/p&gt;

&lt;p&gt;It contains &lt;code&gt;SecurityContext&lt;/code&gt; which by default is a &lt;code&gt;threadLocal&lt;/code&gt; object. thus every request thread has its own &lt;code&gt;SecurityContext&lt;/code&gt; object.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--geExhkOb--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/http://www.initgrep.com/assets/images/arc-sec.svg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--geExhkOb--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/http://www.initgrep.com/assets/images/arc-sec.svg" alt="SecurityContextHolder API Diagram" width="489" height="190"&gt;&lt;/a&gt;&lt;em&gt;SecurityContextHolder API Diagram&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Security Context
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;securityContext&lt;/code&gt; object contains &lt;code&gt;Authentication&lt;/code&gt; Object. The &lt;code&gt;Authentication&lt;/code&gt; object serves two main purposes within Spring Security —&lt;/p&gt;

&lt;p&gt;It acts as an input to &lt;code&gt;AuthenticationManager&lt;/code&gt; to provide the credentials a user has provided to authenticate.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  AuthenticationManager.authenticate(Authentication authentication)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It also represents the currently authenticated user. The current &lt;code&gt;Authentication&lt;/code&gt; can be obtained from the &lt;code&gt;SecurityContext.&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  SecurityContextHolder.getContext().getAuthentication()

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Authentication provides the below details regarding an authenticated user:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;Principal&lt;/code&gt; — which identifies the user. When authenticating with a username/password this is often an instance of &lt;code&gt;UserDetails&lt;/code&gt; interface.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Credentials&lt;/code&gt; — is basically the password&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;GrandtedAuthorities&lt;/code&gt; — provide the authorization scope for the principal. It is fine grained scope for authorization. &lt;code&gt;GrantedAuthorities&lt;/code&gt; can be obtained from the &lt;code&gt;Authentication.getAuthorities()&lt;/code&gt; method.&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;if you have reached this far and want to explore more on spring security. Here are a few posts to get you going.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.initgrep.com/posts/java/spring/Spring-Security-implement-user-pass-auth"&gt;username and password authentication using form-based login&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.initgrep.com/posts/java/spring/Spring-Security-in-memory-auth"&gt;In-Memory Authentication using DaoAuthenticationProvider&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.initgrep.com/posts/java/spring/Spring-Security-jpa-authprovider"&gt;JPA implemenation of UserDetailsService For DaoAuthenticationProvider&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>spring</category>
      <category>security</category>
      <category>jpa</category>
      <category>authentication</category>
    </item>
    <item>
      <title>Reactive State management in the angular - NgRx Store, actions, selectors</title>
      <dc:creator>irshad sheikh</dc:creator>
      <pubDate>Tue, 15 Sep 2020 00:00:00 +0000</pubDate>
      <link>https://dev.to/irshsheik/reactive-state-management-in-the-angular-ngrx-store-actions-selectors-4ap6</link>
      <guid>https://dev.to/irshsheik/reactive-state-management-in-the-angular-ngrx-store-actions-selectors-4ap6</guid>
      <description>&lt;p&gt;NgRx framework helps to build reactive angular applications.&lt;/p&gt;

&lt;h2&gt;
  
  
  Basic Concepts
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;NgRx store&lt;/code&gt; provides reactive state management for the angular application. NgRx store is the redux implementation developed specifically for angular applications and provides RxJS observable API.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;state&lt;/code&gt; is an immutable data structure that is a single source of truth for the whole application.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;NgRx Actions&lt;/code&gt; represent the unique events in the application which may be used to perform state transition or trigger side-effects.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;NgRx Reducers&lt;/code&gt;are pure functions that react to &lt;code&gt;Actions&lt;/code&gt;to perform state transitions.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;NgRx Selectors&lt;/code&gt;are pure functions that select, derive, or compose a slice of the state.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;NgRx Effects&lt;/code&gt; allow the isolation of side-effects.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisites -
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;you have a fair understanding of the angular framework.&lt;/li&gt;
&lt;li&gt;You have a basic understanding of redux architecture.&lt;/li&gt;
&lt;li&gt;you have a fair knowledge of &lt;code&gt;RxJs&lt;/code&gt; Observable API and various operators.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Table of contents
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Installation&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;State&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;Design the State&lt;/li&gt;
&lt;li&gt;Initialize the State&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;NgRx Actions&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;NgRx Reducer&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;createReducer function&lt;/li&gt;
&lt;li&gt;Create ActionReducerMap&lt;/li&gt;
&lt;li&gt;Register the State&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;NgRx selectors&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;Selectors&lt;/li&gt;
&lt;li&gt;createSelector function&lt;/li&gt;
&lt;li&gt;String selectors.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Installation
&lt;/h2&gt;

&lt;p&gt;If you already have an angular app, you can directly go to &lt;strong&gt;step - 4&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# 1) install angular cli
npm install -g @angular/cli

# 2) create a demo app
ng new ngrx-angular-demo

# 3) navigate to demo app
cd ngrx-angular-demo

# 4) install ngrx store
ng add @ngrx/store@latest

# 5) run angular in dev mode
ng serve

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;To begin with&lt;/strong&gt; , let us have a look at an example file structure. A structure like this would be helpful to split up each feature of &lt;code&gt;NgRx&lt;/code&gt;state management in your app. I usually replicate the same structure in each feature module.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
    ──store
        |_ app.actions.ts
        |_ app.effects.ts
        |_ app.reducer.ts
        |_ app.selectors.ts

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;app.actions.ts&lt;/code&gt; file will contain the &lt;code&gt;NgRX actions&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;app.effects.ts&lt;/code&gt;file will contain the &lt;code&gt;NgRx effects&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;app.reducer.ts&lt;/code&gt; file will contain the &lt;code&gt;State&lt;/code&gt; design and its initialization. it will also contain a reducer function.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;app.selectors.ts&lt;/code&gt; will contain the &lt;code&gt;NgRx selectors&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Here is the complete &lt;a href="https://github.com/initgrep-post-demos/ngrx-demo/tree/master/src/app/store"&gt;project setup&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  State
&lt;/h2&gt;

&lt;p&gt;The state represents an immutable object that contains the state of an application. It is read-only, so every state transition will return a new state rather than modifying the existing state. As the application grows, each feature should contain a separate state which are part of the global app state. As such, the application state contains one or more feature states.&lt;/p&gt;

&lt;p&gt;The state is similar to &lt;code&gt;Javascript&lt;/code&gt; objects. It contains the feature states as the &lt;code&gt;key-value&lt;/code&gt; pairs _where the &lt;code&gt;key&lt;/code&gt; represents a feature state and the &lt;code&gt;value&lt;/code&gt; is the feature state object.&lt;/p&gt;

&lt;p&gt;The state related to a feature module is referred to as &lt;code&gt;feature state&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface State{
    feature_1: FeatureOneState,
    feature_2: FeatureTwoState,
    feature_3: FeatureThreeState
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Design the State
&lt;/h3&gt;

&lt;p&gt;Let’s assume, our angular application has many feature modules. One of the feature modules is responsible for user’s profile. The &lt;code&gt;profile&lt;/code&gt;module is responsible for rendering the list of &lt;code&gt;users&lt;/code&gt;and the related &lt;code&gt;posts&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;To design the state, we can assume that the state required for the profile module should contain &lt;strong&gt;List of users&lt;/strong&gt; and &lt;strong&gt;List of posts&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Let’s call the profile state as &lt;code&gt;ProfileFeatureState&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/** User modal */
export interface User {

  id: number;
  email: string;
  first_name: string;
  last_name: string;
  avatar: string;
}

/ **post modal** /
export interface Post {
  id: number;
  userId: number;
  title: string;
  body: string;
}

/ **the modals should ideally be in their own ts file** /

export interface ProfileFeatureState {
  users: User[];
  posts: Post[];
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We defined the type for &lt;code&gt;User&lt;/code&gt;and &lt;code&gt;Post&lt;/code&gt; and also created an interface for &lt;code&gt;ProfileFeatureState&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Finally, we would add &lt;code&gt;ProfileFeatureState&lt;/code&gt; to the applications root state -&lt;code&gt;AppState&lt;/code&gt;. The &lt;code&gt;profile&lt;/code&gt; key represents the &lt;code&gt;profileFeatureState&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface AppState{    
    profile: UserFeatureState,    
//..other features here
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Initialize the State
&lt;/h3&gt;

&lt;p&gt;Initially, the state of the application is &lt;code&gt;null&lt;/code&gt;since there would be no data. As such, both the &lt;code&gt;users array&lt;/code&gt; and &lt;code&gt;posts array&lt;/code&gt; would be initialized to &lt;code&gt;null&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const initialProfileFeatureState: ProfileFeatureState = {
  users: null,
  addresses: null
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At this point, the &lt;code&gt;app.reducer.ts&lt;/code&gt; file should look like -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/*app.reducer.ts*/

/** User modal */
export interface User {
  id: number;
  email: string;
  first_name: string;
  last_name: string;
  avatar: string;
}

/** Post Modal */

export interface Post {
  id: number;
  userId: number;
  title: string;
  body: string;
}

export interface ProfileFeatureState {
  users: User[];
  addresses: Address[];
}

export const initialProfileFeatureState: ProfileFeatureState = {
  users: null,
  addresses: null
};

export interface AppState {
  profile: ProfileFeatureState;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Actions:
&lt;/h2&gt;

&lt;p&gt;NgRx Actions represent events in the application. They may trigger a state transition or trigger a side-effect in the &lt;code&gt;NgRx Effect&lt;/code&gt; services.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Action{
    type:string
    //optional metadata properties
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;Action&lt;/code&gt;interface contains a property called &lt;code&gt;Type&lt;/code&gt;. The &lt;code&gt;Type&lt;/code&gt;property &lt;strong&gt;identifies&lt;/strong&gt; the action. Actions can also contain optional &lt;code&gt;metadata&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;createAction&lt;/code&gt;function is used to create the actions and it returns an &lt;a href="https://ngrx.io/api/store/ActionCreator"&gt;ActionCreator&lt;/a&gt; function. &lt;code&gt;ActionCreator&lt;/code&gt; function when called returns an action of type &lt;code&gt;TypedAction&lt;/code&gt;. Optionally, we can also supply additional metadata using &lt;a href="https://ngrx.io/api/store/props"&gt;props&lt;/a&gt; function.&lt;/p&gt;

&lt;p&gt;Let’s go ahead and create an action to add users to &lt;code&gt;ProfileFeatureState&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const addUsers = createAction(
 '[profile] add users',
 props&amp;lt;{ users: User[] }&amp;gt;()
);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice the type of &lt;code&gt;addUsers&lt;/code&gt; action as &lt;code&gt;[profile] add users&lt;/code&gt;. The &lt;code&gt;[profile]&lt;/code&gt; represents the source of action. Also, the props contain the array of users as the metadata.&lt;/p&gt;

&lt;p&gt;Similarly, we can create an action for adding posts to the feature state.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//file: app.actions.ts

export const addPosts = createAction(
  '[profile] add posts',
  props&amp;lt;{ posts: Post[] }&amp;gt;()
);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;&lt;code&gt;addUsers&lt;/code&gt;&lt;/strong&gt; action is dispatched to indicate that the users should be added to the state. It will also contain &lt;code&gt;user[]&lt;/code&gt; as metadata.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Similarly the Actions related to posts are dispatched&lt;/em&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Actions represent the events and not the commands or operations. A single command or operation may generate many types of Actions. For example, An operation that creates a new user would at least generate Actions for &lt;em&gt;success&lt;/em&gt; and &lt;em&gt;failure&lt;/em&gt; such as &lt;code&gt;[profile] user created&lt;/code&gt; or &lt;code&gt;[profile] user creation failed&lt;/code&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  NgRx Reducer -
&lt;/h2&gt;

&lt;p&gt;Reducers are &lt;a href="https://en.wikipedia.org/wiki/Pure_function"&gt;&lt;strong&gt;pure functions&lt;/strong&gt;&lt;/a&gt; which perform transitions from one state to another state based on the latest action dispatched. The reducer functions do not modify the existing state, rather it returns a new state for every state transition. Hence all the reducer functions perform immutable operations.&lt;/p&gt;

&lt;h3&gt;
  
  
  CreateReducer
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;NgRx&lt;/strong&gt; provides a &lt;a href="https://ngrx.io/api/store/createReducer"&gt;createReducer&lt;/a&gt; function to create reducers. It takes &lt;code&gt;initialState&lt;/code&gt; as the first param and &lt;code&gt;any&lt;/code&gt; number of &lt;code&gt;on&lt;/code&gt; functions. The &lt;code&gt;on&lt;/code&gt; function provide association between actions and the state changes.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;When an action is dispatched, all the reducers receive the action. The &lt;code&gt;on&lt;/code&gt; function mapping determines whether the reducer should handle the action.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;createReducer&lt;/code&gt; function returns an &lt;a href="https://ngrx.io/api/store/ActionReducer"&gt;ActionReducer&lt;/a&gt; function . ActionReducer function takes an &lt;a href="https://ngrx.io/api/store/Action"&gt;Action&lt;/a&gt; and a &lt;a href="https://ngrx.io/api/store/State"&gt;State&lt;/a&gt; as input, and returns a new computed State.&lt;/p&gt;

&lt;p&gt;Let’s go ahead a create reducer that handles transitions for &lt;code&gt;ProfileFeatureState&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import * as AppActions from './app.actions';

const theProfFeatureReducer = createReducer(
  initialProfileFeatureState,
  on(AppActions.addUsers, (state, { users }) =&amp;gt; ({
    ...state,
    users: [...users]
  })),
  on(AppActions.addPosts, (state, { posts }) =&amp;gt; ({
    ...state,
    posts: [...posts]
  })),

);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;createReducer&lt;/code&gt; function maps many actions and returns an &lt;code&gt;ActionReducer&lt;/code&gt; function.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;addUsers&lt;/code&gt; action is &lt;strong&gt;mapped&lt;/strong&gt; to a &lt;em&gt;function that creates a new &lt;code&gt;User&lt;/code&gt; array and returns a newly computed state&lt;/em&gt;. Similarly the &lt;code&gt;addPosts&lt;/code&gt; action is mapped.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;The […] &lt;code&gt;spread operator&lt;/code&gt; copies the properties of the object and returns a new object. It only performs the shallow copying and does not copy the nested structures. You should always consider a better alternative if you are dealing with a state that contains nested data structures. Libraries like &lt;strong&gt;lodash&lt;/strong&gt; provide methods to clone nested structures.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Create ActionReducerMap
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;ActionReducerMap&lt;/code&gt; provides the mapping as &lt;code&gt;key-value&lt;/code&gt; pairs where the &lt;code&gt;key&lt;/code&gt; represents the feature name as a string and the &lt;code&gt;value&lt;/code&gt; is the &lt;code&gt;ActionReducer function&lt;/code&gt; returned by &lt;code&gt;createReducer&lt;/code&gt; function.&lt;/p&gt;

&lt;p&gt;In our case, the &lt;code&gt;ActionReducerMap&lt;/code&gt; will contain &lt;code&gt;profile&lt;/code&gt; as a key and &lt;code&gt;value&lt;/code&gt; as &lt;code&gt;theProfFeatureReducer&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/**The profileFeatureReducer function is necessary as function calls are not supported in the View Engine AOT compiler. It is no longer required if you use the default Ivy AOT compiler (or JIT)**/

function profileFeatureReducer
(state: ProfileFeatureState = initialState, action: Action) {
  return theProfFeatureReducer(state, action);
}

/ **AppActionReducer Map** /
export const AppActionReducerMap: ActionReducerMap&amp;lt;AppState&amp;gt; = {
  profile: profileFeatureReducer
  // ... other feature go here

};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;It is not necessary to create an &lt;code&gt;ActionReducerMap&lt;/code&gt;. You can directly provide the mapping in &lt;code&gt;StoreModule.forRoot({key: ActionReducer})&lt;/code&gt;while registering the reducer in app.module.ts. You can also separately register the feature state in the feature module. I prefer creating the &lt;code&gt;ActionReducerMap&lt;/code&gt;separately as it provides a better type checking in Typescript.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;At this point, our &lt;code&gt;app.reducer.ts&lt;/code&gt; file should look like :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/ **app.reducer.ts** /
export interface ProfileFeatureState {
  users: User[];
  posts: Post[];
}

export const initialProfileFeatureState: ProfileFeatureState = {
  users: null,
  posts: null
};

export interface AppState {
  profile: ProfileFeatureState;
}

const theProfFeatureReducer = createReducer(
  initialProfileFeatureState,
  on(AppActions.addUsers, (state, { users }) =&amp;gt; ({
    ...state,
    users: [...users]
  })),
  on(AppActions.addPosts, (state, { posts }) =&amp;gt; ({
    ...state,
    posts: [...posts]
  }))
);

function profileFeatureReducer(state: ProfileFeatureState = initialProfileFeatureState, action: Action) {
  return theProfFeatureReducer(state, action);
}

export const AppActionReducerMap: ActionReducerMap&amp;lt;AppState&amp;gt; = {
  profile: profileFeatureReducer
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Register the State
&lt;/h4&gt;

&lt;p&gt;Once the reducer is created, It should be registered in the Module . The state can be registered using one of the two options:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Register Root state&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To register the global store in the application&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;StoreModule.forRoot({ AppActionReducerMap })

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;StoreModule.forRoot()&lt;/code&gt; takes &lt;code&gt;ActionReducerMap&lt;/code&gt; as an argument. The map contains &lt;code&gt;key&lt;/code&gt; and &lt;code&gt;ActionReducer&lt;/code&gt; Object returned by &lt;code&gt;createReducer&lt;/code&gt; function.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Register each feature state separately -&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Feature states are similar to root states but they represent the state of specific features of an application. Typically, each feature should be registed in its own module.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;StoreModule.forFeature({ profile: profileFeatureReducer })

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you have come this far. You might also want to read about NgRx Selectors.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;How to create NgRx Selectors&lt;/li&gt;
&lt;li&gt;How to use createSelector function to compose selectors with - single or multiple slices of state&lt;/li&gt;
&lt;li&gt;How to use a projector function to return only a part within the slice of state.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;NgRx selectors are used to select a slice of state. I have a detailed post about it &lt;strong&gt;&lt;a href="https://www.initgrep.com/posts/javascript/angular/state-management-in-angualar-using-ngrx"&gt;here&lt;/a&gt;&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

</description>
      <category>angular</category>
      <category>typescript</category>
      <category>all</category>
      <category>ngrx</category>
    </item>
    <item>
      <title>Ngrx Effects - Isolate side-effects in angular applications</title>
      <dc:creator>irshad sheikh</dc:creator>
      <pubDate>Tue, 15 Sep 2020 00:00:00 +0000</pubDate>
      <link>https://dev.to/irshsheik/ngrx-effects-isolate-side-effects-in-angular-applications-24ej</link>
      <guid>https://dev.to/irshsheik/ngrx-effects-isolate-side-effects-in-angular-applications-24ej</guid>
      <description>&lt;h2&gt;
  
  
  what is a Side-effect?
&lt;/h2&gt;

&lt;p&gt;A &lt;a href="http://en.wikipedia.org/wiki/Side_effect_%28computer_science%29"&gt;side effect&lt;/a&gt; refers simply to the modification of some kind of state - for instance:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;em&gt;Changing the value of a variable;&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;Writing some data to disk;&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;Enabling or disabling a button in the User Interface.&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;…&lt;a href="https://softwareengineering.stackexchange.com/questions/40297/what-is-a-side-effect"&gt;source&lt;/a&gt;&lt;/p&gt;

&lt;h5&gt;
  
  
  Table of contents
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Why NgRx Effects?&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;Service based design vs NgRx Effects based design&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;NgRx Effects&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;Installation&lt;/li&gt;
&lt;li&gt;Implementation&lt;/li&gt;
&lt;li&gt;Register NgRx Effects in module&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Why NgRx Effects?
&lt;/h2&gt;

&lt;p&gt;A pure component has an immutable input and produces the events as output. These components are essentially dumb and most of the computations are done outside of it. A pure component has a single responsibility similar to &lt;em&gt;pure functions&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Now, If the components are not doing any computations, most of the computations and side-effects would be moved inside the services. That is the first-hand use of angular services. It is easy to inject them into components and perform various computations.&lt;/p&gt;

&lt;p&gt;Now here are a few things you should consider -&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;First of all, if your application is growing fast and you are storing/managing state inside your components or services, you should consider a state management solution.&lt;/li&gt;
&lt;li&gt;The services are an ideal choice but you have to manually take care of storing the state, making sure the state remains immutable, consistent, and available for all the dependent components as well as services.&lt;/li&gt;
&lt;li&gt;Let’s assume, you have a service taking care of communicating via APIs to some remote server. You inject the service in a component and call the method of the service inside the component.&lt;/li&gt;
&lt;li&gt;…and if you have another service, which performs some computation which is supposed to be run when the user interacts with UI such as a click of a button. Again, you would inject the service in component, and on &lt;code&gt;click&lt;/code&gt; of the button, a method of the service is called.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;It works great… But if you notice, the component is tighly coupled with the service and it knows about what operations to perform when a user &lt;em&gt;clicks a button&lt;/em&gt; or when an API should be called.&lt;/p&gt;

&lt;p&gt;The very first &lt;strong&gt;disadvantage&lt;/strong&gt; of this pattern you would come across is &lt;strong&gt;&lt;em&gt;components are hard to test since they are dependent on many services&lt;/em&gt;&lt;/strong&gt;. You would also notice that It is almost &lt;strong&gt;&lt;em&gt;impossible to reuse the components&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;So what is the alternative approach?&lt;/em&gt;&lt;/strong&gt; …&lt;/p&gt;

&lt;p&gt;The alternative approach is to let components be pure and not responsible for managing the state . Instead make them reactive so that when an input data is available, it renders it to UI and when there are UI interactions, it generates the relevant Events.&lt;/p&gt;

&lt;p&gt;That is it…&lt;/p&gt;

&lt;p&gt;The component does not have to know, how the Input data is made available or how the events are handled.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The services are nevertheless an important part of the application. They would still contain all the methods to do various computations or communicate via APIs. But now they are no longer being injected inside the component.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;I have already written a post about &lt;a href="https://dev.to/igagrock/reactive-state-management-in-the-angular-ngrx-store-actions-selectors-4ap6"&gt;reactive state management using NgRx store, actions, and selectors.&lt;/a&gt; You can go through it to have an understanding of NgRx state management.&lt;/p&gt;

&lt;p&gt;Let’s see a comparison between the service-based design and NgRx effects.&lt;/p&gt;

&lt;p&gt;You might notice fewer elements in play during service-based design but don’t let it fool you. It is better to have more elements in application than to have a lousy app.&lt;/p&gt;

&lt;h3&gt;
  
  
  Service based design
&lt;/h3&gt;

&lt;p&gt;Suppose, our &lt;code&gt;AppComponent&lt;/code&gt;requires a list of users.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;We have a service &lt;code&gt;AppRemoteService&lt;/code&gt; and it contains &lt;code&gt;users$ observable&lt;/code&gt; which can be subscribed to get a list of users.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;users$ = this.httpClient.get&amp;lt;User[]&amp;gt;(URL).pipe(take(1));

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;We have injected the &lt;code&gt;AppRemoteService&lt;/code&gt; in side the &lt;code&gt;AppComponent&lt;/code&gt; and we would subscribe to &lt;code&gt;AppRemoteService.users$&lt;/code&gt; observable .
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Component({
    template: `
    &amp;lt;div class="user-container" 
      *ngIf="localUsers"&amp;gt;
     &amp;lt;app-user *ngfor="let user of localUsers" 
                [inputUser]="user"&amp;gt;
  &amp;lt;/div&amp;gt;
    `
})
export class AppComponent{
//state inside component
localUsers: User[];

constructor(private remoteService: RemoteService){}

  ngOnInit(){
      //handle the subscription here
  this.remoteService.users$.subscrible(
      users =&amp;gt; this.localUsers = users;
      );
  }
  } 

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  NgRx Effects based design
&lt;/h3&gt;

&lt;p&gt;Here is how NgRx effects will change it -&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The AppComponent would only require &lt;code&gt;NgRx Store&lt;/code&gt; to select the &lt;code&gt;state&lt;/code&gt; or dispatch &lt;code&gt;actions&lt;/code&gt;.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export class AppComponent implements OnInit {
 constructor(private store: Store&amp;lt;fromApp.AppState&amp;gt;) { }
 }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;As soon as the component requires the list of users, it would dispatch an action &lt;code&gt;loadUsers&lt;/code&gt; when the component is initialized.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export class AppComponent implements OnInit {
 constructor(private store: Store&amp;lt;fromApp.AppState&amp;gt;) { }

 ngOnInit(): void {
     //action dispatched
    this.store.dispatch(fromActions.loadUsers());
 }

}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;The Component will use &lt;strong&gt;NgRx selector&lt;/strong&gt; &lt;code&gt;selectUsers&lt;/code&gt; and subscribe to its observable.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
@Component({
 template: `
     &amp;lt;div class="user-container" 
         *ngIf="localUsers$ | async as users"&amp;gt;
         &amp;lt;app-user *ngfor="let user of users" 
                    [inputUser]="user"&amp;gt;
     &amp;lt;/div&amp;gt;
 `
})
export class AppComponent implements OnInit {
  localusers$ = this.store.select(fromSelectors.selectUsers);

  constructor(private store: Store&amp;lt;fromApp.AppState&amp;gt;) { }

  ngOnInit(): void {
    this.store.dispatch(fromActions.loadUsers());
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;NgRx Effects&lt;/strong&gt; will be listening to the stream of actions dispatched since the latest state change. &lt;code&gt;loadUsers$&lt;/code&gt; effect is interested in &lt;code&gt;loadUsers&lt;/code&gt; action dispatched by &lt;code&gt;AppComponent&lt;/code&gt;. As such, when the component is initialized, the &lt;code&gt;loadUsers&lt;/code&gt; action is dispatched. The effect reacts to it and subscribes &lt;code&gt;remoteservice.users$&lt;/code&gt; .&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Once the data is fetched, the &lt;code&gt;loadUsers$&lt;/code&gt; effect will dispatch &lt;code&gt;addUsers&lt;/code&gt; action with associated metadata - users. The respective reducer function will transition the state. The latest state will contain recently feteched users.&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//app.effects.ts
 loadUsers$ = createEffect(
    () =&amp;gt; this.action$.pipe(
        ofType(AppActions.loadUsers),
        mergeMap(() =&amp;gt; this.remoteService.users$
        .pipe(
            map(users =&amp;gt; AppActions.addUsers({ users })),
            catchError(error =&amp;gt; {
            return of(error);
            })
        )),
 ));



//app.reducer.ts
//addUsers action mapping 

const theReducer = createReducer(
  initialState,
  on(AppActions.addUsers, (state, { users }) =&amp;gt; ({
    ...state,
    users: [...users]
  }))

);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;As soon as the data is available, the &lt;code&gt;localusers$&lt;/code&gt; observable subscription will have users list ready for the component to render.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In contrast with the service-based approach isolating the side-effects using NgRx Effects, the component is not concerned about how the data is loaded. Besides allowing a component to be pure, It also makes testing components easier and increases the chances of reusability.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;If you have come this far, you might also want to know how to install and implement the NgRx Effects in an angular application. I have written a detailed post. &lt;strong&gt;&lt;a href="https://www.initgrep.com/posts/javascript/angular/handle-side-effects-in-angular-ngrx"&gt;Click here&lt;/a&gt;&lt;/strong&gt; to check it out.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>angular</category>
      <category>javascript</category>
      <category>typescript</category>
      <category>all</category>
    </item>
    <item>
      <title>Create Microsoft Office Addin using Angular CLI</title>
      <dc:creator>irshad sheikh</dc:creator>
      <pubDate>Tue, 18 Jun 2019 17:07:29 +0000</pubDate>
      <link>https://dev.to/igagrock/create-microsoft-office-addin-using-angular-cli-bk7</link>
      <guid>https://dev.to/igagrock/create-microsoft-office-addin-using-angular-cli-bk7</guid>
      <description>&lt;p&gt;If you are reading this tutorial, you are probably one of the developers out there trying to figure out how to create a Microsoft office add-in using Angular CLI.&lt;/p&gt;

&lt;p&gt;Microsoft provides the complete process for creating add-ins using angular through a yeoman generator for VS Code editor. This method works fine but it uses the manual webpack config with angular. I also faced issues such as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;not able to use template-url in angular components&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;no support for CSS files for each angular components&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The goal of this tutorial is to demonstrate a way of creating a project structure using &lt;a href="mailto:angular@8.0.0"&gt;angular@8.0.0&lt;/a&gt; CLI, configure it and make it ready for developing office add-ins.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Please note, It still does not support the &lt;code&gt;office-addin-debugger&lt;/code&gt; plugin provided by Microsoft. I have added it as an npm dev-dependency here and I am still trying to figure how to make it work. But you can always debug the add-in on the web app such as outlook web.&lt;/em&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;I assume you have &lt;code&gt;node&lt;/code&gt; and &lt;code&gt;npm&lt;/code&gt; already installed&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Let us begin –&lt;/strong&gt;  &lt;/p&gt;

&lt;h2&gt;
  
  
  Generate Office add-in angular app using yeoman generator
&lt;/h2&gt;

&lt;p&gt;Office &lt;a href="https://docs.microsoft.com/en-us/outlook/add-ins/quick-start?tabs=visual-studio-code"&gt;official docs&lt;/a&gt; have provided detailed steps. I will only provide concise steps.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Run the following command in the command line. It will install the office Yeoman generator.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install -g yo generator-office
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Generate the office adding angular project structure using the below command.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yo office --skip-install
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The above command will provide interactive input. Choose the below options&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight javascript"&gt;&lt;code&gt;   &lt;span class="nx"&gt;Choose&lt;/span&gt; &lt;span class="nx"&gt;a&lt;/span&gt; &lt;span class="nx"&gt;project&lt;/span&gt; &lt;span class="nx"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;Use&lt;/span&gt; &lt;span class="nx"&gt;arrow&lt;/span&gt; &lt;span class="nx"&gt;keys&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; 
   &lt;span class="c1"&gt;// choose (2) Office Add-in Task Pane project using Angular framework&lt;/span&gt;

   &lt;span class="nx"&gt;Choose&lt;/span&gt; &lt;span class="nx"&gt;a&lt;/span&gt; &lt;span class="nx"&gt;script&lt;/span&gt; &lt;span class="nx"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;Use&lt;/span&gt; &lt;span class="nx"&gt;arrow&lt;/span&gt; &lt;span class="nx"&gt;keys&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
   &lt;span class="c1"&gt;// choose (1) Typescript&lt;/span&gt;

   &lt;span class="nx"&gt;What&lt;/span&gt; &lt;span class="k"&gt;do&lt;/span&gt; &lt;span class="nx"&gt;you&lt;/span&gt; &lt;span class="nx"&gt;want&lt;/span&gt; &lt;span class="nx"&gt;to&lt;/span&gt; &lt;span class="nx"&gt;name&lt;/span&gt; &lt;span class="nx"&gt;your&lt;/span&gt; &lt;span class="nx"&gt;add&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="k"&gt;in&lt;/span&gt;&lt;span class="p"&gt;?&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;My&lt;/span&gt; &lt;span class="nx"&gt;Office&lt;/span&gt; &lt;span class="nx"&gt;Add&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="k"&gt;in&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; 
   &lt;span class="c1"&gt;//Give any name you want. for this tutorial, I would keep demo-addin&lt;/span&gt;

   &lt;span class="nx"&gt;Which&lt;/span&gt; &lt;span class="nx"&gt;Office&lt;/span&gt; &lt;span class="nx"&gt;client&lt;/span&gt; &lt;span class="nx"&gt;application&lt;/span&gt; &lt;span class="nx"&gt;would&lt;/span&gt; &lt;span class="nx"&gt;you&lt;/span&gt; &lt;span class="nx"&gt;like&lt;/span&gt; &lt;span class="nx"&gt;to&lt;/span&gt; &lt;span class="nx"&gt;support&lt;/span&gt;&lt;span class="p"&gt;?&lt;/span&gt; 
   &lt;span class="c1"&gt;//choose (3) Outlook&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Notice &lt;code&gt;--skip-install&lt;/code&gt; argument. Well, We don’t want &lt;code&gt;npm&lt;/code&gt; to install all the dependencies here. We would only need &lt;code&gt;manfiest.xml&lt;/code&gt; file and some of the Microsoft office dependencies from package.json.&lt;/p&gt;

&lt;p&gt;Our outlook addin project structure is done using yeomen generator. Below is the structure of the generated project.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;.
    ├── assets
    │   ├── icon-16.png
    │   ├── icon-32.png
    │   ├── icon-80.png
    │   └── logo-filled.png
    ├── CONTRIBUTING.md
    ├── LICENSE
    ├── manifest.xml
    ├── package.json
    ├── package-lock.json
    ├── README.md
    ├── src
    │   ├── commands
    │   └── taskpane
    ├── tsconfig.json
    └── webpack.config.js
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;
  
  
  Creating an angular application using Angular CLI
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Install the Angular CLI
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install -g @angular/cli
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Generate an angular app
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ng new demo-angular-addin
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Run &lt;code&gt;ng serve&lt;/code&gt; to make sure the app is working&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The structure of our angular app would look like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;.
      ├── angular.json
      ├── e2e
      ├── node_modules
      ├── package.json
      ├── package-lock.json
      ├── README.md
      ├── src
      ├── tsconfig.json
      └── tslint.json
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;
  
  
  Copy the addin manifest to the angular application
&lt;/h2&gt;

&lt;p&gt;Copy the &lt;code&gt;manifest.xml&lt;/code&gt; from demo-addin which we generated using yeomen generator and paste it in the root folder of the angular app.&lt;/p&gt;

&lt;h2&gt;
  
  
  Change the angular application default port number
&lt;/h2&gt;

&lt;p&gt;Notice that the &lt;code&gt;manifest.xml&lt;/code&gt; has all the mappings for port 3000 such as &lt;code&gt;localhost:3000&lt;/code&gt;. Also, the angular application default port is 4200. We either have to change the port in manifest or change angular server port. Either way, it should work.&lt;/p&gt;

&lt;p&gt;Let us change the default port(4200) of the angular app to 3000. Open &lt;code&gt;angular.json&lt;/code&gt; file and look for &lt;code&gt;server&lt;/code&gt; key and changed the default port. Below is an example.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"serve": {
     "builder": "@angular-devkit/build-angular:dev-server",
     "options": {
         "browserTarget": "demo-angular-addin:build",
         "port": 3000
    },
    "configurations": {
                "production": {
        "browserTarget": "demo-angular-addin:build:production",
        "port": 3000
                }
    }
   },
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Run &lt;code&gt;ng-serve&lt;/code&gt; to validate the port.&lt;/p&gt;

&lt;h2&gt;
  
  
  Copy the default icons from generated office addin to angular app
&lt;/h2&gt;

&lt;p&gt;The default icons provided are configured in addin manifest. These icons will be shown when the add-in is loaded.&lt;/p&gt;

&lt;p&gt;If both the projects are in the same folder, use the below command or do it manually.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cp -r demo-addin/assets/* demo-angular-addin/src/assets/
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;
  
  
  Update the manifest mapping – replace with index.html page
&lt;/h2&gt;

&lt;p&gt;In the &lt;code&gt;manifest.xml&lt;/code&gt;, for each occurrence of &lt;code&gt;taskpane.url&lt;/code&gt; or any other locations where the URL resembles like &lt;code&gt;https://localhost:3000/taskpane.html&lt;/code&gt;, update &lt;strong&gt;taskpane.html&lt;/strong&gt; to &lt;strong&gt;index.html&lt;/strong&gt;. You can also remove the taskpane.html and only keep host: port (localhost:3000) only.&lt;/p&gt;

&lt;h2&gt;
  
  
  Configure SSL for the angular application
&lt;/h2&gt;

&lt;p&gt;It is mandatory for Microsoft Office add-ins to be served over &lt;code&gt;https&lt;/code&gt; connection. We need to generate an SSL certificate and key and configure our angular application to serve over &lt;code&gt;https&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Go to this tutorial titled &lt;a href="https://medium.com/@rubenvermeulen/running-angular-cli-over-https-with-a-trusted-certificate-4a0d5f92747a"&gt;Running Angular CLI over HTTPS with a Trusted Certificate&lt;/a&gt;. It has all the steps to configure SSL in an angular application.&lt;/p&gt;

&lt;p&gt;If you still face any issues, try to install the certificate by choosing &lt;code&gt;local machine&lt;/code&gt;. and use the SSL options directly in the terminal.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ng serve --ssl true --ssl-cert "ssl/server.crt" --ssl-key "ssl/server.key"
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;You can also configure the same command in &lt;code&gt;package.json&lt;/code&gt; inside scripts – such as :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"start-ssl" : "ng serve --ssl true --ssl-cert \"ssl/server.crt\" --ssl-key \"ssl/server.key\""
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;
  
  
  Change the Typescript compiler target type to es5 instead of es2015
&lt;/h2&gt;

&lt;p&gt;While I was testing the Outlook addin for the desktop app, it did not load angular components. However, It was working fine in the outlook web app. I initially posted a &lt;a href="https://stackoverflow.com/questions/56600059/microsoft-office-addin-for-outlook-does-not-load-on-outlook-desktop-app"&gt;stackOverFlow question&lt;/a&gt;. After thorough debugging, I was able to figure out that Outlook desktop app does not support &lt;code&gt;es2015&lt;/code&gt; yet.&lt;/p&gt;

&lt;p&gt;Let’s update &lt;code&gt;tsconfig.app.json&lt;/code&gt; and add the new target under &lt;code&gt;compilerOptions&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"target": "es5"
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;
  
  
  Add the missing dependencies and dev-dependencies using npm
&lt;/h2&gt;

&lt;h5&gt;
  
  
  npm dependencies
&lt;/h5&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install --save @microsoft/office-js @microsoft/office-js-helpers@^1.0.1 office-ui-fabric-js@^1.3.0
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;I have added &lt;code&gt;office-js&lt;/code&gt; also as an npm dependency. However, &lt;code&gt;office js&lt;/code&gt; is not a valid es6 module and it can not be used as such. We still need to load it using script tags from CDN. We will get to it later in the tutorial. You can also keep track of this issue &lt;a href="https://github.com/Microsoft/TypeScript/issues/11420"&gt;here&lt;/a&gt;. If it is updated as an es6 module in the future, you can directly use it by importing in components rather loading it from CDN.&lt;/p&gt;

&lt;h5&gt;
  
  
  npm devdependencies
&lt;/h5&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install --save-dev @types/office-js@^1.0.1 @types/office-runtime@^1.0.7 office-addin-debugging@^2.1.13 office-addin-dev-certs@^1.0.1 office-toolbox@^0.1.1
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h5&gt;
  
  
  Add the missing types
&lt;/h5&gt;

&lt;p&gt;During compilation, Typescript compiler is going to complain about missing types. Since we will be using Microsoft Office APIs during development, we will need to add office-js to types.&lt;/p&gt;

&lt;p&gt;Update the &lt;code&gt;tsconfig.app.json&lt;/code&gt; and add &lt;code&gt;office-js&lt;/code&gt; under the &lt;code&gt;types&lt;/code&gt; array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"types": [
      "office-js"
   ]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;
  
  
  Copy the script from taskpane.html to index.html
&lt;/h2&gt;

&lt;p&gt;As mentioned earlier, Office-js has to be added from CDN. Along with it, if you intend to use office &lt;code&gt;fabric-ui&lt;/code&gt; for developing the addin user interface, include the fabric libraries from CDN.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!-- Office JavaScript API --&amp;gt;
   &amp;lt;script type="text/javascript" src="https://appsforoffice.microsoft.com/lib/1.1/hosted/office.js"&amp;gt;&amp;lt;/script&amp;gt;

   &amp;lt;!-- For more information on Office UI Fabric, visit https://developer.microsoft.com/fabric. --&amp;gt;
   &amp;lt;link rel="stylesheet" href="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-js/1.4.0/css/fabric.min.css" /&amp;gt;
   &amp;lt;link rel="stylesheet" href="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-js/1.4.0/css/fabric.components.min.css" /&amp;gt;

   &amp;lt;script src="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-js/1.4.0/js/fabric.min.js"&amp;gt;&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;
  
  
  Bootstrap the angular application inside the &lt;code&gt;Office.initialize&lt;/code&gt; function.
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;Office.initialize&lt;/code&gt; makes sure the addin is loaded after the Office application has completely loaded.&lt;/p&gt;

&lt;p&gt;let’s update the &lt;code&gt;main.ts&lt;/code&gt; file by wrapping the bootstrap code inside the &lt;code&gt;initialize&lt;/code&gt; function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Office.initialize = reason =&amp;gt;{
       platformBrowserDynamic().bootstrapModule(AppModule)
                 .catch(err =&amp;gt; console.error(err));
   };
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The only thing left now is to side-load our Microsoft Outlook addin. You can find it in official documentation &lt;a href="https://docs.microsoft.com/en-us/office/dev/add-ins/testing/create-a-network-shared-folder-catalog-for-task-pane-and-content-add-ins"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;--&lt;br&gt;
Originally published at &lt;a href="https://www.initgrep.com/posts/javascript/angular/microsoft-office-addin-using-angular-cli"&gt;https://www.initgrep.com&lt;/a&gt; on June 16, 2019.&lt;/p&gt;

</description>
      <category>angular</category>
      <category>yeomengenerator</category>
      <category>microsoftofficeaddin</category>
    </item>
    <item>
      <title>Programmatic Criteria Queries using JPA Criteria API</title>
      <dc:creator>irshad sheikh</dc:creator>
      <pubDate>Mon, 11 Feb 2019 00:00:00 +0000</pubDate>
      <link>https://dev.to/irshsheik/programmatic-criteria-queries-using-jpa-criteria-api-1h65</link>
      <guid>https://dev.to/irshsheik/programmatic-criteria-queries-using-jpa-criteria-api-1h65</guid>
      <description>&lt;p&gt;Java Persistence API (JPA) provides the specification of managing data, such as accessing and persisting data, between Java Objects and the databases.&lt;/p&gt;

&lt;p&gt;There are obviously many ways in JPA that could be used to interact with a database such as JPQL(Java Persistence Query Language), Criteria API, and Entity specific methods such as persist, merge, remove, flush, etc.&lt;/p&gt;

&lt;p&gt;I initially found Criteria API quite intimidating. To be frank, I had to invest quite some time to figure it out. It eventually turned out to be quite a fluent API. I thought why not just write about the experiences. So here it is, &lt;strong&gt;“Creating Programmatic Criteria Queries using JPA Criteria API”&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Criteria Queries are type-safe and portable. They are written using Java programming language APIs. They use the abstract schema of the persistent entities to find, modify, and delete persistent entities by invoking JPA Entity Operations.&lt;/p&gt;

&lt;p&gt;We will be using the following domain model for building the criteria queries in this tutorial.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--NWj2eQKi--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/http://www.initgrep.com/assets/images/Criteria-object-UML.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--NWj2eQKi--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/http://www.initgrep.com/assets/images/Criteria-object-UML.png" alt="Object Model- UML" width="458" height="304"&gt;&lt;/a&gt;&lt;em&gt;UML diagram describing the Object Relationship Mapping&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;We have three Objects( ref. to diagram above ) &lt;code&gt;Student&lt;/code&gt; , &lt;code&gt;Course&lt;/code&gt; and &lt;code&gt;Passport&lt;/code&gt;. Each of the Objects has a relationship with each other:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;Student&lt;/code&gt; has a &lt;code&gt;One-To-One&lt;/code&gt; relationship with &lt;code&gt;Passport&lt;/code&gt;. It means that Each Student can only have one Passport and vice versa.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Student&lt;/code&gt; has a &lt;code&gt;One-To-Many&lt;/code&gt; relationship with &lt;code&gt;Address&lt;/code&gt; which means that a student can have one or more addresses and an address is always assigned to one student.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Student&lt;/code&gt; has a &lt;code&gt;Many-To-Many&lt;/code&gt; relationship with &lt;code&gt;Course&lt;/code&gt; which means that Each Student can enroll in many courses and one course can have many students enrolled.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We will begin with a simple Criteria Query and slowly try to build upon it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public Long getStudentsCount() {

        / **CriteriaBuilder instance** / 
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();

        / **create a criteriaQuery Object** /
        CriteriaQuery&amp;lt;Long&amp;gt; studentQuery = builder.createQuery(Long.class);

        / **create a Root Object -&amp;gt; references to the queried entity** /
        Root&amp;lt;Student&amp;gt; studentRoot = studentQuery.from(Student.class);

        / **Path Object to refer the attribute name of entity** /
        / **we are not using it for now** /
        Path&amp;lt;Object&amp;gt; namePath = studentRoot.get("name");

        / **Aggregate Expression for count operation** /
        Expression&amp;lt;Long&amp;gt; countExpression = builder.count(studentRoot);

        / **** /
        studentQuery.select(countExpression);

        /** instance of Typed Query */
        TypedQuery&amp;lt;Long&amp;gt; typedStudentQuery = 
                            entityManager.createQuery(studentQuery);

        / **return the result** /
        Long count = typedStudentQuery.getSingleResult();

        return count;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;The above code example retrieves the total count of students present in the database.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Criteria queries are an Object graph where each part of the graph represents an atomic part of the query. The various steps in building the object graph roughly translate to the following steps.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A &lt;code&gt;CriteriaBuilder&lt;/code&gt; interface contains all the required methods to build Criteria Queries, Expressions, Ordering, and Predicates.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;CriteriaQuery&lt;/code&gt; interface defines functionality required to build a top-level query. The type specified for criteria query i.e &lt;code&gt;criteriaQuery&amp;lt;Class&amp;lt;T&amp;gt; resultClass&amp;gt;&lt;/code&gt; would be the type of the result returned. If no type is provided, the type of result would be &lt;code&gt;Object&lt;/code&gt;. Criteria Query contains the methods that specify the item(s) to be returned in the query result, restrict the result based on certain conditions, group results, specify an order for the result, and &lt;a href="https://docs.oracle.com/javaee/6/api/javax/persistence/criteria/CriteriaQuery.html"&gt;much more&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Root&lt;/code&gt; interface represents the root entities involved in the query. There could be multiple roots defined in the Criteria Query.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Path&lt;/code&gt; interface represents the path to the attribute in the &lt;code&gt;root&lt;/code&gt; entity. &lt;code&gt;Path&lt;/code&gt; interface also &lt;code&gt;extends&lt;/code&gt; to the &lt;code&gt;Expression&lt;/code&gt; Interface which contains methods that return Predicates.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;builder.count()&lt;/code&gt; is an aggregate method. It returns an expression that would be used for &lt;code&gt;Selection&lt;/code&gt; of the result. When aggregate methods are used as arguments in the &lt;code&gt;select&lt;/code&gt; method, the type of the query should match the return type of aggregate method.&lt;/li&gt;
&lt;li&gt;A &lt;code&gt;TypedQuery&lt;/code&gt; instance is required to run the &lt;code&gt;CriteriaQuery&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The final output of the above example is below :)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;select
        count(student0_.id) as col_0_0_ 
    from
        student student0_
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;It seems quite the over work–doesn’t it.&lt;/strong&gt; The output of so many lines of code is just a plain old &lt;code&gt;SELECT&lt;/code&gt; query. But the Criteria API was created to serve a different purpose i.e &lt;em&gt;programmable Query API&lt;/em&gt;. It helps to build queries dynamically. You could write just one program to build queries for all objects in your application or build queries depending upon your business logic.&lt;/p&gt;

&lt;p&gt;Let’s say, we want to get the count of either Students, Courses or any other entities present in our application. We could either write different queries for each of them or we could only use Criteria API.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public &amp;lt;T&amp;gt; Long getCountOfEntity(Class&amp;lt;T&amp;gt; claz) {

        CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery&amp;lt;Long&amp;gt; studentQuery = builder.createQuery(Long.class);
        Root&amp;lt;T&amp;gt; root = studentQuery.from(claz);
        Expression&amp;lt;Long&amp;gt; countExpression = builder.count(root);
        studentQuery.select(countExpression);
        TypedQuery&amp;lt;Long&amp;gt; typedStudentQuery = em.createQuery(studentQuery);

        return typedStudentQuery.getSingleResult();
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I have only updated the previous example to allow the generic parameter which specifies the &lt;code&gt;Class&lt;/code&gt; of the &lt;code&gt;Entity&lt;/code&gt;. The rest of the Code stays the same. You can learn more about Java Generics &lt;a href="https://docs.oracle.com/javase/tutorial/java/generics/index.html"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Let’s look at the above example in detail.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Criteria Query&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CriteriaQuery&amp;lt;T&amp;gt; createQuery(Class&amp;lt;T&amp;gt; resultClass);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;CreateQuery&lt;/code&gt; method takes the &lt;code&gt;Class&lt;/code&gt; name of the result type as an argument.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If the result is returned as a data-set related to the entity e.g all the students or one of the students. The parameter should be &lt;code&gt;Student.class&lt;/code&gt;.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;builder.createQuery(Student.class);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;If the query returns any other result irrespective of which entity it works on, It should have a parameter of the returned type. As we saw above, when the count was returned, the parameter type was &lt;code&gt;Long.class&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;builder.createQuery(Long.class);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Root&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Root&amp;lt;T&amp;gt; root = studentQuery.from(Student.Class)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;Root&lt;/code&gt; refers to the entity on which the query would be run such as &lt;code&gt;Student.class&lt;/code&gt; in the above example.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Select&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;studentQuery.select(countExpression);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;select&lt;/code&gt; method specifies the result to be returned by the Query. If all the attributes of an entity are supposed to be returned instead of just returning the count, we could pass the &lt;code&gt;root&lt;/code&gt; entity as the parameter such as below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;studentQuery.select(studentRoot);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt; &lt;/p&gt;

&lt;p&gt;&lt;em&gt;If you have come this far, you might also want to read about various methods, Criteria API provides to implement criteria join, Fetch Join, Aggregate functions, and subqueries. I have posted a detailed post about it. &lt;strong&gt;&lt;a href="https://www.initgrep.com/posts/java/jpa/create-programmatic-queries-using-criteria-api"&gt;Click here&lt;/a&gt;&lt;/strong&gt; to check it out.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>jpa</category>
      <category>java</category>
      <category>hibernate</category>
      <category>all</category>
    </item>
  </channel>
</rss>
