Menu

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

package javax.annotation.security does not exist

We need to include this maven dependecy or JAR in java project to fix the javax.annotation.security does not exist issue.

https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api

Maven dependency to add in POM.xml file

<!-- https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api -->
<dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>javax.annotation-api</artifactId>
    <version>1.3.2</version>
</dependency>
If Maven dependecy is already there and still it is not working then, look on the JDK configuration. It means your JDK is not correctly configured to use and build this code, for more refer Package javax.annotation does not exist JDK issue.

JUnit for Java getter and setter methods

 

POJO class

public class ColleagueDetails {
private String colleagueID;
private String colleagueEmail;
public ColleagueDetails(String colleagueID, String colleagueEmail) {
this.colleagueID = colleagueID;
this.colleagueEmail = colleagueEmail;
}
public String getColleagueID() { return colleagueID; }
public void setColleagueID(String colleagueID) { this.colleagueID = colleagueID; }
public String getColleagueEmail() { return colleagueEmail; }
public void setColleagueEmail(String colleagueEmail) { this.colleagueEmail = colleagueEmail; }
}

Test class
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

class ColleagueDetailsTest {
ColleagueDetails colleagueDetails = new ColleagueDetails("1234", "email@jorvee.com");

@BeforeEach
void setUp() { }

@Test
void getColleagueIDTest() {
colleagueDetails.setColleagueID("1234");
assertEquals("1234", colleagueDetails.getColleagueID());
}

@Test
void getColleagueEmailTest() {
colleagueDetails.setColleagueEmail("email@jorvee.com");
assertEquals("email@jorvee.com", colleagueDetails.getColleagueEmail());
}

}

Insufficient Heap Memory

Issue "Insufficient Heap Memory"

Using 64bit VM settings, min.heap=1024MB, min permgen=256MB, default fork arguments=[-Xmx1024m, -XX:MaxPermSize=256m]

**** WARNING: insufficent heap memory ****
The JVM reports 910 MB but we recommend at least 1024 MB +/- 20
Use your JVM's heap size option (like -Xmx1024M) to set that size.
Will fork a JVM to get enough memory.
********************************************************************************
Available memory below specified limits and low-memory action set to fork, will fork to get enough memory
Not forking JVM as -nofork option is set
Setting properties from file

Resolution

If you have just closed any java program then wait for a few minutes and give chance to garbage collection to remove the unwanted space and clean the Heap memory.

Can we have multiple doGet() or doPost() in a servlet?

 No, it doesn't make sense to creating multiple doGet() or doPost() methods in a Servlet. The compiler will always execute the first one. It's better to write a different Servlet to handle the different requests.


One other way is the method overriding, we can override doGet() or doPost() in any of the methods viceversa. For more read Overriding Service, Get, and Post

working with enum in Java

enum Level {
  LOW("A"),
  MEDIUM("B"),
  HIGH("C");
  
  	public final String value;
  
  	Level(String val){
  		value=val;
  	}
	public String getValue() {
        return value;
    }
}

public class Main { 
  public static void main(String[] args) { 
    String myVar = Level.HIGH.getValue(); 
    System.out.println(myVar); 
  } 
}

 


Output of enum value
Output


Reading excel data in Java Sprint Boot

In this article, we will walk through the steps and program which we need to develop to read the excel data in Java program or spring boot application.

1. Maven dependency 

There is an Apache POI library that we need to add to our project, that will help us to easily perform read and write with excel. 


<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>

2. Apache POI

A major use of the Apache POI api is for Text Extraction applications such as web spiders, index builders, and content management systems.
The Apache POI Project's mission is to create and maintain Java APIs for manipulating various file formats based upon the Office Open XML standards (OOXML) and Microsoft's OLE 2 Compound Document format (OLE2). In short, you can read and write MS Excel files using Java. In addition, you can read and write MS Word and MS PowerPoint files using Java. Apache POI is your Java Excel solution (for Excel 97-2008). We have a complete API for porting other OOXML and OLE2 formats and welcome others to participate.

There are four types of API available in Apache POI, that we can use to extract the text from different types of files.
  1. POIFS: POIFS APIs are used if you had a document written in OLE 2 Compound Document Format, probably written using MFC, that you needed to read in Java.
  2. HSSF: HSSF APIs are used if you needed to read or write an Excel file using Java (XLS).
  3. XSSF: XSSF APIs are used if you need to read or write an OOXML Excel file using Java (XLSX).
  4. SXSSF: SXSSF APIs can be used for large excel files, that allows you to write very large Excel (XLSX) files in a memory optimized way.
The above summary has been written from Apache POI documentation. To read and explore more about POI you may visit the official Apache POI site. https://poi.apache.org/ 

3. Reading from an excel file

After importing the required dependency let's see a sample program that will help us to read the text from an excel sheet.
An excel sheet name "role_mapping_sheet.xlsx" having the following data. This excel sheet you need to keep in the project and it path we have to define in the program. Below is the snapshot of excel data.

Now, we need to create a model class that maps the value of these two columns into two class variables.

RoleTableModel.java
/**
 * 
 */
package serialization;

/**
 * @author rashid
 *
 */
public class RoleTableModel {
	
	public RoleTableModel(String title) {
		super();
		this.title = title;
	}

	public RoleTableModel() {
	}

	private String title;

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	@Override
	public String toString() {
		return "RoleTableModel [title=" + title + "]";
	}
}


Now, see the actual implementation class where we are performing the extraction. Below is the class InsertRoleData.java 

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.thymeleaf.util.ClassLoaderUtils;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import serialization.RoleTableModel;


public class InsertRoleData {
	Workbook workbook;
	private static final Logger LOGGER = LoggerFactory.getLogger(InsertRoleData.class);
	public List<RoleTableModel> getExcelDataAsList() {
		
		List<String> list = new ArrayList<String>();
		int noOfColumns = 0;
		try {
			FileInputStream file = new FileInputStream(new File("src\\main\\resources\\static\\role_mapping_sheet.xlsx"));
			workbook = new XSSFWorkbook(file);
			Sheet sheet = workbook.getSheetAt(0);
			noOfColumns = sheet.getRow(0).getLastCellNum();

			for (Row row : sheet) {
				for (Cell cell : row) {
					String cellValue = cell.toString();
					list.add(cellValue);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		List<RoleTableModel> allRoles = createList(list, noOfColumns);
		LOGGER.info("Number of columns: "+noOfColumns);
		return allRoles;
	}
	
	private List<RoleTableModel> createList(List<String> excelData, int noOfColumns) {

		ArrayList<RoleTableModel> invList = new ArrayList<RoleTableModel>();

		int i = noOfColumns;
		do {
			RoleTableModel inv = new RoleTableModel();
			inv.setTitle(excelData.get(i));
			LOGGER.info("role model "+inv.toString());
			invList.add(inv);
			i = i + (noOfColumns);
			
		} while (i < excelData.size());
		LOGGER.info("role model list "+invList.toString());
		return invList;
	}
	
}

You may now simply run your spring boot or java application and read the text from excel sheet cell by cell. Hope this helps you in implementation. If you face any issue while implementation of Apache POI, feels free to ask your question in the comment section. Thank You!

Diamond operator is not supported in source

While running a Java project with IntelliJ, we might face an error stating "diamond operator is not supported in -source 1.5", which means we are trying to run the project on a lower version of Java which is developed on a higher version.

Error statement 

java: diamond operator is not supported in -source 1.5

  (use -source 7 or higher to enable diamond operator)


Solution/Apply the following fix

Go to File option from menu >> Project Structure >> Project Settings >> Modules. Here in Module, we need to use the higher version of language level under the Source tab 


Hope this helps you!



Cast an object to Integer in Java

We could cast an object that have integer value into an integer using below Java code.

int value = Integer.parseInt(object.toString());

How to get the last path segment of an URL using Java

With any programming language, we come at some point where we need the last segment of the URL to manage and moderate the request and response. Hence with this sample Java program, we will see how we can get the last segment of the URL or URI after a slash (/).

public class JavaSubStringSample {

	public static void main(String[] args) {
		String path = "http://localhost/customize";
		String finalName = path.substring(path. lastIndexOf('/'));
		System.out.println(finalName);
	}
}


The above program will return the last segment of a given URL from the path variable. i.e. /customize. You may also remove the special charecter slash by adding +1 after lastIndexOf method in substring method.


Java LastIndexOf() - rashid jorvee
Screenshot of result



Why there is no main method in Servlet?

A Java Servlet is a plugin to a web server and always run in web container.

When we run any program that has main method, the program runs the web server with the help of main method. And a web server runs the Servlet.