0

I am new to Selenium and facing an issue while running my selenium Java file from command prompt (through framework).

I have two Java (Selenium) files: 1. ShoppingCart.java (which has all the functions and the main method), 2. ExcelWrite.java (which has Excel objects and deals with Excel sheets for updating results)

I am calling the static method of ExcelWrite.java into my main class ShoppingCart.java as:

<< ExcelWrite.method_name(argument_list) >>

Both files belong to the same package "shop".

When E try to compile the above two files separately by javac ExcelWrite.java and javac ShoppingCart.java, ExcelWrite.java compiles but ShoppingCart.java gives error:

symbol not found at << ExcelWrite.method_name(argument_list) >>

However when when I try this: javac *.java (from the directory where the files are) both files compiles and .class files are created.

But when trying to run ShoppingCart.java from Command Prompt, it's giving me error:

Could not find or load the main class.

Script works perfectly fine on Eclipse.

java version: 1.8.0_25

Path of my jdk in environment variables: C:\Program Files\Java\jdk1.8.0_25\bin; path of my java files: C:\Users\pooja.a.tripathi\Desktop\Omni

Classpath in environment variables: C:\Program Files\Java\jdk1.8.0_25\bin;C:\Dependency\selenium-java-2.40.0.jar;C:\Dependency\selenium-server-standalone-2.40.0.jar;C:\Dependency\Eclipse_TestNG\guava-base-r03.jar;C:\Dependency\Eclipse_TestNG\guava-collections-r03.jar;C:\Dependency\Eclipse_TestNG\junit-4.8.2.jar;C:\Dependency\Eclipse_TestNG\testng.jar;C:\Dependency\Eclipse_TestNG\testng-sorces.jar;C:\Dependency\POI\commons-codec-1.5.jar;C:\Dependency\POI\commons-logging-1.1,jar;C:\Dependency\POI\dom4j-1.6.1.jar\C:\Dependency\POI\junit-4.11.jar;C:\Dependency\POI\log4j-1.2.13.jar;C:\Dependency\POI\poi-examples-3.10-FINAL-20140208;C:\Dependency\POI\poi-excelant-3.10-FINAL-20140208.jar;C:\Dependency\POI\poi-ooxml-3.10-FINAL-20140208.jar;C:\Dependency\POI\poi-ooxml-schemas-3.10-FINAL-20140208.jar;C:\Dependency\POI\poi-scratchpad-3.10-FINAL-20140208;C:\Dependency\POI\stax-api-1.0.1.jar;C:\Dependency\POI\xmlbeans-2.3.0;C:\Dependency\POI\poi-3.10-FINAL-20140208.jar

I also tried setting classpath and using: java -cp shop.ShoppingCart java -cp .ShoppingCart but nothing seems working. I tried everything available on the various threads but to no avail. I read that the issue mainly comes due to classpath.

Can anyone let me know why my both Java files are not getting compiled separately and how to run it?

Below is the code of both the files:

ShoppingCart.java

package shop;

// import jar files
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;


public class ShoppingCart {
// Variable declaration
    private WebDriver driver = new FirefoxDriver();
    String url = "http://omnichanneldemo.com/index.php?route=common/home";
    String portalTitle = "Omnichannel Demo";
    String actualTitle = "";

//Function to launch the site
private void LauchSite(String url) {
      // Command To Open URL In Browser
       System.out.println("Launching Site");
       driver.manage().window().maximize();
       driver.get(url);
       //Verify the Page title
        actualTitle = driver.getTitle();  
        try{
        // compare the actual title of the page with the expected one and print the result as accordingly                               
            if (actualTitle.contentEquals(portalTitle)){
                   WriteLog("//1. Website Launched <" + driver.getCurrentUrl() + ">");                 
               }
            }
            catch(Exception e)
            {               
                e.printStackTrace(); 
                e.getCause();
                WriteLog("//1. error in launching website");                
            }                                    
 } 

//Function to select the category and the product
private void CategorySelection()
{                                                                
    // Select category - "Gaming"
        try{
          WebElement category= driver.findElement(By.linkText("Gaming"));
          WriteLog("//2. Category exist >"+category);         
          if (category!=null){
                  category.click();
            }
          }catch(NoSuchElementException e){
              e.printStackTrace(); 
              e.getCause();
              WebDriverWait wait = new WebDriverWait(driver, 10);             
              WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Gaming")));
              if(element!=null)
                  element.click();
              else
                  WriteLog("//2. Category not clickable or does not exist >"+element);  
          }
    // Select product - "Microsoft Wired Controller For Windows" 
        try{
            WebElement game = driver.findElement(By.linkText("Microsoft Wired Controller For Windows"));
            WriteLog("//3. Game exist >"+game);
            if(game!=null)
                game.click();           
        }catch(NoSuchElementException e){
            e.printStackTrace(); 
            e.getCause();
            WebDriverWait wait = new WebDriverWait(driver, 10);           
          WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Gaming")));
          if(element!=null)
              element.click();
          else
              WriteLog("//3. Category not clickable or does not exist >"+element);  
        }
}

//Function to add category to shopping cart
private void AddCategoryToCart()
{                                                               
    //Select button " Add to Cart"
        try{
            WebElement addbtn = driver.findElement(By.xpath("//button[@id='button-cart']"));
            //System.out.println(addbtn);
            WriteLog("//4. Add to Cart button exist >"+addbtn);
            if (addbtn!=null)
                addbtn.click();
        }catch(Exception e)
        {
            e.printStackTrace(); 
            e.getMessage();
            WriteLog("//4. Unable to proceed as either the Add to Cart button is not visible or not selectable >");
            WebDriverWait wait = new WebDriverWait(driver, 60);           
            WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@id='button-cart']")));
                if(element!=null)
                    element.click();
                else
                    WriteLog("//4. Category not clickable or does not exist >"+element);  }
            try{
                //WebElement item = driver.findElement(By.xpath("(//button[@type='button'])[5]"));              
                WebDriverWait wait1 = new WebDriverWait(driver, 60);          
                WebElement item = wait1.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[3]/div/button")));
                //System.out.println(item);
                if (item!=null){
                    item.click();
                    WriteLog("//5. Item updated in cart. Proceeding with checkout.");

                    /*WebElement details = driver.findElement(By.xpath("//div[@id='cart']/ul/li[2]/div/p/a[2]/strong"));
                    System.out.println(details);*/  
                    /*if (details!=null)
                        {
                            WriteLog("//5. Item updated in cart. Proceeding with checkout."); */
                }
                else
                    System.out.println("Cannot click on item button");

            }
                catch(Exception e)
            {
                e.printStackTrace(); 
                e.getMessage();
                WriteLog("//5. Unable to proceed as either the Add to Cart button is not visible or not selectable. Re-trying >");              
                WebDriverWait wait1 = new WebDriverWait(driver, 60);          
                WebElement item = wait1.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[3]/div/button")));
                System.out.println(item);
                if (item!=null)
                    item.click();
                WebElement details = driver.findElement(By.xpath("//div[@id='cart']/ul/li[2]/div/p/a[2]/strong"));
                    if (details!=null)
                    {
                        WriteLog("//5. Item updated in cart. Proceeding with checkout."); 
                    }
                    else
                        WriteLog("//5.Unable to proceed");
            }               
}  

//Function to checkout from shopping cart
private void CartCheckout(){

     // Select checkout option
        try{
            WebDriverWait wait = new WebDriverWait(driver, 60);           
            WebElement checkout = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@id='cart']/ul/li[2]/div/p/a[2]/strong")));
            //System.out.println(checkout);
            if (checkout!=null){
                checkout.click();  
                //WebElement info = driver.findElement(By.xpath("(//input[@name='account'])[2]"));
                //System.out.println(info);
                //if(info!=null){
                  //WriteLog("//5. Order checked out");  
                //}
            }
        }catch(Exception e)
        {    
            e.printStackTrace(); 
            e.getMessage();
            WebDriverWait wait = new WebDriverWait(driver, 60);  
            WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@id='cart']/ul/li[2]/div/p/a[2]/strong")));
            if(element!=null){
              element.click();
                WebElement info = driver.findElement(By.xpath("(//input[@name='account'])[2]"));
                if(info!=null){
                    WriteLog("//5. Order checked out"); }
                else
                    WriteLog("//5. Cannot proceed");
            }
        }
}

//Function to fill guest customer details
 private void CustomerDetails(){

       //Select "Guest Account" option and continue
     try{
         WebDriverWait wait = new WebDriverWait(driver, 60);  
         WebElement guestrdbtn = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("(//input[@name='account'])[2]")));
         //WebElement guestrdbtn2 = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@id='collapse-checkout-option']/div/div/div/div[2]/label")));
         //System.out.println(guestrdbtn);
         WriteLog("//6. Proceeding with Guest Account");
         if(guestrdbtn!=null){
            guestrdbtn.click();
            driver.findElement(By.id("button-account")).click();
         }          

     }catch(NoSuchElementException e)
     {
         e.getMessage();
         e.printStackTrace();
     }

        //driver.findElement(By.xpath("//div[@id='collapse-checkout-option']/div/div/div/div[2]/label")).click();
        //driver.findElement(By.id("button-account")).click();

       //Fill customer details
     WebDriverWait wait = new WebDriverWait(driver, 60);
     WebElement item = wait.until(ExpectedConditions.elementToBeClickable(By.id("input-payment-firstname")));
     //System.out.println(item);
             if (item!=null){
                 driver.findElement(By.id("input-payment-firstname")).clear();
                 driver.findElement(By.id("input-payment-firstname")).sendKeys("guest");
                 driver.findElement(By.id("input-payment-lastname")).clear();
                 driver.findElement(By.id("input-payment-lastname")).sendKeys("user");
                 driver.findElement(By.id("input-payment-email")).clear();
                 driver.findElement(By.id("input-payment-email")).sendKeys("guest@abc.com");
                 driver.findElement(By.id("input-payment-telephone")).clear();
                 driver.findElement(By.id("input-payment-telephone")).sendKeys("22334455");
                 driver.findElement(By.id("input-payment-address-1")).clear();
                 driver.findElement(By.id("input-payment-address-1")).sendKeys("address1");
                 driver.findElement(By.id("input-payment-city")).clear();
                 driver.findElement(By.id("input-payment-city")).sendKeys("london");
                 driver.findElement(By.id("input-payment-postcode")).clear();
                 driver.findElement(By.id("input-payment-postcode")).sendKeys("54631");
                 WriteLog("//7. Details entered");
        }
             else{
                 System.out.println("error occurred");
             }

         try{
         WebElement rselect = driver.findElement(By.id("input-payment-zone"));
         List<WebElement> roptions = rselect.findElements(By.tagName("option"));
             for (WebElement option : roptions) {
                 if("Assam".equals(option.getText()))option.click();
             }              
         }
         catch(NoSuchElementException e)
         {
             e.printStackTrace(); 
             e.getCause();
             WriteLog("//7. Unable to value from dropdown");
             WebDriverWait wait1 = new WebDriverWait(driver, 60);  
             WebElement rselect= wait1.until(ExpectedConditions.elementToBeClickable(By.id("input-payment-zone")));
             if (rselect!=null){                 
             List<WebElement> roptions = rselect.findElements(By.tagName("option"));
                 for (WebElement option : roptions) {
                     if("Assam".equals(option.getText()))option.click();
                 }        
             }else
                 WriteLog("//6. cannot continue.."); 
         }
      //Select Continue option
          driver.findElement(By.id("button-guest")).click();
          WriteLog("//8. Proceeding to shipment details");
}

//Function to add additional details 
private void AdditionalDetails()
{
           // Add additional comments, agree to Terms and Conditions and proceed to Confirmation screen
            driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
           driver.findElement(By.name("comment")).clear();
           driver.findElement(By.name("comment")).sendKeys("Home Delivery");
           driver.findElement(By.id("button-shipping-method")).click();
           driver.findElement(By.name("agree")).click();
           driver.findElement(By.id("button-payment-method")).click();
           driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}

//Function to confirm the order
private void ConfirmOrder() throws Exception
{
      String status=null;
        //Select button Confirm Order   
          driver.findElement(By.id("button-confirm")).click();
           try{
           // Verify Confirmation screen
           String text = driver.findElement(By.xpath(".//*[@class='checkout-success']/div[2]/div/div/h1")).getText();
           //System.out.println(text);           
             if (text.equalsIgnoreCase("Your order has been placed!"))
                {
                  System.out.println("Order placed successfuly");
                  status = "Pass";
                }
             else{
                  System.out.println("Order confirmation failed.");
                  status = "Fail";
                 }        
           }
           catch(Exception e)
           {
               e.printStackTrace();  
               e.getMessage();
           }
        //Calling function to update test result in excel   
       ExcelWrite.writereport(status, 1,0);

       //Select "Continue" option to return to home screen
             WebDriverWait wait1 = new WebDriverWait(driver, 60);  
             WebElement contbtn= wait1.until(ExpectedConditions.elementToBeClickable(By.linkText("Continue")));
             if (contbtn!=null)
             contbtn.click();
             WriteLog("//8. Navigating back to home screen");
       //Close the browser
            driver.close();
}                                                

//Function to write log messages
private void WriteLog(String message) {
        System.out.println(message);
}

public static void main(String[] args) throws Exception {
     try{   
        ShoppingCart obj= new ShoppingCart();
        obj.LauchSite("http://omnichanneldemo.com/index.php?route=common/home");
        obj.CategorySelection();
        obj.AddCategoryToCart();
        obj.CartCheckout();
        obj.CustomerDetails();
        obj.AdditionalDetails();
        obj.ConfirmOrder(); 

     }catch(Exception e){
        e.printStackTrace(); 
        e.getMessage();
      }
   }              
}

ExcelWrite.java

package shop;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.*;
import org.apache.poi.ss.usermodel.*;


public class ExcelWrite {
    public static void writereport(String status, int rownum, int colnum) 
    {
        System.out.println(status);
        try {
        FileInputStream fis = new FileInputStream("C:\\E2EFramework\\Data\\Datasheet_1.xls");
        Workbook wb=WorkbookFactory.create(fis);
        Sheet S = wb.getSheet("Temp");
            Row row = S.getRow(rownum);
            //System.out.println(rownum);
            Cell cell = row.getCell(colnum, row.RETURN_BLANK_AS_NULL);
            //System.out.println(colnum);
            if(cell==null)
            {
                cell = row.createCell(colnum);
                cell.setCellValue(status);
            }else {              
                cell.setCellValue(status);               
                }

        FileOutputStream fos=new FileOutputStream("C:\\E2EFramework\\Data\\Datasheet_1.xls");
        wb.write(fos);
        fis.close();
        fos.close();
    }
    catch(IOException | InvalidFormatException e)
    {
        e.printStackTrace();
    }
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Pooja
  • 1
  • where you have put your java file and have you set class path? – Helping Hands Feb 16 '15 at 06:11
  • Add the excact error message, in which directory are your class files placed and where do you run java. – Jens Feb 16 '15 at 06:28
  • Hi, path of my java file: C:\Users\pooja.a.tripathi\Desktop\Omni my class files are getting generated in the above path Exact error message : "Could not find or load main class" when i try running my ShoppingCart.java file from the above mentioned path. I tried setting the classpath as: set CLASSPATH = "C:\Program Files\Java\jdk1.8.0_25\bin" Please let me know what's the error. Thanks, Pooja – Pooja Feb 16 '15 at 06:30
  • First of all go to CMD and type java from any drive and run it , if it run successfully then only that is confirmed that your set classpath it FINE. – Helping Hands Feb 16 '15 at 06:42
  • I have only 1 drive which is C i tried with different folders and java is getting recognised. – Pooja Feb 16 '15 at 06:47
  • possible duplicate of [Error: Could not find or load main class](http://stackoverflow.com/questions/7485670/error-could-not-find-or-load-main-class) –  Feb 16 '15 at 06:50
  • Hi RC, I tried all which is mentioned in the above thread you have provided, but it didn't helped me. Need help. – Pooja Feb 16 '15 at 06:53
  • @Pooja - you can do one thing , create JAR of your project and run it through command line like : java -jar yourjarname.jar – Helping Hands Feb 16 '15 at 07:01
  • Hi Helping Hands, Tried creating the jar file from below command : jar -cf Shopping.jar ShoppingCart(which the java file in which main method resides) Can you please tell me why is it giving me this error? It creates the jar file but same time giving me error: ShoppingCart: no such file or directory I am creating the jar file from the same location where my java files and class files exist. – Pooja Feb 16 '15 at 07:40
  • I re-tried by command: jar -cf example.jar * and it didn't throw me any error but when i tried running the jar file : java -jar example.jar its giving me error: no main manifest attribute in example.jar – Pooja Feb 16 '15 at 07:48

1 Answers1

0

Adding . to CLASSPATH variable in Environment variables solved my problem!!

Java searches for the classes in the paths mentioned in CLASSPATH variable, if you don't add . there, it won't search for classes in current working directory!!!

Go to Control panel > System and Security > System > Advanced System Settings > Advanced

Click Environment Variables

If CLASSPATH variable is present under User variables , add '.' separated by semicolon. For example if java is installed in C:\Program Files\Java\jdk1.8.0_25\bin , CLASSPATH will be

C:\Program Files\Java\jdk1.8.0_25\bin;.;

Click OK.