<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chanaka Anuruddha on Medium]]></title>
        <description><![CDATA[Stories by Chanaka Anuruddha on Medium]]></description>
        <link>https://medium.com/@chanaka.14?source=rss-c02b5b76826d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*w6tWkQQc_5YJMMP3Mgohmg.jpeg</url>
            <title>Stories by Chanaka Anuruddha on Medium</title>
            <link>https://medium.com/@chanaka.14?source=rss-c02b5b76826d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 06:36:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chanaka.14/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Creational Design Patterns in Java]]></title>
            <link>https://medium.com/@chanaka.14/creational-design-patterns-in-java-a35219682d71?source=rss-c02b5b76826d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a35219682d71</guid>
            <dc:creator><![CDATA[Chanaka Anuruddha]]></dc:creator>
            <pubDate>Sat, 14 Oct 2023 07:43:20 GMT</pubDate>
            <atom:updated>2023-10-14T13:24:51.621Z</atom:updated>
            <content:encoded><![CDATA[<p>Creational design patterns in Java are a set of techniques that deal with the object creation process, providing efficient and flexible ways to instantiate objects. These patterns focus on managing object creation complexities, ensuring that objects are created in a manner that best suits the application’s needs.</p><p>In this section, we will explore key creational design patterns in Java, such as <strong>Factory Method</strong>,<strong> Abstract Factory </strong>and<strong> Singleton</strong>. Each of these patterns offers a unique approach to object creation, addressing specific requirements and scenarios within your application. These patterns enhance code quality and maintainability, making them valuable tools for simplifying object creation in Java.</p><h4><strong>1. Factory </strong>Pattern</h4><p>The Factory Pattern follows the principle of defining an <strong>interface</strong> or an <strong>abstract class</strong> for creating objects while allowing subclasses to decide which specific class to instantiate.</p><p>This pattern enables sub-classes to select the type of objects they want to create, promoting loose coupling by avoiding the need to bind application-specific classes directly into the code.</p><p>Suppose you have an application that needs to create different types of documents, such as PDFs and Word documents, without the client code knowing the specific classes of these documents. Let’s implement the Factory Design Pattern to achieve this</p><p>First, you define an interface that declares the common methods that all documents will implement. In this case, the Document interface has create() and save() methods.</p><pre>interface Document {<br>    void create();<br>    void save();<br>}</pre><p>Next, you implement concrete classes for different types of documents. In the example, we have two concrete classes: PDFDocument and WordDocument, both implementing the Document interface. Each class provides its specific implementation for the create() and save() methods.</p><pre><br>class PDFDocument implements Document {<br>    public void create() {<br>        System.out.println(&quot;Creating a PDF document&quot;);<br>    }<br><br>    public void save() {<br>        System.out.println(&quot;Saving the PDF document&quot;);<br>    }<br>}<br><br>class WordDocument implements Document {<br>    public void create() {<br>        System.out.println(&quot;Creating a Word document&quot;);<br>    }<br><br>    public void save() {<br>        System.out.println(&quot;Saving the Word document&quot;);<br>    }<br>}</pre><p>Now, you create a factory class, DocumentFactory, which contains factory methods responsible for creating objects. The factory methods take a parameter, documentType, to determine which type of document to create. The factory knows which concrete class to instantiate based on the input parameter.</p><pre>class DocumentFactory {<br>    public Document createDocument(String documentType) {<br>        if (documentType == null) {<br>            return null;<br>        } else if (documentType.equalsIgnoreCase(&quot;PDF&quot;)) {<br>            return new PDFDocument();<br>        } else if (documentType.equalsIgnoreCase(&quot;Word&quot;)) {<br>            return new WordDocument();<br>        }<br>        return null;<br>    }<br>}</pre><p>In your client code, you no longer create objects using constructors of concrete classes. Instead, you call the factory methods on the DocumentFactory to create objects. The client code doesn&#39;t need to know the specific classes of the objects; it relies on the factory to handle the object creation.</p><pre>public class FactoryPatternDocumentExample {<br>    public static void main(String[] args) {<br>        DocumentFactory documentFactory = new DocumentFactory();<br><br>        Document pdfDocument = documentFactory.createDocument(&quot;PDF&quot;);<br>         pdfDocument.create();<br>        pdfDocument.save();<br><br>        Document wordDocument = documentFactory.createDocument(&quot;Word&quot;);<br>        wordDocument.create();<br>        wordDocument.save();<br>    }<br>}</pre><p>Once you’ve created the objects using the factory, you can use them as needed in your application. In this example, we’ve created PDF and Word documents, and the client code demonstrates how to create and use them.</p><h4><strong>2. Abstract Factory </strong>Pattern</h4><p>Abstract Factory pattern is almost similar to Factory Pattern and is considered as another layer of abstraction over factory pattern. Abstract Factory patterns work around a super-factory which creates other factories.<br>Abstract factory pattern implementation provides us with a framework that allows us to create objects that follow a general pattern. So at runtime, the abstract factory is coupled with any desired concrete factory which can create objects of the desired type.</p><p>Let’s look into a example, we’ll create two interfaces, Color and Shape.</p><pre><br>interface Color {<br>    void fill();<br>}<br><br>interface Shape {<br>    void draw();<br>}</pre><p>Implement concrete classes that implement the interfaces. Each concrete class represents a different type of object within its family. In our case, we have two concrete color classes (RedColor and BlueColor) and two shape classes (Circle and Rectangle).</p><pre>// Implement concrete classes for colors<br>class RedColor implements Color {<br>    public void fill() {<br>        System.out.println(&quot;Filling with red color&quot;);<br>    }<br>}<br><br>class BlueColor implements Color {<br>    public void fill() {<br>        System.out.println(&quot;Filling with blue color&quot;);<br>    }<br>}<br><br>// Implement concrete classes for shapes<br>class Circle implements Shape {<br>    public void draw() {<br>        System.out.println(&quot;Drawing a circle&quot;);<br>    }<br>}<br><br>class Rectangle implements Shape {<br>    public void draw() {<br>        System.out.println(&quot;Drawing a rectangle&quot;);<br>    }<br>}</pre><p>Create an abstract factory interface that declares methods for creating objects from the different families. We’ll define a Factory interface with two factory methods: createColor() and createShape().</p><pre><br>interface Factory {<br>    Color createColor();<br>    Shape createShape();<br>}</pre><p>Implement concrete factories that provide specific implementations for creating objects. In our case, we have two concrete factories: RedFactory and BlueFactory, each responsible for creating objects with red or blue colors along with their shapes.</p><pre>// Implement concrete factories for red objects<br>class RedFactory implements Factory {<br>    public Color createColor() {<br>        return new RedColor();<br>    }<br><br>    public Shape createShape() {<br>        return new Circle();<br>    }<br>}<br><br>// Implement concrete factories for blue objects<br>class BlueFactory implements Factory {<br>    public Color createColor() {<br>        return new BlueColor();<br>    }<br><br>    public Shape createShape() {<br>        return new Rectangle();<br>    }<br>}</pre><p>In our client code, we use a specific factory to create objects with the desired colors and shapes. The client code can now create objects without knowing the exact classes of colors and shapes. You simply select the appropriate factory for the type of objects you want to create.</p><pre>public class AbstractFactoryPatternColorShapeExample {<br>    public static void main(String[] args) {<br>        // Create a Red factory<br>        Factory redFactory = new RedFactory();<br><br>        // Create a red color and its corresponding shape<br>        Color redColor = redFactory.createColor();<br>        Shape redShape = redFactory.createShape();<br><br>        // Use red objects<br>        redColor.fill();<br>        redShape.draw();<br><br>        // Create a Blue factory<br>        Factory blueFactory = new BlueFactory();<br><br>        // Create a blue color and its corresponding shape<br>        Color blueColor = blueFactory.createColor();<br>        Shape blueShape = blueFactory.createShape();<br><br>        // Use blue objects<br>        blueColor.fill();<br>        blueShape.draw();<br>    }<br>}</pre><h4>3. Singleton Pattern</h4><p>Singleton pattern is one of the simplest design patterns in Java. As its name suggests, is designed to ensure that a class has only one instance and provides a global point of access to that instance. Sometimes we need to have only one instance of our class for example a single DB connection shared by multiple objects as creating a separate DB connection for every object may be costly.</p><p>Let’s see the simplest implementation.</p><pre>public class SingleObject {<br><br>   //create an object of SingleObject<br>   private static SingleObject instance = new SingleObject();<br><br>   //make the constructor private so that this class cannot be<br>   //instantiated<br>   private SingleObject(){}<br><br>   //Get the only object available<br>   public static SingleObject getInstance(){<br>      return instance;<br>   }<br><br>   public void showMessage(){<br>      System.out.println(&quot;This is a singlton class&quot;);<br>   }<br><br>}<br></pre><p>Get the only object from the singleton class.</p><pre>public class SingletonPatternDemo {<br>   public static void main(String[] args) {<br><br>      //Get the only object available<br>      SingleObject object = SingleObject.getInstance();<br><br>      //show the message<br>      object.showMessage();<br>   }<br>}</pre><p>We’ve reached the end of this article, and I hope you’ve enjoyed reading it. I trust it has given you a solid understanding of the basic creational design patterns. If there are any aspects or details that I might have missed, please don’t hesitate to share your thoughts in the comment section below. Your feedback is greatly appreciated, and I’m here to answer any questions you may have. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a35219682d71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Single Sign-On (SSO) and Microservices Architecture]]></title>
            <link>https://medium.com/@chanaka.14/single-sign-on-sso-and-microservices-architecture-9786466429fb?source=rss-c02b5b76826d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9786466429fb</guid>
            <dc:creator><![CDATA[Chanaka Anuruddha]]></dc:creator>
            <pubDate>Sat, 22 Jul 2023 07:34:28 GMT</pubDate>
            <atom:updated>2023-07-22T07:48:02.767Z</atom:updated>
            <content:encoded><![CDATA[<p>As modern applications adopt Microservices Architecture to enhance scalability and maintainability, managing user authentication and authorization across multiple microservices can become complex. Single Sign-On (SSO) is a powerful solution that simplifies this process by centralizing identity management and enabling seamless authentication across the entire microservices ecosystem. In this article, we’ll explore how SSO fits into a Java-based Microservices Architecture and provide step-by-step code examples for its implementation.</p><h3>Understanding SSO in the Context of Microservices</h3><p>In a Microservices Architecture, individual services are responsible for specific functionalities, and users may need to access multiple services simultaneously. Traditionally, each service would handle its authentication, leading to redundant login attempts and security challenges. SSO introduces a unified authentication mechanism where users log in once, and their session is propagated securely across all the microservices, eliminating the need for multiple logins.</p><h3>OAuth 2.0 for Single Sign-On</h3><p>OAuth 2.0 is a widely adopted authorization framework used for implementing SSO in modern applications. Let’s dive into a practical example to understand how OAuth 2.0 works in the context of microservices.</p><p><strong>Step 1: Setup the Authorization Server</strong></p><p>To implement an Authorization Server for OAuth 2.0, we can use Spring Security OAuth 2.0 module.</p><pre>@Configuration<br>@EnableAuthorizationServer<br>public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {<br><br>    @Autowired<br>    private AuthenticationManager authenticationManager;<br><br>    @Override<br>    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {<br>        clients.inMemory()<br>            .withClient(&quot;clientapp&quot;)<br>            .secret(&quot;test@mysecret&quot;)<br>            .authorizedGrantTypes(&quot;password&quot;, &quot;refresh_token&quot;)<br>            .scopes(&quot;read&quot;, &quot;write&quot;)<br>            .accessTokenValiditySeconds(3600)<br>            .refreshTokenValiditySeconds(86400);<br>    }<br><br>    @Override<br>    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {<br>        endpoints.authenticationManager(authenticationManager);<br>    }<br>}</pre><p><strong>Step 2: Secure Microservices with SSO</strong></p><p>Now that we have the Authorization Server set up, we can secure our microservices using OAuth 2.0.</p><pre>@Configuration<br>@EnableResourceServer<br>public class ResourceServerConfig extends ResourceServerConfigurerAdapter {<br><br>    @Override<br>    public void configure(HttpSecurity http) throws Exception {<br>        http.authorizeRequests()<br>            .antMatchers(&quot;/api/public&quot;).permitAll()<br>            .antMatchers(&quot;/api/private&quot;).authenticated();<br>    }<br>}</pre><h3>Securing Communication Between Microservices</h3><p>In a Microservices Architecture, securing communication between services is crucial. We can use JSON Web Tokens (JWT) to achieve secure communication while implementing SSO.</p><pre>import io.jsonwebtoken.Jwts;<br>import io.jsonwebtoken.SignatureAlgorithm;<br><br>public class JwtUtils {<br><br>    private static final String SECRET_KEY = &quot;your_secret_key&quot;;<br><br>    public static String generateToken(String username) {<br>        return Jwts.builder()<br>                .setSubject(username)<br>                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)<br>                .compact();<br>    }<br><br>    public static String getUsernameFromToken(String token) {<br>        return Jwts.parser()<br>                .setSigningKey(SECRET_KEY)<br>                .parseClaimsJws(token)<br>                .getBody()<br>                .getSubject();<br>    }<br>}</pre><h3>Conclusion</h3><p>SSO can be a great way to improve the user experience in a microservices architecture. By implementing SSO, users can log in once and gain access to multiple microservices without having to remember multiple passwords or login credentials.</p><p>There are a number of different ways to implement SSO in a microservices architecture. The best approach will depend on the specific requirements of the application.</p><p>The code examples in this article illustrate how to implement SSO using Spring Security. There are many other ways to implement SSO in a microservices architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9786466429fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>