1 /*
   2  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 package test.java.awt.regtesthelpers.process;
  25 
  26 import java.io.*;
  27 
  28 /** This class is created to solve interprocess communication problems.
  29  *  When you need to write a regression test which should verify inter jvm
  30  *  behavior such as DnD data transfer, Clipboard data transfer, focus
  31  *  transfer etc., you could use the next scenario:
  32  *
  33  *  1. Write an implementation for the parent JVM, using applet test.
  34  *  2. Write an implimentation for the child JVM or native application, using
  35  *     main() function.
  36  *  3. Execute child process using  ProcessCommunicator.executeChildProcess()
  37  *     method.
  38  *  4. You can decide whetherthe test is passed on the basis of
  39  *     ProcessResults class data.
  40  *
  41  *  Note: The class is not thread safe. You should access its methods only from the same
  42  *        thread.
  43  */
  44 
  45 public class ProcessCommunicator {
  46 
  47     private static final String javaHome = System.getProperty("java.home", "");
  48     private static final String javaPath = javaHome + File.separator + "bin" +
  49             File.separator + "java ";
  50     private static String command = "";
  51 
  52     private ProcessCommunicator() {}
  53 
  54     /** The same as {#link #executeChildProcess(Class,String)} except
  55      *  the {@code classPathArgument} parameter. The class path
  56      *  parameter is for the debug purposes
  57      *
  58      *  @param classToExecute is passed to the child JVM
  59      *  @param classPathArguments class path for the child JVM
  60      *  @param args arguments that will be passed to the executed class
  61      *  @return results of the executed {@code Process}
  62      */
  63     public static ProcessResults executeChildProcess(final Class classToExecute,
  64                            final String classPathArguments, final String [] args)
  65     {
  66         try {
  67             String command = buildCommand(classToExecute, classPathArguments, args);
  68             Process process = Runtime.getRuntime().exec(command);
  69             return doWaitFor(process);
  70         } catch (IOException e) {
  71             throw new RuntimeException(e);
  72         }
  73     }
  74 
  75     /** Executes child {code Process}
  76      *
  77      * @param classToExecute class to be executed as a child java process
  78      * @param args args to be passed in to the child process
  79      * @return results of the executed {@code Process}
  80      */
  81     public static ProcessResults executeChildProcess(final Class classToExecute,
  82                            final String [] args)
  83     {
  84         return executeChildProcess(classToExecute, System.getProperty("java.class.path"), args);
  85     }
  86 
  87     /**
  88      * Waits for a process and return its results.
  89      * This is a workaround for <code>Process.waitFor()</code> never returning.
  90      *
  91      * @return results of the executed {@code Process}
  92      */
  93     private static ProcessResults doWaitFor(final Process p) {
  94         ProcessResults pres = new ProcessResults();
  95 
  96         final InputStream in;
  97         final InputStream err;
  98 
  99         try {
 100             in = p.getInputStream();
 101             err = p.getErrorStream();
 102 
 103             boolean finished = false;
 104 
 105             while (!finished) {
 106                 try {
 107                     while (in.available() > 0) {
 108                         pres.appendToStdOut((char)in.read());
 109                     }
 110                     while (err.available() > 0) {
 111                         pres.appendToStdErr((char)err.read());
 112                     }
 113                     // Ask the process for its exitValue. If the process
 114                     // is not finished, an IllegalThreadStateException
 115                     // is thrown. If it is finished, we fall through and
 116                     // the variable finished is set to true.
 117                     pres.setExitValue(p.exitValue());
 118                     finished  = true;
 119                 }
 120                 catch (IllegalThreadStateException e) {
 121                     // Process is not finished yet;
 122                     // Sleep a little to save on CPU cycles
 123                     Thread.currentThread().sleep(500);
 124                 }
 125             }
 126             if (in != null) in.close();
 127             if (err != null) err.close();
 128         }
 129         catch (Throwable e) {
 130             System.err.println("doWaitFor(): unexpected exception");
 131             e.printStackTrace();
 132         }
 133         return pres;
 134     }
 135 
 136     /** Builds command on the basis of the passed class name,
 137      *  class path and arguments.
 138      *
 139      * @param classToExecute with class will be executed in the new JVM
 140      * @param classPathArguments java class path (only for test purposes)
 141      * @param args arguments for the new application. This could be used
 142      *             to pass some information from the parnent to child JVM.
 143      * @return command to execute the {@code Process}
 144      */
 145     private static String buildCommand(final Class classToExecute,
 146                          final String classPathArguments, final String [] args)
 147     {
 148         StringBuilder commandBuilder = new StringBuilder();
 149         commandBuilder.append(javaPath).append(" ");
 150         commandBuilder.append("-cp ").append(System.getProperty("test.classes", ".")).append(File.pathSeparatorChar);
 151 
 152         if (classPathArguments.trim().length() > 0) {
 153             commandBuilder.append(classPathArguments).append(" ");
 154         }
 155 
 156         commandBuilder.append(" ");
 157         commandBuilder.append(classToExecute.getName());
 158         for (String argument:args) {
 159             commandBuilder.append(" ").append(argument);
 160         }
 161         command = commandBuilder.toString();
 162         return command;
 163     }
 164 
 165     /** Could be used for the debug purposes.
 166      *
 167       * @return command that was build to execute the child process
 168      */
 169     public static String getExecutionCommand () {
 170         return command;
 171     }
 172 }