Solved

How to stop a running process in a GUI in Java?

Posted on 2013-11-10
4
373 Views
Last Modified: 2013-11-14
Hi,
I have a GUI in Java and I need to stop a process while it is running.

I tried to stop the process using the code below but it did not really stop the process instead it stopped showing the results in the GUI. When I do println I can still see that the process is running.

This is the code I have:

public class RunPerl {
    

    private static List<CheckDetail> checkDetails = null;
    final static List<CheckDetail> checkDetailsAll = new ArrayList<CheckDetail>();    
    static FileTree fileTree = new FileTree();
    
    //this is to stop all running checks
    private static List<CheckRunner> checkRunners = new ArrayList<CheckRunner>();
    
    private static Shell shell;
    private static Table table;
    private static String[] titles;
    private static Group groupResults;
    private static Display display;
    private static Composite compTB3_table_newThread;
    private static boolean exitLoop;
    //static Text txt;
    
    public static String[] getFileList(){
        String[] Filelist = null;
        
        return Filelist;
    }
    


        public static void runMwcheck(String content, Map<Integer, String> checkNameMap, Composite compTB3_table, StringBuilder failedCheckList, boolean reRun) throws IOException {
            Set<String> results = null;
            
            //String content = Gui.getFileList();          
            setcompTB3_table_newThread(compTB3_table);
            //separate the text by new line characters
            //and assign them to an array
            String fileData[] = content.split("(" + System.getProperty("line.separator") + ")+");
            
            
            //get the list of checks from the checks list in TAB2
            //Map<Integer, TreeItem> checkListMap = new HashMap<Integer, TreeItem>();
            //Map<Integer, String> checkNameMap= new HashMap<Integer, String>();
            //checkNameMap = CheckListTree.getInstance().getCheckedStandards(checkListMap, checkNameMap);
               
            String tempDir = null;
            StringBuilder checkList = new StringBuilder();
            Iterator<Entry<Integer, String>> it_checkNameMap = checkNameMap.entrySet().iterator();
            // if this is to run only the failed checks, then you should not get the check list from the checks tab.
            //It will be passed from the toolbarlistener
            if (reRun){
            	checkList = failedCheckList;
            }
            else{
            	// loop through the hashmap and create the checks list
	            while (it_checkNameMap.hasNext()) {
	                Entry<Integer, String> pairs_checkNameMap = it_checkNameMap.next();
	                checkList.append(" -guiCheck ").append(pairs_checkNameMap.getValue());
	            }
            }
            
             //loop through each line (request) in the text box
            
            String perlCmd;
            String mtcheckCmd;
            String setMwcheckPathCmd;
            String sandboxLocation = null;
            String batchFileCmd = null;
            //FutureTask<CheckRunner> task = new FutureTask(myRunner);
            //ExecutorService checkExecutor = Executors.newFixedThreadPool(5);
           ExecutorService checkExecutor = Executors.newSingleThreadExecutor();
            HashMap<String, Future> futures = new HashMap<String,Future>(fileData.length);
            //int j = 0;
            for (int j = 0; j < fileData.length; j++){
                    String fileInfoLine = fileData[j];
                    String OS = System.getProperty("os.name").toLowerCase();
                    fileInfoLine = fileInfoLine.replaceAll("\\r|\\n", "");
                    Pattern sandboxLocPattern = Pattern.compile("(?<=(-f|-d|-d -r|-c)).+?(?=(?:product))");
                    Matcher matchSandboxLoc = sandboxLocPattern.matcher(fileInfoLine);
                    if (matchSandboxLoc.find()){
                        sandboxLocation = matchSandboxLoc.group();
                        fileInfoLine = fileInfoLine.replace(sandboxLocation," ");
                        sandboxLocation = sandboxLocation.replaceAll("-f|-d|-d -r|-c", "");
                    } else{
                        sandboxLocation = "";
                    }
                    
                    if (OS.indexOf("win") >= 0){
                        tempDir = "C:/Temp/mtcheck";
                        batchFileCmd = "cmd.exe /C \\\\somepath\\bin\\mtcheckGui.bat" +" " + sandboxLocation + " " + fileInfoLine + " " + checkList ;
                    }
                    else{
                        tempDir = "/tmp/mtcheck";
                        batchFileCmd = "/somepath/bin/mtcheckGui.sh" +" " + sandboxLocation + " " + fileInfoLine + " " + checkList ;
                    }
                    perlCmd = batchFileCmd;
                    CheckRunner myRunner = new CheckRunner();
                    
                    //this is to stop all running checks
                    checkRunners.add(myRunner);
                    
                    myRunner.setCommand(perlCmd);
                    futures.put(fileInfoLine, checkExecutor.submit(myRunner));       
                }
            
            
            exitLoop = false;
            boolean newRun = true;
            boolean evenRow = true;
            
            // String fileName = null;
            while(true && exitLoop == false) {
                
            HashMap<String, Future> tempFutures = futures;   
            ArrayList<String> keyList = new ArrayList<String>();
            
            for (Entry<String, Future> entry  : tempFutures.entrySet()) {
            	//This is to stop the process
            	if (exitLoop) break;
                Future<List<CheckDetail>> f = entry.getValue();
                    try {
                        checkDetails = f.get(1, TimeUnit.MILLISECONDS);
                        
                        if (checkDetails != null) {
                            keyList.add(entry.getKey());
                            checkDetailsAll.addAll(checkDetails); 
                            evenRow = Gui.populateResultsTable(checkDetails,shell,table,titles, newRun, evenRow, groupResults);
                            newRun = false;                            
                        }
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (TimeoutException e) {
                       ;
                    }
            }    

            if (!futures.isEmpty()){             
                for (String key : keyList) {
                    futures.remove(key);
                }                        
            }
            
            if (futures.isEmpty())
               exitLoop = true;
            }

            checkExecutor.shutdown();
            
            //This is to set the initial set of data in the table to save the relevant information to a xml file.
            CSFilteringCheckBoxes.setTableDataInitialData();
                       
            //return checkDetailsAll;
        }
        
        public void setTable(Table table, String[] titles) {
            RunPerl.table = table;
            RunPerl.titles = titles;
        }  
        
        
        public void setShell(Shell shell, Display display) {
            RunPerl.shell = shell; 
            RunPerl.display = display;
        }
        
        public void setGroupResults(Group groupResults) {
            RunPerl.groupResults = groupResults; 
        }
        
        public static void setcompTB3_table_newThread(Composite combTB3){
            compTB3_table_newThread = combTB3;
        }
        
        public Composite getcompTB3_table_newThread(){
            return compTB3_table_newThread;
        }
        
        
        public static void saveResults(String file) throws ParserConfigurationException, IOException, ClassNotFoundException{
            DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            //get current date time with Date()
            Date date = new Date();

            
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.newDocument();
         
            Element rootElement = doc.createElement("Results");
            doc.appendChild(rootElement);
            
            Element dateElement = doc.createElement("Date");
            rootElement.appendChild(dateElement);
            dateElement.setTextContent(dateFormat.format(date));
            //List<CheckDetail> checkDetailsTable = Gui.getTableData();
            List<CheckDetail> checkDetailsTableAll = CSFilteringCheckBoxes.getTableData();
            
            for (CheckDetail checkDetail : checkDetailsTableAll) {
                Element detailElement = doc.createElement("Detail");
                rootElement.appendChild(detailElement);

                Element nameElement = doc.createElement("name");
                detailElement.appendChild(nameElement);
                nameElement.setTextContent(checkDetail.getFileName());

                Element checkElement = doc.createElement("check");
                detailElement.appendChild(checkElement);
                checkElement.setTextContent(checkDetail.getName());

                Element statusElement = doc.createElement("status");
                detailElement.appendChild(statusElement);
                statusElement.setTextContent(checkDetail.getStatus());

                Element existingLineNumbersElement= doc.createElement("existingLineNumbers");
                detailElement.appendChild(existingLineNumbersElement);
                existingLineNumbersElement.setTextContent(checkDetail.getExistingLineNumbers());

                Element newLineNumbersElement= doc.createElement("newLineNumbers");
                detailElement.appendChild(newLineNumbersElement);
                newLineNumbersElement.setTextContent(checkDetail.getNewLineNumbers());

            }


            Transformer transformer = null;
            try {
                transformer = TransformerFactory.newInstance().newTransformer();
            } catch (TransformerConfigurationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (TransformerFactoryConfigurationError e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    
   
            // This is to serialize to a File
            FileWriter fileWriter = null;
            try {
                fileWriter = new FileWriter(file);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                transformer.transform(new DOMSource(doc), new StreamResult(fileWriter));
            } catch (TransformerException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            try {
                fileWriter.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
        
        //this is to stop all running checks
        public static void stopAllRunners() {
            for (CheckRunner runner : checkRunners) {
                if (runner != null) {
                	exitLoop = true;
                	runner.stop();
                }
            }
        }
        
        public static List<CheckDetail> getCheckResults(){       	
        	return  checkDetailsAll;
        }
}

Open in new window




This is the CheckRunner.java class:

public class CheckRunner implements Callable<List<CheckDetail>> {
    protected String resultsXML;
    protected String execCmd;
    static List<CheckDetail> checkDetails = null;
    final static List<CheckDetail> checkDetailsAll = new ArrayList<CheckDetail>();
    static Process mtcheck_process = null;
    
   public void setCommand(String perlCmd)
   {
       execCmd = perlCmd;
   }
   
   public List<CheckDetail> call() {
      
     //get the environment variables
       Map<String, String> env = System.getenv();
       String [] environment = new String[env.size()];
       int i = 0;
       for (Map.Entry<String, String> entry : env.entrySet())
       {
           environment[i] = entry.getKey() + "=" + entry.getValue();
           i++;
       }
       
       Runtime mtcheck_runtime = Runtime.getRuntime();
       
       
       try {
           mtcheck_process = mtcheck_runtime.exec(execCmd);
           mtcheck_process.waitFor();
       } catch (Exception e) {
    	 //DEBUG:: System.out.println("error executing " + execCmd);
       }
       

       /* dump output stream */
       InputStream is = mtcheck_process.getInputStream();
       BufferedReader reader = new BufferedReader
           ( new InputStreamReader(is));
       String commandLineOutput;
       
       try {
        while ((commandLineOutput = reader.readLine()) != null) {
               Pattern p = Pattern.compile("\\d{8}_\\d{4}_\\d{2}_.*?_Mwcheck_CodingStandards_ALL_Files.xml");
               Matcher m = p.matcher(commandLineOutput);
               if (m.find()){
                   resultsXML = m.group();                       
               }
             //DEBUG:: System.out.println(commandLineOutput);
               //Log command line output to the log file
               try {
            	   DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            	   Date date = new Date();
            	   //System.out.println(dateFormat.format(date));
            	   //This will append the command line out put to the log file
                   BufferedWriter out = new BufferedWriter(new FileWriter("//somepath//mtcheck/" + dateFormat.format(date) + "_UserData.txt", true));                   
                   out.write("\tCommand Line Output: " + commandLineOutput + "\r\n");
                   out.close();
               } catch (IOException e) {
               	//DEBUG:: System.out.println("writeToFile problem:");
                   e.printStackTrace();
               }
           }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
       System.out.flush(); 
       /* print final result of process */
     //DEBUG:: System.err.println("Exit status=" + mtcheck_process.exitValue());
       
       String tempDir = null;
       String OS = System.getProperty("os.name").toLowerCase();
       
       if (OS.indexOf("win") >= 0){
           tempDir = "C:/Temp/mtcheck";
       } else{
           tempDir = "/tmp/mtcheck";
       }
       
       //get the name of the  generated XML from the CLI 
       //and parse it to generate the results table
       String path2ResultsXML = tempDir + "/" + resultsXML;
          
       //TO DO: check if this file exists
       
       new ParseResultsXML().parse(path2ResultsXML);
       //checkDetails = new ParseResultsXML().getResultsXMLData();
       checkDetails = new ParseResultsXML().parse(path2ResultsXML);
       checkDetailsAll.addAll(checkDetails);  
             
       for(Iterator<CheckDetail> j = checkDetailsAll.iterator();j.hasNext();) {
           CheckDetail checkDetail = j.next();
           String fileName = checkDetail.getFileName();
           fileName = fileName.replace('/', '\\');
           checkDetail.setFileName(fileName);
       }
       
    //return checkDetailsAll;
       return checkDetails;
}

    public static List<CheckDetail> getList(){
        return checkDetailsAll;
    }
    
    public static void cleanList(){
        checkDetailsAll.removeAll(checkDetailsAll);
    }
    
    public void stop() {
        if (mtcheck_process != null) {
            mtcheck_process.destroy();
        }
    }
}

Open in new window


stopAllRunners() is invoked by a listener when you click on a button. Then this is supposed to stop the runners but it does not stop it. Instead, since the exitloop is becomes true, the populateResultsTable method is not called.

But this is not enough for me, because if I start the process again then everything masses up due to already running process..

Can you please me help to stop this running process?

Thanks,
0
Comment
Question by:Tolgar
  • 2
4 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 39638486
As i've mentioned elsewhere before, the ultimate sanction is Process.destroy. I note that the Process class doesn't appear anywhere in the code you posted
0
 
LVL 35

Accepted Solution

by:
mccarl earned 500 total points
ID: 39638511
Tolgar,

In our last attempt at this I thought that I couldn't fully help because I don't have your full environment on my side to play with and get working. However, I should have asked you to post the full code again, and I would have noticed this.... You didn't do everything that I suggested in that previous question (the first bullet point).

Look at line 6 of CheckRunner.java, you STILL have your Process object declared as static.
0
 

Author Comment

by:Tolgar
ID: 39644688
I think it works now. I am closing this thread for now :)
0
 
LVL 35

Expert Comment

by:mccarl
ID: 39647340
Glad you got it going! :)
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Suggested Solutions

A short article about a problem I had getting the GPS LocationListener working.
A short article about problems I had with the new location API and permissions in Marshmallow
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now