Tuesday, 7 December 2021

Spring Data: ArangoTemplate: replace multiple documents

ArangoOperations interface provides ‘replace’ method to replace a document.

 

Signature

<T> MultiDocumentEntity<? extends DocumentEntity> replace(Iterable<T> values, Class<T> entityClass, DocumentReplaceOptions options) throws DataAccessException;

<T> MultiDocumentEntity<? extends DocumentEntity> replace(Iterable<T> values, Class<T> entityClass) throws DataAccessException;

 

Replaces multiple documents in the specified collection with the ones in the values, the replaced documents are specified by the _key attributes in the documents in values.

 

‘DocumentReplaceOptions’  is used to provide additional options while replacing the document. Below table summarizes possible options while replacing the document.

 

Option

Data type

Description

waitForSync

Boolean

Wait until document has been synced to disk.

ignoreRevs

Boolean

By default, or if this is set to true, the _rev attributes in the given document is ignored. If this is set to false, then the _rev attribute given in the body document is taken as a precondition. The document is only replaced if the current revision is the one specified.

ifMatch

String

Replace a document based on target revision

returnNew

Boolean

Return additionally the complete new document under the attribute new in the result.

returnOld

Boolean

Return additionally the complete previous revision of the changed document under the attribute old in the result.

silent

Boolean

If set to true, an empty object will be returned as response. No meta-data will be returned for the created document. This option can be used to save some network traffic.

streamTransactionId

String

If set, the operation will be executed within the transaction.

 

Example

DocumentReplaceOptions docReplaceOptions = new DocumentReplaceOptions();
docReplaceOptions.returnNew(true);
docReplaceOptions.returnOld(true);

MultiDocumentEntity<DocumentUpdateEntity> updatedDocs = (MultiDocumentEntity<DocumentUpdateEntity>) arangoTemplate.replace(Arrays.asList(emp1ToReplace, emp2ToReplace), Employee.class, docReplaceOptions);

 

Find the below working application.

 

Step 1: Create new maven project ‘arango-template-replace-documents’.

 

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>arango-template-replace-documents</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;
    private Integer age;

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

    public Employee() {
        
    }

    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 [key=" + key + ", arangoId=" + arangoId + ", id=" + id + ", firstName=" + firstName
                + ", lastName=" + lastName + ", age=" + age + "]";
    }

}

 

Step 4: Define Arango DB configuration class.

 

ArangoConfig.java

package com.sample.app.config;

import org.springframework.context.annotation.Configuration;

import com.arangodb.ArangoDB;
import com.arangodb.springframework.annotation.EnableArangoRepositories;
import com.arangodb.springframework.config.ArangoConfiguration;

@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 5: Define main application class.

 

App.java

package com.sample.app;

import java.util.Arrays;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import com.arangodb.entity.DocumentCreateEntity;
import com.arangodb.entity.DocumentUpdateEntity;
import com.arangodb.entity.MultiDocumentEntity;
import com.arangodb.model.DocumentCreateOptions;
import com.arangodb.model.DocumentReplaceOptions;
import com.arangodb.model.DocumentUpdateOptions;
import com.arangodb.springframework.core.ArangoOperations;
import com.sample.app.entity.Employee;

@SpringBootApplication
public class App {

    @Autowired
    private ArangoOperations arangoTemplate;

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

    private static void print(DocumentCreateEntity documentCreateEntity) {
        System.out.println("\nid : " + documentCreateEntity.getId());
        System.out.println("key : " + documentCreateEntity.getKey());
        System.out.println("revision : " + documentCreateEntity.getRev());
        System.out.println("doc : " + documentCreateEntity.getNew());
    }

    @Bean
    public CommandLineRunner demo() {

        return (args) -> {
            Employee emp1 = new Employee(1, "Shanmukha Rao", "Kummari");
            Employee emp2 = new Employee(1, "Sarath", "Chandra");

            DocumentCreateOptions docCreateOptions = new DocumentCreateOptions();
            docCreateOptions.returnNew(true);

            DocumentCreateEntity documentCreateEntity1 = (DocumentCreateEntity) arangoTemplate.insert(emp1,
                    docCreateOptions);

            DocumentCreateEntity documentCreateEntity2 = (DocumentCreateEntity) arangoTemplate.insert(emp2,
                    docCreateOptions);

            print(documentCreateEntity1);
            print(documentCreateEntity2);

            Employee emp1ToReplace = new Employee();
            emp1ToReplace.setKey(documentCreateEntity1.getKey());
            emp1ToReplace.setFirstName("Shanmukha Rao Kummari");
            emp1ToReplace.setAge(35);

            Employee emp2ToReplace = new Employee();
            emp2ToReplace.setKey(documentCreateEntity2.getKey());
            emp2ToReplace.setFirstName("Sarath Chandra");
            emp2ToReplace.setAge(42);

            DocumentReplaceOptions docReplaceOptions = new DocumentReplaceOptions();
            docReplaceOptions.returnNew(true);
            docReplaceOptions.returnOld(true);

            MultiDocumentEntity<DocumentUpdateEntity> updatedDocs = (MultiDocumentEntity<DocumentUpdateEntity>) arangoTemplate
                    .replace(Arrays.asList(emp1ToReplace, emp2ToReplace), Employee.class, docReplaceOptions);

            Collection<DocumentUpdateEntity> updatedDocsCollection = updatedDocs.getDocuments();

            System.out.println("\nUpdated document");
            for (DocumentUpdateEntity updatedDoc : updatedDocsCollection) {
                System.out.println("\nid : " + updatedDoc.getId());
                System.out.println("key : " + updatedDoc.getKey());
                System.out.println("revision : " + updatedDoc.getRev());
                System.out.println("newDoc : " + updatedDoc.getNew());
                System.out.println("oldDoc : " + updatedDoc.getOld());
            }

        };
    }
}

 

Total project structure looks like below.

 

 


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

id : employees/36762
key : 36762
revision : _cUlY3aq---
doc : {"_key":"36762","_id":"employees\/36762","_rev":"_cUlY3aq---","id":1,"firstName":"Shanmukha Rao","lastName":"Kummari","_class":"com.sample.app.entity.Employee"}

id : employees/36764
key : 36764
revision : _cUlY3b----
doc : {"_key":"36764","_id":"employees\/36764","_rev":"_cUlY3b----","id":1,"firstName":"Sarath","lastName":"Chandra","_class":"com.sample.app.entity.Employee"}

Updated document

id : employees/36762
key : 36762
revision : _cUlY3cO---
newDoc : {"_key":"36762","_id":"employees\/36762","_rev":"_cUlY3cO---","firstName":"Shanmukha Rao Kummari","age":35,"_class":"com.sample.app.entity.Employee"}
oldDoc : {"_key":"36762","_id":"employees\/36762","_rev":"_cUlY3aq---","id":1,"firstName":"Shanmukha Rao","lastName":"Kummari","_class":"com.sample.app.entity.Employee"}

id : employees/36764
key : 36764
revision : _cUlY3cO--A
newDoc : {"_key":"36764","_id":"employees\/36764","_rev":"_cUlY3cO--A","firstName":"Sarath Chandra","age":42,"_class":"com.sample.app.entity.Employee"}
oldDoc : {"_key":"36764","_id":"employees\/36764","_rev":"_cUlY3b----","id":1,"firstName":"Sarath","lastName":"Chandra","_class":"com.sample.app.entity.Employee"}

You can download complete working application from below link.

https://github.com/harikrishna553/springboot/tree/master/arangodb/arango-template-replace-documents 

 

 



 

 

 

 

 

 

Previous                                                    Next                                                    Home

FastAPI: Specify sample payload using Field

When using Field() with Pydantic models, you can also declare extra info for the JSON Schema by passing any other arbitrary arguments to the function.

 

Example

class Employee(BaseModel):
    name: str = Field(..., example = "Krishna")
    age : int = Field(..., example = 31)

 

Find the below working application.

 

requestSamplePayloadUsingField.py

from fastapi import FastAPI, Body
from pydantic import BaseModel, Field
from typing import Optional

app = FastAPI()

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

class Employee(BaseModel):
    name: str = Field(..., example = "Krishna")
    age : int = Field(..., example = 31)

@app.get("/emps")
def allEmployees():
    return emps

@app.post("/emps")
def createEmployee(emp: Employee):
    noOfEmps = len(emps)
    newId = noOfEmps + 1
    emps[newId] = dict(emp)

    return {
        "id" : newId, 
        "name" : emps[newId]['name'], 
        "age": emps[newId]['age']
        }

 

Open terminal and execute the command ‘uvicorn requestSamplePayloadUsingField:app --reload’.

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

 

Open the url ‘http://localhost:8000/docs’ in browser and expand 'POST /emps' api, you will see the sample payload is documented.

 


 

  

Previous                                                    Next                                                    Home

Spring: How to auto wire two beans implementing the same interface?

Here is the scenario, where I have an interface ‘HelloResponse’ and two classes HiServiceImpl and WelcomeServiceImpl are implementing the interface HelloService.

 

Now I want to autowire the beans of type HiServiceImpl and WelcomeServiceImpl. Since these two classes are implementing the same interface, we can use @Qualifier annotation to explicitly specify the bean that we are interested to use.

 

Step 1: Define service classes by specifying the component name explicitly.

@Component("hiService")
public class HiServiceImpl implements HelloService{

	........
	........
}

 

@Component("welcomeService")
public class WelcomeServiceImpl implements HelloService{

	........
	........

}

 

Step 2: Explicitly specify the component name using @Qualifier annotation while autowiring.

@RestController
public class HelloController {

	@Autowired
	@Qualifier("hiService")
	private HelloService hiService;

	@Autowired
	@Qualifier("welcomeService")
	private HelloService welcomeServiceImpl;

	......
	......
}

 

Find the below working application.

 

Step 1: Create new maven project ‘qualifier-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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>qualifier-demo</artifactId>
	<version>1</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.5.6</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>


	<dependencies>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>


	</dependencies>

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

</project>

 

Step 3: Define HelloService.

 

HelloService.java

package com.sample.app.service;

public interface HelloService {
	
	public String sayHello();

}

 

Step 4: Define HiServiceImpl and WelcomeServiceImpl classes.

 

HiServiceImpl.java

package com.sample.app.service.impl;

import org.springframework.stereotype.Component;

import com.sample.app.service.HelloService;

@Component("hiService")
public class HiServiceImpl implements HelloService{

	@Override
	public String sayHello() {
		return "Hi!!!!!!!!";
	}

}

 

WelcomeServiceImpl.java

package com.sample.app.service.impl;

import org.springframework.stereotype.Component;

import com.sample.app.service.HelloService;

@Component("welcomeService")
public class WelcomeServiceImpl implements HelloService{

	@Override
	public String sayHello() {
		return "Welcome!!!!!!";
	}

}

 

Step 5: Define HelloController.

 

HelloController.java

 

package com.sample.app.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sample.app.service.HelloService;

@RestController
public class HelloController {

	@Autowired
	@Qualifier("hiService")
	private HelloService hiService;

	@Autowired
	@Qualifier("welcomeService")
	private HelloService welcomeServiceImpl;

	@GetMapping(value = "/hi", produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<HelloResponse> sayHi() {
		HelloResponse resp = new HelloResponse(hiService.sayHello());
		return ResponseEntity.ok(resp);

	}

	@GetMapping(value = "/welcome", produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<HelloResponse> sayWelcome() {
		HelloResponse resp = new HelloResponse(welcomeServiceImpl.sayHello());
		return ResponseEntity.ok(resp);

	}

	private static class HelloResponse {
		String resp;

		public HelloResponse() {
		}

		public HelloResponse(String resp) {
			super();
			this.resp = resp;
		}

		public String getResp() {
			return resp;
		}

		public void setResp(String resp) {
			this.resp = resp;
		}
		
		

	}
}

Step 6: Define main application class.

 

App.java

package com.sample.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {
	public static void main(String[] args) {

		SpringApplication.run(App.class, args);

	}
}

Total project structure looks like below.

 

 


Run App.java

 

Open the url 'http://localhost:8080/hi' in browser, you will see below message.

{"resp":"Hi!!!!!!!!"}

 

Open the url 'http://localhost:8080/welcome' in browser, you will see below message.

{"resp":"Welcome!!!!!!"}

 


You can download the complete working application from below link.

https://github.com/harikrishna553/springboot/tree/master/rest/qualifier-demo



Previous                                                    Next                                                    Home

Check whether I have JDK or JRE in my system

JRE vs JDK

JRE is implementation of Java Virtual Machine, Which actually executes Java Programs. JDK is a bundle of software used to develop Java Applications.

 

Usually, when you only care about running Java programs on your browser or computer you will only install JRE. It's all you need. On the other hand, if you are planning to do some Java programming, you will also need JDK.

 


 

To confirm the JDK

Execute the command ‘javac -version’.

$javac -version
javac 1.8.0_251

If you got the java compiler version details, then JDK is installed in your system.

 

To confirm the JRE

If javac command failed to get the compiler version, execute the command ‘java -version’.

$java -version
java version "1.8.0_251"
Java(TM) SE Runtime Environment (build 1.8.0_251-b08)
Java HotSpot(TM) 64-Bit Server VM (build 25.251-b08, mixed mode)

If you got the java runtime environment details, then JRE is installed in your system. If this command failed, then either Java path is not set properly or Java is not installed in your system.



You may like

Interview Questions

Why do we declare logger with static and final?

How to check the type of a variable in Java?

Set a system property in command line

How to get the capacity of ArrayList in Java?

volatile reference vs Atomic references defined in java.util.concurrent.atomic package