validate date format using regex JAVA - regex-lookarounds

Can we validate dd/MM/yyyy and MM/dd/yyyy format together using regex.
I want to validate any valid date format from user, I wrote regex for all other format but not able to differentiate dd/MM/yyyy and MM/dd/yyyy together.

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
*
*/
/**
* #author Ravi Shankar
*
*/
public class DateFormater {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new DateFormater().dateParser("CURR-MAY");
}
public String dateParser(String paramDate){
String date=null;
DateFormat df= null;
DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
//
if(null != paramDate && !paramDate.equalsIgnoreCase("")){
paramDate = paramDate.trim();
if(paramDate.matches("\\d{4}[/]\\d{1,2}[/]\\d{1,2}")){
df = new SimpleDateFormat("yyyy/MM/dd");
}else if(paramDate.matches("\\d{4}[-]\\d{1,2}[-]\\d{1,2}")){
df = new SimpleDateFormat("yyyy-MM-dd");
}else if(paramDate.matches("\\d{4}[.]\\d{1,2}[.]\\d{1,2}")){
df = new SimpleDateFormat("yyyy.MM.dd");
}else if(paramDate.matches("\\d{1,2}[/]\\d{1,2}[/]\\d{2}")){
df = new SimpleDateFormat("MM/dd/yy");
}else if(paramDate.matches("\\d{1,2}[-]\\d{1,2}[-]\\d{2}")){
df = new SimpleDateFormat("MM-dd-yy");
}else if(paramDate.matches("\\d{1,2}[.]\\d{1,2}[.]\\d{2}")){
df = new SimpleDateFormat("MM.dd.yy");
}else if(paramDate.matches("\\d{1,2}[/]\\d{1,2}[/]\\d{4}")){
df = new SimpleDateFormat("MM/dd/yyyy");
}else if(paramDate.matches("\\d{1,2}[-]\\d{1,2}[-]\\d{4}")){
df = new SimpleDateFormat("MM-dd-yyyy");
}else if(paramDate.matches("\\d{1,2}[.]\\d{1,2}[.]\\d{4}")){
df = new SimpleDateFormat("MM.dd.yyyy");
}else if(paramDate.matches("\\d{1,2}[/]\\d{1,2}")){
df = new SimpleDateFormat("MM/dd/yyyy");
paramDate = addYear(paramDate);
}else if(paramDate.matches("\\d{1,2}[-]\\d{1,2}")){
df = new SimpleDateFormat("MM-dd-yyyy");
paramDate = addYear(paramDate);
}else if(paramDate.matches("\\d{1,2}[.]\\d{1,2}")){
df = new SimpleDateFormat("MM.dd.yyyy");
paramDate = addYear(paramDate);
}else if(paramDate.matches("\\d{1,2}[/]\\d{4}")){
df = new SimpleDateFormat("MM/yyyy");
}else if(paramDate.matches("\\d{1,2}[-]\\d{4}")){
df = new SimpleDateFormat("MM-yyyy");
}else if(paramDate.matches("\\d{1,2}[.]\\d{4}")){
df = new SimpleDateFormat("MM.yyyy");
}else if(paramDate.matches("\\S{3}[/]\\d{2}")){
df = new SimpleDateFormat("MMM/yy");
}else if(paramDate.matches("\\S{3}[-]\\d{2}")){
df = new SimpleDateFormat("MM-yy");
}else if(paramDate.matches("\\S{3}[.]\\d{2}")){
df = new SimpleDateFormat("MM.yy");
}else if(paramDate.matches("\\d{1,2}[/]\\S{3}")){
df = new SimpleDateFormat("MM/dd/yyyy");
paramDate = addYear2(paramDate);
}else if(paramDate.matches("\\d{1,2}[-]\\S{3}")){
df = new SimpleDateFormat("MM-dd-yyyy");
paramDate = addYear2(paramDate);
}else if(paramDate.matches("\\d{1,2}[.]\\S{3}")){
df = new SimpleDateFormat("MM.dd.yyyy");
paramDate = addYear2(paramDate);
}else if(paramDate.matches("\\S{3}")){
df = new SimpleDateFormat("MM/dd/yyyy");
paramDate = addYear3(paramDate);
}else if(paramDate.matches("\\S{3,6}[-]\\S{3}")){
df = new SimpleDateFormat("MM/dd/yyyy");
paramDate = addYear3(paramDate);
}
try {
date = sdf.format(df.parse(paramDate));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return date;
}
/**
* #param paramDate
* Adding Year in MM/DD
* #return
*/
public String addYear(String paramDate){
int month = 0;
String sp= "";
if(paramDate.matches("\\d{1,2}[/]\\d{1,2}")){
month =Integer.parseInt(paramDate.split("/")[0]);
sp="/";
}else if(paramDate.matches("\\d{1,2}[-]\\d{1,2}")){
month =Integer.parseInt(paramDate.split("-")[0]);
sp="-";
}else if(paramDate.matches("\\d{1,2}[.]\\d{1,2}")){
month =Integer.parseInt(paramDate.split(".")[0]);
sp=".";
}
month =Integer.parseInt(paramDate.split("/")[0]);
Calendar cal = Calendar.getInstance();
int cm = cal.get(Calendar.MONTH) + 1;
int year = 0;
if((month - cm)>=0){
year = cal.get(Calendar.YEAR);
}else{
year = cal.get(Calendar.YEAR)+1;
}
return paramDate= paramDate+sp+year;
}
/**
* #param paramDate
* Converting dd/MMM to MM/dd and adding yyyy
* #return
*/
public String addYear2(String paramDate){
String date="";
DateFormat sdf = new SimpleDateFormat("MM/dd"); ;
DateFormat df = new SimpleDateFormat("dd/MMM"); ;
if(paramDate.matches("\\d{2}[-]\\S{3}")){
df = new SimpleDateFormat("dd-MMM");
}else if(paramDate.matches("\\d{2}[.]\\S{3}")){
df = new SimpleDateFormat("dd.MMM");
}
try {
date = addYear(sdf.format(df.parse(paramDate)));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return date;
}
/**
* #param paramDate
* converting MMM to MM/dd and adding yyyy
* #return
*/
public String addYear3(String paramDate){
String date="";
DateFormat sdf = new SimpleDateFormat("MM/dd");
DateFormat df = new SimpleDateFormat("MMM");
if(paramDate.matches("\\S{3,6}[-]\\S{3}")){
paramDate=paramDate.split("-")[1];
}
try {
date = addYear(sdf.format(df.parse(paramDate)));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return date;
}
}

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;
}

Saving ArrayList<Uri> in SharedPreferences and retrieving

I am trying to save multiple images into Uri List in SharedPreferences and retrieving them on another activity. I have code here. The error occurs that no adapter attached.
saving :
JSONArray a = new JSONArray();
for (int i = 0; i < uriList.size(); i++) {
a.put(uriList.get(i));
}
String save_form_image = "{\"uri\":\""+a+"\"}";
pref.setStringImage(getApplicationContext(),getTime,save_form_image);
retrieving :
pref = new PreferenceManager();
rv = (RecyclerView) findViewById(R.id.review_image_rv);
uriList = new ArrayList<Uri>();
manager = new LinearLayoutManager(Review.this, manager.HORIZONTAL, false);
rv.setLayoutManager(manager);
rv.setAdapter(image_adapter);
image_adapter = new MultiImageAdapter(uriList,Review.this);
prefs = getSharedPreferences("uri",MODE_PRIVATE);
Collection<?> col_val = prefs.getAll().values();
Iterator<?> it_val = col_val.iterator();
Collection<?> col_key = prefs.getAll().keySet();
Iterator<?> it_key = col_key.iterator();
while (it_val.hasNext() && it_key.hasNext()) {
String value = (String) it_val.next();
String key = (String) it_key.next();
try {
JSONObject jsonObject = new JSONObject(value);
String json = jsonObject.getString("uri");
JSONArray jsonArray = new JSONArray(json);
for(int i = 0; i < jsonArray.length(); i++) {
String a = (String) jsonArray.get(i);
uri = Uri.parse(a);
uriList.add(uri);
image_adapter.addItem(key,uriList);
}
Toast.makeText(getApplicationContext(),"loaded",Toast.LENGTH_SHORT).show();
} catch (JSONException e) {}
image_adapter.notifyDataSetChanged();
}
System.out.println(image_adapter.getItemCount());

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.

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;
}
}

Execution gets stuck at date picking functionality of selenium webdriver

I am new to selenium automation, I have written a script to pick check in and check out dates from webpage of tripadvisor.in. I hope the code and xpaths are correct coz out of 7 or 8 executions the scrips successfully running only once. I thought abt synchronization issue and tried adding all types of waits but still the execution getting stuck as calendar. Sometimes stucking at check-in date, sometimes at check-out date but sometimes working fine. Can I get help to sort this issue plz...
public void selectCheckDate(String date, WebElement forwardArrow) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
try {
Date expectedDate = dateFormat.parse(prop.getProperty(date));
String day = new SimpleDateFormat("dd").format(expectedDate);
String month = new SimpleDateFormat("MMMM").format(expectedDate);
String year = new SimpleDateFormat("yyyy").format(expectedDate);
String expectedMonthYear = month + " " + year;
logger.log(Status.INFO, "Expected Month and year: "+expectedMonthYear);
WebDriverWait wait = new WebDriverWait(driver, 20);
String dd1 = "", dd2 = "";
String d1 = null, d2 = null;
boolean flag1 = false;
boolean flag2 = false;
while (true) {
String displayDate1 = driver.findElement(By.xpath("//*[#class='vr-datepicker-LargeStyles__caption--Srrff']/div")).getText();
String displayDate2 = driver.findElement(By.xpath("(//*[#class='vr-datepicker-LargeStyles__caption--Srrff']/div)[2]")).getText();
if (displayDate1.contains(expectedMonthYear)) {
//addWait();
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 7; j++) {
d1 = "//*[#id='BODY_BLOCK_JQUERY_REFLOW']/div[14]/div/div/div[2]/div/div/div[2]/div[1]/div[3]/div["
+ i + "]/div[" + j + "]";
boolean ex = isElementExists(d1);
if(ex==true) {
dd1 = driver.findElement(By.xpath(d1)).getText();
if (dd1.equals(day)) {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(d1))).click();
//driver.findElement(By.xpath(d1)).click();
flag1 = true;
break;
}
}
}
if (flag1 == true) {
break;
}
}
if (flag1 == true) {
reportPass("Entered date: "+prop.getProperty(date));
break;
}
} else if (displayDate2.contains(expectedMonthYear)) {
//addWait();
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 7; j++) {
d2 = "//*[#id='BODY_BLOCK_JQUERY_REFLOW']/div[14]/div/div/div[2]/div/div/div[2]/div[2]/div[3]/div["
+ i + "]/div[" + j + "]";
boolean ex1 = isElementExists(d2);
if(ex1==true) {
dd2 = driver.findElement(By.xpath(d2)).getText();
if (dd2.equals(day)) {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(d2))).click();
//driver.findElement(By.xpath(d2)).click();
flag2 = true;
break;
}
}
}
if (flag2 == true) {
break;
}
}
if (flag2 == true) {
reportPass("Entered date: "+prop.getProperty(date));
break;
}
} else {
forwardArrow.click();
}
}
} catch (ParseException e) {
reportFail(e.getMessage());
}
}