fbpx

Best ways to run spring boot app via command line

We can easily build spring boot application using mvn spring-boot:run and run spring boot app via command line . Assuming you have already created a simple spring boot app, here are the next steps you need to follow to run spring boot app .

Add Maven Plugin in Your Spring Boot Project

In order to run your spring boot app , we need to add spring-boot-maven-plugin in your project parent pom.xml. Open your project pom.xml and add the following line inside it . In most of the cases it will be present already .

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

Running Spring boot apps as Jar from Command line

In order to run your spring boot app as jar we need to first build our application . Navigate to your project folder and run the following command to build your app.

mvn clean install 

Now that your project is build successfully , navigate to target directory and locate your spring boot app jar . You jar file name would be something like webapp-1.0.0SNAPSHOT.jar where webapp is the artifactid . Now issue the following command

java -jar webapp-1.0.0.SNAPSHOT.jar 

Running Spring boot based app with profiling enabled

We can also do profiling in our spring boot based app and run the jar in linux . Have a look at How We can enable Profiling in spring boot app.

java -jar -Dspring.profiles.active=dev webapp-1.0.0.SNAPSHOT.jar 

We can also set server port in spring boot app from command line using following command

java -jar -Dspring.profiles.active=dev -Dserver.port=9090 webapp-1.0.0.SNAPSHOT.jar  

Running Spring boot app via command line using maven

Now , I personally really love this command here , reason is it proved to me as Mr Dependable for me . I was getting a some weired issue like my tomcat used to stop without showing any error . I used to use this command and it used to show me the exact error in debug mode .

I was basically having issue in autowiring and i disabled my debug mode by mistake . I found that this actually runs in debug mode for me .

mvn spring-boot:run

This command line run will also be beneficial when you’re using spring-boot-dev-tool with auto reload/restart when you have changed you application.

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-devtools</artifactId>
 <optional>true</optional>
</dependency>

How to Run spring Boot App Using Gradle

If you are using gradle as your build tool to build spring boot app , you can try following code to run spring boot app using gradle

./gradle bootRun

How to provide hot fix in spring boot apps

lets take an example where we want to provide hot-fix in spring boot apps . Let’s say we missed a logic in one of our classes and now we have fixed , but deployment and build takes time .

In those scenarios if you have a spring boot app packaged as jar . We need to follow these steps .

  1. Extract the Jar using following command
Jar -xvf webapp-1.0.0.SNAPSHOT.jar

2.Once you extract the jar you will find following structure

spring boot extract jar

Now , you can update your hotfix class file directly , most of the compiled classes are present inside BOOT-INF/classess including your application.properties.

Now you can run following command in spring boot to run this extracted spring boot jar .

java -Dspring.profiles.active=dev -Xdebug -Xnoagent -Djava.compiler=NONE org.springframework.boot.loader.JarLauncher 

Notice we mention profiles as well, if you are not sure . Learn how can you profile your spring boot apps.

These were the top best ways you can run spring boot app from command line .

Have a look at other tutorials on Spring :-

Configure SSL Spring Boot 2

Learn Spring Security

Best 5 Ways to Use Spread Operator In JavaScript

Understand Spread Operator In JavaScript with example . We are also going to find out How to Deep Copy objects In Modern JavaScript , We will also check How Spread Operator doesn’t deep copy the Properties and what should we do if we want to deep copy object properties in JavaScript .

Did you noticed {...} in any of your code ? This interesting dots in JavaScript  is known as spread operator . In this post we are going to demystify this special syntax in JavaScript world .

What is Spread Operator In JavaScript

Spread operator is one of the most interesting featured added in JavaScript in recent days. As the name Suggests Spread , so it basically spreads or expands the value of an iterable object in JavaScript.

Have a look at the definition of Spread Operator from Mozilla Doc .

There are multiple scenarios where spread operator comes to the rescue while doing development . We will be having a look at all those use cases here

Examples of Using Spread Operator With JavaScript

  1. Merging Objects .
  2. Merging or Copying Arrays .
  3. Converting String to Array .
  4. Deep Copy Using Spread Operator In JavaScript .

How To Merge Two Objects ?

We have two objects and we are going to using spread operator on both the object literals and construct a new merged object , with contents of both the objects .

let employee = { name:'Frugalis',lastname:'Minds'};
const salary = { grade: 'A', basic: '$2900' };
const summary = {...employee, ...salary};

Now Once you try running this , the result is a merged object literals here achieved in a pretty simple way using this amazing JavaScript feature

Here employee and salary objects are merged together and that produces a new object with merged key value pairs .

Now lets say we have some common key in both the objects , How would spread operator behave in that case .

let’s have a look

let employee = { name:'Frugalis',lastname:'Minds'};
 const salary = { name: 'A', basic: '$2900' };
 const summary = {…employee, …salary};
Spread Operator Javascript Merged Object

Note:- In all cases of merging objects wheather multiple or single . Always the last object will be replaced in all scenarios .

With the above scenario we can also use Object.assign{} to achieve the same result but with Spread operator its more easier and convenient .

Converting String to Array

Considering one of the very common use case and simple one to demonstrate an example of Spread operator in JavaScript world .

let data= "spring"
  // Without spread operator
 console.log(…data);

We have converted a plain simple string to an array using Spread operator .

Merging Or Copying Arrays Using Spread Operator

Now lets say we have a two different array of String or any other array . We can use spread operator on arrays to merge two arrays together like below

Have a look at the array below

let javaTech= ['spring', 'java'];
 console.log(javaTech); // Without spread operator
 console.log(…javaTech);

We are expanding this whole iterator of array into single piece of object . If you notice we do not get array anywhere in content. We actually get the items of the array in plain text format.

Now lets say we merge a two different set of arrays here . Lets See how Spread operator works in that case .

let techlist1= ['spring', 'java'];
 let techlist2= ['javascript', 'nodejs', 'mongo'];
 let fullstacklist= […techlist1, …techlist2];
 console.log(fullstacklist);

Here You have seen the Spread operator merges the two arrays techlist1 and techlist2 .

Resultant is a list of String which is retrieved out of the array and assigned into a new array using [] syntax .

In all of the above cases, we have seen the copying of array is done similar to what we used to do using object.assign{} .

All the above spread operator examples in JavaScript are doing a shallow copy , what if i need my spread operator to do a deep copy of nested objects .

Deep Copy Using Spread Operator In JavaScript

So I was providing some question’s answer on Stack Overflow, and found that Spread Operator doesn’t exactly do deep copy .

That led to me long debugging sessions for the Spread Operator and I will share my observations on Spread Operator and Deep Copy using spread operator in my JavaScript code.

Problem Statement – 

So problem was, I wanted to deep copy the JavaScript Object let’s say –

 let fruglise = {
 type : “Code”,
 code : 123
 }
 

So whenever we use a spread operator (written as …) for copying the object, I thought it does in a way of deep copy thing like – 

let copyObject = {...fruglise}
So whenever we change the properties of the “copyObject” ( copyObject.code = 36 ) it will not change the properties of the original object.

Spread operator deep copy example

Here you could see, in the above code snippet. We have changed the property of the “copyObject” but didn’t reflect on the original object.

But Let’s see different magic example ,

let randomExample = {a : 123, b: {c : 23}}
let copyRandomExample = {...randomExample}

What if we’ll do –

copyRandomExample.b.c = 1000

Guess What ? It will change the properties of the Original Object, Have look –

Well why so ?

Because it (Spread Operator) does till the first level, whenever it finds the nested level, it doesn’t do the Deep Copy. It does the Shallow Copy of the Object from next level onwards .

In summary Spread Operator (written as …) does the Shallow Copy(for first level it does but for others it doesn’t). 

How to Deep Copy Objects in JavaScript – 
Well if you want to the Deep Copy of the Object you could Use JSON.parse(JSON.stringify(object).But it will not work for the non-Json object just like if the Object values are function().

spread operator deep copy

If one needs full proof of Deep Copy then one could use lodash’s clone Copy.

Points to Remember for interview :-

  1. Spread operator in JavaScript does not Perform Deep Copy Of Objects
  2. You Can use Spread operators as an arguments in iterator objects in javascript .

Builder Design Pattern

What is Builder Design Pattern ? Why we should care about it ?

Starting from Creational Design Pattern, so wikipedia says “creational design pattern are design pattern that deals with object creation mechanism, trying to create objects in manner that is suitable to the situation”.


The basic form of object creations could result in design problems and result in complex design problems, so to overcome this problem Creational Design Pattern somehow allows you to create the object.

Builder is one of the Creational Design Pattern.

When to consider the Builder Design Pattern ?

Builder is useful when you need to do lot of things to build an Object. Let’s imagine DOM (Document Object Model), so if we need to create the DOM, We could have to do lot of things, appending plenty of nodes and attaching attributes to them. We could also imagine about the huge XML Object creation where we will have to do lot of work to create the Object. A Factory is used basically when we could create the entire object in one shot.

As Joshua Bloch (He led the Design of the many library Java Collections Framework and many more) – “Builder Pattern is good choice when designing the class whose constructor or static factories would have more than handful of parameters

While considering the pattern you need to look whether Object is having –

1. Complex Constructor : Multiple constructor having multiple parameters with nested Object. Let’s say you love Pizza (PS : I Love Burger ) . We might have encountered time in where we need customise Object(pizza).

This is called Telescoping Constructor Pattern and problem with this is once constructor have more than 4-5 arguments it is hard to remember the order of parameters. (Although some IDE solves this problems)

One alternative to this problem is we could use JAVABean Pattern where you call constructor with required argument and use setter afterwards –

The Problem is with that Object is created on several calls, it may be in inconsistent state partway through its construction.

2. Large Number of Parameter – Having large number of parameters is also key point to consider.

3. Immutability – You could force the immutability to the object once it is done.

Let’s see any example and learn how to implement the builder pattern :

Things are simple when we have 4-5 parameters but eventually becomes messy when we have more than this.

Convert to Builder Pattern : Let’s now add extra fields to the to the POJO and convert it into Builder Design. Create the static anonymous inner class name Builder to the POJO, why static because we want to return or use the current object. Add same fields of POJO and setter of each field with return type of Builder Class. Lastly add the build() method which will return the Object of our POJO.

The resulting builder create code:

Pros :

  1. Code is more readable and maintainable if number of property are more than 4-5 in class.
  2. You can force the Immutability to the Object by not creating the setter() in POJO and only allowing the getter() in POJO.
  3. Robustness to the code as fully constructed object will be available always.

Cons :

  1. It increases the code duplication in the class well it can be improved with library like Project Lombok.

So How was your Pizza, Keep Building, Keep Coding.

Connect with us at LinkedIn –


Binary Search : Extra Care

So you might be aware of the algorithm of Binary Search, simple one right. But there is simple bug lies in Binary Search if we don’t care at all while writing the codes and most of the beginner does same. Here is Java Edition of Algorithm –

So what’s Bug Here or do you think everything is okay here? The Bug is in the line

In Programming Pearls Bentley says that the analogous line “sets m to the average of l and u, truncated down to the nearest integer.” On the face of it, this assertion might appear correct, but it fails for large values of the int variables low and high. Specifically, it fails if the sum of low and high is greater than the maximum positive int value (231 – 1). The sum overflows to a negative value, and the value stays negative when divided by two. In C this causes an array index out of bounds with unpredictable results. In Java, it throws ArrayIndexOutOfBoundsException.

This bug can manifest itself for search space is 230 or greater (roughly a billion elements). 

So what’s best way to fix the Bug? Here’s the one way manually add half the range to the low number:

Do you know how this works,
Calculation without adjustment would’ve been like 5 + 10 = 15 -> 15/2 = 7.5
here, sum can cause overflow but not subtraction.
5 + (10-5)/2 == 5 + 5/2 == 5 + 2.5 == 7.5 . We calculate the average difference instead of actual average and add it to smaller number to get same results.

Second way to fix this is using logical bit shifting.

Where >>> is logical right shift operator.

Reason this works is, logical bit shift unlike arithmetic shift considers sign bit also in shift operation. When overflow happens addition operation sets sign-bit to store result. This is still valid summation but interpreting it as signed int will have wrong results.
eg,
1111 unsigned represents 31
signed represents – 15
Also as we know right shift bit operation is equivalent to dividing by 2.
So, shift considering the extra bit results,
0111. ie, 15.

Happy Exploring and Happy Coding…

Connect with us at LinkedIn –


Using Custom Authentication Provider Spring Security

Custom Auth Provider Spring Security

In this post we are going to find out why we need Custom Authentication Provider in Spring Security . Why do we need to implement this .

If You have  followed previous post about Flow of Authentication in Spring Security .

Spring Security has several areas where patterns you have defined are tested against incoming requests in order to decide how the request should be handled.

How Authentication Provider Flow Start :-

This occurs when the FilterChainProxy decides which filter chain a request should be passed through and also when the FilterSecurityInterceptor decides which security constraints apply to a request.

Once it reaches the right authentication filter based on the authentication mechanism used ,  it extract the given credentials  from the request and then using the supplied values it creates the authentication object.

The it calls 'authenticate' method of the AuthenticationManager.

Now once Authentication manager tries to authenticate the request it  passes through the authentication providers to authenticate the user.

All the Authentication Providers inside spring security framework implement this interface .

Have a look at the Authentication Provider interface below :-

package org.springframework.security.authentication;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

public interface AuthenticationProvider {
	Authentication authenticate(Authentication authentication)
			throws AuthenticationException;

	boolean supports(Class<?> authentication);
}

Now As you know for Writing a Custom Authentication provider in Spring Security , you basically should create your own implementation .

But Wait , Lets find out Why do we need a Custom Authentication Provider in Your Spring based applications by example .

Use Cases where we Need Custom Authentication Provider :-

Lets say you are using authentication services provided by some third party in the form of Jar or an API.

In that case you can use the Spring Security Custom Authentication Provider to validate the username and password using the API . Once the validation is successful  we create the Authentication object and return to Spring Security framework.

Lets Implement a Custom Authentication Provider In Spring Security , by implementing Authentication Provider interface .

Lets Configure Spring Boot First before Configuring Custom Authentication Provider .

Configure Spring Security Configuration for Custom Provider 

package com.frugalis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
@ComponentScan("com.frugalis")
public class CustAuthProviderConfig extends WebSecurityConfigurerAdapter {
  
    @Autowired
    private CustomAuthenticationProvider authProvider;
 
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authProvider);
    }
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated()
            .and().httpBasic();
    }
}

The above code registers a custom authentication provider and authorize users .Now lets define a Custom Authentication Provider

package com.frugalis;

import java.util.ArrayList;
import java.util.List;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

	boolean shouldAuthenticateAgainstThirdPartySystem = true;

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		String name = authentication.getName();
		String password = authentication.getCredentials().toString();

		if (name.equals("admin") && password.equals("password")) {
			final List<GrantedAuthority> grantedAuths = new ArrayList<>();
			grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
			final UserDetails principal = new User(name, password, grantedAuths);
			final Authentication auth = new UsernamePasswordAuthenticationToken(principal, password, grantedAuths);
			return auth;
		} else {
			return null;
		}

	}

	@Override
	public boolean supports(Class<?> authentication) {

		return authentication.equals(UsernamePasswordAuthenticationToken.class);
	}

}

Code Explanation

In above code we have retrieved Username and password from the Authentication object . Once We retrieve the Authentication Object and Credentials , we are validating the username and password .

You can perform database based authentication , we have done a hard coded validation here .

Once user is valid we try and set GRANTED_AUTHORITY in list of String and return an UserDetails Object to the Caller an Authentication object . Instead of spring provided UserDetails , we can customize the User object set in principal and return .

Building and Publishing NPM TypeScript Package

Building and Publishing NPM TypeScript Package : A Guide from Scratch

In this guide we will build NPM Package from scratch using TypeScript and publish it to the central repository as NPM Package. We will use TypeScript to write the package and Jest to test our code functionality.

What are We going to Build :-

This is what we are going to build , We are going to build a small soap web client package and publish in npm.

https://www.npmjs.com/package/soap-web-client

What is NPM :-

NPM is a package manager and world’s largest library for the node packages from where you could use open-source package and publish your package there. .

Let me tell you npm is a node based package manager . Its is used to manage your projects packages from online registry of packages public and private both . For developers npm is a command line tool , used to manage or pull packages often referred as project dependencies . If you are from a Java programming background , you can think of npm similar to maven .

Here is the official documentation of npm .

Why TypeScript ?

Typescript is a static typed language and helps you write error free code. Typescript is a superset of JavaScript which provides a richer environment for spotting common errors while you write the code.

Let’s KickOff :

Make sure to have latest version of the node, at least >= 7.6 because we have used async/await in our package which was introduced in the nodejs 7.6


Pick a Unique Name :
Since there are a number of packages available in npm, it will be hard for you to name your package but you’ll have to choose one. In this guide we have chosen the name “soap-web-client” since we are going to make a package for the soap web services.

Basic Setup :

Make a Git Repository with the name you have chosen in https://github.com

Clone the created repository :- 

git clone <repository_name.git> && cd soap-web-client

Init your Package :

Let’s create the package.json file first. Enter the below command in command line.

npm init 

Or 

yarn init

Awesome we have done the basics. Package.json will look like something, not exactly. But for sure this package.json provides a metadata about our package that we are going to publish in npm .

 Building and Publishing NPM TypeScript Package : A Guide from Scratch
publishing your npm typescript package in npm

npm install --save-dev typescript

Or 
yarn add -D typescript
Good now you’ll see the node_modules folder.
In order to compile typescript we also needed the tsconfig.json file. So let’s add the same in the root.

{
   "compilerOptions": {
       "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
       "module": "commonjs",
       "allowJs": true, /* Allow javascript files to be compiled. */
       "strict": true, /* Enable all strict type-checking options. */
       "outDir": "./lib", /* Redirect output structure to the directory. */
       "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
   },
   "include": ["src"],
   "exclude": ["node_modules"]
}

Wooh, we have done lots of thing here, let’s understand , tsconfig file indicates the project as typescript project and it includes options on how the typescript files to be compiled

Browsers can’t execute TypeScript directly. Typescript must be “transpiled” into JavaScript using the tsc compiler, which requires some configuration. Typically, you add a TypeScript configuration file called tsconfig.json to your project to guide the compiler as it generates JavaScript files.

target – we want to compile down to “es5” whatever we are writing in the typescript file. There are other target options available.

module – Use commonjs for compatibility.

allowJs – allow javascript files to be compiled.

strict – enable all strict type checking options.

outDir – Redirect target to what directory.

include – which folder should we include for the typescript to be compile.

exclude – which folder should we exclude for the transpile.

Your first step to publish your own npm package :
You are very close to publishing your first npm package. Let’s create the “src” folder and inside this let’s create “index.ts”.

Write any function inside the index.ts file and export that method.

const demoMethod = () => {
return “I’m Duffer”;
}
module.exports = demoMethod;

We have created soap-web-client service hence we have coded like that –



Okay now it is good to go, Next step is to add build scripts in the package.json under scripts.

build” : “tsc”

Now run the build command in the terminal/console.

yarn build

Or 

npm run build

And Magic… You’ll see the lib folder in the root directory.

We have Created the our method which will be exported, let’s write a test case for the same using Jest.

Setup Testing with Jest :


Jest, an awesome package by Facebook.

Since we will be writing tests against our typescript source-files, we also need to add ts-jest and @types/jest. The test suite is only used during development so let’s add them as devDependencies.

npm install --save-dev jest ts-jest @types/jest

Or

yarn add -D jest ts-jest @types/jest

We have added the jest dependency now, let’s put the configuration for the test environment, you could put it into package.json or you could create some configuration file which will provide the configuration to test environment and same we will indicate in the package.json

Let’s create the new file  “jestconfig.json”.

and remove the old test script present in the package.json with

   "test": "jest --config=jestconfig.json",

We will add two more scripts inside the package.json for future use, one is to get code coverage and another is just to clean node_modules.

“coverage” :  “jest --config=jestconfig.json --coverage”,

“clean” : “sudo rm -rf node_modules/”
Now at the end package.json will look like this, you could add dependency on package.json what you need for the first package, but let’s make it simple.

We have done a test setup, let’s create __tests__ folder in the root directory to write the test case in one place.

Write a basic test case :

Let’s write a basic test case for the method we have written in the index.test.ts file.

const testDemoMethod = require(“../src/index”);
test(‘DemoTestCase’ , ()=>{
	expect(testDemoMethod()).toBe(`I’m Duffer`);
});

Save it, now try to run


npm test

Or

yarn test

You’ll see a screen like this, in-case some test are failing, resolve first.

Now we are ready to publish the first package – 

Commit your code to git :

git add .

git commit -m “my first package”

git push origin master

If you don’t have an account at npm, first create the account at https://www.npmjs.com/signupIf you have command then let’s login first in our terminal.

npm login

Or 

yarn login

Provide your username and email id of registered npmjs account, you’ll not have to put your password here.

Last step towards magic :

Let’s publish it, now run publish and provide credentials of npmjs account.

npm publish

Or 

yarn publish

View your package – 
Now you could browse your package at npm. The url of the package will be https://npmjs.com/pacakge/<your-package-name>, in my case it is https://www.npmjs.com/package/soap-web-client

Nice we have got a new package …

Bumping a new version :

If you have made changes and want to push it again after the latest changes then let’s add patch version.

npm version patch

Or 

yarn version --patch

And then again Publish it using the publish command.

Happy coding and publishing ….

Connect with us at LinkedIn –