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

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.

Related

Android MPAndroidChart xAxis.setValueFormatter throws ArrayIndexOutOfBoundsException

Good morning,
I'm struggling with ArrayIndexOutOfBoundsException thrown when i'm inserting the row
xAxis.setValueFormatter(formatter) (commented in code).
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bc = findViewById(R.id.chart);
CaricaStorico cs = new CaricaStorico();
try {
cs.execute().get();
} catch (ExecutionException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
List<BarEntry> turno1 = new ArrayList<>();
List<BarEntry> turno2 = new ArrayList<>();
List<BarEntry> turno3 = new ArrayList<>();
String[] date = new String[100];
boolean datiturno1 = false;
boolean datiturno2 = false;
boolean datiturno3 = false;
for (int i = 0; i < storicoMacchina.size(); i++) {
Storico st = storicoMacchina.get(i);
System.out.println(st.getData() + " - " + st.getProduzione1() + " - " + st.getProduzione2() + " - " + st.getProduzione3());
turno1.add(new BarEntry(i, st.getProduzione1()));
turno2.add(new BarEntry(i, st.getProduzione2()));
turno3.add(new BarEntry(i, st.getProduzione3()));
if (st.getProduzione1() != 0) {
datiturno1 = true;
}
if (st.getProduzione2() != 0) {
datiturno2 = true;
}
if (st.getProduzione3() != 0) {
datiturno3 = true;
}
Calendar c = Calendar.getInstance();
c.setTime(st.getData());
String dataMese = c.get(Calendar.DAY_OF_MONTH) + "/" + (c.get(Calendar.MONTH) + 1);
xLabels.add(dataMese);
}
ValueFormatter formatter = new ValueFormatter() {
#Override
public String getAxisLabel(float value, AxisBase axis) {
return xLabels.get((int) value);
}
};
BarDataSet set1 = null;
BarDataSet set2 = null;
BarDataSet set3 = null;
set1 = new BarDataSet(turno1, "Turno 1");
set2 = new BarDataSet(turno2, "Turno 2");
set3 = new BarDataSet(turno3, "Turno 3");
System.out.println(datiturno1 + "," + datiturno2 + "," + datiturno3);
float groupSpace = 0.04f;
float barSpace = 0.02f;
float barWidth = 0.3f;
// set1.setColors(new int[] { R.color.red, R.color.red1, R.color.red2, R.color.red3 },MainActivity.this);
set1.setColor(getResources().getColor(R.color.turno1));
set2.setColor(getResources().getColor(R.color.turno2));
set3.setColor(getResources().getColor(R.color.turno3));
BarData barData;
if (datiturno3 == false) {
barData = new BarData(set1, set2);
groupSpace = 0.06f;
barSpace = 0.02f;
barWidth = 0.45f;
} else {
barData = new BarData(set1, set2, set3);
}
barData.setBarWidth(barWidth);
bc.setData(barData);
Description desc = new Description();
desc.setText("Produzione ultima settimana");
bc.setDescription(desc);
bc.groupBars(0, groupSpace, barSpace);
XAxis xAxis = bc.getXAxis();
xAxis.setCenterAxisLabels(true);
xAxis.setPosition(XAxis.XAxisPosition.BOTH_SIDED);
xAxis.setAxisMinimum(0f);
xAxis.setGranularity(1);
xAxis.setAxisMaximum(storicoMacchina.size());
// xAxis.setValueFormatter(formatter);
bc.invalidate();
}
without this line code is working fine except for the labels in xAxis that i'm trying to set with this line.
Anyone can help me to find what i'm doing wrong?
Thank you for your help
your text
I'have found workaround to solve my problem changing the code above with this
If anyone can explain me the reason value index differs from my xlabel, dataset size will be appreciated.
Thanks again
public String getAxisLabel(float value, AxisBase axis) {
String label = "";
if ((value >= 0) && (value <= xLabels.size() -1)) {
label = xLabels.get((int) value);
}
return label;
}

Want to use same data provider but different excel path for different functions to provide data in selenium

Want to use same DataProvider to provide data to multiple methods. Have created utility using Apache POI to read excel File and parameterized it and using data provider im sending data to the application.
Data Provider provides the data to one of the methods but using same data provider I want to provide data to another method but with different excel path. In short, parameterized the path. How to do it?
public Object [][] logindetails() {
configexcel datas= new configexcel("C:\\Users\\xyz.xlsx"); //configexcel class
int rows= datas.rowsncol(0);
int col= datas.column(0);
Object [][] data= new Object[rows-1][col];
for(int i=1;i<rows;i++) {
for (int j=0;j<col;j++) {
data[i-1][j]= datas.readdata(0,i,j);
}
return data;
}
--configexcel datas= new configexcel("C:\\Users\\xyz.xlsx"); //want to parameterize this.
//Constructor
package excelconfig;
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class configexcel {
XSSFWorkbook loadwb;
XSSFSheet sheet;
public configexcel(String excelpath) {
try {
File src=new File(excelpath);
FileInputStream file= new FileInputStream(src);
loadwb= new XSSFWorkbook(file);
} catch (Exception e) {
System.out.print("The error is"+e.getMessage());
}
}
public String readdata(int sheets,int row,int col) {
sheet=loadwb.getSheetAt(sheets);
String inputs=sheet.getRow(row).getCell(col).getStringCellValue();
return inputs;
}
public int rowsncol(int rows) {
int count=loadwb.getSheetAt(rows).getLastRowNum();
count=count+1;
return count;
}
public int column(int col) {
sheet= loadwb.getSheetAt(0);
int counts= sheet.getRow(col).getLastCellNum();
// counts=counts+1;
return counts;
}```
}
Use excel reader in selenium and store data fields in your code and do parameterization
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Calendar;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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.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 (Exception e) {
e.printStackTrace();
}
}
// returns the row count in a sheet
public int getRowCount(String sheetName) {
int index = workbook.getSheetIndex(sheetName);
if (index == -1)
return 0;
else {
sheet = workbook.getSheetAt(index);
int number = sheet.getLastRowNum() + 1;
return number;
}
}
// returns the data from a cell
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 "";
//System.out.println(cell.getCellType().name());
//
if (cell.getCellType().name().equals("STRING"))
return cell.getStringCellValue();
// if (cell.getCellType().STRING != null)
// if(cell.getCellType()==Xls_Reader.CELL_TYPE_STRING)
// return cell.getStringCellValue();
else if ((cell.getCellType().name().equals("NUMERIC")) || (cell.getCellType().name().equals("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.DAY_OF_MONTH) + "/" + cal.get(Calendar.MONTH) + 1 + "/" + cellText;
// System.out.println(cellText);
}
return cellText;
} else if (cell.getCellType().BLANK != null)
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().name().equals("STRING"))
return cell.getStringCellValue();
//
// if (cell.getCellType().STRING != null)
// return cell.getStringCellValue();
else if ((cell.getCellType().name().equals("NUMERIC")) || (cell.getCellType().name().equals("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;
// System.out.println(cellText);
}
return cellText;
} else if (cell.getCellType().BLANK != null)
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 style
// CellStyle cs = workbook.createCellStyle();
// cs.setWrapText(true);
// cell.setCellStyle(cs);
cell.setCellValue(data);
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) {
// System.out.println("**************addColumn*********************");
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.GREY_40_PERCENT.index);
// style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
sheet = workbook.getSheetAt(index);
row = sheet.getRow(0);
if (row == null)
row = sheet.createRow(0);
// cell = row.getCell();
// if (cell == null)
// System.out.println(row.getLastCellNum());
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.GREY_40_PERCENT.index);
XSSFCreationHelper createHelper = workbook.getCreationHelper();
// style.setFillPattern(XSSFCellStyle.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();
}
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;
}
}

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.

Reading 3rd data data from excel using HSSF

I am trying to read the excel data, there are 2 data exist in the excel but my program is trying to read 3rd data which is null. Can some one please help me on this. below is my code.
public static Object[][] readExcel(String filePath, String sheetName)
throws IOException {
String[][] sheetData = null;
FileInputStream inputStream = new FileInputStream(filePath);
workBook = new HSSFWorkbook(inputStream);
sheet = workBook.getSheet(sheetName);
int k, l;
int rowCount = sheet.getLastRowNum()-sheet.getFirstRowNum();
System.out.println(rowCount);
int readRowCount = sheet.getFirstRowNum();
Row r = sheet.getRow(1);
int totalCol = r.getLastCellNum();
System.out.println(totalCol);
sheetData = new String[rowCount + 1][totalCol];
k = 0;
for (int i = readRowCount + 1; i <= rowCount; i++, k++) {
l = 0;
for (int j = 0; j < totalCol; j++, l++) {
try {
sheetData[k][l] = getCellData(i, j);
System.out.println(sheetData[k][l]);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return (sheetData);
}
public static String getCellData(int RowNum, int ColNum) throws Exception {
try {
Cell = sheet.getRow(RowNum).getCell(ColNum);
String CellData = Cell.getStringCellValue();
return CellData;
} catch (Exception e) {
return "";
}
}
enter image description here

Get List of artifacts in an Ivy Repositoty

I manage an Ivy repository with an extensive number of artifacts and i have been requested to list all third party librarys which we have a hundred odd. does anyone know of a a way to retrieve a list of artifacts from an ivy repo?
i found no such way to do this, i wrote a script in java to get the results, thought i might share the answer if people wanted it in the future, it is also formatted to be copied straight into an excel document.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
public class ListArtifacts {
public static void main(String[] args) {
Collection<File> all = new ArrayList<File>();
addTree(new File("."), all);
String delimeter = "\\.";
List<String> remove = new ArrayList<String>();
List<String> everything = new ArrayList<String>();
remove.add("pom");
remove.add("jar");
remove.add("xml");
remove.add("txt");
remove.add("sha1");
remove.add("md5");
remove.add("metadata");
remove.add("tar");
remove.add("gz");
remove.add("zip");
remove.add("rar");
FileWriter fWriter = null;
BufferedWriter writer = null;
try {
fWriter = new FileWriter("info.txt");
writer = new BufferedWriter(fWriter);
Iterator itr = all.iterator();
while (itr.hasNext() == true){
String[] split;
String temp = itr.next().toString();
split = temp.split(delimeter);
int i = 0;
int j = 0;
boolean flag = false;
while (i < split.length){
while (j < remove.size()){
if (split[i].equals(remove.get(j))){
flag = true;
}
j++;
}
j = 0;
i++;
}
if (flag == false){
String output = "";
int k=0;
boolean flag2 = false;
boolean hasVersion = false;
while (k < split.length){
if (flag2 == true){
output += ".";
flag2 = false;
}
output = output + split[k].toString();
boolean lastInt = false;
try{
String last = split[k].substring(split[k].length() - 1);
if (isInteger(last) == true)
lastInt = true;
}catch(Exception e){}
if ((isInteger(split[k].toString()) == true) || (lastInt == true)){
flag2 = true;
hasVersion = true;
}
k++;
}
if (hasVersion == true){
everything.add(output.substring(1));
writer.append(output.substring(1));
writer.newLine();
}
}
}
int i = 0;
String delim = "\\\\";
String finalOutput = "";
String toSplit = "";
while (i < everything.size()){
toSplit = everything.get(i);
String[] split2 = toSplit.split(delim);
finalOutput = split2[0] + "\t";
int j = 1;
while (j < split2.length-2){
finalOutput += split2[j] + ".";
j++;
}
finalOutput += split2[split2.length-2] + "\t";
finalOutput += split2[split2.length-1];
writer.append(finalOutput);
writer.newLine();
i++;
}
writer.close();
} catch (Exception e) {
}
System.out.println(all);
}
public static boolean isInteger(String input )
{
try
{
Integer.parseInt(input);
return true;
}
catch(Exception e)
{
return false;
}
}
static void addTree(File file, Collection<File> all) {
File[] children = file.listFiles();
if (children != null) {
for (File child : children) {
all.add(child);
addTree(child, all);
}
}
}
}
im sure this can be done much more cleanly, but i did no higher thinking just did the first thing i thought of with no revision.
If you are looking to do this using ivy during a build, the report task should help you get a report of all the JARs you are using.
If you are trying to fetch these details from the repository manager (covering all possible users), could you answer the question from #oers? Repository managers often offer some API that you can use to get reports about the artifacts that they store.