GrxProcessManager.java
Go to the documentation of this file.
00001 /*
00002  * Copyright (c) 2008, AIST, the University of Tokyo and General Robotix Inc.
00003  * All rights reserved. This program is made available under the terms of the
00004  * Eclipse Public License v1.0 which accompanies this distribution, and is
00005  * available at http://www.eclipse.org/legal/epl-v10.html
00006  * Contributors:
00007  * General Robotix Inc.
00008  * National Institute of Advanced Industrial Science and Technology (AIST) 
00009  */
00010 /*
00011  *  GrxProcessManager.java
00012  *
00013  *  Copyright (C) 2007 GeneralRobotix, Inc.
00014  *  All Rights Reserved
00015  *
00016  *  @author Yuichiro Kawasumi (General Robotix, Inc.)
00017  *  2004/03/16
00018  */
00019 
00020 package com.generalrobotix.ui.util;
00021 
00022 import java.io.BufferedReader;
00023 import java.io.File;
00024 import java.io.IOException;
00025 import java.io.InputStream;
00026 import java.io.InputStreamReader;
00027 import java.io.PrintStream;
00028 import java.util.ArrayList;
00029 import java.util.List;
00030 import java.util.Map;
00031 import java.util.Set;
00032 import java.util.concurrent.ConcurrentLinkedQueue;
00033 
00034 import jp.go.aist.hrp.simulator.ServerObject;
00035 import jp.go.aist.hrp.simulator.ServerObjectHelper;
00036 
00037 import org.eclipse.swt.widgets.Display;
00038 import org.eclipse.core.runtime.IProgressMonitor;
00039 
00040 import com.generalrobotix.ui.GrxBaseItem;
00041 import com.generalrobotix.ui.GrxPluginManager;
00042 import com.generalrobotix.ui.grxui.Activator;
00043 import com.generalrobotix.ui.util.SynchronizedAccessor;
00044 import com.generalrobotix.ui.util.GrxXmlUtil;
00045 import com.generalrobotix.ui.util.GrxServerManager;
00046 import com.generalrobotix.ui.util.FileUtil;
00047 
00048 @SuppressWarnings("serial")
00049 public class GrxProcessManager extends GrxBaseItem{
00050     private static GrxProcessManager      GrxProcessManagerThis_            = null;
00051     
00052     private java.util.List<AProcess>      process_         = null;
00053     private boolean                       isEnd_           = false;
00054     private SynchronizedAccessor<Boolean> isType_          = new SynchronizedAccessor<Boolean>(true);
00055     private StringBuffer                  outputBuffer_    = null;
00056     private ConcurrentLinkedQueue<String> lineQueue        = null;
00057     private Thread                        thread_          = null;
00058     private ProcessInfo                                    nameServerInfo_  = null;
00059     private GrxServerManager                       serverManager_   = null;
00060 
00061     public GrxProcessManager(String name, GrxPluginManager manager) {
00062                 super(name, manager);
00063         process_ = new java.util.ArrayList<AProcess>();
00064         outputBuffer_ = new StringBuffer();
00065         lineQueue = new ConcurrentLinkedQueue<String>();
00066         GrxProcessManagerThis_ = this;
00067         createThread();
00068     }
00069 
00070     public static synchronized void shutDown() {
00071         if (GrxProcessManagerThis_ != null) {
00072             GrxProcessManagerThis_.autoStop();
00073             GrxProcessManagerThis_.stopThread();
00074             GrxProcessManagerThis_.process_.clear();
00075             GrxProcessManagerThis_.lineQueue.clear();
00076             GrxProcessManagerThis_ = null;
00077         }
00078     }
00079 
00080     public void setProcessList(GrxServerManager serverManager) {
00081         serverManager_ = serverManager;
00082         IProgressMonitor monitor = null;
00083         setProcessList(monitor);
00084     }
00085 
00086     private void setProcessList(IProgressMonitor monitor){
00087         StringBuffer nsHost = new StringBuffer(""); //$NON-NLS-1$
00088         StringBuffer nsPort = new StringBuffer(""); //$NON-NLS-1$
00089         Activator.refNSHostPort(nsHost, nsPort);
00090         String nsOpt = " -ORBInitRef NameService=corbaloc:iiop:" + nsHost + ":" + nsPort + "/NameService"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
00091         if(!GrxCorbaUtil.isAliveNameService()){
00092             nameServerInfo_ = serverManager_.getNameServerInfo();
00093             FileUtil.deleteNameServerLog(serverManager_.getNameserverLogDir());
00094             if ( isRegistered(nameServerInfo_) ) {
00095                 if( !isRunning(nameServerInfo_) ){
00096                     unregister(nameServerInfo_.id);
00097                     register(nameServerInfo_);
00098                 }
00099             } else {
00100                 register(nameServerInfo_);
00101             }
00102         }
00103         for(ProcessInfo pi : serverManager_.getServerInfo()){
00104             ProcessInfo localPi = pi.clone();
00105             for(int i=0; i<localPi.com.size(); i++){
00106                 if (localPi.useORB) {
00107                     localPi.com.set(i, localPi.com.get(i) + " " + nsOpt);
00108                 } else {
00109                     localPi.com.set(i, localPi.com.get(i));
00110                 }      
00111             }    
00112             if ( isRegistered(localPi) ) {
00113                 if( !isRunning(localPi) ){
00114                     unregister(localPi.id);
00115                     register(localPi);
00116                 }
00117             } else {
00118                 register(localPi);
00119             }
00120         }
00121         autoStart(monitor);
00122     }
00123     
00124     public boolean isRunning(ProcessInfo pi) {
00125         AProcess localProcess = get(pi.id);
00126         if (localProcess != null) {
00127             return localProcess.isRunning();
00128         }
00129         return false;
00130     }
00131 
00132     public boolean isRegistered(ProcessInfo pi) {
00133         if ( get(pi.id) != null) {
00134             return true;
00135         }
00136         return false;
00137     }
00138 
00139     
00140     public boolean register(ProcessInfo pi) {
00141         if (get(pi.id) != null) {
00142             return false;
00143         }
00144         pi=pi.expandEnv();
00145         process_.add(new AProcess(pi));
00146         pi.print();
00147         return true;
00148     }
00149 
00150     public boolean unregister(String id) {
00151         AProcess p = get(id);
00152         if (p == null) {
00153             GrxDebugUtil.println("can't find '" + id + "' on processManager."); //$NON-NLS-1$ //$NON-NLS-2$
00154             return false;
00155         }
00156         if (p.isRunning()) {
00157             GrxDebugUtil.println(id + " is running."); //$NON-NLS-1$
00158             return false;
00159         }
00160         if (process_.remove(p)) {
00161             GrxDebugUtil.println(id + " is unregistered."); //$NON-NLS-1$
00162             return true;
00163         }
00164 
00165         return false;
00166     };
00167 
00168     public void clearList() {
00169         process_.clear();
00170     }
00171 
00172     public AProcess get(String name) {
00173         for (int i = 0; i < process_.size(); i++) {
00174             if (get(i).pi_.id.equals(name)) {
00175                 return get(i);
00176             }
00177         }
00178         return null;
00179     }
00180 
00181     public AProcess get(int n) {
00182         if (0 <= n && n < process_.size()) {
00183             return process_.get(n);
00184         }
00185         return null;
00186     }
00187 
00188     public int size() {
00189         return process_.size();
00190     }
00191 
00192     public void autoStart(IProgressMonitor monitor) {
00193         for (int i = 0; i < process_.size(); i++) {
00194             AProcess p = get(i);
00195             if (p.pi_.autoStart) {
00196                 try {
00197                     (p.getReference())._non_existent();
00198                 } catch (Exception e) {
00199                     p.start(null);
00200                 }
00201             }
00202             if(monitor != null){
00203                 monitor.worked(1);
00204             }
00205         }
00206     }
00207 
00208     public void autoStop() {
00209         for (int i = process_.size(); i > 0; i--) {
00210             AProcess p = get(i - 1);
00211             if (p.pi_.autoStop) {
00212                 p.stop();
00213             }
00214         }
00215     }
00216 
00217     private void killall(String pname) {
00218         try {
00219             if (!System.getProperty("os.name").equals("Linux")) { //$NON-NLS-1$ //$NON-NLS-2$
00220                 return;
00221             }
00222             ProcessInfo pi = new ProcessInfo();
00223             pi.id = "killall"; //$NON-NLS-1$
00224             pi.com.add("/usr/bin/killall"); //$NON-NLS-1$
00225             pi.dir = "/usr/bin/"; //$NON-NLS-1$
00226             pi.autoStart = false;
00227             pi.autoStop = true;
00228             pi.waitCount = 0;
00229             register(pi);
00230             GrxDebugUtil.println("\nkillall " + pname + ":"); //$NON-NLS-1$ //$NON-NLS-2$
00231             AProcess p = get(pi.id);
00232             p.start(pname);
00233             p.waitFor();
00234             GrxDebugUtil.println(p.readBuffer());
00235             p.clearBuffer();
00236             // p.stop();
00237         } catch (Exception e) {
00238             GrxDebugUtil.printErr("killall:", e); //$NON-NLS-1$
00239         }
00240     }
00241 
00242     private String psaxGrep(String str) {
00243         try {
00244             if (!System.getProperty("os.name").equals("Linux")) { //$NON-NLS-1$ //$NON-NLS-2$
00245                 return null;
00246             }
00247             ProcessInfo pi = new ProcessInfo();
00248             pi.id = "psaxGrep"; //$NON-NLS-1$
00249             pi.com.add("/bin/ps ax"); //$NON-NLS-1$
00250             pi.dir = "/bin/"; //$NON-NLS-1$
00251             pi.autoStart = false;
00252             pi.autoStop = true;
00253             pi.waitCount = 0;
00254             register(pi);
00255             GrxDebugUtil.println("\nps ax:"); //$NON-NLS-1$
00256             AProcess p = get(pi.id);
00257             p.clearBuffer();
00258             p.start(null);
00259             p.waitFor();
00260             // p.stop();
00261             String ret = p.readBuffer();
00262             GrxDebugUtil.println(ret);
00263             String[] rets = ret.split("\n"); //$NON-NLS-1$
00264             ret = ""; //$NON-NLS-1$
00265             for (int i = 0; i < rets.length; i++) {
00266                 if (rets[i].indexOf(str + " ") != -1) { //$NON-NLS-1$
00267                     ret += rets[i] + "\n"; //$NON-NLS-1$
00268                 }
00269             }
00270             return ret;
00271         } catch (Exception e) {
00272             GrxDebugUtil.printErr("psaxGrep:", e); //$NON-NLS-1$
00273         }
00274         return null;
00275     }
00276     
00277     public  List<Integer> getPID(String processName){
00278         int splitNum = 1;
00279         List<Integer> ret = new ArrayList<Integer>();
00280         String []commands={"tasklist","/NH"}; //$NON-NLS-1$
00281         String key = new String(processName + ".exe"); //$NON-NLS-1$
00282         Runtime r = Runtime.getRuntime();
00283         if (System.getProperty("os.name").equals("Linux") ||    //$NON-NLS-1$
00284             System.getProperty("os.name").equals("Mac OS X")) { //$NON-NLS-1$
00285             commands[0] = new String ("/bin/ps"); //$NON-NLS-1$
00286             commands[1] = new String ("axh"); //$NON-NLS-1$
00287             key = new String("/" + processName);
00288             splitNum = 0;
00289         }
00290         
00291         try{
00292             Process p = r.exec(commands);
00293             p.waitFor();
00294             InputStream in = p.getInputStream(); 
00295             p.getOutputStream().toString();
00296             BufferedReader br = new BufferedReader(new InputStreamReader(in));
00297             String line;
00298             while ((line = br.readLine()) != null) {
00299                 if( line.indexOf(key) >= 0){
00300                     line = line.replaceAll("^[\\s]+", "");
00301                     String[] splitLine = line.split("[\\s]+");
00302                     if( splitLine.length > splitNum ){
00303                         try {
00304                             Integer pid = Integer.valueOf(splitLine[splitNum]);
00305                             if(pid > 0 ){
00306                                 ret.add(pid);
00307                             }
00308                         } catch (NumberFormatException ex){
00309                             ex.printStackTrace();
00310                         }
00311                     }       
00312                 }
00313             }
00314         } catch (Exception e) {
00315             e.printStackTrace();
00316         }
00317         return ret;
00318     }
00319 
00320     public void restart(IProgressMonitor monitor){
00321         if(serverManager_ != null){
00322             for( ProcessInfo i:serverManager_.getServerInfo()){
00323                 AProcess server = get(i.id);
00324                 if( server.isRunning()){
00325                     server.stop();
00326                 }
00327                 unregister(i.id);
00328                 monitor.worked(1);
00329             }
00330             
00331             
00332             
00333             ProcessInfo pi = serverManager_.getNameServerInfo();
00334            
00335             AProcess nameServer = get(serverManager_.getNameServerInfo().id);
00336             if(nameServer != null){
00337                 if(nameServer.isRunning())
00338                     nameServer.stop();
00339                 unregister(serverManager_.getNameServerInfo().id);
00340             }
00341             monitor.worked(1);
00342             setProcessList(monitor);
00343         }
00344     }
00345     
00346     public static class ProcessInfo implements Cloneable{
00347         public String       id            = null;
00348         public List<String> com           = new ArrayList<String>();
00349         public List<String> env           = new ArrayList<String>();
00350         public String       dir           = null;
00351         public int          waitCount     = -1;
00352         public boolean      isCorbaServer = false;
00353         public boolean      hasShutdown   = false;
00354         public boolean      doKillall     = false;
00355         public boolean      autoStart     = true;
00356         public boolean      autoStop      = true;
00357         public String       args           = "";
00358         public boolean      useORB        = false;
00359         public int               editComIndex   = 0;        // for ServerManagerPanel
00360 
00361         public void print() {
00362             GrxDebugUtil.println("\nID: " + id); //$NON-NLS-1$
00363             for (int i = 0; i < com.size(); i++) {
00364                 GrxDebugUtil.println("COM" + i + ": " + com.get(i)); //$NON-NLS-1$ //$NON-NLS-2$
00365             }
00366             if (env.size() > 0) {
00367                 for (int i = 0; i < env.size(); i++)
00368                     GrxDebugUtil.println("ENV" + i + ": " + env.get(i)); //$NON-NLS-1$ //$NON-NLS-2$
00369             } else {
00370                 GrxDebugUtil.println("ENV: use parent process environment"); //$NON-NLS-1$
00371             }
00372             GrxDebugUtil.println("DIR: " + dir); //$NON-NLS-1$
00373             GrxDebugUtil.println("ARGS: " + args); //$NON-NLS-1$
00374         }
00375         
00376         public ProcessInfo expandEnv(){
00377             ProcessInfo ret = clone();
00378             
00379             for(int i = 0; i < com.size(); ++i){
00380                 ret.com.set(i, GrxXmlUtil.expandEnvVal( com.get(i) )); 
00381             }
00382             ret.dir = GrxXmlUtil.expandEnvVal(dir);
00383             ret.args = GrxXmlUtil.expandEnvVal(args);
00384             
00385             return ret;
00386         }
00387         
00388         protected ProcessInfo clone(){
00389             ProcessInfo ret = null;
00390             try{
00391                 ret = (ProcessInfo)super.clone();
00392                 ret.args = new String(args);
00393                 ret.dir = new String(dir);
00394                 ret.com = new ArrayList<String>();
00395                 for(String i : com){
00396                     ret.com.add(new String(i));
00397                 }
00398                 ret.env = new ArrayList<String>();
00399                 for(String i : env){
00400                     ret.com.add(new String(i));
00401                 }
00402             }catch(CloneNotSupportedException ex){
00403                 ex.printStackTrace();
00404             }
00405             return ret;
00406         }
00407     }
00408 
00409     public void createThread() {
00410         if( thread_ == null ){
00411             thread_ = new Thread() {
00412                 public void run() {
00413                     while (!isEnd_) {
00414                         updateIO();
00415                     }
00416                 }
00417             };
00418             thread_.start();
00419         } else {
00420             startType();
00421         }
00422     }
00423 
00424     private void updateIO() {
00425         for (int i = 0; i < size(); i++) {
00426             AProcess p = process_.get(i);
00427             if (p == null || p.expecting_) {
00428                 continue;
00429             }
00430             StringBuffer sb = p.readLines();
00431             if (sb == null || sb.length() == 0) {
00432                 continue;
00433             }
00434             String newLine = sb.toString();
00435             if (outputBuffer_.length() > 50000) {
00436                 outputBuffer_.delete(0, newLine.length());
00437             }
00438             outputBuffer_.append(newLine);
00439             
00440             //排他処理
00441             isType_.lock();
00442             if( isType_.get() ){
00443                 isType_.unlock();
00444             } else {
00445                 //GrxProcessManagerViewが無いときはoutputBuffer_に出力文字列を貯めるだけ
00446                 isType_.unlock();
00447                 continue;
00448             }
00449             
00450             if (p.showOutput_) {
00451                 lineQueue.offer(newLine);
00452             }
00453         }
00454         // SWTEDT(イベントディスパッチスレッド)外からの呼び出しなので、SWTEDTに通知してやってもらう
00455         Display display = Display.getDefault();
00456         if (display != null && !display.isDisposed()) {
00457             display.asyncExec(new Runnable() {
00458                 public void run() {
00459                     String newLine = null;
00460                     while ((newLine = lineQueue.poll()) != null) {
00461                         notifyObservers("append", newLine); 
00462                         notifyObservers("setTopIndex"); 
00463                     }
00464                 }
00465             });
00466         }
00467         try {
00468             Thread.sleep(10);
00469         } catch (InterruptedException e) {
00470             e.printStackTrace();
00471         }
00472     }
00473 
00474     public void clearBuffer(){
00475         lineQueue.clear();
00476     }
00477     
00478     public StringBuffer getOutputBuffer(){
00479         return outputBuffer_;
00480     }
00481     
00482     public void setOutputBuffer(StringBuffer sb){
00483         outputBuffer_ = sb;
00484     }
00485 
00486     public void stopType() {
00487         isType_.lock();
00488         isType_.set(false);
00489         isType_.unlock();
00490     }
00491 
00492     public void startType() {
00493         isType_.lock();
00494         isType_.set(true);
00495         isType_.unlock();
00496     }
00497     
00498     public void stopThread() {
00499         isEnd_ = true;
00500         try {
00501                 if(thread_!=null)
00502                         thread_.join();
00503         } catch (InterruptedException ex) {
00504             ex.printStackTrace();
00505         }
00506     }
00507 
00508     public class AProcess {
00509         // configs
00510         public ProcessInfo     pi_         = null;
00511         private Process        process_    = null;
00512         private StringBuffer   com_        = null;
00513         private String[]       env_        = null;
00514         private File           dir_        = null;
00515         private boolean        showOutput_ = true;
00516 
00517         // variables
00518         private boolean        expecting_  = false;
00519         private InputStream    is_         = null;
00520         private BufferedReader br_         = null;
00521         private InputStream    es_         = null;
00522         private BufferedReader bre_        = null;
00523         private PrintStream    ps_         = null;
00524         private StringBuffer   buf_        = null;
00525 
00526         public AProcess(ProcessInfo pi) {
00527             pi_ = pi;
00528             updateCom(0);
00529             if (pi_.env.size() > 0) {
00530                 env_ = new String[pi_.env.size()];
00531                 for (int i = 0; i < pi_.env.size(); i++)
00532                     env_[i] = pi_.env.get(i);
00533             }
00534 
00535             try {
00536                 dir_ = new File( pi_.dir );
00537             } catch (Exception e) {
00538                 dir_ = null;
00539             }
00540 
00541             buf_ = new StringBuffer();
00542         }
00543 
00544         public void setCom(String com){
00545             com_ = new StringBuffer(com);
00546         }
00547         
00548         public void updateCom(int i){
00549             com_ = new StringBuffer();
00550             if (pi_.com.size() > i) {
00551                 com_.append(pi_.com.get(i)); //$NON-NLS-1$
00552             if(pi_.args!=null && !pi_.args.equals(""))
00553                 com_.append(" "+pi_.args);
00554             }
00555         }
00556         
00557         public boolean start(String opt){
00558                 for(int i=0; i<pi_.com.size(); i++){
00559                         updateCom(i);
00560                         if(start0(opt)){
00561                                 Thread thread = new Thread() {
00562                         public void run() {
00563                                 try {
00564                                                                 process_.waitFor();
00565                                                 Display display = Display.getDefault();
00566                                                                 if (display != null && !display.isDisposed()) {
00567                                                     display.asyncExec(new Runnable() {
00568                                                         public void run() {
00569                                                                 if (showOutput_){
00570                                                                         notifyObservers("append", "[" + pi_.id + ":O] " + "Process End\n"); 
00571                                                                         notifyObservers("setTopIndex");
00572                                                                 }
00573                                                                 serverManager_.notifyObservers("ProcessEnd", pi_.id);
00574                                                         }
00575                                                     });
00576                                                 }
00577                                                         } catch (InterruptedException e) {
00578                                                                 e.printStackTrace();
00579                                                         }
00580                         }
00581                     };
00582                     thread.start();
00583                                 return true;
00584                         }
00585                 }
00586                 return false;
00587         }
00588                        
00589         private boolean start0(String opt) {
00590             // StatusOut.append("\nStarting "+pi_.id+" ... ");
00591             if (isRunning()) {
00592                 // StatusOut.append("already running.\n");
00593             } else {
00594                 try {
00595                     if (opt == null) {
00596                         opt = ""; //$NON-NLS-1$
00597                     }
00598                     GrxDebugUtil.println(com_.toString() + " " + opt); //$NON-NLS-1$
00599                     if(dir_ != null){
00600                         if(!dir_.exists())
00601                                 dir_ = null;
00602                     }
00603                     
00604                     String[] _com = com_.toString().split(" ");
00605                     String[] _opt = opt.split(" ");
00606                     List<String> com = new ArrayList<String>();
00607                     for(int i=0; i<_com.length; i++)
00608                         if(_com[i].trim().length()!=0 )
00609                                 com.add(_com[i]);
00610                     for(int i=0; i<_opt.length; i++)
00611                         if(_opt[i].trim().length()!=0 )
00612                                 com.add(_opt[i]);
00613                     ProcessBuilder pb = new ProcessBuilder(com);
00614                     if(dir_ == null && new File(com.get(0)).isAbsolute())
00615                         dir_ = new File(com.get(0)).getParentFile();
00616                     pb.directory( dir_ );
00617                     Map<String, String> env = pb.environment();
00618                     if(env_!=null)
00619                         for(int i=0; i<env_.length; i++){
00620                                 String[] arg = env_[i].split("=");
00621                                 if(arg.length==2)
00622                                         env.put(arg[0].trim(), arg[1].trim());
00623                             }
00624                     Set<String> keySet = env.keySet();
00625                     String pathKey = null;
00626                     for (String key : keySet) {
00627                         if (key.equalsIgnoreCase("Path")) {
00628                                 pathKey = key;
00629                         }
00630                     }
00631                     String path = env.get(pathKey);
00632                     env.put(pathKey, Activator.getDefault().getPreferenceStore().getString("SERVER_DIR")+File.pathSeparator+path );
00633                     process_ = pb.start();
00634                     
00635                     is_ = process_.getInputStream();
00636                     br_ = new BufferedReader(new InputStreamReader(is_));
00637                     es_ = process_.getErrorStream();
00638                     bre_ = new BufferedReader(new InputStreamReader(es_));
00639                     ps_ = new PrintStream(process_.getOutputStream());
00640 
00641                     if (pi_.waitCount > 0) {
00642                         Thread.sleep(pi_.waitCount);
00643                     }
00644                     GrxDebugUtil.println("start:OK(" + pi_.id + ")"); //$NON-NLS-1$ //$NON-NLS-2$
00645                     return true;
00646                 } catch (Exception e) {
00647                     process_ = null;
00648                     //GrxDebugUtil.printErr("start:NG(" + pi_.id + ")", e); //$NON-NLS-1$ //$NON-NLS-2$
00649                     return false;
00650                 }
00651             }
00652             return true;
00653         }
00654 
00655         public boolean stop() {
00656             GrxDebugUtil.println("[PMView] stop:stopping " + pi_.id); //$NON-NLS-1$
00657             // StatusOut.append("\nStopping "+pi_.id+" ... ");
00658             if (isRunning()) {
00659                 if (pi_.hasShutdown) {
00660                     return shutdown();
00661                 }
00662                 try {
00663                     if (pi_.doKillall) {
00664                         String com0 = (pi_.com.get(0));
00665                         String path = com0.split(" ")[0]; //$NON-NLS-1$
00666                         String name = new File(path).getName();
00667                         killall(name);
00668                     } else {
00669                         process_.destroy();
00670                         process_.waitFor();
00671                     }
00672                     if (!isRunning()) {
00673                         process_ = null;
00674                         // StatusOut.append("OK\n");
00675                         GrxDebugUtil.println("stop:OK(" + pi_.id + ")"); //$NON-NLS-1$ //$NON-NLS-2$
00676                         if (pi_.id.equals(nameServerInfo_.id)) { //$NON-NLS-1$
00677                             GrxCorbaUtil.removeNameServiceFromList();
00678                         }
00679                         return true;
00680                     }
00681                     // StatusOut.append("NG\n");
00682                     GrxDebugUtil.println("stop:NG(" + pi_.id + ")"); //$NON-NLS-1$ //$NON-NLS-2$
00683                     return false;
00684                 } catch (Exception e) {
00685                     // StatusOut.append("NG\n");
00686                     GrxDebugUtil.printErr("stop:NG(" + pi_.id + ")", e); //$NON-NLS-1$ //$NON-NLS-2$
00687                 }
00688             } else {
00689                 // StatusOut.append("not running.\n");
00690                 GrxDebugUtil.println("stop:" + pi_.id + " is not running."); //$NON-NLS-1$ //$NON-NLS-2$
00691                 return true;
00692             }
00693             return false;
00694         }
00695 
00696         private boolean shutdown() {
00697             try {
00698                 // StatusOut.append("\nShutting down "+pi_.id+" ... ");
00699                 org.omg.CORBA.Object obj = GrxCorbaUtil.getReference(pi_.id);
00700                 ServerObject serverObj = ServerObjectHelper.narrow(obj);
00701                 serverObj.shutdown();
00702                 // StatusOut.append("OK\n");
00703                 GrxDebugUtil.println("shutdown:OK(" + pi_.id + ")"); //$NON-NLS-1$ //$NON-NLS-2$
00704                 return true;
00705             } catch (Exception e) {
00706                 // StatusOut.append("NG\n");
00707                 GrxDebugUtil.printErr("shutdown:NG(" + pi_.id + ")", e); //$NON-NLS-1$ //$NON-NLS-2$
00708             } finally {
00709                 process_.destroy();
00710                 process_ = null;
00711             }
00712             return false;
00713         }
00714 
00715         private void closeReader() {
00716             try {
00717                 br_.close();
00718                 is_.close();
00719                 bre_.close();
00720                 es_.close();
00721             } catch (IOException e) {
00722                 GrxDebugUtil.printErr("ProcessManager.closeReader:" + pi_.id + " couldn't close input stream", e); //$NON-NLS-1$ //$NON-NLS-2$
00723             }
00724         }
00725 
00726         public boolean isRunning() {
00727             try {
00728                 process_.exitValue();
00729                 return false;
00730             } catch (IllegalThreadStateException e) {
00731                 return true;
00732             } catch (Exception e) {
00733                 return false;
00734             }
00735         }
00736 
00737         private boolean isOpenHRPObject() {
00738             return pi_.hasShutdown;
00739         }
00740 
00741         private String expect(String key) {
00742             String[] k = { key };
00743             return expect(k);
00744         }
00745 
00746         private String expect(String[] key) {
00747             expecting_ = true;
00748             String str = checkKey(buf_, key);
00749             while (isRunning()) {
00750                 if (str != null) {
00751                     expecting_ = false;
00752                     return str;
00753                 }
00754                 str = checkKey(readLines(), key);
00755                 try {
00756                     Thread.sleep(10);
00757                 } catch (Exception e1) {}
00758             }
00759             str = checkKey(readLines(), key);
00760             expecting_ = false;
00761             return str;
00762         }
00763 
00764         private String checkKey(StringBuffer str, String[] key) {
00765             if (str != null) {
00766                 for (int i = 0; i < key.length; i++) {
00767                     if (str.indexOf(key[i]) != -1) {
00768                         return key[i];
00769                     }
00770                 }
00771             }
00772             return null;
00773         }
00774 
00775         private StringBuffer readLine(BufferedReader br) {
00776             if (br == null)
00777                 return null;
00778 
00779             StringBuffer ret = new StringBuffer();
00780             try {
00781                 while (br.ready()) {
00782                     char c = (char) br.read();
00783                     ret.append(c);
00784                     if (c == '\n')
00785                         break;
00786                 }
00787             } catch (Exception e) {
00788                 GrxDebugUtil.printErr("ProcessManager.readLine:(" + pi_.id + ")", e); //$NON-NLS-1$ //$NON-NLS-2$
00789             }
00790             if (ret.length() == 0) {
00791                 return null;
00792             }
00793             return ret;
00794         }
00795 
00796         private StringBuffer readLines() {
00797             if (isRunning() || expecting_) {
00798                 StringBuffer buf = new StringBuffer();
00799                 for (int i = 0; i < 100; i++) {
00800                     StringBuffer line1 = readLine(br_);
00801                     StringBuffer line2 = readLine(bre_);
00802                     if (line1 != null) {
00803                         buf.append("[" + pi_.id + ":O] " + line1); //$NON-NLS-1$ //$NON-NLS-2$
00804                     } else if (line2 == null) {
00805                         break;
00806                     }
00807                     if (line2 != null) {
00808                         buf.append("[" + pi_.id + ":E] " + line2); //$NON-NLS-1$ //$NON-NLS-2$
00809                     }
00810                 }
00811 
00812                 buf_.append(buf);
00813                 return buf;
00814             }
00815             return null;
00816         }
00817 
00818         private String readBuffer() {
00819             String ret = buf_.toString();
00820             clearBuffer();
00821             return ret;
00822         }
00823 
00824         private void clearBuffer() {
00825             buf_.delete(0, buf_.toString().length());
00826         }
00827 
00828         private void println(String line) {
00829             if (ps_ != null) {
00830                 ps_.println(line + "\n"); //$NON-NLS-1$
00831                 ps_.flush();
00832             }
00833         }
00834 
00835         private void waitFor() {
00836             try {
00837                 process_.waitFor();
00838             } catch (InterruptedException e) {
00839                 e.printStackTrace();
00840             }
00841         }
00842 
00843         private org.omg.CORBA.Object getReference() {
00844             return GrxCorbaUtil.getReference(pi_.id);
00845         }
00846 
00847         public boolean showOutput(){
00848                 return showOutput_;
00849         }
00850         
00851         public void setShowOutput(boolean b){
00852                 showOutput_ = b;
00853         }
00854     }
00855 }


openhrp3
Author(s): AIST, General Robotix Inc., Nakamura Lab of Dept. of Mechano Informatics at University of Tokyo
autogenerated on Sun Apr 2 2017 03:43:54