Saturday, 8 August 2020

Sort a list using Streams

 In this post, I am going to explain how to sort a list of items using Strems#sort method.

'java.util.stream.Stream' interface provides the following methods to sort a stream.

 

Stream<T> sorted()

Returns a stream consisting of the elements of this stream, sorted according to the natural order.

 

Stream<T> sorted(Comparator<? super T> comparator)

Returns a stream consisting of the elements of this stream, sorted according to the provided Comparator.

 

For example,

a. Below snippet converts list of integers in ascending order.

List<Integer> ascendingOrderItems = items.stream().sorted().collect(Collectors.toList());

                 

b. Below snippet converts list of integers in descending order.

List<Integer> descendingOrderItems = items.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());

 

Find the below working application.

 

App.java

package com.sample.app;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class App {

	public static void main(String args[]) {
		List<Integer> items = new ArrayList<>(Arrays.asList(1, 34, 2, 45, 6, 3, 10, 45));
		
		List<Integer> ascendingOrderItems = items.stream().sorted().collect(Collectors.toList());
		List<Integer> descendingOrderItems = items.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
		
		System.out.println(items);
		System.out.println(ascendingOrderItems);
		System.out.println(descendingOrderItems);
	}
}

Output

[1, 34, 2, 45, 6, 3, 10, 45]

[1, 2, 3, 6, 10, 34, 45, 45]

[45, 45, 34, 10, 6, 3, 2, 1]

 

How to sort custom objects?

To use the sort() method, custom class must implement Comparable interface.

 

Employee.java

package com.sample.app.model;

public class Employee implements Comparable<Employee> {

	private Integer id;
	private String firstName;
	private String lastName;

	public Employee(Integer id, String firstName, String lastName) {
		super();
		this.id = id;
		this.firstName = firstName;
		this.lastName = lastName;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
	}

	@Override
	public int compareTo(Employee emp) {
		return this.id.compareTo(emp.getId());
	}

}

As you see the definition of Employee class, I implemented the comparison (compareTo method) using employee id.

 

Following snippet sort the employees in the ascending order of their ids.

List<Employee> ascendingOrderById = emps.stream().sorted().collect(Collectors.toList());

 

Following snippet sort the employees in the ascending order of their ids.

List<Employee> desscendingOrderById = emps.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());

 

App.java

package com.sample.app;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import com.sample.app.model.Employee;

public class App {

	public static void main(String args[]) {
		Employee emp1 = new Employee(123, "Ram", "Gurram");
		Employee emp2 = new Employee(1, "Gopi", "Battu");
		Employee emp3 = new Employee(23, "Bala", "Murugan");
		Employee emp4 = new Employee(15, "Abhishek", "Gupta");
		Employee emp5 = new Employee(11, "Anand", "Bandaru");
		
		List<Employee> emps = Arrays.asList(emp1, emp2, emp3, emp4, emp5);
		
		List<Employee> ascendingOrderById = emps.stream().sorted().collect(Collectors.toList());
		List<Employee> desscendingOrderById = emps.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
		
		System.out.println(emps + "\n");
		System.out.println(ascendingOrderById + "\n");
		System.out.println(desscendingOrderById);
	}
}

Output

[Employee [id=123, firstName=Ram, lastName=Gurram], Employee [id=1, firstName=Gopi, lastName=Battu], Employee [id=23, firstName=Bala, lastName=Murugan], Employee [id=15, firstName=Abhishek, lastName=Gupta], Employee [id=11, firstName=Anand, lastName=Bandaru]]

[Employee [id=1, firstName=Gopi, lastName=Battu], Employee [id=11, firstName=Anand, lastName=Bandaru], Employee [id=15, firstName=Abhishek, lastName=Gupta], Employee [id=23, firstName=Bala, lastName=Murugan], Employee [id=123, firstName=Ram, lastName=Gurram]]

[Employee [id=123, firstName=Ram, lastName=Gurram], Employee [id=23, firstName=Bala, lastName=Murugan], Employee [id=15, firstName=Abhishek, lastName=Gupta], Employee [id=11, firstName=Anand, lastName=Bandaru], Employee [id=1, firstName=Gopi, lastName=Battu]]

We can even provide custom comparators.

 

Below snippet sort the employees by their firstName.

List<Employee> ascendingOrderByFirstName = emps.stream()

                                    .sorted((e1, e2) -> e1.getFirstName()

                                    .compareTo(e2.getFirstName()))

                                    .collect(Collectors.toList());

                 

Below snippet sort the employees by their lastName.

List<Employee> ascendingOrderByLastName = emps.stream()

                                    .sorted((e1, e2) -> e1.getLastName()

                                    .compareTo(e2.getLastName()))

                                    .collect(Collectors.toList());

 

Find the below working application.

 

App.java

package com.sample.app;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.sample.app.model.Employee;

public class App {

	public static void main(String args[]) {
		Employee emp1 = new Employee(123, "Ram", "Gurram");
		Employee emp2 = new Employee(1, "Gopi", "Battu");
		Employee emp3 = new Employee(23, "Bala", "Murugan");
		Employee emp4 = new Employee(15, "Abhishek", "Gupta");
		Employee emp5 = new Employee(11, "Anand", "Bandaru");

		List<Employee> emps = Arrays.asList(emp1, emp2, emp3, emp4, emp5);

		List<Employee> ascendingOrderByFirstName = emps.stream()
				.sorted((e1, e2) -> e1.getFirstName()
				.compareTo(e2.getFirstName()))
				.collect(Collectors.toList());
		
		List<Employee> ascendingOrderByLastName = emps.stream()
				.sorted((e1, e2) -> e1.getLastName()
				.compareTo(e2.getLastName()))
				.collect(Collectors.toList());

		System.out.println(emps + "\n");
		System.out.println(ascendingOrderByFirstName + "\n");
		System.out.println(ascendingOrderByLastName);
	}
}

Output

[Employee [id=123, firstName=Ram, lastName=Gurram], Employee [id=1, firstName=Gopi, lastName=Battu], Employee [id=23, firstName=Bala, lastName=Murugan], Employee [id=15, firstName=Abhishek, lastName=Gupta], Employee [id=11, firstName=Anand, lastName=Bandaru]]

[Employee [id=15, firstName=Abhishek, lastName=Gupta], Employee [id=11, firstName=Anand, lastName=Bandaru], Employee [id=23, firstName=Bala, lastName=Murugan], Employee [id=1, firstName=Gopi, lastName=Battu], Employee [id=123, firstName=Ram, lastName=Gurram]]

[Employee [id=11, firstName=Anand, lastName=Bandaru], Employee [id=1, firstName=Gopi, lastName=Battu], Employee [id=15, firstName=Abhishek, lastName=Gupta], Employee [id=123, firstName=Ram, lastName=Gurram], Employee [id=23, firstName=Bala, lastName=Murugan]]



Previous                                                    Next                                                    Home

Initial heap size set to a larger value than the maximum heap size

 What is heap?

Heap is a portion of memory where dynamic allocation and deallocations happen.

 

Can I set minimum and maximum heap sizes to my java application?

Yes, you can set using the options -Xms, -Xmx.

 

Option

Description

-Xms

Set initial and minimum heap size

-Xmx

Set maximum heap size

 

Syntax

-Xms<size>[g|G|m|M|k|K]

-Xmx<size>[g|G|m|M|k|K]

 

Example

java -Xms1g -Xmx2g App

 

Above statement sets minimum heap size to 1Gb and maximum to 2Gb.

 

Error ‘Initial heap size set to a larger value than the maximum heap size’ occurs when you set minimum heap size values is set more than maximum heap size.

 

Example

java -Xms2g -Xmx1g App

 

As you see above statement, I set the minimum heap size to 2Gb and maximum heap size to 1Gb. This is completely wrong setting, minimum size should always less than maximum size..

 

App.java

public class App {

	public static void main(String args[]) {
		System.out.println("Hello World");
	}
}

Compile and run the above program, you will get the error ‘Initial heap size set to a larger value than the maximum heap size‘.

$javac App.java
$
$java -Xms2g -Xmx1g HelloWorld
Error occurred during initialization of VM
Initial heap size set to a larger value than the maximum heap size

How to resolve this error?

Set the minimum heap size always less than the maximum heap size.

 

$java -Xms1g -Xmx2g App

Hello World


You may like?

NumberFormatException Explained

 NumberForamtException is thrown when you try to convert a string to numeric type, but the string is in inappropriate format to convert to the numeral.

 

Signature

public class NumberFormatException extends IllegalArgumentException{

        

}

 

Example

Integer.parseInt() method throws NumberFormatException, when you try to convert an incompatible string to an integer.

 

App.java

package com.sample.app;

public class App {

	public static void main(String args[]) {
		try {
			Integer.parseInt("abcd");
		}catch(NumberFormatException e) {
			e.printStackTrace();
		}
	}
}

Output

java.lang.NumberFormatException: For input string: "abcd"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Integer.parseInt(Integer.java:615)
	at com.sample.app.App.main(App.java:7)

Following are some of the core java methods that throw NumberFOrmatException.

 

javax.xml.bind.DatatypeConverterImpl._parseFloat(CharSequence)

javax.xml.bind.DatatypeConverterImpl._parseFloat(CharSequence)

java.math.BigDecimal.BigDecimal(char[], int, int, MathContext)

java.math.BigDecimal.parseExp(char[], int, int)

javax.xml.bind.DatatypeConverterImpl.removeOptionalPlus(CharSequence)

javax.xml.bind.DatatypeConverterImpl.removeOptionalPlus(CharSequence)

java.lang.NumberFormatException.NumberFormatException(String)

java.lang.NumberFormatException.NumberFormatException()

java.lang.NumberFormatException.NumberFormatException(String)

javax.xml.bind.DatatypeConverterImpl._parseDouble(CharSequence)

javax.xml.bind.DatatypeConverterImpl._parseDouble(CharSequence)

javax.xml.bind.DatatypeConverterImpl._parseInt(CharSequence)

javax.xml.bind.DatatypeConverterImpl._parseInt(CharSequence)

java.math.BigDecimal.adjustScale(int, long)

java.math.BigDecimal.BigDecimal(char[], int, int, MathContext)

java.math.BigDecimal.BigDecimal(double, MathContext)

java.math.BigInteger.BigInteger(byte[])

java.math.BigInteger.BigInteger(int, byte[])

java.math.BigInteger.BigInteger(int, int[])

java.math.BigInteger.BigInteger(int[])

java.math.BigInteger.BigInteger(String, int)

java.lang.Byte.decode(String)

java.lang.Long.decode(String)

java.lang.Short.decode(String)

java.lang.NumberFormatException.forInputString(String)

java.lang.Package.isCompatibleWith(String)

java.lang.Byte.parseByte(String, int)

java.math.BigInteger.parseInt(char[], int, int)

java.lang.Integer.parseInt(String, int)

java.lang.Long.parseLong(String, int)

java.lang.Short.parseShort(String, int)

java.lang.Integer.parseUnsignedInt(String, int)

java.lang.Long.parseUnsignedLong(String, int)

 

Possible Causes of NumberFormatException

a. Trying to convert non-numeric string to an integer.

 

App.java

package com.sample.app;

public class App {

	public static void main(String args[]) {
		try {
			Integer.parseInt("abcd");
		}catch(NumberFormatException e) {
			e.printStackTrace();
		}
		
		System.out.println();
		
		try {
			Double.parseDouble("abcd");
		}catch(NumberFormatException e) {
			e.printStackTrace();
		}
		
		System.out.println();
		
		try {
			Float.parseFloat("abcd");
		}catch(NumberFormatException e) {
			e.printStackTrace();
		}
	}
}

Output

java.lang.NumberFormatException: For input string: "abcd"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Integer.parseInt(Integer.java:615)
	at com.sample.app.App.main(App.java:7)

java.lang.NumberFormatException: For input string: "abcd"
	at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
	at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
	at java.lang.Double.parseDouble(Double.java:538)
	at com.sample.app.App.main(App.java:15)

java.lang.NumberFormatException: For input string: "abcd"
	at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
	at sun.misc.FloatingDecimal.parseFloat(FloatingDecimal.java:122)
	at java.lang.Float.parseFloat(Float.java:451)
	at com.sample.app.App.main(App.java:23)

b. Initializing numeric wrapper classes with non-numeric data

Example

Integer i = new Integer("abcd");

Double d = new Double("abcd");

 

App.java

package com.sample.app;

public class App {

	public static void main(String args[]) {
		try {
			new Integer("abcd");
		}catch(NumberFormatException e) {
			e.printStackTrace();
		}
		
		System.out.println();
		
		try {
			new Double("abcd");
		}catch(NumberFormatException e) {
			e.printStackTrace();
		}
		
		System.out.println();
		
		try {
			new Float("abcd");
		}catch(NumberFormatException e) {
			e.printStackTrace();
		}
	}
}

Output

java.lang.NumberFormatException: For input string: "abcd"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Integer.<init>(Integer.java:867)
	at com.sample.app.App.main(App.java:7)

java.lang.NumberFormatException: For input string: "abcd"
	at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
	at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
	at java.lang.Double.parseDouble(Double.java:538)
	at java.lang.Double.<init>(Double.java:608)
	at com.sample.app.App.main(App.java:15)

java.lang.NumberFormatException: For input string: "abcd"
	at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
	at sun.misc.FloatingDecimal.parseFloat(FloatingDecimal.java:122)
	at java.lang.Float.parseFloat(Float.java:451)
	at java.lang.Float.<init>(Float.java:532)
	at com.sample.app.App.main(App.java:23)

c. Passing out of range values

Example

Integer i = Integer.parseInt("1111111111111111");

 

App.java

package com.sample.app;

public class App {

	public static void main(String args[]) {
		try {
			Integer.parseInt("1111111111111111");
		}catch(NumberFormatException e) {
			e.printStackTrace();
		}
		
	}
}

Output

java.lang.NumberFormatException: For input string: "1111111111111111"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:583)
	at java.lang.Integer.parseInt(Integer.java:615)
	at com.sample.app.App.main(App.java:7)

Reference

https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/NumberFormatException.html


You may like

      Interview Questions
      How to initialize string array?
      junit: How to test System.exit
      Split ArrayList to multiple List chunks
       Implement re-try-catch
      Split comma separated string to list of strings





Gson: Converting integers to doubles

 Recently I faced this problem. I have data in the below format.

[{

         "a": 1,

         "b": 2

}, {

         "c": 3,

         "d": 4

}]

 

When I am trying to convert the above data to ‘List<Map<String, Object>>’, gson converting integers to real values like below.

 

[{

         "a": 1.0,

         "b": 2.0

}, {

         "c": 3.0,

         "d": 4.0

}]

 

As you observe above snippet, 1 is converted to 1.0, 2 is converted to 2.0 etc.,

 

App.java

package com.sample.app.util;

import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class App {
	public static void main(String args[]) {
		String json = "[{\"a\":1,\"b\":2},{\"c\":3,\"d\":4}]";

		Gson gson = new Gson();

		List<Map<String, Object>> list = gson.fromJson(json, new TypeToken<List<Map<String, Object>>>() {
		}.getType());
		for (Map<String, Object> item : list) {
			System.out.println(item);
		}

	}
}

Output

{a=1.0, b=2.0}

{c=3.0, d=4.0}

 

Root cause of this behavior?

https://github.com/google/gson/blob/master/gson/src/main/java/com/google/gson/internal/bind/ObjectTypeAdapter.java

 

read() method in ObjectTypeAdapter class is implemented like below.

public Object read(JsonReader in) throws IOException {
    JsonToken token = in.peek();
    switch (token) {
    case BEGIN_ARRAY:
    	......

    case NUMBER:
      return in.nextDouble();
	  	......
    }
  }

As you see above snippet, when a token is of type NUMBER encountered, it is converted to double by default.

 

How to resolve the above problem?

Create a custom deserializer that handles number type correctly.

 

DoubleToIntDeserializer.java

package com.sample.app.util;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.internal.LinkedTreeMap;

public class DoubleToIntDeserializer implements JsonDeserializer<Map<String, Object>> {

	@Override
	@SuppressWarnings("unchecked")
	public Map<String, Object> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
			throws JsonParseException {
		return (Map<String, Object>) read(json);
	}

	public Object read(JsonElement jsonElement) {

		if (jsonElement.isJsonArray()) {
			List<Object> list = new ArrayList<Object>();
			JsonArray jsonArray = jsonElement.getAsJsonArray();
			for (JsonElement anArr : jsonArray) {
				list.add(read(anArr));
			}
			return list;
		}

		if (jsonElement.isJsonObject()) {
			Map<String, Object> map = new LinkedTreeMap<String, Object>();
			JsonObject jsonObject = jsonElement.getAsJsonObject();
			Set<Map.Entry<String, JsonElement>> entitySet = jsonObject.entrySet();
			for (Map.Entry<String, JsonElement> entry : entitySet) {
				map.put(entry.getKey(), read(entry.getValue()));
			}
			return map;
		}

		if (jsonElement.isJsonPrimitive()) {
			JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();
			if (jsonPrimitive.isBoolean()) {
				return jsonPrimitive.getAsBoolean();
			}

			if (jsonPrimitive.isString()) {
				return jsonPrimitive.getAsString();
			}

			if (jsonPrimitive.isNumber()) {

				Number num = jsonPrimitive.getAsNumber();

				if (Math.ceil(num.doubleValue()) == num.longValue())
					return num.longValue();

				return num.doubleValue();

			}
		}

		return null;
	}

}

Build Gson instance using this deserializer.

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(new TypeToken<Map<String, Object>>() {}.getType(), new DoubleToIntDeserializer());
Gson gson = gsonBuilder.create();

App.java

package com.sample.app.util;

import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public class App {
	public static void main(String args[]) {
		String json = "[{\"a\":1,\"b\":2},{\"c\":3,\"d\":4}]";

		GsonBuilder gsonBuilder = new GsonBuilder();
		
		gsonBuilder.registerTypeAdapter(new TypeToken<Map<String, Object>>() {
		}.getType(), new DoubleToIntDeserializer());

		Gson gson = gsonBuilder.create();

		List<Map<String, Object>> list = gson.fromJson(json, new TypeToken<List<Map<String, Object>>>() {
		}.getType());
		for (Map<String, Object> item : list) {
			System.out.println(item);
		}

	}
}

Output

{a=1, b=2}

{c=3, d=4}



Previous                                                    Next                                                    Home

Docker and Kubernetes

Docker Basics

Kubernetes Basics

Kuberentes: Troubleshooting the application

 Using kubectl describe command

Using ‘kubectl describe’ command, you can get detailed information about pods, deployments.

Let’s create a deployment.

kubectl create deployment hello-node --image=jboss/wildfly

$kubectl create deployment hello-node --image=jboss/wildfly
deployment.apps/hello-node created

Get the deployments.

$kubectl get deployments
NAME         READY   UP-TO-DATE   AVAILABLE   AGE
hello-node   1/1     1            1           22s

Use below command to describe the deployment hello-node.

kubectl describe deployment/hello-node

 

Get the pods.

$kubectl get pods
NAME                         READY   STATUS    RESTARTS   AGE
hello-node-59fddbb58-lnh7v   1/1     Running   0          81s

Describe the pod

kubectl describe pod/hello-node-59fddbb58-lnh7v

 

Checking the logs

‘kubectl logs podName’ command is used to get the logs.

 

kubectl logs hello-node-59fddbb58-lnh7v

 

Login to a specific pod

Below command is used to login to the pod.

kubectl exec -it hello-node-59fddbb58-lnh7v /bin/bash

$kubectl exec -it hello-node-59fddbb58-lnh7v /bin/bash
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl kubectl exec [POD] -- [COMMAND] instead.
[jboss@hello-node-59fddbb58-lnh7v ~]$

Once you login to the pod, you can check the log files, execute shell commands.

[jboss@hello-node-59fddbb58-lnh7v ~]$ ps -eaf 
UID        PID  PPID  C STIME TTY          TIME CMD
jboss        1     0  0 08:35 ?        00:00:00 /bin/sh /opt/jboss/wildfly/bin/standalone.sh -b 0.0.0.0
jboss       81     1  3 08:35 ?        00:00:09 /usr/lib/jvm/java/bin/java -D[Standalone] -server -Xms64m -Xmx5
jboss      195     0  0 08:38 pts/0    00:00:00 /bin/bash
jboss      214   195  0 08:39 pts/0    00:00:00 ps -eaf





Previous                                                    Next                                                    Home

Kubernetes: Application upgrades

 In this post, I am going to explain how can we handle application upgrades.

a.   Deploy the image tomcat:8.5.54-jdk11

b.   Upgrade it to the image tomcat:9-jdk14-openjdk-oracle

c.    Rollback to the previous version of tomcat.

 

Deploy the image tomcat:8.5.54-jdk11

Create a deployment using tomcat image ‘tomcat:8.5.54-jdk11’

$kubectl create deployment tomcat --image=tomcat:8.5.54-jdk11
deployment.apps/tomcat created

Check the pods.

$kubectl get pods
NAME                      READY   STATUS    RESTARTS   AGE
tomcat-6586578cf5-h687q   1/1     Running   0          102s

Expose the service.

$kubectl expose deployment tomcat --type=LoadBalancer --port=8080
service/tomcat exposed

Check the status of the service.

$kubectl get services
NAME         TYPE           CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE
kubernetes   ClusterIP      10.96.0.1       <none>        443/TCP          13m
tomcat       LoadBalancer   10.108.30.197   <pending>     8080:30602/TCP   2s

Execute the command ‘minikube service tomcat’ to open the service in web browser.

$minikube service tomcat
|-----------|--------|-------------|-----------------------------|
| NAMESPACE |  NAME  | TARGET PORT |             URL             |
|-----------|--------|-------------|-----------------------------|
| default   | tomcat |        8080 | http://192.168.99.100:30602 |
|-----------|--------|-------------|-----------------------------|
🎉  Opening service default/tomcat in default browser...

You can confirm that tomcat server version is 8.5.54.

 

Upgrade it to the image tomcat:9-jdk14-openjdk-oracle

Update the image by executing below command.

kubectl set image deployment/tomcat tomcat=tomcat:9-jdk14-openjdk-oracle

$kubectl set image deployment/tomcat tomcat=tomcat:9-jdk14-openjdk-oracle
deployment.apps/tomcat image updated

Since we upgraded to new image, you can see two result sets.

$kubectl get rs
NAME                DESIRED   CURRENT   READY   AGE
tomcat-6586578cf5   1         1         1       21m
tomcat-6746995784   1         1         0       20s

Get the pods.

$kubectl get pods
NAME                      READY   STATUS              RESTARTS   AGE
tomcat-6586578cf5-h687q   1/1     Running             0          22m
tomcat-6746995784-tmvnl   0/1     ContainerCreating   0          60s

As you see the output, pod is in ‘ContainerCreating’ state.

 

Wait for some time and query for the pods again.

$kubectl get pods
NAME                      READY   STATUS    RESTARTS   AGE
tomcat-6746995784-tmvnl   1/1     Running   0          114s

As you see the output, tomcat is in Running state now.

 

Let’s open the service in browser.

$minikube service tomcat
|-----------|--------|-------------|-----------------------------|
| NAMESPACE |  NAME  | TARGET PORT |             URL             |
|-----------|--------|-------------|-----------------------------|
| default   | tomcat |        8080 | http://192.168.99.100:30602 |
|-----------|--------|-------------|-----------------------------|
🎉  Opening service default/tomcat in default browser...


From the above image, you can confirm that tomcat is upgraded to 9.0.34.

 

Rollback to previous version

Execute below command to rollout.

kubectl rollout undo deployment/tomcat

$kubectl rollout undo deployment/tomcat
deployment.apps/tomcat rolled back




Previous                                                    Next                                                    Home