Selenium - Unable to pick particular rows from TestData excel file - selenium

I am trying to build the TestDataReader.java file. My code should pick only the rows which are tagged by the particular testcaseid (For eg: for Test Case 1, it should pick only rows with TC_001, for Test Case 2 it should pick only rows with TC_002) and return the data to the Dataprovider method. With the below attached code, When i pass Test Case ID as TC_002, it is putting null in the testData[rowNum][0] column for rows with TC_001.
My expectation is that i should get rows only for TC_002. it should not process for TC_001.
Please suggest what is incorrect in this code.
Below is my TestDatareader class:
package com.automation.website.kaspick.utils;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.HashMap;
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;
public class TestDataReader {
XSSFWorkbook xlWorkbook = null;
XSSFSheet sheet = null;
XSSFRow row = null;
XSSFCell cell = null;
String currentDir = Paths.get("").toAbsolutePath().toString();
String testDataFileName = "\\TestData\\TestData.xlsx";
String sheetName = null;
String xlFilePath = currentDir + testDataFileName;
public Object[][] readTestData(String sheetName, String testCaseID) throws IOException {
String rowHeader = null;
String columnValue = null;
FileInputStream fileInputStream = new FileInputStream(xlFilePath);
xlWorkbook = new XSSFWorkbook(fileInputStream);
sheet = xlWorkbook.getSheet(sheetName);
int rowCount = sheet.getLastRowNum();
Object[][] testData = new Object[rowCount][1]; // This object is created to store the MapData as an object for
// DataProvider
if (sheet.getSheetName().equalsIgnoreCase(sheetName)) {
for (int rowNum = 0; rowNum < rowCount; rowNum++) {
HashMap<Object, Object> testDataInEachRow = new HashMap<Object, Object>();
row = sheet.getRow(rowNum + 1); // Since the first row will be header, parse from the second row
int columnCount = row.getLastCellNum();
for (int colNum = 0; colNum < columnCount; colNum++) {
rowHeader = sheet.getRow(0).getCell(colNum).toString();
if(colNum==0 && !row.getCell(colNum).toString().equalsIgnoreCase(testCaseID)) {
break;
}
if (row.getCell(colNum) != null) {
columnValue = row.getCell(colNum).toString();
} else {
columnValue = "";
}
testDataInEachRow.put(rowHeader, columnValue);
}
}
testData[rowNum][0] = testDataInEachRow;
}
return testData;
}
}
Below is my Test Data. I have masked the data
[TestData.xlsx][1]
[1]: https://i.stack.imgur.com/h6cMf.png

Related

i am getting an error in eclipse - An error occurred while instantiating class : 'void org.apache.xmlbeans.XmlOptions.put(java.lang.Object)'

Here is my code i am using
package testCases;
import org.openqa.selenium.By;
import org.testng.Reporter;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.apache.commons.collections4.*;
import base.TestBase;
public class StudentRegistrationForm extends TestBase {
#Test(dataProvider="getData")
public void addStudent(String fname, String email, String CurrentAddress,String PermAddress) {
driver.get(confg.getProperty("url2"));
log.debug("Navigated to : " + confg.getProperty("url2"));
driver.findElement(By.cssSelector(or.getProperty("fullname"))).sendKeys(fname);
driver.findElement(By.cssSelector(or.getProperty("email"))).sendKeys(email);
driver.findElement(By.cssSelector(or.getProperty("currentAddress"))).sendKeys(CurrentAddress);
driver.findElement(By.cssSelector(or.getProperty("permAddress"))).sendKeys(PermAddress);
driver.findElement(By.cssSelector(or.getProperty("submit"))).click();
log.debug("Completed Test 2 - Student Registration Form");
Reporter.log("Completed Test 2 - Student Registration Form");
}
#DataProvider
public Object[][] getData(){
String SheetName = "sheet1";
int rows = excel.getRowCount(SheetName);
int cols = excel.getColumnCount(SheetName);
Object[][] data = new Object[rows-1][cols];
for(int RowNum = 2; RowNum < rows; RowNum++) {
for(int colNum = 0; colNum < cols; colNum++) {
data[RowNum-2][colNum] = excel.getCellData(SheetName, colNum, RowNum);
}
}
return data;
}
}
Also here is the excel reader. I don't know why I am getting an error attached in the picture:
package utilities;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.commons.collections4.list.*;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFCreationHelper;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFHyperlink;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelReader {
public String path;
public FileInputStream fis =null;
public FileOutputStream fileOut = null;
private XSSFWorkbook workbook = null;
private XSSFSheet sheet = null;
private XSSFRow row = null;
private XSSFCell cell = null;
public ExcelReader(String Path) {
this.path = Path;
try {
fis = new FileInputStream(Path);
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheetAt(0);
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public int getRowCount(String Sheetname) {
int sheetIndex = workbook.getSheetIndex(Sheetname);
if(sheetIndex ==-1)
return 0;
else {
sheet = workbook.getSheetAt(0);
int num = sheet.getLastRowNum();
return num;
}
}
public String getCellData(String sheetname, String colName, int rowNum) {
try {
if (rowNum <= 0)
return "";
int index = workbook.getSheetIndex(sheetname);
int col_num = -1;
if(index == -1)
return "";
sheet = workbook.getSheetAt(index);
row = sheet.getRow(0);
for(int i =0;i < row.getLastCellNum(); i++) {
System.out.println(row.getCell(i).getStringCellValue().trim());
if(row.getCell(i).getStringCellValue().trim().equals(colName.trim()))
col_num = i;
}
if(col_num == -1)
return "";
sheet = workbook.getSheetAt(index);
row = sheet.getRow(rowNum-1);
if(row == null)
return "";
cell = row.getCell(col_num);
if(cell==null)
return "";
if(cell.getCellType()==CellType.STRING)
return cell.getStringCellValue();
else if(cell.getCellType()==CellType.NUMERIC || cell.getCellType()==CellType.FORMULA ){
String cellText = String.valueOf(cell.getNumericCellValue());
if (HSSFDateUtil.isCellDateFormatted(cell)) {
double d = cell.getNumericCellValue();
Calendar cal =Calendar.getInstance();
cal.setTime(HSSFDateUtil.getJavaDate(d));
cellText =
(String.valueOf(cal.get(Calendar.YEAR))).substring(2);
cellText = cal.get(Calendar.DAY_OF_MONTH) + "/" +
cal.get(Calendar.MONTH)+1 + "/" +
cellText;
}
return cellText;
}else if(cell.getCellType()==CellType.BLANK)
return "";
else
return String.valueOf(cell.getBooleanCellValue());
}catch(Exception e) {
e.printStackTrace();
return "row "+rowNum+" or column "+colName +" does not exist in xls";
}
}
// returns the data from a cell
public String getCellData(String sheetName,int colNum,int rowNum){
try{
if(rowNum <=0)
return "";
int index = workbook.getSheetIndex(sheetName);
if(index==-1)
return "";
sheet = workbook.getSheetAt(index);
row = sheet.getRow(rowNum-1);
if(row==null)
return "";
cell = row.getCell(colNum);
if(cell==null)
return "";
if(cell.getCellType()==CellType.STRING)
return cell.getStringCellValue();
else if(cell.getCellType()==CellType.NUMERIC || cell.getCellType()==CellType.FORMULA ){
String cellText = String.valueOf(cell.getNumericCellValue());
if (HSSFDateUtil.isCellDateFormatted(cell)) {
// format in form of M/D/YY
double d = cell.getNumericCellValue();
Calendar cal =Calendar.getInstance();
cal.setTime(HSSFDateUtil.getJavaDate(d));
cellText =
(String.valueOf(cal.get(Calendar.YEAR))).substring(2);
cellText = cal.get(Calendar.MONTH)+1 + "/" +
cal.get(Calendar.DAY_OF_MONTH) + "/" +
cellText;
}
return cellText;
}else if(cell.getCellType()==CellType.BLANK)
return "";
else
return String.valueOf(cell.getBooleanCellValue());
}
catch(Exception e){
e.printStackTrace();
return "row "+rowNum+" or column "+colNum +" does not exist in xls";
}
}
// returns true if data is set successfully else false
public boolean setCellData(String sheetName,String colName,int rowNum, String data){
try{
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
if(rowNum<=0)
return false;
int index = workbook.getSheetIndex(sheetName);
int colNum=-1;
if(index==-1)
return false;
sheet = workbook.getSheetAt(index);
row=sheet.getRow(0);
for(int i=0;i<row.getLastCellNum();i++){
//System.out.println(row.getCell(i).getStringCellValue().trim());
if(row.getCell(i).getStringCellValue().trim().equals(colName))
colNum=i;
}
if(colNum==-1)
return false;
sheet.autoSizeColumn(colNum);
row = sheet.getRow(rowNum-1);
if (row == null)
row = sheet.createRow(rowNum-1);
cell = row.getCell(colNum);
if (cell == null)
cell = row.createCell(colNum);
cell.setCellValue(data);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
}
catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}
// returns true if data is set successfully else false
public boolean setCellData(String sheetName,String colName,int rowNum, String data,String url){
try{
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
if(rowNum<=0)
return false;
int index = workbook.getSheetIndex(sheetName);
int colNum=-1;
if(index==-1)
return false;
sheet = workbook.getSheetAt(index);
row=sheet.getRow(0);
for(int i=0;i<row.getLastCellNum();i++){
if(row.getCell(i).getStringCellValue().trim().equalsIgnoreCase(colName))
colNum=i;
}
if(colNum==-1)
return false;
sheet.autoSizeColumn(colNum);
row = sheet.getRow(rowNum-1);
if (row == null)
row = sheet.createRow(rowNum-1);
cell = row.getCell(colNum);
if (cell == null)
cell = row.createCell(colNum);
cell.setCellValue(data);
XSSFCreationHelper createHelper = workbook.getCreationHelper();
//cell style for hyperlinks
CellStyle hlink_style = workbook.createCellStyle();
XSSFFont hlink_font = workbook.createFont();
hlink_font.setUnderline(XSSFFont.U_SINGLE);
hlink_font.setColor(IndexedColors.BLUE.getIndex());
hlink_style.setFont(hlink_font);
//hlink_style.setWrapText(true);
XSSFHyperlink link = createHelper.createHyperlink(HyperlinkType.FILE);
link.setAddress(url);
cell.setHyperlink(link);
cell.setCellStyle(hlink_style);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
}
catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}
// returns true if sheet is created successfully else false
public boolean addSheet(String sheetname){
FileOutputStream fileOut;
try {
workbook.createSheet(sheetname);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
// returns true if sheet is removed successfully else false if sheet does not exist
public boolean removeSheet(String sheetName){
int index = workbook.getSheetIndex(sheetName);
if(index==-1)
return false;
FileOutputStream fileOut;
try {
workbook.removeSheetAt(index);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
// returns true if column is created successfully
public boolean addColumn(String sheetName,String colName){
try{
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
int index = workbook.getSheetIndex(sheetName);
if(index==-1)
return false;
XSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.GREY_40_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
sheet=workbook.getSheetAt(index);
row = sheet.getRow(0);
if (row == null)
row = sheet.createRow(0);
if(row.getLastCellNum() == -1)
cell = row.createCell(0);
else
cell = row.createCell(row.getLastCellNum());
cell.setCellValue(colName);
cell.setCellStyle(style);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
}catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}
// removes a column and all the contents
public boolean removeColumn(String sheetName, int colNum) {
try{
if(!isSheetExist(sheetName))
return false;
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
sheet=workbook.getSheet(sheetName);
XSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.GREY_40_PERCENT.getIndex());
XSSFCreationHelper createHelper = workbook.getCreationHelper();
style.setFillPattern(FillPatternType.NO_FILL);
for(int i =0;i<getRowCount(sheetName);i++){
row=sheet.getRow(i);
if(row!=null){
cell=row.getCell(colNum);
if(cell!=null){
cell.setCellStyle(style);
row.removeCell(cell);
}
}
}
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
}
catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}
// find whether sheets exists
public boolean isSheetExist(String sheetName){
int index = workbook.getSheetIndex(sheetName);
if(index==-1){
index=workbook.getSheetIndex(sheetName.toUpperCase());
if(index==-1)
return false;
else
return true;
}
else
return true;
}
// returns number of columns in a sheet
public int getColumnCount(String sheetName){
// check if sheet exists
if(!isSheetExist(sheetName))
return -1;
sheet = workbook.getSheet(sheetName);
row = sheet.getRow(0);
if(row==null)
return -1;
return row.getLastCellNum();
}
//String sheetName, String testCaseName,String keyword ,String URL,String message
public boolean addHyperLink(String sheetName,String screenShotColName,String testCaseName,int index,String url,String message){
url=url.replace('\\', '/');
if(!isSheetExist(sheetName))
return false;
sheet = workbook.getSheet(sheetName);
for(int i=2;i<=getRowCount(sheetName);i++){
if(getCellData(sheetName, 0, i).equalsIgnoreCase(testCaseName)){
setCellData(sheetName, screenShotColName, i+index, message,url);
break;
}
}
return true;
}
public int getCellRowNum(String sheetName,String colName,String cellValue){
for(int i=2;i<=getRowCount(sheetName);i++){
if(getCellData(sheetName,colName , i).equalsIgnoreCase(cellValue)){
return i;
}
}
return -1;
}
// to run this on stand alone
public static void main(String arg[]) throws IOException{
ExcelReader datatable = null;
datatable = new ExcelReader("C:\\CM3.0\\app\\test\\Framework\\AutomationBvt\\src\\config\\xlfiles\\Controller.xlsx");
for(int col=0 ;col< datatable.getColumnCount("TC5"); col++){
System.out.println(datatable.getCellData("TC5", col, 1));
}
}
}
I dont know why this error occurs. I have added all the required dependencies. the excel reader is from a separe course and that doesn't show any error. only my code - which uses this class, is showing this error.

Automating Import of large csv files(~3gb) with C#

I am a bit new to this but my goal is to import the data from a csv file into a sql table and include additional values for each row being the file name and date. I was able to accomplish this using entity frame work and iterating through each row of the file but with the size of the files it will take too long too actually complete.
I am looking for a method to accomplish this import faster. I was looking into potentially using csvhelper with sqlbulkcopy to accomplish this but was not sure if there was a way to pass in the additional values needed for each row.
public void Process(string filePath)
{
InputFilePath = filePath;
DateTime fileDate = DateTime.Today;
string[] fPath = Directory.GetFiles(InputFilePath);
foreach (var file in fPath)
{
string fileName = Path.GetFileName(file);
char[] delimiter = new char[] { '\t' };
try
{
using (var db = new DatabaseName())
{
using (var reader = new StreamReader(file))
{
string line;
int count = 0;
int sCount = 0;
reader.ReadLine();
reader.ReadLine();
while ((line = reader.ReadLine()) != null)
{
count++;
string[] row = line.Split(delimiter);
var rowload = new ImportDestinationTable()
{
ImportCol0 = row[0],
ImportCol1 = row[1],
ImportCol2 = TryParseNullable(row[2]),
ImportCol3 = row[3],
ImportCol4 = row[4],
ImportCol5 = row[5],
IMPORT_FILE_NM = fileName,
IMPORT_DT = fileDate
};
db.ImportDestinationTable.Add(rowload);
if (count > 100)
{
db.SaveChanges();
count = 0;
}
}
db.SaveChanges();
//ReadLine();
}
}
}
static int? TryParseNullable(string val)
{
int outValue;
return int.TryParse(val, out outValue) ? (int?)outValue : null;
}
}

APACH POI parsing HTML with JSOUP

Parsing an HTML text constaining <font> tags does not reset the size and family font after </font>
My code works pretty well except after </font>.
Before <font size=9> blablabla.. the text size was 11. I was expecting that after </font> the text size was reset to 11, but it still remains at 9. Same thing for the font family.
Certainly I have misunderstood how to use jsoup. I'd better use CSS, but I don't know how to do.
Thanks for help.
package test;
import java.awt.Color;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import org.apache.poi.xwpf.usermodel.UnderlinePatterns;
import org.apache.poi.xwpf.usermodel.VerticalAlign;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import org.jsoup.select.NodeTraversor;
import org.jsoup.select.NodeVisitor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblLayoutType;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblLayoutType;
public class ReadHtml
{
protected static java.util.Vector<String> contenu = null;
org.apache.xmlbeans.XmlCursor cursor = null;
class WStyle
{
protected String police = "Times New Roman";
protected int taille = 11;
protected Color couleur = Color.black;
protected boolean gras = false;
protected boolean italique = false;
public WStyle() // constructeur
{
super();
}
protected String getPolice() {return police;}
protected int getTaille() {return taille;}
protected Color getCouleur() {return couleur;}
protected boolean getGras() {return gras;}
protected boolean getItalique() {return italique;}
protected void setPolice(String p) {police=p;}
protected void setTaille(int t) {taille=t;}
protected void setCouleur(Color c) {couleur=c;}
protected void setGras(boolean g) {gras=g;}
protected void setItalique(boolean i) {italique=i;}
}
public ReadHtml()
{
super();
contenu = new java.util.Vector<String>();
createWordFile();
}
private XWPFParagraph getTableParagraph(XWPFTableCell cell, String html)
{
cell.removeParagraph(0);
XWPFParagraph paragraph = cell.addParagraph();
paragraph.setSpacingAfterLines(0);
paragraph.setSpacingAfter(0);
Document htmlDocument = Jsoup.parse(html);
Elements htmlParagraphs = htmlDocument.select("p");
for(Element htmlParagraph : htmlParagraphs)
{
System.out.println(htmlParagraph);
ParagraphNodeVisitor nodeVisitor = new ParagraphNodeVisitor(paragraph);
NodeTraversor.traverse(nodeVisitor, htmlParagraph);
}
return paragraph;
}
private void createWordFile()
{
XWPFParagraph para = null;
try
{
XWPFDocument document = new XWPFDocument();
FileOutputStream out = new FileOutputStream(new File("./", "NewTable.docx"));
XWPFTable table = document.createTable();
CTTblLayoutType type = table.getCTTbl().getTblPr().addNewTblLayout();
type.setType(STTblLayoutType.FIXED);
table.getCTTbl().addNewTblGrid().addNewGridCol().setW(BigInteger.valueOf(1670));
table.getCTTbl().getTblGrid().addNewGridCol().setW(BigInteger.valueOf(6000));
String myTexte = "<html><head</head><body><p><font face=\"Verdana\" size=11>Good Morning</font> <font size=9 face=\"Times\"> " +
"<i><b>how are you today </b></i></font> Not so bad.<br>Thanks";
// first line
XWPFTableRow tableRow= table.getRow(0);
para = getTableParagraph(tableRow.getCell(0), "<p>Row #1, Col. #1");
tableRow .getCell(0).setParagraph(para);
XWPFTableCell cell = tableRow.createCell();
para = getTableParagraph(cell, myTexte); // Row #1, Col. #2
tableRow .getCell(1).setParagraph(para);
// seconde line
tableRow= table.createRow();
para = getTableParagraph(tableRow.getCell(0), "<p>Row #2, Col. #1");
tableRow .getCell(0).setParagraph(para);
para = getTableParagraph(tableRow.getCell(1), "<p>Row #2, Col. #2");
tableRow.getCell(1).setParagraph(para);
document.write(out);
document.close();
out.close();
System.out.println("NewTable.docx written successully");
}
catch (FileNotFoundException e) {System.out.println("File exception --> " + e.toString()); }
catch (IOException e) {System.out.println("I/O exception --> " + e.toString()); }
catch (Exception e) {System.out.println("Other exception --> " + e.toString()); }
}
public class ParagraphNodeVisitor implements NodeVisitor
{
String nodeName;
String fontFace;
String fontType;
boolean needNewRun;
boolean isItalic;
boolean isBold;
boolean isUnderlined;
int fontSize;
String fontColor;
VerticalAlign align = VerticalAlign.BASELINE ;
XWPFParagraph paragraph;
XWPFRun run;
ParagraphNodeVisitor(XWPFParagraph paragraph)
{
this.paragraph = paragraph;
this.run = paragraph.createRun();
this.nodeName = "";
this.needNewRun = false;
this.isItalic = false;
this.isBold = false;
this.isUnderlined = false;
this.fontSize = 11;
this.fontColor = "000000";
this.fontFace="Times";
}
#Override
public void head(Node node, int depth)
{
nodeName = node.nodeName();
needNewRun = false;
if ("#text".equals(nodeName))
{
run.setText(((TextNode)node).text());
needNewRun = true; //after setting the text in the run a new run is needed
}
else if ("i".equals(nodeName)) {isItalic = true;}
else if ("b".equals(nodeName)) {isBold = true;}
else if ("sup".equals(nodeName)){align = VerticalAlign.SUPERSCRIPT ;}
else if ("u".equals(nodeName)) {isUnderlined = true;}
else if ("br".equals(nodeName)) {run.addBreak();}
else if ("p".equals(nodeName)) {run.addBreak();}
else if ("font".equals(nodeName))
{
fontColor = (!"".equals(node.attr("color")))?node.attr("color").substring(1):"000000";
fontSize = (!"".equals(node.attr("size")))?Integer.parseInt(node.attr("size")):11;
fontFace = (!"".equals(node.attr("face")))?node.attr("face"):"Times";
}
if (needNewRun) run = paragraph.createRun();
needNewRun = false;
run.setItalic(isItalic);
run.setBold(isBold);
if (isUnderlined) run.setUnderline(UnderlinePatterns.SINGLE);
else run.setUnderline(UnderlinePatterns.NONE);
run.setColor(fontColor);
run.setFontSize(fontSize);
run.setFontFamily(fontFace);
run.setSubscript(align);
}
#Override
public void tail(Node node, int depth)
{
nodeName = node.nodeName();
System.out.println("Node=" + nodeName);
if ("i".equals(nodeName)) {isItalic = false;}
else if ("b".equals(nodeName)) {isBold = false;}
else if ("u".equals(nodeName)) {isUnderlined = false;}
else if ("sup".equals(nodeName)) {align= VerticalAlign.BASELINE ;}
else if ("font".equals("nodeName"))
{
fontColor = "000000";
fontSize = 11;
fontFace="Times";
System.out.println("Family=" + fontFace + " Taille=" + fontSize);
}
if (needNewRun) run = paragraph.createRun();
needNewRun = false;
run.setItalic(isItalic);
run.setBold(isBold);
if (isUnderlined) run.setUnderline(UnderlinePatterns.SINGLE); else run.setUnderline(UnderlinePatterns.NONE);
run.setColor(fontColor);
run.setFontSize(fontSize);
run.setFontFamily(fontFace);
run.setSubscript(align);
}
}
public static void main(String[] args)
{
new ReadHtml() ;
}
}
Please change the following line in your tail method, from
else if ("font".equals("nodeName"))
to
else if ("font".equals(nodeName))
You've compared two string literals instead of compare a string literal to the variable. Because of the typo the condition is always false, therefore fontSize is never reseted.

Gettinh NULL pointer while tryying to write into an excel

This is my Util function :
// Method to write into an XL
public static void writeXL(String fPath, String fSheet, String[][] xData) throws Exception{
File outFile = new File(fPath);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet osheet = wb.createSheet(fSheet);
int xR_TS = xData.length;
// System.out.println(xR_TS);
int xC_TS = xData[0].length;
// System.out.println(xC_TS);
for (int myrow = 0; myrow < xR_TS; myrow++) {
HSSFRow row = osheet.createRow(myrow);
for (int mycol = 0; mycol < xC_TS; mycol++) {
HSSFCell cell = row.createCell(mycol);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(xData[myrow][mycol]);
}
FileOutputStream fOut = new FileOutputStream(outFile);
wb.write(fOut);
fOut.flush();
fOut.close();
}
}
While I am trying to write into this excel using the below command :
// i is the loop value
xlActualTot[i][5]=PayAmt; // where PayAmt is the value I am capturing from website and storing it in xlActualTot[0][5] (type is String[][])
Utils.writeXL("<filepath>","TestData",xlActualTot);
I am getting the below exception at "xlActualTot[0][5]=PayAmt" this line :
java.lang.NullPointerException
Can you all please suggest why I am getting that error?

SQL query into JTable

I've found one totally working query, which gets columns and their data from Oracle DB and puts the output in console printout.
I've spent 3 hours trying to display this data in Swing JTable.
When I am trying to bind data with JTable:
jTable1.setModel(new javax.swing.table.DefaultTableModel(
data, header
));
it keeps telling me that constructor is invalid. That's true, because I need arrays [] and [][] to make that. Any ideas how this can be implemented?
Here is the original query:
package com.javacoderanch.example.sql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class MetadataColumnExample {
private static final String DRIVER = "oracle.jdbc.OracleDriver";
private static final String URL = "jdbc:oracle:thin:#//XXX";
private static final String USERNAME = "XXX";
private static final String PASSWORD = "XXX";
public static void main(String[] args) throws Exception {
Connection connection = null;
try {
//
// As the usual ritual, load the driver class and get connection
// from database.
//
Class.forName(DRIVER);
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
//
// In the statement below we'll select all records from users table
// and then try to find all the columns it has.
//
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select *\n"
+ "from booking\n"
+ "where TRACKING_NUMBER = 1000001741");
//
// The ResultSetMetaData is where all metadata related information
// for a result set is stored.
//
ResultSetMetaData metadata = resultSet.getMetaData();
int columnCount = metadata.getColumnCount();
//
// To get the column names we do a loop for a number of column count
// returned above. And please remember a JDBC operation is 1-indexed
// so every index begin from 1 not 0 as in array.
//
ArrayList<String> columns = new ArrayList<String>();
for (int i = 1; i < columnCount; i++) {
String columnName = metadata.getColumnName(i);
columns.add(columnName);
}
//
// Later we use the collected column names to get the value of the
// column it self.
//
while (resultSet.next()) {
for (String columnName : columns) {
String value = resultSet.getString(columnName);
System.out.println(columnName + " = " + value);
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
connection.close();
}
}
}
Ok I found a bit better way adding SQL query to JTable without even using the ArrayList. Maybe will be helpful for someone, completely working:
import java.awt.*;
import javax.swing.*;
import java.sql.*;
import java.awt.image.BufferedImage;
public class report extends JFrame {
PreparedStatement ps;
Connection con;
ResultSet rs;
Statement st;
JLabel l1;
String bn;
int bid;
Date d1, d2;
int rows = 0;
Object data1[][];
JScrollPane scroller;
JTable table;
public report() {
Container cp = getContentPane();
cp.setLayout(new BorderLayout());
setSize(600, 600);
setLocation(50, 50);
setLayout(new BorderLayout());
setTitle("Library Report");
try {
Class.forName("oracle.jdbc.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#XXXXX", "XXXXX", "XXXXX");
} catch (Exception e) {
}
try {
/*
* JDBC 2.0 provides a way to retrieve a rowcount from a ResultSet without having to scan through all the rows
* So we add TYPE_SCROLL_INSENSITIVE & CONCUR_READ_ONLY
*/
st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); //Creating Statement Object
} catch (SQLException sqlex) {
System.out.println("!!!###");
}
try {
rs = st.executeQuery("select TRACKING_NUMBER, INCO_TERM_CODE, MODE_OF_TRANSPORT\n"
+ "from salog.booking\n"
+ "where rownum < 5");
// Counting rows
rs.last();
int rows = rs.getRow();
rs.beforeFirst();
System.out.println("cc " + rows);
ResultSetMetaData metaData = rs.getMetaData();
int colummm = metaData.getColumnCount();
System.out.println("colms =" + colummm);
Object[] Colheads = {"BookId", "BookName", "rtyry"};
if (Colheads.length != colummm) {
// System.out.println("EPT!!");
JOptionPane.showMessageDialog(rootPane, "Incorrect Column Headers quantity listed in array! The program will now exit.", "System Error", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
data1 = new Object[rows][Colheads.length];
for (int i1 = 0; i1 < rows; i1++) {
rs.next();
for (int j1 = 0; j1 < Colheads.length; j1++) {
data1[i1][j1] = rs.getString(j1 + 1);
}
}
JTable table = new JTable(data1, Colheads);
JScrollPane jsp = new JScrollPane(table);
getContentPane().add(jsp);
} catch (Exception e) {
}
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[]) {
JFrame frm = new report();
frm.setSize(600, 600);
frm.setLocation(50, 50);
BufferedImage image = null;
frm.setIconImage(image);
frm.setVisible(true);
frm.show();
}
}