Tuesday, 14 December 2021

Gson: Convert json string to Pretty print json string

Below snippet convert the json to Pretty json string.

String uglyJson = "{\"name\": \"Krishna\", \"age\": 31}";

Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement jsonElement = JsonParser.parseString(uglyJson);
String prettyJsonString = gson.toJson(jsonElement);

 

Find the below working application.

 

PrettyJson.java

package com.sample.app.json;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

public class PrettyJson {

	public static void main(String args[]) {
		String uglyJson = "{\"name\": \"Krishna\", \"age\": 31}";

		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		JsonElement jsonElement = JsonParser.parseString(uglyJson);
		String prettyJsonString = gson.toJson(jsonElement);

		System.out.println(prettyJsonString);
	}

}

 

Output

{
  "name": "Krishna",
  "age": 31
}

 

 

 

Previous                                                    Next                                                    Home

How to specify jar files in command line?

Java takes the current directory as default classpath, you can customize this using -cp option.

 

Syntax

In Linux and MAC systems

javac -cp jar1:jar2:jar3:dir1:dir2:. HelloWorld.java
java -cp jar1:jar2:jar3:dir1:dir2:. HelloWorld

 

In Windows systems

javac -cp jar1;jar2;jar3;dir1;dir2;. HelloWorld.java
java -cp jar1;jar2;jar3;dir1;dir2;. HelloWorld

 

Let’s see it with an example.

 

PrettyJson.java

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

public class PrettyJson {

	public static void main(String args[]) {
		String uglyJson = "{\"name\": \"Krishna\", \"age\": 31}";

		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		JsonElement jsonElement = JsonParser.parseString(uglyJson);
		String prettyJsonString = gson.toJson(jsonElement);

		System.out.println(prettyJsonString);
	}

}

 

In my case gson-2.8.9.jar library is located at '/Users/Shared/jars/' folder.

$javac -cp /Users/Shared/jars/gson-2.8.9.jar:. PrettyJson.java 
$
$java -cp /Users/Shared/jars/gson-2.8.9.jar:. PrettyJson
{
  "name": "Krishna",
  "age": 31
}

 


 

   

You may like

Interview Questions

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

Check whether I have JDK or JRE in my system

How to check whether string contain only whitespaces or not?

How to call base class method from subclass overriding method?

Can an interface extend multiple interfaces in Java?

Monday, 13 December 2021

Java: Convert ByteBuffer to a string

Approach 1: 'StandardCharsets.UTF_8.decode(byteBuffer).toString()' method can be used to convert ByteBuffer to a string.

 

ByteBufferToString.java

package com.sample.app.strings;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

public class ByteBufferToString {

	public static void main(String args[]) {
		ByteBuffer byteBuffer = ByteBuffer.allocate(100);
		byteBuffer.put("Hello World".getBytes(StandardCharsets.UTF_8));

		byteBuffer.flip();
		String str = StandardCharsets.UTF_8.decode(byteBuffer).toString();

		System.out.println("str : " + str);
	}

}

Output

str : Hello World

 

Approach 2: Get the bytes from ByteBuffer and convert the bytes to a string.

byte[] bytes = byteBuffer.array();
String str = new String(bytes, StandardCharsets.UTF_8);

ByteBufferToString1.java

package com.sample.app.strings;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

public class ByteBufferToString1 {

	public static void main(String args[]) {
		ByteBuffer byteBuffer = ByteBuffer.allocate(100);
		byteBuffer.put("Hello World".getBytes(StandardCharsets.UTF_8));

		byte[] bytes = byteBuffer.array();
		String str = new String(bytes, StandardCharsets.UTF_8);

		System.out.println("str : " + str);

	}

}

Output

str : Hello World

 

  

Previous                                                    Next                                                    Home

FastAPI: Declare Response model object

FastAPI allows you to declare the model used for the response with the parameter response_model in any of the http operations like get, post, put etc.,

 

Example

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

 

In the above example, I set Employee as reponse type to the method empById. Find the below working application.

 

responseModel1.py

from fastapi import FastAPI, Path
from typing import Optional
from pydantic import BaseModel
from enum import Enum

app = FastAPI()

class CountryEnum(str, Enum):
    India = "India"
    China = "China"
    Russia = "Russia"

# model classes
class Employee(BaseModel):
    name: str
    age: int
    country: str

emp1 = Employee(name= "Krishna", age = 32, country = "India")
emp2 = Employee(name= "Ram", age = 42, country = "India")
emp3 = Employee(name= "Sailu", age = 33, country = "India")

employees = {1 : emp1, 2 : emp2, 3 : emp3}

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

 

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

 

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

  Open the url ‘http://localhost:8000/docs’ in browser and expand the api 'GET /emps​/by-id​/{empId}', you will see the response model in Responses section against 200 status code.

 


 

 

  

Previous                                                    Next                                                    Home

Spring Data: ArangoTemplate: Check for the existence of the document by id or key

Spring data ArangoOpreations interface provides ‘exists’ method to check whether a document exists or not.

 

boolean exists(Object idOrKey, Class<?> entityClass) throws DataAccessException;

This method return true if the document exists with given key or id, else false.

 

Example

arangoTemplate.exists(docId, Employee.class)
arangoTemplate.exists(docKey, Employee.class)

Find the below working application.

 

Step 1: Create new maven project ‘arango-template-doc-exists’.

 

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-doc-exists</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 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 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.springframework.core.ArangoOperations;
import com.arangodb.springframework.core.CollectionOperations;
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);
    }

    @Bean
    public CommandLineRunner demo() {

        return (args) -> {
            CollectionOperations empsCollection = arangoTemplate.collection(Employee.class);
            empsCollection.drop();

            Employee emp1 = new Employee(1, "Chamu", "M");
            
            DocumentCreateEntity docCreateEntity = (DocumentCreateEntity) arangoTemplate.insert(emp1);
            
            String docId = docCreateEntity.getId();
            String docKey = docCreateEntity.getKey();
            
            System.out.println("id : " + docId);
            System.out.println("key : " + docKey);
            
            System.out.println("\nIs doc exists with given id (" + docId + ") ? " + arangoTemplate.exists(docId, Employee.class));
            System.out.println("Is doc exists with given key (" + docKey + ") ? " + arangoTemplate.exists(docKey, Employee.class));
            

        };
    }
}

Total project structure looks like below.



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

id : employees/41354
key : 41354

Is doc exists with given id (employees/41354) ? true
Is doc exists with given key (41354) ? true

You can download complete working application from below link.

https://github.com/harikrishna553/springboot/tree/master/arangodb/arango-template-doc-exists

 

  

Previous                                                    Next                                                    Home