Saturday, 9 July 2022

How to call super class method from sub class overriding method?

Yes, you can call the super class method from subclass overriding method using super keyword.

 

Syntax

super.methodName(arguments); 

 

MethodOverridingDemo1.java

package com.sample.app;

public class MethodOverridingDemo1 {
	
	public static class A{
		public void welcomeUser() {
			System.out.println("Hiiii!!!!!");
		}
	}
	
	public static class B extends A{
		@Override
		public void welcomeUser() {
			super.welcomeUser();
			System.out.println("Hello...........");
		}
	}
	
	public static void main(String[] args) {
		B b = new B();
		b.welcomeUser();
	}

}

 

Output

Hiiii!!!!!
Hello...........

 

Unlink constructor, super class method call doesn’t need to be first statement in the overriding method.

public static class B extends A {
	@Override
	public void welcomeUser() {
		System.out.println("Hello...........");
		super.welcomeUser();

	}
}

 

MethodOverridingDemo2.java

package com.sample.app;

public class MethodOverridingDemo2 {

	public static class A {
		public void welcomeUser() {
			System.out.println("Hiiii!!!!!");
		}
	}

	public static class B extends A {
		@Override
		public void welcomeUser() {
			System.out.println("Hello...........");
			super.welcomeUser();

		}
	}

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

}

 

Output

Hello...........
Hiiii!!!!!

 

You can call super class method any number of times from the sub class method.

 

MethodOverridingDemo3.java

package com.sample.app;

public class MethodOverridingDemo3 {

	public static class A {
		public void welcomeUser() {
			System.out.println("Hiiii!!!!!");
		}
	}

	public static class B extends A {
		@Override
		public void welcomeUser() {
			super.welcomeUser();
			System.out.println("Hello...........");
			super.welcomeUser();
			super.welcomeUser();
			super.welcomeUser();

		}
	}

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

}

 

Output

Hiiii!!!!!
Hello...........
Hiiii!!!!!
Hiiii!!!!!
Hiiii!!!!!

 

You can call any non-private method of super class from the subclass.

 


public static class B extends A {
	public void demo() {
		welcomeUser();
		welcomeUser();
	}
}

SuperclassMethodCallDemo.java

package com.sample.app;

public class SuperclassMethodCallDemo {
	public static class A {
		public void welcomeUser() {
			System.out.println("Hiiii!!!!!");
		}
	}

	public static class B extends A {
		public void demo() {
			welcomeUser();
			welcomeUser();
		}
	}
	
	public static void main(String[] args) {
		new B().demo();
	}
}

Output

Hiiii!!!!!
Hiiii!!!!!

Is it mandatory to call super class method from overriding method?

No, it is optional.

 

MethodOverridingDemo4.java

package com.sample.app;

public class MethodOverridingDemo4 {
	public static class A {
		public void welcomeUser() {
			System.out.println("Hiiii!!!!!");
		}
	}

	public static class B extends A {
		@Override
		public void welcomeUser() {
			System.out.println("Hello...........");
		}
	}

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

Output

Hello...........

You may like

Interview Questions

float vs double in Java

Quick guide to race condition in Java with examples

How to read the file content using an iterator in Java?

Implement a Closeable iterator in Java

Quick guide to generate random data in Java

What are the different cache eviction strategies?





Friday, 8 July 2022

How to get the decimal grouping character for given locale?

Below snippet return the decimal grouping separator for given locale.

private static Character getDecimalGroupingChar(Locale locale) {
	DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(locale);
	DecimalFormatSymbols symbols = format.getDecimalFormatSymbols();
	Character groupingChar = symbols.getGroupingSeparator();
	return groupingChar;
}

 


Find the below working application.

 

DecimalGroupingCharDemo.java
package com.sample.app;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;

public class DecimalGroupingCharDemo {
	private static final double NUMBER = 987654321.123;

	private static Character getDecimalGroupingChar(Locale locale) {
		DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(locale);
		DecimalFormatSymbols symbols = format.getDecimalFormatSymbols();
		Character groupingChar = symbols.getGroupingSeparator();

		System.out.println(locale + "\t\t\t'" + groupingChar + "'\t" + format.format(NUMBER));

		return groupingChar;
	}

	public static void main(String[] args) {
		System.out.println("Country  decimalGroupingCharacter  " + NUMBER);

		getDecimalGroupingChar(Locale.GERMAN);
		getDecimalGroupingChar(new Locale("fi"));
		getDecimalGroupingChar(new Locale("en_IN"));

	}

}

 

Output

Country  decimalGroupingCharacter  9.87654321123E8
de			'.'	987.654.321,123
fi			' '	987 654 321,123
en_in			','	987,654,321.123

 

 

 

You may like

Miscellaneous

Extract private and public key from keystore

Public, private key generation in Java

Export public key certificate from keystore

Read pkcs12 certificate information in Java

How to Get Client Certificate from HttpServletRequest

Programmatically import certificate to cacerts file in Java

Sign a jar file using jarsigner tool

Atlas client: Create a type, where attribute type is a set

In this post, I am going to explain how can we define an attribute that takes list of string.

 

To define an attribute with type list, you should specify

a.   typeName as array<string>

b.   cardinality should be set to SET like below.

 

"attributeDefs": [
    {
      "name": "hobbies",
      "typeName": "array<string>",
      "isOptional": false,
      "cardinality": "SET",
      "valuesMinCount": 1,
      "valuesMaxCount": 2147483647,
      "isUnique": false,
      "isIndexable": true,
      "includeInNotification": false,
      "searchWeight": -1
    }
  ]

 

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

 

atlas-application.properties

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

 

Define AttributeWithSetOfStrings class.

 

AttributeWithSetOfStrings.java

package com.sample.app.attributes;

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.AtlasTypesDef;
import org.apache.atlas.model.typedef.AtlasStructDef.AtlasAttributeDef;

import com.fasterxml.jackson.core.JsonProcessingException;

public class AttributeWithSetOfStrings {

  private static final String TYPE_NAME = "DemoType3";

  private static void createType(AtlasClientV2 atlasClient) throws AtlasServiceException {
    AtlasAttributeDef attributeDef1 = new AtlasAttributeDef();
    attributeDef1.setName("hobbies");
    attributeDef1.setTypeName("array<string>");
    attributeDef1.setCardinality(AtlasAttributeDef.Cardinality.SET);
    attributeDef1.setIsIndexable(true);
    attributeDef1.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));

    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("hobbies", Arrays.asList("football", "cricket", "football"));

    // Following are the mandatory attributes
    atlasEntity.setAttribute("qualifiedName", "AttributeWithSetOfStrings_DEMO1");
    atlasEntity.setAttribute("name", "AttributeWithSetOfStrings_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.

 

Open Atlas UI and query for the type ‘DemoType3’.

 

 


 

  Navigate to the entity ‘AttributeWithSetOfStrings_DEMO1’ to see the properties.

 


 

 

Previous                                                    Next                                                    Home

HIVE: Execute sql statements in a file

Syntax

hive -f {FILE_PATH}

 

Step 1: Let’s create sql statement in a file ‘data.sql’

 

data.sql

CREATE TABLE employee (
id INT,
name STRING,
hobbies ARRAY<STRING>,
technology_experience MAP<STRING,STRING>,
gender_age STRUCT<gender:STRING,age:INT>
)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '|'
COLLECTION ITEMS TERMINATED BY ','
MAP KEYS TERMINATED BY ':'
STORED AS TEXTFILE;

Step 2: Execute data.sql file using hive command line tool.

$hive -f data.sql 
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/usr/local/Cellar/hive/3.1.2_2/libexec/lib/log4j-slf4j-impl-2.10.0.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/usr/local/Cellar/hadoop/3.3.0/libexec/share/hadoop/common/lib/slf4j-log4j12-1.7.25.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.apache.logging.slf4j.Log4jLoggerFactory]
Hive Session ID = 7b4468cf-f00b-4173-b88a-ec8e2b347ccb

Logging initialized using configuration in jar:file:/usr/local/Cellar/hive/3.1.2_2/libexec/lib/hive-common-3.1.2.jar!/hive-log4j2.properties Async: true
Hive Session ID = e2a6e609-4fa0-48a4-85bc-0bed0358b0c3
OK
Time taken: 1.433 seconds

Step 3: login to hive in interactive mode and execute the command ‘show tables’ to confirm.

hive> show tables;
OK
employee
Time taken: 0.062 seconds, Fetched: 1 row(s)


 

Previous                                                    Next                                                    Home

Atlas client: Create a type, where attribute type is a list

In this post, I am going to explain how can we define an attribute that takes list of string.

 

To define an attribute with type list, you should specify

a.   typeName as array<string>

b.   cardinality should be set to LIST like below.

 

"attributeDefs": [
    {
      "name": "hobbies",
      "typeName": "array<string>",
      "isOptional": false,
      "cardinality": "LIST",
      "valuesMinCount": 1,
      "valuesMaxCount": 2147483647,
      "isUnique": false,
      "isIndexable": true,
      "includeInNotification": false,
      "searchWeight": -1
    }
  ]

 

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 AttributeWithListOfStrings class.

 

AttributeWithListOfStrings.java

package com.sample.app.attributes;

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.AtlasTypesDef;
import org.apache.atlas.model.typedef.AtlasStructDef.AtlasAttributeDef;

import com.fasterxml.jackson.core.JsonProcessingException;

public class AttributeWithListOfStrings {

	private static final String TYPE_NAME = "DemoType2";

	private static void createType(AtlasClientV2 atlasClient) throws AtlasServiceException {
		AtlasAttributeDef attributeDef1 = new AtlasAttributeDef();
		attributeDef1.setName("hobbies");
		attributeDef1.setTypeName("array<string>");
		attributeDef1.setCardinality(AtlasAttributeDef.Cardinality.LIST);
		attributeDef1.setIsIndexable(true);
		attributeDef1.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));

		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("hobbies", Arrays.asList("football", "cricket", "football"));

		// Following are the mandatory attributes
		atlasEntity.setAttribute("qualifiedName", "AttributeWithListOfStrings_DEMO1");
		atlasEntity.setAttribute("name", "AttributeWithListOfStrings_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);

	}
}

 

Login to Atlas UI and query for the type ‘DemoType2’.

 

  


Navigate to the entity ‘AttributeWithListOfStrings_DEMO1’ to see all the properties.

 

 


As you see above image, hobby ‘football’ is repeated twice. We can solve this problem by making the attribute cardinality as SET. I will explain this in my next post.


Previous                                                    Next                                                    Home

Hive: Replace columns of a table

  Syntax 

ALTER TABLE name REPLACE COLUMNS (col_spec[, col_spec ...])

 

Example

ALTER TABLE employee REPLACE COLUMNS ( 
emp_id INT,  
emp_name STRING);

 

Above snippet delete all the columns from the employee table and replaces it with emp_id, emp_name columns. You can use ‘REPLACE COLUMNS’ statement to delete a column.

hive> DESC employee;
OK
id                  	int                 	                    
name                	string              	                    
organization        	string              	Organization name in the compay
age                 	int                 	employee age        
Time taken: 0.073 seconds, Fetched: 4 row(s)
hive> ;
hive> ;
hive> ALTER TABLE employee REPLACE COLUMNS ( 
    > emp_id INT,  
    > emp_name STRING);
OK
Time taken: 0.088 seconds
hive> ;
hive> ;
hive> DESC employee;
OK
emp_id              	int                 	                    
emp_name            	string              	                    
Time taken: 0.102 seconds, Fetched: 2 row(s)



Previous                                                    Next                                                    Home

Wednesday, 6 July 2022

Hive: Add columns to existing table

Syntax

ALTER TABLE name ADD COLUMNS (col_spec[, col_spec ...])

Example

ALTER TABLE employee ADD COLUMNS ( 
organization STRING COMMENT 'Organization name in the compay',
age INT COMMENT 'employee age');

Above snippet add two columns to employee table.

a.   organization

b.   age

 

Let’s experiment it with an example.

 

Step 1: Create employee table by executing below command.

CREATE TABLE employee (id INT, name STRING);

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

Let’s add couple of columns to employee table.

 

ALTER TABLE employee ADD COLUMNS ( 
organization STRING COMMENT 'Organization name in the compay',
age INT COMMENT 'employee age');

 

hive> ALTER TABLE employee ADD COLUMNS ( 
    > organization STRING COMMENT 'Organization name in the compay',
    > age INT COMMENT 'employee age');
OK
Time taken: 0.132 seconds
hive> ;
hive> ;
hive> DESC employee;
OK
id                  	int                 	                    
name                	string              	                    
organization        	string              	Organization name in the compay
age                 	int                 	employee age        
Time taken: 0.057 seconds, Fetched: 4 row(s)

 

 

Previous                                                    Next                                                    Home