Gets the java runner for execute_java and execute_java_async.
972752
def _get_runner(classpath, main, jvm_options, args, executor,
               cwd, distribution,
               create_synthetic_jar, synthetic_jar_dir):
  """"""

  executor = executor or SubprocessExecutor(distribution)

  safe_cp = classpath
  if create_synthetic_jar:
    safe_cp = safe_classpath(classpath, synthetic_jar_dir)
    logger.debug('Bundling classpath {} into {}'.format(':'.join(classpath), safe_cp))

  return executor.runner(safe_cp, main, args=args, jvm_options=jvm_options, cwd=cwd)
725128
def find_runner(program):
    
    if os.path.isfile(program) and not os.access(program, os.X_OK):
        # program is a path to a non-executable file
        try:
            opened = open(program)
        except PermissionError:
            return None
        first_line = opened.readline().strip()
        if first_line.startswith('#!'):
            return shlex.split(first_line[2:])
        if program.endswith('.py'):
            return [sys.executable]
    return None
444540
def _get_runner(self, conf):
        '''
        
        '''
        conf = self._setup_fun_config(copy.deepcopy(conf))
        if not getattr(self, '_runner', None):
            self._runner = salt.cli.support.localrunner.LocalRunner(conf)
        else:
            self._runner.opts = conf
        return self._runner
418016
public InternalRunner create(Class<?> klass, Supplier<MockitoTestListener> listenerSupplier) throws InvocationTargetException {
        try {
            String runnerClassName = "org.mockito.internal.runners.DefaultInternalRunner";
            //Warning: I'm using String literal on purpose!
            //When JUnit is not on classpath, we want the code to throw exception here so that we can catch it
            //If we statically link the class, we will get Error when class is loaded
            return new RunnerProvider().newInstance(runnerClassName, klass, listenerSupplier);
        } catch (InvocationTargetException e) {
            if (!hasTestMethods(klass)) {
                throw new MockitoException(
                    "\n" +
                    "\n" +
                    "No tests found in " + klass.getSimpleName() + "\n" +
                    "Is the method annotated with @Test?\n" +
                    "Is the method public?\n"
                    , e);
            }
            throw e;
        } catch (Throwable t) {
            throw new MockitoException(
                    "\n" +
                    "\n" +
                    "MockitoRunner can only be used with JUnit 4.5 or higher.\n" +
                    "You can upgrade your JUnit version or write your own Runner (please consider contributing your runner to the Mockito community).\n" +
                    "Bear in mind that you can still enjoy all features of the framework without using runners (they are completely optional).\n" +
                    "If you get this error despite using JUnit 4.5 or higher then please report this error to the mockito mailing list.\n"
                    , t);
        }
    }
1158791
@Override
    public GroovyRunner get(Object key) {
        if (key == null) {
            return null;
        }
        Map<String, GroovyRunner> map = getMap();
        readLock.lock();
        try {
            return map.get(key);
        } finally {
            readLock.unlock();
        }
    }
586378
def execute(self):
    

    jvm_resolve_subsystem = JvmResolveSubsystem.global_instance()
    if jvm_resolve_subsystem.get_options().resolver != 'coursier':
      return

    # executor = self.create_java_executor()
    classpath_products = self.context.products.get_data('compile_classpath',
                                                        init_func=ClasspathProducts.init_func(
                                                          self.get_options().pants_workdir))
    executor = self.create_java_executor()
    self.resolve(self.context.targets(), classpath_products, sources=False, javadoc=False, executor=executor)
1333091
public Class getJavaClass()
  {
    try {
      ClassLoader loader = Thread.currentThread().getContextClassLoader();
      
      return Class.forName(getName(), false, loader);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
194808
private Map<Optional<Executor>, List<ExecutableFlow>> getFlowToExecutorMap() {
    final HashMap<Optional<Executor>, List<ExecutableFlow>> exFlowMap =
        new HashMap<>();

    for (final Pair<ExecutionReference, ExecutableFlow> runningFlow : this.runningExecutions.get()
        .values()) {
      final ExecutionReference ref = runningFlow.getFirst();
      final ExecutableFlow flow = runningFlow.getSecond();
      final Optional<Executor> executor = ref.getExecutor();

      // We can set the next check time to prevent the checking of certain
      // flows.
      if (ref.getNextCheckTime() >= DateTime.now().getMillis()) {
        continue;
      }

      List<ExecutableFlow> flows = exFlowMap.get(executor);
      if (flows == null) {
        flows = new ArrayList<>();
        exFlowMap.put(executor, flows);
      }

      flows.add(flow);
    }

    return exFlowMap;
  }
1276526
def runner(self, jvm_options=None, args=None, executor=None):
    """"""
    args = args or []
    if self._ivy_settings and '-settings' not in args:
      args = ['-settings', self._ivy_settings] + args

    options = list(jvm_options) if jvm_options else []
    if self._ivy_resolution_cache_dir and '-cache' not in args:
      # TODO(John Sirois): Currently this is a magic property to support hand-crafted <caches/> in
      # ivysettings.xml.  Ideally we'd support either simple -caches or these hand-crafted cases
      # instead of just hand-crafted.  Clean this up by taking over ivysettings.xml and generating
      # it from BUILD constructs.
      options += ['-Divy.cache.dir={}'.format(self._ivy_resolution_cache_dir)]
    options += self._extra_jvm_options

    executor = executor or SubprocessExecutor(DistributionLocator.cached())
    if not isinstance(executor, Executor):
      raise ValueError('The executor argument must be an Executor instance, given {} of type {}'.format(
                         executor, type(executor)))

    return executor.runner(classpath=self._classpath, main='org.apache.ivy.Main',
                           jvm_options=options, args=args)
183990
public static String getSparkExecutorId(){
        if(sparkExecutorId != null)
            return sparkExecutorId;

        synchronized (SparkUtils.class){
            //re-check, in case some other thread set it while waiting for lock
            if(sparkExecutorId != null)
                return sparkExecutorId;

            String s = System.getProperty("sun.java.command");
            if(s == null || s.isEmpty() || !s.contains("executor-id")){
                sparkExecutorId = UIDProvider.getJVMUID();
                return sparkExecutorId;
            }

            int idx = s.indexOf("executor-id");
            String sub = s.substring(idx);
            String[] split = sub.split(" ");
            if(split.length < 2){
                sparkExecutorId = UIDProvider.getJVMUID();
                return sparkExecutorId;
            }
            sparkExecutorId = split[1];
            return sparkExecutorId;
        }
    }
254975
def _get_java_env(self):
        ""
        env = super(_StreamingAnalyticsSubmitter, self)._get_java_env()
        vcap = streamsx.rest._get_vcap_services(self._vcap_services)
        env['VCAP_SERVICES'] = json.dumps(vcap)
        return env
288153
public RunnerDetail getRunnerDetail(Integer runnerId) throws GitLabApiException {

        if (runnerId == null) {
            throw new RuntimeException("runnerId cannot be null");
        }

        Response response = get(Response.Status.OK, null, "runners", runnerId);
        return (response.readEntity(RunnerDetail.class));
    }
943229
def _local_run(self, run_conf):
        '''
        
        '''
        try:
            ret = self._get_runner(run_conf).run()
        except SystemExit:
            ret = 'Runner is not available at this moment'
            self.out.error(ret)
        except Exception as ex:
            ret = 'Unhandled exception occurred: {}'.format(ex)
            log.debug(ex, exc_info=True)

        return ret
597252
function Runner(emitter, config) {
  debug('RUNNER INIT');
  var dotStrider = path.join(process.env.HOME || '/', '.strider');
  this.config = _.extend({
    pty: false,
    io: new EventEmitter2({
      wildcard: true
    }),
    processJob: core.process,
    pluginDir: path.join(__dirname, '../node_modules'),
    dataDir: process.env.STRIDER_CLONE_DEST || dotStrider,
    concurrentJobs: parseInt(process.env.CONCURRENT_JOBS || '1', 10) || 1,
    defaultRecentBuilds: parseInt(process.env.DEFAULT_RECENT_BUILDS || '1', 10) || 1
  }, config);
  this.emitter = emitter;
  this.queue = new JobQueue(this.processJob.bind(this), this.config.concurrentJobs);
  this.io = this.config.io;
  this.callbackMap = {};
  this.hooks = [];
  this.jobdata = new JobData(this.io);
  this.attach();
}
848343
def _run_runner(self):
        '''
        
        '''
        import salt.minion
        ret = {}
        low = {'fun': self.opts['fun']}
        try:
            # Allocate a jid
            async_pub = self._gen_async_pub()
            self.jid = async_pub['jid']

            fun_args = salt.utils.args.parse_input(
                    self.opts['arg'],
                    no_parse=self.opts.get('no_parse', []))

            verify_fun(self.functions, low['fun'])
            args, kwargs = salt.minion.load_args_and_kwargs(
                self.functions[low['fun']],
                fun_args)
            low['arg'] = args
            low['kwarg'] = kwargs

            if self.opts.get('eauth'):
                if 'token' in self.opts:
                    try:
                        with salt.utils.files.fopen(os.path.join(self.opts['cachedir'], '.root_key'), 'r') as fp_:
                            low['key'] = salt.utils.stringutils.to_unicode(fp_.readline())
                    except IOError:
                        low['token'] = self.opts['token']

                # If using eauth and a token hasn't already been loaded into
                # low, prompt the user to enter auth credentials
                if 'token' not in low and 'key' not in low and self.opts['eauth']:
                    # This is expensive. Don't do it unless we need to.
                    import salt.auth
                    resolver = salt.auth.Resolver(self.opts)
                    res = resolver.cli(self.opts['eauth'])
                    if self.opts['mktoken'] and res:
                        tok = resolver.token_cli(
                                self.opts['eauth'],
                                res
                                )
                        if tok:
                            low['token'] = tok.get('token', '')
                    if not res:
                        log.error('Authentication failed')
                        return ret
                    low.update(res)
                    low['eauth'] = self.opts['eauth']
            else:
                user = salt.utils.user.get_specific_user()

            if low['fun'] in ['state.orchestrate', 'state.orch', 'state.sls']:
                low['kwarg']['orchestration_jid'] = async_pub['jid']

            # Run the runner!
            if self.opts.get('async', False):
                if self.opts.get('eauth'):
                    async_pub = self.cmd_async(low)
                else:
                    async_pub = self.asynchronous(self.opts['fun'],
                                                  low,
                                                  user=user,
                                                  pub=async_pub)

                # by default: info will be not enough to be printed out !
                log.warning(
                    'Running in asynchronous mode. Results of this execution may '
                    'be collected by attaching to the master event bus or '
                    'by examing the master job cache, if configured. '
                    'This execution is running under tag %s', async_pub['tag']
                )
                return async_pub['jid']  # return the jid

            # otherwise run it in the main process
            if self.opts.get('eauth'):
                ret = self.cmd_sync(low)
                if isinstance(ret, dict) and set(ret) == {'data', 'outputter'}:
                    outputter = ret['outputter']
                    ret = ret['data']
                else:
                    outputter = None
                display_output(ret, outputter, self.opts)
            else:
                ret = self._proc_function(self.opts['fun'],
                                          low,
                                          user,
                                          async_pub['tag'],
                                          async_pub['jid'],
                                          daemonize=False)
        except salt.exceptions.SaltException as exc:
            evt = salt.utils.event.get_event('master', opts=self.opts)
            evt.fire_event({'success': False,
                            'return': '{0}'.format(exc),
                            'retcode': 254,
                            'fun': self.opts['fun'],
                            'fun_args': fun_args,
                            'jid': self.jid},
                           tag='salt/run/{0}/ret'.format(self.jid))
            # Attempt to grab documentation
            if 'fun' in low:
                ret = self.get_docs('{0}*'.format(low['fun']))
            else:
                ret = None

            # If we didn't get docs returned then
            # return the `not availble` message.
            if not ret:
                ret = '{0}'.format(exc)
            if not self.opts.get('quiet', False):
                display_output(ret, 'nested', self.opts)
        else:
            # If we don't have any values in ret by now, that's a problem.
            # Otherwise, we shouldn't be overwriting the retcode.
            if not ret:
                ret = {
                    'retcode': salt.defaults.exitcodes.EX_SOFTWARE,
                }
        log.debug('Runner return: %s', ret)

        return ret
1004641
private Runnable getRunnable(ClassLoaderLeakPreventor preventor, Thread thread) {
    if(oracleTarget == null && ibmRunnable == null) { // Not yet initialized
      oracleTarget = preventor.findField(Thread.class, "target"); // Sun/Oracle JRE
      ibmRunnable = preventor.findField(Thread.class, "runnable"); // IBM JRE       
    }

    return (oracleTarget != null) ? (Runnable) preventor.getFieldValue(oracleTarget, thread) : // Sun/Oracle JRE  
        (Runnable) preventor.getFieldValue(ibmRunnable, thread);   // IBM JRE
  }
237719
def runner(coro):
    """"""

    @wraps(coro)
    def inner(self, *args, **kwargs):
        if self.mode == 'async':
            return coro(self, *args, **kwargs)
        return self._loop.run_until_complete(coro(self, *args, **kwargs))

    return inner