Tuesday, 7 March 2023

How to get all the enum values in Java?

In this post, I am going to explain how to get all the enum values in Java.

 

Approach 1: Using EnumSet.allOf method.

‘EnumSet.allOf ‘ method return an enum set containing all of the elements in the specified element type.

Set<AppState> appStates = EnumSet.allOf(AppState.class);

Approach 2: Using Class#getEnumConstants method.

Class#getEnumConstants() method return all the elements of this enum class or null if this Class object does not represent an enum type.

AppState[] appStatesArr = AppState.class.getEnumConstants();
for(AppState appState: appStatesArr) {
	System.out.println(appState);
}

 

Approach 3: Using EnumClass.values() method.

AppState[] appStatesArr = AppState.values();
for(AppState appState: appStatesArr) {
	System.out.println(appState);
}

 

Find the below working application.

 

EnumValuesDemo.java

 

package com.sample.app;

import java.util.EnumSet;
import java.util.Set;

public class EnumValuesDemo {
	private static enum AppState {
		INIT, READY, RUNNING, ABORT;
	}

	public static void main(String[] args) {

		Set<AppState> appStates = EnumSet.allOf(AppState.class);
		System.out.println(appStates + "\n");

		AppState[] appStatesArr = AppState.class.getEnumConstants();
		for (AppState appState : appStatesArr) {
			System.out.println(appState);
		}
		System.out.println();

		appStatesArr = AppState.values();
		for (AppState appState : appStatesArr) {
			System.out.println(appState);
		}
		System.out.println();

	}

}

 

Output

[INIT, READY, RUNNING, ABORT]

INIT
READY
RUNNING
ABORT

INIT
READY
RUNNING
ABORT

 



You may like

Interview Questions

Constant folding in Java

Quick guide to assertions in Java

java.util.Date vs java.sql.Date

How to break out of nested loops in Java?

Implementation of Bag data structure in Java

Scanner throws java.util.NoSuchElementException while reading the input

Monday, 6 March 2023

Scanner throws java.util.NoSuchElementException while reading the input

While reading the input using Scanner, I stuck with below error.

Exception in thread "main" java.util.NoSuchElementException
	at java.util.Scanner.throwFor(Scanner.java:862)
	at java.util.Scanner.next(Scanner.java:1485)
	at java.util.Scanner.nextInt(Scanner.java:2117)
	at java.util.Scanner.nextInt(Scanner.java:2076)
	at com.sample.app.ScannerDemo.main(ScannerDemo.java:11)

 

My code snippet looks like below.

 

ScannerDemo.java
package com.sample.app;

import java.util.Scanner;

public class ScannerDemo {

	public static void main(String[] args) {
		while (true) {
			try (Scanner scanner = new Scanner(System.in)) {
				System.out.println("Enter a number");
				int userInput = scanner.nextInt();
				System.out.println("User entered : " + userInput);

				System.out.println("Enter non zero to continue and 0 to exit");

				userInput = scanner.nextInt();
				if (0 == userInput) {
					System.exit(0);
				}

			}
		}

	}

}

 

Sample Output

Enter a number
123
User entered : 123
Enter non zero to continue and 0 to exit
1
Enter a number
Exception in thread "main" java.util.NoSuchElementException
	at java.util.Scanner.throwFor(Scanner.java:862)
	at java.util.Scanner.next(Scanner.java:1485)
	at java.util.Scanner.nextInt(Scanner.java:2117)
	at java.util.Scanner.nextInt(Scanner.java:2076)
	at com.sample.app.ScannerDemo.main(ScannerDemo.java:11)

 

Root cause

After some analysis, I figured out there is a problem in using try-with-resource statement. try-with-resource statement close the scanner instance automatically when the scanner went out of scope. When the scanner#close is initiated, it internally close the System.in input stream as well.

 

I verified the same using below statement.

System.out.println("Is the input stream available ?" + System.in.available());

ScannerDemo.java

package com.sample.app;

import java.io.IOException;
import java.util.Scanner;

public class ScannerDemo {

	public static void main(String[] args) throws IOException {
		while (true) {
			try (Scanner scanner = new Scanner(System.in)) {
				System.out.println("Is the input stream available ?" + System.in.available());

				System.out.println("Enter a number");
				int userInput = scanner.nextInt();
				System.out.println("User entered : " + userInput);

				System.out.println("Enter non zero to continue and 0 to exit");

				userInput = scanner.nextInt();
				if (0 == userInput) {
					System.exit(0);
				}

			}

			System.out.println("Is the input stream available ?" + System.in.available());
		}

	}

}

Sample Output

Is the input stream available ?0
Enter a number
123
User entered : 123
Enter non zero to continue and 0 to exit
1
Exception in thread "main" java.io.IOException: Stream closed
	at java.io.BufferedInputStream.getInIfOpen(BufferedInputStream.java:159)
	at java.io.BufferedInputStream.available(BufferedInputStream.java:410)
	at com.sample.app.ScannerDemo.main(ScannerDemo.java:26)

How I resolved the problem?

Do not close the Scanner, as long as you need to work with it.

 

ScannerDemo.java

package com.sample.app;

import java.io.IOException;
import java.util.Scanner;

public class ScannerDemo {

	public static void main(String[] args) throws IOException {
		try (Scanner scanner = new Scanner(System.in)) {
			while (true) {

				System.out.println("Enter a number");
				int userInput = scanner.nextInt();
				System.out.println("User entered : " + userInput);

				System.out.println("Enter non zero to continue and 0 to exit");

				userInput = scanner.nextInt();
				if (0 == userInput) {
					System.exit(0);
				}

			}

		}

	}

}

Sample Output

Enter a number
123
User entered : 123
Enter non zero to continue and 0 to exit
1
Enter a number
124
User entered : 124
Enter non zero to continue and 0 to exit
1
Enter a number
125
User entered : 125
Enter non zero to continue and 0 to exit
0


 

You may like

Interview Questions

Quick guide to load balancers

Constant folding in Java

Quick guide to assertions in Java

java.util.Date vs java.sql.Date

How to break out of nested loops in Java?

Implementation of Bag data structure in Java

Playwright: press(): working with keyboard events

There are three keyboard events in JavaScript.

 

a.   keydown: Key down event is fired whenever a key is pressed and it keep on firing as long as we are holding the key down. Keydown event is fired for all the keys.

b.   keyup: Key up event is fired whenever a key is released.

c.    keypress: key press event is fired whenever a key is pressed. Unlike keydown event it is not fired for special keys like alt, tab etc.,

 

keydown vs keypress

 

a.   If you press any special key, browser will fire only key down event, not the keypress event.

b.   The keydown provide a code indicating which key is pressed, while keypress indicates which character was entered.

For example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress. An uppercase "A" is reported as 65 by all events.

 

Locator.press method

Locator.press() method produce a single key stroke on the selected element.

 

Example

page.locator("#demoInputField").press("A");

All the keyboard shortcuts like shift, ctrl, esc are supported.

 

Example

page.locator("#demoInputField").press("Shift+A");
page.locator("#demoInputField").press("Meta");
page.locator("#demoInputField").press("Control");
page.locator("#demoInputField").press("Alt");
page.locator("#demoInputField").press("CapsLock");
page.locator("#demoInputField").press("Escape");

page.locator("#demoInputField").press("Shift+ArrowLeft");
page.locator("#demoInputField").press("Shift+ArrowRight");
page.locator("#demoInputField").press("Shift+ArrowUp");
page.locator("#demoInputField").press("Shift+ArrowDown");

Find the below working application.

 

keyEvents.html

<!DOCTYPE html>
<html>

<body>

	<p>Type any key in the text box to see the key event demos</p>

	Type something here: <input id="demoInputField" />

	<p id="result"></p>

	<script>
		document.getElementById("demoInputField").addEventListener('keydown', (event) => {
			var name = event.key;
			var code = event.code;
			document.getElementById("result").innerHTML += `Key down '${name}', Key code value: '${code}',<br />\n`;
		}, false);

		document.getElementById("demoInputField").addEventListener('keyup', (event) => {
			var name = event.key;
			var code = event.code;
			document.getElementById("result").innerHTML += `Key up '${name}', Key code value: '${code}'<br />\n`;
		}, false);

		document.getElementById("demoInputField").addEventListener('keypress', (event) => {
			var name = event.key;
			var code = event.code;
			document.getElementById("result").innerHTML += `Key press '${name}', Key code value: '${code}'<br />\n`;
		}, false);

	</script>


</body>

</html>

FileUtil.java

package com.sample.app.util;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class FileUtil {

	public static String resourceAsString(String resourceName) throws IOException {
		ClassLoader classLoader = FileUtil.class.getClassLoader();
		URL url = classLoader.getResource(resourceName);
		if (url == null) {
			return null;
		}

		URLConnection urlConnection = url.openConnection();

		urlConnection.setUseCaches(false);

		try (InputStreamReader inputStreamReader = new InputStreamReader(urlConnection.getInputStream())) {
			char[] buffer = new char[1048];
			StringBuilder builder = new StringBuilder();

			int count = -1;
			while ((count = inputStreamReader.read(buffer, 0, buffer.length)) != -1) {
				builder.append(buffer, 0, count);
			}

			return builder.toString();
		}

	}
}

KeyboardEvents.java

package com.sample.app.actions;

import java.io.File;
import java.io.IOException;

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import com.sample.app.util.FileUtil;

public class KeyboardEvents {
	public static void main(String[] args) throws IOException, InterruptedException {
		try (Playwright playwright = Playwright.create()) {
			Browser browser = playwright.chromium()
					.launch(new BrowserType.LaunchOptions().setHeadless(false).setSlowMo(100));
			final String content = FileUtil.resourceAsString("actions" + File.separator + "keyEvents.html");

			Page page = browser.newPage();
			page.setContent(content);

			page.locator("#demoInputField").press("A");
			page.locator("#demoInputField").press("a");
			page.locator("#demoInputField").press("$");

			// Following modification shortcuts are also supported: Shift, Control, Alt,
			// Meta
			page.locator("#demoInputField").press("Shift+A");
			page.locator("#demoInputField").press("Meta");
			page.locator("#demoInputField").press("Control");
			page.locator("#demoInputField").press("Alt");
			page.locator("#demoInputField").press("CapsLock");
			page.locator("#demoInputField").press("Escape");

			page.locator("#demoInputField").press("Shift+ArrowLeft");
			page.locator("#demoInputField").press("Shift+ArrowRight");
			page.locator("#demoInputField").press("Shift+ArrowUp");
			page.locator("#demoInputField").press("Shift+ArrowDown");

			String result = page.locator("#result").textContent();
			System.out.println(result);

		}
	}

}

Output

Key down 'A', Key code value: 'KeyA',
Key press 'A', Key code value: 'KeyA'
Key up 'A', Key code value: 'KeyA'
Key down 'a', Key code value: 'KeyA',
Key press 'a', Key code value: 'KeyA'
Key up 'a', Key code value: 'KeyA'
Key down '$', Key code value: 'Digit4',
Key press '$', Key code value: 'Digit4'
Key up '$', Key code value: 'Digit4'
Key down 'Shift', Key code value: 'ShiftLeft',
Key down 'A', Key code value: 'KeyA',
Key press 'A', Key code value: 'KeyA'
Key up 'A', Key code value: 'KeyA'
Key up 'Shift', Key code value: 'ShiftLeft'
Key down 'Meta', Key code value: 'MetaLeft',
Key up 'Meta', Key code value: 'MetaLeft'
Key down 'Control', Key code value: 'ControlLeft',
Key up 'Control', Key code value: 'ControlLeft'
Key down 'Alt', Key code value: 'AltLeft',
Key up 'Alt', Key code value: 'AltLeft'
Key down 'CapsLock', Key code value: 'CapsLock',
Key up 'CapsLock', Key code value: 'CapsLock'
Key up 'Escape', Key code value: 'Escape'
Key down 'Escape', Key code value: 'Escape',
Key down 'Shift', Key code value: 'ShiftLeft',
Key down 'ArrowLeft', Key code value: 'ArrowLeft',
Key up 'ArrowLeft', Key code value: 'ArrowLeft'
Key up 'Shift', Key code value: 'ShiftLeft'
Key down 'Shift', Key code value: 'ShiftLeft',
Key down 'ArrowRight', Key code value: 'ArrowRight',
Key up 'ArrowRight', Key code value: 'ArrowRight'
Key up 'Shift', Key code value: 'ShiftLeft'
Key down 'Shift', Key code value: 'ShiftLeft',
Key down 'ArrowUp', Key code value: 'ArrowUp',
Key up 'ArrowUp', Key code value: 'ArrowUp'
Key up 'Shift', Key code value: 'ShiftLeft'
Key down 'Shift', Key code value: 'ShiftLeft',
Key down 'ArrowDown', Key code value: 'ArrowDown',
Key up 'ArrowDown', Key code value: 'ArrowDown'
Key up 'Shift', Key code value: 'ShiftLeft'

 

Previous                                                 Next                                                 Home

PlantUML: stereotypes in a sequence diagram

We can add stereotypes to the participants using << and >>

 

stereotype.txt

@startuml

participant clientStub <<Generated>>
participant server <<Tested>>

clientStub -> server : Send request
server -> clientStub : Send response

@enduml

Above snippet generate below diagram.


 


 

guillemet character is used to display the stereotype by default. You can disable this with below statement.

skinparam guillemet false

stereotypeDisableGuillemet.txt

@startuml

skinparam guillemet false

participant clientStub <<Generated>>
participant server <<Tested>>

clientStub -> server : Send request
server -> clientStub : Send response

@enduml

Above snippet generate below diagram.



 

Previous                                                    Next                                                    Home

Micronaut: How to import beans from other libraries?

Using @Import annotation, we can import the beans from third party libraries.

import io.micronaut.context.annotation.Import;

@Import( 
        packages = { 
                "com.sample.app",
                "com.sample.chatserver"},
        annotated = "*") 
public class App {
}

 

Previous                                                    Next                                                    Home