Sonar null pointer voilation while reading excel file - java

Sonar giving null pointer violation for below line of code.
cell1.getRow()
Please could you help us to resolve this issue.
private List<InvalidUploadedExcelData> validateSheet(Sheet sheet) throws Exception {
InvalidUploadedExcelData ITD;
ArrayList<InvalidUploadedExcelData> returnedInvalidTestDataList = new ArrayList<InvalidUploadedExcelData>();
Cell cell1, cell2, cell3;
for (int i = 1; i < sheet.getRows(); i++) {
cell1 = sheet.getCell(0, i);
cell2 = sheet.getCell(1, i);
cell3 = sheet.getCell(2, i);
if ((cell1 == null || StringUtils.isEmpty(cell1.getContents().trim()))) {
ITD = new InvalidUploadedExcelData(TITLE_TEST_ID, "Row-" + (cell1.getRow() + 1) + " Column-" + (cell1.getColumn() + 1) + " is missing");
returnedInvalidTestDataList.add(ITD);
} else if (!isValidProperty(cell1.getContents().trim())) {
ITD = new InvalidUploadedExcelData(TITLE_TEST_ID + ":" + cell1.getContents().trim(), "Row-" + (cell1.getRow() + 1) + " Column-" + (cell1.getColumn() + 1) + " is not valid");
returnedInvalidTestDataList.add(ITD);
}
}
return returnedInvalidTestDataList;
}

The following lines will cause a NullPointerException if cell1 is actually null as you check for null in the if-condition, but you still enter the branch and then access cell1.getRow() in there.
if ((cell1 == null || StringUtils.isEmpty(cell1.getContents().trim()))) {
ITD = new InvalidUploadedExcelData(TITLE_TEST_ID, "Row-" + (cell1.getRow() + 1) + " Column-" + (cell1.getColumn() + 1) + " is missing");
You will need to get the row/column information differently in this case to be safe.

Related

Final 2D-Array data getting altered without implicitly changing its value using Java

I am currently facing an issue regarding this method getSurroundingSumGrid() which is supposed to take data from an earlier grid that was built based off of text file data and use it to determine new values within the array sumGrid. The STATICGRID array gets built at first with the correct values but then as the for loop continues on, the STATICGRID values change to what i have set sumGrid to change to. I don't have any defined code where STATICGRID is ever set to equal another value and if I did it should give an error.
public double[][] getSurroundingSumGrid() {
this.sumGrid = getBaseGrid();
for (int rowNum = 0; rowNum < sumGrid.length; rowNum++) {
final double[][] STATICGRID = this.getBaseGrid();
double topNum = 0, botNum = 0, rightNum = 0, leftNum = 0;
for (int colNum = 0; colNum < sumGrid[0].length; colNum++) {
try {
topNum = STATICGRID[rowNum - 1][colNum];
System.out.println("TOPNUM : (" + (rowNum-1) + "," + colNum + ") " + STATICGRID[rowNum-1][colNum]);
} catch (Exception e) {
topNum = STATICGRID[rowNum][colNum];
System.out.println("Top IndexOutOfBoundsException: " + STATICGRID[rowNum][colNum] + " used instead.");
}
try {
botNum = STATICGRID[rowNum + 1][colNum];
System.out.println("BOTNUM : (" + (rowNum+1) + "," + colNum + ") " + STATICGRID[rowNum+1][colNum]);
} catch (Exception e) {
botNum = STATICGRID[rowNum][colNum];
System.out.println("Bot IndexOutOfBoundsException: " + STATICGRID[rowNum][colNum] + " used instead.");
}
try {
leftNum = STATICGRID[rowNum][colNum - 1];
System.out.println("LEFTNUM : (" + rowNum + "," + (colNum-1) + ") " + STATICGRID[rowNum][colNum-1]);
} catch (Exception e) {
leftNum = STATICGRID[rowNum][colNum];
System.out.println("Left IndexOutOfBoundsException: " + STATICGRID[rowNum][colNum] + " used instead.");
}
try {
rightNum = STATICGRID[rowNum][colNum + 1];
System.out.println("RIGHTNUM : (" + rowNum + "," + (colNum+1) + ") " + STATICGRID[rowNum][colNum+1]);
} catch (Exception e) {
rightNum = STATICGRID[rowNum][colNum];
System.out.println("Right IndexOutOfBoundsException: " + STATICGRID[rowNum][colNum] + " used instead.");
}
this.sumGrid[rowNum][colNum] = topNum + botNum + rightNum + leftNum;
System.out.println("STATICGRID NEW NUM : " + STATICGRID[rowNum][colNum]);
System.out.println("SUMGRID NEW NUM : " + sumGrid[rowNum][colNum]);
}
}
return this.sumGrid;
}
When doing these tests with the code I can see very clearly that the data in both arrays are changing overtime, and in turn giving me wrong results. I've tried for about 2 hours just moving things around and can't seem to figure out how to get this to work properly.
As you can even see, I even attempted rebuilding the STATICGRID array every single time the for loop completed and it wouldn't even hinder the result. It does the same thing regardless of where you put the STATICGRID at (either outside or inside at the top-most level of the for loop, and it doesn't matter whether it's final or not), it does the same thing. After looking at it for so long I'm beyond confused on why my code isn't working and I have a slight feeling that it is the try-catch statement but I wouldn't at all know why. I don't know a ton about the statement and what it does entirely but the reason it is there is because the data can get an IndexOutOfBoundsException so instead of getting that it would instead count itself for each IndexOutOfBoundsException it got as per the assignment instructions.
Thanks and I hope this makes sense.
Alright, thanks to FredK's suggestion at using a deepCopy, I did some research and used this method to get better results. This is the unoptomizedDeepCopy by Philip Isehour. I don't exactly understand it but I'm going to just use it for now and spend some time learning more about this and how they work. I'm currently a CS221 student and we haven't gone over deepCopy yet.
public static Object deepCopy(Object orig) {
Object obj = null;
try {
// Write the object out to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(orig);
out.flush();
out.close();
// Make an input stream from the byte array and read
// a copy of the object back in.
ObjectInputStream in = new ObjectInputStream(
new ByteArrayInputStream(bos.toByteArray()));
obj = in.readObject();
}
catch(IOException e) {
e.printStackTrace();
}
catch(ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
return obj;
}
After this method, I then was able to stop the array from changing value by using this in front of the getBaseGrid() method.
public double[][] getSurroundingSumGrid() {
this.sumGrid = (double[][]) GridMonitor.deepCopy(this.getBaseGrid());
double[][] staticGrid = (double[][]) GridMonitor.deepCopy(this.getBaseGrid());
double topNum, botNum, rightNum, leftNum;
for (int rowNum = 0; rowNum < sumGrid.length; rowNum++) {
for (int colNum = 0; colNum < sumGrid[0].length; colNum++) {
try {
topNum = staticGrid[rowNum - 1][colNum];
} catch (Exception e) {
topNum = staticGrid[rowNum][colNum];
}
try {
botNum = staticGrid[rowNum + 1][colNum];
} catch (Exception e) {
botNum = staticGrid[rowNum][colNum];
}
try {
leftNum = staticGrid[rowNum][colNum - 1];
} catch (Exception e) {
leftNum = staticGrid[rowNum][colNum];
}
try {
rightNum = staticGrid[rowNum][colNum + 1];
} catch (Exception e) {
rightNum = staticGrid[rowNum][colNum];
}
this.sumGrid[rowNum][colNum] = topNum + botNum + rightNum + leftNum;
}
}
return this.sumGrid;
}
Thanks!

Why is it the last data is always null

I have a problem getting all the data in jtable. The last data that display is always "null" even though i enter data in that cell. Can anyone help me
for (int i = 0; i < model_1.getRowCount(); i++) {
if (String.valueOf(model_1.getValueAt(i, 0)) != null && !String.valueOf(model_1.getValueAt(i, 0)).isEmpty()) {
date = String.valueOf(model_1.getValueAt(i, 0));
}
if (String.valueOf(model_1.getValueAt(i, 1)) != null && !String.valueOf(model_1.getValueAt(i, 1)).isEmpty()) {
meal = String.valueOf(model_1.getValueAt(i, 1));
}
if (String.valueOf(model_1.getValueAt(i, 2)) != null && !String.valueOf(model_1.getValueAt(i, 2)).isEmpty()) {
time = String.valueOf(model_1.getValueAt(i, 2));
}
if (String.valueOf(model_1.getValueAt(i, 3)) != null && !String.valueOf(model_1.getValueAt(i, 3)).isEmpty()) {
activity = String.valueOf(model_1.getValueAt(i, 3));
}
try {
System.out.println(date + " " + meal + " " + time + " " + activity);
}
}
here is my sample output:
2017-10-02 sdfsd 01:30 sdfsdfsf
2017-10-03 dsfdfs 01:00 null
I guess your jtable is still active so the data hasn't been saved to the model yet.
Try to add this before your code:
if (table.isEditing())
table.getCellEditor().stopCellEditing();

Optimizing the method block

I'm writing a Selenium code in Java. And below is one of the methods block.
private static void getPaceNumber(WebDriver chromeDriver, String dBName, XSSFSheet paceSheet, String pubName, int i,
XSSFCell cell, XSSFWorkbook workbook) throws Exception {
System.out.println("DBID is " + dBName + " and fpn is " + pubName);
CellStyle style = workbook.createCellStyle();
int defaultHeight = paceSheet.getRow(0).getHeight();
cell = paceSheet.getRow(i).createCell(1);
paceSheet.getRow(i).setHeight((short) (defaultHeight * 2));
if (dBName == "" || dBName.equals("null")) {
System.out.println("Null Block");
cell.setCellValue("N/A");
} else {
chromeDriver.findElement(By.xpath("html/body/form[2]/b/b/table/tbody/tr[2]/td[2]/textarea"))
.sendKeys("\"" + dBName + "\"");
chromeDriver.findElement(By.xpath("html/body/form[2]/b/b/table/tbody/tr[4]/td[2]/input[1]")).click();
// Thread.sleep(500L);
System.out.println("entered second block");
List<WebElement> pace = chromeDriver
.findElements(By.xpath("html/body/form[2]/table[1]/tbody/tr[2]/td[2]/input[1]"));
int paceSize = pace.size();
System.out.println("pace size is " + paceSize);
int pubPaceNumber = 0;
int dbPaceNumber;
if (paceSize >= 1) {
dbPaceNumber = Integer.parseInt(
chromeDriver.findElement(By.xpath("html/body/form[2]/table[1]/tbody/tr[2]/td[2]/input[1]"))
.getAttribute("value"));
chromeDriver.findElement(By.xpath(".//*[#id='searchPublication']")).click();
chromeDriver.findElement(By.xpath("html/body/form[2]/b/b/table/tbody/tr[2]/td[2]/textarea"))
.sendKeys("\"" + pubName + "\"");
chromeDriver.findElement(By.xpath("html/body/form[2]/b/b/table/tbody/tr[4]/td[2]/input[1]")).click();
int paceSizse = chromeDriver
.findElements(By.xpath("html/body/form[2]/table[1]/tbody/tr[2]/td[2]/input[1]")).size();
if (paceSizse >= 1) {
pubPaceNumber = Integer.parseInt(
chromeDriver.findElement(By.xpath("html/body/form[2]/table[1]/tbody/tr[2]/td[2]/input[1]"))
.getAttribute("value"));
} else {
List<WebElement> table = chromeDriver
.findElements(By.xpath("html/body/form[2]/table[1]/tbody/tr[4]/td/b"));
int tabSize = table.size();
System.out.println("Tab size is " + tabSize);
if (tabSize == 1) {
chromeDriver.findElement(By.xpath(".//*[#id='searchPublication']")).click();
chromeDriver.findElement(By.xpath("html/body/form[2]/b/b/table/tbody/tr[2]/td[2]/textarea"))
.sendKeys("\"" + pubName + "\"");
chromeDriver.findElement(By.xpath("html/body/form[2]/b/b/table/tbody/tr[4]/td[2]/input[1]"))
.click();
List<WebElement> paceWithFPN = chromeDriver
.findElements(By.xpath("html/body/form[2]/table[1]/tbody/tr[2]/td[2]/input[1]"));
int paceWithFPNSize = paceWithFPN.size();
if (paceWithFPNSize >= 1) {
cell.setCellValue("N/A");
} else {
cell.setCellValue("N/A");
}
} else {
cell.setCellValue("N/A");
}
}
if (dbPaceNumber == pubPaceNumber) {
cell.setCellValue(dbPaceNumber);
} else {
cell.setCellValue(dbPaceNumber + "\n" + pubPaceNumber);
style.setWrapText(true);
style.setAlignment(CellStyle.ALIGN_RIGHT);
cell.setCellStyle(style);
}
} else {
List<WebElement> table = chromeDriver
.findElements(By.xpath("html/body/form[2]/table[1]/tbody/tr[4]/td/b"));
int tabSize = table.size();
System.out.println("Tab size is " + tabSize);
if (tabSize == 1) {
chromeDriver.findElement(By.xpath(".//*[#id='searchPublication']")).click();
chromeDriver.findElement(By.xpath("html/body/form[2]/b/b/table/tbody/tr[2]/td[2]/textarea"))
.sendKeys("\"" + pubName + "\"");
chromeDriver.findElement(By.xpath("html/body/form[2]/b/b/table/tbody/tr[4]/td[2]/input[1]"))
.click();
List<WebElement> paceWithFPN = chromeDriver
.findElements(By.xpath("html/body/form[2]/table[1]/tbody/tr[2]/td[2]/input[1]"));
int paceWithFPNSize = paceWithFPN.size();
if (paceWithFPNSize >= 1) {
int paceSubNumber = Integer.parseInt(chromeDriver
.findElement(By.xpath("html/body/form[2]/table[1]/tbody/tr[2]/td[2]/input[1]"))
.getAttribute("value"));
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellValue(paceSubNumber);
} else {
cell.setCellValue("N/A");
}
} else {
cell.setCellValue("N/A");
}
}
}
chromeDriver.findElement(By.xpath(".//*[#id='searchPublication']")).click();
}
Basically there are 2 values used in this program dBName and pubName
Here what the program does is.
enter dBName in a text area and get the result and store it in variable `dbPaceNumber.
hit on search and again do the same but this time enter pubName and store the value in variable pubPaceNumber
Compare these two variables and see if they are same, if so, enter the result in Excel Cell else concatenate these two values and store it in Excel Cell.
What is need
Here in my code the below block is repeated once for pubName and once for dBName, I want to know if i can make a common block for both and use it. I mean instead of having two block of same code with different data, is there a way that i can make a single block to check once for pubName and once for dBName.
List<WebElement> table = chromeDriver
.findElements(By.xpath("html/body/form[2]/table[1]/tbody/tr[4]/td/b"));
int tabSize = table.size();
System.out.println("Tab size is " + tabSize);
if (tabSize == 1) {
chromeDriver.findElement(By.xpath(".//*[#id='searchPublication']")).click();
chromeDriver.findElement(By.xpath("html/body/form[2]/b/b/table/tbody/tr[2]/td[2]/textarea"))
.sendKeys("\"" + pubName + "\"");
chromeDriver.findElement(By.xpath("html/body/form[2]/b/b/table/tbody/tr[4]/td[2]/input[1]"))
.click();
List<WebElement> paceWithFPN = chromeDriver
.findElements(By.xpath("html/body/form[2]/table[1]/tbody/tr[2]/td[2]/input[1]"));
int paceWithFPNSize = paceWithFPN.size();
if (paceWithFPNSize >= 1) {
int paceSubNumber = Integer.parseInt(chromeDriver
.findElement(By.xpath("html/body/form[2]/table[1]/tbody/tr[2]/td[2]/input[1]"))
.getAttribute("value"));
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellValue(paceSubNumber);
} else {
cell.setCellValue("N/A");
}
} else {
cell.setCellValue("N/A");
}
Thanks

Why is my jpql .getResultList() returning 0 rows for a good query

I was using the exact same query yesterday and it was working fine today I made a few changes to flow of the program and the query no longer returns and rows.
the first function that my programs goes to:
public void prepareSummary(Date startDate , Date endDate)
{
int getStartDay = getDayFromDate(startDate);
int getStartMonth = getMonthFromDate(startDate);
//
int getEndDay = getDayFromDate(endDate);
int getEndMonth = getMonthFromDate(endDate);
int getYear = getYearFromDate(startDate);
if(getStartMonth <= getEndMonth)
{
if(getStartMonth == getEndMonth)
{
if(getStartDay < getEndDay)
{
while(getStartDay <= getEndDay)
{
Calendar cal = Calendar.getInstance();
cal.set( getYear, getStartMonth, getStartDay);
Date queryStart = getStartOfDay(cal.getTime());
Date queryEnd = getEndOfDay(cal.getTime());
List<Object[]> res = getSumList(queryStart, queryEnd);
doQuery(res);
++getStartDay;
}
}
else
{
}
}
else
{
}
}
else
{
}
}
Here is what getSumList looks like:
public List<Object[]> getSumList(Date start, Date end) {
String query = "";
query += "SELECT COUNT(s) pCount,"
+ "p.nameText,"
+ "g.nameText,"
+ "t.shiftID"
+ " FROM Sheets s , GradeNames g , SpecieNames p, ShiftTimes t"
+ " WHERE s.createdLocal > :start and s.createdLocal < :end"
+ " AND s.specieNameIndex = p.nameIndex "
+ " AND s.gradeNameIndex = g.nameIndex"
+ " AND s.shiftIndex = t.shiftIndex"
+ " GROUP BY p.nameText , g.nameText , t.shiftID";
Query q = em.createQuery(query);
q.setParameter("start", start);
q.setParameter("end", end);
return q.getResultList();
}
This next function doesn't matter at this point because nothing is being executed because the list length is zero:
private void doQuery(List<Object[]> obj)
{
int length = obj.size();
String grade = null;
Long standingCount = (long) 0;
System.out.println("Length" + length);
for (int i = 0; i < length; ++i) {
// HAVE A LIST OF ALL ITEMS PULLED FROM DATABASE
Object[] tmpObj = obj.get(i);
Long tmpCount = (Long) tmpObj[0];
String tmpSpecieName = (String) tmpObj[1];
Double tmpThickness = Double.parseDouble(getSpecie().getThicknessFromSpecie(tmpSpecieName));
String tmpLength = getSpecie().getLengthFromSpecie(tmpSpecieName);
String tmpGradeName = (String) tmpObj[2];
String tmpShift = (String) tmpObj[3];
tmpSpecieName = getSpecie().getSpecieFromSpecie(tmpSpecieName);
//// END OF ALL ITEMS PULLED FROM DATABASE
if (grade != pullGradeName(tmpGradeName) && grade != null) {
System.out.println("Count:" + standingCount + "Grade:" + tmpGradeName + "--" + "Specie" + tmpSpecieName + "Shift:" + tmpShift + "Thickness:" + tmpThickness + "Length:" + tmpLength + "SpecieNAme:" + tmpSpecieName);
// do previous insert
grade = pullGradeName(tmpGradeName);
} else if (grade != pullGradeName(tmpGradeName) && grade == null) {
grade = pullGradeName(tmpGradeName);
} else if (grade == pullGradeName(tmpGradeName)) {
standingCount = standingCount + tmpCount;
}
System.out.println("Count:" + tmpCount + "Grade:" + tmpGradeName + "--" + "Specie" + tmpSpecieName + "Shift:" + tmpShift + "Thickness:" + tmpThickness + "Length:" + tmpLength + "SpecieNAme:" + tmpSpecieName);
}
}
Check the SQL that is generated, and the tables you are querying over. As the query requires inner joins, if one of the tables was cleared, it would return no results. If you want to get a 0 count, you need to use an outer join syntax which isn't possible in JPA unless you use object level mappings:
"SELECT COUNT(s) pCount,"
+ "p.nameText,"
+ "g.nameText,"
+ "t.shiftID"
+ " FROM Sheets s outer join s.specialNameIndex p,"
+ " outer join s.gradeNameIndex g, outer join s.shiftIndex t"
+ " WHERE s.createdLocal > :start and s.createdLocal < :end"
+ " GROUP BY p.nameText , g.nameText , t.shiftID";

return array from inside an if,for statement

I am building a tag reader for inventory purpose. Using the for loop to iterate through the tags to count/total the ids. I get an error on my return line "tagsFound cannot be resolved into a variable". How do i use the variable inside the for loop and then access it outside the loop?
public String[] getTags(AlienClass1Reader reader)throws AlienReaderException{
int coneCount = 0;
int drumCount = 0;
// Open a connection to the reader
reader.open();
// Ask the reader to read tags and print them
Tag tagList[] = reader.getTagList();
if (tagList == null) {
System.out.println("No Tags Found");
} else {
System.out.println("Tag(s) found: " + tagList.length);
for (int i=0; i<tagList.length; i++) {
Tag tag = tagList[i];
System.out.println("ID:" + tag.getTagID() +
", Discovered:" + tag.getDiscoverTime() +
", Last Seen:" + tag.getRenewTime() +
", Antenna:" + tag.getAntenna() +
", Reads:" + tag.getRenewCount()
);
//tagFound[i]= "" + tag.getTagID();
String phrase = tag.getTagID();
tagFound[i] = phrase;
String delims = "[ ]+";
String[] tokens = phrase.split(delims);
if (tokens[0].equals("0CCE") && tokens[3].equals("1001")){drumCount++;}
if (tokens[0].equals("0CCE") && tokens[3].equals("1004")){coneCount++;}
String[] tagsFound;
tagsFound[i] = tag.getTagID();
}
System.out.println("Cones= " + coneCount);
System.out.println("Drums= " + drumCount);
// Close the connection
reader.close();
return tagsFound;
}
}
public String[] getTags(AlienClass1Reader reader)throws AlienReaderException{
int coneCount = 0;
int drumCount = 0;
// Open a connection to the reader
reader.open();
// Ask the reader to read tags and print them
Tag tagList[] = reader.getTagList();
if (tagList == null) {
System.out.println("No Tags Found");
} else {
System.out.println("Tag(s) found: " + tagList.length);
String[] tagsFound = new String[tagList.length];
for (int i=0; i<tagList.length; i++) {
tagsFound = "";
Tag tag = tagList[i];
System.out.println("ID:" + tag.getTagID() +
", Discovered:" + tag.getDiscoverTime() +
", Last Seen:" + tag.getRenewTime() +
", Antenna:" + tag.getAntenna() +
", Reads:" + tag.getRenewCount()
);
//tagFound[i]= "" + tag.getTagID();
String phrase = tag.getTagID();
tagFound[i] = phrase;
String delims = "[ ]+";
String[] tokens = phrase.split(delims);
if (tokens[0].equals("0CCE") && tokens[3].equals("1001")){drumCount++;}
if (tokens[0].equals("0CCE") && tokens[3].equals("1004")){coneCount++;}
tagsFound[i] = tag.getTagID();
}
System.out.println("Cones= " + coneCount);
System.out.println("Drums= " + drumCount);
// Close the connection
reader.close();
return tagsFound;
}
}
the returned array will have empty strings in the positions where the tag does not satisfy the criteria.

Categories

Resources