Wednesday, 6 July 2022

Atlas client: Create an entity

In this post, I am going to explain how to create an instance of a type.

 

For the demo purpose, I am going to define a type ‘DemoType1’ with some properties to it. Once the type is defined successfully, I am going to create an instance of the type ‘DemoType1’.

 

Follow below steps to define an instance of entity DemoType1.

 

Step 1: Define an instance of AtlasEntity and populate the attributes that you are interested.

AtlasEntity atlasEntity = new AtlasEntity();

atlasEntity.setTypeName(TYPE_NAME);

atlasEntity.setAttribute("a", 10);
atlasEntity.setAttribute("b", 20);

// Following are the mandatory attributes
atlasEntity.setAttribute("qualifiedName", "CreateEntity_DEMO1");
atlasEntity.setAttribute("name", "CreateEntity_DEMO1");

Step 2: Define an instance of AtlasEntityWithExtInfo, pass it to an argument to ‘createEntity’ method to define an entity.

AtlasEntity.AtlasEntityWithExtInfo atlasEntityWithExtInfo = new AtlasEntity.AtlasEntityWithExtInfo();
atlasEntityWithExtInfo.setEntity(atlasEntity);
atlasClient.createEntity(atlasEntityWithExtInfo);

Find the below working application.

 

Create atlas-application.properties file under src/main/resources folder.

 

atlas-application.properties

atlas.client.readTimeoutMSecs=30000
atlas.client.connectTimeoutMSecs=30000

Define ‘CreateEntity’ class.

 

CreateEntity.java


package com.sample.app.entity;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import org.apache.atlas.AtlasClientV2;
import org.apache.atlas.AtlasServiceException;
import org.apache.atlas.model.instance.AtlasEntity;
import org.apache.atlas.model.typedef.AtlasEntityDef;
import org.apache.atlas.model.typedef.AtlasStructDef.AtlasAttributeDef;
import org.apache.atlas.model.typedef.AtlasTypesDef;

import com.fasterxml.jackson.core.JsonProcessingException;

public class CreateEntity {

    private static final String TYPE_NAME = "DemoType1";

    private static void createType(AtlasClientV2 atlasClient) throws AtlasServiceException {
        AtlasAttributeDef attributeDef1 = new AtlasAttributeDef();
        attributeDef1.setName("a");
        attributeDef1.setTypeName("int");
        attributeDef1.setCardinality(AtlasAttributeDef.Cardinality.SINGLE);
        attributeDef1.setIsIndexable(true);
        attributeDef1.setIsUnique(false);

        AtlasAttributeDef attributeDef2 = new AtlasAttributeDef();
        attributeDef2.setName("b");
        attributeDef2.setTypeName("int");
        attributeDef2.setCardinality(AtlasAttributeDef.Cardinality.SINGLE);
        attributeDef2.setIsIndexable(true);
        attributeDef2.setIsUnique(false);

        AtlasEntityDef atlasEntityDef = new AtlasEntityDef();
        atlasEntityDef.setName(TYPE_NAME);
        atlasEntityDef.setCreatedBy("Krishna");
        atlasEntityDef.setUpdatedBy("krishna");
        atlasEntityDef.setDescription("Represent a laptoo specification");
        atlasEntityDef.setAttributeDefs(Arrays.asList(attributeDef1, attributeDef2));

        Set<String> superTypes = new HashSet<>();
        superTypes.add("DataSet");
        atlasEntityDef.setSuperTypes(superTypes);

        AtlasTypesDef atlasTypesDef = new AtlasTypesDef();

        atlasTypesDef.getEntityDefs().add(atlasEntityDef);

        atlasClient.createAtlasTypeDefs(atlasTypesDef);
    }

    private static void createEntity(AtlasClientV2 atlasClient) throws AtlasServiceException {

        AtlasEntity atlasEntity = new AtlasEntity();

        atlasEntity.setTypeName(TYPE_NAME);

        atlasEntity.setAttribute("a", 10);
        atlasEntity.setAttribute("b", 20);
        
        // Following are the mandatory attributes
        atlasEntity.setAttribute("qualifiedName", "CreateEntity_DEMO1");
        atlasEntity.setAttribute("name", "CreateEntity_DEMO1");

        AtlasEntity.AtlasEntityWithExtInfo atlasEntityWithExtInfo = new AtlasEntity.AtlasEntityWithExtInfo();
        atlasEntityWithExtInfo.setEntity(atlasEntity);

        atlasClient.createEntity(atlasEntityWithExtInfo);
    }

    public static void main(String[] args) throws AtlasServiceException, JsonProcessingException {

        AtlasClientV2 atlasClient = new AtlasClientV2(new String[] { "http://localhost:21000" },
                new String[] { "admin", "admin" });

        createType(atlasClient);
        createEntity(atlasClient);

    }
}

Run above application. Login to (http://localhost:21000/) Atlas portal and query for all the entities of type DemoType1, you will see an entity with name ‘CreateEntity_DEMO1’ is created in Atlas.




Click on the entity hyper link to see all the properties of the entity.





Previous                                                    Next                                                    Home

Tuesday, 5 July 2022

Hive: Change the column name and type

Syntax

ALTER TABLE tableName CHANGE columnName newColumnName newColumnType

 

Example

ALTER TABLE employee CHANGE id emp_id BIGINT;

 

Above snippet rename the ‘id’ column of employee table to ‘emp_id’ and set the type to BIGINT.

 

Let’s experiment it with an example.

 

Step 1: Create user table.

CREATE TABLE employee (id INT, name STRING);

hive> CREATE TABLE employee (id INT, name STRING);
OK
Time taken: 0.133 seconds
hive> ;
hive> ;
hive> DESC employee;
OK
id                  	int                 	                    
name                	string              	                    
Time taken: 0.062 seconds, Fetched: 2 row(s)

Step 2: Let’s rename the column name ‘id’ to ‘emp_id’ and change the data type to BIGINT.

 

hive> ALTER TABLE employee CHANGE id emp_id BIGINT;
OK
Time taken: 0.116 seconds
hive> ;
hive> ;
hive> DESC employee;
OK
emp_id              	bigint              	                    
name                	string              	                    
Time taken: 0.081 seconds, Fetched: 2 row(s)

 

 

Previous                                                    Next                                                    Home

Atlas Client: Get all the classification types headers

AtlasClientV2#getAllTypeDefHeaders method can be used to retrieve all the classification types.

 

Example

SearchFilter searchFilter = new SearchFilter();
searchFilter.setParam("type", "classification");
List<AtlasTypeDefHeader> atlasTypesDefHeaders = atlasClient.getAllTypeDefHeaders(searchFilter);

 

Find the below working application.

 

Create atlas-application.properties file under src/main/resources folder.

 

atlas-application.properties

atlas.client.readTimeoutMSecs=30000
atlas.client.connectTimeoutMSecs=30000

 

JsonUtil.java

package com.sample.app.types;

import java.util.List;

import org.apache.atlas.AtlasClientV2;
import org.apache.atlas.AtlasServiceException;
import org.apache.atlas.model.SearchFilter;
import org.apache.atlas.model.typedef.AtlasTypeDefHeader;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.sample.app.util.JsonUtil;

public class GetClassifications {
	
	public static void main(String[] args) throws AtlasServiceException, JsonProcessingException {
		AtlasClientV2 atlasClient = new AtlasClientV2(new String[] { "http://localhost:21000" },
				new String[] { "admin", "admin" });

		SearchFilter searchFilter = new SearchFilter();
		searchFilter.setParam("type", "classification");
		List<AtlasTypeDefHeader> atlasTypesDefHeaders = atlasClient.getAllTypeDefHeaders(searchFilter);

		System.out.println(JsonUtil.prettyPrintJson(atlasTypesDefHeaders));
	}

}

 

GetClassifications.java

package com.sample.app.types;

import java.util.List;

import org.apache.atlas.AtlasClientV2;
import org.apache.atlas.AtlasServiceException;
import org.apache.atlas.model.SearchFilter;
import org.apache.atlas.model.typedef.AtlasTypeDefHeader;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.sample.app.util.JsonUtil;

public class GetClassifications {
	
	public static void main(String[] args) throws AtlasServiceException, JsonProcessingException {
		AtlasClientV2 atlasClient = new AtlasClientV2(new String[] { "http://localhost:21000" },
				new String[] { "admin", "admin" });

		SearchFilter searchFilter = new SearchFilter();
		searchFilter.setParam("type", "classification");
		List<AtlasTypeDefHeader> atlasTypesDefHeaders = atlasClient.getAllTypeDefHeaders(searchFilter);

		System.out.println(JsonUtil.prettyPrintJson(atlasTypesDefHeaders));
	}

}

 

Output

[ {
  "guid" : "d71e4578-3e55-4a86-ae04-c9c971ee0420",
  "name" : "sensitive_data",
  "category" : "CLASSIFICATION"
}, {
  "guid" : "23558f0d-1818-4e16-b583-9160927e07db",
  "name" : "classified",
  "category" : "CLASSIFICATION"
} ]

 


 

 

Previous                                                    Next                                                    Home

Rate limit a spring boot API using Bucket4j

In this post, I am going to explain how to rate limit a spring boot API using Bucket4j.

 

Bucket4j is a Java rate-limiting library based on token-bucket algorithm.

 

What is Token bucket algorithm

A token bucket add or generate tokens at some fixed rate. For example, I can create a token bucket of size 10 and a refill rate of 1 per 10 seconds. This refill happen only when the number of token in the bucket are < 10.

 

Let us try to understand this with below example. 

Time      Requests    AvailableTokens
5:00:00     0          10 (we have 10 tokens initially)
5:00:10     0          10 (refill attempt failed cause Bucket is full)
5:00:20     0          10 (refill attempt failed cause Bucket is full)
5:00:30     0          10 (refill attempt failed cause Bucket is full)
5:00:40     0          10 (refill attempt failed cause Bucket is full)
5:00:50     0          10 (refill attempt failed cause Bucket is full)
5:00:58     8          2 (10 - 8) 
5:01:00     0          3 (refill 1 token)
5:01:10     0          4 (refill 1 token)
5:01:20     0          5 (refill 1 token)
5:01:30     0          6 (refill 1 token)
5:01:49     4          2 (6 - 4) 
5:01:50     0          3 (refill 1 token)

 

When a client send request to the API, application remove the token from bucket if it is available and accept the request. Request is rejected when the bucket do not have any tokens.

 

Define a bucket

Bandwidth limit = Bandwidth.classic(5, Refill.greedy(2, Duration.ofSeconds(30)));
Bucket bucket = Bucket.builder().addLimit(limit).build();

 

Above definition set the bucket capacity to 5 and refill the tokens in a greedy manner (2 tokens for every 30 seconds). For example refill "10 tokens per 1 second" will add 1 token per each 100 millisecond, in other words refill will not wait 1 second to regenerate whole bunch of 10 tokens.

 

Apply the token to REST API

@RequestMapping("/hello")
public ResponseEntity<String> home() {

	System.out.println("Availabel tokens : " + bucket.getAvailableTokens());

	if (bucket.tryConsume(1)) {
		return ResponseEntity.ok("Hello!!!!");
	}

	return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS).header("Retry-After", "10").build();

}

 

'tryConsume(long numTokens)' tries to consume a specified number of tokens from this bucket and return true if the tokens were consumed, false otherwise.

 

Find the below working application.

 

Step 1: Create new maven project ‘bucket4j-hello-world’.

 

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>bucket4j-hello-world</artifactId>
	<version>1</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.6.6</version>
	</parent>

	<dependencies>

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

		<dependency>
			<groupId>com.github.vladimir-bukhtoyarov</groupId>
			<artifactId>bucket4j-core</artifactId>
			<version>7.5.0</version>
		</dependency>


	</dependencies>
</project>

 

Step 3: Define HelloController class.

 

HelloController.java

package com.sample.app.controller;

import java.time.Duration;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Bucket;
import io.github.bucket4j.Refill;

@RestController
public class HelloController {

	private final Bucket bucket;

	public HelloController() {
		Bandwidth limit = Bandwidth.classic(5, Refill.greedy(2, Duration.ofSeconds(30)));
		bucket = Bucket.builder().addLimit(limit).build();
	}

	@RequestMapping("/hello")
	public ResponseEntity<String> home() {

		System.out.println("Availabel tokens : " + bucket.getAvailableTokens());

		if (bucket.tryConsume(1)) {
			return ResponseEntity.ok("Hello!!!!");
		}

		return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS).header("Retry-After", "10").build();

	}
}

Step 4: 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/hello’ in browser.

 

 


 

When the bucket has no token left, you will get http response code 429.

 


 

You can download complete working application from this link.


Previous                                                 Next                                                 Home

Rate limit spring boot apps

 

      Rate limit a spring boot API using Bucket4j