Monday, 29 May 2023

Micronaut REST API development tutorial

Micronaut: rest: Hello world application
Micronaut rest: test the hello world application
Micronaut: Customize the running port of the server
Run the Micronaut application on a random port
Micronaut: Execute the code when server completes startup
Micronaut: @PostConstruct: Execute the code post dependency injection
Micronaut: URI path variables
Supported HTTP Methods or verbs in Micronaut
Micronaut: Map multiple uris to a controller method
Micronaut: support non-standard HTTP methods
Micronaut: @Body: Bind the request body to a POJO
Micronaut: @CookieValue: bind a cookie value to method argument
Micronaut: Bind HTTP header to a method parameter
Micronaut: @QueryValue: bind the request query parameter to a method argument
Micronaut: How to make a request parameter optional in Micronaut?
Micronaut: @RequestBean: bind any bindable value to bean object
Micronaut: Upload a file as InputStream
Micronaut: bind all the query parameters to a POJO
Micronaut: bind path variables, headers and query parameters to a POJO
Micronaut: type based binding demo
Micronaut: Inject HttpRequest object
Micronaut: Inject HttpRequest using ServerRequestContext
Micronaut: Send response with status code
Micronaut: Set the http status code using @Status annotation
Micronaut: How to Send a Response Code Only?
How to Specify the MediaType Consumed by a REST API in Micronaut?
Micronaut Request Payload Validation Guide

Previous                                                    Next                                                    Home

Playwright: Get the locator by ARIA role

'page.getByRole()' method locate the elements by their ARIA role.

 

Signature

Locator getByRole(AriaRole role)
Locator getByRole(AriaRole role, GetByRoleOptions options)

 

Example

ElementHandle elementHandle = page.getByRole(AriaRole.BANNER).elementHandle();

 

Find the below working application.

 

ariaRoles.html

<html>

<head>
	<title>ARIA roles example</title>
</head>

<body>
	<h1 role="banner" id="myBanner" class="headerSection">This is page banner</h1>

	<div role="contentinfo">
		blog: https://self-learning-java-tutorial.blogspot.com/
	</div>

</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();
		}

	}
}

 

GetLocatorByAriaRoles.java

package com.sample.app.locators;

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

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

public class GetLocatorByAriaRoles {
	public static void main(String[] args) throws IOException {
		try (Playwright playwright = Playwright.create()) {

			Browser browser = playwright.chromium()
					.launch(new BrowserType.LaunchOptions().setHeadless(false).setSlowMo(100));

			final String content = FileUtil.resourceAsString("locators" + File.separator + "ariaRoles.html");

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

			ElementHandle elementHandle = page.getByRole(AriaRole.BANNER).elementHandle();

			String role = elementHandle.getAttribute("role");
			String id = elementHandle.getAttribute("id");
			String clazz = elementHandle.getAttribute("class");

			System.out.println("role : " + role);
			System.out.println("id : " + id);
			System.out.println("class : " + clazz);
		}
	}
}

 

Output

role : banner
id : myBanner
class : headerSection

 

 

 

Previous                                                 Next                                                 Home

PlantUML: add label to a relation in class diagram

We can add label on a relation using : followed by a label text.

 

Example

Human *-- Brain : contains

 

addLabel.txt

@startuml

title "Class Composition"

class Human

Class Brain
class Lungs
class Liver
class Heart
class Stomach
class Kidney
class Bladder

class Frontal
class Parietal
class Temporal
class Occipital

Human *-- Brain : contains
Human *-- Lungs : contains
Human *-- Liver : contains
Human *-- Heart : contains
Human *-- Stomach : contains
Human *-- Kidney : contains
Human *-- Bladder : contains

Brain *-- Frontal : contains
Brain *-- Parietal : contains
Brain *-- Temporal : contains
Brain *-- Occipital : contains

@enduml

 

Above snippet generate below diagram.

 


 

Previous                                                    Next                                                    Home

Convert a string to boolean in Python

Using bool() method, we can convert a string to boolean in Python.

 

Example

bool_val = bool(input_str)

string_to_boolean.py

input_str = input('Enter a string ')
print('input_str : ', input_str, " type : ", type(input_str))

bool_val = bool(input_str)
print('bool_val : ', bool_val)

Output

Enter a string hello
input_str :  hello  type :  <class 'str'>
bool_val :  True

Following rules are followed while considering a value as True in Python.

 

a.   Any non-zero numeric value is considered as True. 0, 0.0 are evaluated to False

b.   Nom empty strings, dictionaries, lists, tuples, sets is considered as True. Empty strings (""), empty lists ([]), empty tuples (()) and empty sets ({}) are evaluated as False.

c.    Special value ‘None’ is considered as False

d.   Boolean True is considered as True, and False is considered as False.

 

bool_values.py

print("Following values evaluated to True")
print('bool("True") : ', bool("True"))
print('bool("false") : ', bool("false"))
print('bool("False") : ', bool("False"))
print('bool("Yes") : ', bool("Yes"))
print('bool("No") : ', bool("No"))
print('bool("0") : ', bool("0"))
print('bool("0.0") : ', bool("0.0"))
print('bool("1") : ', bool("1"))
print('bool([2, 3]) : ', bool([2, 3]))
print('bool({"id" : 1}) : ', bool({"id":1}))
print('bool(True) : ', bool(True))

print("\nFollowing values evaluated to False")
print('bool(0) : ', bool(0))
print('bool(0.0) : ', bool(0.0))
print('bool([]) : ', bool([]))
print('bool({}) : ', bool({}))
print('bool(()) : ', bool(()))
print('bool(set()) : ', bool(set()))
print('bool(None) : ', bool(None))
print('bool(False) : ', bool(False))

Output

Following values evaluated to True
bool("True") :  True
bool("false") :  True
bool("False") :  True
bool("Yes") :  True
bool("No") :  True
bool("0") :  True
bool("0.0") :  True
bool("1") :  True
bool([2, 3]) :  True
bool({"id" : 1}) :  True
bool(True) :  True

Following values evaluated to False
bool(0) :  False
bool(0.0) :  False
bool([]) :  False
bool({}) :  False
bool(()) :  False
bool(set()) :  False
bool(None) :  False
bool(False) :  False



 

Previous                                                 Next                                                 Home

Convert a string to float in Python

Using float() function, you can convert a string to a float in Python.

 

Example

float_var = float(input_str)

 

float_to_int.py

input_str = input('Enter a string ')
print('input_str : ', input_str, " type : ", type(input_str))

float_var = float(input_str)
print('float_var : ', float_var, " type : ", type(float_var))

 

Output

Enter a string 12.34
input_str :  12.34  type :  <class 'str'>
float_var :  12.34  type :  <class 'float'>

 

If the input_str contains any non-numeric characters, you will endup in ValueError like below.

Enter a string 12.aw2
input_str :  12.aw2  type :  <class 'str'>
Traceback (most recent call last):
  File "/Users/Shared/PycharmProjects/python/python-core/1.introduction/string_to_float.py", line 4, in <module>
    float_var = float(input_str)
ValueError: could not convert string to float: '12.aw2'

Process finished with exit code 1

We can handle above error situations using try-except block.


string_to_float.py

input_str = input('Enter a string ')
print('input_str : ', input_str, " type : ", type(input_str))

try:
    float_var = float(input_str)
    print('float_var : ', float_var, " type : ", type(float_var))
except ValueError as ve:
    print("input string contain non numeric characters. error : ", ve)

Output

Enter a string 12.aw2
input_str :  12.aw2  type :  <class 'str'>
input string contain non numeric characters. error :  could not convert string to float: '12.aw2'



Previous                                                 Next                                                 Home

Convert a string to integer in Python

Using int() function, you can convert a string to an integer in Python.

 

Example

int_var = int(input_str)

 

string_to_int.py

input_str = input('Enter a string ')
print('input_str : ', input_str, " type : ", type(input_str))

int_var = int(input_str)
print('int_var : ', int_var, " type : ", type(int_var))

Output

Enter a string 12345
input_str :  12345  type :  <class 'str'>
int_var :  12345  type :  <class 'int'>

If the input_str contains any non-numeric characters, you will endup in ValueError like below.

Enter a string hello
input_str :  hello  type :  <class 'str'>
Traceback (most recent call last):
  File "/Users/Shared/PycharmProjects/python/python-core/1.introduction/string_to_int.py", line 4, in <module>
    int_var = int(input_str)
ValueError: invalid literal for int() with base 10: 'hello'

We can handle above error situations using try-except block.

 


string_to_int.py

input_str = input('Enter a string ')
print('input_str : ', input_str, " type : ", type(input_str))

try:
    int_var = int(input_str)
    print('int_var : ', int_var, " type : ", type(int_var))
except ValueError as ve:
    print("input string contain non numeric characters. error : ", ve)

Output

Enter a string hello
input_str :  hello  type :  <class 'str'>
input string contain non numeric characters. error :  invalid literal for int() with base 10: 'hello'




Previous                                                 Next                                                 Home