CodeByAkram

How to set connection timeout for RestTemplate in spring?

How to set connection timeout for RestTemplate in spring? codebyakram

We can set the timeout for RestTemplate by doing some custom configuration for RestTemplate.

First you need to create a class named as HttpClientConfig in this class we configure HttpClient because RestTemplate internally uses the HttpClient.


package com.codebyakram;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HttpClientConfig {

 public static final Logger LOGGER = org.slf4j.LoggerFactory.getLogger(HttpClientConfig.class.getName());
 // Determines the timeout in milliseconds until a connection is established.
 private static final int CONNECT_TIMEOUT = 30000;

 // The timeout when requesting a connection from the connection manager.
 
 private int REQUEST_TIMEOUT = 10000;
 
 @Bean
 public CloseableHttpClient httpClient() {
  RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(REQUEST_TIMEOUT).build();
  return HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
 }
}

Here in this class we setting HttpClient in RestTemplate

package com.codebyakram;

import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

 @Autowired
 CloseableHttpClient httpClient;


 @Bean
 public RestTemplate restTemplate() {
  RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory());
  return restTemplate;
 }

 @Bean
 public HttpComponentsClientHttpRequestFactory clientHttpRequestFactory() {
  HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
  clientHttpRequestFactory.setHttpClient(httpClient);
  return clientHttpRequestFactory;
 }

 @Bean
 public TaskScheduler taskScheduler() {
  ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
  scheduler.setThreadNamePrefix("poolScheduler");
  scheduler.setPoolSize(50);
  return scheduler;
 }
}

So now we are done with the cofiguration of request timeout for RestTemplate.

How to Sort a Stack using Merge Sort?

Interviewer may ask you this question if you have more than 3 years of experience in java development. So lets have a look, how to sort a stack using merge sort?

Lets see sample input and output for better understanding:

How to Sort a Stack using Merge Sort? codebyakram


Algorithm
For this we will follow these below two steps,
1. Break the stack into two parts by using two temporary stack.

2. When only one element remains on a Stack, Merge it.

Lets have a look on the program,


package com.codebyakram;
 
import java.util.Stack;
 
public class SortStack {
 
    public static void main(String args[]) {
        Stack stack = new Stack();
        stack.push(5);
        stack.push(9);
        stack.push(4);
        stack.push(1);
        stack.push(2);
        stack.push(-1);

 
        sort(stack);
 
        System.out.println(stack);
    }
 
    private static void sort(Stack stack) {
        Stack s1 = new Stack();
        Stack s2 = new Stack();
 
        while (stack.size() != 0) {
            if (stack.size() % 2 == 0) {
                s1.push(stack.pop());
            } else {
                s2.push(stack.pop());
            }
        }
 
        if (s1.size() > 1) {
            sort(s1);
        }
 
        if (s2.size() > 1) {
            sort(s2);
        }
 
        merge(s1, s2, stack);
    }
 
    private static void merge(Stack s1, Stack s2, Stack stack) {
        Stack mergedStack = new Stack();
        while (!s1.isEmpty() && !s2.isEmpty()) {
            if ((Integer) s1.peek() < (Integer) s2.peek()) {
                mergedStack.push(s2.pop());
            } else {
                mergedStack.push(s1.pop());
            }
        }
 
        while (!s1.isEmpty()) {
            mergedStack.push(s1.pop());
        }
 
        while (!s2.isEmpty()) {
            mergedStack.push(s2.pop());
        }
 
        while (!mergedStack.isEmpty()) {
            stack.push(mergedStack.pop());
        }
    }
}

Adjacency List in Java

An adjacency list represents a graph as an array of linked list.

The index of the array represents a vertex and each element in its linked list represents the other vertices that form an edge with the vertex.

Adjacency List representation
A graph and its equivalent adjacency list representation is shown below.

Adjacency List in Java, codebyakram
An adjacency list is efficient in terms of storage because we only need to store the values for the edges. For a sparse graph with millions of vertices and edges, this can mean a lot of saved space.

Adjacency List Structure
The simplest adjacency list needs a node data structure to store a vertex and a graph data structure to organize the nodes.


We stay close to the basic definition of graph - a collection of vertices and edges {V, E}. For simplicity we use an unlabeled graph as opposed to a labeled one i.e. the vertexes are identified by their indices 0,1,2,3.

Let's dig into the data structures.

struct node
{
    int vertex;
    struct node* next;
};
struct Graph
{
    int numVertices;
    struct node** adjLists;
};

Don't let the struct node** adjLists overwhelm you.

All we are saying is we want to store a pointer to struct node*. This is because we don't know how many vertices the graph will have and so we cannot create an array of Linked Lists at compile time.

Adjacency List Java
We use Java Collections to store the Array of Linked Lists.

class Graph
{
    private int numVertices;
    private LinkedList adjLists[];
}

The type of LinkedList is determined what data you want to store in it. For a labeled graph, you could store a dictionary instead of an Integer

Adjacency List code Java

import java.io.*;
import java.util.*;
class Graph
{
    private int numVertices;
    private LinkedList adjLists[];
 
    Graph(int vertices)
    {
        numVertices = vertices;
        adjLists = new LinkedList[vertices];
        
        for (int i = 0; i < vertices; i++)
            adjLists[i] = new LinkedList();
    }
 
    void addEdge(int src, int dest)
    {
        adjLists[src].add(dest);
    }
 
    public static void main(String args[])
    {
        Graph g = new Graph(4);
 
         g.addEdge(0, 1);
         g.addEdge(0, 2);
         g.addEdge(1, 2);
         g.addEdge(2, 3);
    }
}

Breadth first search in Java

Traversal meaning visiting all the nodes of a graph. Breadth first Search is also known as Breadth first traversal and is a recursive algorithm for searching all the nodes of a graph or tree data structure.

BFS algorithm
A standard BFS algorithm implementation puts each nodes of the graph or tree into one of two categories:
Visited and
Not Visited

The purpose of the algorithm is to mark each node as visited while avoiding cycles.

The algorithm works as follows:

  1. Start by putting any one of the graph's node at the back of a queue or array.
  2. Take the front node of the queue and add it to the visited list.
  3. Create a list of that node's adjacent nodes. Add the ones which aren't in the visited list to the back of the queue.
  4. Keep repeating steps 2 and 3 until the queue is empty.

The graph might have two different disconnected parts so to make sure that we cover every node, we can also run the BFS algorithm on every node

BFS example
Let's see how the BFS algorithm works with an example. We use an undirected graph with 5 nodes.

BFS, codebyakram

We start from node 0, the BFS algorithm starts by putting it in the Visited list and putting all its adjacent nodes in the queue.


Next, we visit the element at the front of queue i.e. 1 and go to its adjacent nodes. Since 0 has already been visited, we visit 2 instead.
BFS, codebyakram

Node 2 has an unvisited adjacent node in 4, so we add that to the back of the queue and visit 3, which is at the front of the queue.

BFS, codebyakram

BFS, codebyakram


Only 4 remains in the queue since the only adjacent node of 3 i.e. 0 is already visited. We visit it.

BFS, codebyakram

Since the queue is empty, we have completed the Depth First Traversal of the graph.

BFS pseudocode



create a queue Q 
mark v as visited and put v into Q 
while Q is non-empty 
    remove the head u of Q 
    mark and enqueue all (unvisited) neighbours of u

BFS Java code

import java.io.*;
import java.util.*;
 
class Graph
{
    private int numVertices;
    private LinkedList adjLists[];
    private boolean visited[];
 
    Graph(int v)
    {
        numVertices = v;
        visited = new boolean[numVertices];
        adjLists = new LinkedList[numVertices];
        for (int i=0; i i = adjLists[currVertex].listIterator();
            while (i.hasNext())
            {
                int adjVertex = i.next();
                if (!visited[adjVertex])
                {
                    visited[adjVertex] = true;
                    queue.add(adjVertex);
                }
            }
        }
    }
 
    public static void main(String args[])
    {
        Graph g = new Graph(4);
 
        g.addEdge(0, 1);
        g.addEdge(0, 2);
        g.addEdge(1, 2);
        g.addEdge(2, 0);
        g.addEdge(2, 3);
        g.addEdge(3, 3);
 
        System.out.println("Following is Breadth First Traversal "+
                           "(starting from vertex 2)");
 
        g.BFS(2);
    }
}

DFS algorithm in Java

Traversal meaning visiting all the nodes of a given graph. Depth first Search is also know as Depth first traversal. DFS is a recursive algorithm for searching all the vertices of a graph or tree.

DFS algorithm
A standard DFS implementation puts each vertex of the graph into one of two categories:

1.Visited
2. Not Visited

The purpose of the algorithm is to mark each vertex as visited while avoiding cycles.

The DFS algorithm works as follows:


  1. Start by putting any one of the graph's vertices on top of a stack.
  2. Take the top item of the stack and add it to the visited list.
  3. Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited list to the top of stack.
  4. Keep repeating steps 2 and 3 until the stack is empty.

DFS example
Let's see how the Depth First Search algorithm works with an example. We use an undirected graph with 5 vertices.

DFS, codebyakram

We start from node 0, the DFS algorithm starts by putting it in the Visited list and putting all its adjacent nodes in the stack.

DFS, codebyakram

Next, we visit the element at the top of stack i.e. 1 and go to its adjacent nodes. Since 0 has already been visited, we visit 2 instead.

DFS, codebyakram
Node 2 has an unvisited adjacent node in 4, so we add that to the top of the stack and visit it.

DFS, codebyakram


DFS, codebyakram

After we visit the last element 3, it doesn't have any unvisited adjacent nodes, so we have completed the Depth First Traversal of the graph.

DFS, codebyakram


DFS pseudocode (recursive implementation)
The pseudocode for Depth first Search is shown below. In the init() function, notice that we run the DFS function on every node. This is because the graph might have two different disconnected parts so to make sure that we cover every vertex, we can also run the DFS algorithm on every node.



DFS(G, u)
    u.visited = true
    for each v ∈ G.Adj[u]
        if v.visited == false
            DFS(G,v)
     
init() {
    For each u ∈ G
        u.visited = false
     For each u ∈ G
       DFS(G, u)
}

DFS Java code

import java.io.*;
import java.util.*;
 
class Graph
{
    private int numVertices;
    private LinkedList adjLists[];
    private boolean visited[];
 
    Graph(int vertices)
    {
        numVertices = vertices;
        adjLists = new LinkedList[vertices];
        visited = new boolean[vertices];
        
        for (int i = 0; i < vertices; i++)
            adjLists[i] = new LinkedList();
    }
 
    void addEdge(int src, int dest)
    {
        adjLists[src].add(dest);
    }
 
    void DFS(int vertex)
    {
        visited[vertex] = true;
        System.out.print(vertex + " ");
 
        Iterator ite = adjLists[vertex].listIterator();
        while (ite.hasNext())
        {
            int adj = ite.next();
            if (!visited[adj])
                DFS(adj);
        }
    }
 
 
    public static void main(String args[])
    {
        Graph g = new Graph(4);
 
         g.addEdge(0, 1);
         g.addEdge(0, 2);
         g.addEdge(1, 2);
         g.addEdge(2, 3);
 
        System.out.println("Following is Depth First Traversal");
 
        g.DFS(2);
    }
}