Friday, 5 November 2021

Pydantic: Error handling

Pydnatic throws ‘ValidationError’ whenever it see an issue while validating the data.

 

validation_error_1.py

from pydantic import BaseModel, ValidationError, conint, constr

class Employee(BaseModel):
    id: int
    name: constr(min_length=3, max_length=10)
    age: conint(gt=18)

try:
    emp1 = Employee(id = 1, name = 'Pt', age = 8)
except ValidationError as e:
    print(e)

 

Output

2 validation errors for Employee
name
  ensure this value has at least 3 characters (type=value_error.any_str.min_length; limit_value=3)
age
  ensure this value is greater than 18 (type=value_error.number.not_gt; limit_value=18)

As you see the output, Pydantic will return the list of errors found in the input data.

 

Different ways to extract the information from ValidaitonError object

Method

Description

e.errors()

method will return list of errors found in the input data.

e.json()

method will return a JSON representation of errors.

str(e)

method will return a human readable representation of the errors.

 

validation_error_2.py

from pydantic import BaseModel, ValidationError, conint, constr

class Employee(BaseModel):
    id: int
    name: constr(min_length=3, max_length=10)
    age: conint(gt=18)

try:
    emp1 = Employee(id = 1, name = 'Pt', age = 8)
except ValidationError as e:
    print(e.errors())
    print('\n\n\n')
    print(e.json())
    print('\n\n\n')
    print(str(e))


Output

[{'loc': ('name',), 'msg': 'ensure this value has at least 3 characters', 'type': 'value_error.any_str.min_length', 'ctx': {'limit_value': 3}}, {'loc': ('age',), 'msg': 'ensure this value is greater than 18', 'type': 'value_error.number.not_gt', 'ctx': {'limit_value': 18}}]




[
  {
    "loc": [
      "name"
    ],
    "msg": "ensure this value has at least 3 characters",
    "type": "value_error.any_str.min_length",
    "ctx": {
      "limit_value": 3
    }
  },
  {
    "loc": [
      "age"
    ],
    "msg": "ensure this value is greater than 18",
    "type": "value_error.number.not_gt",
    "ctx": {
      "limit_value": 18
    }
  }
]




2 validation errors for Employee
name
  ensure this value has at least 3 characters (type=value_error.any_str.min_length; limit_value=3)
age
  ensure this value is greater than 18 (type=value_error.number.not_gt; limit_value=18)


{

    "loc": [

      "age"

    ],

    "msg": "ensure this value is greater than 18",

    "type": "value_error.number.not_gt",

    "ctx": {

      "limit_value": 18

    }

  }

As you see above snippet, each error object contain properties loc, msg, type and ctx. Below table summarizes the properties.

 

Property

Description

loc

Specifies the error's location as a list. The first item in the list will be the field where the error occurred,

msg

Human readable error message

type

Computer readable identifier for the error type

ctx

an optional object which contains values required to render the error message.




 

  

Previous                                                    Next                                                    Home

Spring data: ArangoDB: count all the documents in a collection

‘count’ method of repository interface is used to count all the documents in the collection.

 

Example

long noOfDocuments = employeeRepo.count();

 

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

 

Step 1: Create new maven project ‘count-total-documents-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>count-total-documents-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 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;

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

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

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

}

 

Step 4: Define Repository 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 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 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) -> {

      System.out.println("Adding two new documents to the employees collection");

      List<Employee> emps = Arrays.asList(new Employee(1, "Ram", "Gurram"),
          new Employee(2, "Sundar", "Deavanagari"));

      employeeRepo.saveAll(emps);

      long noOfDocuments = employeeRepo.count();

      System.out.println("Total number of documents in the collection : " + noOfDocuments);

      System.out.println("\nAdding one more document to the collection");

      employeeRepo.save(new Employee(3, "Kishore", "Munipati"));

      noOfDocuments = employeeRepo.count();

      System.out.println("Total number of documents in the collection : " + noOfDocuments);

    };
  }
}

 

Total project structure looks like below.

 



 

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

 

 

Adding two new documents to the employees collection
Total number of documents in the collection : 2

Adding one more document to the collection
Total number of documents in the collection : 3

 

You can download complete working application from below link.

https://github.com/harikrishna553/springboot/tree/master/arangodb/count-total-documents-demo

 

 

 

Previous                                                    Next                                                    Home

Find the difference between two joda Datetimes in milliseconds

DateTime class provides ‘getMillis’ method which return the milliseconds of the datetime instant from the Java epoch. Using ‘getMillis’ method, you can find the difference in milliseconds.

 

Example

DateTime today = new DateTime();
DateTime tomorrow = today.plusDays(1);

long diffInMillis = tomorrow.getMillis() - today.getMillis();

 

DateTimeDiffInMilliseconds.java

package com.sample.app.joda;

import org.joda.time.DateTime;

public class DateTimeDiffInMilliseconds {

	public static void main(String args[]) {
		DateTime today = new DateTime();
		DateTime tomorrow = today.plusDays(1);

		long diffInMillis = tomorrow.getMillis() - today.getMillis();

		System.out.println("Difference between today and tomorrow in milliseconds: " + diffInMillis);

	}

}

 

Output

Difference between today and tomorrow in milliseconds: 86400000

 

 

 

 


Previous                                                    Next                                                    Home

Find the difference between two joda Datetime objects

Approach 1: Using Duration object.

 

DateTimeDifference1.java

package com.sample.app.joda;

import org.joda.time.DateTime;
import org.joda.time.Duration;

public class DateTimeDifference1 {

	public static void main(String args[]) {
		DateTime today = new DateTime();
		DateTime tomorrow = today.plusDays(1);

		Duration duration = new Duration(today, tomorrow);

		System.out.println("Difference between today and tomorrow:");
		System.out.println("\tin days: " + duration.getStandardDays());
		System.out.println("\tin hours: " + duration.getStandardHours());
		System.out.println("\tin minutes: " + duration.getStandardMinutes());
		System.out.println("\tin seconds: " + duration.getStandardSeconds());
	}

}

Output

Difference between today and tomorrow:
	in days: 1
	in hours: 24
	in minutes: 1440
	in seconds: 86400


Approach 2: Using Days.daysBetween, Hours.hoursBetween, Minutes.minutesBetween and Seconds.secondsBetween methods.

 

DateTimeDifference2.java

package com.sample.app.joda;

import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Hours;
import org.joda.time.Minutes;
import org.joda.time.Seconds;

public class DateTimeDifference2 {

	public static void main(String args[]) {
		DateTime today = new DateTime();
		DateTime tomorrow = today.plusDays(1);

		System.out.println("Difference between today and tomorrow:");
		System.out.println("\tin days: " + Days.daysBetween(today, tomorrow).getDays());
		System.out.println("\tin hours: " + Hours.hoursBetween(today, tomorrow).getHours());
		System.out.println("\tin minutes: " + Minutes.minutesBetween(today, tomorrow).getMinutes());
		System.out.println("\tin seconds: " + Seconds.secondsBetween(today, tomorrow).getSeconds());
	}

}


Output

Difference between today and tomorrow:
	in days: 1
	in hours: 24
	in minutes: 1440
	in seconds: 86400






 

  

Previous                                                    Next                                                    Home

joda time programs

 

      Find the difference between two joda Datetime objects
      Find the difference between two joda Datetimes in milliseconds
Previous                                                    Next                                                    Home

Why do we declare logger with static and final?

While working with Java applications, you may already see a logger object defined like below.

private static final Logger logger =  LoggerFactory.getLogger(AppConfig.class);

 

Why is the logger instance defined as private?

Usually, logger instances are specific to a class, no point in making these available to outside of the class. So, it is recommended to make them private.

 

Why is the logger instance defined with static specifier?

In general, we use the class name to log the log messages like below. Adding a class name helps in identifying the error easily.

Nov 03, 2021 5:12:20 PM com.sample.app.AppConfig main
WARNING: No default configurations set for the app readtime out

 

In memory footprint point of view also, if the logger is defined as static, only one logger instance is created and used by all the other references of given class, whereas an instance logger member will cost a variable reference for every instance of the class.

 

If your class is implementing Serializable interface, all instance properties are serialized by default. If you do not make the logger as static, you need to explicitly add transient keyword to the logger instances wherever you used.

 

In summary, static logger variables will take less memory footprint, and less CPU overhead.

 

Why is the logger instance defined with final specifier?

Once a logger instance is defined, usually we do not change the properties of it during the application lifetime. So, it is defined with final.

 

Reference

http://slf4j.org/faq.html#declared_static

 

 

 

You may like

Interview Questions

Java: How to find the minimum element in a collection?

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