Thursday, 8 September 2022

Quick guide to assertions in Java

In this post, I am going to explain about the assert statement in Java with the help of examples.

 

Assertions were added in Java1.4, that enables you to test the assumptions about your application. Even though assert keyword was added in Java1.4, it is still a little-known feature of the language.

 

Where can I use assertions?

For example, you write a method to calculate the sum of two numbers, you might assert that the calculated sum is not infinity.

 

Assertions are used to

a.   Find the bugs at the earliest during development

b.   Document the inner workings of your program.

 

Assert statement has two forms.

 

Form 1
assert Expression1 ;

 

If the expression1 is not evaluated to true, system will throw an error.

 

App.java

package com.sample.app;

public class App {

    public static boolean isEqual(Object obj1, Object obj2) {
        assert obj1 != null;
        return obj1.equals(obj2);
    }
    
    public static void main(String[] args) {
        isEqual(null, "Hello World");
    }
}

Run above application, you will end up in NullPointerException.

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Object.equals(Object)" because "obj1" is null
    at com.sample.app.App.isEqual(App.java:7)
    at com.sample.app.App.main(App.java:11)

Wait…what happened to my assertion, which is supposed to check obj1 != null, before calling equals method. It is because, assertions are not enabled by default in Java.

 

How to enable assertions in Java?

Use the option -ea or -enableassertions to enable assertions in your application.

java –ea App
    (or)
java –enableassertions App

Run the application by enabling the assertion, you will get assertion error.

 

Exception in thread "main" java.lang.AssertionError

    at com.sample.app.App.isEqual(App.java:6)

    at com.sample.app.App.main(App.java:11)

 

 

Form 2

assert Expression1 : Expression2 ;

 

In this form,

a.   Expression1 is a Boolean expression which is evaluated to either true or false.

b.   Expression2 is an expression that has a value. (It cannot be an invocation of a method that is declared void.)

 

Form2 syntax is used to provide an additional message about the error.

 

Example

assert obj1 != null : "obj1 must not be null";

App.java

package com.sample.app;

public class App {

    public static boolean isEqual(Object obj1, Object obj2) {
        assert obj1 != null : "obj1 must not be null";
        return obj1.equals(obj2);
    }
    
    public static void main(String[] args) {
        isEqual(null, "Hello World");
    }
}

Output

Exception in thread "main" java.lang.AssertionError: obj1 must not be null
    at com.sample.app.App.isEqual(App.java:6)
    at com.sample.app.App.main(App.java:11)

Enable and disable assertions at various granularities

a. Use the option -enableassertions, or -ea to enable assertions at various granularities.

b. Use the option -disableassertions, or -da to disable assertions at various granularities.

 

Following table summarizes the various granularities supported by Java.

 

Granularity

Description

no arguments

Enables or disables assertions in all classes except system classes.

packageName...

Enables or disables assertions in the named package and any subpackages.

...

Enables or disables assertions in the unnamed package in the current working directory.

className

Enables or disables assertions in the named class

 

Example 1: Following command runs HelloWorld program, with assertions enabled in only package com.sample.app.services and its subpackages:

 java -ea:com.sample.app.services... HelloWorld

Example 2: Following command runs the HelloWorld program with assertions enabled in package com.sample.service but disabled in the package com.sample.service.arithmetic.

java -ea:com.sample.service... -da:com.sample.service.arithmetic HelloWorld

Example 3: Following command runs the HelloWorld program with assertions enabled in the clas com.sample.app.MyClass.

java -ea com.sample.app.MyClass HelloWorld

I would suggest you to read this post formore details on when to use assertions and when not to use assertions.

 

You may like

Interview Questions

How to check whether a class is loaded or not in Java?

How to get a random element from Set?

Extract the elements of specific type in a collection

Method overloading ambiguity with null values in Java

Quick guide to load balancers

Constant folding in Java

Atlas Client: Get the glossary by guid

AtlasClientV2#getGlossaryByGuid method is used to get the glossary by guid.

 

Signature

public AtlasGlossary getGlossaryByGuid(String glossaryGuid) throws AtlasServiceException

Example

AtlasGlossary atlasGlossary = atlasClient.getGlossaryByGuid("844a3e1a-110c-4bef-91bf-622dc1eab3e7");

Find the below working application.

 

atlas-application.properties

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

JsonUtil.java

package com.sample.app.util;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JsonUtil {
	public static String marshal(Object obj) throws JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		return mapper.writeValueAsString(obj);
	}

	public static <T> T unmarshal(Class<T> clazz, String json)
			throws JsonParseException, JsonMappingException, IOException {
		ObjectMapper mapper = new ObjectMapper();
		return (T) mapper.readValue(json, clazz);
	}

	public static String prettyPrintJson(Object obj) throws JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		mapper.enable(SerializationFeature.INDENT_OUTPUT);
		return mapper.writeValueAsString(obj);
	}
}

GetGlossaryByGuid.java

package com.sample.app.glossary;

import org.apache.atlas.AtlasClientV2;
import org.apache.atlas.AtlasServiceException;
import org.apache.atlas.model.glossary.AtlasGlossary;

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

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

    AtlasGlossary atlasGlossary = atlasClient.getGlossaryByGuid("844a3e1a-110c-4bef-91bf-622dc1eab3e7");
    
    if(atlasGlossary == null) {
      System.out.println("Glossary not exists");
    }else {
      System.out.println("atlasGlossary : \n" + JsonUtil.prettyPrintJson(atlasGlossary));
    }
    
  }
}

Output

atlasGlossary : 
{
  "guid" : "844a3e1a-110c-4bef-91bf-622dc1eab3e7",
  "qualifiedName" : "myGlosary3",
  "name" : "myGlosary3",
  "shortDescription" : "Demo Glossary",
  "longDescription" : "Demo GLossary.......",
  "terms" : [ {
    "termGuid" : "cd2dbbc5-0440-477e-a6e6-175eb13e3d46",
    "relationGuid" : "607768b1-d47a-4659-aa63-9acc8d175c80",
    "displayText" : "term1"
  } ]
}

    


 

Previous                                                    Next                                                    Home

Hive: degrees(n): Convert radians to degrees

Signature

degrees(n)

hive> SELECT degrees(90);
OK
_c0
5156.620156177409
Time taken: 0.05 seconds, Fetched: 1 row(s)

 

 

 

Previous                                                    Next                                                    Home

Wednesday, 7 September 2022

Atlas Client: Get All glossaries

AtlasClientV2#getAllGlossaries method is used to get all the glossaries.

 

Signature

public List<AtlasGlossary> getAllGlossaries(String sortByAttribute, int limit, int offset) throws AtlasServiceException

 

Example

List<AtlasGlossary> glossaries = atlasClient.getAllGlossaries(null, 10, 0);

 

Find the below working application.

 

atlas-application.properties

 

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

JsonUtil.java

package com.sample.app.util;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JsonUtil {
	public static String marshal(Object obj) throws JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		return mapper.writeValueAsString(obj);
	}

	public static <T> T unmarshal(Class<T> clazz, String json)
			throws JsonParseException, JsonMappingException, IOException {
		ObjectMapper mapper = new ObjectMapper();
		return (T) mapper.readValue(json, clazz);
	}

	public static String prettyPrintJson(Object obj) throws JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		mapper.enable(SerializationFeature.INDENT_OUTPUT);
		return mapper.writeValueAsString(obj);
	}
}

GetAllGlossaries.java

package com.sample.app.glossary;

import java.util.List;

import org.apache.atlas.AtlasClientV2;
import org.apache.atlas.AtlasServiceException;
import org.apache.atlas.model.glossary.AtlasGlossary;

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

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

    List<AtlasGlossary> glossaries = atlasClient.getAllGlossaries(null, 10, 0);
    
    System.out.println("Glossaires : \n" + JsonUtil.prettyPrintJson(glossaries));
  }
}

Output

Glossaires :
[ {
  "guid" : "844a3e1a-110c-4bef-91bf-622dc1eab3e7",
  "qualifiedName" : "myGlosary3",
  "name" : "myGlosary3",
  "shortDescription" : "Demo Glossary",
  "longDescription" : "Demo GLossary.......",
  "terms" : [ {
    "termGuid" : "cd2dbbc5-0440-477e-a6e6-175eb13e3d46",
    "relationGuid" : "607768b1-d47a-4659-aa63-9acc8d175c80",
    "displayText" : "term1"
  } ]
}, {
  "guid" : "d8c82f0e-d7bb-4da8-9b04-a60f24f35761",
  "qualifiedName" : "supply-chain",
  "name" : "supply-chain",
  "shortDescription" : "supply-chain",
  "longDescription" : "supply-chain"
}, {
  "guid" : "62bc12e8-90b6-4bcf-bd08-f25bcf37a93b",
  "qualifiedName" : "finance",
  "name" : "finance",
  "shortDescription" : "finance",
  "longDescription" : "finance"
} ]



  

Previous                                                    Next                                                    Home

Hive: cos: Return cosine of the value

Signature

cos(n)

 

hive> SELECT * FROM emp;
OK
emp.id	emp.name	emp.hobbies	emp.technology_experience	emp.gender_age	emp.rating
1	Hari	["Football","Cricket"]	{"Java":"3.4Yrs","C":"4.5Yrs"}	{"gender":"Male","age":30}	-1.5
2	Chamu	["Trekking","Watching movies"]	{"Selenium":"5.6Yrs"}	{"gender":"Feale","age":38}	3.0
3	Sailu	["Chess","Listening to music"]	{"EmbeddedC":"9Yrs"}	{"gender":"Femle","age":32}	2.5
4	Gopi	["Cricket"]	{"Datastage":"11Yrs"}	{"gender":"Male","age":32}	-0.7
Time taken: 0.043 seconds, Fetched: 4 row(s)
hive> ;
hive> ;
hive> SELECT rating,cos(rating) FROM emp;
OK
rating	_c1
-1.5	0.0707372016677029
3.0	-0.9899924966004454
2.5	-0.8011436155469337
-0.7	0.7648421872844885
Time taken: 0.047 seconds, Fetched: 4 row(s)

 

 

Previous                                                    Next                                                    Home

Monday, 5 September 2022

Hive: conv: Convert number from one base to other base

Signature

conv( bigint n, int from_base, int to_base )

hive> SELECT * FROM emp;
OK
emp.id	emp.name	emp.hobbies	emp.technology_experience	emp.gender_age	emp.rating
1	Hari	["Football","Cricket"]	{"Java":"3.4Yrs","C":"4.5Yrs"}	{"gender":"Male","age":30}	-1.5
2	Chamu	["Trekking","Watching movies"]	{"Selenium":"5.6Yrs"}	{"gender":"Feale","age":38}	3.0
3	Sailu	["Chess","Listening to music"]	{"EmbeddedC":"9Yrs"}	{"gender":"Femle","age":32}	2.5
4	Gopi	["Cricket"]	{"Datastage":"11Yrs"}	{"gender":"Male","age":32}	-0.7
Time taken: 0.056 seconds, Fetched: 4 row(s)
hive> ;
hive> ;
hive> SELECT name,gender_age.age,conv(gender_age.age,10,2) FROM emp;
OK
name	age	_c2
Hari	30	11110
Chamu	38	100110
Sailu	32	100000
Gopi	32	100000
Time taken: 0.056 seconds, Fetched: 4 row(s)

 

 

 

Previous                                                    Next                                                    Home

Apache Atlas: Create glossary term

AtlasClientV2 provides 'createGlossaryTerm' method to create a glossary term.

 

Signature

public AtlasGlossaryTerm createGlossaryTerm(AtlasGlossaryTerm glossaryTerm) throws AtlasServiceException

public List<AtlasGlossaryTerm> createGlossaryTerms(List<AtlasGlossaryTerm> glossaryTerms) throws AtlasServiceException

 

Example

AtlasGlossaryTerm glossaryTerm = new AtlasGlossaryTerm();
glossaryTerm.setName("term1");
glossaryTerm.setShortDescription("term1...");
glossaryTerm.setLongDescription("term1...........");

AtlasGlossaryHeader atlasGlossaryHeader = new AtlasGlossaryHeader();
atlasGlossaryHeader.setGlossaryGuid(persistedGlossary.getGuid());
glossaryTerm.setAnchor(atlasGlossaryHeader);

 

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.util;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JsonUtil {
	public static String marshal(Object obj) throws JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		return mapper.writeValueAsString(obj);
	}

	public static <T> T unmarshal(Class<T> clazz, String json)
			throws JsonParseException, JsonMappingException, IOException {
		ObjectMapper mapper = new ObjectMapper();
		return (T) mapper.readValue(json, clazz);
	}

	public static String prettyPrintJson(Object obj) throws JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		mapper.enable(SerializationFeature.INDENT_OUTPUT);
		return mapper.writeValueAsString(obj);
	}
}

CreateTerm.java

package com.sample.app.glossary;

import org.apache.atlas.AtlasClientV2;
import org.apache.atlas.AtlasServiceException;
import org.apache.atlas.model.glossary.AtlasGlossary;
import org.apache.atlas.model.glossary.AtlasGlossaryTerm;
import org.apache.atlas.model.glossary.relations.AtlasGlossaryHeader;

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

public class CreateTerm {

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

    AtlasGlossary atlasGlossary = new AtlasGlossary();
    atlasGlossary.setName("myGlosary3");
    atlasGlossary.setShortDescription("Demo Glossary");
    atlasGlossary.setLongDescription("Demo GLossary.......");

    AtlasGlossary persistedGlossary = atlasClient.createGlossary(atlasGlossary);
    System.out.println("Glossary : \n" + JsonUtil.prettyPrintJson(persistedGlossary));

    AtlasGlossaryTerm glossaryTerm = new AtlasGlossaryTerm();
    glossaryTerm.setName("term1");
    glossaryTerm.setShortDescription("term1...");
    glossaryTerm.setLongDescription("term1...........");

    AtlasGlossaryHeader atlasGlossaryHeader = new AtlasGlossaryHeader();
    atlasGlossaryHeader.setGlossaryGuid(persistedGlossary.getGuid());
    glossaryTerm.setAnchor(atlasGlossaryHeader);

    AtlasGlossaryTerm persistedGLossaryTerm = atlasClient.createGlossaryTerm(glossaryTerm);
    System.out.println("\n\npersistedGLossaryTerm : \n" + JsonUtil.prettyPrintJson(persistedGLossaryTerm));

  }
}

 

Output

Glossary : 
{
  "guid" : "844a3e1a-110c-4bef-91bf-622dc1eab3e7",
  "qualifiedName" : "myGlosary3",
  "name" : "myGlosary3",
  "shortDescription" : "Demo Glossary",
  "longDescription" : "Demo GLossary......."
}


persistedGLossaryTerm : 
{
  "guid" : "cd2dbbc5-0440-477e-a6e6-175eb13e3d46",
  "qualifiedName" : "term1@myGlosary3",
  "name" : "term1",
  "shortDescription" : "term1...",
  "longDescription" : "term1...........",
  "anchor" : {
    "glossaryGuid" : "844a3e1a-110c-4bef-91bf-622dc1eab3e7",
    "relationGuid" : "607768b1-d47a-4659-aa63-9acc8d175c80"
  },
  "glossaryTermHeader" : {
    "termGuid" : "cd2dbbc5-0440-477e-a6e6-175eb13e3d46",
    "qualifiedName" : "term1@myGlosary3"
  }
}

 

You can confirm the same from Atlas UI.

 


 

 

 

Previous                                                    Next                                                    Home