Tuesday, 9 November 2021

Spring Data: ArangoDB: Pagination example

Spring data supports pagination along with sorting. For example, below snippet retrieves the first 5 documents sorted by ascending order of employee age.

 

Example

Iterable<Employee> empIterable = employeeRepo.findAll(PageRequest.of(0, 5, Sort.by(Sort.Direction.ASC, "age")));

 

Follow below step-by-step procedure to build complete working application.

 

Step 1: Create new maven project ‘pagination-support-demo’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

 

<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.sample.app</groupId>
  <artifactId>pagination-support-demo</artifactId>
  <version>1</version>

  <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent -->
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.5</version>
  </parent>


  <dependencies>
    <dependency>
      <groupId>com.arangodb</groupId>
      <artifactId>arangodb-spring-boot-starter</artifactId>
      <version>2.3.3.RELEASE</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

</project>

 

Step 3: Define Employee entity class.

 

Employee.java

 

package com.sample.app.entity;

import com.arangodb.springframework.annotation.ArangoId;
import com.arangodb.springframework.annotation.Document;
import org.springframework.data.annotation.Id;

@Document("employees")
public class Employee {

  @Id // db document field: _key
  private String key;

  @ArangoId // db document field: _id
  private String arangoId;

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

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

  public String getKey() {
    return key;
  }

  public void setKey(String key) {
    this.key = key;
  }

  public String getArangoId() {
    return arangoId;
  }

  public void setArangoId(String arangoId) {
    this.arangoId = arangoId;
  }

  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;
  }

  public Integer getAge() {
    return age;
  }

  public void setAge(Integer age) {
    this.age = age;
  }

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

}

 

Step 4: Define EmployeeRepository interface.

 

EmployeeRepository.java

package com.sample.app.repository;

import com.arangodb.springframework.repository.ArangoRepository;
import com.sample.app.entity.Employee;

public interface EmployeeRepository extends ArangoRepository<Employee, String> {

}

Step 5: Define Arango db configuration class.

 

ArangoConfig.java

package com.sample.app.config;

import com.arangodb.ArangoDB;
import com.arangodb.springframework.annotation.EnableArangoRepositories;
import com.arangodb.springframework.config.ArangoConfiguration;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableArangoRepositories(basePackages = { "com.sample.app" })
public class ArangoConfig implements ArangoConfiguration {

  @Override
  public ArangoDB.Builder arango() {
    return new ArangoDB.Builder().host("localhost", 8529).user("root").password("tiger");
  }

  @Override
  public String database() {
    return "abc_org";
  }
}


Step 6: Define main application class.

 

App.java

package com.sample.app;

import java.util.Arrays;
import java.util.List;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

import com.sample.app.entity.Employee;
import com.sample.app.repository.EmployeeRepository;

@SpringBootApplication
public class App {
  public static void main(String args[]) {
    SpringApplication.run(App.class, args);
  }

  @Bean
  public CommandLineRunner demo(EmployeeRepository employeeRepo) {
    return (args) -> {
      List<Employee> emps = Arrays.asList(new Employee(1, "Ram", "Gurram", 31),
          new Employee(2, "Sundar", "Deavanagari", 32), new Employee(3, "Srinuvasa rao", "Guma", 43),
          new Employee(4, "Madhavi Latha", "Gumma", 41), new Employee(5, "Gopi", "Battu", 33),
          new Employee(6, "Sailu", "PTR", 33), new Employee(7, "Venkat", "PTR", 32));

      employeeRepo.saveAll(emps);

      Iterable<Employee> empIterable = employeeRepo
          .findAll(PageRequest.of(0, 5, Sort.by(Sort.Direction.ASC, "age")));

      for (Employee emp : empIterable) {
        System.out.println(emp);
      }
    };
  }
}


Total project structure looks like below.



Run App.java, you will see below messages in console.

Employee [id=1, firstName=Ram, lastName=Gurram, age=31]
Employee [id=2, firstName=Sundar, lastName=Deavanagari, age=32]
Employee [id=7, firstName=Venkat, lastName=PTR, age=32]
Employee [id=5, firstName=Gopi, lastName=Battu, age=33]
Employee [id=6, firstName=Sailu, lastName=PTR, age=33]


You can download complete working application from below link.

https://github.com/harikrishna553/springboot/tree/master/arangodb/pagination-support-demo

 

  

Previous                                                    Next                                                    Home

Python: issubclass: Check whether this class is subclass of other class or not

Signature

issubclass(class, classinfo)

 

This method return True if class is a subclass (direct, indirect or virtual) of classinfo, else False. A class is considered a subclass of itself.

 

issubclass_1.py

from collections import namedtuple

Employee = namedtuple("Employee", "id age name")

print('issubclass(Employee, tuple) -> ' + str(issubclass(Employee, tuple)))
print('issubclass(Employee, Employee) -> ' + str(issubclass(Employee, Employee)))
print('issubclass(Employee, list) -> ' + str(issubclass(Employee, list)))

 

Output

issubclass(Employee, tuple) -> True
issubclass(Employee, Employee) -> True
issubclass(Employee, list) -> False

 

‘classinfo’ may be a tuple of class objects. ‘issubclass(x, (A, B))’ is equivalent to issubclass(x, A) or issubclass(x, B)

 

issubclass_2.py

 

from collections import namedtuple

Employee = namedtuple("Employee", "id age name")

print('issubclass(Employee, (tuple, Employee)) -> ' + str(issubclass(Employee, (tuple, Employee))))
print('issubclass(Employee, (tuple, Employee, list)) -> ' + str(issubclass(Employee, (tuple, Employee, list))))

 

Output

issubclass(Employee, (tuple, Employee)) -> True
issubclass(Employee, (tuple, Employee, list)) -> True

 

  

Previous                                                    Next                                                    Home

FastAPI: Provide default values to the query parameter

You can provide default values to the query parameters.

 

Example

@app.get("/emps")
def emps(pageNum : int = 1, pageSize : int = 10):
    return {'received' : {'pageNum' : pageNum, 'pageSize': pageSize}}

 

In the example above, api is defined with default values of pageNum=1 and pageSize=10. When FastAPI do not receive any query parameter, it will considers default value, below table summarizes the same.

 

URL

pageNum and pageSize

http://127.0.0.1:8000/emps

{"pageNum":1,"pageSize":10}

http://127.0.0.1:8000/emps?pageNum=8

{"pageNum":8,"pageSize":10}

http://127.0.0.1:8000/emps?pageSize=8

{"pageNum":1,"pageSize":8}

http://127.0.0.1:8000/emps?pageSize=8&pageNum=7

{"pageNum":7,"pageSize":8}

 

defaultValuesToQueryParam.py

 

from fastapi import FastAPI, Path

app = FastAPI()

@app.get("/")
def home():
    return {'name' : 'Hello World app', 'version': '2.0.0'}

@app.get("/emps")
def emps(pageNum : int = 1, pageSize : int = 10):
    return {'received' : {'pageNum' : pageNum, 'pageSize': pageSize}}

 

Open terminal and execute the command ‘uvicorn defaultValuesToQueryParam:app --reload'

from fastapi import FastAPI, Path

app = FastAPI()

@app.get("/")
def home():
    return {'name' : 'Hello World app', 'version': '2.0.0'}

@app.get("/emps")
def emps(pageNum : int = 1, pageSize : int = 10):
    return {'received' : {'pageNum' : pageNum, 'pageSize': pageSize}}

 

Open the url ‘http://127.0.0.1:8000/docs’ and experiment with the api.

 


 

  

Previous                                                    Next                                                    Home

Monday, 8 November 2021

How to check the type of a variable in Java?

Using 'object.getClass().getName()' we can get type of an object.

 

TypeOfAVariable.java

package com.sample.app.classes;

import java.util.ArrayList;
import java.util.List;

public class TypeOfAVariable {
	public static void main(String args[]) {
		String str = "Hello";
		List<Integer> intList = new ArrayList<>();

		System.out.println("Type of variable str is : " + str.getClass().getName());
		System.out.println("Type of variable intList is : " + intList.getClass().getName());
	}

}

 

One drawback of above approach is, it will not work for primitive types. You can use below utility class to get the type of primitive types along with reference types.

 

TypeUtil.java

package com.sample.app.classes;

public class TypeUtil {

	public static String typeName(byte b) {
		return "byte";
	}

	public static String typeName(short s) {
		return "short";
	}

	public static String typeName(int i) {
		return "int";
	}

	public static String typeName(long l) {
		return "long";
	}

	public static String typeName(float f) {
		return "float";
	}

	public static String typeName(double d) {
		return "double";
	}

	public static String typeName(char ch) {
		return "char";
	}

	public static String typeName(boolean b) {
		return "boolean";
	}

	public static String typeName(Object obj) {
		if (obj == null) {
			throw new IllegalArgumentException("can't deduce type for null");
		}
		return obj.getClass().getName();
	}

}

 

TypeOfAVariable1.java

package com.sample.app.classes;

import java.util.ArrayList;
import java.util.List;

public class TypeOfAVariable1 {

	public static void main(String args[]) {
		byte b = 1;
		short s = 2;
		int i = 3;
		long l = 4;

		float f = 1.1f;
		double d = 1.2;

		char ch = 'c';

		boolean b1 = true;

		String str = "Hello";
		List<Integer> intList = new ArrayList<>();

		System.out.println("Type of variable b is : " + TypeUtil.typeName(b));
		System.out.println("Type of variable s is : " + TypeUtil.typeName(s));
		System.out.println("Type of variable i is : " + TypeUtil.typeName(i));
		System.out.println("Type of variable l is : " + TypeUtil.typeName(l));
		System.out.println("Type of variable f is : " + TypeUtil.typeName(f));
		System.out.println("Type of variable d is : " + TypeUtil.typeName(d));
		System.out.println("Type of variable ch is : " + TypeUtil.typeName(ch));
		System.out.println("Type of variable b1 is : " + TypeUtil.typeName(b1));
		System.out.println("Type of variable str is : " + TypeUtil.typeName(str));
		System.out.println("Type of variable intList is : " + TypeUtil.typeName(intList));
	}

}

 

Output

Type of variable b is : byte
Type of variable s is : short
Type of variable i is : int
Type of variable l is : long
Type of variable f is : float
Type of variable d is : double
Type of variable ch is : char
Type of variable b1 is : boolean
Type of variable str is : java.lang.String
Type of variable intList is : java.util.ArrayList

 

 

 

You may like

Interview Questions

Java: Get the index of first occurrence of a substring

Java: Get the index of last occurrence of a substring

Java: Get all the indexes of occurrence of a substring

Java: How to replace a value in ArrayList or LinkedList

Why do we declare logger with static and final?

Sunday, 7 November 2021

FastAPI: make the query parameters optional

By setting the value to None, we can make the query parameters optional.

 

Example

@app.get("/emps/by-name")
def emByName(name: Optional[str] = None):
    if name == None:
        return {"message" : "no input provided"}
    for empId in emps:
        if emps[empId]["name"] == name:
            return emps[empId]
    return {"message" : "Not found"}

 

main.py

from fastapi import FastAPI, Path
from typing import Optional

app = FastAPI()

# employees information
emps = {
    1 : {
        "name" : "Krishna",
        "age": 32
    },
    2 : {
        "name" : "Ram",
        "age": 33
    }
}

# Create an endpoint
@app.get("/")
def home():
    return {"name" : "Hello World app", "version": "2.0.0"}

# Employees REST APIs
@app.get("/emps/by-id/{empId}")
def empById(empId: int = Path(None, description = "Enter valid employee id", gt = 0, lt = 3)):
    if(empId in emps):
        return emps[empId]
    else:
        raise Exception("Employee not exist with given id " + str(empId))

@app.get("/emps/by-name")
def emByName(name: Optional[str] = None):
    if name == None:
        return {"message" : "no input provided"}
    for empId in emps:
        if emps[empId]["name"] == name:
            return emps[empId]
    return {"message" : "Not found"}

Run the application by executing the command 'uvicorn main:app --reload'.

 

$uvicorn main:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [96380] using statreload
INFO:     Started server process [96382]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

  Open the url ‘http://127.0.0.1:8000/docs’ in browser, and experiment with the api ‘/emps/by-name’.

 

 


 

  

Previous                                                    Next                                                    Home

Python: id(): return identity of the object

‘id()’ method return an unique identifier to the object.

 

id_function_demo_1.py

class Employee:  
    def __init__(self, id, name):  
        self.id = id  
        self.name = name  

emp1 = Employee(1,"Ram")
emp2 = Employee(1,"Ram")
emp3 = Employee(1,"Ram")      

print('id(emp1) -> ' + str(id(emp1)))
print('id(emp2) -> ' + str(id(emp2)))
print('id(emp3) -> ' + str(id(emp3)))

 

Output

id(emp1) -> 4309679840
id(emp2) -> 4309679648
id(emp3) -> 4309679504

 

 

Previous                                                    Next                                                    Home