[Solved] javax.naming.NameNotFoundException: MyXYZConnectionFactory not found


javax.naming.NameNotFoundException: MyXYZQueueConnectionFactory not found error occurred when JNDI name trying to configured it not exist on provider or some mismatch with name.

For Example:
In this example, I was trying to get MyXYZQueueConnectionFactory while factory on provider JNDI name is given as MyQueueConnectionFactory.

Stacktrace of Error


Binding name:`java:comp/env/jms/QueueName `
Binding name:`java:comp/env/jms/MyQueueConnectionFactory `
JNDI lookup failed: javax.naming.NameNotFoundException: MyXYZQueueConnectionFactory not found
Unbinding name:`java:comp/env/jms/QueueName `
Unbinding name:`java:comp/env/jms/MyXYZQueueConnectionFactory `

Solutions

  • Check for JNDI name and factory created on configured server.
  • Check name of JNDI and factory is same as you want to pint on server.

[Solved] JMSInitialContext: Unable to get the internal JNDI context


JMSInitialContext: “Unable to get the internal JNDI context” error occurs when the developer/ config person has incorrectly specified the client properties file.

For Example: A developer might have used the windows syntax for path in a unix system environment. This error can also occurred when the correct path to the app.properties file is not correct.

Solutions

The developer/config person has to define the path to the config directory properly and defined JNDI should be available.

Stacktrace of Error


java -Djms.properties=%J2EE_HOME%\config\app.properties MyQueueSender MyFIOTQueue

Queue name is MyFIOTQueue


SEVERE JMSInitialContext: Unable to get internal JNDI context because:
javax.naming.CommunicationException: Cannot connect to ORB [Root exception is
org.omg.CORBA.COMM_FAILURE: minor code: 789479689 completed: No]
This error can be rectified by the user setting the class path for the client application correctly.

[Solved]com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table ‘ABC’ doesn’t exist


“com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table ‘test.stock’ doesn’t exist” this exception in hibernate generally occured when mentioned table in mapping(hbm.xml) or JPA annotated entity table not exist in database. Sometime table exist in database but table with mentioned catalog or schema (due to copy paste or typing mistake) doesn’t exist.

Problem

In this case issue is “com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table ‘test.stock’ doesn’t exist”. This issue is because of ‘test.stock’ table is not find out because here in put mentioned catalog as “test” that is schema or database name while in hibernate.cfg.xml mentioned schema name as facingissuesonitdb.

Input Stock.hbm.xml


<hibernate-mapping>
    <class name="com.facingissuesonit.model.Stock" table="stock" catalog="test">
    <id name="stockId" type="java.lang.Integer">
            <column name="STOCK_ID" />
            <generator class="identity" />
        </id>
        <property name="stockCode" type="string">
            <column name="STOCK_CODE" length="10" not-null="true" unique="true" />
        </property>
        <property name="stockName" type="string">
            <column name="STOCK_NAME" length="20" not-null="true" unique="true" />
        </property>
     
    </class>
</hibernate-mapping>
     

Exception StackTrace


ERROR: Table 'test.stock' doesn't exist
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test.stock' doesn't exist
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
    at com.mysql.jdbc.Util.getInstance(Util.java:381)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3558)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3490)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2109)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2643)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2077)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2362)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2280)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2265)
    at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:384)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:205)
    ... 22 more

Solutions

  • Solution 1: Replace above xml attribute catalog value from “test” to “facingissuesonitdb” as used same in hibernate.cfg.xml.
  • Solution 2: If your application is using only one database/schema then recommendation is to mention schema name in hibernate.cfg.xml so that in future if your schema name get change only configuration file need to update not all mapping files.
    
    <property name="hibernate.default_schema">'facingissuesonitdb'</property>
    

[Solved]org.hibernate.MappingException: Unknown entity: XYZ


“org.hibernate.MappingException: Unknown entity” this exception occurred when you are using an entity in Hibernate session but with respect to that entity mapping file (hbm.xml) is not defined or used an POJO class with out any JPA/Hibernate annotations.

Example


org.hibernate.MappingException: Unknown entity: com.facingissuesonit.model.Stock
    at org.hibernate.metamodel.internal.MetamodelImpl.entityPersister(MetamodelImpl.java:620)
    at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1634)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:104)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:689)

Solutions

In my case, I used an entity Stock in hibernate session but forget to add my Stock.hbm.xml file mapping in hibernate.cfg.xml file. When I added this line of statement in my hibernate.cfg.xml then problem resolved.

Problem: Hibernate was trying to find out the mapping for used entity Stock.java in all defined XML and not able to get that’s what throw exception.
Add this line in hibernate.cfg.xml



Java Program: Print characters having prime frequencies in order of occurrence


Question : Print characters having prime frequencies in order of occurrence

Given a string str containing only lowercase characters. The task is to print the characters having prime frequency in the order of their occurrence. Note that repeated elements with prime frequencies are printed as many times as they occur in order of their occurrence.

Examples:

  • Input: str = “facingissuesonit”
    Output: facingissuesonit Frequency
    ‘f’ 1
    ‘a’ 1
    ‘c’ 1
    ‘i’ 3
    ‘n’ 2
    ‘g’ 1
    ‘s’ 3
    ‘u’ 1
    ‘e’ 1
    ‘o’ 1
    ‘t’ 1

    ‘i’, ‘n’ and ‘s’ are the only characters with prime frequencies.
    Output: insinsis

  • Input: str = “aeroplane”
    Output: aeae

Algorithm

  • Step 1: Ask the user to input String
  • Step 2: Get count of each character occurrence and insert in character-based sorted map
  • Step 3: Remove Character those occurrences are not Prime
  • Step 4: Print Character in alphabetical order and reduce the count by one
  • Step 5: Remove an entry from the map if the count is zero
  • Step 6: Repeat step 4 and 5 until map get empty

Java Program

 

public class Program2 {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);
System.out.print("Enter a text String: ");
String inputStr = input.nextLine();
System.out.println("Result :" + primePlacesString(inputStr));
}

private static List primePlacesString(String inputStr) {
List charList = null;
char[] chars = inputStr.toCharArray();
// Enter Character and respected occurence in map
TreeMap map = new TreeMap();
for (Character c : chars) {
if (map.get(c) == null) {
map.put(c, 1);
} else {
map.put(c, map.get(c).intValue() + 1);
}
}
// Removed character those occurence are not prime
Character[] keys = (Character[]) map.keySet().toArray(new Character[map.size()]);
for (Character key : keys) {
if (!isPrimeNumber(map.get(key))) {
map.remove(key);
}
}
// get list of character in sequence as per counts
if (map != null && !map.isEmpty()) {
charList = new ArrayList();
printMapInSquence(map, charList);
}
return charList;
}

// Code to check number is prime or not
private static boolean isPrimeNumber(Integer number) {
boolean isPrimeNumber = true;
if (number == 0 || number == 1) {
isPrimeNumber = false;
} else {
for (int i = 2; i <= number / 2; i++) {
if (number % i == 0) {
isPrimeNumber = false;
break;
}
}
}

return isPrimeNumber;
}

private static void printMapInSquence(Map map, List charList) {
if (map != null && !map.isEmpty()) {

Character[] keys = (Character[]) map.keySet().toArray(new Character[map.size()]);
for (Character key : keys) {
charList.add(key);
if (map.get(key) == 1) {
// remove characters those are already printed and count are 1
map.remove(key);
} else {
// reduce counts of printed characters and counts more than one
map.put(key, map.get(key) - 1);
}
}
printMapInSquence(map, charList);
}
}

}

Output


Enter a text String: facingissuesonit
Result :[i, n, s, i, n, s, i, s]

Enter a text String: aeroplane
Result :[a, e, a, e]

 

[Solved]org.hibernate.exception.SQLGrammarException: could not execute statement


“org.hibernate.exception.SQLGrammarException: could not execute statement” this exception generally occurred when there is some issue with generated query grammar or syntax. Actual reason of issue you will in exception stacktrace cause.

Problem

In this case issue is “com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table ‘test.stock’ doesn’t exist”. This issue is because of test.stock table is not find out because here input mapping xml file having catalog as “test” that is schema or database name while in hibernate.cfg.xml mentioned schema name as facingissuesonitdb.

Input Stock.hbm.xml


<hibernate-mapping>
    <class name="com.facingissuesonit.model.Stock" table="stock" catalog="test">
    <id name="stockId" type="java.lang.Integer">
       <column name="STOCK_ID" />
       <generator class="identity" />
    </id>
    <property name="stockCode" type="string">
           <column name="STOCK_CODE" length="10" not-null="true"     unique="true" />
    </property>
    <property name="stockName" type="string">
            <column name="STOCK_NAME" length="20" not-null="true" unique="true" />
    </property>
</class>
</hibernate-mapping>

Exception StackTrace


ERROR: Table 'test.stock' doesn't exist
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute statement
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
    at org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:57)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:42)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2909)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3480)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:626)
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:280)
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:261)
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:306)
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:318)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:275)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:182)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:113)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:689)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:681)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:676)
    at com.facingissuesonit.App.main(App.java:29)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test.stock' doesn't exist
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
    at com.mysql.jdbc.Util.getInstance(Util.java:381)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3558)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3490)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2109)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2643)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2077)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2362)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2280)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2265)
    at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:384)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:205)
    ... 22 more

Solutions

  • Solution 1: Replace above xml attribute catalog value from “test” to “facingissuesonitbd” as used same in hibernate.cfg.xml.
  • Solution 2: If your application is using only one database/schema then recommendation is to mention schema name in hibernate.cfg.xml so that in future if your schema name get change only configuration file need to update not all mapping files.
    
    <property name="hibernate.default_schema">facingissuesonitdb</property>
    

Java Program : Get all possible values of X such that A % X = B


Question:  Write a java program to get  all possible values of X such that A % X = B. Input two integers A and B. The task is to find the  all possible values X such that A % X = B. If there are infinite number of possible values then print -1.

Examples:

  1. Input: A = 21, B = 5
    Output: 2
    8 and 16 are the only valid values for X.
  2. Input: A = 5, B = 5
    Output: -1
    X can have any value > 5

Algorithm

  • Step 1: Ask the user to input values of A and B
  • Step 2: Find out all possible factors of (A-B) which are greater than B
  • Step 3: Use StringJoiner to print the possible value in comma separated form.

Java Program

public class Program1 {
public static void main(String[] args) {
System.out.println("Enter values of A and B to get possible values of X from expression A % X = B");

Scanner input = new Scanner(System.in);
System.out.print("Please Enter an integer A: ");
int A = input.nextInt();

System.out.print("Please Enter an integer B: ");
int B = input.nextInt();

System.out.println("Possible Values of X :" + getAllowedValues(A, B));
}

private static String getAllowedValues(int A, int B) {
//Use to print value in comma separated form
StringJoiner joiner = new StringJoiner(",");

if (A - B > 0) {
//find out all possible factor of(A-B) which are greater than B
for (int C = (A - B); C > 0 & C > B; C /= 2) {
if ((A - B) % C == 0)
joiner.add(Integer.toString(C));
}
} else {
joiner.add("-1");
}
return joiner.toString();
}

}

Output


Enter values of A and B to get possible values of X from expression A % X = B
Please Enter an integer A: 21
Please Enter an integer B: 5
Possible Values of X :16,8

Enter values of A and B to get possible values of X from expression A % X = B
Please Enter an integer A: 5
Please Enter an integer B: 5
Possible Values of X :-1

[Solved] Fortify Issue “Log Forging” and “Cross Site Script Injection” in log file


To fix fortify scan “Log Forging” or “Cross Site Script Injection” issue need to remove script tag before printing log message in console or log file.

Why?

If logs statement having script tag then open these logs over browser like kibana while analysis. The script or content inside the script tag can execute that cause “cross-site script injections”.

Solutions

Call this lines of code which below uses a regular expression to identify valid script tags and removes them from the message while leaving the script code between the starting and end tags.

Remove script tag from log string message

[Solved] Maven Error on Eclipse/STS : Could not calculate build plan org.apache.maven.plugins:maven-jar-plugin:jar:2.4


This maven error generally happen when create maven based web project by using “maven-archtype-console” which generally try to import all library automatically.

You will see this complete error message on pom.xml


Could not calculate build plan: Plugin org.apache.maven.plugins:maven-jar-plugin:2.4 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-jar-plugin:jar:2.4

maven error

POM.XML



  4.0.0
  com.FacingIssuesOnIT
  Spring-Core-Examples
  0.0.1-SNAPSHOT
  Spring-Core-Examples
  Spring Core Exammples

Solution 1:

You need just to follow those steps:
Right Click on your project: Run (As) -> Maven clean
Right Click on your project: Run (As) -> Maven install
After which, if the build fails when you do Maven Install, it means there is no web.xml file under WEB-INF or some problem associated with it.

Solution 2:

Right click on project-> Maven->Click checked box ‘Force Update’->Update

[Solved] Maven Error on Eclipse/STS : Failure to transfer org.apache.maven.plugins:maven-surefire-plugin:pom:2.12.4


This maven error generally happen when create maven based web project by using “maven-archtype-webapp” which generally try to import all library automatically.

You will see this complete error message on pom.xml


Description Resource Path Location Type Failure to transfer org.apache.maven.plugins:maven-surefire-plugin:pom:2.12.4 from http://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced. Original error: Could not transfer artifact org.apache.maven.plugins:maven-surefire-plugin:pom:2.12.4 from/to central (http://repo.maven.apache.org/maven2): The operation was cancelled. pom.xml /SpringCoreTuto line 1 Maven Configuration Problem

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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.fiot.example</groupId>
  <artifactId>SpringCoreTuto</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringTuto Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>SpringCoreTuto</finalName>
  </build>
</project>

Solution 1:

You need just to follow those steps:
Step 1: Right Click on your project: Run (As) -> Maven clean
Step 2: Right Click on your project: Run (As) -> Maven install
After which, if the build fails when you do Maven Install, it means there is no web.xml file under WEB-INF or some problem associated with it.

Solution 2:

Right click on project-> Maven->Click checked box ‘Force Update’->Update

[Solved] javax.crypto.AEADBadTagException: Tag mismatch


AEADBadTagException is subclass of BadPaddingException. It’s occurred when a Cipher unable to verify the authentication tag. It’s occurred when Cipher is AEAD i.e GCM/CCM mode.

public class AEADBadTagException extends BadPaddingException

Constructor

  • AEADBadTagException(): Constructs a default constructor of AEADBadTagException with no detail message.
  • AEADBadTagException(String msg): Constructs a message constructor of AEADBadTagException with the specified detail message.

Exception

Here is a complete example of encryption and decryption based on algorithm AES/GCM/NoPadding but having an issue because of IV value which is used for authentication.

import java.security.SecureRandom;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>
/**
* example for plain text encryption and decryption by using Java AES 256 GCM Encryption Algorithm
*/
public class AES_GCM_Example
{
        static String plainText = "facing Issues on IT  (Learn from Others Experience)";
           public static final int AES_KEY_SIZE = 256;
           public static final int GCM_IV_LENGTH = 12;
           public static final int GCM_TAG_LENGTH = 16;

           public static void main(String[] args) throws Exception
           {
               KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
               keyGenerator.init(AES_KEY_SIZE);

               // Generate Key
               SecretKey key = keyGenerator.generateKey();

               byte[] IV = new byte[GCM_IV_LENGTH];
               SecureRandom random = new SecureRandom();
               random.nextBytes(IV);

               System.out.println("Original Text : " + plainText);

               byte[] cipherText = encrypt(plainText.getBytes(), key, IV);
               System.out.println("Encrypted Text : " + Base64.getEncoder().encodeToString(cipherText));

               String decryptedText = decrypt(cipherText, key, IV);
               System.out.println("DeCrypted Text : " + decryptedText);
           }

           public static byte[] encrypt(byte[] plaintext, SecretKey key, byte[] IV) throws Exception
           {
               // Get Cipher Instance for selected algorithm
               Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");

               // Create SecretKeySpec for key
               SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");

               // Create GCMParameterSpec for key
               GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, IV);

               // Initialize Cipher for ENCRYPT_MODE for encrypt plaintext
               cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmParameterSpec);

               // Perform Encryption
               byte[] cipherText = cipher.doFinal(plaintext);

               return cipherText;
           }

           public static String decrypt(byte[] cipherText, SecretKey key, byte[] IV) throws Exception
           {
               // Get Cipher Instance based on selective AES algorithm
               Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");

               // Create SecretKeySpec for key
               SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");

               // Create GCMParameterSpec for key
               //IV = new byte[GCM_IV_LENGTH]; //here is issue

               GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, IV);

               // Initialize Cipher for DECRYPT_MODE to in plain text
               cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmParameterSpec);

               // Perform Decryption on encrypted text
               byte[] decryptedText = cipher.doFinal(cipherText);

               return new String(decryptedText);
           }

       }

Output


Original Text : facing Issues on IT  (Learn from Others Experience)
Encrypted Text : AxboQXVKKPMm05cRaslMuxDl8IK77OLgG2ddnVSKzQUVQEXL/Xic+OHN/8ixbrFbvSrytStUWBsYQyXIWLQB22+0sg==
Exception in thread "main" javax.crypto.AEADBadTagException: Tag mismatch!
       at com.sun.crypto.provider.GaloisCounterMode.decryptFinal(GaloisCounterMode.java:524)
       at com.sun.crypto.provider.CipherCore.finalNoPadding(CipherCore.java:1023)
       at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:960)
       at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:824)
       at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:436)
       at javax.crypto.Cipher.doFinal(Cipher.java:2121)
       at enc_dec.AES_GCM_Example.decrypt(AES_GCM_Example.java:84)
       at enc_dec.AES_GCM_Example.main(AES_GCM_Example.java:41)

Solution

Here is an issue on decryption while changing the value of IV as in line by creating new byte array which is different from the value passed in encryption that’s why encryption and decryption authentication get failed.

As a solution specific this issue comment line 68 and it will return output as below.


Original Text : facing Issues on IT  (Learn from Others Experience)
Encrypted Text : faSkDrA737VyiocRk1n5arFGaO5r7GDN6xFmz7hjZppkN0y8sgcj9N5iqaZ2+gbRowli5Ocfm1sQB2qL+nEVIzsWVg==
DeCrypted Text : facing Issues on IT  (Learn from Others Experience)

References

[Solved] org.apache.tika.parser.utils.DataURISchemeParseException


DataURISchemaParseException is a subclass of TikaException. This schema has occurred when there is a mismatch of syntax or encoding of URI data when compared with URI schema.

public class DataURISchemeParseException extends TikaException

Constructors

  • DataURISchemeParseException(String msg)

Data URI Scheme?

Data URI Scheme is a URI scheme that provides a way to include data inline in webpages if that were external resources. The data URI scheme is useful to get CSS or images for the web pages with the same URL and no need any separate HTTP URL for download.

Data URI Schema.jpg

For more detail, about Data URI Schema you can refer this link: https://en.wikipedia.org/wiki/Data_URI_scheme

References

https://tika.apache.org/1.22/api/org/apache/tika/parser/utils/DataURISchemeParseException.html

Python Overview


Python is a general-purpose interpreted, interactive, object-oriented, scripting, and high-level programming language. Python is highly readable and mostly uses English keywords and syntactical constructions other than languages.

Python Developed by Guido van Rossum during 1985- 1990. Python source code is also available in the GNU GPL (General Public License).

Why Python?

  • Python is Interpreted: Python did not require compilation. It’s processed by an interpreter at runtime. This is similar to PHP and PERL.
  • Python is Interactive: Python is interactive because you can write a python program on Python prompt and interact with an interpreter.
  • Python is Object-Oriented: Python supports Object-Oriented features for programming that encapsulates code within objects.
  • Python is a Startup Language for Beginner’s: Python supports a wide range of applications from Simple text to WWW browsers to games. Its keyword is the most common words of English to understand a program.

Python Features

Python is the most widely used language for application development. Here are the most important features that are the reason it’s most preferred:

  • Easy-to-learn: Python has a simple structure, keywords of the English language, and a clearly defined syntax. This allows the beginner level programmer to easily pick up.
  • Easy-to-read: Python code is more clear and indentation based formatting so you can easily read it.
  • Easy-to-maintain: Python’s source code is easy-to-maintain.
  • A broad standard library: Python’s library is cross-platform compatible and very portable.
  • Interactive Mode: Python is interactive because you can write a python program on Python prompt and interact with the interpreter. It allows testing and debugging of code on the snippet.
  • Extendable: Python is extendable to add low-level modules to the interpreter. By these modules enable programmers to add to or customize their tools to be more efficient.
  • Portable: Python is portable because it runs on a variety of hardware platforms and provides the same interface for all platforms.
  • Scalable: Python provides a better structure and support for programs for application than shell scripting.
  • Databases: Python provides interfaces to support all major databases use for commercial applications.
  • GUI Programming: Python supports GUI applications that can be developed and ported to so many system calls, libraries and windows systems, Macintosh, Windows MFC, etc.

Python Characteristics

These are the most important characteristics of Python Programming Language:

  • Python supports structured and functional programming methods and also supports some features of OOP.
  • Python can be used as a scripting language or can be compiled to byte-code for developing large applications.
  • Python supports dynamic type checking and also provides very high-level dynamic data types.
  • Python supports automatic garbage collection the same as Java.
  • Python can be easily integrated with C, C++, ActiveX, CORBA, COM, and Java.

Where to use Python?

Python is a very popular language to use in developing the application, used a scripting language and nowadays is the most popular language to use in Artificial intelligence and machine learning.

  • Web Development: Django, Bottle, Pyramid, Tornado, Flask, Web2py
  • GUI Development: tkInter, pyQt, PySide, Kivy, wxPython, PygObject
  • Software Development: Buildbot, Trac, Roundup
  • System Administration: Ansible, OpenStack, Salt
  • Scientific and Numeric: Pandas, IPython, SciPy

References

[Solved] org.apache.tika.parser.chm.exception.ChmParsingException


ChmParsingException is a subclass of TikaException. This is exception occurs when there is a problem with the CHM file.

public class ChmParsingExceptionv extends TikaException

Constructors

  • ChmParsingException(String description)

CHM ?

CHM is a compiled HTML help format used for software documentation, which consists of HTML pages, indexes, and other navigation tools. These files are compressed and deployed in binary format.

CHM files support the following features:

  • Data Compression
  • In-built search engine.
  • One file can merge multiple .chm files.
  • Extended character supports, although fully not support Unicode.

 

References

[Solved] org.apache.tika.io.EndianUtils. BufferUnderrunException


BufferUnderFlowException is a subclass of TikaException. This exception occurred when buffer fed from a lower rate while read at a higher rate. There can be many reasons for this connection interruption, hard drive corrupted or CPU speed issue.

public static class EndianUtils.BufferUnderrunException extends TikaException

Constructors

  • BufferUnderrunException()

Solutions

As this issue can be from multiple reasons that’s why having multiple solutions as per need:

  1. Increase buffer size.
  2. Before burning external devices perform hard drive defragmentation.
  3. Avoid burn data onto a device in the network
  4. Always take the backup of data before transferring.
  5. Run hard drive scanning software to identify the corrupted file in the machine before export it.
  6. Always set TIKA memory consumption as higher and CPU and hard drive speed requirements to ensure enough RAM is available.
  7. Make sure the device consuming data or network connection functioning properly.

References

https://tika.apache.org/1.22/api/org/apache/tika/io/EndianUtils.BufferUnderrunException.html

[Solved]org.apache.tika.exception.TikaMemoryLimitException


TikaMemoryLimitException is a subclass of TikaException. This exception generally occurred when there are lots of nested or embedded files within documents.

For Example :

  1.  Maven jars: Where one jar contains pom having a reference of other dependencies
  2. Git objects
  3. Word documents having lots of embedded files.

For parsing these nested/embedded files a large number of memory required that’s the reason for parser consuming memory up to highest mark will through this exception.

Solutions

  1. Set memory uses limit for TIKA as much as possible. at least more than 1 GB
  2. Make a common practice to shield the input stream with CloseShieldInputStreams so that it can fail if reaching the max limit.

Generally in TIKA, these allocations were coming from TikaInputStream.get(InputStream, TemporaryResources) which check if the type of InputStream for identify it’s support mark or not.

  • BufferedInputStream
  • ByteArrayInputStream

Unfortunately, because of this common practice to wrap InputStreams in CloseShieldInputStreams, causing this exception even if the mark is in fact supported.

public class TikaMemoryLimitException extends TikaException

Constructors

  • TikaMemoryLimitException(String msg)

References

https://tika.apache.org/1.22/api/org/apache/tika/exception/TikaMemoryLimitException.html

[Solved] org.apache.tika.mime.MimeTypeException


MimeTypeException is a subclass of TikaException. This exception occurred when there is a mismatch with selected parser and document mime type or Mime Type not supported by TIKA.

public class MimeTypeException extends TikaException

Constructors

  • MimeTypeException(String message) :Constructs a MimeTypeException with the specified detail message.
  • MimeTypeException(String message, Throwable cause)
    Constructs a MimeTypeException with the specified detail message and root cause.

References

https://tika.apache.org/1.22/api/org/apache/tika/mime/MimeTypeException.html

TIKA: MS-Excel Content and Metadata Extraction


In this program, you will see complete steps to extraction content and metadata of the MS-Excel file by using TIKA OOXMLParser.

Sample File

TIKA MS excel File Content and Metadata extrcation
TIKA MS Excel File Content and Metadata extraction

Complete Example

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.microsoft.ooxml.OOXMLParser;
import org.apache.tika.sax.BodyContentHandler;

import org.xml.sax.SAXException;

public class TikaMSExcelParserExample {

	public static void main(final String[] args) throws IOException, TikaException, SAXException {

		// detecting the file type
		BodyContentHandler handler = new BodyContentHandler();
		Metadata metadata = new Metadata();
		FileInputStream inputstream = new FileInputStream(new File("C:\\Users\\Saurabh Gupta\\Desktop\\TIKA\\TIKA-MS-EXCEL.xlsx"));
		ParseContext pcontext = new ParseContext();

		// OOXml parser
		OOXMLParser msofficeparser = new OOXMLParser();
		msofficeparser.parse(inputstream, handler, metadata, pcontext);
		System.out.println("Contents of the excel document:" + handler.toString());
		System.out.println("Metadata of the excel document:");
		String[] metadataNames = metadata.names();

		for (String name : metadataNames) {
			System.out.println(name + ": " + metadata.get(name));
		}
	}
}

Output


Contents of the excel document:Sheet1
    First Name  Last Name   DOB
    Saurabh Gupta   10-Dec-85
    Gaurav  Kumar   12-May-86
    Rahul   Roi 12-Jun-10
    Raghvendra  Rana    5-Jan-95
    Tanaya  Jain    13-Mar-85



Metadata of the excel document:
date: 2019-11-23T00:25:08Z
extended-properties:AppVersion: 15.0300
meta:creation-date: 2006-09-16T00:00:00Z
extended-properties:Application: Microsoft Excel
extended-properties:Company: 
Creation-Date: 2006-09-16T00:00:00Z
dcterms:created: 2006-09-16T00:00:00Z
custom:WorkbookGuid: e742a774-13a6-49b2-8ba3-1b6118163781
dcterms:modified: 2019-11-23T00:25:08Z
Last-Modified: 2019-11-23T00:25:08Z
Last-Save-Date: 2019-11-23T00:25:08Z
Application-Version: 15.0300
protected: false
meta:save-date: 2019-11-23T00:25:08Z
Application-Name: Microsoft Excel
modified: 2019-11-23T00:25:08Z
publisher: 
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
dc:publisher: 

[Solved] org.apache.tika.exception.TikaConfigException


TikaConfigException is a subclass of TikaException. This exception occurred when there is an error in the Tika config file. It can also occur when one or more of the parsers failed to initialize from that erroneous config.

public class TikaConfigException extends TikaException

Constructors

  • TikaConfigException(String msg): Creates an instance of the exception with a message.
  • TikaConfigException(String msg, Throwable cause): Create an instance of exception with message and cause.

References

https://tika.apache.org/1.22/api/org/apache/tika/exception/TikaConfigException.html

[Solved] org.apache.tika.exception.CorruptedFileException


CorruptedFileException is a subclass of TikaException. This exception occurred when the parse absolutely, and because of corrupted content positively has to stop. This exception doesn’t catch and swallowed if an embedded parser throws it.

public class CorruptedFileException extends TikaException

Constructors

  • CorruptedFileException(String msg): This constructor use to throw an error message.
  • CorruptedFileException(String msg, Throwable cause): This constructor is used to through exception with the cause.

References

https://tika.apache.org/1.22/api/org/apache/tika/exception/CorruptedFileException.html

[Solved] org.apache.tika.exception.AccessPermissionException


AccessPermissionException is a subclass on TikaException. This exception occurred when a document/file does not allow content extraction. For Example, This exception is most common for PDF type documents, which might cause this type of exception.

public class AccessPermissionException extends TikaException

Solutions

Always check file access, read, write and executable permission before going to use with TIKA, accordingly perform operations.

File file = new File("TEST-File");

With Java NIO Libraries
boolean isRegularFile = Files.isRegularFile(file);
boolean isHidden = Files.isReadable(file);
boolean isReadable = Files.isReadable(file);
boolean isExecutable = Files.isExecutable(file);
boolean isSymbolicLink = Files.isSymbolicLink(file);
boolean isWritable = Files.isWritable(directory);

With Java IO Libraries
boolean isReadable=file.isReadable();
boolean isWritable=file.setWritable();
boolean isExecutable=file.setExecutable();

Constructors

Here are list of Constructor for this exception class:

  • AccessPermissionException() : Default constructor
  • AccessPermissionException(String info) : Constructor with exception message
  • AccessPermissionException(String info, Throwable th): Throw exception with message and stack trace.
  • AccessPermissionException(Throwable th): Throw exception message stack trace.

References

https://tika.apache.org/1.22/api/org/apache/tika/exception/AccessPermissionException.html

[Solved]org.apache.tika.exception.UnsupportedFormatException


UnsupportedFormatException is a subclass of  TikaException. This exception is thrown by parsers when a file format does not support it. It happens generally when based on MIME type not able to differentiate versions.

For Example: When writing mime type as application/perfect covers all versions of WordPerfect format while parsers only support 6.x only.

Solution

To handle such cases whenever possible distinguish file formats by specific MIME Type so that if any unsupported version finds out that will take care by EmptyParser. Even if not able to distinguish by MIME Type use the distinguish versions.

Here is a complete list of supported Format, Parsers, and Mime Type for TIKA

TIKA Supported Document Formats, Parsers and MIME Type

public class UnsupportedFormatException
extends TikaException

 

Constructors

  • UnsupportedFormatException(String msg)

References

https://tika.apache.org/1.22/api/org/apache/tika/exception/UnsupportedFormatException.html

[Solved]org.apache.tika.exception.EncryptedDocumentException: Unable to process: document is encrypted


EncryptedDocumentException is subclass of TikaException. This Exception occurred when TIKA parser tries to extract the content of Encrypted Microsoft word documents.

 public class EncryptedDocumentException extends TikaException

Constructors

  • EncryptedDocumentException()
  • EncryptedDocumentException(String info)
  • EncryptedDocumentException(String info, Throwable th)
  • EncryptedDocumentException(Throwable th)

This exception message and exception type dependend on type of encrypted file (docx or doc):

  • File password-protected.docx : org.apache.tika.exception.EncryptedDocumentException: Unable to process: document is encrypted
  • File password-protected.doc : org.apache.poi.EncryptedDocumentException: Cannot process encrypted word file

Here is stacktrace for both types of the documents:

Tika password-protected.docx


Exception in thread "main" org.apache.tika.exception.EncryptedDocumentException: Unable to process: document is encrypted
    at org.apache.tika.parser.microsoft.OfficeParser.parse(OfficeParser.java:245)
    at org.apache.tika.parser.microsoft.OfficeParser.parse(OfficeParser.java:167)
    at org.apache.tika.parser.CompositeParser.parse(CompositeParser.java:242)
    at org.apache.tika.parser.CompositeParser.parse(CompositeParser.java:242)
    at org.apache.tika.parser.AutoDetectParser.parse(AutoDetectParser.java:120)
    at org.apache.tika.cli.TikaCLI$OutputType.process(TikaCLI.java:142)
    at org.apache.tika.cli.TikaCLI.process(TikaCLI.java:418)
    at org.apache.tika.cli.TikaCLI.main(TikaCLI.java:112)

Tika password-protected.doc


Exception in thread "main" org.apache.tika.exception.TikaException: Unexpected RuntimeException from org.apache.tika.parser.microsoft.OfficeParser@119e7782
    at org.apache.tika.parser.CompositeParser.parse(CompositeParser.java:244)
    at org.apache.tika.parser.CompositeParser.parse(CompositeParser.java:242)
    at org.apache.tika.parser.AutoDetectParser.parse(AutoDetectParser.java:120)
    at org.apache.tika.cli.TikaCLI$OutputType.process(TikaCLI.java:142)
    at org.apache.tika.cli.TikaCLI.process(TikaCLI.java:418)
    at org.apache.tika.cli.TikaCLI.main(TikaCLI.java:112)
Caused by: org.apache.poi.EncryptedDocumentException: Cannot process encrypted word file
    at org.apache.poi.hwpf.model.FileInformationBlock.(FileInformationBlock.java:77)
    at org.apache.poi.hwpf.HWPFDocumentCore.(HWPFDocumentCore.java:155)
    at org.apache.poi.hwpf.HWPFDocument.(HWPFDocument.java:218)
    at org.apache.tika.parser.microsoft.WordExtractor.parse(WordExtractor.java:80)
    at org.apache.tika.parser.microsoft.OfficeParser.parse(OfficeParser.java:199)
    at org.apache.tika.parser.microsoft.OfficeParser.parse(OfficeParser.java:167)
    at org.apache.tika.parser.CompositeParser.parse(CompositeParser.java:242)

References

https://tika.apache.org/1.22/api/org/apache/tika/exception/EncryptedDocumentException.html

[Solved] org.apache.tika.exception.TikaException: Error creating OOXML extractor


TikaException is the most common cached exception which required to handle while using APIs for TIKA.

Constructors

These are two constructors of the TikaException class.

  • TikaException(String msg): TikaException  throw with message
  • TikaException(String msg, Throwable cause): TikaException throws message and cause of the exception.

Example

In this example, parsing pdf file content and metadata throwing TikaException because of using the parser for PDF doesn’t support it. By mistake or copy-paste use Parser of OOXMLParser which is generally used to parser Microsoft documents.

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.parser.microsoft.ooxml.OOXMLParser;
import org.apache.tika.parser.pdf.PDFParser;
import org.apache.tika.sax.BodyContentHandler;
import org.apache.tika.parser.txt.TXTParser;

import org.xml.sax.SAXException;

public class TikaPdfParserExample {

   public static void main(final String[] args) throws IOException,SAXException, TikaException {

      //detecting the file type
      BodyContentHandler handler = new BodyContentHandler();
      Metadata metadata = new Metadata();
      FileInputStream inputstream = new FileInputStream(new File("C:\\Users\\Saurabh Gupta\\Desktop\\TIKA\\PDF-FILE.pdf"));
      ParseContext pcontext=new ParseContext();

      //auto detect document parser
      Parser  parser = new OOXMLParser();
      parser.parse(inputstream, handler, metadata,pcontext);
      System.out.println("Contents of the text document:" + handler.toString());
      System.out.println("Metadata of the text document:");
      String[] metadataNames = metadata.names();

      for(String name : metadataNames) {
         System.out.println(name + " : " + metadata.get(name));
      }
   }
}

Output


Exception in thread "main" org.apache.tika.exception.TikaException: Error creating OOXML extractor
    at org.apache.tika.parser.microsoft.ooxml.OOXMLExtractorFactory.parse(OOXMLExtractorFactory.java:209)
    at org.apache.tika.parser.microsoft.ooxml.OOXMLParser.parse(OOXMLParser.java:110)
    at com.fiot.tika.exceptions.handling.TikaTextParserExample.main(TikaTextParserExample.java:31)
Caused by: org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException: No valid entries or contents found, this is not a valid OOXML (Office Open XML) file
    at org.apache.poi.openxml4j.util.ZipArchiveThresholdInputStream.getNextEntry(ZipArchiveThresholdInputStream.java:143)
    at org.apache.poi.openxml4j.util.ZipInputStreamZipEntrySource.(ZipInputStreamZipEntrySource.java:47)
    at org.apache.poi.openxml4j.opc.ZipPackage.(ZipPackage.java:106)
    at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:299)
    at org.apache.tika.parser.microsoft.ooxml.OOXMLExtractorFactory.parse(OOXMLExtractorFactory.java:110)
    ... 2 more
Caused by: java.util.zip.ZipException: Unexpected record signature: 0X46445025
    at org.apache.commons.compress.archivers.zip.ZipArchiveInputStream.getNextZipEntry(ZipArchiveInputStream.java:260)
    at org.apache.poi.openxml4j.util.ZipArchiveThresholdInputStream.getNextEntry(ZipArchiveThresholdInputStream.java:139)
    ... 6 more

Solutions

Always use AutoDetectParser in TIKA if not sure about document type or specific Parser as per document type.

Preferences

https://tika.apache.org/1.8/api/org/apache/tika/exception/TikaException.html

[Solved]org.apache.tika.exception.ZeroByteFileException: InputStream must have > 0 bytes


TikaZeroByteException is a subclass of TikaException. TikaZeroByteException occurred when using AutoDetectParser to extract the content of the file which is having no text or zero-bytes. In this case, auto-detect parser throws TikaZeroByteException.


public class ZeroByteFileException extends TikaException

Constructors

  • ZeroByteFileException(String msg): This constructor used to throw an exception with a message.

ZeroByteFileException Example

Here is an example to parse content and metadata of text file by using AutoDetectParser. But it’s throwing an exception because it is not having any content/zero.

package com.fiot.tika.exceptions.handling;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.BodyContentHandler;
import org.apache.tika.parser.txt.TXTParser;

import org.xml.sax.SAXException;

public class TikaTextParserExample {

   public static void main(final String[] args) throws IOException,SAXException, TikaException {

      //detecting the file type
      BodyContentHandler handler = new BodyContentHandler();
      Metadata metadata = new Metadata();
      FileInputStream inputstream = new FileInputStream(new File("C:\\Users\\Saurabh Gupta\\Desktop\\TIKA\\BLANK-FILE.txt"));
      ParseContext pcontext=new ParseContext();

      //auto detect document parser
      Parser  parser = new AutoDetectParser();
      parser.parse(inputstream, handler, metadata,pcontext);
      System.out.println("Contents of the text document:" + handler.toString());
      System.out.println("Metadata of the text document:");
      String[] metadataNames = metadata.names();

      for(String name : metadataNames) {
         System.out.println(name + " : " + metadata.get(name));
      }
   }
}

Output


Exception in thread "main" org.apache.tika.exception.ZeroByteFileException: InputStream must have > 0 bytes
    at org.apache.tika.parser.AutoDetectParser.parse(AutoDetectParser.java:122)
    at com.fiot.tika.exceptions.handling.TikaTextParserExample.main(TikaTextParserExample.java:29)

Solutions

To handle ZeroByteException there are two ways:

  1. Always check file size before use it.
  2. If you already know the content type of file using specific Parser. For Example in the above case replace the line with below text parser instance then no exception will occur.

Parser parser = new  TextParser();

References

https://tika.apache.org/1.22/api/org/apache/tika/exception/ZeroByteFileException.html

TIKA Document Content Extraction


TIKA supports various parsers for different types of document formats. TIKA decides the right parser and extract content based on the document type.

Here you can get a complete list of TIKA supported documents formats:

TIKA Supported Formats and Parsers

TIKA Content Extraction

There are two ways to extract content from a document by TIKA API:

  1. TIKA Facade class: Tika.parseToString()
  2. Parser Class : Parser.parse()

TIKA Facade class : Tika.parseToString()

Tika facade class parseToString() method is used to extract content from a document. Tika internally uses the following steps to extract content from the document:

  1.  Tika internally uses the mechanism to detect document type.
  2. Based on document type decide a suitable parser from the parser repository.
  3. The selected parser will parse the document and extract the content.
Tika tika = new Tika();
String content = tika.parseToString(file);

Example : TIKA Extract Content by Tika.parseToString()

Here in this program, you will see complete steps to extract content by the Tika facade class.

import java.io.File;
import java.io.IOException;

import org.apache.tika.Tika;
import org.apache.tika.exception.TikaException;

import org.xml.sax.SAXException;

public class TikaContentExtraction1 {

   public static void main(final String[] args) throws IOException, TikaException {

      File file = new File("hello.txt");

      //Instantiating Tika facade class
      Tika tika = new Tika();

      String filecontent = tika.parseToString(file);
      System.out.println("Document Content: " + filecontent);
   }
}

Output


Document Content:
This is
TIKA
Test

Parser Interface: Parser.parse()

In TIKA, the parser package provides several interfaces and classes to extract the content of a document. Here is a list of Interface, classes, and method used to extract content:

Parser Interface

TIKA supports multiple parsers according to document format. All these parser classes implement the Parser interface. For example : PDFParser, Mp3Parser,OfficeParser etc.

See Also: TIKA Supported Documents Format and Parsers

CompositeParser

CompositeParser has used a composite design pattern internally which allows using a group of parser by a single instance. It allows accessing all parser those implemented Parser interfaces.

AutoDetectParser

AutoDetectParser is a subclass of CompositeParser, which provides automatic document type detection. It automatically detects document type and send to appropriate parser classes by composite methodology.

parse() method

parse() method of the Parser interface used to extract content and metadata from the given document. Here is a prototype of parse() method and parameters descriptions:

parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context);

TIKA supports several individual parser classes i.e XMLParser, PDFParser, Mp3Parser, etc. Which can be used parse specific document type. If you want to use a generic parsing way, TIKA provides CompositeParser or AutoDetectParser which will automatically detect document type and select specific parser for extracting the content and metadata.


Parser parser = new CompositeParser();  
   (or)
Parser parser = new AutoDetectParser();
   (or)        , 
Create object of any individual parsers supported by  TIKA Library 
Object Description
InputStream stream The input stream of a file.
ContentHandler handler Tika sends content as XHTML content, where it extracts the text content by SAX API.
Metadata metadata Metadata tells about the internal information of the document. This object used as a source and target of the document.
ParseContext context This object is used where the need to customize the parsing process as per client needs.

Steps to Extract Document content by Parser

  • Step 1: Create an instance of an input stream of the document.
File  file = new File(filepath)
FileInputStream inputstream = new FileInputStream(file);
   or
InputStream stream = TikaInputStream.get(new File(filename));

Note: FileInputSream doesn’t support random access for reads for efficiently process file format. We can use TikaInputStream for random access to the file.

  • Step 2: Create an instance of ContentHandler.
    TIKA supports these three content handlers:
Content Handler Description
BodyContentHandler This class picks the body part of the XHTML output and writes that content to the output writer or output stream. Then it redirects the XHTML content to another content handler instance.
LinkContentHandler This content extraction class is used to parse only H-ref or links documents and send it to crawlers.
TeeContentHandler This class is useful when needing to use multiple tools simultaneously.

Example

BodyContentHandler handler = new BodyContentHandler( );
  • Step 3: Create an instance of Meta Data
Metadata metadata = new Metadata();
  • Step 4: Create an instance of ParserContext
ParseContext context =new ParseContext();
  • Step 5: Call Parser.parse() method
    Call Parser.parse() method with arguments as given below.

Parser.parse(inputstream, handler, metadata, context);
  • Step 6: Extract Document Content

Call handler.toString() method to extract parse content of the document as text.

Complete Example: Extract Document Content

In this example, you will get to know complete steps to extract content from TIKA supported parser.

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.BodyContentHandler;

import org.xml.sax.SAXException;

public class TikaContentExtractionByParser {

   public static void main(final String[] args) throws IOException,SAXException, TikaException {

      File file = new File("hello.txt");

      //parse() method parameters
      Parser parser = new AutoDetectParser();
      BodyContentHandler handler = new BodyContentHandler();
      Metadata metadata = new Metadata();
      FileInputStream inputstream = new FileInputStream(file);
      ParseContext context = new ParseContext();

      //parsing the file hello.txt
      parser.parse(inputstream, handler, metadata, context);

      System.out.println("Document Content : " + Handler.toString());
   }
}

Output

Document Content:
This is
TIKA
Test

In further posts, you will get to know about to extract content and metadata from the document.

TIKA Language Detection


Language detection required were needing to classified documents based on language, there is a separate class LanguageIdentifier to detect the language of the text.

LanguageIdentifier class use the following algorithms to detect language:

Profiling Corpus Algorithm

Create a profile for language based on matched common words from different language dictionaries. For example a common word for English like a, an, the, etc. Then decide the language name.

Here use terms as

Corpus: collections of the most used common terms of written language.
Profiling: a dictionary of words of each language.

Drawback: If two language is having similar characters and words then it’s difficult to decide language based on the frequency of words.

N-gram Algorithm

As a solution to the above drawback of the “Profiling Corpus Algorithm“, a new approach comes of using character sequences of a given length for profiling corpus. This sequence of characters in content is called N-gram, where N is the length of the character sequence.

N-gram approach help in the detection of language in the case of European languages. Ex: English. Tika uses a 3-gram approach for language detection. N-gram approach is good in the case of short texts.

TIKA Supported Languages

As per ISO 639-1 having 184 standard languages but Tika is able to detect only 18 languages as below:

da—Danish de—German et—Estonian
el—Greek en—English es—Spanish
fi—Finnish fr—French hu—Hungarian
is—Icelandic it—Italian nl—Dutch
no—Norwegian pl—Polish pt—Portuguese
ru—Russian sv—Swedish th—Thai

How to detect Langauge by Tika?

getLanguage() method of LanguageIdentifier class is used to get language based on passed text content.

//Create Language Identifier object based on content.
LanguageIdentifier object = new LanguageIdentifier(“English is so funny.”);
//Get lanaguage name based on passing content.
String lang=object.getLangauge()

Example: Detect Langauge from Text

This example will show you steps to get Language Name of passing content.

import java.io.IOException;

import org.apache.tika.exception.TikaException;
import org.apache.tika.language.LanguageIdentifier;

import org.xml.sax.SAXException;

public class LanguageDetection {

   public static void main(String args[])throws IOException, SAXException, TikaException {

      LanguageIdentifier object = new LanguageIdentifier(“English is so funny.”);
      String lang = object.getLanguage();
      System.out.println("Detected Language is : " + lang);
   }
}

Output


Language Detected from content is : en

Example: Detect Langauge from Document Contents

To detect the language of a document, first, we need to parse the document by using parse() method. This parse() method will store parse content in handler object. This handler object content used as an argument of LanguageIdentifier constructor to identify the language.

//Get metadata and extract content by parser parse() method.
parser.parse(inputstream, handler, metadata, context);
//Pass content as parameter of constructor of LanguageIdentifier
LanguageIdentifier object = new LanguageIdentifier(handler.toString());

Complete Example

Here are complete steps to get metadata and extract the content of the document.

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.BodyContentHandler;
import org.apache.tika.language.*;

import org.xml.sax.SAXException;

public class TikaDocumentLanguageDetection{

   public static void main(final String[] args) throws IOException, SAXException, TikaException {

      //Instantiating a file object
      File file = new File("hello.txt");

      //Create objects of required arguments for parse() method.
      Parser parser = new AutoDetectParser();
      BodyContentHandler handler = new BodyContentHandler();
      Metadata metadata = new Metadata();
      FileInputStream content = new FileInputStream(file);

      //Get metadata and extract content by parser parse() method.
      parser.parse(content, handler, metadata, new ParseContext());

      LanguageIdentifier object = new LanguageIdentifier(handler.toString());
	  System.out.println("File Content :" + handler.toString());
      System.out.println("Language Name :" + object.getLanguage());
   }
}

Output


File Content : English is so funny.
Language Name : en

TIKA Document Type Detection


TIKA facade class detect() method is used to detect the document type based on the input file.

Example

In this program, we can detect file type based on the input file.

import java.io.File;
import org.apache.tika.Tika;
public class TikaTypeDetection {

   public static void main(String[] args) throws Exception {

      //Suppose hello.txt is in your current directory
      File file = new File("hello.txt");//

      //Instante tika facade class
      Tika tika = new Tika();

      //detect file type using detect method
      String filetype = tika.detect(file);
      System.out.println(filetype);
   }
}

Output


text/plain

TIKA Supported Document Formats


TIKA supports these documents formats. Here you will also get list of parser with respect to format and MIME Type.

Format Parser MIME Type
HyperText Markup Language HtmlParser text/html
application/vnd.wap.xhtml+xml
application/x-asp
application/xhtml+xml
XML and derived formats DcXMLParser
Microsoft Office document formats OfficeParser
OOXMLParser application/vnd.ms-powerpoint.template.macroenabled.12
application/vnd.ms-excel.addin.macroenabled.12
application/vnd.openxmlformats-officedocument.wordprocessingml.template
application/vnd.ms-excel.sheet.binary.macroenabled.12
application/vnd.openxmlformats-officedocument.wordprocessingml.document
application/vnd.ms-powerpoint.slide.macroenabled.12
application/vnd.ms-visio.drawing
application/vnd.ms-powerpoint.slideshow.macroenabled.12
application/vnd.ms-powerpoint.presentation.macroenabled.12
application/vnd.openxmlformats-officedocument.presentationml.slide
application/vnd.ms-excel.sheet.macroenabled.12
application/vnd.ms-word.template.macroenabled.12
application/vnd.ms-word.document.macroenabled.12
application/vnd.ms-powerpoint.addin.macroenabled.12
application/vnd.openxmlformats-officedocument.spreadsheetml.template
application/vnd.ms-xpsdocument
application/vnd.ms-visio.drawing.macroenabled.12
application/vnd.ms-visio.template.macroenabled.12
model/vnd.dwfx+xps
application/vnd.openxmlformats-officedocument.presentationml.template
application/vnd.openxmlformats-officedocument.presentationml.presentation
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
application/vnd.ms-visio.stencil
application/vnd.ms-visio.template
application/vnd.openxmlformats-officedocument.presentationml.slideshow
application/vnd.ms-visio.stencil.macroenabled.12
application/vnd.ms-excel.template.macroenabled.12
OldExcelParser application/vnd.ms-excel.workspace.3
application/vnd.ms-excel.workspace.4
application/vnd.ms-excel.sheet.2
application/vnd.ms-excel.sheet.3
application/vnd.ms-excel.sheet.4
SpreedsheetMLParser
WordMLParser application/vnd.ms-wordml
Word2006MlParser application/vnd.ms-word2006ml
MSOwnerFileParser application/x-ms-owner
OpenDocument Format OpenDocumentParser application/x-vnd.oasis.opendocument.presentation
application/vnd.oasis.opendocument.chart
application/x-vnd.oasis.opendocument.text-web
application/x-vnd.oasis.opendocument.image
application/vnd.oasis.opendocument.graphics-template
application/vnd.oasis.opendocument.text-web
application/x-vnd.oasis.opendocument.spreadsheet-template
application/vnd.oasis.opendocument.spreadsheet-template
application/vnd.sun.xml.writer
application/x-vnd.oasis.opendocument.graphics-template
application/vnd.oasis.opendocument.graphics
application/vnd.oasis.opendocument.spreadsheet
application/x-vnd.oasis.opendocument.chart
application/x-vnd.oasis.opendocument.spreadsheet
application/vnd.oasis.opendocument.image
application/x-vnd.oasis.opendocument.text
application/x-vnd.oasis.opendocument.text-template
application/vnd.oasis.opendocument.formula-template
application/x-vnd.oasis.opendocument.formula
application/vnd.oasis.opendocument.image-template
application/x-vnd.oasis.opendocument.image-template
application/x-vnd.oasis.opendocument.presentation-template
application/vnd.oasis.opendocument.presentation-template
application/vnd.oasis.opendocument.text
application/vnd.oasis.opendocument.text-template
application/vnd.oasis.opendocument.chart-template
application/x-vnd.oasis.opendocument.chart-template
application/x-vnd.oasis.opendocument.formula-template
application/x-vnd.oasis.opendocument.text-master
application/vnd.oasis.opendocument.presentation
application/x-vnd.oasis.opendocument.graphics
application/vnd.oasis.opendocument.formula
application/vnd.oasis.opendocument.text-master
iWorks document formats IWorkPackageParser application/vnd.apple.keynote
application/vnd.apple.iwork
application/vnd.apple.numbers
application/vnd.apple.pages
WordPerfect document formats WordPerfectParser application/vnd.wordperfect; version=5.1
application/vnd.wordperfect; version=5.0
application/vnd.wordperfect; version=6.x
org.apache.tika.parser.xml.DcXMLParser
application/xml
image/svg+xml
QuattroProParser application/x-quattro-pro; version=9
Portable Document Format PDFParser application/pdf
Electronic Publication Format EpubParser application/x-ibooks+zip
application/epub+zip
FictionBookParser application/x-fictionbook+xml
org.gagravarr.tika.FlacParser
audio/x-oggflac
audio/x-flac
Rich Text Format RTFParser application/rtf
Compression and packaging formats CompressorParser application/zlib
application/x-gzip
application/x-bzip2
application/x-compress
application/x-java-pack200
application/x-lzma
application/deflate64
application/x-lz4
application/x-snappy
application/x-brotli
application/gzip
application/x-bzip
application/x-xz
PackageParser application/x-tar
application/java-archive
application/x-arj
application/x-archive
application/zip
application/x-cpio
application/x-tika-unix-dump
application/x-7z-compressed
RarParser application/x-rar-compressed
AppleSingleFileParser application/applefile
Text formats TXTParser
Feed and Syndication formats FeedParser application/atom+xml
application/rss+xml
IptcAnpaParser text/vnd.iptc.anpa
Help formats ChmParser application/vnd.ms-htmlhelp
application/x-chm
application/chm
Audio formats AudioParser audio/vnd.wave
audio/x-wav
audio/basic
audio/x-aiff
MidiParser application/x-midi
audio/midi
Mp3Parser audio/mpeg
Mp4Parser video/x-m4v
application/mp4
video/3gpp
video/3gpp2
video/quicktime
audio/mp4
video/mp4
VorbisParser audio/vorbis
OpusParser audio/opus
audio/ogg; codecs=opus
SpeexParser audio/ogg; codecs=speex
audio/speex
FlacParser
Image formats ImageParser image/png
image/vnd.wap.wbmp
image/x-jbig2
image/bmp
image/x-xcf
image/gif
image/x-icon
image/x-ms-bmp
JpegParser image/jpeg
TiffParser image/tiff
PSDParser image/vnd.adobe.photoshop
BPGParser image/bpg
image/x-bpg
WebPParser image/webp
ICNSParser image/icns
TesseractOCRParser
WMFParser image/wmf
EMFParser image/emf
Video formats FLVParser video/x-flv
Mp4Parser video/x-m4v
application/mp4
video/3gpp
video/3gpp2
video/quicktime
audio/mp4
video/mp4
OggParser audio/ogg
application/kate
application/ogg
video/daala
video/x-ogguvs
video/x-ogm
audio/x-oggpcm
video/ogg
video/x-dirac
video/x-oggrgb
video/x-oggyuv
TheoraParser video/theora
PooledTimeSeriesParser
Java class files and archives ClassParser application/java-vm
Source code SourceCodeParser text/x-c++src
text/x-groovy
text/x-java-source
Mail formats MboxParser application/mbox
RFC822Parser message/rfc822
OutlookPSTParser application/vnd.ms-outlook-pst
OfficeParser application/x-tika-msoffice-embedded; format=ole10_native
application/msword
application/vnd.visio
application/vnd.ms-project
application/x-tika-msworks-spreadsheet
application/x-mspublisher
application/vnd.ms-powerpoint
application/x-tika-msoffice
application/sldworks
application/x-tika-ooxml-protected
application/vnd.ms-excel
application/vnd.ms-outlook
TNEFParser application/vnd.ms-tnef
application/x-tnef
application/ms-tnef
CAD formats DWGParser image/vnd.dwg
Font formats TrueTypeParser application/x-font-ttf
AdobeFontMetricParser application/x-font-adobe-metric
Scientific formats DIFParser application/dif+xml
GDALParser application/x-gsc
image/x-ozi
application/x-pds
image/eir
application/x-usgs-dem
application/aaigrid
application/x-bag
application/elas
application/x-rs2
application/x-tsx
application/x-lcp
image/geotiff
application/x-mbtiles
application/x-cappi
application/x-netcdf
application/x-gsag
application/x-epsilon
application/x-ace2
application/jaxa-pal-sar
image/x-pcraster
application/x-msgn
image/arg
application/x-hdf
image/x-mff
application/x-kro
image/x-hdf5-image
image/x-dimap
image/x-srp
image/big-gif
application/x-envi
application/x-cosar
application/x-ntv2
image/bmp
application/x-doq2
application/x-bt
application/x-kml
application/x-gmt
application/x-rst
application/vrt
application/pcisdk
application/x-ctg
application/x-e00-grid
application/x-rik
image/ida
image/x-mff2
application/sdts-raster
application/x-snodas
image/jp2
image/sar-ceos
application/terragen
application/x-wcs
application/leveller
application/x-ingr
application/x-gtx
image/sgi
application/x-pnm
image/raster
application/fits
application/x-r
image/gif
application/x-envi-hdr
application/x-http
application/x-rmf
application/x-ecrg-toc
application/aig
application/x-rpf-toc
image/adrg
application/x-srtmhgt
application/x-generic-bin
application/jdem
image/x-airsar
application/x-webp
application/x-ngs-geoid
application/x-pcidsk
image/x-fujibas
application/x-wms
application/x-map
image/ceos
application/xpm
application/x-zmap
image/envisat
application/x-ers
application/x-doq1
application/x-isis2
application/x-nwt-grd
application/x-ppi
image/ilwis
application/x-isis3
application/x-nwt-grc
application/x-blx
application/gff
application/x-ndf
image/jpeg
application/x-geo-pdf
application/x-l1b
image/fit
application/x-gsbg
application/x-sdat
application/x-ctable2
application/x-grib
application/x-coasp
application/x-dipex
application/grass-ascii-grid
image/fits
application/x-til
application/x-dods
image/png
application/x-gxf
application/x-gs7bg
application/x-cpg
application/x-lan
application/x-xyz
image/bsb
application/x-p-aux
application/dted
application/x-rasterlite
image/nitf
image/hfa
application/x-fast
application/x-los-las
GeographicInformationParser text/iso19139+xml
GeoParser application/geotopic
GribParser application/x-grib2
HDFParser application/x-hdf
ISArchiveParser application/x-isatab
NetCDFParser application/x-netcdf
MatParser application/x-matlab-data
Executable programs and libraries ExecutableParser application/x-msdownload
application/x-sharedlib
application/x-elf
application/x-object
application/x-executable
application/x-coredump
Crypto formats Pkcs7Parser application/pkcs7-signature
application/pkcs7-mime
TSDParser
Database formats SQLite3Parser
JackcessParser application/x-msaccess
DBFParser application/x-dbf
Natural Language Processing SentimentParser
JournalParser
Image and Video object recognition Tika recognization package

References

https://tika.apache.org/1.22/formats.html

TIKA Reference API


Java Programmers can integrate the Tika library in their applications by using the Tika facade class and other below classes.

Tika Class

Tika facade class abstracts the complexity and provides simple methods to explore the functionalities of TIKA.

package:org.apache.tika

Constructors

Followings are constructors of Tika class:

Constructor Description
Tika () Tika default constructor uses the default configuration and constructs the Tika class.
Tika (Detector detector) Creates the Tika facade class by accepting the detector instance as a parameter.
Tika (Detector detector, Parser parser) Creates a Tika facade class by accepting the detector and parser instances as parameters.
Tika (Detector detector, Parser parser, Translator translator) Creates the Tika facade class by accepting the detector, the parser, and the translator instance as parameters.
Tika (TikaConfig config) Creates a Tika facade class by accepting the object of the TikaConfig class as a parameter.

Methods and Description

The following are the important methods of the Tika facade class:

Method Description
parseToString (File file) This method parses and extract extracted text content in the String format. By default, string parameter length is limited.
int getMaxStringLength () This method returns the maximum length of strings returned by the method.
void setMaxStringLength (int maxStringLength) Set the maximum length of strings returned while extracting data from the file.
Reader parse (File file) This method parses and extract extracted text content in the form of java.io.reader object.
String detect (InputStream stream, Metadata metadata) This method accepts an InputStrea and Metadata of an object as parameters and returns the document type name.
String translate (InputStream text, String targetLanguage) This method accepts the InputStream and a String representing the language that we want our text to be translated. It returns, given text to the desired language, attempting to auto-detect the source language.

Parser Interface

This interface implemented by all the parser classes of the Tika package.

package: org.apache.tika.parser

Methods

This is the important method of Tika Parser interface −

Methods Description
parse (InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) This parse method use is given document input stream into a sequence of XHTML and SAX events. After parsing, it places the metadata in the object of MetaData class and extracted document content in the object of the ContentHandler class.

Metadata Class

This MetaData class implements various interfaces such as CreativeCommons, Geographic, HttpHeaders, Message, MSOffice, ClimateForcast, TIFF, TikaMetadataKeys, TikaMimeKeys, Serializable to support various data models.

package: org.apache.tika.metadata

Constructors

Constructor Description
Metadata() Constructs new, empty metadata.

Methods

Methods Description
add (Property property, String value) Adds a new metadata property in the form of key/value pair.
add (String name, String value) Adds a new metadata property in the form of key/value pair.
String get (Property property) Returns the property’s value (if any).
String get (String name) Returns the key’s value (if any).
Date getDate (Property property) Returns the value of Date of metadata property.
String[] getValues (Property property) Returns all the values of metadata associated with property.
String[] getValues (String name) Returns all the values of a given metadata key.
String[] names() Returns all the key names of metadata elements in a metadata object.
set (Property property, Date date) Sets the date of the given metadata property
set(Property property, String[] values) Sets multiple values for a metadata property.

LanguageIdentifier Class

This class used to identify the language of the given content.

package : org.apache.tika.language

Constructors

Constructor Description
LanguageIdentifier (LanguageProfile profile) Instantiates the language identifier for parameter LanguageProfile.
LanguageIdentifier (String content) Instantiates the language identifier for text content.

Methods

Methods Description
String getLanguage () Returns the language of the content of current LanguageIdentifier object.

TIKA Environment Setup for Applications


In the previous post Apache Tika Introduction, you have got an idea of apache Tika and it’s used. In this post, you will learn about the TIKA  environment setup for applications.

As a programmer, we can integrate Apache TIKA in window or Linux or another OS environment by using:

  • Command-line
  • Tika API
  • Command-line interface (CLI) of TIKA
  • Graphical User interface (GUI) of TIKA
  • The source code.

System Requirements

  • JDK Java SE 2 JDK 1.6 or above
  • Memory 1 GB RAM (recommended)
  • Disk Space No minimum requirement
  • Operating System Version Windows XP or above, Linux

Tika Environment Setup Steps

  • Step 1: Set JAVA_HOME and Path as mentioned on the below link.
    JAVA_HOME and PATH Setup Steps
  • Step 2: Add these libraries in your CLASSPATH or pom.xml to use TIKA APIs.

<dependency>
   <groupId>org.apache.Tika</groupId>
   <artifactId>Tika-core</artifactId>
   <version>1.6</version>
</dependency>
<dependency>
   <groupId>org.apache.Tika</groupId>
   <artifactId> Tika-parsers</artifactId>
   <version> 1.6</version>
</dependency>
<dependency>
   <groupId> org.apache.Tika</groupId>
   <artifactId>Tika</artifactId>
   <version>1.6</version>
</dependency>
<dependency>
   <groupId>org.apache.Tika</groupId>
   < artifactId>Tika-serialization</artifactId>
   < version>1.6< /version>
</dependency>
<dependency>
   < groupId>org.apache.Tika< /groupId>
   < artifactId>Tika-app< /artifactId>
   < version>1.6< /version>
</dependency>
<dependency>
   <groupId>org.apache.Tika</groupId>
   <artifactId>Tika-bundle</artifactId>
   <version>1.6</version>
</dependency>

Apache Tika Introduction


Apache Tika provides generic API for all document type content detection, analysis and content extraction from multiple file formats. Tika internally uses various documents parsers to extract metadata and structured text content from the various file types. For Example PDF, Spreadsheet, text file, images, etc.

Tika latest version 1.22 released on 1st Aug 2019 by Apache software foundation. Tika completely has written in Java and supports cross-platform.

Tika Version History

Year Development
2006 The idea of Tika was proposed in front of the Lucene Project Management Committee.
2006 The concept of Tika and its benefits in the Jackrabbit project was discussed.
2007 Tika entered into Apache.
2008 Both 0.1 and 0.2 Versions were released and Tika graduated from the incubator to the Lucene sub-project.
2009 This year Tika Versions 0.3, 0.4, and 0.5 were released.
2010 Both 0.6 and 0.7 Version was released and Tika graduated into the top-level Apache project.
2011 Tika 1.0 was released with book “Tika in Action” was also released in the same year.
2019 Tika 1.22 was release for additional CSV and HWP files type.

Why Tika?

As per https://filext.com/, there are around 25k to 50K file extensions (Structured and Non Structured) and these are growing day by day. To deal with so many types of format Tika provides universal Java API to support around 1400 file types that cover most common and popular formats.

Tika provides content extraction, metadata extraction, and language identification capabilities. Tika written in Java, still used by other languages also by calling restful services and CLI tools.

Where to use Apache Tika?

  • Search Engine: Tika uses the search engine to create search indexing for text in digital documents.
  • Document Analysis: Analysis of the documents like images, pdf to do analysis based on extract content.
  • Digital Asset Management (DAM): It’s used with an organization where maintains a library of documents, images, videos, ebooks, drawings to classify based on common features.
  • Content Analysis: Analyse the content from the web site and care of user’s interest like amazon shows movies, products based on the user’s visit. Machine learning based on content.

Features of Tika

  • Unified parser Interface: Tika internally uses best suitable parser libraries within a single parser interface. Due to this feature Tika, reduce the burden of developer from the burden of selecting the suitable parser library and use it according to the file type encountered.
  • Low memory usage: Tika consumes fewer memory resources, therefore, it is easily embedded with Java applications. We can also use Tika within the application which runs on platforms with fewer resources like mobile PDA.
  • Fast processing: Tika can quickly extract and detect content from applications.
  • Flexible metadata: Tika understands all type of metadata models which are used to define files.
  • Parser integration: Tika supports various parser libraries available for each document type in the same application.
  • MIME-type detection: Tika can extract and detect content from all MIME types.
  • Language detection: Tika includes language identification feature, therefore it can be used in documents based on language type in multilingual websites.

Mask Zipcode/Pincode/Postal Code on Web Page


A lot of information that you share freely, such as your date of birth, phone number, ZIP code and email address, are very valuable to criminals. Think of how many accounts require you to verify your identity by entering in your birthday or your ZIP code before making a transaction.

Alone, your ZIP code might not be of much value all by itself, but criminals will take that information and post it on underground sites where they buy, sell and trade bunches of personal information. From those sites, criminals can purchase enough of your personal information to use it for fraud

See Also :

CVV Masking Example

Here considering, Pincode of length 5 digits. By masking will hide all 5 digits. For example, my pincode is 75038 than after mask will display as XXXXX. Pincode for some card can also be as six digit take this as assignment and make code changes accordingly so that support for both five and six digits.

original zipcode masked zipcode

Note :

This masking example is created considering standard length of text size and formatting of text field, that can vary according to organizations. If your organization having different format and text size modify source code according to your need. If you are facing any issue drop a comments will try to connect as soon as possible.

Download Source code

To download the source code of this example, click on below given download link.

Mask Pincode

Drop me your questions in comments section.

References

Mask Passport On Web Page


The passport serves as proof of your identity and your nationality which itself can be advantageous depending on your destination. As such, you should prioritize its security above all else when you travel overseas.

See Also :

Consequences of Passport Number Identity Theft

Under no circumstances should you disclose any sensitive information regarding yourself, passport number included. It may just be a jumble of digits but it’s a very valuable commodity for criminals if they even get their hands on it.
There are lots of consequences of passport identity theft as below:

  • A criminal could easily manufacture a passport with passport number, full legal name , date of birth and another person’s picture on it. This may not get them into the US (easily) but it could conceivable get them to a country nearby and then from there they could travel to the US or travel on others countries.
  • Criminal all over the world can use others stolen passport to commit a crime or do anything on others name.
  • The passport is use as an identity official documents if you don’t have driving license. Think about if someone using fraud passport and make some accident on road.
  • The fraud passport with your personal information full legal name, date of birth (available in facebook) , another person picture and address used to impersonate you. This fraud passport can be used as identity proof to open and access your credit / debit cards, social security, email, medical records, your character, your tax records.
  • A lot of passports have a chip too, which stores all your personal data.

Passport Masking Example

Here considering, Passport of length 8 digits. By masking will hide initial 4 digits. For example, my passport number is A1234765 than after mask will display as XXXX4765. Passport for some card can also be vary as per county take this as assignment and make code changes accordingly so that support for both 8 and more digits.

Original passport mask passport

Note :
This masking example is created considering standard length of text size and formatting of text field, that can vary according to organizations. If your organization having different format and text size modify source code according to your need. If you are facing any issue drop a comments will try to connect as soon as possible.

Download Source code


To download the source code of this example, click on below given download link.

Mask Passport

Drop me your questions in comments section.

References

Elasticsearch ingest node , Filebeat Integration for Log Parsing


Here is you will know about configuration for Elasticsearch Ingest Node, Creation of pipeline and processors for Ingest Node. You will see to configuration for filebeat to shipped logs to Ingest Node.

Below is some sample logs line which will be shipped through filebeat to Elasticsearch Ingest Node.

Sample Logs


2016-06-01 05:14:51,921 INFO main [com.mchange.v2.log.MLog] - MLog clients using log4j logging.
2016-06-01 05:14:52,065 INFO main [com.mchange.v2.c3p0.C3P0Registry] - Initializing c3p0-0.9.1.2 [built 21-May-2007 15:04:56; debug? true; trace: 10]
2016-06-01 05:14:52,728 INFO net.sf.ehcache.CacheManager@204119 [net.sf.ehcache.util.UpdateChecker] - New update(s) found: 2.4.7 [http://www.terracotta.org/confluence/display/release/Release+Notes+Ehcache+Core+2.4]. Please check http://ehcache.org for the latest version.
2016-06-01 05:14:53,198 WARN main [com.ibatis.sqlmap.engine.builder.xml.SqlMapParser] - Duplicate -include 'rowSubSelectEnd' found.
2016-06-01 05:14:53,199 WARN main [com.ibatis.sqlmap.engine.builder.xml.SqlMapParser] - Duplicate -include 'activitiesSelect' found.
2016-06-01 05:14:56,172 ERROR main [com.fsvps.clientPortal.service.clientReport.ReportsServiceImpl] - Invalid/unreadable reportsBasePath dir: C:homeclientReportsBase
2016-06-01 05:15:51,784 INFO main [com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource] - Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 1, acquireRetryAttempts -> 0, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 2x2tdj9h36ggie1v52d93|144b457, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> oracle.jdbc.driver.OracleDriver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 2x2tdj9h36ggie1v52d93|144b457, idleConnectionTestPeriod -> 140, initialPoolSize -> 0, jdbcUrl -> jdbc:oracle:thin:@10.226.168.6:1521:FSVD2, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 150, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 20, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 1, numHelperThreads -> 3, numThreadsAwaitingCheckoutDefaultUser -> 0, preferredTestQuery -> select 1, properties -> {user=******, password=******}, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false ]
2016-06-01 05:16:13,317 INFO com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#0 [com.mchange.v2.resourcepool.BasicResourcePool] - An exception occurred while acquiring a poolable resource. Will retry.
java.sql.SQLException: The Network Adapter could not establish the connection
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:412)
    at oracle.jdbc.driver.PhysicalConnection.(PhysicalConnection.java:531)
    at oracle.jdbc.driver.T4CConnection.(T4CConnection.java:221)
    at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
    at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:503)
    at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:134)
    at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:182)
    at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:171)
    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:137)
    at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1014)
    at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:32)
    at com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask.run(BasicResourcePool.java:1810)
    at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547)
Caused by: oracle.net.ns.NetException: The Network Adapter could not establish the connection
    at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:359)
    at oracle.net.resolver.AddrResolution.resolveAndExecute(AddrResolution.java:422)
    at oracle.net.ns.NSProtocol.establishConnection(NSProtocol.java:672)
    at oracle.net.ns.NSProtocol.connect(NSProtocol.java:237)
    at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1042)
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:301)
    ... 12 more
Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at oracle.net.nt.TcpNTAdapter.connect(TcpNTAdapter.java:141)
    at oracle.net.nt.ConnOption.connect(ConnOption.java:123)
    at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:337)
    ... 17 more
2016-06-01 05:16:13,317 INFO com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#2 [com.mchange.v2.resourcepool.BasicResourcePool] - An exception occurred while acquiring a poolable resource. Will retry.
java.sql.SQLException: The Network Adapter could not establish the connection
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:412)
    at oracle.jdbc.driver.PhysicalConnection.(PhysicalConnection.java:531)
    at oracle.jdbc.driver.T4CConnection.(T4CConnection.java:221)
    at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
    at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:503)
    at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:134)
    at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:182)
    at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:171)
    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:137)
    at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1014)
    at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:32)
    at com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask.run(BasicResourcePool.java:1810)
    at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547)
Caused by: oracle.net.ns.NetException: The Network Adapter could not establish the connection
    at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:359)
    at oracle.net.resolver.AddrResolution.resolveAndExecute(AddrResolution.java:422)
    at oracle.net.ns.NSProtocol.establishConnection(NSProtocol.java:672)
    at oracle.net.ns.NSProtocol.connect(NSProtocol.java:237)
    at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1042)
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:301)
    ... 12 more

Filebeat Configuration

To check this example put above sample logs in file app.log and configure filebeat.yaml file as below:

Prospectors Configuration


filebeat.prospectors:
- type: log
- D:your-directory-path*.log*

#Multiline configutaion as per above logs to stack trace
multiline.pattern: '^[([0-9]{4})-([0-9]{2})-([0-9]{2})'
multiline.negate: true
multiline.match: after

#Elasticsearch Ingest Node Pipe Line configuration
output.elasticsearch:
  # Array of hosts to connect to.
  hosts: ["localhost:9200"]
  pipeline: grok-pipeline

Below is complete sample filebeat.yaml file

######Filebeat Configuration Example ########
#=========================== Filebeat prospectors =============================
filebeat.prospectors:

# Below are the prospector specific configurations.
- type: log
  # Change to true to enable this prospector configuration.
  enabled: true
  # Paths that should be crawled and fetched. Glob based paths.
  paths:
    - D:fsv_logs*.log*
    #- c:programdataelasticsearchlogs*

  # Exclude lines. A list of regular expressions to match. It drops the lines that are
  # matching any regular expression from the list.
  #exclude_lines: ['^DBG']

  # Include lines. A list of regular expressions to match. It exports the lines that are
  # matching any regular expression from the list.
  #include_lines: ['^ERR', '^WARN']

  # Exclude files. A list of regular expressions to match. Filebeat drops the files that
  # are matching any regular expression from the list. By default, no files are dropped.
  #exclude_files: ['.gz$']

  # Optional additional fields. These fields can be freely picked
  # to add additional information to the crawled log files for filtering
  #fields:
  #  level: debug
  #  review: 1

  ### Multiline options

  # Mutiline can be used for log messages spanning multiple lines. This is common
  # for Java Stack Traces or C-Line Continuation

  # The regexp Pattern that has to be matched all lines starting with [
  multiline.pattern: '^[([0-9]{4})-([0-9]{2})-([0-9]{2})'

  # Defines if the pattern set under pattern should be negated or not. Default is false.
  multiline.negate: true

  # Match can be set to "after" or "before". It is used to define if lines should be append to a pattern
  # that was (not) matched before or after or as long as a pattern is not matched based on negate.
  # Note: After is the equivalent to previous and before is the equivalent to to next in Logstash
  multiline.match: after

#============================= Filebeat modules ===============================

filebeat.config.modules:
  # Glob pattern for configuration loading
  path: ${path.config}modules.d*.yml

  # Set to true to enable config reloading
  reload.enabled: false

  # Period on which files under path should be checked for changes
  #reload.period: 10s

#==================== Elasticsearch template setting ==========================

setup.template.settings:
  index.number_of_shards: 3
  #index.codec: best_compression
  #_source.enabled: false

#================================ Outputs =====================================

# Configure what output to use when sending the data collected by the beat.

#-------------------------- Elasticsearch output ------------------------------
output.elasticsearch:
  # Array of hosts to connect to.
  hosts: ["localhost:9200"]
  pipeline: grok-pipeline
  # Optional protocol and basic auth credentials.
  #protocol: "https"
  #username: "elastic"
  #password: "changeme"

In above filbeat.yaml you can check for configuration for filbeat, multiline processing logs and Ingest Node pipe line.

Ingest Node pipeline Creation and configure Processors

You can execute below commands by using curl or Kibana Adsense /Dev tools to create pipeline to execute processors.

Here I have configured below processors with in pipeline:

grok processor : grok processor will parse logs message to fields values which will help to do analysis.

date processor : date processor will change @timestamp values corresponding timestamp of each logs line. Which will help while indexing and sorting of logs based on timestamp.

date_index_name : date_index_name processor will create elasticsearch indexes with suffix as date so that easily maintain indexes as per durability.

Kibana adsense


GET _template/


GET  _ingest/pipeline/grok-pipeline
GET _ingest/pipeline/grok-pipelin?filter_path=*.version
DELETE _ingest/pipeline/my-pipeline-id
POST _ingest/pipeline/_simulate
{
  "pipeline": {
  "description" : "grok parse of log message",
  "processors": [
    {
      "grok": {
        "field": "message",
        "patterns": ["^\[%{TIMESTAMP_ISO8601:timestamp}\]\s+\[%{LOGLEVEL:level}\]\s+\[%{GREEDYDATA:ip}\]\s+\[%{GREEDYDATA:CARD_ID}\]\s+\[%{GREEDYDATA:thread}\]\s+\[%{GREEDYDATA:CLASS_NAME}\]\s+-%{GREEDYDATA:complete_message}({({[^}]+},?\s*)*})?\s*$(?(?m:.*))?"]
      }
    }
  ]
  },
  "docs":[
  {
    "_source": {
      "message": "[2014-03-27 13:30:01,106] [INFO] [0:0:0:0:0:0:0:1] [] [Task-Thread-for-com.mchange.v2.async.ThreadPerTaskAsynchronousRunner@79eb1cad] [com.mchange.v2.resourcepool.BasicResourcePool] - An exception occurred while acquiring a poolable resource. Will retry."
    }
  }
  ]
}

POST _ingest/pipeline/_simulate
{
  "pipeline": {
  "description" : "grok parse of log message",
  "processors": [
    {
      "date": {
        "field": "timestamp",
        "target_field" : "timestamp",
        "formats": ["%{YEAR}-%{MONTHNUM}-%{MONTHDAY} %{HOUR}:%{MINUTE}:%{SECOND},%{MILLISECOND}"],
        "timezone" : "America/Chicago"
      }
    }
  ]
  },
  "docs":[
  {
    "_source": {
      "timestamp": "2014-03-27 13:30:01,106"
    }
  }
  ]
}



PUT _ingest/pipeline/grok-pipeline
{
  
  "description" : "grok parse of log message",
  "version" : 123,
  "processors": [
    {
      "grok": {
        "field": "message",
        "patterns": ["^\[%{TIMESTAMP_ISO8601:timestamp}\]\s+\[%{LOGLEVEL:level}\]\s+\[%{GREEDYDATA:ip}\]\s+\[%{GREEDYDATA:CARD_ID}\]\s+\[%{GREEDYDATA:thread}\]\s+\[%{GREEDYDATA:CLASS_NAME}\]\s+-%{GREEDYDATA:complete_message}({({[^}]+},?\s*)*})?\s*$(?(?m:.*))?"]
      },
     "date": {
        "field": "timestamp",
        "target_field" : "timestamp",
        "formats": ["yyyy-MM-dd HH:mm:ss,SSS"],
        "timezone" : "America/Chicago"
      },
      "date_index_name" : {
        "field" : "timestamp",
        "index_name_prefix" : "filebeat-",
        "date_rounding" : "d"
      }
    }
  ]
}

PUT _ingest/pipeline/date-pipeline
{
  
  "description" : "grok parse of timestamp to @timestamp",
  "processors": [
    {
      "date": {
        "field": "timestamp",
        "target_field" : "timestamp",
        "formats": ["TIMESTAMP_ISO8601"],
        "timezone" : "America/Chicago"
      }
    }
  ]
}

delete filebeat*

GET _search
{
  "query": {
    "match_all": {}
  }
}

GET _ingest/processor/grok

Elasticsearch

bootstrap.memory_lock: false
cluster.name: FIOT_CLUSTER
http.port: 9200
node.data: true
node.ingest: true
node.master: true
node.max_local_storage_nodes: 1
node.name: FIOT_NODE_1
path.data: D:ElasticsearchDatadata
path.logs: D:ElasticsearchDatalogs
transport.tcp.port: 9300

 

Java: Collection Framework Introduction


A collection is an object (also called container) to deal with a group of objects or elements as a single unit. These objects called as elements of Collection. Collections are used to perform operations like the store, retrieve, manipulate, communicate and aggregate.

A collection can have a different type of data. Based on data can decide the type collection data structure.

  • Homogeneous
  • Heterogeneous
  • Unique
  • Duplicate

See Also: 

Real-life Example of Collection

Here are some real-life examples of collections:

  • LinkedList: Your web page visiting history.
  • LinkedList: Train Coaches are connected to each other.
  • LinkedList: Our brain, when we remember something memory follow association because of one memory link to another.  This way recall in sequence.
  • Stack & LinkedList: Stack of Plates or Towel at the party. The top plate always picks first.
  • Queue & LinkedList: Queue/line of the person standing on the railway ticket window or for food in the mess.
  • A classroom is a collection of students.
  • A money bank is a collection of coins.
  • A school bag is a collection of books.

Why need collection?

There are four ways in Java to store values by JVM.

1:Variable approach

If we need to handle one, two or three or fewer numbers of values then the variable approach is a good bit if need to deal with so many objects like 5000 then variable approach have some drawback:

  • The limitation of a variable is that it can store only one value at a time.
  • Readability and reusability of the code will be down.
  • JVM will take more time for the execution.

2: Using a class object approach

Using a class object, we can store multiple “fixed” numbers of values of different types. For example, suppose we are creating a class named Person.

class Person{
String Name ;
int age ;
}

If you create the object of Person class like this

Person p1=new Person(); // So can you think how many values can store in this person object?

The answer is only two i.e name and age. but if you will want to store the third value, it will not possible.

3: Using an array object approach

Array improved the readability of code, by using a single variable for a huge number of values but there are various problems and limitations with the array.


Student[] st=new Student[5000];
  1. Array allow to store only homogeneous data type.
  2. Array is static and fixed in length size.
  3. Array concept help with standard data structure, but when need to deal with the sorting of objects, search for a specific item, etc.

4: Collection Object:

By using a collection object, we can store the same or different data without any size limitation.

What is a Framework in Java?

A framework is a set of several classes and interfaces which provide a readymade architecture.

What is a Collections Framework?

A collection framework provides a unified readymade architecture for storing and manipulating a group of objects. All collections frameworks contain the following:

  • Interfaces: Interfaces generally forms a hierarchy and allow collections object to be manipulated independently of the details of their representation.
  • Implementations: Provides a concrete representation by data structure and implementation of  collections interfaces.
  • Algorithms: The methods that perform useful operations, such as searching and sorting, on objects that implement collection interfaces.

Benefits of Collections Framework

Collections Framework provides lots of benefits:

  • Reduces programming effort: The Collections framework provides useful data structures and algorithms so that developers can concentrate on programming logic only.
  • Increases program performance and quality: Collections Framework provides high-quality data structures and algorithms implementations for good performance. These collections interface APIs are interchangeable so that easily tuned by switching collection implementations.
  • Allows interoperability among unrelated APIs: These data structures are interchangeable so that choose data structure and algorithms according to requirement.
  • Reduces effort to learn and to use new APIs: Most of APIs are common for collections framework because of the inherent Collection interface. only some APIs need to remember that are specific to the data structure.
  • Reduces effort to design new APIs: If new data structure and algorithm change create polymorphism of API and change the internal algorithm of APIs.
  • Fosters software reuse: If new data structure added use standard APIs so that easy to learn for developers.

References

Java : Collection Framework Hierarchy


All the classes and interfaces of the collection framework are in java.util package. This hierarchy for the collection framework specifically mentioned the class and interface with respect to each type.

Java Collection Framework Hierarchy

Iterable Interface

The Iterable interface is the root interface for all the collection classes because the Collection interface extends the Iterable interface, therefore, all the subclasses of Collection interface also implement the Iterable interface.

The iterable interface contains only one abstract method.

  • Iterator iterator(): It returns the iterator over the elements of type T.

Iterator Interface

The iterator interface provides the facility of iterating the elements in a forward direction only.
For more detail: Java: Iterator Interface methods and Examples

Collection Interface

The Collection interface builds the foundation for the Collection framework. The collection interface is one of the interfaces which is implemented by all the Collection framework classes. It provides common methods to implement by all the subclasses of collection interfaces.
For more detail: Java: Collection Interface methods and Examples

List Interface

List interface is the subtype/child interface of the Collection interface. It stores objects/elements in list type data structure in ordered form and also allowed duplicate values.

Implementation classes for List interface are ArrayList, LinkedList, Vector, and Stack.

For Example: To instantiate List Interface with Implementation classes follow:


List  list1= new ArrayList();  
List  list2 = new LinkedList();  
List  list3 = new Vector();  
List  list4 = new Stack();

For more detail: Java: List Interface methods and Examples

ArrayList Class

The ArrayList implements the List interface. It’s having the following features:

  • ArrayList uses a dynamic array data structure to store objects and elements.
  • ArrayList allows duplicate objects and elements.
  • ArrayList maintains the insertion order.
  • ArrayList is non-synchronized.
  • ArrayList elements/objects can be accessed randomly.

For more detail: Java: ArrayList Interface methods and Examples

LinkedList Class

LinkedList implements the List interface. It’s having the following features:

  • LinkedList uses a doubly linked list data structure to store elements.
  • LinkedList allowed storing the duplicate elements.
  • LinkedList maintains the insertion order.
  • LinkedList is not synchronized.
  • LinkedList manipulation is fast because no shifting is required.

For more detail: Java: LinkedList Class methods and Examples

Vector Class

Vector Class implements List interface. It’s having the following features:

  • Vector is similar to the ArrayList class.
  • Vector class uses data structure as a dynamic array to store the data elements.
  • Vector is synchronized.
  • Vector contains many methods that are not the part of Collection Framework.

For more detail: Java: Vector Class methods and Examples

Stack Class

The Stack is the subclass of the Vector class. It’s having the following features:

  • Stack implements the Vector data structure with the (LIFO)last-in-first-out.
  • Stack contains all of the methods of the Vector class.
  • Stack also provides its methods like boolean push(), boolean peek(), boolean push(object o), which defines its features.

For more detail: Java: Stack Class methods and Examples

Queue Interface

Queue Interface extends the Collection interface. It’s having the following features:

  • Queue interface maintains the FIFO (first-in-first-out) order.
  • Queue can be defined as an ordered list that is used to hold the elements which are about to be processed.
  • Queue interface implemented by the various classes like PriorityQueue, Deque, and ArrayDeque.

Queue interface can be instantiated as:

Queue q1 = new PriorityQueue();  
Queue q2 = new ArrayDeque();  

For more detail: Java: Queue Interface methods and Examples

Here are detail about classes which implements Queue Interface.

PriorityQueue

The PriorityQueue class implements the Queue interface.

  • PriorityQueue holds the elements or objects which are to be processed by their priorities.
    PriorityQueue doesn’t allow null values to be stored in the queue.

For more detail: Java: PriorityQueue Class methods and Examples

Deque Interface

Deque stands for the double-ended queue which allows us to perform the operations at both ends.interface extends the Queue interface.

  • Deque extends the Queue interface.
  • Deque allows remove and add the elements from both the side.
Deque d = new ArrayDeque(); 

For more detail: Java: Deque Interface methods and Examples

ArrayDeque Class

ArrayDeque class implements the Deque interface.

  • ArrayDeque facilitates us to use the Deque.
  • ArrayDeque allows add or delete the elements from both the ends.
  • ArrayDeque is faster than ArrayList and has no capacity restrictions.

For more detail: Java: ArrayQueue Class methods and Examples

Set Interface

Set Interface extends Collection Interface and present in java.util package.

  • Set doesn’t allow duplicate elements or objects.
  • Set store elements in an unordered way.
  • Set allows only one null value.
  • Set is implemented by HashSet, LinkedHashSet, and TreeSet.

We can create an instantiation of Set as below:

Set s1 = new HashSet();  
Set s2 = new LinkedHashSet();  
Set s3 = new TreeSet();

For more detail: Java: Set Interface methods and Examples

HashSet

HashSet class implements Set Interface. It’s having the following features:

  • HashSet internally uses data structure like a hash table for storage.
  • HashSet uses hashing technique for storage of the elements.
  • HashSet always contains unique items.

For more detail: Java: HashSet Class methods and Examples

LinkedHashSet

LinkedHashSet class implements Set Interface. It’s having the following features:

  • LinkedHashSet store items in LinkedList.
  • LinkedHashSet store unique elements.
  • LinkedHashSet maintains the insertion order.
  • LinkedHashSet allows null elements.

For more detail: Java: LinkedHashSet Class methods and Examples

SortedSet Interface

SortedSet Interface extends Set Interface. It’s having the following features:

  • SortedSet provides a total ordering on its elements.
  • SortedSet elements are arranged in the increasing (ascending) order.
  • SortedSet provides additional methods that inhibit the natural ordering of the elements.

The SortedSet can be instantiated as:

SortedSet set = new TreeSet();  

For more detail: Java: SortedSet Interface methods and Examples

TreeSet Class

TreeSet class implements the SortedSet interface.  It’s having the following features:

  • TreeSet uses a tree data structure for storage.
  • TreeSet also contains unique elements.
  • TreeSet elements access and retrieval time is quite fast.
  • TreeSet elements stored in ascending order.

For more detail: Java: TreeSet Class methods and Examples

Map Interface

In the collection framework, a map contains values on the basis of key and value pair. This pair is known as an entry. A map having the following features:

  • Map contains unique keys.
  • Map allows duplicate values.
  • Map is useful to search, update or delete elements on the basis of a key.
  • Map is the root interface in Map hierarchy for Collection Framework.
  • Map interface is extended by SortedMap and implemented by HashMap, LinkedHashMap.
  • Map implementation classes HashMap and LinkedHashMap allow null keys and values but TreeMap doesn’t allow null key and value.
  • Map can’t be traversed, for traversing needs to convert into the set using method keySet() or entrySet().

For more detail: Java: Map Class methods and Examples

HashMap Class

HashMap class implements Map interface. It’s having following features:

  • HashMap uses data structure as a Hash Table.
  • HashMap store values based on keys.
  • HashMap contains unique keys.
  • HashMap allows duplicate values.
  • HashMap doesn’t maintain order.
  • HashMap class allows only one null key and multiple null values.
  • HashMap is not synchronized.
  • HashMap initial default capacity is 16 elements with a load factor of 0.75.

For more detail:

LinkedHashMap Class

LinkedHashMap class extends the HashMap class. It’s having the following features:

  • LinkedHashMap contains values based on the key.
  • LinkedHashMap contains unique elements.
  • LinkedHashMap may have one null key and multiple null values.
  • LinkedHashMap is not synchronized.
  • LinkedHashMap maintains the insertion order.
  • LinkedHashMap default initial capacity is 16 with a load factor of 0.75.

For more detail: Java: LinkedHashMap Class methods and Examples

TreeMap Class

TreeMap class implements the SortedMap interface. it’s having the following features:

  • TreeMap uses data structure as red-black tree.
  • TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
  • TreeMap contains only unique elements.
  • TreeMap doesn’t allow null keys and values.
  • TreeMap is not synchronized.
  • TreeMap maintains an ascending order.

For more detail: Java: TreeMap Class methods and Examples

HashTable Class

Hashtable class implements a Map interface and extends Dictionary class to store key and values as pairs. It’s having the following features:

  • HashTable store values as an array of the list where each list is known as a bucket of the node(key and value pair).
  • HashTable class is in java.util package.
  • Hashtable contains unique elements.
  • Hashtable doesn’t allow null key or value.
  • Hashtable is synchronized.
  • Hashtable initial default capacity is 11 whereas the load factor is 0.75.

For more detail: Java: HashTable Class methods and Examples

See Also:

Java: Arrays vs Collections


In Java, Arrays and Collections both are to deal with a group of objects but there are lots of differences in terms of data structure or performing operations.

Here are some most common differences:

Difference between Arrays & Collections

Arrays Collections
Arrays is having fixed-length.. Collections are growable in nature i.e increase or decrease.
Arrays are not recommended in terms of memory concerns. Collections use different data structures and recommended to use with respect to memory.
Arrays are used with respect to performance. Collections are not recommended to use with respect to performance.
Arrays can store only homogeneous (same type) of data. Collections can hold both homogeneous and heterogeneous elements.
Arrays do not have a single API. Collections having big list of methods.
Arrays can work with primitives and object types. Collections can hold only objects but not with primitive. If you pass as primitive internally convert to object.
See Also: Array & Arrays Class Examples See Also: Collection Framework and Examples

Java: HashCode and Equals Contract


In Java java.lang.Object is the superclass of all the classes provides two very important methods :

public boolean equals(Object obj)
public int hashCode()

See Also:

Internally these methods are used when need to check equality of objects but developer implementation prospects mainly used when need to implement HashMap because on that time developers have to implement these methods inside your User Defined class. Lot’s of the time when the developer is not aware of the contract of hashcode() and equals() method they make mistake and not received expected results from HashMap. Before going to detail of hashcode() and equals() contract, Let’s discuss first the problems.

Most Common Problem

In this example,  green and red car object is stored successfully in a HashMap, but when the map is asked to retrieve this green car object, the car object is not found in map and returning as null.

import java.util.HashMap;
import java.util.Map;

public class Car {
	private String color;

	public Car(String color) {
		this.color = color;
	}

	public boolean equals(Object obj) {
		if (!(obj instanceof Car))
			return false;
		if (obj == this)
			return true;
		return this.color.equals(((Car) obj).color);
	}
	public static void main(String[] args) {
		Car a1 = new Car("green");//hashcode
		Car a2 = new Car("red");

		// HashMap stores car type and its quantity
		Map m = new HashMap();
		m.put(a1, 10);
		m.put(a2, 20);
		//hashcode diffrent from previos green object consider different object
		System.out.println(m.get(new Car("green")));
	}
}
         

Output

null

The above program prints as null. However, we can check that this car object is stored in the map by inspecting in the debugger:

Java hashCode and Equals Contract

In the above program problem is hashcode() method was not implemented.

Before going to the solution to this problem in detail. We need to understand the equals() and hashcode() method contract.

hashcode() and equals() Method Contract

The contract between equals() and hasCode() is that:

  1.  If two objects are equal, then they must have the same hash code value.
  2.  If two objects have the same hashcode value, they may or may not be equal.

The main idea is Map worked on hashing techniques to find an object faster in comparison to linear search. In this case, because the hashcode() method is no implemented. It will call by default method of object class i.e return different hashcode value for different objects. In this above case both the objects store in HashMap and retrieving will have different hashcode values.

See Also: Java: Hashmap Working

In HashMap, store values in form array of buckets of the object where these array having hashcode value while objects having objects that match with the same hashcode. For example, the Hash Code is like a sequence of boxes for storage where different kinds of stuff can be stored in different boxes. It is more efficient if you organize stuff to a different place instead of the same garage. So it’s a good practice to keep kinds of stuff on related boxes i.e equally distribute the hashCode value.

The solution is to add hashCode() method to the Car class. Here we are getting hash value based on the size of color length as implemented below.

import java.util.HashMap;
import java.util.Map;

public class Car {
	private String color;

	public Car(String color) {
		this.color = color;
	}

	public boolean equals(Object obj) {
		if (!(obj instanceof Car))
			return false;
		if (obj == this)
			return true;
		return this.color.equals(((Car) obj).color);
	}

	public int hashCode(){
		return this.color.length();
}
	public static void main(String[] args) {
		Car a1 = new Car("green");//hashcode
		Car a2 = new Car("red");

		// HashMap stores car type and its quantity
		Map m = new HashMap();
		m.put(a1, 10);
		m.put(a2, 20);
		//hashcode different from previous green object consider different object
		System.out.println(m.get(new Car("green")));
	}

}

Output

10

Java: Aggregation and Composition (HAS-A)


Pre-requisite: Java: OOPS Concepts, Java: Class, Java: Object

If objects are having an association as “HAS-A” then there could be two types of relationship between objects:

  1. Aggregation
  2. Composition

Aggregation

Aggregation is a special type of association where objects have their independent life cycle but there is ownership. These owners and associate objects have the “HAS-A” relationship.

For Example, A person may associate with an Organization but he/she has an independent existence in the world.

Benefits of Aggregation

  • Aggregation provides reusability.

Note: For code reusability, if classes having IS-A relationship use Inheritance and for Has-A relationship use Aggregation.

Example of Aggregation

Here Employee class is associated with address class with Aggregation (HAS-A) relationship. Employee class contained an object of Address, this address object contains its own information like city, state, country, etc. Both of these objects are not strongly associate because if employee looses their jobs but still have the same address.

public class Address {
	String city, state, country;

	public Address(String city, String state, String country) {
		this.city = city;
		this.state = state;
		this.country = country;
	}

}

 

 

public class Employee {
	int id;
	String name;
	Address address;

	public Employee(int id, String name, Address address) {
		this.id = id;
		this.name = name;
		this.address = address;
	}

	void display() {
		System.out.println(id + " " + name);
		System.out.println(address.city + " " + address.state + " " + address.country);
	}

	public static void main(String[] args) {
		Address address1 = new Address("Noida", "UP", "India");
		Address address2 = new Address("Greater Noida", "UP", "India");

		Employee e = new Employee(101, "Saurabh", address1);
		Employee e2 = new Employee(102, "Gaurav", address2);

		e.display();
		e2.display();

	}
}

Composition

The composition is special type of aggregation where one object is strongly associated with another object and more restrictive. When the contained object in “HAS-A” and one object can not exist without the existence of others it’s the case of composition.

For Example:

  • Wheels in a car.
  • House has a room. Here the room can’t exist without the house.
  • An employee has a job. A job can’t exist without an employee.

Benefits of Composition

  • The composition provides reusability.
  • The composition can control the visibility of another object and reuse only when needed.

Examples of Compositions
Here Person and Job class having a composition relationship. In this case, Job class creates at runtime whenever a new person comes and we can change the salary from backend without change on client-side.

public class Person {
	//composition has-a relationship
    private Job job;

    public Person(){
        this.job=new Job();
        job.setSalary(1000L);
    }
    public long getSalary() {
        return job.getSalary();
    }
}
public class Job {
	private String role;
    private long salary;
    private int id;

    public String getRole() {
        return role;
    }
    public void setRole(String role) {
        this.role = role;
    }
    public long getSalary() {
        return salary;
    }
    public void setSalary(long salary) {
        this.salary = salary;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

}
public class TestComposition {

	public static void main(String[] args) {
		Person person = new Person();
		long salary = person.getSalary();

	}

}

Examples of Compositions & Aggregation
Let’s have an example of a University, it’s department and professors associated with departments.

University & Department Association: It’s a composition association because without University will exist in any department.
Department and Professors Association: It’s aggregate association because both are associated but not having any dependency like if department close professor lose. Both are are an independent entities.

import java.util.List;

public class University {
	 private List departments;

     public void destroy(){
         //it's composition, when i destroy a university I also
		 //destroy the departments. they cant live without university instance
         if(departments!=null)
             for(Department d : departments) d.destroy();
         departments.clear();
         departments = null;
     }

}
public class Department {
	private List professors;
    private University university;

    Department(University univ){
        this.university = univ;
        //check here univ not null throw whatever depending on your needs
    }

    public void destroy(){
        //It's aggregation here, if we fire any professor then they
		//will come out of department but they can still keep living
        for(Professor p:professors)
            p.fire(this);
        professors.clear();
        professors = null;
    }

}
public class Professor {
	 private String name;
     private List attachedDepartments;

     public void destroy(){

     }

     public void fire(Department d){
         attachedDepartments.remove(d);
     }
}

Java: Inheritance (IS-A)


Pre-requisite: Java: OOPS Concepts, Java: Class, Java: Object

Inheritance is a process where child class acquired all the properties and behaviors of the parent class. Inheritance is used when one object is based on another object. Here parent class also called a superclass and child class called a subclass.

For Example,  Person is Parent class and Employee is a subclass of Person. which acquired all the properties and behavior of Person class.

Advantage of inheritance

What is code Reusability in Inheritance?

Inheritance facilitates to reuse the fields and methods of the parent class in child class syntax of Java Inheritance.

Syntax of Inheritance Declaration

class Subclass-name extends Superclass-name  
{  
   //fields 
   //methods   
}

In java, extends keyword is used to inherit a class where a new class derived properties and methods of an existing class. The class that inherited is called a Parent/Superclass, and a new derived class is called a child/subclass.

What You Can Do in a Subclass?

A subclass inherits all of the public and protected members(fields, methods and nested classes) of its parent class, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the private members of the parent class.

Constructors are not members of the class, so they are not inherited by child class, but the constructor of the parent class can be invoked from the child class by using super.

These inherited members can use as-is, replace them, hide them, or supplement them with new members:

  • Parent class inherited fields  can be used directly, just like any other class field.
  • You can declare a field in the child class with the same name as the one in the parent class, thus hiding it (not recommended).
  • You can declare new fields in the child class that are not in the parent class.
  • The inherited parent class methods can be used directly as they are.
  • You can write a methods in child class that has the same signature as the one in the parent class. i.e Method Overriding.
  • You can write a new static method in the child class with the same signature as on the parent class, thus hiding it.
  • You can declare new methods in the child class that are not in the parent class.
  • You can write a child class constructor that invokes the constructor of the parent class, either implicitly or by using the keyword super.

Example of Inheritance

In this example, Animal is a parent class which is extended by the Dog Child class. The animal class having properties name, breed, age and color. There is one method print() to print all these values. Dog subclass will inherit all these properties those having access modifiers as public and protected. Child class Dog print() method is calling parent class print() method by super keyword.

Java inheritance Example
Java Inheritance Example
//POJO Class
public class Animal {
	// private variables
	private String name;
	private String breed;
	private int age;
	private String color;

	// Getter and setter methods
	public Animal(String name, String breed, int age, String color) {
		this.name = name;
		this.breed = breed;
		this.age = age;
		this.color = color;
	}
    //Method of class
	public String print() {
		return "Animal [name=" + name + ", breed=" + breed + ", age=" + age + ", color=" + color + "]";
	}
}
public class Dog extends Animal {
	private String type;

	public Dog(String name, String breed, int age, String color, String type) {
		// call super class constructor to initialize
		super(name, breed, age, color);
		this.type = type;
	}

	// Overriding method of parent class
	@Override
	public String print() {
		return "Dog [type=" + type + ", print()=" + super.print() + "]";
	}
}
public class TestInheritance {

	public static void main(String[] args) {

		 //Instance with Parameterize Constructor
	     Animal dog=new Animal("Tommy","Small Dog",5,"Black");
	     //calling super class method because reference to super class
	     System.out.println(dog.print());

	     Animal dog_tiny=new Dog("Tiny","Small Dog",4,"Black","Bichon Friese");
	     //calling super class method because reference to super class
	     System.out.println(dog_tiny.print());

	     Dog dog_big=new Dog("Tufan","Big Dog",4,"White","Spotted");
	     //calling sub class method because reference to sub class
	     System.out.println(dog_big.print());
	}
}

Output


Animal [name=Tommy, breed=Small Dog, age=5, color=Black]
Dog [type=Bichon Friese, print()=Animal [name=Tiny, breed=Small Dog, age=4, color=Black]]
Dog [type=Spotted, print()=Animal [name=Tufan, breed=Big Dog, age=4, color=White]]

Here from this output, you will see the print method called based on object not by references of the object.

Points about Inheritance

  • extends the keyword used to implement inheritance.
  • Java doesn’t support multiple inheritances. It’s possible by implementing multiple interfaces.
  • Inheritance has an “IS-A” relationship.
  • Excepting Object Class, which has no parent class, every class has one and only one direct parent class (single inheritance). In the absence of any other explicit parent class, every class is implicitly a child class of Object.

Type of Inheritance in Java

Java supports three types of inheritance only for classes:

  1. Single
  2. Multi-Level
  3. HierarchicalJava Types Of Inheritance

Note:

  • Multiple Inheritance is not supported in java through the class.
  • Multiple and Hybrid inheritance is supported in java through interface only.

Single Level Inheritance

As you have seen in the above example is a single level of inheritance.

Multi-Level Inheritance

class Animal{
void eat(){System.out.println("Animal eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("Dog barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("Baby Dog weeping...");}
}
class MultiLevelInheritanceTest{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}

Output


Baby Dog Weepig...
Dog barking...
Animal eating...

Hierarchical Inheritance

class Animal{
void eat(){System.out.println("Animal eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("Dog barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("Cat meowing...");}
}
class TestHierchicalInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//Compile Time Error
}}

Output


Cat meowing...
Animal eating...

Why multiple inheritance is not supported in java?

Java doen’t support multiple inheritance for class because of fixing ambiguity of common members like fields or method.

Suppose, we have three claases ClassA, ClassB and ClassC where ClassC extends ClassA and ClassB which are having common method display(). If you call display() method from child class then not sure which method got called because of ambiguity.
Since java not support multiple inheritance that’s why throgh compile time exception.

class ClassA{
void display(){System.out.println("Inside Class A");}
}
class ClassB{
void display(){System.out.println("Inside Class B");}
}
//Compile time issue issue here
class ClassC extends ClassA,ClassB{
 //suppose if it were
 public static void main(String args[]){
   ClassC obj=new ClassC();
   //Here it will through compile time issue
   obj.display();
}

 

“Learn From Others Experience"

%d bloggers like this: