Saturday, 6 November 2021

Spring Data: ArangoDB: Sort by a key

'findAll(Sort sort)' method is used to sort the documents by specific property value.

 

Example

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

Step 1: Create new maven project ‘sort-by-doc-property-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>sort-by-doc-property-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.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(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]
Employee [id=4, firstName=Madhavi Latha, lastName=Gumma, age=41]
Employee [id=3, firstName=Srinuvasa rao, lastName=Guma, age=43]

You can download complete working application from below link.

https://github.com/harikrishna553/springboot/tree/master/arangodb/sort-by-doc-property-demo



  

Previous                                                    Next                                                    Home

Python: dict(): Create a dictionary

‘dict()’ is used to create a dictionary.

 

Example

empDict = dict(name = "Krishna", age = 36, id = 1)

 

create_dict_using_dict_function.py

empDict = dict(name = "Krishna", age = 36, id = 1)

print(empDict)

 

Output

{'name': 'Krishna', 'age': 36, 'id': 1}

 

 

Previous                                                    Next                                                    Home

python: built-in functions

      bytearray: Return mutable array of bytes
      bytes(): get immutable bytes object
      dict(): Create a dictionary
      frozenset: make the iterable immutable
      id(): return identity of the object
      issubclass: Check whether this class is subclass of other class or not
      len(): Get the length of an object
            Get the length of a string
            Find the number of items in a list
            get number of items in the range
            Get number of items in the set
            Get number of items in the frozen set

FastAPI: Working with query parameters

Query parameters are a set of parameters attached to the end of a url. Query parameters go after the ? in a URL, separated by & characters.

 

For the uri http://localhost:8080/?name=sailu&gender=f, name is mapped to ‘sailu’ and ‘gender’ is mapped to f.

 

Example

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

 

Above snippet maps the query parameter name to the argument name.

 

Find the below working application.

 

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: str):
    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'.

 

Open the url ‘http://127.0.0.1:8000/docs’ and work with the api /emps/by-name.

 


 

  

Previous                                                    Next                                                    Home

Java: Remove single character at given index from a string

In this post, I am going to explain how to remove single character at given index from a string. Strings in Java are immutable, so once a string is defined, you can’t change the value. Possible way is to create new string that do not contain the character at given index from original string.

 

Multiple approaches to remove single character at given index from a string.

 

Approach 1: Traverse the string character by character, form a new string by skipping the character at specific index.

 

SkipCharDemo1.java

package com.sample.app.strings;

public class SkipCharDemo1 {

	private static String skipCharAtIndex(String str, int index) {
		if (str == null || index < 0 || index > str.length()) {
			return str;
		}

		char[] chars = str.toCharArray();

		StringBuilder stringBuilder = new StringBuilder();

		for (int i = 0; i < chars.length; i++) {
			if (i == index) {
				continue;
			}
			stringBuilder.append(chars[i]);
		}

		return stringBuilder.toString();
	}

	public static void main(String args[]) {

		String str = "Hello";

		System.out.println("str -> " + str);

		for (int i = 0; i < str.length(); i++) {
			String result = skipCharAtIndex(str, i);
			System.out.println("Skipped ch at index " + i + ", result " + result);
		}

	}

}

 

Output

str -> Hello
Skipped ch at index 0, result ello
Skipped ch at index 1, result Hllo
Skipped ch at index 2, result Helo
Skipped ch at index 3, result Helo
Skipped ch at index 4, result Hell

 

Approach 2: Get StringBuilder instance from the string, remove the character at given index using deleteCharAt method.

 

SkipCharDemo2.java

 

package com.sample.app.strings;

public class SkipCharDemo2 {

	private static String skipCharAtIndex(String str, int index) {
		if (str == null || index < 0 || index > str.length()) {
			return str;
		}

		StringBuilder stringBuilder = new StringBuilder(str);
		return stringBuilder.deleteCharAt(index).toString();

	}

	public static void main(String args[]) {

		String str = "Hello";

		System.out.println("str -> " + str);

		for (int i = 0; i < str.length(); i++) {
			String result = skipCharAtIndex(str, i);
			System.out.println("Skipped ch at index " + i + ", result " + result);
		}

	}

}

 

Output

str -> Hello
Skipped ch at index 0, result ello
Skipped ch at index 1, result Hllo
Skipped ch at index 2, result Helo
Skipped ch at index 3, result Helo
Skipped ch at index 4, result Hell

Approach 3: using substring method.


 

SkipCharDemo3.java

package com.sample.app.strings;

public class SkipCharDemo3 {

	private static String skipCharAtIndex(String str, int index) {
		if (str == null || index < 0 || index > str.length()) {
			return str;
		}

		return str.substring(0, index) + str.substring(index + 1);

	}

	public static void main(String args[]) {

		String str = "Hello";

		System.out.println("str -> " + str);

		for (int i = 0; i < str.length(); i++) {
			String result = skipCharAtIndex(str, i);
			System.out.println("Skipped ch at index " + i + ", result " + result);
		}

	}

}


Output

str -> Hello
Skipped ch at index 0, result ello
Skipped ch at index 1, result Hllo
Skipped ch at index 2, result Helo
Skipped ch at index 3, result Helo
Skipped ch at index 4, result Hell


 

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?

Friday, 5 November 2021

FastAPI: Path parameter can contain /

Sometimes you may need to pass the filepath as a path parameter. Most of the implementations do not support to pass filepaths in the url, but FastAPI support this feature.

 

You need to define a path parameter like below

/file/{filePath:path}

 

filePath points to the actual filepath and path specifies that the parameter should match any path.

 

Example

@app.get("/file/{filePath:path}")
def getFileByPath(filePath: str):
    return {'received' : filePath}

 

filePath.py

from fastapi import FastAPI, Path

app = FastAPI()

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

@app.get("/file/{filePath:path}")
def getFileByPath(filePath: str):
    return {'received' : filePath}

 

Open the terminal and execute the command 'uvicorn filePath:app --reload'.

 

Open the url ‘http://127.0.0.1:8000/file/a/b/c.txt’ in browser, you will receive below output.

{"received":"a/b/c.txt"}

If you want the path to contain a leading slash (/), url should be like ‘file//a/b/c.txt’ ‘ two slashes between file and actual file path. Open the url ‘http://127.0.0.1:8000/file//a/b/c.txt’ in browser, you will receive below output.

 

{"received":"/a/b/c.txt"}

 


 

 

 

 

  

Previous                                                    Next                                                    Home