1 /*
   2  * Copyright (c) 1998, 1999, 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 /* @test
  25  * @bug 4109103
  26  * @summary rmid should annotate child process output
  27  *
  28  * @author Laird Dornin; code borrowed from Ann Wollrath
  29  *
  30  * @library ../../../testlibrary
  31  * @build TestLibrary RMID MyRMI CheckAnnotations_Stub
  32  * @run main/othervm/policy=security.policy/timeout=480 CheckAnnotations
  33  */
  34 
  35 import java.io.*;
  36 import java.rmi.*;
  37 import java.rmi.activation.*;
  38 import java.util.Properties;
  39 import java.util.StringTokenizer;
  40 import java.util.concurrent.TimeUnit;
  41 import java.util.concurrent.locks.Condition;
  42 import java.util.concurrent.locks.Lock;
  43 import java.util.concurrent.locks.ReentrantLock;
  44 
  45 
  46 public class CheckAnnotations
  47     extends Activatable implements MyRMI, Runnable
  48 {
  49     private static MyRMI myRMI = null;
  50     static class NotifyOutputStream extends ByteArrayOutputStream {
  51         final Lock lock;
  52         final Condition signal;
  53         
  54         NotifyOutputStream(Lock lock, Condition signal) {
  55             this.lock = lock;
  56             this.signal = signal;
  57         }
  58 
  59         @Override
  60         public synchronized void write(int b) {
  61             lock.lock();
  62             try{
  63                 super.write(b);
  64                 signal.signal();
  65             } finally {
  66                 lock.unlock();
  67             }
  68         }
  69         
  70         @Override
  71         public synchronized void write(byte b[], int off, int len) {
  72             lock.lock();
  73             try{
  74                 super.write(b, off, len);
  75                 if (len != 0)
  76                     signal.signal();
  77             } finally {
  78                 lock.unlock();
  79             }
  80         }
  81     }
  82 
  83     // buffers to store rmid output.
  84     private static final Lock lock = new ReentrantLock();
  85     private static final Condition writeOutSig = lock.newCondition();
  86     private static final Condition writeErrSig = lock.newCondition();
  87     private static final NotifyOutputStream rmidOut = new NotifyOutputStream(lock, writeOutSig);
  88     private static final NotifyOutputStream rmidErr = new NotifyOutputStream(lock, writeErrSig);
  89 
  90     public static void main(String args[]) {
  91         RMID rmid = null;
  92 
  93         System.err.println("\nRegression test for bug/rfe 4109103\n");
  94 
  95         try {
  96 
  97             // Set security manager according to the
  98             // testlibrary.
  99             TestLibrary.suggestSecurityManager(TestParams.defaultSecurityManager);
 100 
 101             // start an rmid.
 102             RMID.removeLog();
 103             rmid = RMID.createRMID(rmidOut, rmidErr, false);
 104             rmid.start();
 105 
 106             /* Cause activation groups to have a security policy that will
 107              * allow security managers to be downloaded and installed
 108              */
 109             Properties p = new Properties();
 110             // this test must always set policies/managers in its
 111             // activation groups
 112             p.put("java.security.policy",
 113                   TestParams.defaultGroupPolicy);
 114             p.put("java.security.manager",
 115                   TestParams.defaultSecurityManager);
 116 
 117             /* new desc - we will reuse in order to get multiple vms.*/
 118             System.err.println("Create activation group in this VM");
 119             ActivationGroupDesc groupDesc =
 120                 new ActivationGroupDesc(p, null);
 121             ActivationSystem system = ActivationGroup.getSystem();
 122             ActivationGroupID groupID = system.registerGroup(groupDesc);
 123             ActivationGroup.createGroup(groupID, groupDesc, 0);
 124 
 125             ActivationDesc desc = new ActivationDesc
 126                 ("CheckAnnotations", null, null);
 127             myRMI = (MyRMI) Activatable.register(desc);
 128             /* The test-
 129              * Loop a bunch of times to force activator to
 130              * spawn VMs (groups)
 131              */
 132             for (int i = 0; i < 3; i++) {
 133 
 134                 // object activated in annotation check via method call
 135                 if(!checkAnnotations(i-1)) {
 136                     TestLibrary.bomb("Test failed: output improperly annotated.");
 137                 }
 138                 /*
 139                  * Clean up object too.
 140                  */
 141                 System.err.println
 142                     ("Deactivate object via method call");
 143                 myRMI.shutdown();
 144             }
 145             System.err.println
 146                 ("\nsuccess: CheckAnnotations test passed ");
 147 
 148         } catch (Exception e) {
 149             TestLibrary.bomb("\nfailure: unexpected exception ", e);
 150         } finally {
 151             try {
 152                 Thread.sleep(4000);
 153             } catch (InterruptedException ignore) {
 154             }
 155             myRMI = null;
 156             System.err.println("rmid shut down");
 157             ActivationLibrary.rmidCleanup(rmid);
 158         }
 159     }
 160 
 161     /**
 162      * check to make sure that the output from a spawned vm is
 163      * formatted/annotated properly.
 164      * @param iteration
 165      * @return 
 166      * @throws java.io.IOException 
 167      * @throws java.lang.InterruptedException 
 168      */
 169     public static boolean checkAnnotations(int iteration)
 170         throws IOException, InterruptedException
 171     {
 172         try {
 173             Thread.sleep(1000);
 174         } catch(InterruptedException e) {
 175             System.err.println(e.getMessage());
 176         }
 177         /**
 178          * cause the spawned vm to generate output that will
 179          * be checked for proper annotation.  printOut is
 180          * actually being called on an activated implementation.
 181          */
 182         myRMI.printOut("out" + iteration);
 183         myRMI.printErr("err" + iteration);
 184         myRMI.printOut("out" + iteration);
 185         myRMI.printErr("err" + iteration);
 186 
 187         /* we have to wait for output to filter down
 188          * from children so we can read it before we
 189          * kill rmid.
 190          */
 191 
 192         String outString, errString;
 193         
 194         class WaitThread extends Thread{
 195             final Lock lock;
 196             final Condition signal;
 197             final long timeout;
 198             WaitThread(Lock lock, Condition signal, long timeout) {
 199                 this.lock = lock;
 200                 this.signal = signal;
 201                 this.timeout = timeout;
 202             }
 203 
 204             @Override
 205             public void run(){
 206                 long goTime = timeout;
 207                 lock.lock();
 208                 try{
 209                     while(goTime > 0L) {
 210                         long start = System.currentTimeMillis();
 211                         try {
 212                             if(signal.await(goTime, TimeUnit.MILLISECONDS)) {
 213                                 break;
 214                             }
 215                         } catch (InterruptedException e) {
 216                             throw new RuntimeException("Signal interrupt unexpected:" + e);
 217                         }
 218                         goTime =  timeout - System.currentTimeMillis() + start;
 219                     }
 220                 } finally {
 221                     lock.unlock();
 222                 }
 223             }
 224         }
 225         outString = rmidOut.toString();
 226         errString = rmidErr.toString();
 227         if ((!"".equals(outString)) && (!"".equals(errString))) {
 228             System.err.println("obtained annotations");
 229         } else { 
 230             WaitThread waitOutT = new WaitThread(lock, writeOutSig, 10000);
 231             WaitThread waitErrT = new WaitThread(lock, writeErrSig, 10000);
 232             waitOutT.start();
 233             waitErrT.start();
 234             waitOutT.join();
 235             waitErrT.join();
 236             outString = rmidOut.toString();
 237             errString = rmidErr.toString();
 238             if ((!"".equals(outString)) && (!"".equals(errString))) {
 239                 System.err.println("obtained annotations");
 240             }
 241         }
 242 
 243         rmidOut.reset();
 244         rmidErr.reset();
 245         // only test when we are annotating..., first run does not annotate
 246         if (iteration >= 0) {
 247             System.err.println("Checking annotations...");
 248             System.err.println(outString);
 249             System.err.println(errString);
 250 
 251             StringTokenizer stOut = new StringTokenizer(outString, ":");
 252             StringTokenizer stErr = new StringTokenizer(errString, ":");
 253 
 254             String execErr = null;
 255             String execOut = null;
 256             String destOut = null;
 257             String destErr = null;
 258             String outTmp  = null;
 259             String errTmp  = null;
 260 
 261             while (stOut.hasMoreTokens()) {
 262                 execOut = outTmp;
 263                 outTmp  = destOut;
 264                 destOut = stOut.nextToken();
 265             }
 266             while (stErr.hasMoreTokens()) {
 267                 execErr = errTmp;
 268                 errTmp  = destErr;
 269                 destErr = stErr.nextToken();
 270             }
 271 
 272             if ((execErr == null)||(errTmp == null)||
 273                 (destErr == null)) {
 274                 return false;
 275             }
 276             if ((execOut == null)||(outTmp == null)||
 277                 (destOut == null)) {
 278                 return false;
 279             }
 280             // just make sure that last two strings are what we expect.
 281             if (execOut.equals("ExecGroup-" + iteration)
 282                 && (new String(destOut.substring(0,4)).equals("out" +
 283                                                               iteration))
 284                 && (execErr.equals("ExecGroup-"+iteration))
 285                 && (new String(destErr.substring(0,4)).equals("err" +
 286                                                               iteration)) ) {
 287                 return true;
 288             } else {
 289                 return false;
 290             }
 291         }
 292         return true;
 293     }
 294 
 295     // implementation of MyRMI, make this object activatable.
 296     public CheckAnnotations
 297         (ActivationID id, MarshalledObject mo)
 298      throws RemoteException {
 299 
 300         // register/export anonymously
 301         super(id,0);
 302     }
 303 
 304     @Override
 305     public void printOut(String toPrint) {
 306         System.out.println(toPrint);
 307     }
 308 
 309     @Override
 310     public void printErr(String toPrint) {
 311         System.err.println(toPrint);
 312     }
 313 
 314     /**
 315      * Spawns a thread to deactivate the object.
 316      * @throws java.lang.Exception
 317      */
 318     @Override
 319     public void shutdown() throws Exception {
 320         (new Thread(this,"CheckAnnotations")).start();
 321     }
 322 
 323     /**
 324      * Thread to deactivate object. First attempts to make object
 325      * inactive (via the inactive method).  If that fails (the
 326      * object may still have pending/executing calls), then
 327      * unexport the object forcibly.
 328      */
 329     @Override
 330     public void run() {
 331         ActivationLibrary.deactivate(this, getID());
 332     }
 333 }