NullPointerException при запуске двух отдельных JVM

У меня есть основная программа, известная как Start.java, которая экспортируется как файл jar. Затем этот Jar-файл будет запущен и извлечет данные из листа Excel. Код для Start.jar следующий:

public class Start {
    public static int count;    
    public static String jar_filepath;
    public static String testability;
    public static String tc_name;
    public static String url;
    public static String test_data_filepath;
    public static String tc_result_filepath;
    public static String date_time = new SimpleDateFormat
                     ("ddMMyyyy_HHmm'.xlsx'").format(new Date());`

    public static void main(String[] args) throws IOException, Throwable{       
        //Read TestConfig.xlsx for checking which test case to be test
        FileInputStream StartInput = new 
        FileInputStream("c:\\TestAutomation\\TestConfigWithMacro.xlsm");        
        XSSFWorkbook StartInputWB = new XSSFWorkbook(StartInput);
        XSSFSheet sheet = StartInputWB.getSheet("Config");      
        for(count = 1;count<=sheet.getLastRowNum();count++){
            System.out.println(count);
            XSSFRow row = sheet.getRow(count);
            testability = row.getCell(0).toString();  
            tc_name = row.getCell(1).toString();
            jar_filepath = row.getCell(2).toString();
            url = row.getCell(3).toString();
            test_data_filepath = row.getCell(4).toString();
            tc_result_filepath = row.getCell(5).toString()+tc_name+"_"+date_time;
            System.out.println("Test Case Name : " + tc_name);          
            if(testability.equals("Y")||testability.equals("y)")){
                System.out.println("Test Case Name : " + tc_name);
                //String command = "cmd /s/k start java -jar " + jar_filepath;
                Process p = Runtime.getRuntime().exec("cmd /c start cmd /k java -jar "+jar_filepath);
                Thread.sleep(50000);    

Выполнение Start.jar вызовет файл тестового примера, известный как LoginCaptchaChrome.jar, кодировка которого приведена ниже:

public class LoginCaptchaChrome {   

    public static void main(String[] args) throws IOException,  
    InterruptedException{System.setProperty("webdriver.chrome.driver", "C:\\Users\\user1\\Desktop\\work\\chromedriver_win32\\chromedriver.exe");        
        //The following creates test result excel sheet
        //System.out.println(Start.tc_result_filepath);
        FileOutputStream fos = new FileOutputStream(Start.tc_result_filepath);
        //FileOutputStream fos = new FileOutputStream("c:\\Test Data\\write.xlsx");
        XSSFWorkbook workbook = new XSSFWorkbook();                                 
        XSSFSheet sheet1  = workbook.createSheet("TS1");
        CellStyle style = workbook.createCellStyle();       
        XSSFFont bold = workbook.createFont();
        bold.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
        style.setFont(bold);
        style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        style.setBorderRight(XSSFCellStyle.BORDER_THIN);
        style.setBorderTop(XSSFCellStyle.BORDER_THIN);        
        int a = 0;      
        Row row = sheet1.createRow(a);
        Cell TC = row.createCell(0);
        TC.setCellValue("No.");
        TC.setCellStyle(style);
        sheet1.autoSizeColumn(0);
        Cell Expected = row.createCell(1);
        Expected.setCellValue("Expected Result");
        Expected.setCellStyle(style);
        sheet1.autoSizeColumn(1);
        Cell Actual = row.createCell(2);        
        Actual.setCellValue("Actual Result");           
        Actual.setCellStyle(style);
        sheet1.autoSizeColumn(2);
        workbook.write(fos);
        fos.close();
        workbook.close();    
        credentials.getFile();  
    }

    public static void runTest(String string0, String string, String string1) throws InterruptedException, IOException{
        WebDriver login = new ChromeDriver();       
        System.out.println(login);

        login.get(Start.url);
        //login.get("https://2015.qa.int.www.mol.com/");
        login.findElement(By.xpath("//*[@id='lorem']/img")).isDisplayed();
        login.findElement(By.xpath("//*[@id='popupfoot']/a/i")).click();
        login.findElement(By.linkText("Log in")).click();    
        Thread.sleep(2000);         
        login.findElement(By.xpath("//*[@id='EmailAddress']")).sendKeys(credentials.username);
        login.findElement(By.xpath("//*[@id='Password']")).sendKeys(credentials.password);        
        Thread.sleep(2000);
        login.findElement(By.xpath("//*[@id='LoginForm']/footer[1]/table/tbody/tr/td[2]/button")).click();        
        Thread.sleep(2000); 

        if(login.getPageSource().contains("The email or password you entered is incorrect. Please try again.")){

            login.get(Start.url);
            login.quit();                   
        }
        else{
            login.findElement(By.xpath("//*[@id='myModalEligibleToIncreaseWalletLimit']/div/div/div[3]/a")).click();
            String i = login.findElement(By.xpath("//*[@id='AccountSettingsForm']/fieldset/section[2]/div/label")).getText();
            //The following populate test result
            if(i.equals("Please fill in for account security enquiries and account termination request.")){
                FileInputStream input_pass = new FileInputStream(Start.tc_result_filepath);
                XSSFWorkbook wb_pass = new XSSFWorkbook(input_pass);
                XSSFSheet sheet2 = wb_pass.getSheet("TS1");
                CellStyle style_pass = wb_pass.createCellStyle();  
                style_pass.setBorderBottom(XSSFCellStyle.BORDER_THIN);
                style_pass.setBorderLeft(XSSFCellStyle.BORDER_THIN);
                style_pass.setBorderRight(XSSFCellStyle.BORDER_THIN);
                style_pass.setBorderTop(XSSFCellStyle.BORDER_THIN);
                int b = credentials.count;          
                Row row_Pass = sheet2.createRow(b);
                Cell TC_Pass = row_Pass.createCell(0);
                TC_Pass.setCellValue(credentials.tc);
                TC_Pass.setCellStyle(style_pass);
                Cell Expected_Pass = row_Pass.createCell(1);
                Expected_Pass.setCellValue(i); 
                sheet2.autoSizeColumn(b);
                Expected_Pass.setCellStyle(style_pass);
                Cell Result = row_Pass.createCell(2);
                Result.setCellValue("PASS"); 
                Result.setCellStyle(style_pass);            
              FileOutputStream write_pass = new FileOutputStream(Start.tc_result_filepath); 
              //FileOutputStream write_pass = new FileOutputStream("c:\\Test Data\\write.xlsx");
                wb_pass.write(write_pass);
                write_pass.close();
                wb_pass.close();
            }
            else{
            FileInputStream input_fail = new FileInputStream(Start.tc_result_filepath);
            //FileInputStream input_fail = new FileInputStream("c:\\Test Data\\write.xlsx");
                XSSFWorkbook wb_fail = new XSSFWorkbook(input_fail);
                XSSFSheet sheet2 = wb_fail.getSheet("TS1");
                CellStyle style_fail = wb_fail.createCellStyle(); 
                style_fail.setBorderBottom(XSSFCellStyle.BORDER_THIN);
                style_fail.setBorderLeft(XSSFCellStyle.BORDER_THIN);
                style_fail.setBorderRight(XSSFCellStyle.BORDER_THIN);
                style_fail.setBorderTop(XSSFCellStyle.BORDER_THIN);
                int b = credentials.count;          
                Row row_Fail = sheet2.createRow(b);
                Cell TC_Fail = row_Fail.createCell(0);
                TC_Fail.setCellValue(credentials.tc);
                TC_Fail.setCellStyle(style_fail);  
                Cell Expected_Fail = row_Fail.createCell(1);
                Expected_Fail.setCellValue(i);
                sheet2.autoSizeColumn(b);
                Expected_Fail.setCellStyle(style_fail);  
                Cell Result_Fail = row_Fail.createCell(2);
                Result_Fail.setCellValue("FAIL"); 
                XSSFFont font = wb_fail.createFont();
                font.setColor(IndexedColors.RED.getIndex());
                style_fail.setFont(font);             
                Result_Fail.setCellStyle(style_fail);

            FileOutputStream write_fail = new FileOutputStream(Start.tc_result_filepath);
            //FileOutputStream write_fail = new FileOutputStream("c:\\Test Data\\write.xlsx");
                wb_fail.write(write_fail);
                write_fail.close();
                wb_fail.close();            
            }           
            login.quit();
            System.out.println("Test end");
        }
    }
}   

Когда я запускал, выполнив start.jar, окно cmd открывалось и закрывалось немедленно, несмотря на то, что я использую cmd /c start cmd /k ...., и мой код просто перестал выполняться.

Затем вместо отладки я выполняю Start.java через Eclipse. На этот раз окно cmd было открыто, но вместо этого отображается следующее

Exception in thread "main" java.lang.NullPointerException at java.io.FileOutputStream.<init>(Unknown Source) at java.io.FileOutputStream.<init>(Unknown Source) at LoginCaptchaChrome.main(LoginCaptchaChrome.java:46)

Строка 46 относится к этой строке кода: FileInputStream input_pass = new FileInputStream(Start.tc_result_filepath);

В режиме отладки Eclipse я действительно вижу, что Start.tc_result_path заполняется местоположением пути, но я не уверен, почему JVM выдает NullPointerException.


person lamCM    schedule 16.08.2016    source источник
comment
Вы запускаете совершенно другой экземпляр JVM. Они не разделяют классовое состояние.   -  person chrylis -cautiouslyoptimistic-    schedule 17.08.2016
comment
Возможно, вы неправильно поняли, как взаимодействуют процессы (JVM).   -  person Sotirios Delimanolis    schedule 17.08.2016
comment
@SotiriosDelimanolis Проблема здесь (отдельные JVM) достаточно отличается от канонического дубликата, поэтому я не думаю, что он требует закрытия.   -  person chrylis -cautiouslyoptimistic-    schedule 17.08.2016
comment
Спасибо, ребята, за отзыв. Другими словами, я не могу запустить Start.jar для вызова LoginCaptchaChrome.jar, пока запущен Start.jar? Прошу прощения, если это звучит банально, но должен признать, что я только начинаю глубоко разбираться в Java. Спасибо   -  person lamCM    schedule 17.08.2016
comment
Обновления: я попытался изменить Start.tc_result_path на абсолютный путь, то есть C: \ TestAutomation \ Result.xlsx, и он работает. Моя проблема теперь в том, почему Start.tc_path_path приводит к ошибке нулевого указателя. Еще раз спасибо.   -  person lamCM    schedule 17.08.2016