Skip to main content

Posts

Showing posts with the label java

WebAssembly vs Java Applets

A Detailed Comparison: WebAssembly vs. Java Applets WebAssembly and Java Applets are technologies aimed at enhancing web applications by enabling execution of code directly in the browser. However, they have significant differences in terms of architecture, performance, security, and modern web development practices. Let's compare these two technologies in-depth, along with scenarios and code samples. WebAssembly Architecture: WebAssembly is a binary instruction format that allows high-level languages to be compiled into a low-level bytecode that can run efficiently in browsers. It provides a secure sandboxed environment where code can execute without direct access to browser internals. WebAssembly modules can be integrated into web applications, enabling performance-critical components to run faster than JavaScript. Performance: WebAssembly code can achieve near-native performance, making it suitable for applications requiring complex computations or real-time interacti

Using Spring Cloud Config Server for Multi-tenancy configuration

Let's walk through a basic example of how to set up and use Spring Cloud Config Server to manage configuration for multiple tenants in a Spring Boot Application. Step 1: Create a Spring Cloud Config Server Create a new Spring Boot project with the Spring Cloud Config Server dependency. <!-- pom.xml --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency> Configure the Spring Cloud Config Server: // src/main/java/com/example/ConfigServerApplication.java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.config.server.EnableConfigServer; @SpringBootApplication @EnableConfigServer public class ConfigServerApplication { public static void main(String[] args) { SpringApplication.run(ConfigServerApplication.class, args); } } Configure the appl

Using Apache Avro for Efficient Data Serialization

Introduction In the world of software development, efficient data serialization plays a crucial role in enabling smooth communication between different components, systems, and applications. One popular technology that addresses the challenges of data serialization is Apache Avro. Avro is a powerful and versatile framework that offers a compact and efficient way to serialize data, making it an ideal choice for various scenarios. In this article, we will explore the need for efficient data serialization, the problems it helps us solve, and how to use Apache Avro with Java, using a "Product" entity as an example. The Need for Efficient Data Serialization Modern software systems are often composed of multiple components running on different platforms and communicating over various protocols. This communication involves sending data between these components, which can be in different formats and structures. Data serialization is the process of converting complex data str

Upgrade from http1.1 to http2 for Java spring boot applications hosted in tomcat

In this post, we will list down the tasks to be done for enabling the HTTP 2.0 support in spring boot applications which are hosted in Apache tomcat webserver Application Level Changes Spring boot Application Configuration Changes server.http2.enabled=true In the spring boot application's application.properties file, we have to add the above line so that Spring boot can add the support for http2 Tomcat server configuration In the tomcat web server, we should have SSL enabled before doing the below change. To start with, we have to shutdown the tomcat server instance that is running CD to the directory that has tomcat installed and cd to the bin directory and run the below command sh shutdown.sh We have add the UpgradeProtocol  which adds the respective Http2Protocol handler classname to the connector pipeline that enables support for http2.0 <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" /> The above UpgradeProtocol can be added to the connec

Jsonview in Spring boot

Introduction There are scenarios where we have a DTO or a model class that contains a collection of properties and there might be some endpoints that require a subset of them and some other endpoint that might need all of them. Example: Consider a scenario where we need a list of Categories in a dropdown and we have an API that gets all the categories from the static masterdata and need to send to the UI in response to an API call. Problem Statement  We might choose to use a `Map` data type so that we send out the key-value pairs to the database or to choose to build a custom DTO with only the Id, name of the categories. In a longer run, if we opt to use multiple DTO in the source, sooner there will be a very large collection of DTO classes that represent subset of a static data. Solution Rather than ending up with a large number of such DTO classes, we can use a JSON View. This helps us have a single class and control which fields are part of which view.  Example: We can have a dropd

Handling exceptions in the Executor service threads in Java

Introduction This is a continuation post on the exception handling strategies in the threads in Java. For Introduction, please read this post The second post is available here This post addresses the problem statement "How to use the exception handlers in the threads spawned by the Executor Service in Java?" Not all times, we will be using Thread  classes to run our threads because we have to manage a lot of the underlying logic for managing threads. There is ExecutorService in Java which comes to the rescue for the above problem. In the previous posts, we have discussed on how to handle the exceptions in plain threads. However, when using executor service, we do not create / manage threads, so how do we handle exception in this case. We have a ThreadFactory   as an argument which can be used to customize the way threads are created for use within the ExecutorService . The below snippet of code leverages this feature to illustrate the exception handling, wherein we create a

Handling exceptions at thread level in Java

Introduction This is a continuation to the post on exception handling on threads. For those interested in the background, please visit this link This post discusses on the topic "Can I use separate exception handlers for threads performing mission critical tasks vs non trivial tasks?" Per-Thread Exception Handler Let's us assume that we built a handler that wants to notify the support team that something has gone wrong in some special thread processing, like the one below (not really notifying anyone but helps correlate the context) class SupportNotificationExceptionHandler implements Thread . UncaughtExceptionHandler { @Override public void uncaughtException ( Thread t, Throwable e) { notifySupport (t, e); } private void notifySupport ( Thread t, Throwable e) { System . out . println ( "Notified support team on: " + e. getMessage () + " raised from : " + t. getName ()); } } Let us now apply the above special handle

Handling Exceptions in Threads in Java

Introduction Exception handling is very critical to any application and any language that was used to develop. This helps the following stakeholders Stakeholders End-User: A graceful message that indicates that something has gone wrong in the system due to some wrong input or due to some internal fault Developer A clean way to get to know which line of code caused the exception and the stack trace that can help us reach to the points impacted Support Team A helpful hint that they can try to verify and resolve if it is something within their reach or to escalate to the product team SRE (Site Reliability Engineering) An indication of how far the application is performing w.r.to being reliable to the end-users and how faults are handled or tolerated etc.. Problem Statement When we use threads to get the job done for performing some intensive task (computation or Network intensive tasks), it becomes difficult to track down on the exceptions. This post is one in a series of posts that will

reified type in Kotlin

Introduction In Java, we have a type erasure problem where the runtime will not be able to preserve the type of the generic type that was intended and that will result in many times we having to pass the name of the class like Class<clz> ..  to provide the context information to perform the operations in generics. Type Erasure fun < T > getOnlyInts ( list : List < Any >): MutableList < T > { var result : MutableList < T > = mutableListOf () for ( item in list ) if ( item is T ) { result .add( item ) } return result } The above snippet of code illustrates the problem of type erasure where the type information for T is lost at runtime. this results in the type check failure in the line item is T Since the type data is erased , the runtime cannot figure out if it is performing the right type check. Hence the compilation fails. reiefied In Kotlin, we have the reified types which helps us to preserve the type information

sequences in Kotlin

Introduction Sequences in Kotlin are similar to that of the stream s in Java, where in the evaluation happens lazily and the volume of data processed in each step in the chain are reducing based on the met criteria. Sample Let us consider the below given sample data class data class Car ( val model : String , val year : Int ) We can create a collection of cars so that we can evaluate both and understand the difference between collections and sequence   in Kotlin var cars = listOf ( Car ( "Toyota" , 2021), Car ( model = "Tesla-S" , 2022), Car ( "Mercedes - Maybach" , 2022) ) Sequence In the below given snippet of code, we are performing the filtering of cars by name and then printing the year println ( cars . asSequence (). filter { it . model == "Toyota" } . map { it . year } This produces the output as given below kotlin.sequences.TransformingSequence@b97c004a This is because the sequence is lazy and is not evaluated as there is

Extension Functions in Kotlin

Introduction Extension functions help us a lot when implementing re-usable code. In many cases where we are required to provide re-usable code, but unable to add the function to the class may be because it was from a 3rd party library or from an external module, we end up adding a pile of helpers in getting the job done. In Java, this feature is not supported unlike in C# and other languages. The drawback of this is we have to create a helper class and create static methods which are not tied to the types. This results in helper classes being used and is not more readable than having the method as an extension or part of the type. data class RationalNumber( val numerator: Int , val denominator: Int ) fun Int.r(): RationalNumber = RationalNumber( this , 1 ) fun Pair< Int , Int >.r(): RationalNumber = RationalNumber( this .first, this .second) The above snippet explains the use of extension functions  which help us in extending the Integer and the Pair Types. After building t

Renaming types on Import

The following snippet of code illustrates how the rename functionality works in Kotlin after importing a type. import kotlin.random.Random as KRandom import java.util.Random as JRandom fun useDifferentRandomClasses(): String {     return "Kotlin random: " +             KRandom.nextInt( 2 ) +             " Java random:" +             JRandom().nextInt( 2 ) +             "." } In the above snippet of code, we see that we are importing two Random types. We are able to use KRandom for the type imported from Kotlin and JRandom for the type imported from java.util.Random

Kotlin Data Classes and Smart Casts

Introduction Kotlin is a language that is built by the Jetbrains team and opensource contributors. The following are the goals that this language helps us achieve (not full set, for more details please visit kotlinlang.org Modern, concise and safe programming language A productive way to write server‑side applications (still using the frameworks that target JVM) Cross-platform layer for native applications Big, friendly and helpful community Kotlin Data Classes Below I am giving some of the kotlin snippets and short descriptions on what they can perform. Keep in mind that kotlin achieves very concise code data class Person ( val name: String , val age: Int ){     } fun getPeople(): List <Person> {     return listOf(Person( "Alice" , 29 ), Person( "Bob" , 31 )) } fun comparePeople(): Boolean {     val p1 = Person( "Alice" , 29 )     val p2 = Person( "Alice" , 29 )     return p1 == p2   // should be true } In the snippet above, we

How to implement Global Exception Handler in Spring Boot

Exception Handling There is always a requirement to handle all the NFR (Non-Functional Requirements) well in any application so that the application performs well in production and possess the excellent traceability and exception reporting mechanisms for better visibility on what happens in applications. Types of Exceptions We normally use exceptions within each domain of the application like Customers, Orders, Inventory etc. There are also a lot of custom exceptions that might be required when the application is built to capture, report the exceptions to the user. In this process, we can follow the below given process Base Exceptions There are multiple use-cases where we need separate exceptions to report multiple error conditions or cases, let us consider one such case for data validation. BaseValidationException import java.util.List; public class BaseValidationException extends RuntimeException { public BaseValidationException() { super(); } public BaseVali

Helpful functions from org apache commons collections

Introduction There are times when we are faced with the option to get the intersection of 2 lists. The type of list can be either a simple type like number / strings or a complex type like Object. This might involve developers building loops and performing comparison. This can be resulting in not following the DRY principle where we do not have to repeat ourselves what is already implemented. We can leverage the functionality provided in the collections4 library which can help us get the desired result. In this example, let us consider the following example.  Sample Scenario We can consider a "Cart" store which keeps track of the various items that we have added the cart. Every addition or deletion of the item to the cart needs to be updated. User's normally add some items and when they find out that their product of interest has its availability, they would want to add that to the cart and balance out by removing a lesser priority item. Now, when the user proceeds for th

How to design a method

Introduction We have been reading articles about how to architect / design a system, microservices etc. However, I still find that there are developers that require some details on how to write / create a method. These are valid for statically typed languages like C# , Java which I have worked. though some of them apply to Javascript as a good practice. Below are some of the points that I consider worth noting The method should have a descriptive verb of the action that it is performing. ReadFromConfigurationFile SaveUserData CheckInOrderPriorToPayment 2. The arguments if any to the method should be validated prior to consumption. There are some built-in types in Java that helps in checking for nulls like  requireNonNull  from  java.util Note:  The below given method is one that i had built which checks for null and empty value and if so, throws suitable exceptions. We have been using similar built-in functionality in  Microsoft Enterprise Library  for .Net as  Guard.Null  or  Guard.Nu