<?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 Praveen Fernando on Medium]]></title>
        <description><![CDATA[Stories by Praveen Fernando on Medium]]></description>
        <link>https://medium.com/@Praveen_Fernando?source=rss-56611250a0e6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5JuKjBk5-1hWANsxohIhTQ.png</url>
            <title>Stories by Praveen Fernando on Medium</title>
            <link>https://medium.com/@Praveen_Fernando?source=rss-56611250a0e6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 19:28:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Praveen_Fernando/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[Understanding JDK, JRE, and Maven: Essential Tools for Java Development]]></title>
            <link>https://medium.com/@Praveen_Fernando/understanding-jdk-jre-and-maven-essential-tools-for-java-development-1ba47e1c7c69?source=rss-56611250a0e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ba47e1c7c69</guid>
            <category><![CDATA[environment-variables]]></category>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[jdk]]></category>
            <category><![CDATA[jre]]></category>
            <category><![CDATA[setup-guide]]></category>
            <dc:creator><![CDATA[Praveen Fernando]]></dc:creator>
            <pubDate>Fri, 18 Aug 2023 17:31:41 GMT</pubDate>
            <atom:updated>2023-08-18T17:38:02.489Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NNp8hsbLZ_0FHRzbq4XPaA.jpeg" /></figure><p>Java, one of the most popular programming languages, has stood the test of time due to its portability and versatility. To develop and run Java applications, you need a set of tools that facilitate the process. In this article, we’ll delve into three essential components: the Java Development Kit (JDK), the Java Runtime Environment (JRE), and Apache Maven. We’ll explore their roles, stable versions, provide download links, and guide you through environment configurations.</p><blockquote><strong>Java Development Kit (JDK)</strong></blockquote><p>The Java Development Kit (JDK) is a comprehensive software package that provides the tools and binaries required for Java development. It includes a compiler, debugger, and various utilities to help developers create, compile, and run Java applications.</p><p><em>Stable Versions: JDK 8, JDK 11, and JDK 17</em></p><p>As of the latest update, JDK 17 is the most recent stable version, but it’s important to note that different projects and applications may have compatibility requirements with specific JDK versions. Here, we’ll provide information about JDK 8, JDK 11, and JDK 17.</p><p><em>Download Links</em></p><p>- [JDK 8 Download](<a href="https://www.oracle.com/java/technologies/javase-jdk8-downloads.html">https://www.oracle.com/java/technologies/javase-jdk8-downloads.html</a>)<br>- [JDK 11 Download](<a href="https://www.oracle.com/java/technologies/javase-jdk11-downloads.html">https://www.oracle.com/java/technologies/javase-jdk11-downloads.html</a>)<br>- [JDK 17 Download](<a href="https://www.oracle.com/java/technologies/javase-downloads.html">https://www.oracle.com/java/technologies/javase-downloads.html</a>)</p><p><em>Environment Configuration</em></p><p>After downloading the JDK versions of your choice, follow these steps to set up your environment:</p><p>1. Installation: Run the JDK installer and follow the on-screen instructions to complete the installation process.</p><p>2. Environment Variables: Set up the `JAVA_HOME` environment variable to point to the JDK installation directory. Add the `bin` directory of the JDK to the system’s `PATH` variable.</p><p>3. Verify Installation: Open a terminal or command prompt and type `java -version` to verify that the JDK is installed correctly.</p><blockquote><strong>Java Runtime Environment (JRE)</strong></blockquote><p>The Java Runtime Environment (JRE) is a subset of the JDK and is necessary for running Java applications on your machine. It contains the Java Virtual Machine (JVM), class libraries, and other resources required to execute Java programs.</p><p><em>Stable Versions: JRE 8, JRE 11, and JRE 17</em></p><p>The JRE versions typically match the corresponding JDK versions. Therefore, JRE 8, JRE 11, and JRE 17 are the stable versions corresponding to their respective JDK versions.</p><p><em>Download Links</em></p><p>- [JRE 8 Download](<a href="https://www.oracle.com/java/technologies/javase-jre8-downloads.html">https://www.oracle.com/java/technologies/javase-jre8-downloads.html</a>)<br>- [JRE 11 Download](<a href="https://www.oracle.com/java/technologies/javase-jre11-downloads.html">https://www.oracle.com/java/technologies/javase-jre11-downloads.html</a>)<br>- [JRE 17 Download](<a href="https://www.oracle.com/java/technologies/javase-jre8-downloads.html">https://www.oracle.com/java/technologies/javase-jre8-downloads.html</a>)</p><p><em>Environment Configuration</em></p><p>Setting up the JRE environment is simpler than the JDK:</p><p>1. Installation: Run the JRE installer and follow the on-screen instructions to complete the installation.</p><p>2. Environment Variables: Similar to the JDK, you can set the `JAVA_HOME` environment variable to point to the JRE installation directory.</p><p>3. Verification: Open a terminal or command prompt and type `java -version` to ensure that the JRE is properly installed.</p><blockquote><strong>Apache Maven</strong></blockquote><p>Apache Maven is a powerful build automation and project management tool. It simplifies the process of managing dependencies, compiling, testing, and packaging Java applications.</p><p><em>Stable Version: Apache Maven 3.8.4</em></p><p>As of the latest update, Apache Maven 3.8.4 is the stable version. It includes bug fixes and improvements over previous releases.</p><p><em>Download Link</em></p><p>You can download Apache Maven 3.8.4 from the official Apache Maven website: [Apache Maven Download](<a href="https://maven.apache.org/download.cgi">https://maven.apache.org/download.cgi</a>)</p><p><em>Environment Configuration</em></p><p>To set up Apache Maven:</p><p>1. Download and Extraction: Download the Apache Maven binary zip file and extract it to a directory of your choice.</p><p>2. Environment Variables: Set up the `MAVEN_HOME` environment variable to point to the Maven installation directory. Add the `bin` directory of Maven to the system’s `PATH` variable.</p><p>3. Verification: Open a terminal or command prompt and type `mvn -version` to verify that Maven is installed correctly.</p><p><strong>Conclusion</strong></p><p>Understanding the roles and proper configuration of the Java Development Kit (JDK), Java Runtime Environment (JRE), and Apache Maven is essential for effective Java development. By installing and configuring these tools correctly, you’ll have a solid foundation for building, running, and managing Java applications with ease. Keep an eye on official websites for updates and new releases to stay up-to-date with the latest enhancements and features in the Java ecosystem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ba47e1c7c69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Fundamentals]]></title>
            <link>https://medium.com/@Praveen_Fernando/javascript-fundamentals-f5e25fd16345?source=rss-56611250a0e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5e25fd16345</guid>
            <category><![CDATA[javascript-fundamental]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Praveen Fernando]]></dc:creator>
            <pubDate>Fri, 22 Jul 2022 08:06:18 GMT</pubDate>
            <atom:updated>2022-07-22T08:06:18.588Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*PmUTWiNpLP-Qult2tuUtWw.jpeg" /></figure><p>JavaScript (JS) is a lightweight, interpreted, and scripting language with first-class functions. While it is most well-known as the scripting language for Web pages, many non-browser environments. In JavaScript’ the most important component is the JavaScript engine. This js engine is used to compile the program and make it into reality. These engines work in 2 phases:</p><ol><li>Creation phase.</li><li>Execution phase.</li></ol><blockquote><strong>Creation phase :</strong></blockquote><p>As the first step of the creation phase, it creates the activation object(which means scanning all the code and listing down all the variables and declarations).In the second step, it creates the scope chain(which means it lists down all the variables in the current function), and in the final step, it determines <strong>this</strong> object.</p><blockquote><strong>Execution phase:</strong></blockquote><p>Assume we have a script with variables and functions. The very first-time when this program runs it creates a call stack called execution context. In the creation phase, any variable, or any function(not function expressions) in the script, it will take and create in the global scope or global execution context. The global execution context is the place where JavaScript code that is not inside a function gets executed. it will create this variable, but it will not proceed with assignments. So, these variable values would be undefined.</p><p>Whenever we invoke a function, it will create a new function context. All the 3 steps will run the function scope. Every time when we invoke a function it creates a new execution context and once it returns, it destroys this and returns back to the parent.</p><blockquote><strong>Call stack</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zDMaEPqpl6uubAjgCXW3iA.png" /></figure><p>When you execute a script, the engine creates a Global Execution Context and pushes it on top of the call stack. Whenever a function is called, the JavaScript engine creates a function execution context for the function, pushes it on top of the call stack, and starts executing the function.</p><p>If a function calls another function, the JavaScript engine creates a new function execution context for the function that is being called and pushes it on top of the call stack. When the current function completes, the engine pops it off the call stack and resumes the execution where it left off.</p><p>When we invoke a recursion function it will keep creating a stack until the stack is full. As a result, it leads to a stack overflow error.</p><p>The variables and values are stored in heap. Heaps is the place where JavaScript stores the variables and their values. Stack is the place where the JavaScript creates frames according to your method invocation.</p><blockquote><strong>Hoisting</strong></blockquote><p>JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables, or classes to the top of their scope, prior to execution of the code.</p><p>Once the script runs it shows the variable as undefined because variables because during the creation phase it moved all the globally declared variables to its top, but it only moves the variable declaration, not the initialization. This means we can use JavaScript variables before it declares. To understand these let&#39;s use the below example. Here we use variable a(var a) before its declaration as shown in blow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*2X2zBC5hc1PXCYTIfS4_iQ.png" /></figure><p>It will print undefined in the console because the creation phase will only move variable declaration, not the initialization. Most of the developers think hosting only works with var but the variables create using the let keyword can also be hoisted. When we use “<strong>var”</strong> it creates a function scope but when we use “<strong>let” </strong>it creates a script scope. The JavaScript engine is aware that there is a variable, but it cannot use it before declaring it. If we use the let variable before declaring it, it will give a Reference Error as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w7mn_uds1c7tM8w0wOvxjQ.png" /></figure><p>Hosting works for the function but not for reference. Hosting supports, when it is a “<strong>var”</strong> and function but in “<strong>let</strong>”, hosting works but cannot use that.</p><blockquote><strong>Reactive Programming</strong></blockquote><p>Reactive programming describes a design paradigm that relies on asynchronous programming logic that allows us to manipulate streams of data using functions. This means we do the operation of streams of data that starts from one place and being consumed at other places.</p><p>In order to make the reactive programming in reality we need 3 things:</p><ol><li>Data Streams</li><li>Functional Programming</li><li>Asynchronous Observer</li></ol><p><strong><em>Use of Reactive Programming</em></strong></p><ul><li>Can be used anywhere it takes time to process the request. As an example, sending a request to HTTP backend and backend take time to process and developers don’t have to wait until that time. So, this HTTP backend can use Reactive Programming.</li><li>Can be used to log notifications. As an example, the observer can wait for the notifications, and when the notification comes developers can log it.</li></ul><blockquote><strong>Imperative programming</strong></blockquote><ul><li>Imperative programming is a software development paradigm where functions are implicitly coded in every step required to solve a problem.</li><li>Focus on how the program works, and it has an easy learning curve.</li><li>Functions, conditions, loops, and OOP concepts are available.</li><li>Statements can change the state of the program. Eg: Java, C</li></ul><blockquote><strong>Functional programming</strong></blockquote><ul><li>functional programming is a set of approaches to coding, usually described as a programming paradigm.</li><li>Focuses on what is the object(what to solve).</li><li>Can be a long curve on migrations and ideally to be stateless.</li><li>Use Functions to create expressions rather than statements</li><li>We use chains of functions. Eg: Scala</li></ul><p>Almost all the languages do not support reactive programming. Therefore we need some external support to convert these languages to reactive programming. Reactivex.io is the official framework that governs reactive programming, and it has separate libraries for each language, such as RxJava(for Java), RxJS(for JavaScript), Rx.net(for dot net), RxScala(for Scala), and NgRx(for angular) for multiple languages.</p><blockquote><strong>Promises Vs Observables</strong></blockquote><p><strong>Promise</strong></p><p>A Promise is an object that represents the eventual success or failure of an asynchronous operation. As well as its return value. JavaScript promise is a promised operation that has various states such as Created, Pending, Success, and Error. The JavaScript Promise is the backbone of asynchronous programming in JavaScript. It allows us to queue asynchronous tasks as a Promise and handle other stuff while we wait for the promise to complete.</p><p><strong>Observables</strong></p><p>An Observable is a listener that subscribes to an event emitter and fires every time a new event is emitted. In other words, an Observable observes whatever you tell it to and then fires when a specified condition is met. As an example, we observe for a specific button click and then log to the console.</p><p>~end~</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5e25fd16345" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Manual messages acknowledge in Kafka]]></title>
            <link>https://medium.com/@Praveen_Fernando/manual-messages-acknowledge-in-kafka-5e5a4c79ae56?source=rss-56611250a0e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e5a4c79ae56</guid>
            <dc:creator><![CDATA[Praveen Fernando]]></dc:creator>
            <pubDate>Wed, 20 Jul 2022 18:17:21 GMT</pubDate>
            <atom:updated>2022-07-20T18:20:56.387Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Y6LxJIGBQGrP8eLIqXVung.jpeg" /></figure><p>We are going to look at how to send messages as batches not as single or one by one. For demonstration, we use the same project we use previously.</p><p>We use “eachBatch” To send messages as a batch. Here the consumer will take messages as a batch and commit these messages back to Kafka(consumer offset). While sending a huge number of messages crashers can happen. To avoid that we have 2 ways:</p><p><strong>autoCommitThreshold</strong></p><p>We can use a threshold called autoCommitThreshold. When a given number of messages is reached, it will send the commit to offset back to the server. (if the threshold is 10 it will commit messages 10 by 10.)</p><p><strong>autoCommitInterval</strong></p><p>We can use autoCommitInterval to avoid that. What it does is, for a given time it commits messages back to what consumers state to the server.</p><p>Let’s see what happens when we stop auto-commit using a demonstration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*bjSPZqSS2rdNGRskJenbIQ.png" /><figcaption>consumer.js</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*2bmrQTEggOvMKWlviwerrQ.png" /><figcaption>producer.js</figcaption></figure><p>Once we run the producer and consumer, all the messages are printed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bWcp1gq6sngsWaVh4L4HmA.png" /></figure><p>Now, let’s break the break message purposely and see what will happen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*BrYnB9-Kja3mnjXUd2tD3w.png" /></figure><p>It breaks from the 5th message but keeps retrying and within a couple of seconds, it starts again from the 0th message this happens, because these messages are in the same batch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6kOjVZC1B2ZOUkih_UGN-w.png" /></figure><p>However, we do not want messages above 5th to retry because they are successfully processed. When this runs again after retrying, we can still see that 4th message. This happens Because it’s processed as batches. (1 by 1)</p><p>Now let&#39;s add this retry and see what would happen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*g40NihvhPFQJdPcqnKlNYA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*on8SVPipWC7TLVMxZPRRbw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C0SZqdu53vufna_84k6HVg.png" /></figure><p>Once we remove this retry It breaks from the crashed message 18th but still shows the successfully processed 17th message. This happens because Kafka sets consumer offset to the last successfully processed message. Since the 18th message fails, it doesn’t get the consumer offset. Therefore, when Kafka retries it starts from the last consumer offset. This can be handled by making Kafka by sending the next offset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*mPwcXJPnzGX3Unbf2fPz-Q.png" /></figure><p>Now the problem is solved and the processed message will not be displayed. However, This will keep retrying since this message does not get processed. The problem is meanwhile this retying happens, other messages will queue up inside the topic.</p><p>Now let’s start with another consumer, the 21st message is sent to both the consumers to process. but this is a broken message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dWAnshbC4QaswYZa1JfmJg.png" /></figure><p>Let’s assume that we fixed the broken message and try creating another consumer, while the above consumers keep running the 21st message. Now the messages are distributed among the two consumers as usual. but the running consumers will now get an error and will not be used to process the messages because the message will be handled by a single consumer.</p><p>Until we fix the problem more and more messages keep coming. But none of the messages will be dispatched and this leads to a lag between the last produced message and the last committed message.</p><blockquote><strong><em>Session Timeout</em></strong></blockquote><p>The session timeout property handles the rebalancing properly. Let’s assume the Session Timeout is the 30s. If you didn’t unable to send a heartbeat within this time, the consumer will get detached from Kafka. To avoid this, we can use 2 solutions.</p><ol><li>Increase session Timeout time. This might cause a problem which is in case the consumer is really dead. Kafka has to wait a long time to identify it and it might impact rebalancing</li><li>Keep session Intervals in a reliable amount and from each message send a heartbeat as an input.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*COyiqrk9d5eZGsSlerYKgA.png" /></figure><p>The heartbeat will inform Kafka that the consumer is alive and stay away from getting detached.</p><blockquote><strong>Reference</strong></blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F4HV2N0GKhd8%3Fstart%3D639%26feature%3Doembed%26start%3D639&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D4HV2N0GKhd8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F4HV2N0GKhd8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/40788b0a1560832a415383c5b344c25b/href">https://medium.com/media/40788b0a1560832a415383c5b344c25b/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e5a4c79ae56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chapter 18 — Remote Deployment with RMI]]></title>
            <link>https://medium.com/@Praveen_Fernando/chapter-18-remote-deployment-with-rmi-c94569edabba?source=rss-56611250a0e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/c94569edabba</guid>
            <category><![CDATA[head-first-java]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Praveen Fernando]]></dc:creator>
            <pubDate>Sun, 17 Jul 2022 04:02:41 GMT</pubDate>
            <atom:updated>2022-07-17T04:02:41.815Z</atom:updated>
            <content:encoded><![CDATA[<h3>Chapter 18 — Remote Deployment with RMI</h3><p><strong>Distributed Computing</strong></p><p>To design a remote method call we need to create 4 things such as server, client, server helper, and client helper. Let’s find out how to create these.</p><ol><li>Create client and server apps. The server app is the remote service that has an object with the method that the client wants to invoke.</li><li>Create client and server ‘helpers”. They’ll handle all the low-level networking and I/O details so your client and service can pretend like they’re in the same heap.</li></ol><p>The client object acts like it’s making remote method calls. But what it’s really doing is calling methods on a heap-local ‘proxy’ object that handles all the low-level details of Sockets and streams.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*ur0hq_cgQmx2wmYOAY2WZA.png" /></figure><p><strong><em>How the method call happens.</em></strong></p><ol><li>The client object calls the doBigThing() method on the client helper object.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*OY91BuuZIZ9pjJJ8bDXOKQ.png" /></figure><p>2. The client helper packages up information(arguments, method name, etc.) about the call and ships it over the network to the service helper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*bZZDY0gc8EXlP5hzrMbT_w.png" /></figure><p>3. Then the service helper unpacks the information from the client helper and finds out which method to call (on which object) and invokes the real method on the real service object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*sIQ-X7EgBtUsO_jJLhJopQ.png" /></figure><p>In Java, RMI builds the client and service helper objects for you, and it knows how to make the client helper look like the Real Service. In RMI, the client helper is a ‘stub’ and the server helper is a ‘skeleton’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*c_NQTy_HPxvn2OH69T-VgA.png" /></figure><p><strong><em>Making the Remote Service</em></strong></p><p><strong><em>Step one : Make a Remote Interface.</em></strong></p><p>The remote interface defines the methods that a client can call remotely.</p><ol><li>Extend java.rmi.Remote</li></ol><pre>public interface MyRemote extends Remote {}</pre><p>2. Declare that all methods throw a RemoteException</p><pre>import java.rmi.*;<br>public interface MyRemote extends Remote {<br>    public String sayHello() throws RemoteException;<br>}</pre><p>3. Be sure arguments and return values are primitives or Serializable.</p><pre>public String sayHello() throws RemoteException;</pre><p><strong><em>Step two : Make a Remote Implementation.</em></strong></p><p>It has the real implementation of the remote methods defined in the remote interface. It’s the object that the client wants to call methods on.</p><ol><li>Implement the Remote interface</li></ol><pre>public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote {<br>    public String sayHello() {<br>        return “Server says, ‘Hey’”;<br>    }// more code in class <br>}</pre><p>2. Extend UnicastRemoteObject</p><pre>public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote {}</pre><p>3. Write a no-arg constructor that declares a RemoteException</p><pre>public MyRemoteImpl() throws RemoteException { }</pre><p>4. Register the service with the RMI registry</p><pre>try {<br>    MyRemote service = new MyRemoteImpl();<br>    Naming.rebind(“Remote Hello”, service);<br>} catch(Exception ex) {...}</pre><p><strong><em>Step three : generate stubs and skeletons.</em></strong></p><p>It’s all handled automatically when you run the rmic tool that ships with your Java development kit.</p><ul><li>Run rmic on the remote implementation class</li></ul><p><strong><em>Step four : run rmiregistry</em></strong></p><p>It’s where the user goes to get the proxy (the client stub/helper object).</p><ul><li>Bring up a terminal and start the rmiregistry.</li></ul><p><strong><em>Step five : Start the service.</em></strong></p><p>The service implementation class instantiates an instance of the service and registers it with the RMI registry. Registering it makes the service available to clients</p><ul><li>Bring up another terminal and start your service</li></ul><blockquote><strong><em>server-side</em></strong></blockquote><p>The Remote interface:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*Y6cIQNpIc43rXd1QL-IdNA.png" /></figure><p>The Remote service (the implementation):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*R9YSkdaP_OLIKXJNRSwGUA.png" /></figure><p><strong><em>How does the client get the stub object?</em></strong></p><ul><li>The client does a lookup on the RMI registry.</li></ul><pre>Naming.lookup(“rmi://127.0.0.1/Remote Hello”);</pre><ul><li>RMI registry returns the stub object.</li><li>The client invokes a method on the stub, as though the stub IS the real service.</li></ul><blockquote><strong><em>Client-side</em></strong></blockquote><p>Simple system, you can simply hand-deliver the stub class to the client. With dynamic class downloading, a stub object (or really any Serialized object) is ‘stamped’ with a URL that tells the RMI system on the client where to find the class file for that object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*pcs3q71YM8dTfTb5Esobfg.png" /></figure><blockquote><strong><em>Servlets</em></strong></blockquote><p>Servlets are Java programs that run on an HTTP web server. Servlets run the code on the server, as a result of client interaction with a web page. To run a servlet, you must have a web server capable of running servlets, such as the Tomcat server from apache.org.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*c_ZO8bppuW8Jmfy_VJPfZQ.png" /></figure><p><strong><em>Steps for making and running a servlet</em></strong></p><ul><li>Find out where your servlets need to be placed.</li><li>Get the servlets.jar and add it to your classpath.</li><li>Write a servlet class by extending HttpServlet.</li></ul><pre>public class MyServletA extends HttpServlet { ... }</pre><ul><li>Write an HTML page that invokes your servlet.</li></ul><pre>&lt;a href=”servlets/MyServletA”&gt;This is the most amazing servlet.&lt;/a&gt;</pre><ul><li>Make your servlet and HTML page available to your server.</li></ul><blockquote><strong><em>Enterprise JavaBeans: RMI on steroids</em></strong></blockquote><p>An EJB server adds a collection of services that you don’t get with straight RMI. Such as transactions, security, concurrency, database management, and networking. An EJB server steps into the middle of an RMI call and layers in all of the services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*krRvm1lx24xMOYrKitXmCA.png" /></figure><blockquote><strong><em>Universal Service browser</em></strong></blockquote><p><strong><em>How it works:</em></strong></p><ol><li>The client starts and lookup up the ServiceServer in the RMI registry and gets back the stub.</li><li>Client calls getServiceList() on the stub. The ServiceServer returns an array of services.</li><li>The client displays the list of services in a GUI</li><li>The user selects from the list, so the client calls the getService() method on the remote service. It returns a serialized object.</li><li>The client calls the getGuiPanel() on the serialized service object it just got from the remote service. The GUI for that service is displayed inside the browser, and the user can interact with it locally.</li></ol><blockquote><strong>Reference</strong></blockquote><p><a href="https://www.rcsdk12.org/cms/lib/NY01001156/Centricity/Domain/4951/Head_First_Java_Second_Edition.pdf">https://www.rcsdk12.org/cms/lib/NY01001156/Centricity/Domain/4951/Head_First_Java_Second_Edition.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c94569edabba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chapter 17 — Package, Jars, and Deployment.]]></title>
            <link>https://medium.com/@Praveen_Fernando/chapter-17-package-jars-and-deployment-e7af07fd6b65?source=rss-56611250a0e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7af07fd6b65</guid>
            <category><![CDATA[head-first-java]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jar]]></category>
            <dc:creator><![CDATA[Praveen Fernando]]></dc:creator>
            <pubDate>Sat, 16 Jul 2022 18:02:27 GMT</pubDate>
            <atom:updated>2022-07-16T18:02:27.162Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Chapter 17 — Package, Jars, and Deployment.</strong></h3><blockquote><strong><em>Jars</em></strong></blockquote><p>Java program is a bunch of classes. We can deploy our java program using local, a combination of local, remote, and fully remote deploy options.</p><p>JAR file is a Java Archive, and It is based on the “pkzip” file format, and it allows you to bundle all your classes into one. So that instead of presenting your client with all class files, you hand over just a single JAR file.</p><p>Making a Jar file executable allows you to run it. An executable Jar means the end-user doesn’t have to pull the class files out and the user can run the app while the class files are still in the JAR. Inside the Jar file, there is a file called manifest. Which holds the information to make the program executable. Manifest informs JVM, where the main method is located.</p><p><strong><em>Making an executable JAR</em></strong></p><ol><li>Make sure all of your class files are in the class directory.</li><li>Create a manifest.txt file that states which class has the main() method.</li><li>Run the jar tool to create a JAR file.</li></ol><pre>%cd MyProject/classes<br>%jar -cvmf manifest.txt app1.jar *.class<br>OR<br>%jar -cvmf manifest.txt app1.jar MyApp.class</pre><blockquote><strong><em>Packages</em></strong></blockquote><ul><li>Java package is a group of similar types of classes, interfaces, and sub-packages. Packages in java can be categorized in two forms, built-in packages, and user-defined packages.</li><li>Packages can prevent name conflicts, but only if you choose a package name that’s guaranteed to be unique. The best way to do that is to preface your packages with your reverse domain name.</li></ul><p>You must put a class into a directory structure that matches the package hierarchy. To put your class in a package you have to follow the following steps:</p><ol><li>Choose a package name.</li><li>Put a package statement in your class.</li><li>Set up a matching directory structure.</li></ol><blockquote>Compiling with the -d flag</blockquote><p>To create a compiled class land in the current package directory structure under the class directory.</p><pre>%cd MyProject/source<br>%javac -d ../classes com/headfirstjava/PackageExercise.java</pre><p>The -d flag tells the compiler to put the class into its package directory structure, using the class specified after the -d as the root directory. But if the directories aren’t there, create them first and then put the class in the right root directory.</p><p><strong><em>Making an executable JAR with packages</em></strong></p><ol><li>Make sure all of your class files are within the correct package structure.</li><li>Create a manifest.txt file that states which class has the main() method and use the fully qualified class name.</li><li>Run the jar tool to create a JAR.</li></ol><blockquote><strong><em>Java Web Start</em></strong></blockquote><p>Java Web Start is an application deployment technology that gives you the power to launch full-featured applications with a single click from your Web browser.</p><p>Java Web Start app is an executable JAR that’s distributed over the Web. Once the end-users launch a Java Web Start app by clicking on a link on a Web page and it downloads an application. once the app downloads, it runs outside the browser, just like any other stand-alone Java application.</p><p><strong><em>How Java Web Start works</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*tTiinNOJXlQAr3_glhu-uA.png" /></figure><p><strong><em>Making and deploying a Java Web Start app</em></strong></p><ol><li>Make an executable JAR for your application.</li><li>Write a .jnlp file.</li><li>Place your JAR and .jnlp files on your Web server.</li><li>Add a new mime type to your Web server</li><li>Create a Web page with a link to your .jnlp file.</li></ol><blockquote><strong><em>The .jnlp file</em></strong></blockquote><ul><li>A .jnlp file is a simple XML document that describes your JWS application. It includes tags for specifying the name and location of the JAR and the name of the class with the main() method.</li><li>When a browser gets a .jnlp file from the server (because the user clicked on a link to the .jnlp file), the browser starts up the JWS helper app.</li><li>The JWS helper app reads the .jnlp file and requests the executable JAR from the Web server.</li><li>When the JWS gets the JAR, it invokes the main() method (specified in the .jnlp file).</li></ul><blockquote><strong>Reference</strong></blockquote><p><a href="https://www.rcsdk12.org/cms/lib/NY01001156/Centricity/Domain/4951/Head_First_Java_Second_Edition.pdf">https://www.rcsdk12.org/cms/lib/NY01001156/Centricity/Domain/4951/Head_First_Java_Second_Edition.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7af07fd6b65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chapter 16 — Collections and Generics]]></title>
            <link>https://medium.com/@Praveen_Fernando/chapter-16-collections-and-generics-e4660e1a08a1?source=rss-56611250a0e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4660e1a08a1</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Praveen Fernando]]></dc:creator>
            <pubDate>Sat, 16 Jul 2022 10:02:22 GMT</pubDate>
            <atom:updated>2022-07-16T10:02:22.597Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Chapter 16 — Collections and Generics</strong></h3><blockquote><strong><em>Data structures</em></strong></blockquote><p>ArrayList is the one you’ll use most often but the ArrayList class doesn’t have a sort method. It is not the only collection and there are more key collection classes.</p><ul><li>TreeSet — The elements are sorted and prevent duplicates</li><li>HashMap — allows storing and accessing elements using name/value pairs.</li><li>LinkedList — Easy to create structures like stacks or queues.</li><li>HashSet — Prevents duplicates and can find that element in the collection quickly.</li><li>LinkedHashMap — remember the order of elements (name/value pairs) were inserted</li></ul><blockquote><strong><em>Generics</em></strong></blockquote><p>By using generics, you can create type-safe collections and can be caught problems at compile time instead of runtime.</p><ol><li>Creating instances of generified classes.</li></ol><pre>new ArrayList&lt;Song&gt;();</pre><p>2. Declaring and assigning variables of generic types.</p><pre>List&lt;Song&gt; songList = new ArrayList&lt;Song&gt;();</pre><p>3. Declaring and invoking methods that take generic types.</p><pre>void foo(List&lt;Song&gt; list);<br>x.foo(songList);</pre><p>There are 2 key areas to look at in a generified class:</p><ol><li>The class declaration.</li><li>The method declarations.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lo1JLoPIjZmVvNJV06Bplg.png" /></figure><p>“E” stands for the type of elements that this collection holds and returns.</p><p>Generic class means that the class declaration includes a type parameter and the Generic method means that the method declaration uses a type of parameter in its signature.</p><p>The sort method can take only lists of Comparable objects.</p><p><strong><em>Comparator</em></strong></p><p>The sort order is determined by the Comparator rather than the element’s own compareTo() method by passing a Comparator to the sort() method.</p><ul><li>Invoking the one-argument sort(List o) method means the list element’s compareTo() method determines the order. So, it is a must to implement the elements in the list in the Comparable interface.</li><li>Invoking sort(List o, Comparator c) means the list element’s compareTo() method will NOT be called, and the Comparator’s compare() method will be used instead. This means the elements in the list are not needed to implement the Comparable interface.</li></ul><p>List collection is used when we care about the sequence, and it uses the index position. Set collection is used when we care about the uniqueness of the element while the Map collection uses to find elements by using the key (Key value pair can be used to find the elements).</p><blockquote><strong><em>The Collection API</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*8hKL-X9JEt8I53cGPok6vQ.png" /></figure><blockquote><strong><em>Object Equality</em></strong></blockquote><ul><li>Reference equality : Where two references refer to the same object on the heap. By using use the == operator can check whether the two references are really referring to the same object.</li><li>Object equality : Where two references and two objects are on the heap, but the objects are considered meaningfully equivalent. By using use the equals() method can check whether they are equal.</li></ul><p>HashSet checks for duplicate values by using hashCode() and equals().The blow image shows how it is done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*GfJ5ko_Gj3aJUjcJDzMWWQ.png" /></figure><blockquote><strong><em>TreeSet</em></strong></blockquote><p>TreeSet elements must be comparable. To use a TreeSet, one of these things must be true: The elements in the list must be of a type that implements Comparable or TreeSet’s overloaded constructor that takes a Comparator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*yPk9vqiz89g4JKykGuJaQQ.png" /></figure><blockquote><strong><em>Map</em></strong></blockquote><p>Each element in a Map is actually 2 objects which are key and value. Keys must be unique, and have duplicate values, but not duplicate keys.</p><p>Example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*QSCfBF79cDCeDMZ1bilUEQ.png" /></figure><blockquote><strong>Reference</strong></blockquote><p><a href="https://www.rcsdk12.org/cms/lib/NY01001156/Centricity/Domain/4951/Head_First_Java_Second_Edition.pdf">https://www.rcsdk12.org/cms/lib/NY01001156/Centricity/Domain/4951/Head_First_Java_Second_Edition.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4660e1a08a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chapter 15 — Networking and threads]]></title>
            <link>https://medium.com/@Praveen_Fernando/chapter-15-networking-and-threads-eaba4084f77b?source=rss-56611250a0e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/eaba4084f77b</guid>
            <category><![CDATA[head-first-java]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Praveen Fernando]]></dc:creator>
            <pubDate>Sat, 16 Jul 2022 05:08:09 GMT</pubDate>
            <atom:updated>2022-07-16T05:08:09.341Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Chapter 15 — Networking and threads</strong></h3><p>To make connections between two machines, we need a Socket connection. A Socket of java.net.Socket class is an object that represents a network connection between two machines. To make a Socket connection, you need to know two things about the server: who it is, and which port it’s running on. In other words, IP address and TCP port number.</p><ol><li>Connect : The client connects to the server by establishing a Socket connection.</li><li>Send : The client sends a message to the server</li><li>Receive : The Client gets a message from the server</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G2yf72KBeaKAoE8ZnkWWEg.png" /></figure><p>A TCP port is a 16-bit number that identifies a specific program on the server. The TCP port numbers from 0 to 1023 are reserved for well-known services. But we can use port numbers between 1024 and 65535 as a chat server.</p><blockquote><strong><em>Read data from a Socket</em></strong></blockquote><p>To communicate over a Socket connection, you use streams. The InputStreamReader class of the java.io package can be used to convert data in bytes into data in characters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ceEjEo3be0VbboXgAJgJUw.png" /></figure><p>1. Make a Socket connection to the server.</p><pre>Socket chatSocket = new Socket(“127.0.0.1”, 5000);</pre><p>2. Make an InputStreamReader chained to the Socket’s low-level input stream.</p><pre>InputStreamReader stream = new InputStreamReader(chatSocket.getInputStream());</pre><p>3. Make a BufferedReader and read.</p><pre>BufferedReader reader = new BufferedReader(stream);<br>String message = reader.readLine();</pre><blockquote><strong><em>Write data to a Socket</em></strong></blockquote><p>The PrintWriter class of the java.io package can be used to write output data in a commonly readable form (text). The client establishes a connection with the server, receives an input stream from it, and reads a message from the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*UAOEJFfeWtAn7zUf9C2xew.png" /></figure><p>1. Make a Socket connection to the server.</p><pre>Socket chatSocket = new Socket(“127.0.0.1”, 5000);</pre><p>2. Make a PrintWriter chained to the Socket’s low-level output stream.</p><pre>PrintWriter writer = new PrintWriter(chatSocket.getOutputStream());</pre><p>3. Write (print) something.</p><pre>writer.println(“message to send”);<br>writer.print(“another message”);</pre><p><strong><em>How it works</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*98a5lfNtP6holyjqZQg_Nw.png" /></figure><p>A thread is a separate thread of execution. This means a separate call stack. A Thread class represents a thread.</p><p><strong><em>How to launch a new thread</em></strong></p><ol><li>Make a Runnable object</li></ol><pre>Runnable threadJob = new MyRunnable();</pre><p>2. Make a Thread object (the worker) and give it Runnable</p><pre>Thread myThread = new Thread(threadJob);</pre><p>3. Start the Thread</p><pre>myThread.start();</pre><p>Runnable is to a Thread means a job is to a worker. A Runnable is the job a thread is supposed to run. A Runnable holds the method that goes on the bottom of the new thread’s stack.</p><p>The thread scheduler decides which thread runs and which doesn’t. It might let one thread run to its heart’s content while the other threads starve.</p><p>Putting a thread to sleep allows other threads to get a chance to run. When the thread wakes up, it always goes back to the runnable state and waits for the thread scheduler to choose it to run again.</p><p>The synchronized keyword means that a thread needs a key in order to access the synchronized code.</p><p>Every Java object has a lock, and it has only one key. Most of the time, the lock is unlocked, and nobody cares. But if an object has synchronized methods, a thread can enter one of the synchronized methods ONLY, if the key for the object’s lock is available. This means, only if another thread hasn’t already grabbed the one key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*g4y4_Ivb0ICVDssevHwDoQ.png" /></figure><p>When a thread attempts to enter a synchronized method, the thread must get the key for the object. If the key is not available when another thread already has it, the thread goes into a kind of waiting lounge, until the key becomes available.</p><p>If an object has more than one synchronized method, there is still only one key. Once any thread has entered a synchronized method on that object, no thread can enter any other synchronized method on the same object. This restriction lets you protect your data by synchronizing any method that manipulates the data.</p><blockquote><strong>Reference</strong></blockquote><p><a href="https://www.rcsdk12.org/cms/lib/NY01001156/Centricity/Domain/4951/Head_First_Java_Second_Edition.pdf">https://www.rcsdk12.org/cms/lib/NY01001156/Centricity/Domain/4951/Head_First_Java_Second_Edition.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eaba4084f77b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chapter 14 — Serialization and file I/O]]></title>
            <link>https://medium.com/@Praveen_Fernando/chapter-14-serialization-and-file-i-o-1bf8a2b5785b?source=rss-56611250a0e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bf8a2b5785b</guid>
            <category><![CDATA[serialization]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Praveen Fernando]]></dc:creator>
            <pubDate>Fri, 15 Jul 2022 20:00:30 GMT</pubDate>
            <atom:updated>2022-07-15T20:00:30.267Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Chapter 14 — Serialization and file I/O</strong></h3><p>serializable objects have the ability to save the state. The serialized file is much harder for humans to read, but it’s much easier (and safer) for your program to restore the three objects from serialization than from reading in the object’s variable values that were saved to a text file.</p><p><strong><em>Writing a serialized object to a file.</em></strong></p><ol><li>Make a FileOutputStream object which knows how to connect to and create a file.</li></ol><pre>FileOutputStream fileStream = new FileOutputStream(“MyGame.ser”);</pre><p>2. Make an ObjectOutputStream that lets you write objects, but it can’t directly connect to a file.</p><pre>ObjectOutputStream os = new ObjectOutputStream(fileStream);</pre><p>3. Write the object.</p><pre>os.writeObject(characterOne);<br>os.writeObject(characterTwo);<br>os.writeObject(characterThree);</pre><p>4. Close the ObjectOutputStream at the top and closes the ones underneath, so the FileOutputStream (and the file) will close automatically.</p><pre>os.close();</pre><blockquote><strong><em>Data moves in streams from one place to another</em></strong></blockquote><p>Connection streams represent a connection to a source or destination like a file, socket, etc. while chain streams can’t connect on their own and must be chained to a connection stream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*bKK7M3iDbQKIEW2aHZUU1w.png" /></figure><p>Objects in the heap have a state and the value of an instance of an object. This makes instances different in the same class.</p><p>Serialized objects save the values of the instance variables so that an identical instance (object) can be brought back to life on the heap.</p><p>When an object is serialized, all the objects it refers to from instance variables are also serialized. And all the objects those objects refer to are serialized.</p><p>Its main purpose is to announce that the class implementing it is, well, serializable. In other words, objects of that type are savable through the serialization mechanism. If any superclass of a class is serializable, the subclass is automatically serializable even if the subclass doesn’t explicitly declare implements Serializable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*keLElNrBnJyQPSKMnHv1-Q.png" /></figure><p>Either the entire object graph is serialized correctly, or serialization fails.</p><blockquote><strong><em>Deserialization</em></strong></blockquote><p>The whole point of serializing an object is so that you can restore it back to its original state at some later date, in a different ‘run’ of the JVM.</p><p>1. Make a FileInputStream</p><pre>FileInputStream fileStream = new FileInputStream(“MyGame.ser”);</pre><p>2. Make an ObjectInputStream</p><pre>ObjectInputStream os = new ObjectInputStream(fileStream);</pre><p>3. Read the objects</p><pre>Object one = os.readObject();<br>Object two = os.readObject();<br>Object three = os.readObject()</pre><p>4. Cast the objects</p><pre>GameCharacter elf = (GameCharacter) one;<br>GameCharacter troll = (GameCharacter) two;<br>GameCharacter magician = (GameCharacter) three;</pre><p>5. Close the ObjectInputStream</p><pre>os.close();</pre><p><strong><em>What happens during deserialization?</em></strong></p><p>Once an object is deserialized, the JVM tries to bring the object back to life by making a new object on the heap that has the same state the serialized object had.</p><ol><li>The object is read from the stream.</li><li>The JVM determines the object’s class type.</li><li>The JVM attempts to find and load the object’s class. If not then JVM throws an exception, and the deserialization fails.</li><li>A new object is given space on the heap</li><li>If the object has a non-serializable class somewhere up its inheritance tree, the constructor for that non-serializable class will run along with any constructors above that. Once the constructor chaining begins, all superclasses which are non-serializable will reinitialize their state.</li><li>The object’s instance variables are given the values from the serialized state.</li></ol><blockquote><strong><em>The java.io.File class</em></strong></blockquote><p>A File object represents the name and path of a file or directory on a disk. But it does NOT represent, or give you access to, the data in the file. We can do below things that we can do with the file object.</p><p>1. Make a File object representing an existing file</p><pre>File f = new File(“MyCode.txt”);</pre><p>2. Make a new directory</p><pre>File dir = new File(“Chapter 14”);<br>dir.mkdir();</pre><p>3. List the contents of a directory</p><pre>if (dir.isDirectory()) {<br>    String[] dirContents = dir.list();<br>    for (int i = 0; i &lt; dirContents.length; i++) {<br>        System.<em>out</em>.println(dirContents[i]);<br>    }<br>}</pre><p>4. Get the absolute path of a file or directory</p><pre>System.out.println(dir.getAbsolutePath());</pre><p>5. Delete a file or directory and return true if successful.</p><pre>boolean isDeleted = f.delete();</pre><p>Reading text files is simple, and we use a File object to represent the file, a FileReader to do the actual reading, and a BufferedReader to make the reading more efficient.</p><p>The String split() method can use to break a String into individual tokens.</p><blockquote><strong>Reference</strong></blockquote><p><a href="https://www.rcsdk12.org/cms/lib/NY01001156/Centricity/Domain/4951/Head_First_Java_Second_Edition.pdf">https://www.rcsdk12.org/cms/lib/NY01001156/Centricity/Domain/4951/Head_First_Java_Second_Edition.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bf8a2b5785b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chapter 13 — Using Swing]]></title>
            <link>https://medium.com/@Praveen_Fernando/chapter-13-using-swing-64b08af8ac27?source=rss-56611250a0e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/64b08af8ac27</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[swing]]></category>
            <dc:creator><![CDATA[Praveen Fernando]]></dc:creator>
            <pubDate>Fri, 15 Jul 2022 14:39:26 GMT</pubDate>
            <atom:updated>2022-07-15T14:39:26.112Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Chapter 13 — Using Swing</strong></h3><p>A widget is technically a Swing Component. Text fields, buttons, scrollable lists, radio buttons, etc. are all components. In fact, they all extend <em>javax.swing.JComponent.</em></p><p>The layout manager controls the components contained within the component the layout manager is associated with. The layout manager of the frame controls the size and placement of the panel.</p><p>The process of laying out a background component:</p><ol><li>Create a panel and add three buttons to it.</li><li>The panel’s layout manager asks each button how big that button prefers to be.</li><li>The panel’s layout manager uses its layout policies to decide whether it should respect all, part, or none of the buttons’ preferences.</li><li>Add the panel to a frame.</li><li>The frame’s layout manager asks the panel how big the panel prefers to be.</li><li>The frame’s layout manager uses its layout policies to decide whether it should respect all, part, or none of the panel’s preferences.</li></ol><blockquote><strong><em>The Big Three layout managers: border, flow, and box.</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*yLeXZNT_TjskLRaYNtUwKg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*_x_OKIQrDvJMYReXeWe6Fw.png" /></figure><blockquote><strong><em>JTextField</em></strong></blockquote><p>Constructors&#39;</p><pre>JTextField field = new JTextField(20);<br>JTextField field = new JTextField(“Your name”);</pre><p>process of using it :</p><ol><li>Get text out of it.</li></ol><pre>System.out.println(field.getText());</pre><p>2. Put text in it.</p><pre>field.setText(“whatever”);<br>field.setText(““); //This clears the field</pre><p>3. Get an ActionEvent Once the user presses return or enter.</p><pre>field.addActionListener(myActionListener);</pre><p>4. Select/Highlight the text in the field.</p><pre>field.selectAll();</pre><p>5. Put the cursor back in the field (so the user can just start typing).</p><pre>field.requestFocus();</pre><blockquote><strong><em>JTextArea</em></strong></blockquote><p>Constructors’</p><pre>JTextArea text = new JTextArea(10,20);</pre><p>process of using it :</p><ol><li>Make it have a vertical scrollbar only.</li></ol><pre>JScrollPane scroller = new JScrollPane(text);</pre><pre>text.setLineWrap(true);//Turn on line wrapping </pre><pre>scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);</pre><pre>scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);</pre><pre>panel.add(scroller);</pre><p>2. Replace the text that’s in it.</p><pre>text.setText(“Not all who are lost are wandering”);</pre><p>3. Append to the text that’s in it.</p><pre>text.append(“button clicked”);</pre><p>4. Select/Highlight the text in the field.</p><pre>ext.selectAll();</pre><p>5. Put the cursor back in the field (so the user can just start typing).</p><pre>text.requestFocus();</pre><p><em>Example</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*WYxq_721QBoF1ryxYQzmxQ.png" /></figure><blockquote><strong><em>JCheckBox</em></strong></blockquote><p>Constructors’</p><pre>JCheckBox check = new JCheckBox(“Goes to 11”);</pre><p>process of using it :</p><ol><li>Listen for an item event (when it’s selected or deselected)</li></ol><pre>check.addItemListener(this);</pre><p>2. Handle the event (and find out whether or not it’s selected)</p><pre>public void itemStateChanged(ItemEvent ev) {<br>    String onOrOff = “off”;<br>    if (check.isSelected()) onOrOff = “on”;<br>    System.<em>out</em>.println(“Check box is “ + onOrOff);<br>}</pre><p>3. Select or deselect it in code</p><pre>check.setSelected(true);<br>check.setSelected(false);</pre><blockquote><strong><em>JList</em></strong></blockquote><p>Constructors’</p><pre>String [] listEntries = {“alpha”, “beta”, “gamma”,“delta”,“epsilon”, “zeta”, “eta”, “theta “};</pre><pre>JList list = new JList(listEntries);</pre><p>process of using it</p><ol><li>Make it have a vertical scrollbar.</li></ol><pre>JScrollPane scroller = new JScrollPane(list);</pre><pre>scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);</pre><pre>scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);</pre><pre>panel.add(scroller);</pre><p>2. Set the number of lines to show before scrolling.</p><pre>list.setVisibleRowCount(4);</pre><p>3. Restrict the user to select only ONE thing at a time.</p><pre>list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);</pre><p>4. Register for list selection events.</p><pre>list.addListSelectionListener(this);;</pre><p>5. Handle events (find out which thing in the list was selected).</p><pre>public void valueChanged(ListSelectionEvent lse) {<br>    if( !lse.getValueIsAdjusting()) {<br>        String selection = (String) list.getSelectedValue();<br>        System.<em>out</em>.println(selection);<br>    }<br>}</pre><blockquote><strong>Reference</strong></blockquote><p><a href="https://www.rcsdk12.org/cms/lib/NY01001156/Centricity/Domain/4951/Head_First_Java_Second_Edition.pdf">https://www.rcsdk12.org/cms/lib/NY01001156/Centricity/Domain/4951/Head_First_Java_Second_Edition.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64b08af8ac27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design patterns for Microservices — Part 3]]></title>
            <link>https://medium.com/@Praveen_Fernando/design-patterns-for-microservices-part-3-3ec9a4a76f5e?source=rss-56611250a0e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ec9a4a76f5e</guid>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Praveen Fernando]]></dc:creator>
            <pubDate>Fri, 15 Jul 2022 11:33:10 GMT</pubDate>
            <atom:updated>2022-07-15T11:33:10.832Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Design patterns for Microservices — Part 3</strong></h3><blockquote><strong><em>Proxy Pattern</em></strong></blockquote><p>Assume your Company has a monolithic application and they decided to move it into a microservices architecture. In that case, your team might be assigned to develop multiple services and deploy those continuously. While developing these microservices, maybe you might do some services that require changes(like updating their functionalities). Updating a particular service can affect the other services, which consume that service. As a result, this might be led to a whole system break, and also it will hold the development of the application. However, we have a well-known solution for this type of situation: The Proxy Design Pattern.</p><p>This pattern is very similar to Aggregator Design Pattern and is even considered a variation of it. But in this case, no aggregation needs to happen on the client, but a different microservice may be invoked based upon the business need. If you have a frequent update service it is better if you deploy the first service with a proxy service. By this, you can independently deploy your service without disturbing to your consumer.</p><p>Semantic versioning is important, and it has major, minor, and patch.</p><ul><li>Major version is you increment when your service is compatible with your previous version.</li><li>Minor when you have new functionality however previous functionality will work and remain as it is.</li><li>Patch version you can increment the way you want.</li></ul><p>When service discovery it is better to use an external party to discover the service for you. When infrastructure changed then all the things inside it can be changed. When implementing proxy patterns, you have to keep eye on thread pools. This can solve by using multiple thread pools or use thread handover mechanism.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ec9a4a76f5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>