Showing posts with label JAVA. Show all posts
Showing posts with label JAVA. Show all posts

Wednesday, January 8, 2020

Setting up Lombok with SpringToolSuite and Intellij Idea

Lombok is a java library that you can plug into your editor which will automatically generate code in .class file instead of in source file.
E.g:  getters, setters toString, equals, hashcode, builder, loggers, and many others.

In this tutorial, I’ll talk about configuring it in two of the most popular IDEs- IntelliJ IDEA and Spring Tool Suite.

Check my Github repo to learn project Lombok using java source code.

Note: Step for installing the plugin for Eclipse and Spring tool Suite (STS) are the same.

Steps to configure Lombok in STS


  • Download Lombok jar from the Lombok site.
  • Double click on Lombok jar which will open below Installer wizard, Choose IDEs in which you want to install. If your not IDE is not listed then you can browse using Specify location tab.

  • Once selected, click on Install/update button and you are done.



Steps to configure Lombok in IntelliJ IDEA

  • Open IntelliJ Idea and click on File-> Settings…
  • Click on Plugin option and then search for Lombok
  • Click on the Install button on the plugin page



  • Once done with the installation, click on the restart IDE button.

Friday, November 1, 2019

SonarQube setup on windows 10

Overview

SonarQube is an automatic code review tool to detect bugs, vulnerabilities and code smell in your code. It can integrate with your existing workflow to enable continuous code inspection across your project branches and pull requests. 

Prerequisite

Make sure you have JAVA 11 or higher version installed on your window machine.


Step to setup SonarQube

  • Download Community edition from https://www.sonarqube.org/downloads/
  • Extract it and go to the bin folder.
  • Choose windows-x86–32 or windows-x86–64 based on your machine configuration.
  • Run StartSonar.bat which will start the SonarQube server. 
  • Open browser and hit http://localhost:9000

  • If you want, you can start the sonarQube server to a different port by just updating the port number (sonar.web.port=9070) to sonar.properties which is present under conf directory.
  • You can login to the portal using default credential (admin:admin).

Congratulation! SonarQube server is up and running on localhost:9000.

Sunday, August 18, 2019

Microservices: Service Registry and Discovery


In my previous blog, I have already talked about Netflix Hystrix Circuit Breaker Microservices and explained it by creating two applications i.e. Product Service and Price Service.
In this post, I’ll use both applications to explain what is the Service Registry and Discovery Server.

What is Service Registry and Discovery and why do we need it in the first place?

In our monolithic application, mostly service invoke one another through language methods or procedure calls and even in traditional distributed system deployment, services run at fixed, well-known locations (hosts and ports) and so can easily call one another using HTTP/REST. Over here the network locations of service instances are relatively static.

With the microservice architecture system, this is a much more difficult problem as service instances have dynamically assigned network locations. Service instances change dynamically because of auto-scaling, failure or upgrade. So, you can see that it’s not possible to hard code the locations (hosts and ports) of service instances in our application.

Apart from that, most of the time we have to deploy the same instance on multiple hosts (E.g. During Big billions day sale where 1000’s of instances is running to support high demand) which will be again a tedious task for the load balancer to register and deregister itself for all these services.
 

What is Service Registry and Discovery?

Service Registry is the server instance where all the service provider register itself when it starts up and deregisters itself when it leaves the system. The service instance’s registration is typically refreshed periodically using a heartbeat mechanism.

Whenever a client has to communicate with other service instances, it has to first query to Service registry to get the network location and then uses a load-balancing algorithm to select one of the available service instances and invoke a request. 

The above instance discovery pattern is called a Client-Side discovery pattern and this can be easily implemented using Netflix Eureka as a Service Registry. It provides a REST API for managing service‑instance registration and for querying available instances.

Netflix also provides Netflix Ribbon which is an IPC client that works with Eureka to load balance requests across the available service instances.


Implementation

As we already have two microservices product-service and price-service and we know product-service is internally invoking price-service to get the price detail of the products. We will do minor changes with these two applications to support service registry.

Discovery Server Implementation

  • Create a spring boot application and Eureka Server starter dependency to your pom.xml file 

  • Add @EnableEurekaServer annotation to Enable Eureka Server.
  • By default, Each Eureka Server is also a Eureka Client which needs at least one service URL to locate service registry. We have to disable this feature as we are creating single node Eureka Server. 
  • Add below properties to application.properties file.

  • Now start the discovery-server application and access http://localhost:8761 which will display the UI similar to below screenshot. 

  • As of now, no application is registered with the Eureka Server. 

2. Registering product-service and price-service to Eureka Clients

  • Let’s make out product-service and price-service as Eureka Client which should register to Eureka Server itself on starts up.
  • Add Eureka Client dependency on both pom.xml files.

  • Configure eureka.client.service-url.defaultZone property in application.properties to automatically register with the Eureka Server. 

  • Now start product-service and price service application and hit http://localhost:8761. We will see product-service and price-service is registered with SERVICE ID as PRODUCT-SERVICE and PRICE-SERVICE respectively. We can also notice the status as UP(1) which means the services are up and running and only one instance of product and price-service are running. 

3. Update hard code URL with application name in product-service and restart the application. 


4. Now open browser and hit product URL and you will get the below response.


Congratulation!!! Our application is perfectly working with Discovery Service. 

Spring-boot microservices can be downloaded from GITHUB

Happy Coding...!!!

Tuesday, April 23, 2019

JAVA 11 – New String methods


JAVA 11 – New String methods

In this blog, we will discuss about all six new methods which got introduced with JDK 11.

  • isBlank(): returns true if string is empty otherwise false. White spaces code will also be considered as empty string.

// Java 8 Predefine Functional Interface
             // The best way to learn JAVA 8 is to implement it wherever you can...
             BiConsumer<String, String> display = (msg1, msg2) -> System.out.println(msg1 + msg2);

             // local variable type inference
             var msg = "Welcome to waheedtechblog page";
             // String msg = "Welcome to waheedtechblog page"; both are same

             // Will return true if string is empty or any white spaces
             if (msg.isBlank()) {
                    display.accept("msg attribute is emty", msg);
             } else {
                    display.accept("1. Hello, ", msg);
             }

String emptyMsg = "";
display.accept("2. Is msg Empty: ", String.valueOf(emptyMsg.isBlank()));

             String whitespacesMsg = "\n\t";
display.accept("2. Is msg empty: ", String.valueOf(whitespacesMsg.isBlank()));
Output:
            1. Hello, Welcome to waheedtechblog page
2. Is msg Empty: true
3. Is msg empty: true

  • lines(): This method returns a stream of lines extracted from the string, separated by line terminators such as \n, \r etc.

            String lineMsg = "Welcome\nto\nwaheedtechblog\npage";
       display.accept("3. Line Msg: \n", lineMsg);
       // line returns streams of line extracted from the String
       List<String> lines = lineMsg.lines().collect(Collectors.toList());
       System.out.println("4. line as list: " + lines);
Output:
       3. Line Msg:
Welcome
to
waheedtechblog
page
4. line as list: [Welcome, to, waheedtechblog, page]

  • repeat(n): This method returns the concatenated string of original string repeated the number of times in the argument.

var repeatMessage = "Welcome";
// returns a new string whose value is the concatenation of this string repeated
             // ‘n’ times.
             display.accept("9. Repeat msg: ", repeatMessage.repeat(5));
Output:
9. Repeat msg: WelcomeWelcomeWelcomeWelcomeWelcome

  • Strip(), StripLeading(),StripTrailing(): These method are used to strip white spaces from the String

                   var stripMsg = "    Welcome to   \t Waheedtechblog page     ";
             display.accept("5. Normal Print: ", "$" + stripMsg + " $");
             // As the name suggests, Strip() methods are used to strip whitespaces from the
             // string.
             display.accept("6. Using Strip(): ", "$" + stripMsg.strip() + "$");
             display.accept("7. Using StripLeading(): ", "$" + stripMsg.stripLeading() + "$");
display.accept("8. Using StripTrailing: ", "$" + stripMsg.stripTrailing() + "$");

Output:
5. Normal Print: $    Welcome to        Waheedtechblog page      $
6. Using Strip(): $Welcome to    Waheedtechblog page$
7. Using StripLeading(): $Welcome to    Waheedtechblog page     $
8. Using StripTrailing: $    Welcome to        Waheedtechblog page$

You can download the source code from my GitHub repository.

Happy Coding…!!!

Sunday, April 21, 2019

Java 10 - Local Variable Type Inference


Java 10 - Local Variable Type Inference

In one of my previous blog, I have already discussed about Type Inference. If you don’t have the idea about Type Inference then you can check my blog here.

If we want to understand Type Inference in one line then we can say that It is the capability of the compiler to automatically detect the datatype of a variable at the compiler time.

What is Local Variable type inference?

Java 10 added new feature that allows the developer to skip the type declaration associated with local variables (those defined inside method definitions, initialization blocks, for-loops, and other blocks like if-else), and the type is inferred by the JDK. It will, then, be the job of the compiler to figure out the datatype of the variable.
Until Java 9, we had to define the type of the local variable.

E.g.: String message = “Welcome to Waheedtechblog.com”;

The above statement is right as that’s how things have been since the inception of java but if you observe, the type of the object at right side is clearing mentioning the type of data that we have defined at left side which makes the variable redundant.
So with Java 10, We can declare a local variable without defining its data type at left side.

            Var message = “Welcome to Waheedtechblog.com”;

Over here, we don’t have to provide the data type of String to local variable message. Compiler will get the datatype based on right hand side value.

Note:
  • This feature is available only for local variables with the initializer. It cannot be used for member variables, method parameters, return types, etc as the initializer is required as without which compiler won’t be able to infer the type.
  • To support backward compatibility, var is not a java reserved keyword. So, we can create variable with name var as it is allowed.

Let’s see where all we can use var

package com.waheedtechblog.typeinference;

import java.util.function.BiConsumer;
import java.util.function.Consumer;

public class TypeInferenceExample {

       static {
             // static block variable
             var staticVaribale = "var in static block";
             Consumer<String> displayOnConsole = msg -> {
                    System.out.println(msg);
             };
             displayOnConsole.accept(staticVaribale);

       }

       public static void main(String[] args) {

             TypeInferenceExample inferenceExample = new TypeInferenceExample();

             BiConsumer<String, String> displayOnConsole = (str, msg) -> {
                    System.out.println(str + msg);
             };

             // Before Java 10
             String message = "Welcome to Waheedtechblog.com";
             displayOnConsole.accept("Before JDK 10: ", message);

             // Using JDK 10, Local Variable
             var message10 = "Welcome to Waheedtechblog.com";
             displayOnConsole.accept("With JDK 10: ", message);

             // local variable declaration in enhanced loops
             String[] countryName = { "India", "Japan", "UAE", "USA", "UK" };
             displayOnConsole.accept("", "List of Country using enhanced loop");
             for (var country : countryName) {
                    displayOnConsole.accept("", country);
             }

             // basic for loop
             displayOnConsole.accept("", "List of Country using basic loop");
             for (var i = 0; i < countryName.length; i++) {
                    displayOnConsole.accept("", countryName[i]);
             }

             displayOnConsole.accept("Length of string '" + message10 + "' is: ",
                           String.valueOf(inferenceExample.getLenth(message10)));


             // var is not keyword, so you can create variable with name var as well.
     String var = "var is not keyword";
     displayOnConsole.accept("", var);
       }

       // can return var type as well
       private int getLenth(String msg) {
             var length = msg.length();
             return length;
       }

}

Output:
var in static block
Before JDK 10: Welcome to Waheedtechblog.com
With JDK 10: Welcome to Waheedtechblog.com
List of Country using enhanced loop
India
Japan
UAE
USA
UK
List of Country using basic loop
India
Japan
UAE
USA
UK
Length of string 'Welcome to Waheedtechblog.com' is: 29
var is not keyword

Illegal use of Var:

1.    Can’t use as a class field
Class Test {
            Var msg; // not allowed as it is local variable inference
}
2.    Local variable without initialization
Private void getOTP(){
            Var otp ; // cant use without initializer
}
3.    Not allowed as parameter for any methods
Private void getOTP(var secretKey){
            //Error, cannot use var on method parameter
}
4.    Not permitted in method return type
Private var getOTP(String secretKey){
            //Error, Method return type cannot be var
}
5.    Not permitted with variable initialized with ‘NULL’
Private String getOTP(String secretKey){
            Var msg = null; Error, cant initialize as null
}

You can download the source code from my GitHub repository.

Happy Coding..!!!









How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...