Beispiel #1
0
  /**
   * Executes the command in the executor it is currently set to.
   *
   * @param source that sent the command
   * @param args command arguments
   * @throws CommandException if the command executor is null or if {@link
   *     Executor#execute(CommandSource, Command, CommandArguments)} throws a CommandException.
   */
  public void process(CommandSource source, CommandArguments args) throws CommandException {

    // check permissions
    if (permission != null && !source.hasPermission(permission)) {
      throw new CommandException("You do not have permission to execute this command.");
    }

    args.flags().registerFlags(this.flags);

    // no child found, try to execute
    for (CommandFilter filter : filters) {
      filter.validate(this, source, args);
    }

    // execute a child if applicable
    if (children.size() > 0) {
      Command child = getChild(args.popString("child"), false);
      if (child != null) {
        if (executor != null) {
          executor.execute(source, this, args);
        }
        child.process(source, args);
      } else {
        throw args.failure("child", "Unknown child!", false);
      }
    } else {
      if (executor == null) {
        throw new CommandException("CommandDescription exists but has no set executor.");
      }
      args.flags().parse();
      executor.execute(source, this, args);
    }
  }
Beispiel #2
0
 public Builder with(@CheckForNull Computer computer) {
   if (computer == null) {
     return this;
   }
   if (computer.isOnline()) {
     final List<Executor> executors = computer.getExecutors();
     final boolean acceptingTasks = computer.isAcceptingTasks();
     for (Executor e : executors) {
       definedExecutors++;
       onlineExecutors++;
       if (e.getCurrentWorkUnit() != null) {
         busyExecutors++;
       } else {
         idleExecutors++;
         if (acceptingTasks) availableExecutors++;
       }
     }
   } else {
     final int numExecutors = computer.getNumExecutors();
     definedExecutors += numExecutors;
     if (computer.isConnecting()) {
       connectingExecutors += numExecutors;
     }
   }
   return this;
 }
Beispiel #3
0
 /** Returns the number of idle {@link Executor}s that can start working immediately. */
 public int countIdle() {
   int n = 0;
   for (Executor e : executors) {
     if (e.isIdle()) n++;
   }
   return n;
 }
  private ValidationResult getValidationResult() {
    if (!myValidationResultValid) {
      myLastValidationResult = null;
      try {
        RunnerAndConfigurationSettings snapshot = getSnapshot();
        if (snapshot != null) {
          snapshot.setName(getNameText());
          snapshot.checkSettings();
          for (ProgramRunner runner : RunnerRegistry.getInstance().getRegisteredRunners()) {
            for (Executor executor : ExecutorRegistry.getInstance().getRegisteredExecutors()) {
              if (runner.canRun(executor.getId(), snapshot.getConfiguration())) {
                checkConfiguration(runner, snapshot);
                break;
              }
            }
          }
        }
      } catch (RuntimeConfigurationException exception) {
        myLastValidationResult =
            exception != null
                ? new ValidationResult(
                    exception.getLocalizedMessage(), exception.getTitle(), exception.getQuickFix())
                : null;
      } catch (ConfigurationException e) {
        myLastValidationResult =
            new ValidationResult(
                e.getLocalizedMessage(),
                ExecutionBundle.message("invalid.data.dialog.title"),
                null);
      }

      myValidationResultValid = true;
    }
    return myLastValidationResult;
  }
 @Override
 protected void hyperlinkActivated(HyperlinkEvent e) {
   final Module moduleByName =
       ModuleManager.getInstance(myProject).findModuleByName(e.getDescription());
   if (moduleByName != null) {
     myConfiguration.getConfigurationModule().setModule(moduleByName);
     try {
       final Executor executor =
           myConsoleProperties.isDebug()
               ? DefaultDebugExecutor.getDebugExecutorInstance()
               : DefaultRunExecutor.getRunExecutorInstance();
       final ProgramRunner runner =
           RunnerRegistry.getInstance().getRunner(executor.getId(), myConfiguration);
       assert runner != null;
       runner.execute(
           executor,
           new ExecutionEnvironment(
               myConfiguration,
               myProject,
               getRunnerSettings(),
               getConfigurationSettings(),
               null));
       final Balloon balloon = myToolWindowManager.getToolWindowBalloon(myTestRunDebugId);
       if (balloon != null) {
         balloon.hide();
       }
     } catch (ExecutionException e1) {
       LOG.error(e1);
     }
   }
 }
 public <E> List<E> query(
     MappedStatement ms,
     Object parameterObject,
     RowBounds rowBounds,
     ResultHandler resultHandler,
     CacheKey key,
     BoundSql boundSql)
     throws SQLException {
   Cache cache = ms.getCache();
   if (cache != null) {
     flushCacheIfRequired(ms);
     if (ms.isUseCache() && resultHandler == null) {
       ensureNoOutParams(ms, parameterObject, boundSql);
       if (!dirty) {
         cache.getReadWriteLock().readLock().lock();
         try {
           @SuppressWarnings("unchecked")
           List<E> cachedList = (List<E>) cache.getObject(key);
           if (cachedList != null) return cachedList;
         } finally {
           cache.getReadWriteLock().readLock().unlock();
         }
       }
       List<E> list =
           delegate.<E>query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
       tcm.putObject(
           cache, key, list); // issue #578. Query must be not synchronized to prevent deadlocks
       return list;
     }
   }
   return delegate.<E>query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
 }
 public static void run(
     InvocationOutputHandler outputHandler,
     Map<String, String> envVarsForApp,
     CommandLine command,
     File projectRoot,
     long timeout)
     throws ProjectCannotStartException {
   long startTime = logStartInfo(command, projectRoot);
   ExecuteWatchdog watchDog = new ExecuteWatchdog(timeout);
   Executor executor = createExecutor(outputHandler, command, projectRoot, watchDog);
   try {
     int exitValue = executor.execute(command, envVarsForApp);
     if (executor.isFailure(exitValue)) {
       String message =
           watchDog.killedProcess()
               ? "Timed out waiting for " + command
               : "Exit code " + exitValue + " returned from " + command;
       throw new ProjectCannotStartException(message);
     }
   } catch (Exception e) {
     String message =
         "Error running: "
             + dirPath(projectRoot)
             + "> "
             + StringUtils.join(command.toStrings(), " ");
     outputHandler.consumeLine(message);
     outputHandler.consumeLine(e.toString());
     throw new ProjectCannotStartException(message, e);
   }
   logEndTime(command, startTime);
 }
  @Override
  public void execute(Executor executor) {
    setActive(); /*
                 currentRequestor = null;
                  Check if there is a valid host to which return the task output
                 for(int i=0; i<delegationChain.size() && currentRequestor == null; i++){
                 	if(myRouter.getPresenceCollector().isHostInRange(delegationChain.get(i))){
                 		currentRequestor = delegationChain.get(i);
                 	}
                 } */

    if (
    /*currentRequestor != null*/ myRouter.getPresenceCollector().isHostInRange(requestor)
        && executor.moreCommunicatorsAvailable()) {
      int[] missingRestOfMap =
          ((M2MShareRouter) requestor.getRouter()).getIntervalsForDownloadFwd(getID());
      if (missingRestOfMap == null) {
        setCompleted();
        return;
      }
      System.err.println(
          myRouter.getHost() + " - in DTNDownloadFwd.execute comincio a trasferire a " + requestor);
      executor.addCommunicator(
          myRouter.getPresenceCollector().getConnectionFor(requestor),
          myRouter.getHost(),
          filehash,
          missingRestOfMap);
      /* keep state = ACTIVE */
      return;
    }
    // no communicator started
    setIncomplete();
  }
  public static <R> R execute(
      String url, String traceHearName, HttpRequest httpRequest, Executor<R> executor)
      throws IOException {
    if (!AuthDesc.isAuth()) {
      return executor.execute();
    }

    try {
      httpRequest.setHeader(
          traceHearName,
          "ContextData="
              + sender
                  .beforeSend(
                      Identification.newBuilder()
                          .viewPoint(url)
                          .spanType(WEBBuriedPointType.instance())
                          .build())
                  .toString());
      return executor.execute();
    } catch (IOException e) {
      sender.handleException(e);
      throw e;
    } finally {
      sender.afterSend();
    }
  }
  protected void appendForkInfo(Executor executor) throws ExecutionException {
    final String forkMode = getForkMode();
    if (Comparing.strEqual(forkMode, "none")) {
      if (forkPerModule()) {
        if (isExecutorDisabledInForkedMode()) {
          final String actionName = UIUtil.removeMnemonic(executor.getStartActionText());
          throw new CantRunException(
              "'"
                  + actionName
                  + "' is disabled when per-module working directory is configured.<br/>"
                  + "Please specify single working directory, or change test scope to single module.");
        }
      } else {
        return;
      }
    } else if (isExecutorDisabledInForkedMode()) {
      final String actionName = executor.getActionName();
      throw new CantRunException(
          actionName
              + " is disabled in fork mode.<br/>Please change fork mode to &lt;none&gt; to "
              + actionName.toLowerCase(Locale.ENGLISH)
              + ".");
    }

    final JavaParameters javaParameters = getJavaParameters();
    final Sdk jdk = javaParameters.getJdk();
    if (jdk == null) {
      throw new ExecutionException(
          ExecutionBundle.message("run.configuration.error.no.jdk.specified"));
    }

    try {
      final File tempFile = FileUtil.createTempFile("command.line", "", true);
      final PrintWriter writer = new PrintWriter(tempFile, CharsetToolkit.UTF8);
      try {
        if (JdkUtil.useDynamicClasspath(getConfiguration().getProject())) {
          String classpath = PathUtil.getJarPathForClass(CommandLineWrapper.class);
          final String utilRtPath = PathUtil.getJarPathForClass(StringUtilRt.class);
          if (!classpath.equals(utilRtPath)) {
            classpath += File.pathSeparator + utilRtPath;
          }
          writer.println(classpath);
        } else {
          writer.println("");
        }

        writer.println(((JavaSdkType) jdk.getSdkType()).getVMExecutablePath(jdk));
        for (String vmParameter : javaParameters.getVMParametersList().getList()) {
          writer.println(vmParameter);
        }
      } finally {
        writer.close();
      }

      passForkMode(forkMode, tempFile);
    } catch (Exception e) {
      LOG.error(e);
    }
  }
Beispiel #11
0
 /**
  * Stops this build if it's still going.
  *
  * <p>If we use this/executor/stop URL, it causes 404 if the build is already killed, as {@link
  * #getExecutor()} returns null.
  */
 public synchronized void doStop(StaplerRequest req, StaplerResponse rsp)
     throws IOException, ServletException {
   Executor e = getExecutor();
   if (e != null) e.doStop(req, rsp);
   else
     // nothing is building
     rsp.forwardToPreviousPage(req);
 }
 /**
  * Receives users command until 'Esc' entered
  *
  * @param args
  */
 public static void main(String[] args) {
   Executor e = new Executor();
   Scanner input = new Scanner(System.in);
   String userData = "-help";
   e.about();
   while (!"Esc".equals(userData)) {
     e.execute(userData);
     userData = input.nextLine();
   }
 }
Beispiel #13
0
 /**
  * Returns the time when this computer last became idle.
  *
  * <p>If this computer is already idle, the return value will point to the time in the past since
  * when this computer has been idle.
  *
  * <p>If this computer is busy, the return value will point to the time in the future where this
  * computer will be expected to become free.
  */
 public final long getIdleStartMilliseconds() {
   long firstIdle = Long.MIN_VALUE;
   for (Executor e : oneOffExecutors) {
     firstIdle = Math.max(firstIdle, e.getIdleStartMilliseconds());
   }
   for (Executor e : executors) {
     firstIdle = Math.max(firstIdle, e.getIdleStartMilliseconds());
   }
   return firstIdle;
 }
Beispiel #14
0
  public static void main(String[] args) {

    Executor ex = new GameLogExecutorNate();

    try {
      ex.execute();
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Beispiel #15
0
  private void addNewExecutorIfNecessary() {
    Set<Integer> availableNumbers = new HashSet<Integer>();
    for (int i = 0; i < numExecutors; i++) availableNumbers.add(i);

    for (Executor executor : executors) availableNumbers.remove(executor.getNumber());

    for (Integer number : availableNumbers) {
      Executor e = new Executor(this, number);
      e.start();
      executors.add(e);
    }
  }
Beispiel #16
0
 @Override
 protected void performDelete() throws IOException, InterruptedException {
   // if a build is in progress. Cancel it.
   RunT lb = getLastBuild();
   if (lb != null) {
     Executor e = lb.getExecutor();
     if (e != null) {
       e.interrupt();
       // should we block until the build is cancelled?
     }
   }
   super.performDelete();
 }
Beispiel #17
0
  public ExePane(Executor mdl, UiCommon texts) {
    super(new BorderLayout());
    ui = texts;
    model = mdl;

    mdl.getParent()
        .addPropertyChangeListener(
            new PropertyChangeListener() {

              @Override
              public void propertyChange(PropertyChangeEvent evt) {
                if (evt.getSource() == model) {
                  if (EventQueue.isDispatchThread()) {
                    refresh();
                  } else {
                    EventQueue.invokeLater(
                        new Runnable() {

                          public void run() {
                            refresh();
                          }
                        });
                  }
                }
              }
            });

    mdl.setInputStream(new TextAreaStream(std));
    mdl.setErrorStream(new TextAreaStream(err));

    SwingHelper h = new SwingHelper(this);
    h.with("header", new BorderLayout(), BorderLayout.PAGE_START)
        .add("line", new JLabel(model.getCommand().getLine()), BorderLayout.CENTER)
        .add("state", stateLabel, BorderLayout.LINE_END)
        .back();

    //        h.add("streams", new JSplitPane(JSplitPane.VERTICAL_SPLIT,
    //                new JScrollPane(std), new JScrollPane(err)), BorderLayout.CENTER);

    h.with("streams", new JTabbedPane(), BorderLayout.CENTER)
        .add("std", new JScrollPane(std))
        .add("err", new JScrollPane(err))
        .back();

    // streams =
    std.setEditable(false);
    err.setEditable(false);

    h.with("buttons", new FlowLayout(), BorderLayout.PAGE_END).add("button", activeButton);
  }
Beispiel #18
0
  private synchronized void setNumExecutors(int n) {
    if (numExecutors == n) return; // no-op

    int diff = n - numExecutors;
    this.numExecutors = n;

    if (diff < 0) {
      // send signal to all idle executors to potentially kill them off
      for (Executor e : executors) if (e.isIdle()) e.interrupt();
    } else {
      // if the number is increased, add new ones
      addNewExecutorIfNecessary();
    }
  }
  @SuppressWarnings("unchecked")
  public Map<String, String> getBuildVariables(AbstractBuild build, EnvInjectLogger logger)
      throws EnvInjectException {
    Map<String, String> result = new HashMap<String, String>();

    // Add build process variables
    result.putAll(build.getCharacteristicEnvVars());

    try {
      //            EnvVars envVars = new EnvVars();
      //            for (EnvironmentContributor ec : EnvironmentContributor.all()) {
      //                ec.buildEnvironmentFor(build, envVars, new LogTaskListener(LOG, Level.ALL));
      //                result.putAll(envVars);
      //            }

      JDK jdk = build.getProject().getJDK();
      if (jdk != null) {
        Node node = build.getBuiltOn();
        if (node != null) {
          jdk = jdk.forNode(node, logger.getListener());
        }
        jdk.buildEnvVars(result);
      }
    } catch (IOException ioe) {
      throw new EnvInjectException(ioe);
    } catch (InterruptedException ie) {
      throw new EnvInjectException(ie);
    }

    Executor e = build.getExecutor();
    if (e != null) {
      result.put("EXECUTOR_NUMBER", String.valueOf(e.getNumber()));
    }

    String rootUrl = Hudson.getInstance().getRootUrl();
    if (rootUrl != null) {
      result.put("BUILD_URL", rootUrl + build.getUrl());
      result.put("JOB_URL", rootUrl + build.getParent().getUrl());
    }

    // Add build variables such as parameters, plugins contributions, ...
    result.putAll(build.getBuildVariables());

    // Retrieve triggered cause
    Map<String, String> triggerVariable = new BuildCauseRetriever().getTriggeredCause(build);
    result.putAll(triggerVariable);

    return result;
  }
  /** {@inheritDoc} */
  @Override
  public void run() {
    List<Grid> clientGrids = runGrid();

    assert clientGrids.size() == clientNodes;

    int threadsCnt = clientNodes * threadsPerClient;

    Executor e = Executors.newFixedThreadPool(threadsCnt);

    for (Grid grid : clientGrids) {
      for (int j = 0; j < threadsPerClient; j++)
        e.execute(new GridJobLoadTestSubmitter(grid, taskParams, cancelRate, submitDelay));
    }
  }
 public void submit(final EventHandler eh) {
   Executor executor = getExecutor(getExecutorServiceType(eh.getEventType()));
   if (executor == null) {
     // This happens only when events are submitted after shutdown() was
     // called, so dropping them should be "ok" since it means we're
     // shutting down.
     LOG.error(
         "Cannot submit ["
             + eh
             + "] because the executor is missing."
             + " Is this process shutting down?");
   } else {
     executor.submit(eh);
   }
 }
 public void execute() throws ExecuteException {
   if (executor == null) {
     throw new ExecuteException(name + ": is not defined");
   } else {
     executor.execute();
   }
 }
Beispiel #23
0
  /**
   * Schedules runnable task for execution.
   *
   * @param w Runnable task.
   * @throws GridException Thrown if any exception occurred.
   */
  @SuppressWarnings({"CatchGenericClass", "ProhibitedExceptionThrown"})
  public void execute(final GridWorker w) throws GridException {
    workers.add(w);

    try {
      exec.execute(
          new Runnable() {
            @Override
            public void run() {
              try {
                w.run();
              } finally {
                workers.remove(w);
              }
            }
          });
    } catch (RejectedExecutionException e) {
      workers.remove(w);

      throw new GridComputeExecutionRejectedException(
          "Failed to execute worker due to execution rejection.", e);
    } catch (RuntimeException e) {
      workers.remove(w);

      throw new GridException("Failed to execute worker due to runtime exception.", e);
    } catch (Error e) {
      workers.remove(w);

      throw e;
    }
  }
 /** Do Unwind state transition. */
 @Override
 protected void i_unwind(Executor e) throws CALExecutorException {
   // Simply push the single argument of this application
   // and update the current instruction pointer.
   e.stack.push(record);
   e.setIP(getCode());
 }
Beispiel #25
0
  void refresh() {
    Command cmd = model.getCommand();
    stateLabel.setForeground(ui.getColor(cmd));
    stateLabel.setText(ui.getState(cmd));

    activeButton.setAction(getActionMap().get(cmd.isRunning() ? "stop" : "close"));
  }
 public void restart() {
   final Project project =
       PlatformDataKeys.PROJECT.getData(
           DataManager.getInstance().getDataContext(myDescriptor.getComponent()));
   if (ExecutorRegistry.getInstance()
       .isStarting(project, myExecutor.getId(), myRunner.getRunnerId())) {
     return;
   }
   try {
     final ExecutionEnvironment old = myEnvironment;
     myRunner.execute(
         myExecutor,
         new ExecutionEnvironment(
             old.getRunProfile(),
             old.getExecutionTarget(),
             project,
             old.getRunnerSettings(),
             old.getConfigurationSettings(),
             myDescriptor,
             old.getRunnerAndConfigurationSettings()));
   } catch (RunCanceledByUserException ignore) {
   } catch (ExecutionException e1) {
     Messages.showErrorDialog(
         project, e1.getMessage(), ExecutionBundle.message("restart.error.message.title"));
   }
 }
Beispiel #27
0
 @Override
 public Object queryForObject(SqlStatement sql, Class requiredType) throws DatabaseException {
   if (sql instanceof SelectFromDatabaseChangeLogLockStatement) {
     return false;
   }
   return delegatedReadExecutor.queryForObject(sql, requiredType);
 }
Beispiel #28
0
 private void reallyStart() {
   synchronized (syncLock) {
     threadStarted = true;
   }
   if (logMINOR) Logger.minor(this, "Starting thread... " + name + " : " + runner);
   realExecutor.execute(runner, name);
 }
  public static void main(String[] args) throws IOException {
    ServerSocket socket = new ServerSocket(9001);

    while (true) {
      final Socket connection = socket.accept();
      exec.execute(new ConnectionHandlerTask(connection));
    }
  }
 boolean isEnabled() {
   ProcessHandler processHandler = myDescriptor.getProcessHandler();
   boolean isTerminating = processHandler != null && processHandler.isProcessTerminating();
   boolean isStarting =
       ExecutorRegistry.getInstance()
           .isStarting(myEnvironment.getProject(), myExecutor.getId(), myRunner.getRunnerId());
   return !isStarting && !isTerminating;
 }