0

I have created a cucumber project. Project structure can be seen in the below screenshot

My main class is util package and RunCukesTest is the main class

enter image description here

I tried to create Executable Jar by right clicking on the project

My pom.xml looks like this

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>cucumber-aaa-Maven-Junit</groupId>
    <artifactId>cucumber-aaa-Maven-Junit</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>cucumber-aaa-Maven-Junit</name>
    <description>cucumber-aaa-Maven-Junit</description>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.5.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/info.cukes/cucumber-java -->
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>1.2.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/info.cukes/cucumber-core -->
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-core</artifactId>
            <version>1.2.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/info.cukes/cucumber-junit -->
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>1.2.5</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>com.vimalselvam</groupId>
            <artifactId>cucumber-extentsreport</artifactId>
            <version>3.0.1</version>
        </dependency>

        <dependency>
            <groupId>com.relevantcodes</groupId>
            <artifactId>extentreports</artifactId>
            <version>2.41.2</version>
        </dependency>

        <dependency>
            <groupId>com.aventstack</groupId>
            <artifactId>extentreports</artifactId>
            <version>3.0.7</version>
            <scope>provided</scope>
        </dependency>


    </dependencies>

    <build>
            <plugins>
                <plugin>
                    <artifactId>maven-assembly-plugin</artifactId>
                    <configuration>
                        <descriptorRefs>
                            <descriptorRef>jar-with-dependencies</descriptorRef>
                        </descriptorRefs>
                        <archive>
                            <manifest>
                                <mainClass>util.RunCukesTest</mainClass>
                            </manifest>
                        </archive>
                    </configuration>
                </plugin>
            </plugins>
    </build>

</project>

I created runnable jar by right clicking projet-->Export-->Runnable jar--> Then Copy required libraries into a sub-folder next to the generated Jar

See SS below

[enter image description here][2]

I opened cmd and gave java -jar Maven.jar and got the error message saying "java.lang.IllegalArgumumentException: Not a file or directory: " SS below

Pls help me in resolving this issue.

I also tried with Library--> extract required libraries into generated Jar while exporting to Jar but no luck.

enter image description here

Ravi
  • 30,829
  • 42
  • 119
  • 173
  • Debug your main file, outside jar, and see what files/resources it requires in youre FileResourceIterator class – Optional Sep 28 '17 at 03:38
  • When I debug my main file, it runs perfectly. – Mohammed Sajjad Sep 28 '17 at 03:47
  • If I take that Jar file inside my project folder.. it works fine.. since I moved that jar to other location(in cmd, you can see its in desktop), I am facing this issue.. – Mohammed Sajjad Sep 28 '17 at 03:53
  • Then that tells you the issue. Probably your class looks out for file/folder in some relative path, which is not present, when you are running jar from different location. – Optional Sep 28 '17 at 03:59
  • I want my jar file to be independent of the project. I mean, it should run even if I run from any location. Please tell me how do I do that – Mohammed Sajjad Sep 28 '17 at 04:03
  • I guess we can only tell that depending on what is there in your code for FileResourceIterator or wherever u are looking for a directory – Optional Sep 28 '17 at 04:10
  • Can you please provide me any reference to create an executable jar for Maven(cucumber) project – Mohammed Sajjad Sep 28 '17 at 04:14
  • Creating executable jar is fine. You already did it. But the code inside the jar also should be compatible to work from any location and not fixed location. e.g if you create an executable jar, that depends on properties or config file at Location x/b/a and throws error if its not there, then that is not the issue of jar – Optional Sep 28 '17 at 04:16
  • That was a good point.. I found the problem.. since its a cucumber project, I have mentioned feature file path in RunCukesTest.. that y it is throwing error when I move jar file away from project.. any solution? – Mohammed Sajjad Sep 28 '17 at 05:01
  • You can add the file, in relative location, from where you are running your jar. – Optional Sep 28 '17 at 05:20
  • I have elaborated the same question in another question. Can u please look into this issue and tell me how to resolve this. https://stackoverflow.com/questions/46525682/how-to-maintain-folder-structure-while-exporting-to-runnable-jar-in-eclipse – Mohammed Sajjad Oct 02 '17 at 17:27

2 Answers2

0

src/test/**/ won't be part of your jar file by default. See this SO post on creating an executable test-jar

How can I include test classes into Maven jar and execute them?

beirtipol
  • 823
  • 5
  • 21
0

Use these,

package com;
import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class Example {
    WebDriver driver = null;
    @Test(dataProvider="getData")
    public void SearchTerm(String browser,String str1, String str2) {
        /*int c = str2.split(str1).length - 1;
        if(c>0)
            System.out.println("Number of times found: "+c);*/
        if(browser.equalsIgnoreCase("chrome")) {
            System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\Drivers\\chromedriver.exe");
            driver = new ChromeDriver();
        }else if(browser.equalsIgnoreCase("Firefox")){
            System.setProperty("webdriver.gecko.driver", "D:\\Selenium\\Drivers\\geckodriver.exe");
            DesiredCapabilities capabilities = DesiredCapabilities.firefox();
            capabilities.setCapability("marionette", true);
            driver = new FirefoxDriver(capabilities);
        }
        int i = 0;
        Pattern p = Pattern.compile(str1);
        Matcher m = p.matcher( str2 );
        while (m.find()) {
            i++;
        }
        System.out.println(i);
    }
    @Test
    public void takeScreenshot() throws IOException {
        File reportFile;
        reportFile =  new File("");;
        while (reportFile.exists());
        File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(screenshot, reportFile);
    }
    @DataProvider(name = "getData", parallel = true )
    public Object[][] getData() throws Exception{
        XlsxReader xls = new XlsxReader("Data");
        int rows = xls.getRowCount("Sheet1");
        int cols = xls.getColumnCount("Sheet1");

        Object[][] data = new Object[rows-1][cols];

        for(int rNum=2;rNum<=rows;rNum++) {
            for(int cNum=0;cNum<cols;cNum++) {
                data[rNum-2][cNum] = xls.getCellData("Sheet1", cNum, rNum);
                System.out.println(xls.getCellData("Sheet1", cNum, rNum));
            }
        }
        return data;
    }
}

And this xlsxreader.java

package com;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Calendar;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.util.NumberToTextConverter;
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 XlsxReader
{             
                private XSSFWorkbook workbook;
                private XSSFSheet Sheet;
                private XSSFRow row;
                private XSSFCell cell;
                private FileInputStream fis;
                private int iIndex;
                private static String sFileName1 = null;
                public XlsxReader(String sFileName)
                {
                                sFileName1 = sFileName;
                                try
                                {
                                                //app = new ConfigManager("App");
                                                String dir = null;
                                                File directory = new File (".");
                                                dir = directory.getCanonicalPath();
                                                String sFilePath = dir + "\\Data\\" + sFileName + ".xlsx";
                                                //String sFilePath = "D:\\FrameWorks\\SeleniumJava\\WorkSpace\\GuidewirePC\\Data\\Data.xlsx";
                                                File file = new File(sFilePath);
                                                if(file.exists())
                                                {
                                                fis = new FileInputStream(sFilePath);
                                                workbook = new XSSFWorkbook(fis);

                                                fis.close();
                                                }
                                                else
                                                {
                                                                //UtilityMethods.infoBox("File with name-'"+sFileName+"' doesn't exists in Data Folder, Please Re-check given file name", "Config.properties");
                                                                System.out.println("doesn't exists in Data Folder" );
                                                                System.exit(0);
                                                }
                                }
                                catch (Exception e)
                                {                                             
                                                System.out.println("Exceptione is ="+e.getMessage());
                                                //UtilityMethods.infoBox(e.getMessage(), "Exception");
                                                System.exit(0);
                                }
                }

                public void setCellData(String sheetName,String Result,  int RowNum, int ColNum) throws Exception      {

                                iIndex = workbook.getSheetIndex(sheetName);
                                if(iIndex==-1)
                                {
                                                //UtilityMethods.infoBox("Sheet with name-'"+sheetName+"' doesn't exists in this excel file, please Re-check given sheet name","Missing sheet");
                                                System.exit(0);
                                }
                                                Sheet = workbook.getSheetAt(iIndex);
                                                row = Sheet.getRow(RowNum);
                                                Cell cell2 = row.createCell(ColNum);
                                                cell2.setCellValue(Result);

                                                //cell = Sheet.getRow(RowNum).getCell(ColNum); 
            //cell.setCellValue(Result);
                                                String dir = null;
                                                File directory = new File (".");
                                                dir = directory.getCanonicalPath();
                                                String sFilePath = dir + "\\Data\\" + sFileName1 + ".xlsx";
                                                FileOutputStream webdata=new FileOutputStream(sFilePath);
                                                workbook.write(webdata);
                                }

                public int getRowCount(String sheetName) throws Exception
                {
                                int number = 0;
                                if(isSheetExist(sheetName))
                                {
                                                Sheet = workbook.getSheetAt(iIndex);
                                                number=Sheet.getLastRowNum()+1;
                                }
                                return number;

                }             

                /**
                * Purpose- To get column count of specified sheet
                * @param sheetName- Sheet name should be provided
                * @return- Returns value of column count
                * @throws Exception
                */
                public int getColumnCount(String sheetName) throws Exception
                {                             
                                if(isSheetExist(sheetName))
                                {
                                                Sheet = workbook.getSheet(sheetName);
                                                row = Sheet.getRow(0);

                                                if(row==null)
                                                                return -1;

                                                return row.getLastCellNum();
                                }
                                return 0;                             
                }
                public String getCellData(String sheetName,String colName,int rowNum,int rowPadding,int columnPadding){
                                try{

                                                if(isSheetExist(sheetName))
                                                {                                             
                                                                if(rowNum <=0)
                                                                {
                                                                                //UtilityMethods.infoBox("Row number should be greater than 0", "");
                                                                                System.exit(0);
                                                                                return "";
                                                                }
                                                                int col_Num=-1;                              
                                                                Sheet = workbook.getSheetAt(iIndex);

                                                                                row=Sheet.getRow(rowPadding);

                                                                for(int i=columnPadding;i<row.getLastCellNum();i++)
                                                                                {             
                                                                                if(row.getCell(i).getStringCellValue().trim().contains(colName.trim()))
                                                                                                {
                                                                                                                col_Num=i;

                                                                                                                break;
                                                                                                }

                                                                                }

                                                                if(col_Num==-1)
                                                                                {
                                                                                                //UtilityMethods.infoBox("Column with specified name"+colName+" is not being displayed", "Config.properties");
                                                                                                System.exit(0);
                                                                                                return "";
                                                                                }

                                                                row = Sheet.getRow(rowNum-1);
                                                                if(row==null)
                                                                                return "";
                                                                cell = row.getCell(col_Num);

                                                                if(cell==null)
                                                                                return "";                                            
                                                                if(cell.getCellType()==Cell.CELL_TYPE_STRING)
                                                                  return cell.getStringCellValue();
                                                                else if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC || cell.getCellType()==Cell.CELL_TYPE_FORMULA )
                                                                {

                                                                                String cellText=NumberToTextConverter.toText(cell.getNumericCellValue());

                                                                                  if (HSSFDateUtil.isCellDateFormatted(cell))
                                                                                  {
                                                                           // format in form of D/M/YY
                                                                                                  double d = cell.getNumericCellValue();
                                                                                                  Calendar cal =Calendar.getInstance();
                                                                                                  cal.setTime(HSSFDateUtil.getJavaDate(d));                                                                        
                                                                                                  int Year = cal.get(Calendar.YEAR);
                                                                                                  int Day = cal.get(Calendar.DAY_OF_MONTH);
                                                                                                  int Month = cal.get(Calendar.MONTH)+1;
                                                                          cellText = Day + "/" + Month + "/" + (String.valueOf(Year)).substring(2);
                                                                      }                                         
                                                                                  return cellText;
                                                                  }
                                                                else if(cell.getCellType()==Cell.CELL_TYPE_BLANK)
                                                      return "";
                                                                else
                                                                  return String.valueOf(cell.getBooleanCellValue());
                                                }
                                                return "";
                                }
                                catch(Exception e)
                                {                                             
                                                System.out.println("Exceptione is =" + e.getMessage());
                                                //UtilityMethods.infoBox("row "+rowNum+" or column "+colName +" does not exist in xls", "Config.properties");
                                                return "row "+rowNum+" or column "+colName +" does not exist in xls";
                                }
                }
                public String getCellData(String sheetName,int colNum,int rowNum){
                                try{

                                                if(isSheetExist(sheetName))
                                                {                                             
                                                                if(rowNum <=0)
                                                                {
                                                                                //UtilityMethods.infoBox("Row number should be greater than 0", "");
                                                                                System.exit(0);
                                                                                return "";
                                                                }

                                                                Sheet = workbook.getSheetAt(iIndex);
                                                                row = Sheet.getRow(rowNum-1);
                                                                if(row==null)
                                                                                return "";
                                                                cell = row.getCell(colNum);

                                                                if(cell==null)
                                                                                return "";                                            
                                                                if(cell.getCellType()==Cell.CELL_TYPE_STRING)
                                                                  return cell.getStringCellValue();
                                                                else if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC || cell.getCellType()==Cell.CELL_TYPE_FORMULA )
                                                                {
                                                                                // String cellText  = String.valueOf(cell.getNumericCellValue());
                                                                                String cellText=NumberToTextConverter.toText(cell.getNumericCellValue());
                                                                                  if (HSSFDateUtil.isCellDateFormatted(cell))
                                                                                  {
                                                                           // format in form of D/M/YY
                                                                                                  double d = cell.getNumericCellValue();
                                                                                                  Calendar cal =Calendar.getInstance();
                                                                                                  cal.setTime(HSSFDateUtil.getJavaDate(d));                                                                        
                                                                                                  int Year = cal.get(Calendar.YEAR);
                                                                                                  int Day = cal.get(Calendar.DAY_OF_MONTH);
                                                                                                  int Month = cal.get(Calendar.MONTH)+1;
                                                                          cellText = Day + "/" + Month + "/" + (String.valueOf(Year)).substring(2);
                                                                      }                                         
                                                                                  return cellText;
                                                                  }
                                                                else if(cell.getCellType()==Cell.CELL_TYPE_BLANK)
                                                      return "";
                                                                else
                                                                  return String.valueOf(cell.getBooleanCellValue());
                                                }
                                                return "";
                                }
                                catch(Exception e)
                                {                                             
                                                System.out.println("Exceptione is =" + e.getMessage());
                                                //UtilityMethods.infoBox("row "+rowNum+" or column "+colNum +" does not exist in xls", "Config.properties");
                                                return "row "+rowNum+" or column "+colNum +" does not exist in xls";
                                }
                }



}