Sunday, 10 August 2025

List Comprehensions in Python

Suppose we need to create a list with first 10 multiple of 6 in it, So we may do this with a normal

for loop or with list comprehensions, Let's see both of them and understand the difference.

Normal For loop

list1 =[]

for n in range(1,11):

list1.append(n*6)

print(list1)

Output:

[6, 12, 18, 24, 30, 36, 42, 48, 54, 60]

List comprehension

list1 = [n*6 for n in range(1,11)]

print(list1)

Output:

[6, 12, 18, 24, 30, 36, 42, 48, 54, 60]

We got the same output using list comprehensions just by writing a line of code.

In general list comprehension

[<the_expression> for <the_element> in <the_iterable>]

Comparing this with our example n*6 is the expression, n is the element, range(1,11) is the

iterable.

Applying list comprehension with a condition

Now, Suppose we need to create a list of multiple of 6 for just even numbers between 1 to 10.

list1 =[]

for n in range(1,11):

if n%2==0:

list1.append(n*6)

print(list1)

Output:

[12, 24, 36, 48, 60]

Using list comprehensions

list1 = [n*6 for n in range(1,11) if n%2==0]

print(list1)

Output:

[12, 24, 36, 48, 60]

In general list comprehension

[<the_expression> for <the_element> in <the_iterable> if <the_condition>]

Comparing this with our example n*6 is the expression, n is the element, range(1,11) is the

iterable and n%2==0 is the condition.

Applying list comprehension with if-else condition

Now, Suppose we need to create a list of multiple of 6 for even numbers between 1 to 10 and

multiple of 5 for rest of the numbers.

list1 =[]

for n in range(1,11):

if n%2==0:

list1.append(n*6)

else:

list1.append(n*5)

print(list1)

Output:

[5, 12, 15, 24, 25, 36, 35, 48, 45, 60]

Using list comprehensions

list1 = [n*6 if n%2==0 else n*5 for n in range(1,11)]

print(list1)

Output:

[5, 12, 15, 24, 25, 36, 35, 48, 45, 60]

In general list comprehension

[<the_expression> if <the_condition> else <other_expression> for <the_element> in

<the_iterable>]

Comparing this with our example n*6 is the expression, n%2==0 is the condition, n*5 is the

other expression, n is the element and range(1,11) is the iterable.

Applying list comprehension with Nested loops

Now, Suppose we need to multiply n ranging from 1 to 10 with first 1 then 2 and then 3.

list1 =[]

for i in range(1,4):

for j in range(1,11):

list1.append(i*j)

print(list1)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30]

list1 = [i*j for i in range(1,4) for j in range(1,11) ]

print(list1)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30]

In general list comprehension

[ <the_expression> for <element_a> in <iterable_a> (optional if <condition_a>)

for <element_b> in <iterable_b> (optional if <condition_b>)

for <element_c> in <iterable_c> (optional if <condition_c>)

... and so on ...]

Comparing this with our example i*j is the expression, i is the element_a, j is the element_b,

range(1,4) is the iterable_a and range(1,11) is the iterable_b.

Monday, 4 August 2025

🏃‍♂️ My First 5K Run: Lessons Beyond the Track 🏅

 This weekend, I completed my first 5K run—and it turned out to be much more than just a race. It was a powerful reminder of how mindset, consistency, and perspective shape our journey in life and leadership. Here are some takeaways that I believe apply far beyond running:


🔹 Mindset Matters

Waking up at 4 AM and showing up at the venue wasn’t easy—but it all started with setting the right mindset. Whether in personal goals or professional ambitions, your mental readiness sets the tone.


🔹 Consistency Pays Off

Until now, I had never run 5K in one stretch. But consistent preparation and showing up every day made it possible. Small, steady steps lead to big breakthroughs.


🔹 Hurdles Are Inevitable

There were moments I wanted to stop. Fatigue, breathlessness, and doubts crept in. But determination and focus helped me push through. Obstacles are a given—your response defines your path.


🔹 Run Your Own Race

In the race, some were ahead, others behind. But that didn’t make anyone better or worse. Everyone has a different pace and strength. The real win is in honoring your unique journey—comparison is a distraction.


🔹 Be a Leader Who Lifts Others

Some runners took time to cheer and guide others. It reminded me that leadership isn’t just about reaching your own goals—it’s also about helping others cross their finish lines.


🔹 Embrace Highs and Lows

The uphill was tough, the downhill easy. Just like life. Stay grounded in good times, and stay hopeful in the hard ones. Both are temporary. What matters is how you carry yourself through them.


🔹 No Excuses

The most inspiring moment? A 97-year-old man completing the race. If he can do it, we can too. Excuses are often just stories we tell ourselves. Let’s choose action instead.


🔹 Winning Is Great. Learning Is Greater.

I didn’t run to win—I ran to grow. And even if you don’t cross first, every experience carries insights to fuel your next step.

Saturday, 17 May 2025

SOLID Pattern Quick Notes - Design Patterns for Writing Classes in OOPS

SOLID is a famous design pattern for writing classes in OOPS

S: Single Responsibility Principle

O: Open Closed Principle

L: Liskov's Substitution Principle

I: Interface Segregation Principle

D: Dependency Inversion Principle


Single Responsibility Principle (SRP)

- Class should have one and only one responsibility

- Write a Class to achieve one goal

- SRP helps to provide high maintainability and better visibility to control across application module

Open Closed Principle (OCP)

- Software components should be open for extension, but closed for modification.

- Our classes should not contain constraints that will require other developers to modify our classes in order to accomplish their job – only by extend our classes to accomplish their job.

- It helps to achieve  software extensibility in a versatile, intuitive, and non-harmful way.

 Liskov's Substitution Principle (LSP)

 -Derived types must be completely substitutable for their base types.

- Objects of subclasses must behave in the same way as the objects of super classes.

- This principle useful for runtime-type identification followed by the cast.

Interface Segregation Principle (ISP)

-Clients should not be forced to implement unnecessary methods that they will not use.  

-splits an interface into two or more interfaces until clients are not forced to implement methods that they will not use.

This principle stands for Clients should not be forced to implement unnecessary methods that they will not use. In other words, we should split an interface into two or more interfaces until clients are not forced to implement methods that they will not use. For example, consider the Connection interface, which has three methods: connect(), socket(), and http(). A client may want to implement this interface only for connections via HTTP. Therefore, they don't need the socket() method. Most of the time, the client will leave this method empty, and this is a bad design. In order to avoid such situations, simply split the Connection interface into two interfaces; SocketConnection with the socket() method, and HttpConnection with the http() method. Both interfaces will extend the Connection interface that remains with the common method, connect()


Dependency Inversion Principle (DIP).

-Depend on abstractions, not on concretions.

- sustains the use of abstract layers to bind concrete modules together instead of having concrete modules that depend on other concrete modules.

- sustains the decoupling of concrete modules.

This principle stands for Depend on abstractions, not on concretions. This means that we should rely on abstract layers to bind concrete modules together instead of having concrete modules that depend on other concrete modules. To accomplish this, all concrete modules should expose abstractions only. This way, the concrete modules allow extension of the functionality or plug-in in another concrete module while retaining the decoupling of concrete modules. Commonly, high coupling occurs between high-level concrete modules and low-level concrete modules.

Ex: A database JDBC URL, PostgreSQLJdbcUrl, can be a low-level module, while a class that connects to the database may represent a high-level module, such as ConnectToDatabase#connect().

Time Complexity of an Algorithm

 

Time Complexity Description Example
O(1) Constant time     Accessing an element in an array
O(log n) Logarithmic time     Binary search
O(n) Linear time     Iterating over an array
O(n log n) Linearithmic time     Merge sort, quicksort (avg case)
O(n²) Quadratic time     Nested loops over array
O(2ⁿ) Exponential time     Recursive Fibonacci
O(n!) Factorial time     Permutations / Travelling Salesman


O(1) - Constant Time - The time doesn't change no matter how big the input is

Ex: Accessing element of an array . int x = nums[0];  // Always takes the same time

O(log n) - Logarithimic Time : You reduce the input size by half each step i.e Guessing a number between 1 and 100 by halving the range each time

Ex: Binary Search 

 while (low <= high) {
    int mid = (low + high) / 2;
    if (nums[mid] == target) return mid;
    else if (nums[mid] < target) low = mid + 1;
    else high = mid - 1;
}

O(n) - Linear time - Time grows directly with input size

Ex : Looping over an array i.e. Reading every page in a book once
for (int i : nums) {
    System.out.println(i);
}

O(n log n) - Linearithmic Time - A combination of linear and logarithimic Time - common in efficient sorting

Ex; Merge Sort, quick sort (average case) - merge sort splits the array ( log n) and merges each part (O (n))

Sorting a phone book - split , sort and merge

O(n2) - Quadratic Time - Time grows with the square of the input - often from the nested loops
Ex; Two loops over an array - i.e. comparing every student with every other student

for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        // O(n²)
    }
}

O(2n) - Exponential Time - Each step doubles the number of operations

Ex : Recursive fibonacci 

int fib(int n) {
    if (n <= 1) return n;
    return fib(n - 1) + fib(n - 2);
}

O(n!) - Factorial Time - Insanely slow for even modest input sizes — involves all permutations.

Ex : Generating all permutations - Trying every possible seating arrangement for n people.

void permute(List<Integer> nums, int index) {
    if (index == nums.size()) return;
    for (int i = index; i < nums.size(); i++) {
        Collections.swap(nums, i, index);
        permute(nums, index + 1);
        Collections.swap(nums, i, index);
    }
}








Monday, 5 May 2025

System Design Preparation

 Following are the system design preparation materials

https://github.com/ashishps1/awesome-system-design-resources?tab=readme-ov-file

https://dev.to/somadevtoo/9-software-architecture-patterns-for-distributed-systems-2o86

https://martinfowler.com/articles/patterns-of-distributed-systems/

Saturday, 19 August 2023

Important Jargons of Artificial Intelligence

1. AI (Artificial Intelligence): The creation of computer systems that can perform tasks that typically require human intelligence, like understanding language, recognizing patterns, and making decisions.


2. LLM (Large Language Model): An advanced type of AI that can understand and generate human-like text by learning patterns from vast amounts of written language data.

3. Machine Learning: A subset of AI that focuses on teaching computers how to learn from data and improve their performance on a task without being explicitly programmed.


4. ChatGPT: A specific instance of a large language model developed by OpenAI, designed to generate human-like text and engage in conversations with users.


5. ChatBot: A computer program or AI application that simulates human conversation, allowing users to interact with it via text or speech to obtain information or perform tasks.

Saturday, 15 January 2022

React Preparations - Materials

 0. Get started with React

https://www.taniarascia.com/getting-started-with-react/

1. React and Redux

https://medium.com/codingthesmartway-com-blog/learn-redux-introduction-to-state-management-with-react-b87bc570b12a

2. Thinking in React

https://reactjs.org/docs/thinking-in-react.html

3. React Free course

https://www.udemy.com/course/react-basic-in-just-1-hour/?LSNPUBID=JVFxdTr9V80&ranEAID=JVFxdTr9V80&ranMID=39197&ranSiteID=JVFxdTr9V80-gMEc02YOV2FtjWGPT6pUbw&utm_medium=udemyads&utm_source=aff-campaign

React basic in just 1 hour [2021] - Leo Trieu - udemy




Interview Preparation - Java - Experienced Professional

In this Blog, I am trying to collect useful blogs which helps for preparing Java Interview - For Experienced professional. 

0) Introduction to Algorithms and Data structure in Java

From 0 to 1: Data Structures & Algorithms in Java by Loony Corn

https://github.com/PacktPublishing/From-0-to-1-Data-Structures-Algorithms-in-Java

Popular Problem-Solving Approaches in Data Structures and Algorithms

https://medium.com/enjoy-algorithm/popular-problem-solving-approaches-in-data-structures-and-algorithms-6b4d30a0823d

1) For Java Interview preparation

https://medium.com/javarevisited/25-topics-and-resources-to-crack-java-developer-interviews-in-2021-8fbfe317513

https://blog.usejournal.com/from-hi-from-google-again-to-congratulations-on-your-offer-with-google-6f77e93be2bd

https://medium.com/nerd-for-tech/googles-interview-preparation-routine-be6647910a5b


2) For quick database concepts review

https://keerthiga14.medium.com/top-6-important-concepts-of-dbms-519faae8f065

3) For OAuth2 & Security

https://darutk.medium.com/the-simplest-guide-to-oauth-2-0-8c71bd9a15bb

https://darutk.medium.com/diagrams-and-movies-of-all-the-oauth-2-0-flows-194f3c3ade85

https://auth0.com/docs/authorization/which-oauth-2-0-flow-should-i-use

3) Rest API performance improvement

https://developers.google.com/blogger/docs/3.0/performance

4) Deploy Spring Boot microservice into Azure

https://docs.microsoft.com/en-us/learn/modules/azure-spring-cloud-workshop/

5) For Java Programming interview questions

https://www.java67.com/2018/06/data-structure-and-algorithm-interview-questions-programmers.html

6) Microservices using Spring Boot quick demo - ( daily code buffer you tube)

https://www.youtube.com/watch?v=BnknNTN8icw



Tuesday, 3 August 2021

React - npm : self signed certificate in certificate chain issue

 When I try to install react-router using "npm install react-router-dom"

I got below mentioned error message

PS C:\PracticeApps\React\my-react-app> npm install react-router-dom

npm WARN registry Unexpected warning for https://registry.npmjs.org/: Miscellaneous Warning SELF_SIGNED_CERT_IN_CHAIN: request to https://registry.npmjs.org/react-router-dom failed, reason: self signed certificate in certificate chain

npm WARN registry Using stale data from https://registry.npmjs.org/ due to a request error during revalidation.

npm ERR! code SELF_SIGNED_CERT_IN_CHAIN

npm ERR! errno SELF_SIGNED_CERT_IN_CHAIN

npm ERR! request to https://registry.npmjs.org/react-router-dom/-/react-router-dom-5.2.0.tgz failed, reason: self signed certificate in certificate chain  


npm ERR! A complete log of this run can be found in:

npm ERR!     C:\Users\KMATADA\AppData\Roaming\npm-cache\_logs\2021-08-03T14_08_06_664Z-debug.log


Solution : Try to run below commands

1.  npm install npm -g --ca=""


2. npm config set strict-ssl false   ( not recommended - ignoring ssl error is bad idea)



Reference Link

https://stackoverflow.com/questions/9626990/receiving-error-error-ssl-error-self-signed-cert-in-chain-while-using-npm



Thursday, 8 July 2021

Configure/ Enable Swagger API for Spring Boot 2 (2.5.2)

 Enabling Swagger API documentation in Spring Boot 2.5.2 is pretty simple now.

We just need to few dependency and we are good to go

For Spring Boot Applications, If you are migrating to 2.5.2 version then perform the following operations

1. Remove library inclusions of earlier releases. Specifically remove springfox-swagger2 and springfox-swagger-ui inclusions.

2. Remove the @EnableSwagger2 annotations

3. Add the springfox-boot-starter as shown below

4. No need to external config class to configure docket-api. It is handled automatically.


Following is the dependency we have to add in our pom.xml (for maven project)


That's it!!!

and swagger-ui location has moved from 
http://host/context-path/swagger-ui.html 
to 
http://host/context-path/swagger-ui/index.html 
OR http://host/context-path/swagger-ui/

as shown below




The complete code can be found in my github

Friday, 25 June 2021

PSQLException: ERROR: UNION types text and boolean cannot be matched

Recently I have faced the issue mentioned below

Caused by: org.postgresql.util.PSQLException: ERROR: UNION types text and boolean cannot be matched

Detailed stack trace :

org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440)

at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2183)

at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:308)

at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:441)

at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:365)

at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:143)

at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:106)

at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52)

at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java)

at org.springframework.jdbc.core.JdbcTemplate$1.doInPreparedStatement(JdbcTemplate.java:677)

at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:616)

... 81 common frames omitted


Use case : In my Repository, i have union of 3 queries and i have introduced new boolean attribute and i started getting this error

Important thing to note when using union : order of attributes or column should be same in all the individual queries.

Example Query which was giving above error 

select name,id isValid from ((select t1.name as name ,t1.id as id ,t1.isValid as isValid from table t1) union (select t2.name as name,t2.id as id,' ' as isValid  from table t2) union(select t3.name as name,t3.id,t3.isValid as isValid from table t3) ) table t;

Even though order is same for all the 3 querues, mistke in the above query is ' ' as isValid from table 2

I was assigning text type value to boolean attribute hence i was getting the exception


 correct way is ( pass default value in my case FALSE)

select name,id isValid from ((select t1.name as name ,t1.id as id ,t1.isValid as isValid from table t1) union (select t2.name as name,t2.id as id, FALSE as isValid  from table t2) union(select t3.name as name,t3.id,t3.isValid as isValid from table t3) ) table t;


Hope it helps :)

Saturday, 5 June 2021

Transaction Propagation in Spring, Spring Boot

What is Transaction Propagation ?

Propagation defines our business logic's boundary. Spring manages to start and pause a transaction based on our propagation setting.

In Spring Boot, we enable the transaction propagation using @Transactional annotation.

@Transactional : It Describes a transaction attribute on an individual method or on a class. 

We can set propagation, isolation, timeout, read-only and rollback conditions for our transaction using this annotation.

If annotation is applied at class level, then spring consider it for all the public methods, but if we applied at private or protected method then it ignores without an error.

Ex : 

  @Transactional(propagation = Propagation.REQUIRES_NEW)

  public void deleteExistingData() {
  }

Following are the settings for propagation

1.REQUIRED -  Default. Support a current transaction, create a new one if none exists.

2.SUPPORTS - Support a current transaction, execute non-transactionally if none exists.

3.MANDATORY - Support a current transaction, throw an exception if none exists. 

throw IllegalTransactionStateException

4.REQUIRES_NEW - Creates a new transaction, and suspend the current transaction if one exists.

5.NOT_SUPPORTED - Execute non transitionally, suspend the current transaction if one exists.

6.NEVER - Execute non-transitionally, throw an exception if a transaction exists.

7.NESTED - Execute within a nested transaction if a current transaction exists.

Thursday, 4 March 2021

Kubernetes - Getting started with - Introduction, Pods

Kubernetes Building Blocks


How communication happens within Kubernetes






Running a Pod (2 ways)
1) kubectl run command
2) kubectl create/apply command with a yaml file

The kubectl get command can be used to pods information and many other kubernetes objects
For ex : kubectl get pod lists all pods
             kubectl get all  lists all resources

Expose a Pod port

By default pods and container are only accessible within kubernetes cluster
To use expose container port externally we can use kubectl port-forward

Ex : kubectl port-forward [name of the pod ] 8080:80  where 8080 is external port and 80 is internal port

Delete Pod

Running Pod will cause deployment to be created
To delete pod use kubectl delete pod or find a deployment and run kubectl delete deployment
kubectl delete  pod [name of pod] will cause pod to be recreated
kubectl delete deployment [name of the deployment] -: delete deployment that manages the pod

To delete a pod which is created using yaml file then we can use below mentioned command
kubectl delete -f file.pod.yml



Sample yaml file for pod creation (Ex : nginx)


kubectl create -f file.pod.yml  will results in error if pod already exists

So alternative way to create or apply changes to a pod is to use kubectl apply -f file.pod.yml

Use --save-config when you want to use kubectl apply in the feature (it saves current properties in resource's annotations)

kubectl apply -f file.pod.yml  --save-config





Pod Health
Kubernetes relies on Probes to determine the health of the pod container

A probe is a diagnostic performed periodically by kubelet on a container




Readiness Probe ; when should a container start receiving traffic?
Liveliness Probe : when should a container restart ?

Reference : Mr.Dan Wahlin  course

Kubernetes - Getting started with - ReplicaSet ,Deployments

ReplicaSet : It is a declarative way to manage the pods.

Deployment : it is a declarative way to manage the pods using ReplicaSet.






How Does Spring Boot Work?






Spring MVC Integration with SpringBoot(Internal mechanism steps-)







Useful Links related to Spring

Spring Web Application Design

Spring Performance


Enable Config Server (Centralized configuration)

Wednesday, 2 September 2020

Token Management in Client Credentials Grant Flow - OAuth 2.0

 There are 4 types of Authorization grant in OAuth 2.0

1)Authorization Code

2)Implicit

3)Resource Owner Password Credentials

4)Client Credentials

In this blog post, I would like to give information on "Client Credentials" authorization grant

This type of grant flow is preferable when there is back-end system to another back-end system communication. Ex: In your server side code, you are trying to invoke OIDC based API to get data and process it.

So the overall Authorization flow at high level is would be

Step 1 : Get "x-api-key" from your authorization provider

Step 2: Get Access Token by passing Client ID & Client Credentials

Step 3: Invoke the API by passing the x-api-key & Access Token (By appending "Bearer")


Once you received the Access Token invoke the API by passing the x-api-key and bearer token as shown below



Now lets see about token management.

In other authorization code grant we will get refresh token and by using this, we can do token management. But in client credentials we do not get any refresh token and we only get access token, token type and expires_in value as shown below



It is advisable to get fresh access token in Client Credentials grant. But in case your requirement is  not get fresh access token for every call, then we can use below mentioned approach.

The attribute expires_in is in seconds, that means the received token will be valid for almost 30 min.

So approach will be, we will use same token till the time is less than the expires_in value and after that get fresh token and use it for another 30 min.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package practice;

public class ClientCredentialsTokenManagement {
  private static final String AUTHORIZATION = "Authorization";
  private static final String BASIC = "Basic";
  private static final String SPACE = " ";
  private static final String GRANT_TYPE = "grant_type";
  private static final String X_API_KEY = "x-api-key";
  private static final String X_API_KEY_VAL = "<< x-api-key-val>>";
  private static final String CONTENT_TYPE = "Content-type";
  private static final String ACCESS_TOKEN_URL = "<<access token url>>";
  private static final String CLIENT_ID = "<<client id>>";
  private static final String CLIENT_SECRET = "<<Client secret value >>";
  private static final String CLIENT_CREDENTIALS = "client_credentials";

  // JWT fields
  private static final String EXPIRES_IN = "expires_in";
  private static final String ACCESS_TOKEN = "access_token";

  private long expiresAt;
  private String accessToken;

  public String getAccessToken() {
    return accessToken;
  }

  public void setAccessToken(String accessToken) {
    this.accessToken = accessToken;
  }

  public long getExpiresAt() {
    return expiresAt;
  }

  public void setExpiresAt(long expiresAt) {
    this.expiresAt = expiresAt;
  }

  // Invoking API with token management

  private void invokeAPI() {
    try {
      long currentTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
      if (currentTime < this.getExpiresAt()) {
        LOGGER.info("Using Existing Token");
        result = invokeQueryApi(paramVal, this.getAccessToken());
        getAccessToken();
      } else {
        LOGGER.info("Requesting new token");
        fetchAccessToken();
        result = invokeQueryApi(paramVal, this.getAccessToken());
      }
    } catch (IOException e) {
      LOGGER.error("Exception while invoking Sma4u Service");
    }
  }

  // Method used to get Access Token using Client Credentials grant Flow

  private void fetchAccessToken() throws IOException {
    HttpPost request = new HttpPost(ACCESS_TOKEN_URL);
    String auth = CLIENT_ID + ":" + CLIENT_SECRET;
    Header header = new BasicHeader(AUTHORIZATION,
        BASIC + SPACE + base64UrlEncodeToString(auth.getBytes(StandardCharsets.UTF_8)));
    request.addHeader(header);
    List<NameValuePair> nameValuePairs = new ArrayList<>();
    nameValuePairs.add(new BasicNameValuePair(GRANT_TYPE, CLIENT_CREDENTIALS));
    request.setEntity(new UrlEncodedFormEntity(nameValuePairs, StandardCharsets.UTF_8));
    HttpResponse response = client.execute(request);
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
      LOGGER.info("OIDC Access Token obtained in exchange for OIDC Authorization Code !!!");
      BufferedReader reader =
          new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
      String line = null;
      StringBuilder sb = new StringBuilder();
      while ((line = reader.readLine()) != null) {
        sb.append(line);
      }
      JSONObject responsJson = new JSONObject(sb.toString());
      LOGGER.info(responsJson.getString(ACCESS_TOKEN));
      accessToken = responsJson.getString(ACCESS_TOKEN);
      this.setAccessToken(responsJson.getString(ACCESS_TOKEN));
      int val = Integer.parseInt(responsJson.get(EXPIRES_IN).toString());
      Long issuedAt = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()) + val;
      this.setExpiresAt(issuedAt);
    }
  }

  private String base64UrlEncodeToString(byte[] input) {
    return Base64.getUrlEncoder().encodeToString(input);
  }

}

Hope this helps. Let me know if any concerns

References

https://tools.ietf.org/html/rfc6749#section-1.3.4

Saturday, 13 June 2020

Java Best Practices to write readable and maintainable code

From my understanding and experience following are the few best practices to write readable and maintainable code

Variables:

Methods:

Exceptions:


As shown in the above diagram never ever catch Throwable

We can use Throwable in a catch clause, but we should never do it! If we use Throwable in a catch clause, it will not only catch all exceptions; it will also catch all errors. Errors are thrown by the JVM to indicate serious problems that are not intended to be handled by an application

Also we should avoid using directly Exception  in the catch block. Try to handle specific exception
Ex:

try{
      readFile();
    }
catch(FileNotFoundException) { }

In catch block,
1) Do not print stacktrace ,  instead use any logging framework
    Ex : catch(.... ex){
                               log.error(ex);
                               }
2) Throw the exception using custom exception wherever appropriate

Class

The class should meet following important principle
1. Follow SRP - Single Responsibility Principle
2. Program to an Interface
3. Maintain Strong Encapsulation within Class
4. Maintain high Cohesion
5. Always try to have minimum Coupling
6 . Use Dependency Injection
7.  Principle of Proximity i.e. well organized methods

SOLID Principle
Single Responsibility Principle
Open Closed Principle'
Liskov Substitution Principle
Interface Segregation Principle
Dependency Inversion

Comments

- Use JavaDoc format if necessary
- Always remove commented out code before pushing to version control system i.e svn or git
- Use comments if necessary, it should not compensate for buggy code. Prefer giving comments only for public methods wherever necessary


Tests(Junit/Mockito)

- Always verify one thing per test
- 1 assertion per test (Except-few cases where it is not applicable)
- No if branching in tests

Test should have basic template like as shown below

 Arrange
   - Setup and initialize the objects and the environment
  Act
    - Exercise the functionality under test
 Assert
    - Verify the result

Test Pattern
AAA - Arrange-Act-Assert
BDD - Given - When - Then

Other Points
- Install Static Code Checker like SonarLint 




=====================Reference=================================
Google Java Style Guide
https://google.github.io/styleguide/javaguide.html

Mr. Andrejs Doronins Java Readability & Maintainability Course




Tuesday, 3 September 2019

Error response from daemon: Get https://registry-1.docker.io/v2 - docker desktop for windows

Problem Statement : Error response from daemon: Get https://registry-1.docker.io/v2

I faced above mentioned problem, when I first installed docker for desktop windows and tried to run

docker run hello-world

The issue is because of corporate proxy setting


Solution which I tried :

Step1 : Right click on the docker icon(bottom right corner) - select settings option

Step2 : Set http and https proxies as shown in below screen shot


May be if any proper solution, kindly let me know.

Thanks
Kotresh

Thursday, 13 June 2019

Exclude jar from war in a Spring Boot gradle project

Spring Boot version : 2.1.4.RELEASE

If you would like to use jar only for compilation purpose and exclude the jar at run time or not part of the war then you can do as follows

In the gradle.build properties file use "compileOnly files" Option

dependencies {
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("io.springfox:springfox-swagger2:2.9.2")
    implementation("io.springfox:springfox-swagger-ui:2.9.2")
compileOnly files('libs/<some>-api.jar')
}

As mentioned in the above dependencies , <some>-api.jar placed under libs folder will be used only for compile time and it will be not part of the war


Friday, 12 April 2019

Spring Boot application as a windows service

In this Blog, I will try to illustrate steps to run Spring Boot application as a Windows Service.

To run Spring Boot application as a windows service we will be using
 winsw: Windows service wrapper

Please follow below mentioned steps

Step1: Check out the version of Microsoft .NET framework to determine correct winsw version for the windows operating system.




To check Microsoft.NET framework version, Navigate to command prompt and run below mentioned command as shown below

reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\full" /v version



If your .NET framework version is less than 3.5 then we need to download winsw v2.1.1 else we can download winsw v2.1.2


Step2: Download the winsw and prepare required directory structure.
We can download the winsw from below mentioned link


From the above mentioned git hub repository download the WinSW.NET4.exe and sample-minimal.xml to a directory and name it “spring-boot-service”

Also rename WinSW.NET4.exe and sample-minimal.xml to spring-boot-service.exe and spring-boot-service.xml


Place  your application war in the same folder (for example spring-boot-service.war)

Modify the spring-boot-service.xml file with proper values

As shown in above screen shot, give unique id for your service (For ex : spring-boot-service)
For the "executable" property give value till JAVA_HOME/java (i.e. folder where your java.exe file is present)

set the argument property as shown below
<arguments>-Dserver.port=9002 -Duser.timezone=UTC -Xms1024m -Xmx2048m -Dlogging.root=C:\test\spring-boot-service\logs\  -jar spring-boot-service.war</arguments> 


Step3: winsw installation and configuration set up
             Open command prompt as an administrator and navigate to directory where you placed winsw installation and configuration file as explained in the Step1 (for example spring-boot-service folder)
i) Execute spring-boot-service.exe install 

ii)                 Open windows “Services” as Administrator –
For Example in Windows 7, following is navigation path to launch windows Services
Start -> Control Panel -> System and Security -> Administrative Tools -> Services(Run as Administrator)

i)                 Now in the Services Window, select the service, right click and start

or in the command prompt run net start <service-name>
 where service-name is unique id which you given in service.xml file

To delete a process run below sc command
sc delete <service name>