Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Tuesday, June 14, 2022

Simple Introduction to Web Workers in JavaScript

 JavaScript is an object-based scripting language which is lightweight and cross-platform. It is an interpreted, full-fledged programming language that enables dynamic interactivity on websites when applied to an HTML document.

Even though js had so many advantages, it is having some drawbacks. It is Single threaded language. This means it has one call stack and one memory heap. As expected, it executes code in order and must finish executing a piece code before moving onto the next.

To resolve the above one,we can use Web worker.

A web worker is a JavaScript code that runs in the background and does not influence the page’s performance.

Web Workers are background scripts and they are relatively heavy-weight, and are not intended to be used in large numbers. Although Web Workers cannot block the browser UI, they can still consume CPU cycles and make the system less responsive.

In HTML5 Web Workers are of two types:

Dedicated Web Workers:
The dedicated worker can be accessed by only one script which has called it. The dedicated worker thread end as its parent thread ends. Dedicated workers are only used by one or single main thread.

Shared Web Workers:
It can be shared by multiple scripts and can communicate using the port. Shared workers can be accessed by different windows, iframes or workers.

Common examples of web workers would be:

1)Dashboard pages that display real-time data such as stock prices, real-time active users, and so on
2)Fetching huge files from the server
3)Autosave functionality

You can create a web worker using the following syntax:

const worker = new Worker(".js");

Worker is an API interface that lets you create a thread in the background. We need to pass a parameter, that is a .js file. This specifies the worker file the API needs to execute.

A worker can be shared or used by multiple consumers/scripts. These are called shared workers. The syntax of the shared worker is very similar to that of the above mentioned workers.

const worker = new SharedWorker(".js");

Terminating the Web Worker:
If you want to immediately terminate the currently running worker in the main thread, then you can terminate it by calling the terminate() method of Web Worker. Here is the syntax for web worker termination:

worker.terminate();

Worker Example:

<!DOCTYPE html>  
<html>  
<head>  
  <style>  
    .div1{  
      margin-left: 350px;  
    }  
  </style>  
</head>  
<body>  

<div class="div1">  
  <h2>Example of Web Worker</h2>  
<label>Enter the number to find the square</label>  
<br><input type="text" name="num" id="num"><br>  
<br><button id="submit">Submit</button>  
<button id="other">Wait</button>  
<div id="text"></div>  
</div>  
<script type="text/javascript">  
  
document.getElementById("other").onclick=function() {  
  alert("Hey! Web Worker is working, and you can wait for the result.");  
}  
  
//Web-worker Code
  var worker= new Worker("worker.js");  
  worker.onmessage= function(event){  
  document.getElementById("text").innerText= event.data;}  
  document.getElementById("submit").onclick= function(){  
  var num= document.getElementById("num").value;  
  worker.postMessage(num);  
 }  
</script>  
<p>
</body>  
</html> 
  • var worker= new Worker("worker.js"); To create the web Worker object.
  • worker.onmessage= function(event): It is used to send the message between the main thread and Worker thread.
  • worker.postMessage(num); This is the method used to communicate between the Worker thread and main thread. Using this method Worker thread return the result to the main thread.

Note: Use the below link to test whether your browser is compatible with html5 feature.

http://html5test.com/

Saturday, June 4, 2022

Dependency Tree in Maven

Dependency management is a core feature of Maven. Managing dependencies for a single project is easy.

Managing dependencies for multi-module projects and applications that consist of hundreds of modules is possible.

Maven avoids the need to discover and specify the libraries that your own dependencies require by including transitive dependencies automatically.

This feature is facilitated by reading the project files of your dependencies from the remote repositories specified.

In general, all dependencies of those projects are used in your project, as are any that the project inherits from its parents, or from its dependencies, and so on.

A project's dependency tree can be filtered to locate specific dependencies.

Maven is powered with Dependency plugin by default.With this plugin, we can have a better understanding and control over the list of dependencies used in a specific project.The plugin comes with several goals.

mvn dependency:tree  is the Command

The main purpose of the dependency:tree goal is to display in form of a tree view all the dependencies of a given project.


Monday, August 31, 2020

Introduction to Junit5

 JUnit5 is the next generation of JUnit. The goal is to create an up-to-date foundation for developer-side testing on the JVM. This includes focusing on Java 8 and above, as well as enabling many different styles of testing.

JUnit 5 is split into three sub-projects: Jupiter, Vintage, and Platform.

They communicate via published APIs, which allows tools and libraries to inject customized behavior. Then, each sub-project is split into several artifacts to separate concerns and guarantee maintainability.

JUnit Vintage:

Implements an engine that allows to run tests written in JUnit 3 and 4 with JUnit 5.

JUnit Jupiter is the combination of the new programming model and extension model for writing tests and extensions in JUnit 5. 



Required Dependencies:

The junit-jupiter-api (version 5.4.2):This dependency provides the public API for writing tests and extensions.

The junit-jupiter-engine (version 5.4.2):This dependency contains the implementation of the JUnit Jupiter test engine that runs our unit tests.

Configuring the Maven Surefire Plugin:

build>

    <plugins>

        <plugin>

            <groupId>org.apache.maven.plugins</groupId>

            <artifactId>maven-surefire-plugin</artifactId>

            <version>2.22.1</version>

        </plugin>

    </plugins>

</build>            

Note: First, if we want to use the native JUnit 5 support of the Maven Surefire Plugin, we must ensure that at least one test engine implementation is found from the classpath. 

That’s why we added the junit-jupiter-engine dependency to the test scope.


Mockito

 Mockito is a mocking framework. It is a Java-based library used to create simple and basic test APIs for performing unit testing of Java applications. It can also be used with other frameworks such as JUnit and TestNG.

The framework allows the creation of test double objects (mock objects) in automated unit tests for the purpose of test-driven development (TDD) or behavior-driven development (BDD).

Mockito allows developers to verify the behavior of the system under test (SUT) without establishing expectations beforehand.One of the criticisms of mock objects is that there is a tight coupling of the test code to the system under test.

Benefits of Mockito:

  • No Handwriting − No need to write mock objects on your own.
  • Refactoring Safe − Renaming interface method names or reordering parameters will not break the test code as Mocks are created at runtime.
  • Return value support − Supports return values.
  • Exception support − Supports exceptions.
  • Order check support − Supports check on order of method calls.
  • Annotation support − Supports creating mocks using annotation.

Following are the mock() methods with different parameters:

mock() method with Class: It is used to create mock objects of a concrete class or an interface. It takes a class or an interface name as a parameter.
Syntax: <T> mock(Class<T> classToMock)

mock() method with Answer: It is used to create mock objects of a class or interface with a specific procedure. It is an advanced mock method, which can be used when working with legacy systems. It takes Answer as a parameter along with the class or interface name. The Answer is an enumeration of pre-configured mock answers.
Syntax: <T> mock(Class<T> classToMock, Answer defaultAnswer)

mock() method with MockSettings: It is used to create mock objects with some non-standard settings. It takes MockSettings as an additional setting parameter along with the class or interface name. MockSettings allows the creation of mock objects with additional settings.
Syntax: <T> mock(Class<T> classToMock, MockSettings mockSettings)

mock() method with ReturnValues: It allows the creation of mock objects of a given class or interface. Now, it is deprecated, as ReturnValues are replaced with Answer.
Syntax: <T> mock(Class<T> classToMock, ReturnValues returnValues)

mock() method with String: It is used to create mock objects by specifying the mock names. In debugging, naming mock objects can be helpful whereas, it is a bad choice using with large and complex code.
Syntax: <T> mock(Class<T> classToMock, String name)


Monday, August 10, 2020

Jdbc Connection Pool

 A JDBC connection pool is a group of reusable connections for a particular database. 

Because creating each new physical connection is time consuming, the server maintains a pool of available connections to increase performance.

 When an application requests a connection, it obtains one from the pool. When an application closes a connection, the connection is returned to the pool.

When creating a connection pool , you are actually defining the aspects of a connection to a specific database. Before creating the pool, you must first install and integrate the JDBC driver. 

The properties of connection pools can vary with different database vendors.

  1. Some common properties are the database’s name (URL), user name, and password.
  2. Certain data specific to the JDBC driver and the database vendor must be entered. Before proceeding, gather the following information:
  3. Database vendor name
  4. Resource type, such as javax.sql.DataSource (local transactions only) javax.sql.XADataSource (global transactions)
  5. Data source class name: If the JDBC driver has a Datasource class for the resource type and database, then the value of the Datasource Classname field is required.
  6. Required properties, such as the database name (URL), user name, and password

A JDBC connection pool is a group of reusable connections for a particular database. When creating the pool with the Administration Console, the Administrator is actually defining the aspects of a connection to a specific database.

Before creating the pool, you must first install and integrate the JDBC driver. When building the Create Connection Pool pages, certain data specific to the JDBC driver and the database vendor must be entered. 

Before proceeding, gather the following information:

  1. Database vendor name
  2. Resource type, such as javax.sql.DataSource (local transactions only) javax.sql.XADataSource (global transactions)
  3. Data source class name
  4. Required properties, such as the database name (URL), user name, and password

Connection Pool Libraries considered for analysis:

1) Apache Commons DBCP2:
  • Easy to configure. Very detailed configuration page.
  • Supports prepared statement caching
  • Does not validate connections on borrow
  • Does not reset transaction isolation when returns to the pool
  • Does not reset the read-only status of the connection
  • Does not reset the auto-commit status of the connection
  • Does not clear SQL warnings
  • DBCP2 compiles and runs under Java 7 only (JDBC 4.1), not sure if it runs on Java 8
  • More than 60 classes in the library
  • Does not validate connections on borrow
  • The code is hosted on GitHub https://github.com/apache/commons-dbcp. The repository has 21 contributors and only 2 contributions in the year 2017. A lot of broken links on the home page, java doc links are broken.
  • I logged into Apache Bugtracker (JIRA) to check for the number of bugs, there are 11 open and reopened bugs.
  • Licensed under Apache 2.0
2)C3P0:
C3P0 is one of the oldest and best-known libraries. It is very well documented. However, according to some reports, it’s easy to misconfigure the pool and can result in poor performance and deadlocks.
  • It comes in a package with hibernate.
  • Works well in the heavy concurrent environment.
  • Supports prepared statement pooling
  • Resets auto commit status when returning to the pool
  • Resets read the only status when returning to the pool
  • Resets isolation level when returning to the pool
  • Does not test connections at getConnection()
  • Around 200 classes in the library. Huge code base compared to others.
  • The code is hosted on Github -> Repository, the library has 5 contributors with 5 contributions to the code this year, 4th May had the last check-in.
  • Issues are tracked on Github tracker and have 41 issues listed.
  • The library is licensed under LGPL v.2.1 and EPL v.1.0
3)Tomcat JDBC:
  • Supports highly concurrent environments and multi-core/CPU systems.
  • It is very well documented here.
  • Async connection retrieval. Can queue connection requests and return Future back.
  • Ability to configure custom interceptors to enhance functionality.
  • It provides multiple ways to configure the pool. One is inside the Apache container, JMX and standalone by using DataSource bean.
  • It does not by default reset auto-commit and transaction levels for connections in the pool, users must configure custom interceptors to do this.
  • Does not by default test connections on getConnection()
  • It does not close abandoned open statements.
  • Pool prepared statement properties are not used.
  • The code is hosted on GitHub. It has 13 active contributors.
  • This is a very active community, one can see looking at the commits and bug list.
  • licensed under Apache 2.0
4) HikariCP:
  • Very light library, around 130 kb.
  • Tests connections at getConnection()
  • Tracks and closes abandoned connections.
  • Clears connections before returning the connection to the client.
  • Resets auto-commit, transaction isolation, read-only status
  • The library has 58 active contributors and has a very detailed configuration page with performance benchmarks.
  • The library has 33 issues listed on GitHub
  • Licensed under Apache 2.0

Monday, August 3, 2020

Introduction to Quartz Scheduler

Quartz is a job scheduling library that can be integrated into a wide variety of Java applications.
Quartz is generally used for enterprise class applications to support process workflow, system management actions and to provide timely services within the applications.
You can create complex schedules for executing any job. Examples are e.g. tasks that run daily, every other Monday 8:30 p.m. or only on the last day of every month. 

You can download Quartz from http://quartz-scheduler.org/downloads

Components:
============
Quartz job:
Quartz job is used for the logic or code which you want to execute. It implements org.quartz.Job interface.

Quartz trigger:
Quartz trigger is used to define the moment when the quartz scheduler will execute quartz’s job.

Types of quartz trigger:
1. SimpleTrigger – SimpleTrigger setting start time, end time, repeat count and repeat interval for quartz’s job.
2.CronTrigger – CronTrigger uses cron expressions to specify the moment when to execute quartz’s job.
 A cron expression is made up of seven sub expressions:
Seconds
Minutes
Hours
Day-of-Month
Month
Day-of-Week
Year (optional field)
3. Scheduler class – Scheduler class is used to connect the quartz job and quartz trigger together and execute the job.
4.JobListener:
JobListener provides the facility to track the status of running jobs. To write a JobListener we have to implements the JobListener interface.

Quartz API:
===========
The key interfaces of the API are:
Scheduler – the primary API for interacting with the scheduler of the framework
Job – an interface to be implemented by components that we wish to have executed
JobDetail – used to define instances of Jobs
Trigger – a component that determines the schedule upon which a given Job will be performed
JobBuilder – used to build JobDetail instances, which define instances of Jobs
TriggerBuilder – used to build Trigger instances




Wednesday, July 29, 2020

Multi-Module Project using Maven

A Spring Boot project that contains nested maven projects is called the multi-module project.

In the multi-module project, the parent project works as a container for base maven configurations.A multi-module project is defined by a parent POM referencing one or more submodules.

The parent maven project must contain the packaging type pom that makes the project as an aggregator. 

The pom.xml file of the parent project consists the list of all modules, common dependencies, and properties that are inherited by the child projects. The parent pom is located in the project's root directory. The child modules are actual Spring Boot projects that inherit the maven properties from the parent project.

Benefits of Using Multi-Modules:
The significant advantage of using this approach is that we may reduce duplication.
Let's say we have an application which consists of several modules, let it be a front-end module and a back-end module.
 
Now, we work on both of them and change functionality which affects the two. In that case, without a specialized build tool, we'll have to build both components separately or write a script which would compile the code, run tests and show the results.

Then, after we get even more modules in the project, it will become harder to manage and maintain.
Besides, in the real world, projects may need certain Maven plugins to perform various operations during build lifecycle, share dependencies and profiles or include other BOM projects.

Therefore, when leveraging multi-modules, we can build our application's modules in a single command and if the order matters, Maven will figure this out for us. Also, we can share a vast amount of configuration with other modules.

Parent POM:
Maven supports inheritance in a way that each pom.xml file has the implicit parent POM, it's called Super POM and can be located in the Maven binaries.
These two files are merged by Maven and form the Effective POM.


ES12 new Features