Performs task specific checks if the
respective task has been configured properly.

@param invokable
an instance of the task this vertex represents
@throws IllegalConfigurationException
thrown if the respective tasks is not configured properly
331164
public void checkConfiguration(final AbstractInvokable invokable) throws IllegalConfigurationException {

		if (invokable == null) {
			throw new IllegalArgumentException("Argument invokable is null");
		}

		// see if the task itself has a valid configuration
		// because this is user code running on the master, we embed it in a catch-all block
		try {
			invokable.checkConfiguration();
		} catch (IllegalConfigurationException icex) {
			throw icex; // simply forward
		} catch (Throwable t) {
			throw new IllegalConfigurationException("Checking the invokable's configuration caused an error: "
				+ StringUtils.stringifyException(t));
		}
	}
699789
public void submitTask(final String evaluatorConfiguration, final String taskConfiguration) {
    final Configuration contextConfiguration = ContextConfiguration.CONF
        .set(ContextConfiguration.IDENTIFIER, "RootContext_" + this.getId())
        .build();
    final String contextConfigurationString = this.configurationSerializer.toString(contextConfiguration);
    this.launchWithConfigurationString(
        evaluatorConfiguration, contextConfigurationString,  Optional.<String>empty(), Optional.of(taskConfiguration));
  }
308913
private void checkOrInvokeValidStartMethod(final boolean invoke, final ClusterId clusterId) throws IllegalStateException {
        Method startMethod = null;
        for (final Method method : prototype.getClass().getDeclaredMethods()) {
            if (method.isAnnotationPresent(Start.class)) {
                if (startMethod != null)
                    throw new IllegalStateException("Multiple methods on the message processor of type\""
                            + SafeString.valueOf(prototype)
                            + "\" is identified as a Start method. Please annotate at most one method using @Start.");
                startMethod = method;
            }
        }

        // if the start method takes a ClusterId or ClusterDefinition then pass it.
        if (startMethod != null) {
            final Class<?>[] parameterTypes = startMethod.getParameterTypes();
            boolean takesClusterId = false;
            if (parameterTypes != null && parameterTypes.length == 1) {
                if (ClusterId.class.isAssignableFrom(parameterTypes[0]))
                    takesClusterId = true;
                else {
                    throw new IllegalStateException("The method \"" + startMethod.getName() + "\" on " + SafeString.objectDescription(prototype) +
                            " is annotated with the @" + Start.class.getSimpleName() + " annotation but doesn't have the correct signature. " +
                            "It needs to either take no parameters or take a single " + ClusterId.class.getSimpleName() + " parameter.");
                }
            } else if (parameterTypes != null && parameterTypes.length > 1) {
                throw new IllegalStateException("The method \"" + startMethod.getName() + "\" on " + SafeString.objectDescription(prototype) +
                        " is annotated with the @" + Start.class.getSimpleName() + " annotation but doesn't have the correct signature. " +
                        "It needs to either take no parameters or take a single " + ClusterId.class.getSimpleName() + " parameter.");
            }
            if (invoke) {
                try {
                    if (takesClusterId)
                        startMethod.invoke(prototype, clusterId);
                    else
                        startMethod.invoke(prototype);
                } catch (final Exception e) {
                    LOGGER.error(MarkerFactory.getMarker("FATAL"), "can't run MP initializer " + startMethod.getName(), e);
                }
            }
        }
    }
225176
void checkThrown() throws SSLException {
        synchronized (thrownLock) {
            if (thrown != null) {

                String msg = thrown.getMessage();

                if (msg == null) {
                    msg = "Delegated task threw Exception/Error";
                }

                /*
                 * See what the underlying type of exception is.  We should
                 * throw the same thing.  Chain thrown to the new exception.
                 */
                Exception e = thrown;
                thrown = null;

                if (e instanceof RuntimeException) {
                    throw (RuntimeException)
                        new RuntimeException(msg).initCause(e);
                } else if (e instanceof SSLHandshakeException) {
                    throw (SSLHandshakeException)
                        new SSLHandshakeException(msg).initCause(e);
                } else if (e instanceof SSLKeyException) {
                    throw (SSLKeyException)
                        new SSLKeyException(msg).initCause(e);
                } else if (e instanceof SSLPeerUnverifiedException) {
                    throw (SSLPeerUnverifiedException)
                        new SSLPeerUnverifiedException(msg).initCause(e);
                } else if (e instanceof SSLProtocolException) {
                    throw (SSLProtocolException)
                        new SSLProtocolException(msg).initCause(e);
                } else {
                    /*
                     * If it's SSLException or any other Exception,
                     * we'll wrap it in an SSLException.
                     */
                    throw (SSLException)
                        new SSLException(msg).initCause(e);
                }
            }
        }
    }
458306
public Object invokeOperation(Map<String, String[]> parameterMap) throws JMException {
        MBeanParameterInfo[] parameterInfoArray = operationInfo.getSignature();

        Object[] values = new Object[parameterInfoArray.length];
        String[] types = new String[parameterInfoArray.length];

        MBeanValueConverter valueConverter = createMBeanValueConverter(parameterMap);

        for (int parameterNum = 0; parameterNum < parameterInfoArray.length; parameterNum++) {
            MBeanParameterInfo parameterInfo = parameterInfoArray[parameterNum];
            String type = parameterInfo.getType();
            types[parameterNum] = type;
            values[parameterNum] = valueConverter.convertParameterValue(parameterInfo.getName(), type);
        }

        return mBeanServer.invoke(objectName, operationInfo.getName(), values, types);
    }
542969
@Override
  public SerializableVoid runTask(ReplicateConfig config, SerializableVoid arg,
      RunTaskContext context) throws Exception {
    JobUtils.loadBlock(context.getFileSystem(), context.getFsContext(),
        config.getPath(), config.getBlockId());
    return null;
  }
588125
public void start(String taskName) throws IllegalStateException {
        this.lastTaskInfo = new TaskInfo(taskName, System.currentTimeMillis());
        this.runningTasks.push(lastTaskInfo);
        ++this.taskCount;
        this.running = true;
        this.currentTaskName = taskName;
    }
29556
@Override
	public void invoke() throws Exception {
		this.headEventReader = new MutableRecordReader<>(
				getEnvironment().getInputGate(0),
				getEnvironment().getTaskManagerInfo().getTmpDirectories());

		TaskConfig taskConfig = new TaskConfig(getTaskConfiguration());

		// store all aggregators
		this.aggregators = new HashMap<>();
		for (AggregatorWithName<?> aggWithName : taskConfig.getIterationAggregators(getUserCodeClassLoader())) {
			aggregators.put(aggWithName.getName(), aggWithName.getAggregator());
		}

		// store the aggregator convergence criterion
		if (taskConfig.usesConvergenceCriterion()) {
			convergenceCriterion = taskConfig.getConvergenceCriterion(getUserCodeClassLoader());
			convergenceAggregatorName = taskConfig.getConvergenceCriterionAggregatorName();
			Preconditions.checkNotNull(convergenceAggregatorName);
		}

		// store the default aggregator convergence criterion
		if (taskConfig.usesImplicitConvergenceCriterion()) {
			implicitConvergenceCriterion = taskConfig.getImplicitConvergenceCriterion(getUserCodeClassLoader());
			implicitConvergenceAggregatorName = taskConfig.getImplicitConvergenceCriterionAggregatorName();
			Preconditions.checkNotNull(implicitConvergenceAggregatorName);
		}

		maxNumberOfIterations = taskConfig.getNumberOfIterations();

		// set up the event handler
		int numEventsTillEndOfSuperstep = taskConfig.getNumberOfEventsUntilInterruptInIterativeGate(0);
		eventHandler = new SyncEventHandler(numEventsTillEndOfSuperstep, aggregators,
				getEnvironment().getUserClassLoader());
		headEventReader.registerTaskEventListener(eventHandler, WorkerDoneEvent.class);

		IntValue dummy = new IntValue();

		while (!terminationRequested()) {

			if (log.isInfoEnabled()) {
				log.info(formatLogString("starting iteration [" + currentIteration + "]"));
			}

			// this call listens for events until the end-of-superstep is reached
			readHeadEventChannel(dummy);

			if (log.isInfoEnabled()) {
				log.info(formatLogString("finishing iteration [" + currentIteration + "]"));
			}

			if (checkForConvergence()) {
				if (log.isInfoEnabled()) {
					log.info(formatLogString("signaling that all workers are to terminate in iteration ["
						+ currentIteration + "]"));
				}

				requestTermination();
				sendToAllWorkers(new TerminationEvent());
			} else {
				if (log.isInfoEnabled()) {
					log.info(formatLogString("signaling that all workers are done in iteration [" + currentIteration
						+ "]"));
				}

				AllWorkersDoneEvent allWorkersDoneEvent = new AllWorkersDoneEvent(aggregators);
				sendToAllWorkers(allWorkersDoneEvent);

				// reset all aggregators
				for (Aggregator<?> agg : aggregators.values()) {
					agg.reset();
				}
				currentIteration++;
			}
		}
	}
1322565
public static void invokeTask (String name, Task task, TaskObserver observer)
    {
        // create a task runner and stick it in our task table
        TaskRunner runner = new TaskRunner(name, task, observer);
        _tasks.put(name, runner);
        // then start the runner up
        runner.start();
    }
1294014
public void configureTaskQuery(TaskQueryImpl query) {
    configureQuery(query);

    if(query.getAuthCheck().isAuthorizationCheckEnabled()) {

      // necessary authorization check when the task is part of
      // a running process instance

      CompositePermissionCheck permissionCheck = new PermissionCheckBuilder()
              .disjunctive()
              .atomicCheck(TASK, "RES.ID_", READ)
              .atomicCheck(PROCESS_DEFINITION, "PROCDEF.KEY_", READ_TASK)
              .build();
        addPermissionCheck(query.getAuthCheck(), permissionCheck);
    }
  }
1249718
@Override
    @FFDCIgnore(value = { RejectedExecutionException.class })
    public <T> T invokeAny(Collection<? extends Callable<T>> tasks, PolicyTaskCallback[] callbacks) throws InterruptedException, ExecutionException {
        int taskCount = tasks.size();

        // Special case to run a single task on the current thread if we can acquire a permit, if a permit is required
        if (taskCount == 1) {
            boolean havePermit = false;
            if (maxPolicy == MaxPolicy.loose || (havePermit = maxConcurrencyConstraint.tryAcquire())) // use current thread
                try {
                    if (state.get() != State.ACTIVE)
                        throw new RejectedExecutionException(Tr.formatMessage(tc, "CWWKE1202.submit.after.shutdown", identifier));

                    // startTimeout does not apply because the task starts immediately
                    PolicyTaskFutureImpl<T> taskFuture = new PolicyTaskFutureImpl<T>(this, tasks.iterator().next(), callbacks == null ? null : callbacks[0], -1);
                    taskFuture.accept(true);
                    runTask(taskFuture);

                    // raise InterruptedException if current thread is interrupted
                    taskFuture.throwIfInterrupted();

                    return taskFuture.get();
                } finally {
                    if (havePermit)
                        transferOrReleasePermit();
                }
        } else if (taskCount == 0)
            throw new IllegalArgumentException();

        InvokeAnyLatch latch = new InvokeAnyLatch(taskCount);
        ArrayList<PolicyTaskFutureImpl<T>> futures = new ArrayList<PolicyTaskFutureImpl<T>>(taskCount);
        try {
            // create futures in advance, which gives the callback an opportunity to reject
            int t = 0;
            for (Callable<T> task : tasks) {
                PolicyTaskCallback callback = callbacks == null ? null : callbacks[t++];
                PolicyExecutorImpl executor = callback == null ? this : (PolicyExecutorImpl) callback.getExecutor(this);
                long startTimeoutNS = callback == null ? startTimeout : callback.getStartTimeout(executor.startTimeout);
                futures.add(new PolicyTaskFutureImpl<T>(executor, task, callback, startTimeoutNS, latch));
            }

            // enqueue all tasks
            for (PolicyTaskFutureImpl<T> taskFuture : futures) {
                // check if done before enqueuing more tasks
                if (latch.getCount() == 0)
                    break;

                taskFuture.executor.enqueue(taskFuture, taskFuture.executor.maxWaitForEnqueueNS.get(), false); // never run on the current thread because it would prevent timeout
            }

            // wait for completion
            return latch.await(-1, futures);
        } catch (RejectedExecutionException x) {
            if (x.getCause() instanceof InterruptedException) {
                throw (InterruptedException) x.getCause();
            } else
                throw x;
        } catch (TimeoutException x) {
            throw new RuntimeException(x); // should be unreachable with infinite timeout
        } finally {
            for (Future<?> f : futures)
                f.cancel(true);
        }
    }
652731
public void invokeEndpointMethod(final Runnable invocation) {
        try {
            invokeEndpointTask.call(null, invocation);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
794322
@SuppressWarnings("unchecked")
    <T> ICompletableFuture<Map<Integer, T>> invokeAsync() {
        assert !invoked : "already invoked";
        invoked = true;
        ensureNotCallingFromPartitionOperationThread();
        invokeOnAllPartitions();
        return future;
    }
1357425
@Override
  protected boolean requestInvoke(FrameBuffer frameBuffer) {
    Runnable invocation = getRunnable(frameBuffer);
    if (invoker != null) {
      try {
        invoker.execute(invocation);
        return true;
      } catch (RejectedExecutionException rx) {
        LOGGER.warn("ExecutorService rejected execution!", rx);
        return false;
      }
    } else {
      // Invoke on the caller's thread
      invocation.run();
      return true;
    }
  }
259087
private void configure(OperationId operationId, Method method, ServiceExecutor executor) {
    if (method.getReturnType() == Void.TYPE) {
      if (method.getParameterTypes().length == 0) {
        executor.register(operationId, () -> {
          try {
            method.invoke(this);
          } catch (IllegalAccessException | InvocationTargetException e) {
            throw new PrimitiveException.ServiceException(e);
          }
        });
      } else {
        executor.register(operationId, args -> {
          try {
            method.invoke(this, (Object[]) args.value());
          } catch (IllegalAccessException | InvocationTargetException e) {
            throw new PrimitiveException.ServiceException(e);
          }
        });
      }
    } else {
      if (method.getParameterTypes().length == 0) {
        executor.register(operationId, () -> {
          try {
            return method.invoke(this);
          } catch (IllegalAccessException | InvocationTargetException e) {
            throw new PrimitiveException.ServiceException(e);
          }
        });
      } else {
        executor.register(operationId, args -> {
          try {
            return method.invoke(this, (Object[]) args.value());
          } catch (IllegalAccessException | InvocationTargetException e) {
            throw new PrimitiveException.ServiceException(e);
          }
        });
      }
    }
  }
798787
public final void registerTaskExecutor(TaskExecutor taskExecutor) {
	if (taskExecutor == null) {
	  throw new TaskExeception(TaskExecutor.class.getSimpleName() + "  NULL");
	}
	this.taskExecutor = taskExecutor;
  }
1089047
public boolean cancelInvocation(Long invokeId) throws TCAPException {
        if (this.previewMode)
            return false;

        try {
            this.dialogLock.lock();
            int index = getIndexFromInvokeId(invokeId);
            if (index < 0 || index >= this.operationsSent.length) {
                throw new TCAPException("Wrong invoke id passed.");
            }

            // lookup through send buffer.
            for (index = 0; index < this.scheduledComponentList.size(); index++) {
                Component cr = this.scheduledComponentList.get(index);
                if (cr.getType() == ComponentType.Invoke && cr.getInvokeId().equals(invokeId)) {
                    // lucky
                    // TCInvokeRequestImpl invoke = (TCInvokeRequestImpl) cr;
                    // there is no notification on cancel?
                    this.scheduledComponentList.remove(index);
                    ((InvokeImpl) cr).stopTimer();
                    ((InvokeImpl) cr).setState(OperationState.Idle);
                    return true;
                }
            }

            return false;
        } finally {
            this.dialogLock.unlock();
        }
    }