Monday, 13 December 2021

Java: Convert string to ByteBuffer

Below snippet is used to convert string to a ByteBuffer.

ByteBuffer byteBuffer = ByteBuffer.allocate(100);
byteBuffer.put("Hello World".getBytes(StandardCharsets.UTF_8));

Find the below working application.

 

StringToByteBuffer.java

package com.sample.app.strings;

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

public class StringToByteBuffer {

	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



Previous                                                    Next                                                    Home

Gson: Disable HTML escaping

In this post, I am going to explain how to disable HTML escaping in Gson library. By default, Gson escapes HTML characters such as <, >.

 

For example,

 

Model.java

package com.sample.app.json;

public class Model {

	private String data;

	public String getData() {
		return data;
	}

	public void setData(String data) {
		this.data = data;
	}

}

 

JsonEscapingDemo.java

package com.sample.app.json;

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

public class JsonEscapingDemo {

	public static void main(String args[]) {
		Gson gson = new GsonBuilder().create();

		Model obj = new Model();
		obj.setData("Hello this is <Krishna>");

		String json = gson.toJson(obj);
		System.out.println(json);
	}

}

 

Output

{"data":"Hello this is \u003cKrishna\u003e"}

 

As you see above snippet, HTML characters < and > are escaped with unicodes \u003c, \u003e.

 

How can I disable HTML escaping?

Disable HTML escaping using disableHtmlEscaping() method.

 

Example

 

Gson gson = new GsonBuilder().disableHtmlEscaping().create();

 

JsonEscapingDemo.java

package com.sample.app.json;

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

public class JsonEscapingDemo {

	public static void main(String args[]) {
		Gson gson = new GsonBuilder().disableHtmlEscaping().create();

		Model obj = new Model();
		obj.setData("Hello this is <Krishna>");

		String json = gson.toJson(obj);
		System.out.println(json);
	}

}

 

Output

{"data":"Hello this is <Krishna>"}

 

 

 

 

 

 

 

 

 

Previous                                                    Next                                                    Home

Eclipse: Organize imports of a project with single keystroke

Approach 1: Using keyboard short cuts

 

In Windows, select the project in the package explorer and press the command: ctrl + shift + o

 

In Mac, select the project in the package explorer and press the command: command + shift + o

 

Approach 2: Right click on the project -> source -> Organize Imports.

 


Previous                                                    Next                                                    Home

Can an interface extend multiple interfaces in Java?

In Java, one interface can extend multiple interfaces.

 

Syntax

interface MyInterface extends interface1, interface2...interfaceN{
	......
	......
}

 

Example

public interface AppUtil extends WelcomeUtil, LogUtil{
	.....
	.....
}

 

 


 

Find the below working application.

 

WelcomeUtil.java

 

package com.sample.app.interfaces;

public interface WelcomeUtil {
	
	public void sayHi();

}

LogUtil.java

package com.sample.app.interfaces;

public interface LogUtil {

	public void log(String msg);
}

AppUtil.java

package com.sample.app.interfaces;

public interface AppUtil extends WelcomeUtil, LogUtil{

	public String appDetails();
}



You may like

Interview Questions

How to get the capacity of ArrayList in Java?

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?

Sunday, 12 December 2021

Java: How to call base class method from subclass overriding method?

Using ‘super’ keyword, you can call the base class method from the subclass overriding method.

class B extends A {
	public void print() {
		super.print();
		System.out.println("In class B");
	}
}

 

Find the below working application.

 

CallingSuperClassMethodDemo.java

 

package com.sample.app.overriding;

public class CallingSuperClassMethodDemo {

	static class A {
		public void print() {
			System.out.println("In class A");
		}
	}

	static class B extends A {
		public void print() {
			super.print();
			System.out.println("In class B");
		}
	}

	public static void main(String args[]) {
		B b = new B();
		b.print();
	}

}

 

Output

In class A
In class B

 

  

You may like

Interview Questions

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

Check whether I have JDK or JRE in my system

How to check whether string contain only whitespaces or not?

Spring Data: ArangoTemplate: Delete multiple documents

Spring Data ArangoOperations interface provides delete() method to delete a document by id or key.

 

Signature

MultiDocumentEntity<? extends DocumentEntity> delete(Iterable<Object> values, Class<?> entityClass, DocumentDeleteOptions options) throws DataAccessException;

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

'values' specify the keys of the documents or the documents themselves.

 

‘DocumentDeleteOptions’ is used to add additional options while deleting the document.

 

Below table summarizes the options can be passed using DocumentDeleteOptions.

 

Option

Data type

Description

waitForSync

Boolean

Wait until deletion operation has been synced to disk.

ifMatch

String

remove a document based on a target revision

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

MultiDocumentEntity<DocumentDeleteEntity> docDeleteEntity = (MultiDocumentEntity<DocumentDeleteEntity>) arangoTemplate.delete(Arrays.asList(docId1, docId2), Employee.class, deleteOptions);

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

 

Step 1: Create new maven project ‘arango-template-delete-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-delete-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 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 java.util.Iterator;

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.DocumentDeleteEntity;
import com.arangodb.entity.DocumentEntity;
import com.arangodb.entity.MultiDocumentEntity;
import com.arangodb.model.DocumentDeleteOptions;
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);
    }

    private void printAllEmps() {
        Iterable<Employee> empsIterable = arangoTemplate.findAll(Employee.class);

        Iterator<Employee> empsIterator = empsIterable.iterator();

        if (!empsIterator.hasNext()) {
            System.out.println("\nNo documents present in the collection");
        } else {
            for (Employee emp : empsIterable) {
                System.out.println(emp);
            }
        }

    }

    @Bean
    public CommandLineRunner demo() {

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

            Employee emp1 = new Employee(1, "Chamu", "M");
            Employee emp2 = new Employee(2, "Krishna", "Gurram");

            DocumentEntity docEntity1 = arangoTemplate.insert(emp1);
            DocumentEntity docEntity2 = arangoTemplate.insert(emp2);

            printAllEmps();

            String docId1 = docEntity1.getId();
            String docId2 = docEntity2.getId();

            DocumentDeleteOptions deleteOptions = new DocumentDeleteOptions();
            deleteOptions.returnOld(true);

            MultiDocumentEntity<DocumentDeleteEntity> docDeleteEntity = (MultiDocumentEntity<DocumentDeleteEntity>) arangoTemplate
                    .delete(Arrays.asList(docId1, docId2), Employee.class, deleteOptions);

            System.out.println("\nDeleted documents : ");
            Collection<DocumentDeleteEntity> docDeletedEntities = docDeleteEntity.getDocuments();
            for (DocumentDeleteEntity docDeletedEntity : docDeletedEntities) {
                System.out.println(docDeletedEntity.getOld());
            }

            printAllEmps();

        };
    }
}

Total project structure looks like below.




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

Employee [key=40101, arangoId=employees/40101, id=1, firstName=Chamu, lastName=M, age=null]
Employee [key=40103, arangoId=employees/40103, id=2, firstName=Krishna, lastName=Gurram, age=null]

Deleted documents : 
Employee [key=null, arangoId=null, id=1, firstName=Chamu, lastName=M, age=null]
Employee [key=null, arangoId=null, id=2, firstName=Krishna, lastName=Gurram, age=null]

No documents present in the collection

You can download complete working application from below link.

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



Previous                                                    Next                                                    Home