<?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 Retheesh Soman on Medium]]></title>
        <description><![CDATA[Stories by Retheesh Soman on Medium]]></description>
        <link>https://medium.com/@retheesh.soman?source=rss-8a3261968358------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*haRgR1Ox5h4TaObBgQxDZg.png</url>
            <title>Stories by Retheesh Soman on Medium</title>
            <link>https://medium.com/@retheesh.soman?source=rss-8a3261968358------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 11:30:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@retheesh.soman/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[SOLID Principle]]></title>
            <link>https://medium.com/@retheesh.soman/solid-principle-65e6d8929f2e?source=rss-8a3261968358------2</link>
            <guid isPermaLink="false">https://medium.com/p/65e6d8929f2e</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Retheesh Soman]]></dc:creator>
            <pubDate>Wed, 10 Sep 2025 18:28:54 GMT</pubDate>
            <atom:updated>2025-09-10T18:28:54.183Z</atom:updated>
            <content:encoded><![CDATA[<p>The <strong>SOLID principles</strong> are a set of five core object-oriented design principles . They help developers write code that is <strong>clean, maintainable, scalable, and testable</strong>.</p><h3>1. S — Single Responsibility Principle (SRP)</h3><ul><li>A class should have <strong>only one reason to change</strong>.</li><li>In other words, each class/module should focus on <strong>one responsibility</strong> or functionality.<br> ✅ Example:</li><li>Instead of having one Invoice class handle both persistence (saving to DB) and printing, split it into:</li><li>InvoiceRepository (for database operations)</li><li>InvoicePrinter (for output)</li></ul><h3>2. O — Open/Closed Principle (OCP)</h3><ul><li>Software entities (classes, modules, functions) should be <strong>open for extension but closed for modification</strong>.</li><li>You should be able to add new functionality without altering existing code.<br> ✅ Example:</li><li>Instead of modifying a Shape class every time a new shape (Circle, Square, Triangle) is added, define a Shape interface with a draw() method. Each shape implements it, so you extend, not modify.</li></ul><h3>3. L — Liskov Substitution Principle (LSP)</h3><ul><li>Objects of a superclass should be <strong>replaceable with objects of its subclasses</strong> without breaking the application.</li><li>Subclasses should <strong>not weaken the behavior</strong> of their parent.<br> ✅ Example:</li><li>If Bird has a method fly(), then Penguin should not extend Bird if it cannot fly—otherwise LSP is violated.</li></ul><h3>4. I — Interface Segregation Principle (ISP)</h3><ul><li>No client should be forced to depend on methods it does not use.</li><li>Instead of one large “fat” interface, create smaller, role-specific interfaces.<br> ✅ Example:</li><li>Instead of one IMachine interface with print(), scan(), fax(), split into:</li><li>IPrinter</li><li>IScanner</li><li>IFax</li></ul><h3>5. D — Dependency Inversion Principle (DIP)</h3><ul><li>High-level modules should not depend on low-level modules. Both should depend on <strong>abstractions</strong>.</li><li>Abstractions should not depend on details; details should depend on abstractions.<br> ✅ Example:</li><li>Instead of a PaymentService depending directly on a CreditCardProcessor, make it depend on a PaymentProcessor interface. Different implementations (CreditCard, PayPal, Stripe) can be injected.</li></ul><p>🔑 <strong>In short:</strong></p><ul><li><strong>SRP</strong> → One responsibility per class.</li><li><strong>OCP</strong> → Extend, don’t modify.</li><li><strong>LSP</strong> → Subclasses must honor parent contracts.</li><li><strong>ISP</strong> → Keep interfaces small and specific.</li><li><strong>DIP</strong> → Depend on abstractions, not concrete details.</li></ul><p>Let’s tie <strong>SOLID principles</strong> to <strong>real-world Spring Boot/Java</strong> patterns you deal with daily (controllers, services, repositories, integrations).</p><h3>1. Single Responsibility Principle (SRP)</h3><h4><strong><em>Each class should only do one thing.</em></strong></h4><p><strong>Bad Example (violates SRP):</strong></p><pre>@Service<br>public class InvoiceService {<br>    public void saveInvoice(Invoice invoice) {<br>        // save to DB<br>    }</pre><pre>    public void printInvoice(Invoice invoice) {<br>        // print logic<br>    }<br>}</pre><ul><li>This class mixes <strong>persistence</strong> and <strong>printing</strong>.</li></ul><p><strong>Good Example (SRP applied):</strong></p><pre>@Service<br>public class InvoiceService {<br>    private final InvoiceRepository repository;</pre><pre>    public InvoiceService(InvoiceRepository repository) {<br>        this.repository = repository;<br>    }</pre><pre>    public void saveInvoice(Invoice invoice) {<br>        repository.save(invoice);<br>    }<br>}</pre><pre>@Component<br>public class InvoicePrinter {<br>    public void print(Invoice invoice) {<br>        // printing logic<br>    }<br>}</pre><ul><li>Now responsibilities are clear: one saves, one prints.</li></ul><h3>2. Open/Closed Principle (OCP)</h3><blockquote><em>Open for extension, closed for modification.</em></blockquote><p><strong>Bad Example (violates OCP):</strong></p><pre>public class PaymentService {<br>    public void processPayment(String type) {<br>        if (&quot;credit&quot;.equals(type)) {<br>            // process credit card<br>        } else if (&quot;paypal&quot;.equals(type)) {<br>            // process PayPal<br>        }<br>    }<br>}</pre><ul><li>Adding a new payment type means <strong>modifying</strong> existing code.</li></ul><p><strong>Good Example (OCP applied with Strategy Pattern):</strong></p><pre>public interface PaymentProcessor {<br>    void process();<br>}</pre><pre>@Component<br>public class CreditCardProcessor implements PaymentProcessor {<br>    public void process() { /* credit card logic */ }<br>}</pre><pre>@Component<br>public class PayPalProcessor implements PaymentProcessor {<br>    public void process() { /* PayPal logic */ }<br>}</pre><pre>@Service<br>public class PaymentService {<br>    private final List&lt;PaymentProcessor&gt; processors;</pre><pre>    public PaymentService(List&lt;PaymentProcessor&gt; processors) {<br>        this.processors = processors;<br>    }</pre><pre>    public void payAll() {<br>        processors.forEach(PaymentProcessor::process);<br>    }<br>}</pre><ul><li>Adding <strong>StripeProcessor</strong> means just <strong>extending</strong>, not modifying existing logic.</li></ul><h3>3. Liskov Substitution Principle (LSP)</h3><blockquote><em>Subclasses must behave consistently with parent.</em></blockquote><p><strong>Bad Example (violates LSP):</strong></p><pre>public class Bird {<br>    public void fly() {}<br>}</pre><pre>public class Penguin extends Bird {<br>    @Override<br>    public void fly() {<br>        throw new UnsupportedOperationException(&quot;Penguins can’t fly&quot;);<br>    }<br>}</pre><ul><li>Breaks LSP: Penguin is not a proper Bird substitute.</li></ul><p><strong>Good Example (LSP applied with proper abstraction):</strong></p><pre>public interface Bird {<br>    void eat();<br>}</pre><pre>public interface FlyableBird extends Bird {<br>    void fly();<br>}</pre><pre>public class Sparrow implements FlyableBird {<br>    public void eat() {}<br>    public void fly() {}<br>}</pre><pre>public class Penguin implements Bird {<br>    public void eat() {}<br>}</pre><ul><li>Clients can substitute safely without breaking behavior.</li></ul><h3>4. Interface Segregation Principle (ISP)</h3><blockquote><em>Clients should not depend on methods they don’t use.</em></blockquote><p><strong>Bad Example (violates ISP):</strong></p><pre>public interface Machine {<br>    void print();<br>    void scan();<br>    void fax();<br>}</pre><pre>public class SimplePrinter implements Machine {<br>    public void print() {}<br>    public void scan() { throw new UnsupportedOperationException(); }<br>    public void fax() { throw new UnsupportedOperationException(); }<br>}</pre><ul><li>SimplePrinter is forced to implement unused methods.</li></ul><p><strong>Good Example (ISP applied):</strong></p><pre>public interface Printer {<br>    void print();<br>}</pre><pre>public interface Scanner {<br>    void scan();<br>}</pre><pre>public class SimplePrinter implements Printer {<br>    public void print() {}<br>}</pre><ul><li>Interfaces are <strong>segregated</strong> based on actual needs.</li></ul><h3>5. Dependency Inversion Principle (DIP)</h3><blockquote><em>Depend on abstractions, not on concrete classes.</em></blockquote><p><strong>Bad Example (violates DIP):</strong></p><pre>@Service<br>public class OrderService {<br>    private final MySQLOrderRepository repository = new MySQLOrderRepository();<br>}</pre><ul><li>High-level service <strong>depends on a low-level detail</strong>.</li></ul><p><strong>Good Example (DIP applied with Spring DI):</strong></p><pre>public interface OrderRepository {<br>    void save(Order order);<br>}</pre><pre>@Repository<br>public class MySQLOrderRepository implements OrderRepository {<br>    public void save(Order order) { /* DB logic */ }<br>}</pre><pre>@Service<br>public class OrderService {<br>    private final OrderRepository repository;</pre><pre>    public OrderService(OrderRepository repository) {<br>        this.repository = repository;<br>    }</pre><pre>    public void placeOrder(Order order) {<br>        repository.save(order);<br>    }<br>}</pre><ul><li>Now service depends on the <strong>interface</strong>, not a specific DB implementation.</li><li>Tomorrow you can inject MongoOrderRepository without touching OrderService.</li></ul><p><strong>Summary for Spring Boot Workflows:</strong></p><ul><li><strong>SRP</strong> → Split controllers, services, and repositories by concern.</li><li><strong>OCP</strong> → Use interfaces &amp; strategy patterns instead of giant if/else.</li><li><strong>LSP</strong> → Model correct inheritance hierarchies (don’t misuse extends).</li><li><strong>ISP</strong> → Keep microservice APIs and Java interfaces slim.</li><li><strong>DIP</strong> → Always inject interfaces, not implementations.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65e6d8929f2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java 8 through 21]]></title>
            <link>https://medium.com/@retheesh.soman/java-8-through-21-c5b8bcd34a25?source=rss-8a3261968358------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5b8bcd34a25</guid>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java21]]></category>
            <dc:creator><![CDATA[Retheesh Soman]]></dc:creator>
            <pubDate>Wed, 01 Jan 2025 22:33:19 GMT</pubDate>
            <atom:updated>2025-01-01T22:33:19.974Z</atom:updated>
            <content:encoded><![CDATA[<p>High-level summary of the highlights and notable features introduced in Java versions 8 through 21:</p><h3>Java 8 (March 2014)</h3><p><strong>Key Features:</strong></p><ol><li><strong>Lambda Expressions</strong> — Introduced functional programming constructs, enabling a more concise syntax.</li><li><strong>Streams API</strong> — Facilitated functional-style operations on collections and other data sources.</li><li><strong>Default Methods</strong> — Allowed interfaces to have default implementations.</li><li><strong>New Date-Time API</strong> — Replaced the cumbersome java.util.Date and Calendar.</li><li><strong>Nashorn JavaScript Engine</strong> — Integrated for executing JavaScript code.</li><li><strong>Optional Class</strong> — Enhanced null-handling with optional values.</li><li><strong>Collectors</strong> — Stream API utilities for reducing and grouping operations.</li></ol><h3>Java 9 (September 2017)</h3><p><strong>Key Features:</strong></p><ol><li><strong>Project Jigsaw (Modular System)</strong> — Introduced modules, enabling better encapsulation and performance.</li><li><strong>JShell</strong> — A REPL (Read-Eval-Print Loop) tool for interactive experimentation.</li><li><strong>Collection Factory Methods</strong> — List.of(), Set.of(), and Map.of() methods for creating immutable collections.</li><li><strong>Process API Updates</strong> — Enhanced support for managing and controlling operating system processes.</li><li><strong>HTTP/2 Client (Preview)</strong> — A modern HTTP client for synchronous and asynchronous communication.</li><li><strong>Compact Strings</strong> — Optimized memory usage for String.</li></ol><h3>Java 10 (March 2018)</h3><p><strong>Key Features:</strong></p><ol><li><strong>Local-Variable Type Inference</strong> — The var keyword for local variable declarations.</li><li><strong>Garbage Collector Enhancements</strong> — Introduction of the G1 Garbage Collector as the default.</li><li><strong>Application Class-Data Sharing (AppCDS)</strong> — Improved startup performance by sharing class metadata.</li></ol><h3>Java 11 (September 2018)</h3><p><strong>Key Features:</strong></p><ol><li><strong>Long-Term Support (LTS)</strong> — Marked as an LTS release.</li><li><strong>New String Methods</strong> — isBlank(), lines(), strip(), and repeat().</li><li><strong>HTTP Client API</strong> — Full implementation of the HTTP/2 Client.</li><li><strong>File Methods</strong> — New methods for reading and writing files as strings.</li><li><strong>Deprecation of JavaFX</strong> — Removed from the core JDK.</li><li><strong>Lambda Parameter Syntax</strong> — Allowed var in lambda expressions.</li></ol><h3>Java 12 (March 2019)</h3><p><strong>Key Features:</strong></p><ol><li><strong>Switch Expressions (Preview)</strong> — Simplified syntax for switch-case blocks.</li><li><strong>JVM Constants API</strong> — Improved access to JVM constants.</li><li><strong>Garbage Collector Enhancements</strong> — Added the Shenandoah GC as an experimental feature.</li></ol><h3>Java 13 (September 2019)</h3><p><strong>Key Features:</strong></p><ol><li><strong>Text Blocks (Preview)</strong> — Simplified handling of multi-line string literals.</li><li><strong>Switch Expressions (Second Preview)</strong> — Further refinement.</li><li><strong>Reimplementation of Legacy Socket API</strong> — Improved maintainability.</li></ol><h3>Java 14 (March 2020)</h3><p><strong>Key Features:</strong></p><ol><li><strong>Records (Preview)</strong> — Compact syntax for immutable data classes.</li><li><strong>Pattern Matching for </strong><strong>instanceof (Preview)</strong> - Simplified type checks.</li><li><strong>Switch Expressions</strong> — Finalized as a standard feature.</li><li><strong>NullPointerException Enhancements</strong> — Better debugging with detailed messages.</li></ol><h3>Java 15 (September 2020)</h3><p><strong>Key Features:</strong></p><ol><li><strong>Text Blocks</strong> — Finalized as a standard feature.</li><li><strong>Sealed Classes (Preview)</strong> — Allowed restricted class hierarchies.</li><li><strong>Hidden Classes</strong> — For framework developers to define non-discoverable classes.</li><li><strong>ZGC Enhancements</strong> — Improved low-latency garbage collection.</li></ol><h3>Java 16 (March 2021)</h3><p><strong>Key Features:</strong></p><ol><li><strong>Records</strong> — Finalized as a standard feature.</li><li><strong>Pattern Matching for </strong><strong>instanceof</strong> - Finalized as a standard feature.</li><li><strong>Vector API (Incubator)</strong> — Enabled better SIMD programming.</li><li><strong>Unix-Domain Socket Channels</strong> — Enhanced inter-process communication.</li></ol><h3>Java 17 (September 2021)</h3><p><strong>Key Features:</strong></p><ol><li><strong>LTS Release</strong> — Long-term support.</li><li><strong>Sealed Classes</strong> — Finalized as a standard feature.</li><li><strong>Pattern Matching for </strong><strong>switch (Preview)</strong> - Enhanced switch expressions.</li><li><strong>New macOS Rendering Pipeline</strong> — Improved compatibility and performance.</li><li><strong>Deprecation and Removal</strong> — Final removal of RMI activation and Applet API.</li></ol><h3>Java 18 (March 2022)</h3><p><strong>Key Features:</strong></p><ol><li><strong>Simple Web Server</strong> — Lightweight HTTP server for prototyping and testing.</li><li><strong>UTF-8 by Default</strong> — Standardized character encoding.</li><li><strong>Code Snippets in Javadoc</strong> — Simplified documentation examples.</li><li><strong>Vector API Updates</strong> — Further enhancements.</li></ol><h3>Java 19 (September 2022)</h3><p><strong>Key Features:</strong></p><ol><li><strong>Virtual Threads (Preview)</strong> — Lightweight threads for better concurrency.</li><li><strong>Structured Concurrency (Incubator)</strong> — Improved error handling in multi-threading.</li><li><strong>Pattern Matching for </strong><strong>switch (Preview)</strong> - Further refinement.</li><li><strong>Foreign Function &amp; Memory API (Preview)</strong> — Interfacing with native code.</li></ol><h3>Java 20 (March 2023)</h3><p><strong>Key Features:</strong></p><ol><li><strong>Scoped Values (Incubator)</strong> — Replacing thread-local variables.</li><li><strong>Record Patterns (Preview)</strong> — Extended pattern matching for deconstruction.</li><li><strong>Virtual Threads Enhancements</strong> — Improved for concurrency.</li></ol><h3>Java 21 (September 2023)</h3><p><strong>Key Features:</strong></p><ol><li><strong>LTS Release</strong> — Long-term support.</li><li><strong>Virtual Threads</strong> — Finalized as a standard feature.</li><li><strong>Pattern Matching for </strong><strong>switch</strong> - Finalized.</li><li><strong>Sequenced Collections</strong> — New APIs for ordering.</li><li><strong>String Templates</strong> — Simplified handling of string formatting.</li><li><strong>Scoped Values</strong> — Standardized feature.</li><li><strong>Foreign Function &amp; Memory API</strong> — Finalized for native interoperability.</li></ol><p>Each release enhances productivity, performance, and code clarity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5b8bcd34a25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sample Kubernetes configuration files for deploying a Spring Boot microservice:]]></title>
            <link>https://medium.com/@retheesh.soman/sample-kubernetes-configuration-files-for-deploying-a-spring-boot-microservice-069ec60b2cf8?source=rss-8a3261968358------2</link>
            <guid isPermaLink="false">https://medium.com/p/069ec60b2cf8</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Retheesh Soman]]></dc:creator>
            <pubDate>Wed, 01 Jan 2025 22:27:28 GMT</pubDate>
            <atom:updated>2025-01-03T06:13:34.050Z</atom:updated>
            <content:encoded><![CDATA[<p>Sample Kubernetes configuration files for deploying a Spring Boot microservice:</p><h3>1. Deployment Configuration</h3><p>This YAML file defines the deployment for the Spring Boot microservice, including the container image, resource requests/limits, and environment variables.</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: spring-boot-app<br>spec:<br>  replicas: 2<br>  selector:<br>    matchLabels:<br>      app: spring-boot-app<br>  template:<br>    metadata:<br>      labels:<br>        app: spring-boot-app<br>    spec:<br>      containers:<br>        - name: spring-boot-container<br>          image: your-docker-image:tag<br>          ports:<br>            - containerPort: 8080<br>          livenessProbe:<br>            httpGet:<br>              path: /actuator/health<br>              port: 8080<br>            initialDelaySeconds: 5<br>            periodSeconds: 10<br>          readinessProbe:<br>            httpGet:<br>              path: /actuator/health<br>              port: 8080<br>            initialDelaySeconds: 5<br>            periodSeconds: 10</pre><h3>2. Service Configuration</h3><p>This YAML file exposes the Spring Boot application using a Kubernetes Service.</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: spring-boot-app-service<br>spec:<br>  selector:<br>    app: spring-boot-app<br>  ports:<br>  - protocol: TCP<br>    port: 80<br>    targetPort: 8080<br>  type: LoadBalancer</pre><h3>3. ConfigMap</h3><p>Use a ConfigMap to manage configuration that the application can use (e.g., environment-specific properties).</p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: spring-boot-app-config<br>data:<br>  application.properties: |<br>    server.port=8080<br>    spring.datasource.url=jdbc:mysql://mysql-service:3306/mydb<br>    spring.datasource.username=myuser<br>    spring.datasource.password=mypassword</pre><h3>4. Secret</h3><p>If you have sensitive information like database passwords, use a Kubernetes Secret.</p><pre>apiVersion: v1<br>kind: Secret<br>metadata:<br>  name: spring-boot-app-secrets<br>type: Opaque<br>data:<br>  db-password: bXlwYXNzd29yZA== # base64 encoded password (example: &quot;mypassword&quot;)</pre><h3>5. Ingress</h3><p>Use an Ingress to expose the application externally and manage routing.</p><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: spring-boot-app-ingress<br>  annotations:<br>    nginx.ingress.kubernetes.io/rewrite-target: /<br>spec:<br>  rules:<br>  - host: springboot.example.com<br>    http:<br>      paths:<br>      - path: /<br>        pathType: Prefix<br>        backend:<br>          service:<br>            name: spring-boot-app-service<br>            port:<br>              number: 80</pre><h3>6. Persistent Volume and Persistent Volume Claim (Optional)</h3><p>If your Spring Boot app requires persistent storage:</p><p><strong>Persistent Volume (PV):</strong></p><pre>apiVersion: v1<br>kind: PersistentVolume<br>metadata:<br>  name: spring-boot-app-pv<br>spec:<br>  capacity:<br>    storage: 1Gi<br>  accessModes:<br>  - ReadWriteOnce<br>  hostPath:<br>    path: /data/spring-boot-app</pre><p><strong>Persistent Volume Claim (PVC):</strong></p><pre>apiVersion: v1<br>kind: PersistentVolumeClaim<br>metadata:<br>  name: spring-boot-app-pvc<br>spec:<br>  accessModes:<br>  - ReadWriteOnce<br>  resources:<br>    requests:<br>      storage: 1Gi</pre><p><strong>Update Deployment to Use PVC:</strong></p><pre>volumeMounts:<br>        - mountPath: &quot;/data&quot;<br>          name: app-data<br>      volumes:<br>      - name: app-data<br>        persistentVolumeClaim:<br>          claimName: spring-boot-app-pvc</pre><p>These YAML configurations can be customized based on your Spring Boot application’s requirements and Kubernetes environment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=069ec60b2cf8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spark : Compare Dataframe]]></title>
            <link>https://medium.com/@retheesh.soman/spark-compare-dataframe-3eda032f57af?source=rss-8a3261968358------2</link>
            <guid isPermaLink="false">https://medium.com/p/3eda032f57af</guid>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Retheesh Soman]]></dc:creator>
            <pubDate>Mon, 01 Oct 2018 05:12:14 GMT</pubDate>
            <atom:updated>2018-10-01T05:12:14.978Z</atom:updated>
            <content:encoded><![CDATA[<ul><li><a href="https://stackoverflow.com/questions/46302104/compare-each-columns-of-two-data-frames-and-output-only-diff-columns">Compare each columns of two data frames and output only diff columns</a></li><li><a href="https://stackoverflow.com/questions/44338412/how-to-compare-two-dataframe-and-print-columns-that-are-different-in-scala">How to compare two dataframe and print columns that are different in scala</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3eda032f57af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Export data from MongoDb to Hdfs Using Spark shell]]></title>
            <link>https://medium.com/@retheesh.soman/export-data-from-mongodb-to-hdfs-using-spark-shell-11ecea5af534?source=rss-8a3261968358------2</link>
            <guid isPermaLink="false">https://medium.com/p/11ecea5af534</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Retheesh Soman]]></dc:creator>
            <pubDate>Wed, 19 Sep 2018 05:12:08 GMT</pubDate>
            <atom:updated>2018-09-19T05:14:53.164Z</atom:updated>
            <content:encoded><![CDATA[<p>Use Case : I have a collection named <strong><em>movies </em></strong>in mongo database <strong><em>mmdb.</em></strong> I would like to export this data to hdfs using spark shell</p><p><strong>Source</strong>:</p><pre><strong>database</strong>: mmdb (mongo database) </pre><pre><strong>Table </strong>: movies </pre><pre>( movies table has two fields _Id and movieName) </pre><p><strong>Destination:</strong></p><pre>hdfs file system </pre><pre><strong>schema</strong>: mmdb_hdfs_schema</pre><p><strong>Execution</strong></p><pre><strong>Step 1.</strong> export <strong>SPARK_MAJOR_VERSION</strong>=2</pre><pre><strong>Step 2</strong>. spark-shell — conf “spark.mongodb.input.uri=mongodb://&lt;db_user&gt;:&lt;db_password&gt;<a href="http://twitter.com/hostname">@&lt;hostname</a>&gt;:&lt;port&gt;/&lt;database_name&gt;.&lt;mongoCollectionName&gt;” — packages &lt;mongo connector package name&gt;</pre><pre>eg: spark-shell --conf &quot;spark.mongodb.input.uri=mongodb://mmdb_user:mmdb_password@localhost:27017/mmdb.movies&quot; --packages org.mongodb.spark:mongo-spark-connector_2.11:2.2.3</pre><pre><strong>Step3. </strong></pre><pre>scala&gt; <strong>import com.mongodb.spark._</strong></pre><pre>scala&gt; val <strong>rdd </strong>= MongoSpark.load(sc).map(line =&gt; line.toJson)</pre><pre>scala&gt; rdd.<strong>saveAsTextFile</strong>(&quot;<strong>hdfs:///user/retheeshs/movies</strong>&quot;);</pre><pre>scala&gt; val <strong>df </strong>= spark.read.json(&quot;hdfs:///user/retheeshs/movies/*&quot;)</pre><pre>scala&gt; val <strong>selectDf </strong>= df.select(&quot;_id.$numberLong&quot;,&quot;movieName&quot;).toDF(&quot;_id&quot;,&quot;movieName&quot;)</pre><pre>scala&gt; selectDf.write.mode(&quot;overwrite&quot;).saveAsTable(&quot;<strong>mmdb_hdfs_schema</strong>.<strong>movies</strong>&quot;)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11ecea5af534" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ACID]]></title>
            <link>https://medium.com/@retheesh.soman/acid-b67bfe1d0e8e?source=rss-8a3261968358------2</link>
            <guid isPermaLink="false">https://medium.com/p/b67bfe1d0e8e</guid>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[acid]]></category>
            <dc:creator><![CDATA[Retheesh Soman]]></dc:creator>
            <pubDate>Wed, 05 Sep 2018 06:12:13 GMT</pubDate>
            <atom:updated>2018-09-05T06:12:13.617Z</atom:updated>
            <content:encoded><![CDATA[<p>A transaction, in any domain, whether a database or not, needs to comply with four properties, collectively</p><p>known as ACID:</p><p>➤➤ Atomic —</p><pre>The contents of the transaction are done as a whole, or not at all. It is not possible</pre><p>to view the database in a state where only half of the transaction is applied.</p><p>➤➤ Consistent —</p><pre>After the transaction, the database meets all the requirements for your domain. For instance, when making a payment between two parties, the amount debited from one party should match the amount credited to the other.</pre><p>➤➤ Isolated —</p><pre>Transactions running in parallel should each behave as though they are the only transaction running on the database.</pre><p>➤➤ Durable —</p><pre>Once the transaction has been committed, it is committed permanently. Any subsequent database change, such as an update or a crash, will have no effect on the committed transaction.</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b67bfe1d0e8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Services]]></title>
            <link>https://medium.com/@retheesh.soman/web-services-40cef84ad2dc?source=rss-8a3261968358------2</link>
            <guid isPermaLink="false">https://medium.com/p/40cef84ad2dc</guid>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Retheesh Soman]]></dc:creator>
            <pubDate>Sun, 19 Aug 2018 23:52:37 GMT</pubDate>
            <atom:updated>2019-04-05T01:54:53.686Z</atom:updated>
            <content:encoded><![CDATA[<p>References including journaldev</p><h3>Introduction</h3><pre>Web Services work on client-server model where client applications can access web services over the network. Web services provide endpoint URLs and expose methods that can be accessed over network through client programs written in java, shell script or any other different technologies.<br> Web services are stateless and doesn’t maintain user session like web applications.</pre><h3><strong>Advantages of Web Services</strong></h3><pre><strong>Interoperatability </strong>: Web services are accessible over network and runs on HTTP/SOAP protocol and uses XML/JSON to transport data, hence it can be developed in any programming language. Web service can be written in java programming and client can be PHP and vice versa.</pre><pre><strong>Reusability</strong>: One web service can be used by many client applications at the same time.</pre><pre><strong>Loose coupling: </strong> Web services client code is totally independent with server code, so we have achieved loose coupling in our application.</pre><pre><strong>Easy to deploy and integrate,</strong> just like web applications.</pre><pre><strong>Multiple service versions can be running at same time</strong>: One web service can be used by many client applications at the same time.</pre><h3><strong>Types of Web Services :</strong></h3><blockquote>There are two types of web services:</blockquote><h4>1. SOAP Web Services:</h4><pre><strong>(i)</strong> Runs on SOAP protocol and uses XML technology for sending data.<br>SOAP stands for Simple Object Access Protocol.<br> <br><strong>(ii)</strong> SOAP is an XML based industry standard protocol for designing and developing web services.</pre><pre><strong>(iii)</strong> Since it’s XML based, it’s platform and language independent. </pre><pre><strong>(iv)</strong> So our server can be based on JAVA and client can be in a different language .NET, PHP etc. and vice versa.</pre><h4>2. Restful Web Services:</h4><pre><strong>(i) </strong>It’s an architectural style and runs on HTTP/HTTPS protocol almost all the time. </pre><pre><strong>(ii) </strong>REST is a stateless client-server architecture where web services are resources and can be identified by their URIs. </pre><pre><strong>(iii) </strong>Client applications can use HTTP GET/POST methods to invoke Restful web services.</pre><h3><strong>Advantages of SOAP Web Services</strong></h3><pre>(i) WSDL document provides contract and technical details of the web services for client applications without exposing the underlying implementation technologies.</pre><pre>(ii) SOAP uses XML data for payload as well as contract, so it can be easily read by any technology.</pre><pre>(iii) SOAP protocol is universally accepted, so it’s an industry standard approach with many easily available open source implementations.</pre><h3><strong>Disadvantages of SOAP Web Services</strong></h3><pre>(i) Only XML can be used, JSON and other lightweight formats are not supported.</pre><pre>(ii) SOAP is based on the contract, so there is a tight coupling between client and server applications.</pre><pre>(iii) SOAP is slow because payload is large for a simple string message, since it uses XML format.</pre><pre>(iv) Anytime there is change in the server side contract, client stub classes need to be generated again.</pre><pre>(v) Can’t be tested easily in browser</pre><h3><strong>WSDL</strong></h3><pre><strong>WSDL </strong>stands for Web Service Description Language. WSDL is an XML based document that provides technical details about the web service. Some of the useful information in WSDL document are: <br>* method name<br>* port types<br>* service end point<br>* binding<br>* method parameters etc.</pre><pre><strong>Some of the different tags in WSDL xml are:</strong></pre><pre>xsd:import namespace and schemaLocation: provides WSDL URL and unique namespace for web service.</pre><pre>message: for method arguments</pre><pre>part: for method argument name and type</pre><pre>portType: service name, there can be multiple services in a wsdl document.</pre><pre>operation: contains method name</pre><pre>soap:address for endpoint URL.</pre><h3><strong>UDDI</strong></h3><pre>UDDI is acronym for <strong><em>Universal Description, Discovery and Integration.</em></strong> UDDI is a directory of web services where client applications can lookup for web services. Web Services can register to the UDDI server and make them available to client applications.</pre><h3>Top down vs Bottom up</h3><pre>In <strong>Top Down approach</strong> first WSDL document is created to establish the contract between web service and client and then code is written, it’s also termed as contract first approach. This is hard to implement because classes need to be written to confirm the contract established in WSDL. Benefit of this approach is that both client and server code can be written in parallel.</pre><pre>In <strong>Bottom Up approach</strong>, first web service code is written and then WSDL is generated. It’s also termed as contract last approach. This approach is easy to implement because WSDL is generated based on code. In this approach client code have to wait for WSDL from server side to start their work.</pre><h3>Rest Web service</h3><pre><strong>REST </strong>is the acronym for <strong><em>REpresentational State Transfer</em></strong>. REST is an architectural style for developing applications that can be accessed over the network and it was brought in light by <strong>Roy Fielding</strong> in his doctoral thesis in 2000. </pre><pre>REST is a stateless client-server architecture where web services are resources and can be identified by their URIs. Client applications can use HTTP GET/POST methods to invoke Restful web services. REST doesn’t specify any specific protocol to use, but in almost all cases it’s used over HTTP/HTTPS. When compared to SOAP web services, these are lightweight and doesn’t follow any standard. We can use XML, JSON, text or any other type of data for request and response. Restful web services supported HTTP methods are — <br>* GET<br>* POST<br>* PUT<br>* DELETE <br>* HEAD.</pre><h4>Advantages of REST web services are:</h4><pre>(i) <strong>Learning curve</strong> is easy since it works on HTTP protocol</pre><pre>(ii) <strong>Supports multiple technologies </strong>for data transfer such as text, xml, json, image etc.</pre><pre>(iii) <strong>No contract </strong>defined between server and client, so loosely coupled implementation.</pre><pre>(iv) <strong>REST is a lightweight protocol</strong> REST methods can be tested easily over browser.</pre><h4>Disadvantages of REST are:</h4><pre>(i) Since there is no contract defined between service and client, it has to be communicated through other means such as documentation or emails.</pre><pre>(ii) Since it works on HTTP, there can’t be asynchronous calls.</pre><pre>(iii) Sessions can’t be maintained.</pre><h4>Resource</h4><pre><strong>Resource </strong>is the fundamental concept of Restful architecture. A resource is an object with a type, relationship with other resources and methods that operate on it. Resources are identified with their <strong>URI</strong>, HTTP methods they support and request/response data type and format of data. </pre><h3>Test Web service</h3><pre>SOAP web services can be tested pro grammatically by generating client stubs from WSDL or through software such as <strong>Soap UI.</strong></pre><pre>REST web services can be tested easily with:- <br><strong>* program<br>* curl commands <br>* browser extensions. </strong></pre><pre>Resources supporting GET method can be tested with browser itself, without any program.</pre><h3>SOA vs Web Services</h3><pre><strong>Service Oriented Architecture (SOA)</strong> is an architectural pattern where applications are designed in terms of services that can be accessed through communication protocol over network. SOA is a <a href="https://www.journaldev.com/1827/java-design-patterns-example-tutorial">design pattern</a> and doesn’t go into implementation.</pre><pre><strong>Web Services</strong> can be thought of as Services in SOAP architecture and providing means to implement SOA pattern.</pre><h3>Accept and Content -type headers in HTTP request</h3><blockquote>These are important headers in Restful web services.</blockquote><h4><strong>Accept headers</strong></h4><pre> <br><strong>Accept headers</strong> tells web service what kind of response client is accepting.</pre><pre>For example:- (i) application/xml : if a web service is capable of sending response in XML and JSON format and client sends Accept header as “application/xml” then XML response will be sent.</pre><pre>(ii) Similarly For Accept header “application/json”, server will send the JSON response.</pre><h4>Content-Type header</h4><pre><strong>Content-Type header</strong> is used to tell server what is the format of data being sent in the request. If Content-Type header is “application/xml” then server will try to parse it as XML data. This header is useful in HTTP Post and Put requests.</pre><h3>Choose between SOAP vs REST</h3><pre>Web Services work on client-server model and when it comes to choose between SOAP and REST, it all depends on project requirements. Let’s look at some of the conditions affecting our choice:</pre><pre><strong>Do you know your web service clients beforehand?</strong> If Yes, then you can define a contract before implementation and SOAP seems better choice. But if you don’t then REST seems better choice because you can provide sample request/response and test cases easily for client applications to use later on.</pre><pre><strong>How much time you have? </strong>For quick implementation REST is the best choice. You can create web service easily, test it through browser/curl and get ready for your clients.</pre><pre><strong>What kind of data format are supported?</strong> If only XML then you can go with SOAP but if you think about supporting JSON also in future then go with REST.</pre><h4>JAX-WS-API</h4><pre>JAX-WS stands for Java API for XML Web Services. JAX-WS is XML based Java API to build web services server and client application. It’s part of standard Java API, so we don’t need to include anything else which working with it. We can create SOAP web services using JAX-WS API, however some of the other frameworks that can be used are Apache Axis and Apache CXF. Note that they are not implementations of JAX-WS API, they are totally different framework that work on Servlet model to expose your business logic classes as SOAP web services.</pre><h3>RPC vs Document Style</h3><pre>RPC style generate WSDL document based on the method name and it’s parameters. No type definitions are present in WSDL document.<br>Document style contains type and can be validated against predefined schema.</pre><blockquote>Program</blockquote><pre>import javax.jws.WebMethod;<br>import javax.jws.WebService;<br>import javax.jws.soap.SOAPBinding;<br>import javax.xml.ws.Endpoint;</pre><pre><strong>@WebService</strong><br>@SOAPBinding(style = SOAPBinding.Style.RPC)<br>public class TestService {</pre><pre><strong>@WebMethod</strong><br>public String sayHello(String msg){<br>return “Hello “+msg;<br>}</pre><pre>public static void <strong>main</strong>(String[] args){</pre><pre>Endpoint.publish(“http://localhost:8888/testWS&quot;, new TestService());</pre><pre>}</pre><pre>}</pre><blockquote>Output</blockquote><pre>&lt;?xml version=&#39;1.0&#39; encoding=&#39;UTF-8&#39;?&gt;</pre><pre>&lt;!-- Published by JAX-WS RI (http://jax-ws.java.net). RI&#39;s version is JAX-WS RI 2.2.10 svn-revision#919b322c92f13ad085a933e8dd6dd35d4947364b. --&gt;&lt;!-- Generated by JAX-WS RI (http://jax-ws.java.net). RI&#39;s version is JAX-WS RI 2.2.10 svn-revision#919b322c92f13ad085a933e8dd6dd35d4947364b. --&gt;</pre><pre>&lt;definitions xmlns:wsu=&quot;http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd&quot; xmlns:wsp=&quot;http://www.w3.org/ns/ws-policy&quot; xmlns:wsp1_2=&quot;http://schemas.xmlsoap.org/ws/2004/09/policy&quot; xmlns:wsam=&quot;http://www.w3.org/2007/05/addressing/metadata&quot; xmlns:soap=&quot;http://schemas.xmlsoap.org/wsdl/soap/&quot; xmlns:tns=&quot;http://service.jaxws.journaldev.com/&quot; xmlns:xsd=&quot;http://www.w3.org/2001/XMLSchema&quot; xmlns=&quot;http://schemas.xmlsoap.org/wsdl/&quot; targetNamespace=&quot;http://service.jaxws.journaldev.com/&quot; name=&quot;TestServiceService&quot;&gt;</pre><pre>&lt;types/&gt;</pre><pre>&lt;message name=&quot;<strong>sayHello</strong>&quot;&gt;<br>   &lt;part name=&quot;arg0&quot; type=&quot;xsd:string&quot;/&gt;<br>&lt;/message&gt;</pre><pre>&lt;message name=&quot;<strong>sayHelloResponse</strong>&quot;&gt;<br> &lt;part name=&quot;return&quot; type=&quot;xsd:string&quot;/&gt;<br>&lt;/message&gt;</pre><pre>&lt;portType name=&quot;<strong>TestService</strong>&quot;&gt;<br>&lt;operation name=&quot;<strong>sayHello</strong>&quot;&gt;<br> &lt;input wsam:Action=&quot;http://service.jaxws.journaldev.com/TestService/sayHelloRequest&quot; message=&quot;tns:sayHello&quot;/&gt;<br> &lt;output wsam:Action=&quot;http://service.jaxws.journaldev.com/TestService/sayHelloResponse&quot; message=&quot;tns:sayHelloResponse&quot;/&gt;<br>&lt;/operation&gt;<br>&lt;/portType&gt;</pre><pre>&lt;binding name=&quot;<strong>TestServicePortBinding</strong>&quot; type=&quot;<strong>tns:TestService</strong>&quot;&gt;&lt;soap:binding transport=&quot;http://schemas.xmlsoap.org/soap/http&quot; style=&quot;<strong>rpc</strong>&quot;/&gt;</pre><pre>&lt;<strong>operation </strong>name=&quot;<strong>sayHello</strong>&quot;&gt;<br> &lt;soap:operation soapAction=&quot;&quot;/&gt;</pre><pre> &lt;<strong>input</strong>&gt;<br> &lt;soap:body use=&quot;literal&quot;   namespace=&quot;<strong>http://service.jaxws.journaldev.com/</strong>&quot;/&gt;<br> &lt;/<strong>input</strong>&gt;<br> <br>&lt;<strong>output</strong>&gt;<br> &lt;soap:body use=&quot;literal&quot;  namespace=&quot;<strong>http://service.jaxws.journaldev.com/</strong>&quot;/&gt;<br> &lt;/<strong>output</strong>&gt;</pre><pre>&lt;/<strong>operation</strong>&gt;<br>&lt;/binding&gt;</pre><pre>&lt;service name=&quot;<strong>TestServiceService</strong>&quot;&gt;<br> &lt;port name=&quot;TestServicePort&quot; binding=&quot;tns:TestServicePortBinding&quot;&gt;   &lt;soap:address location=&quot;<strong>http://localhost:8888/testWS</strong>&quot;/&gt;<br> &lt;/port&gt;<br>&lt;/service&gt;<br>&lt;/definitions&gt;</pre><p>Now just change the SOAPBinding.Style.RPC to SOAPBinding.Style.DOCUMENT and you will get below WSDL.</p><pre>&lt;?xml version=&#39;1.0&#39; encoding=&#39;UTF-8&#39;?&gt; </pre><pre>&lt;!-- Published by JAX-WS RI (http://jax-ws.java.net). RI&#39;s version is JAX-WS RI 2.2.10 svn-revision#919b322c92f13ad085a933e8dd6dd35d4947364b. --&gt;&lt;!-- Generated by JAX-WS RI (http://jax-ws.java.net). RI&#39;s version is JAX-WS RI 2.2.10 svn-revision#919b322c92f13ad085a933e8dd6dd35d4947364b. --&gt;</pre><pre>&lt;definitions xmlns:wsu=&quot;http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd&quot; xmlns:wsp=&quot;http://www.w3.org/ns/ws-policy&quot; xmlns:wsp1_2=&quot;http://schemas.xmlsoap.org/ws/2004/09/policy&quot; xmlns:wsam=&quot;http://www.w3.org/2007/05/addressing/metadata&quot; xmlns:soap=&quot;http://schemas.xmlsoap.org/wsdl/soap/&quot; xmlns:tns=&quot;http://service.jaxws.journaldev.com/&quot; xmlns:xsd=&quot;http://www.w3.org/2001/XMLSchema&quot; xmlns=&quot;http://schemas.xmlsoap.org/wsdl/&quot; targetNamespace=&quot;http://service.jaxws.journaldev.com/&quot; name=&quot;TestServiceService&quot;&gt;</pre><pre>&lt;types&gt;</pre><pre>&lt;xsd:schema&gt;<br>&lt;xsd:import namespace=&quot;http://service.jaxws.journaldev.com/&quot; schemaLocation=&quot;http://localhost:8888/testWS?xsd=1&quot;/&gt;<br>&lt;/xsd:schema&gt;</pre><pre>&lt;/types&gt;</pre><pre>&lt;message name=&quot;sayHello&quot;&gt;<br>&lt;part name=&quot;parameters&quot; element=&quot;tns:sayHello&quot;/&gt;<br>&lt;/message&gt;</pre><pre>&lt;message name=&quot;sayHelloResponse&quot;&gt;<br>&lt;part name=&quot;parameters&quot; element=&quot;tns:sayHelloResponse&quot;/&gt;<br>&lt;/message&gt;</pre><pre>&lt;portType name=&quot;TestService&quot;&gt;<br>&lt;operation name=&quot;sayHello&quot;&gt;</pre><pre>&lt;input wsam:Action=&quot;http://service.jaxws.journaldev.com/TestService/sayHelloRequest&quot; message=&quot;tns:sayHello&quot;/&gt;</pre><pre>&lt;output wsam:Action=&quot;http://service.jaxws.journaldev.com/TestService/sayHelloResponse&quot; message=&quot;tns:sayHelloResponse&quot;/&gt;</pre><pre>&lt;/operation&gt;</pre><pre>&lt;/portType&gt;</pre><pre>&lt;binding name=&quot;TestServicePortBinding&quot; type=&quot;tns:TestService&quot;&gt;&lt;soap:binding transport=&quot;http://schemas.xmlsoap.org/soap/http&quot; style=&quot;document&quot;/&gt;</pre><pre>&lt;operation name=&quot;sayHello&quot;&gt;<br>&lt;soap:operation soapAction=&quot;&quot;/&gt;<br>&lt;input&gt;</pre><pre>&lt;soap:body use=&quot;literal&quot;/&gt;<br>&lt;/input&gt;</pre><pre>&lt;output&gt;<br>&lt;soap:body use=&quot;literal&quot;/&gt;<br>&lt;/output&gt;<br>&lt;/operation&gt;<br>&lt;/binding&gt;</pre><pre>&lt;service name=&quot;TestServiceService&quot;&gt;<br>&lt;port name=&quot;TestServicePort&quot; binding=&quot;tns:TestServicePortBinding&quot;&gt;<br>&lt;soap:address location=&quot;http://localhost:8888/testWS&quot;/&gt;<br>&lt;/port&gt;<br>&lt;/service&gt;<br>&lt;/definitions&gt;</pre><p><strong>Spring vs JAX-RS</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/0*hl-qvgqu58KOtVBs.png" /></figure><p>JAXRS example</p><pre><strong>// @RequestMapping(&quot;/v1&quot;) spring</strong><br>// @<strong>Path</strong>(“/v1”) JAXRS<br>public interface TestService {</pre><pre>//@PostMapping(&quot;/testservice, produces= {&quot;application/json}) Spring<br><br>@<strong>Path</strong>(&quot;/<strong>testservice</strong>&quot;) //jaxrs<br>@<strong>POST//jaxrs</strong><br>@<strong>Produces</strong>(&quot;application/json&quot;)//jaxrs<br>public Response sendAllRecords() throws TestServiceException;</pre><pre>@<strong>Path</strong>(&quot;/testservice/{testparam}&quot;) //jaxrs<br>@<strong>PUT</strong> //jaxrs<br>@<strong>Produces</strong>(&quot;application/json&quot;) //jaxrs<br>public Response sendRecordsByParam(@PathParam(&quot;testparam&quot;) String testParam) throws TestServiceException;</pre><pre>}</pre><p>application.yml</p><pre>cxf.path: /api<br>service.port : 8086</pre><p>Then the URI will be as given below</p><pre><strong>POST</strong><br>https://localhost:8086/api/v1/testservice/</pre><pre><strong>PUT</strong><br>https://localhost:8086/api/v1/testservice/921</pre><pre><strong>GET</strong><br>https://localhost:8086/api/v1/testservice/921</pre><p><strong>Rest Security</strong></p><p><strong>Configuration Bean</strong></p><pre><a href="http://twitter.com/Configuration">@Configuration</a><br><a href="http://twitter.com/EnableResourceServer">@EnableResourceServer</a><br><a href="http://twitter.com/ConditionalOnPropert">@ConditionalOnPropert</a>y(name=&quot;security.oauth2.resource.jwt.keyValue&quot;)</pre><pre>public class <strong>SecurityConfiguration </strong>extends <strong>ResourceServerConfigurerAdapter </strong>{</pre><pre> <a href="http://twitter.com/Value">@Value</a>(&quot;${oauth2.application-scope}&quot;)<br> private String <strong>applicationScope</strong>;<br> <br> <a href="http://twitter.com/Value">@Value</a>(&quot;${cxf.path}&quot;)<br> private String <strong>apiPath</strong>;<br> <br> <a href="http://twitter.com/Value">@Value</a>(&quot;${http.permit:}&quot;)<br> private String <strong>httpPermit</strong>;<br> <br> private static final Logger logger = LoggerFactory.getLogger(SecurityConfiguration.class);</pre><pre> <a href="http://twitter.com/Autowired">@Autowired</a><br> private ApplicationContext applicationContext;<br> <br> <a href="http://twitter.com/Override">@Override</a><br> public void configure(HttpSecurity http) throws Exception {</pre><pre> // Permit anonymous access to /health and /health/** for automated health check processes. <br> // Allow client access to anything provided it matches the</pre><pre> permittedAccessCondition.<strong>permitContractAccess</strong>(http);<br> <strong>permitSwagger</strong>(http);<br> <strong>permitHealthCheck</strong>(http);<br> <strong>permitGeneral</strong>(http);<br> <strong>restrictEverythingElse</strong>(http);</pre><pre> }</pre><pre> protected String permittedAccessCondition() {<br> return String.format(&quot;#oauth2.hasScope(&#39;%s&#39;)&quot;,applicationScope);<br> }</pre><pre> <a href="http://twitter.com/Override">@Override</a><br> public void configure(ResourceServerSecurityConfigurer config) throws Exception {<br> <br> }<br> <br> protected void permitGeneral(HttpSecurity http) throws Exception {<br> <br>     if (httpPermit!=null&amp;&amp;httpPermit.length()&gt;0) {<br>     logger.info(&quot;Permitting unauthenticated access to additional resources by configuration: {}&quot;,httpPermit);<br>       http.authorizeRequests()<br>       .antMatchers(httpPermit.split(&quot;,&quot;))<br>       .permitAll();<br>     }<br> }</pre><pre> protected void permitSwagger(HttpSecurity http) throws Exception {</pre><pre> try { <br> <br>  Class<br> .forName(&quot;org.apache.cxf.jaxrs.swagger.Swagger2Feature&quot;); </pre><pre> http<br> .authorizeRequests()<br> .antMatchers(apiPath+&quot;/swagger.*&quot;, apiPath+&quot;/api-docs&quot;, apiPath+&quot;/api-docs/**&quot;)<br>.permitAll();</pre><pre> } catch (Exception e) {<br> logger.info(&quot;Swagger is not enabled, the feature was not found on the classpath.&quot;);<br> }<br> }<br> <br> protected void restrictEverythingElse(HttpSecurity http) throws Exception {</pre><pre> final String apiAntPath=apiPath+&quot;/**&quot;;<br> http<br>.authorizeRequests()<br>.antMatchers(apiAntPath)<br>.authenticated()<br>.anyRequest()<br>.access(permittedAccessCondition());</pre><pre> }<br> <br> protected void permitHealthCheck(HttpSecurity http) throws Exception {<br> <br>http<br>.authorizeRequests()<br>.antMatchers(&quot;/health&quot;,&quot;/health/**&quot;)<br>.permitAll();</pre><pre> }<br> protected void permitContractAccess(HttpSecurity http) throws Exception {<br> <br>if (applicationContext!=null) {<br> // Configure rest services <br> <br>for (<br>Map.Entry&lt;String,Object&gt; entry : applicationContext<br>.getBeansWithAnnotation(Path.class)<br>.entrySet()<br>) {</pre><pre> Path path=AnnotationUtils<br>.findAnnotation(<br>entry.getValue().getClass(), <br>Path.class);</pre><pre> logger.debug(&quot;Configuring contract access for bean {} with annotation {}&quot;,entry.getKey(),path);</pre><pre> String fullpath=apiPath+path.value();<br> // CXF only allows wadl retrieval using lowercase &quot;_wadl&quot; as query string.<br> String regex=fullpath.replace(&quot;/&quot;, &quot;\\/&quot;)+&quot;\\/?\\?_wadl&quot;;<br> logger.info(&quot;Configuring HTTP security to allow WADL retrieval from {} at {}&quot;,entry.getKey(),regex);<br> http.authorizeRequests().regexMatchers(HttpMethod.GET, regex).permitAll();<br> }<br> // Configure soap services<br> for (String bean : applicationContext.getBeanNamesForAnnotation(WebService.class)) {</pre><pre> String path=apiPath+&quot;/&quot;+bean;<br> logger.info(&quot;Configuring HTTP security to allow WSDL retrieval from {} at {}&quot;,bean,path);</pre><pre> http.authorizeRequests().antMatchers(HttpMethod.GET, path).permitAll();</pre><pre> }<br> } else {<br> logger.error(&quot;Failed to configure contract access, no application context was provided.&quot;);<br> }<br> }<br>}</pre><p>Rest Controller</p><pre>@Api(<br><strong>value</strong> = “/v1”, <strong>authorizations</strong> = {</pre><pre>     @<strong>Authorization</strong>(value = “<strong>oauth2</strong>”, <br>     scopes = <br>     { <br>          @<strong>AuthorizationScope</strong><br>          (scope = “org:retheesh:testapi”, description = “”) <br>      }<br>    ) <br>   }<br>)</pre><p>HTTP Status Codes</p><pre><a href="https://www.restapitutorial.com/httpstatuscodes.html">https://www.restapitutorial.com/httpstatuscodes.html</a> </pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40cef84ad2dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka]]></title>
            <link>https://medium.com/@retheesh.soman/kafka-36a1daaffed7?source=rss-8a3261968358------2</link>
            <guid isPermaLink="false">https://medium.com/p/36a1daaffed7</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Retheesh Soman]]></dc:creator>
            <pubDate>Sun, 19 Aug 2018 19:51:16 GMT</pubDate>
            <atom:updated>2018-09-10T06:46:29.285Z</atom:updated>
            <content:encoded><![CDATA[<p>Copied from <a href="https://www.youtube.com/channel/UCB12jjYsYv-eipCvBDcMbXw">https://www.youtube.com/channel/UCB12jjYsYv-eipCvBDcMbXw</a></p><h4>Kafka Producer Bean definition for String class</h4><pre>@<strong>Configuration<br></strong>public class <strong>KafkaProducerConfiguration</strong> {</pre><pre>@<strong>Bean<br></strong>public <strong>ProducerFactory</strong>&lt;String, String&gt; <strong>producerFactory</strong>() {</pre><pre>Map&lt;String, Object&gt; <strong>config</strong> = new HashMap&lt;&gt;();<br> config.put(<strong>ProducerConfig</strong>.<strong>BOOTSTRAP_SERVERS_CONFIG</strong>,<br> “127.0.0.1:9092  ”);<br> config.put(<strong>ProducerConfig</strong>.<strong>KEY_SERIALIZER_CLASS_CONFIG</strong>,         StringSerializer.class);<br> config.put(<strong>ProducerConfig</strong>.<strong>VALUE_SERIALIZER_CLASS_CONFIG</strong>, StringSerializer.class);</pre><pre>return new <strong>DefaultKafkaProducerFactory</strong>&lt;&gt;(config);</pre><pre>}</pre><pre>@<strong>Bean</strong></pre><pre>public KafkaTemplate&lt;String, String&gt; <strong>kafkaTemplate</strong>() {</pre><pre>return new KafkaTemplate&lt;&gt;(<strong>producerFactory</strong>());</pre><pre>}</pre><pre>}</pre><p><strong>Kafka Consumer Bean definition for String class</strong></p><pre>@<strong>Configuration</strong></pre><pre>public class <strong>KafkaConsumerConfiguration</strong> {<br>@Bean</pre><pre>public ConsumerFactory&lt;String, String&gt; <strong>consumerFactory</strong>() {   <br> <br> Map&lt;String, Object&gt; config = new HashMap&lt;&gt;();<br> config.put(ConsumerConfig.<strong>BOOTSTRAP_SERVERS_CONFIG</strong>,   “127.0.0.1:9092”);<br> config.put(ConsumerConfig.<strong>GROUP_ID_CONFIG</strong>, “group_id”);<br> config.put(ConsumerConfig.<strong>KEY_DESERIALIZER_CLASS_CONFIG</strong>, StringDeserializer.class);<br> config.put(ConsumerConfig.<strong>VALUE_DESERIALIZER_CLASS_CONFIG</strong>, <strong>StringDeserializer</strong>.class);</pre><pre>return new <strong>DefaultKafkaConsumerFactory</strong>&lt;&gt;(config);</pre><pre>}</pre><pre>@<strong>Bean<br></strong>public <strong>ConcurrentKafkaListenerContainerFactory</strong>&lt;String, String&gt; kafkaListenerContainerFactory() {</pre><pre>ConcurrentKafkaListenerContainerFactory&lt;String, String&gt; factory = new ConcurrentKafkaListenerContainerFactory();<br>factory.setConsumerFactory(<strong>consumerFactory</strong>());<br>return factory;</pre><pre>}</pre><h4>Suppose if we have to operate on a custom data type such as</h4><h4>Model Class : User</h4><pre>public class <strong>User</strong> {</pre><pre>private String <strong>name</strong>;<br>private String <strong>dept</strong>;<br>private Long <strong>salary</strong>;</pre><pre>public <strong>User</strong>(String name, String dept, Long salary) {<br> this.name = name;<br> this.dept = dept;<br> this.salary = salary;<br>}</pre><pre>public String <strong>getName</strong>() { return name; }<br>public void <strong>setName</strong>(String name) { this.name = name; }<br>public String <strong>getDept</strong>() { return dept; }<br>public void <strong>setDept</strong>(String dept) { this.dept = dept; }<br>public Long <strong>getSalary</strong>() { return salary; }<br>public void <strong>setSalary</strong>(Long salary) { this.salary = salary; }</pre><pre>}</pre><h4>Kafka Producer for User Class</h4><pre>@<strong>Configuration<br></strong>public class <strong>KafkaProducerConfiguration</strong> {</pre><pre>@<strong>Bean<br></strong>public <strong>ProducerFactory</strong>&lt;String, User&gt; <strong>producerFactory</strong>() {</pre><pre>Map&lt;String, Object&gt; <strong>config</strong> = new HashMap&lt;&gt;();<br>config.put(<strong>ProducerConfig</strong>.<strong>BOOTSTRAP_SERVERS_CONFIG</strong>, “127.0.0.1:9092”);<br>config.put(<strong>ProducerConfig</strong>.<strong>KEY_SERIALIZER_CLASS_CONFIG</strong>, StringSerializer.class);<br>config.put(<strong>ProducerConfig</strong>.<strong>VALUE_SERIALIZER_CLASS_CONFIG</strong>, JsonSerializer.class);</pre><pre>return new <strong>DefaultKafkaProducerFactory</strong>&lt;&gt;(config);</pre><pre>}</pre><pre>@<strong>Bean<br></strong>public KafkaTemplate&lt;String, User&gt; <strong>kafkaTemplate</strong>() {<br>return new KafkaTemplate&lt;&gt;(<strong>producerFactory</strong>());<br>}</pre><pre>}</pre><p><strong>Kafka Consumer for User Class</strong></p><pre>@<strong>Bean</strong></pre><pre>public ConsumerFactory&lt;String, User&gt; userConsumerFactory() {</pre><pre>Map&lt;String, Object&gt; config = new HashMap&lt;&gt;();<br>config.put(ConsumerConfig.<strong>BOOTSTRAP_SERVERS_CONFIG</strong>, “127.0.0.1:9092”);<br>config.put(ConsumerConfig.<strong>GROUP_ID_CONFIG</strong>, “group_json”);<br>config.put(ConsumerConfig.<strong>KEY_DESERIALIZER_CLASS_CONFIG</strong>, StringDeserializer.class);<br>config.put(ConsumerConfig.<strong>VALUE_DESERIALIZER_CLASS_CONFIG</strong>, JsonDeserializer.class);</pre><pre>return new <strong>DefaultKafkaConsumerFactory</strong>&lt;&gt;<br>(<br>config, <br>new StringDeserializer(),<br>new JsonDeserializer&lt;&gt;(<strong>User</strong>.class)<br>);</pre><pre>}</pre><pre>@Bean</pre><pre>public <strong>ConcurrentKafkaListenerContainerFactory</strong>&lt;String, User&gt; userKafkaListenerFactory() {</pre><pre><strong>ConcurrentKafkaListenerContainerFactory</strong>&lt;String, User&gt; factory = new ConcurrentKafkaListenerContainerFactory&lt;&gt;();<br>factory.setConsumerFactory(userConsumerFactory());</pre><pre>return factory;</pre><pre>}</pre><p>Rest Controller Class for Producer</p><pre>@<strong>RestController<br></strong>@<strong>RequestMapping</strong>(“kafka”)<br>public class UserResource {</pre><pre>@Autowired<br>private <strong>KafkaTemplate</strong>&lt;String, User&gt; <strong>kafkaTemplate</strong>;</pre><pre>private static final String <strong>TOPIC</strong> = “Kafka_Example”;</pre><pre>@GetMapping(“<strong>/publish/{name}</strong>”)<br>public String <strong>post</strong>(@PathVariable(“name”) final String name) {</pre><pre>kafkaTemplate.<strong>send</strong>(TOPIC, new User(name, “Technology”, 12000L));</pre><pre>return “Published successfully”;</pre><pre>}<br>}</pre><p>Kafka Listener for the consumer</p><pre>@<strong>Service<br></strong>public class <strong>KafkaConsumer </strong>{</pre><pre> @<strong>KafkaListener</strong>(topics = “Kafka_Example”, group = “group_id”)<br> public void <strong>consume</strong>(String message) {<br>  System.out.println(“Consumed message: “ + message);<br>}</pre><pre>@<strong>KafkaListener</strong>(<strong>topics </strong>= “<strong>Kafka_Example_json</strong>”, <strong>group </strong>= “group_json”,<strong>containerFactory </strong>= “<strong>userKafkaListenerFactory</strong>”)<br>public void <strong>consumeJson</strong>(<strong>User</strong> user) {<br> System.out.println(“Consumed JSON Message: “ + user);<br>}<br>}</pre><p>Steps.</p><pre><strong>Step 1.</strong> Install Zookeeper / Kafka</pre><pre><strong>Step 2.</strong> Start Zookeeper</pre><pre>        cd C:\RS\Softwares\kafka_2.11–1.1.0\bin\windows</pre><pre><strong>zookeeper-server-start.bat C:\RS\Softwares\kafka_2.11–1.1.0\config\zookeeper.properties</strong></pre><pre><strong>Step 3.</strong> Start Kafka Server</pre><pre><strong>kafka-server-start.bat C:\RS\Softwares\kafka_2.11–1.1.0\config\server.properties</strong></pre><pre>Step 4. Create Kafka Topic</pre><pre><strong>kafka-topics.bat — create — zookeeper localhost:2181 — replication-factor 1 — partitions 1 — topic Kafka_Example</strong></pre><pre>Consume from the Kafka Topic via Console</pre><pre><strong>kafka-console-consumer.bat — bootstrap-server localhost:9092 — topic Kafka_Example — from-beginning</strong></pre><p>Publish message via WebService</p><pre><a href="http://localhost:8081/kafka/publish/Sam">http://localhost:8081/kafka/publish/Sam</a></pre><pre><a href="http://localhost:8081/kafka/publish/Peter">http://localhost:8081/kafka/publish/Peter</a></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36a1daaffed7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Immutable Objects]]></title>
            <link>https://medium.com/@retheesh.soman/immutable-objects-602b37860d7f?source=rss-8a3261968358------2</link>
            <guid isPermaLink="false">https://medium.com/p/602b37860d7f</guid>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Retheesh Soman]]></dc:creator>
            <pubDate>Sat, 18 Aug 2018 19:18:11 GMT</pubDate>
            <atom:updated>2018-08-18T19:18:11.441Z</atom:updated>
            <content:encoded><![CDATA[<p>Immutable objects are those whose state cannot be changed once created. Any modification will result in a new object e.g. String, Integer, and other wrapper class. The following rules define a simple strategy for creating immutable objects. Not all classes documented as “immutable” follow these rules. This does not necessarily mean the creators of these classes were sloppy — they may have good reason for believing that instances of their classes never change after construction. However, such strategies require sophisticated analysis and are not for beginners.</p><p>1. Don’t provide “setter” methods — methods that modify fields or objects referred to by fields.</p><p>2. Make all fields final and private.</p><p>3. Don’t allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.</p><p>4. If the instance fields include references to mutable objects, don’t allow those objects to be changed:</p><blockquote>Don’t provide methods that modify the mutable objects.</blockquote><p>Don’t share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=602b37860d7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wait vs Sleep]]></title>
            <link>https://medium.com/@retheesh.soman/wait-vs-sleep-749c5847e854?source=rss-8a3261968358------2</link>
            <guid isPermaLink="false">https://medium.com/p/749c5847e854</guid>
            <category><![CDATA[sleep]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[wait]]></category>
            <dc:creator><![CDATA[Retheesh Soman]]></dc:creator>
            <pubDate>Sat, 18 Aug 2018 19:14:38 GMT</pubDate>
            <atom:updated>2018-08-18T19:14:38.913Z</atom:updated>
            <content:encoded><![CDATA[<p>Copied from <a href="https://javarevisited.blogspot.com/">https://javarevisited.blogspot.com/</a> for the references</p><p><strong>Wait </strong>method is defined in Object class and it available to all object, wait() method is always discussed along with its counterpart notify() and notifyAll() method and used in inter thread communication in Java. The wait() method puts a thread on wait by checking some condition like in Producer Consumer problem, producer thread should wait if Queue is full or Consumer thread should wait if Queue is empty. The notify() method is used to wake up waiting thread by communicating that waiting condition is over now for example once producer thread puts an item on empty queue it can notify Consumer thread that Queue is not empty any more. On the other hand Sleep() method is used to introduce pause on Java application.</p><p>1) First and most important difference between Wait and sleep method is that wait method must be called from synchronized context i.e. from synchronized method or block in Java. If you call wait method without synchronization, it will throw <strong><em>IllegalMonitorStateException </em></strong>in Java. On the other hand there is no requirement of synchronization for calling sleep method , you can call it normally.</p><p>2) Second worth noting difference between wait and sleep method is that, wait operates on <strong>Object </strong>and defined in Object class while sleep operates on current <strong>Thread </strong>and defined in java.lang.Thread class.</p><p>3) Third and another significant difference between wait and sleep in Java is that, wait() method releases the lock of object on which it has called, it does release other locks if it holds any while sleep method of Thread class does not release any lock at all.</p><p>4) wait method needs to be called from a loop in order to deal with false alarm i.e. waking even though waiting condition still holds true, while there is no such thing for sleep method in Java. its better not to call Sleep method from loop.</p><p>here is code snippet for calling wait and sleep method in Java</p><pre><strong>synchronized</strong>(monitor)<br> <strong>while</strong>(condition == <strong>true</strong>){ monitor.wait()) <em>//releases monitor lock</em><br> <br> <strong>Thread</strong>.sleep(100); <em>//puts current thread on Sleep</em></pre><p>5) One more difference between wait and sleep method which is not as significant as previous ones is that wait() is a non static method while sleep() is static method in Java.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*dD0J54bR0RSAQ8p9NRuFhA.png" /></figure><h3>Where to use wait and sleep method in Java</h3><p>By reading properties and behavior of wait and sleep method it’s clear that wait() method should be used in conjunction with notify() or notifyAll() method and intended for communication between two threads in Java while Thread.sleep() method is a utility method to introduce short pauses during program or thread execution. Given the requirement of synchronization for wait, it should not be used just to introduce pause or sleep in Java.</p><p>In summary <strong>wait and sleep method are completely different to each other</strong> and have different use cases. Use wait() and notify() method for inter thread communication while use sleep() method for introducing small pause during thread execution. Also remember, that wait() method will release the lock acquired when it entered into synchronized block or method, but sleep() method will keep the lock with itself. So if you design require releasing the lock during wait period then use wait() and notify method otherwise just use sleep().</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=749c5847e854" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>