Example #1
0
 /**
  * Run the process and notify all listeners.
  *
  * @param pArgs arguments for ProcessBuilder
  * @param pProcessEvent store state in this ProcessEvent
  */
 @SuppressWarnings("deprecation")
 void runAndNotify(LinkedList<String> pArgs, ProcessEvent pProcessEvent) {
   int rc;
   try {
     Process pr = startProcess(pArgs);
     pProcessEvent.setProcess(pr);
     for (ProcessEventListener pel : iProcessEventListener) {
       pel.processStarted(pProcessEvent);
     }
     // TODO: remove in future version
     for (ProcessListener pl : iProcessListener) {
       pl.processStarted(pr);
     }
     rc = waitForProcess(pr);
     pProcessEvent.setReturnCode(rc);
     finished(rc);
   } catch (Exception e) {
     pProcessEvent.setException(e);
     try {
       finished(e);
     } catch (Exception e2) {
       pProcessEvent.setException(e2);
     }
   }
   for (ProcessEventListener pel : iProcessEventListener) {
     pel.processTerminated(pProcessEvent);
   }
   // TODO: remove in future version
   for (ProcessListener pl : iProcessListener) {
     pl.processTerminated(pProcessEvent);
   }
 }
 @Override
 public void complete() {
   for (ProcessListener l : listeners) {
     try {
       l.complete();
     } catch (Throwable th) {
       th.printStackTrace();
     }
   }
 }
 @Override
 public void addMessage(ProcessMessage pm) {
   for (ProcessListener l : listeners) {
     try {
       l.addMessage(pm);
     } catch (Throwable th) {
       th.printStackTrace();
     }
   }
 }
Example #4
0
 private void fireEvent(final String line, final DynByteBuffer sb, final int flag) {
   if ((flag & Executer.LISTENER_STDSTREAM) > 0) {
     for (final ProcessListener listener : this.listener) {
       listener.onProcess(this, line, sb);
     }
   }
   if ((flag & Executer.LISTENER_ERRORSTREAM) > 0) {
     for (final ProcessListener elistener : this.elistener) {
       elistener.onProcess(this, line, sb);
     }
   }
 }
  public boolean dehyphen() {

    if (listener != null) listener.progress(1);
    vd.showPerlMessage("Checking files...\n");
    if (hasProblems()) {
      vd.showPerlMessage("");
      vd.showPerlMessage("Files with problems are listed above. \n");
      vd.showPerlMessage(
          "Run this step again after the above identified problems are corrected.\n");
      listener.progress(0);
      return false;
    } else {
      vd.showPerlMessage("File checking completed. \n");
      listener.progress(5);
      vd.showPerlMessage("Pre-processing files... \n");
      fillInWords();
      if (listener != null) listener.progress(50);

      DeHyphenizer dh =
          new DeHyphenizerCorrected(
              this.database, this.tablename, "word", "count", "-", this.glossarytable, glossary);

      try {
        Statement stmt = conn.createStatement();
        ResultSet rs =
            stmt.executeQuery("select word from " + tablename + " where word like '%-%'");
        while (rs.next()) {
          String word = rs.getString("word");
          String dhword =
              dh.normalFormat(word)
                  .replaceAll(
                      "-",
                      "_"); // so dhwords in _allwords table are comparable to words in _wordpos and
          // other tables.
          Statement stmt1 = conn.createStatement();
          stmt1.execute(
              "update " + tablename + " set dhword ='" + dhword + "' where word='" + word + "'");
          mapping.put(word, dhword);
        }
        stmt.execute("update " + tablename + " set dhword=word where dhword is null");
      } catch (Exception e) {
        LOGGER.error("Problem in VolumeDehyphenizer:dehyphen", e);
        e.printStackTrace();
      }
      normalizeDocument();
      if (listener != null) listener.progress(100);
      return true;
    }
  }
Example #6
0
 private void fireEvent(final DynByteBuffer buffer, final int read, final int flag) {
   if (this.isInterrupted()) {
     return;
   }
   if ((flag & Executer.LISTENER_STDSTREAM) > 0) {
     for (final ProcessListener listener : this.listener) {
       listener.onBufferChanged(this, buffer, read);
     }
   }
   if ((flag & Executer.LISTENER_ERRORSTREAM) > 0) {
     for (final ProcessListener elistener : this.elistener) {
       elistener.onBufferChanged(this, buffer, read);
     }
   }
 }
  @Override
  protected void disposeElementInfo(final Object element, final ElementInfo info) {
    super.disposeElementInfo(element, info);

    if (element instanceof IAdaptable) {
      final ToolProcess process =
          (ToolProcess) ((IAdaptable) element).getAdapter(ToolProcess.class);
      if (process != null) {
        synchronized (fProcesses) {
          final ProcessListener listener = fProcesses.get(process);
          if (listener != null) {
            listener.remove(element);
          }
        }
      }
    }
  }
  /**
   * execute vbs by java.
   *
   * @param command vbs file with params Object to be executed
   * @throws RuntimeException
   * @throws TimeoutException
   */
  public void executeCommands(String[] command) {
    try {
      Process process = Runtime.getRuntime().exec(command);
      ProcessListener listener = new ProcessListener(process);
      listener.start();

      try {
        listener.join(threadTimeOut);
      } catch (InterruptedException ex) {
        listener.interrupt();
        throw new RuntimeException(ex);
      } finally {
        process.destroy();
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  @Override
  protected ElementInfo createElementInfo(final Object element) throws CoreException {
    final ElementInfo info = super.createElementInfo(element);

    if (info != null && element instanceof IAdaptable) {
      final ToolProcess process =
          (ToolProcess) ((IAdaptable) element).getAdapter(ToolProcess.class);
      if (process != null) {
        synchronized (fProcesses) {
          ProcessListener listener = fProcesses.get(process);
          if (listener == null) {
            listener = new ProcessListener(process);
          }
          listener.add(element);
        }
      }
    }

    return info;
  }
 private void subscribeJMXRuntimeEvent() {
   if (debug) {
     System.out.println(
         "["
             + new java.util.Date()
             + " "
             + host
             + " "
             + this.getClass().getSimpleName()
             + "] Subscribe JMX Runtime");
     outDebug.println(
         "["
             + new java.util.Date()
             + " "
             + host
             + " "
             + this.getClass().getSimpleName()
             + "] Subscribe JMX Runtime");
   }
   ProActiveRuntimeImpl part = ProActiveRuntimeImpl.getProActiveRuntime();
   part.addDeployment(listener.getDeployID());
   JMXNotificationManager.getInstance().subscribe(part.getMBean().getObjectName(), this);
   if (debug) {
     System.out.println(
         "["
             + new java.util.Date()
             + " "
             + host
             + " "
             + this.getClass().getSimpleName()
             + "] Subscribed");
     outDebug.println(
         "["
             + new java.util.Date()
             + " "
             + host
             + " "
             + this.getClass().getSimpleName()
             + "] Subscribed");
   }
 }
 /**
  * Allows you to send additional notifications of executed processing steps.
  *
  * @param token the token that is handled
  * @param action the action that is executed on the action
  */
 public void notifyProcessListener(Token token, Action action) {
   if (processListener != null) {
     processListener.log(this, token, action);
   }
 }
  /** check for unmatched brackets too. */
  private void fillInWords() {
    try {
      Statement stmt = conn.createStatement();
      ResultSet rs = null;
      File[] flist = folder.listFiles();
      int total = flist.length;
      for (int i = 0; i < flist.length; i++) {
        BufferedReader reader = new BufferedReader(new FileReader(flist[i]));
        String line = null;
        StringBuffer sb = new StringBuffer();
        while ((line = reader.readLine()) != null) {
          line = line.replaceAll(System.getProperty("line.separator"), " ");
          sb.append(line);
        }
        reader.close();
        String text = sb.toString();
        text = text.toLowerCase();
        text = text.replaceAll("<[^<]+?>", " ");
        text = text.replaceAll("\\d", " ");
        text = text.replaceAll("\\(", " ( ");
        text = text.replaceAll("\\)", " ) ");
        text = text.replaceAll("\\[", " [ ");
        text = text.replaceAll("\\]", " ] ");
        text = text.replaceAll("\\{", " { ");
        text = text.replaceAll("\\}", " } ");
        text = text.replaceAll("\\s+", " ").trim();
        String[] words = text.split("\\s+");
        int lround = 0;
        int lsquare = 0;
        int lcurly = 0;
        int inbracket = 0;
        for (int j = 0; j < words.length; j++) {
          String w = words[j].trim();
          if (w.compareTo("(") == 0) lround++;
          else if (w.compareTo(")") == 0) lround--;
          else if (w.compareTo("[") == 0) lsquare++;
          else if (w.compareTo("]") == 0) lsquare--;
          else if (w.compareTo("{") == 0) lcurly++;
          else if (w.compareTo("}") == 0) lcurly--;
          else {
            w = w.replaceAll("[^-a-z]", " ").trim();
            if (w.matches(".*?\\w.*")) {
              if (lround + lsquare + lcurly > 0) {
                inbracket = 1;
              } else {
                inbracket = 0;
              }
              int count = 1;
              rs =
                  stmt.executeQuery(
                      "select word, count, inbrackets from "
                          + tablename
                          + "  where word='"
                          + w
                          + "'");
              if (rs.next()) { // normal word exist
                count += rs.getInt("count");
                inbracket *= rs.getInt("inbrackets");
              }
              stmt.execute("delete from " + tablename + " where word ='" + w + "'");
              stmt.execute(
                  "insert into "
                      + tablename
                      + " (word, count, inbrackets) values('"
                      + w
                      + "', "
                      + count
                      + ","
                      + inbracket
                      + ")");
            }
          }
        }
        listener.progress(5 + i * 45 / total);

        /*while ((line = reader.readLine()) != null) {
            line = line.toLowerCase();
            line = line.replaceAll("<[^<]+?>", " "); //for xml or html docs
            line = line.replaceAll(num, " ");
            line = line.replaceAll("[^-a-z]", " ");
            line = normalize(line);

            Statement stmt = conn.createStatement();
               ResultSet rs = null;
            String[] words = line.split("\\s+");
            for(int j = 0; j < words.length; j++){
                String w = words[j].trim();
                if(w.matches(".*?\\w.*")){
                    int count = 1;
                    rs = stmt.executeQuery("select word, count from "+tablename+"  where word='"+w+"'");
                    if(rs.next()){
                        count = rs.getInt("count")+1;
                    }
                    stmt.execute("delete from "+tablename+" where word ='"+w+"'");
                    stmt.execute("insert into "+tablename+" (word, count) values('"+w+"', "+count+")");
                }
            }
            rs.close();
            stmt.close();
        }*/
      }
      rs.close();
      stmt.close();
    } catch (Exception e) {
      LOGGER.error("Problem in VolumeDehyphenizer:fillInWords", e);
      e.printStackTrace();
    }
  }
    public void handleNotification(Notification notification, Object handback) {
      try {
        String type = notification.getType();

        if (NotificationType.GCMRuntimeRegistered.equals(type)) {
          if (debug) {
            System.out.println(
                "["
                    + new java.util.Date()
                    + " "
                    + host
                    + " "
                    + this.getClass().getSimpleName()
                    + "] Notification received");
            outDebug.println(
                "["
                    + new java.util.Date()
                    + " "
                    + host
                    + " "
                    + this.getClass().getSimpleName()
                    + "] Notification received");
          }
          GCMRuntimeRegistrationNotificationData data =
              (GCMRuntimeRegistrationNotificationData) notification.getUserData();
          if (data.getDeploymentId() != listener.getDeployID()) {
            return;
          }
          if (debug) {
            System.out.println(
                "["
                    + new java.util.Date()
                    + " "
                    + host
                    + " "
                    + this.getClass().getSimpleName()
                    + "] Notification accepted");
            outDebug.println(
                "["
                    + new java.util.Date()
                    + " "
                    + host
                    + " "
                    + this.getClass().getSimpleName()
                    + "] Notification accepted");
            outDebug.flush();
          }

          ProActiveRuntime childRuntime = data.getChildRuntime();
          if (debug) {
            System.out.println(
                "["
                    + new java.util.Date()
                    + " "
                    + host
                    + " "
                    + this.getClass().getSimpleName()
                    + "] Creating Node");
            outDebug.println(
                "["
                    + new java.util.Date()
                    + " "
                    + host
                    + " "
                    + this.getClass().getSimpleName()
                    + "] Creating Node");
          }
          Node scilabNode = null;
          try {
            scilabNode =
                childRuntime.createLocalNode(
                    nodeBaseName + "_" + nodeName + "_" + nodeCount, true, null, null);
          } catch (Exception e) {
            if (debug) {
              e.printStackTrace();
              e.printStackTrace(outDebug);
            }
            throw e;
          }
          nodeCount++;
          if (debug) {
            System.out.println(
                "["
                    + new java.util.Date()
                    + " "
                    + host
                    + " "
                    + this.getClass().getSimpleName()
                    + "] Node Created : "
                    + scilabNode.getNodeInformation().getURL());
            outDebug.println(
                "["
                    + new java.util.Date()
                    + " "
                    + host
                    + " "
                    + this.getClass().getSimpleName()
                    + "] Node Created :"
                    + scilabNode.getNodeInformation().getURL());
          }
          listener.setNode(scilabNode);

          if (debug) {
            System.out.println(
                "["
                    + new java.util.Date()
                    + " "
                    + host
                    + " "
                    + this.getClass().getSimpleName()
                    + "] Waking up main thread");
            outDebug.println(
                "["
                    + new java.util.Date()
                    + " "
                    + host
                    + " "
                    + this.getClass().getSimpleName()
                    + "] Waking up main thread");
          }
        }
      } catch (Exception e) {
        e.printStackTrace();
        if (debug) {
          e.printStackTrace(outDebug);
        }
      } finally {
        semaphore.release();
      }
    }
  /**
   * Starts the java process on the given Node uri
   *
   * @return process
   * @throws Throwable
   */
  public final Process startProcess(
      String nodeBaseName, ProcessInitializer init, ProcessListener listener) throws Throwable {

    if (debug) {
      System.out.println(
          "["
              + new java.util.Date()
              + " "
              + host
              + " "
              + this.getClass().getSimpleName()
              + "] Starting a new JVM");
      outDebug.println(
          "["
              + new java.util.Date()
              + " "
              + host
              + " "
              + this.getClass().getSimpleName()
              + "] Starting a new JVM");
    }

    // Build java command
    javaCommandBuilder = new DummyJVMProcess();
    javaCommandBuilder.setClassname(StartPARuntime.class.getName());

    int deployID = new SecureRandom().nextInt();
    listener.setDeployID(deployID);

    registrationListener = new RegistrationListener(listener, nodeBaseName);
    registrationListener.subscribeJMXRuntimeEvent();

    javaCommandBuilder.setParameters(
        "-d " + deployID + " -c 1 -p " + RuntimeFactory.getDefaultRuntime().getURL());

    javaCommandBuilder.setJvmOptions("-Dproactive.configuration=" + writeConfigFile());

    // We build the process with a separate environment
    ProcessBuilder pb = new ProcessBuilder();

    // Setting Environment variables
    Map<String, String> env = pb.environment();

    // Specific to the extension
    init.initProcess(javaCommandBuilder, env);

    if (debug) {
      System.out.println("Starting Process:");
      outDebug.println("Starting Process:");
      System.out.println(javaCommandBuilder.getJavaCommand());
      outDebug.println(javaCommandBuilder.getJavaCommand());
      System.out.println("With Environment: {");
      outDebug.println("With Environment: {");
      for (Map.Entry<String, String> entry : pb.environment().entrySet()) {
        System.out.println(entry.getKey() + "=" + entry.getValue());
        outDebug.println(entry.getKey() + "=" + entry.getValue());
      }
      System.out.println("}");
      outDebug.println("}");
    }

    pb.command(javaCommandBuilder.getJavaCommand());

    return pb.start();
  }
Example #15
0
  /*
   * @see flash.tools.debugger.SessionManager#launch(java.lang.String, flash.tools.debugger.AIRLaunchInfo, boolean, flash.tools.debugger.IProgress)
   */
  public Session launch(
      String uri, AIRLaunchInfo airLaunchInfo, boolean forDebugging, IProgress waitReporter)
      throws IOException {
    boolean modify = (getPreference(PREF_URI_MODIFICATION) != 0);
    LaunchInfo launchInfo = new LaunchInfo(uri);
    boolean nativeLaunch =
        launchInfo.isWebBrowserNativeLaunch() || launchInfo.isPlayerNativeLaunch();

    // one of these is assigned to launchAction
    final int NO_ACTION = 0; // no special action
    final int SHOULD_LISTEN = 1; // create a ProcessListener
    final int WAIT_FOR_LAUNCH = 2; // block until process completes

    int launchAction; // either NO_ACTION, SHOULD_LISTEN, or WAIT_FOR_LAUNCH

    uri = uri.trim();

    String osName = System.getProperty("os.name").toLowerCase(); // $NON-NLS-1$
    boolean isMacOSX = osName.startsWith("mac os x"); // $NON-NLS-1$
    boolean isWindows = osName.startsWith("windows"); // $NON-NLS-1$
    // if isMacOSX and isWindows are both false, then it's *NIX

    if (airLaunchInfo == null) {
      // first let's see if it's an HTTP URL or not
      if (launchInfo.isHttpOrAbout()) {
        if (modify && forDebugging && !uri.startsWith("about:")) // $NON-NLS-1$
        {
          // escape spaces if we have any
          uri = URLHelper.escapeSpace(uri);

          // be sure that ?debug=true is included in query string
          URLHelper urlHelper = new URLHelper(uri);
          Map params = urlHelper.getParameterMap();
          params.put("debug", "true"); // $NON-NLS-1$ //$NON-NLS-2$
          urlHelper.setParameterMap(params);

          uri = urlHelper.getURL();
        }
      } else {
        // ok, its not an http: type request therefore we should be able to see
        // it on the file system, right?  If not then it's probably not valid
        File f = null;
        if (uri.startsWith("file:")) // $NON-NLS-1$
        {
          try {
            f = new File(new URI(uri));
          } catch (URISyntaxException e) {
            IOException ioe = new IOException(e.getMessage());
            ioe.initCause(e);
            throw ioe;
          }
        } else {
          f = new File(uri);
        }

        if (f != null && f.exists()) uri = f.getCanonicalPath();
        else throw new FileNotFoundException(uri);
      }

      if (nativeLaunch) {
        // We used to have
        //
        //		launchAction = SHOULD_LISTEN;
        //
        // However, it turns out that when you launch Firefox, if there
        // is another instance of Firefox already running, then the
        // new instance just passes a message to the old one and then
        // immediately exits.  So, it doesn't work to abort when our
        // child process dies.
        launchAction = NO_ACTION;
      } else {
        launchAction = NO_ACTION;
      }

      /**
       * Various ways to launch this stupid thing. If we have the exe values for the player, then we
       * can launch it directly, monitor it and kill it when we die; otherwise we launch it through
       * a command shell (cmd.exe, open, or bash) and our Process object dies right away since it
       * spawned another process to run the Player within.
       */
      if (isMacOSX) {
        if (launchInfo.isWebBrowserNativeLaunch()) {
          File httpExe = m_debuggerCallbacks.getHttpExe();
          m_launchCommand =
              new String[] {
                "/usr/bin/open", "-a", httpExe.toString(), uri
              }; //$NON-NLS-1$ //$NON-NLS-2$
        } else if (launchInfo.isPlayerNativeLaunch()) {
          File playerExe = m_debuggerCallbacks.getPlayerExe();
          m_launchCommand =
              new String[] {
                "/usr/bin/open", "-a", playerExe.toString(), uri
              }; //$NON-NLS-1$ //$NON-NLS-2$
        } else {
          m_launchCommand = new String[] {"/usr/bin/open", uri}; // $NON-NLS-1$
        }
      } else {

        if (launchInfo.isWebBrowserNativeLaunch()) {
          File httpExe = m_debuggerCallbacks.getHttpExe();
          m_launchCommand = new String[] {httpExe.toString(), uri};
        } else if (launchInfo.isPlayerNativeLaunch()) {
          File playerExe = m_debuggerCallbacks.getPlayerExe();
          m_launchCommand = new String[] {playerExe.toString(), uri};
        } else {
          if (isWindows) {
            // We must quote all ampersands in the URL; if we don't, then
            // cmd.exe will interpret the ampersand as a command separator.
            uri = uri.replaceAll("&", "\"&\""); // $NON-NLS-1$ //$NON-NLS-2$

            m_launchCommand =
                new String[] {"cmd", "/c", "start", uri}; // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
          } else {
            String exeName;
            if (launchInfo.isWebPage()) exeName = m_debuggerCallbacks.getHttpExeName();
            else exeName = m_debuggerCallbacks.getPlayerExeName();
            throw new FileNotFoundException(exeName);
          }
        }
      }
    } else // else, AIR
    {
      if (forDebugging) launchAction = SHOULD_LISTEN; // wait inside accept() until ADL exits
      else launchAction = NO_ACTION; // just launch it

      List cmdList = new LinkedList();

      cmdList.add(airLaunchInfo.airDebugLauncher.getPath());

      if (airLaunchInfo.airRuntimeDir != null && airLaunchInfo.airRuntimeDir.length() > 0) {
        cmdList.add("-runtime"); // $NON-NLS-1$
        cmdList.add(airLaunchInfo.airRuntimeDir.getPath());
      }

      if (airLaunchInfo.airSecurityPolicy != null && airLaunchInfo.airSecurityPolicy.length() > 0) {
        cmdList.add("-security-policy"); // $NON-NLS-1$
        cmdList.add(airLaunchInfo.airSecurityPolicy.getPath());
      }

      if (airLaunchInfo.airPublisherID != null && airLaunchInfo.airPublisherID.length() > 0) {
        cmdList.add("-pubid"); // $NON-NLS-1$
        cmdList.add(airLaunchInfo.airPublisherID);
      }

      // If it's a "file:" URL, then pass the actual filename; otherwise, use the URL
      // ok, its not an http: type request therefore we should be able to see
      // it on the file system, right?  If not then it's probably not valid
      File f = null;
      if (uri.startsWith("file:")) // $NON-NLS-1$
      {
        try {
          f = new File(new URI(uri));
          cmdList.add(f.getPath());
        } catch (URISyntaxException e) {
          IOException ioe = new IOException(e.getMessage());
          ioe.initCause(e);
          throw ioe;
        }
      } else {
        cmdList.add(uri);
      }

      if (airLaunchInfo.applicationContentRootDir != null) {
        cmdList.add(airLaunchInfo.applicationContentRootDir.getAbsolutePath());
      }

      if (airLaunchInfo.applicationArguments != null
          && airLaunchInfo.applicationArguments.length() > 0) {
        cmdList.add("--"); // $NON-NLS-1$
        cmdList.addAll(splitArgs(airLaunchInfo.applicationArguments));
      }

      m_launchCommand = (String[]) cmdList.toArray(new String[cmdList.size()]);
    }

    ProcessListener pl = null;
    PlayerSession session = null;
    try {
      // create the process and attach a thread to watch it during our accept phase
      Process proc = m_debuggerCallbacks.launchDebugTarget(m_launchCommand);

      m_processMessages = new StringWriter();
      new StreamListener(new InputStreamReader(proc.getInputStream()), m_processMessages).start();
      new StreamListener(new InputStreamReader(proc.getErrorStream()), m_processMessages).start();
      try {
        OutputStream stm = proc.getOutputStream();
        if (stm != null) stm.close();
      } catch (IOException e) {
        /* not serious; ignore */
      }

      switch (launchAction) {
        case NO_ACTION:
          break;

        case SHOULD_LISTEN:
          {
            // allows us to hear when the process dies
            pl = new ProcessListener(this, proc);
            pl.start();
            break;
          }

        case WAIT_FOR_LAUNCH:
          {
            // block until the process completes
            boolean done = false;
            while (!done) {
              try {
                proc.waitFor();
                done = true;
              } catch (InterruptedException e) {
                /* do nothing */
              }
            }
            if (proc.exitValue() != 0) {
              throw new IOException(m_processMessages.toString());
            }
            break;
          }
      }

      if (forDebugging) {
        /* now wait for a connection */
        session = (PlayerSession) accept(waitReporter, airLaunchInfo != null);
        session.setProcess(proc);
        session.setLaunchUrl(uri);
        session.setAIRLaunchInfo(airLaunchInfo);
      }
    } finally {
      if (pl != null) pl.finish();
    }
    return session;
  }