TODO: We ideally need to update ProcessTree APIs to Support Long (JENKINS-53799).
353535
public static int pid(@Nonnull Process proc) {
            try {
                if (JAVA8_PID_FIELD != null) {
                    return JAVA8_PID_FIELD.getInt(proc);
                } else {
                    long pid = (long)JAVA9_PID_METHOD.invoke(proc);
                    if (pid > Integer.MAX_VALUE) {
                        throw new IllegalAccessError("Java 9+ support error (JENKINS-53799). PID is out of Jenkins API bounds: " + pid);
                    }
                    return (int)pid;
                }
            } catch (IllegalAccessException | InvocationTargetException e) { // impossible
                IllegalAccessError x = new IllegalAccessError();
                x.initCause(e);
                throw x;
            }
        }
333125
@SuppressWarnings("squid:S1166") //For the UnsupportedOperationException
    private Script build(CharStream cs) throws ScriptBuilderException {

        Script v = new Script();

        ANTLRBtrplaceSL2Lexer lexer = new ANTLRBtrplaceSL2Lexer(cs);

        ErrorReporter errorReporter = errBuilder.build(v);

        lexer.setErrorReporter(errorReporter);
        CommonTokenStream tokens = new CommonTokenStream(lexer);

        ANTLRBtrplaceSL2Parser parser = new ANTLRBtrplaceSL2Parser(tokens);
        parser.setErrorReporter(errorReporter);

        SymbolsTable t = new SymbolsTable();

        parser.setTreeAdaptor(new BtrPlaceTreeAdaptor(v, model, namingServiceNodes, namingServiceVMs, tpls, errorReporter, t, includes, catalog));

        try {
            BtrPlaceTree tree = (BtrPlaceTree) parser.script_decl().getTree();
            if (tree != null) {
                if (tree.token != null) {
                        tree.go(tree); //Single instruction
                } else {
                    for (int i = 0; i < tree.getChildCount(); i++) {
                            tree.getChild(i).go(tree);
                        }
                    }
            }
        } catch (RecognitionException e) {
            throw new ScriptBuilderException(e.getMessage(), e);
        } catch (UnsupportedOperationException e) {
            //We only keep the error message
            errorReporter.append(0, 0, e.getMessage());
        }
        if (!errorReporter.getErrors().isEmpty()) {
            throw new ScriptBuilderException(errorReporter);
        }
        return v;
    }
389674
function buildProcessOptions(processes, logRoot, cmdOptions) {
  return _.flatten(_.map(_.keys(processes), function(procKey) {
    var concurrentCount = parser.parseConcurrencyOpts(cmdOptions)[procKey] || 1;
    return _.map(_.range(concurrentCount), function(index) {
      return {
	id: getID(procKey, index),
	user: cmdOptions.user,
	port: cmdOptions.port,
	processCommand: processes[procKey],
	logRoot: logRoot,
	processName: procKey,
	num: index
      };
    });
  }));
}
699691
@Override
    public void buildEnvironment(Run<?,?> build, EnvVars env) {
        Run run = getRun();
        
        String value = (null == run) ? "UNKNOWN" : Jenkins.getInstance().getRootUrl() + run.getUrl();
        env.put(name, value);

        env.put(name + ".jobName", getJobName());   // undocumented, left for backward compatibility
        env.put(name + "_JOBNAME", getJobName());   // prefer this version

        env.put(name + ".number" , getNumber ());   // same as above
        env.put(name + "_NUMBER" , getNumber ());
        
        // if run is null, default to the standard '#1' display name format
        env.put(name + "_NAME",  (null == run) ? "#" + getNumber() : run.getDisplayName());  // since 1.504

        String buildResult = (null == run || null == run.getResult()) ? "UNKNOWN" : run.getResult().toString();
        env.put(name + "_RESULT",  buildResult);  // since 1.517

        env.put(name.toUpperCase(Locale.ENGLISH),value); // backward compatibility pre 1.345

    }
638444
function (pluginName, customParams, callback) {
      [pluginName, customParams, callback] = doArgs(arguments, ['string', ['object', {}], 'function']);

      const body = `<jenkins><install plugin="${pluginName}" /></jenkins>`;

      doRequest({
        method: 'POST',
        urlPattern: [INSTALL_PLUGIN],
        request: {
          body: body,
          headers: { 'Content-Type': 'text/xml' }
        },
        noparse: true,
        bodyProp: 'plugins'
      }, customParams, callback);
    }
998698
private BuildAuditResponse getBuildJobAuditResponse(CollectorItem buildItem, long beginDate, long endDate, List<CollectorItem> repoItems) {


        BuildAuditResponse buildAuditResponse = new BuildAuditResponse();
        List<CollectorItemConfigHistory> jobConfigHists = collItemConfigHistoryRepository.findByCollectorItemIdAndTimestampIsBetweenOrderByTimestampDesc(buildItem.getId(), beginDate - 1, endDate + 1);

        //Check Jenkins Job config log to validate pr author is not modifying the Prod Job
        //since beginDate and endDate are the same column and between is excluding the edge values, we need to subtract/add a millisec
        buildAuditResponse.setConfigHistory(jobConfigHists);


        if (!CollectionUtils.isEmpty(repoItems)) {
            Build build = buildRepository.findTop1ByCollectorItemIdOrderByTimestampDesc(buildItem.getId());
            if (build != null) {
                List<RepoBranch> repoBranches = build.getCodeRepos();

                List<ParsedRepo> codeRepos = repoItems.stream().map(r -> new ParsedRepo((String)r.getOptions().get("url"), (String)r.getOptions().get("branch"))).collect(Collectors.toList());
                List<ParsedRepo> buildRepos = repoBranches.stream().map(b -> new ParsedRepo(b.getUrl(), b.getBranch())).collect(Collectors.toList());

                List<ParsedRepo> intersection =  codeRepos.stream().filter(buildRepos::contains).collect(Collectors.toList());

                buildAuditResponse.addAuditStatus(CollectionUtils.isEmpty(intersection) ? BuildAuditStatus.BUILD_REPO_MISMATCH : BuildAuditStatus.BUILD_MATCHES_REPO);
            } else {
                buildAuditResponse.addAuditStatus(BuildAuditStatus.NO_BUILD_FOUND);
            }
        }
        Set<String> codeAuthors = CommonCodeReview.getCodeAuthors(repoItems, beginDate, endDate, commitRepository);
        List<String> overlap = jobConfigHists.stream().map(CollectorItemConfigHistory::getUserID).filter(codeAuthors::contains).collect(Collectors.toList());
        buildAuditResponse.addAuditStatus(!CollectionUtils.isEmpty(overlap) ? BuildAuditStatus.BUILD_AUTHOR_EQ_REPO_AUTHOR : BuildAuditStatus.BUILD_AUTHOR_NE_REPO_AUTHOR);
        return buildAuditResponse;
    }
213733
def build_tree(self, rebuild=False):
        

        time_qualifier = self.process_hierarchy.bottom_process.time_qualifier
        process_name = self.process_hierarchy.bottom_process.process_name
        if rebuild or self.build_timeperiod is None:
            timeperiod = settings.settings['synergy_start_timeperiod']
        else:
            timeperiod = self.build_timeperiod

        timeperiod = cast_to_time_qualifier(time_qualifier, timeperiod)
        actual_timeperiod = time_helper.actual_timeperiod(time_qualifier)

        while actual_timeperiod >= timeperiod:
            self.get_node(process_name, timeperiod)
            timeperiod = time_helper.increment_timeperiod(time_qualifier, timeperiod)

        self.build_timeperiod = actual_timeperiod
185497
function buildProcessOptions(processes, logRoot, cmdOptions) {
  return _.flatten(_.map(_.keys(processes), function(procKey) {
    var concurrentCount = parser.parseConcurrencyOpts(cmdOptions)[procKey] || 1;
    var command = processes[procKey];
    return _.map(_.range(concurrentCount), function(index) {
      return {
	port: cmdOptions.port,
	app: cmdOptions.app,
	appName: getProcessName(cmdOptions.app, procKey, index),
	environmentVar: getEnvOpts(command, cmdOptions),
	processCommand: command,
	processName: procKey,
	logRoot: logRoot,
	directory: parser.cmdWorkingDir(cmdOptions),
	user: cmdOptions.user,
	num: index
      };
    });
  }));
}
545826
private byte[] collectProcessResultsBytes(Process process, ProcessBuilder builder,
      SubProcessIOFiles outPutFiles) throws Exception {

    Byte[] results;

    try {

      LOG.debug(String.format("Executing process %s", createLogEntryFromInputs(builder.command())));

      // If process exit value is not 0 then subprocess failed, record logs
      if (process.exitValue() != 0) {
        outPutFiles.copyOutPutFilesToBucket(configuration, FileUtils.toStringParams(builder));
        String log = createLogEntryForProcessFailure(process, builder.command(), outPutFiles);
        throw new Exception(log);
      }

      // If no return file then either something went wrong or the binary is setup incorrectly for
      // the ret file either way throw error
      if (!Files.exists(outPutFiles.resultFile)) {
        String log = createLogEntryForProcessFailure(process, builder.command(), outPutFiles);
        outPutFiles.copyOutPutFilesToBucket(configuration, FileUtils.toStringParams(builder));
        throw new Exception(log);
      }

      // Everything looks healthy return bytes
      return Files.readAllBytes(outPutFiles.resultFile);

    } catch (Exception ex) {
      String log = String.format("Unexpected error runnng process. %s error message was %s",
          createLogEntryFromInputs(builder.command()), ex.getMessage());
      throw new Exception(log);
    }
  }
787956
@Override
    public AnalysisResultFuture run(final AnalysisJob job) throws UnsupportedOperationException {
        logger.info("Validating distributed job: {}", job);

        failIfJobIsUnsupported(job);

        final InjectionManager injectionManager =
                _configuration.getEnvironment().getInjectionManagerFactory().getInjectionManager(_configuration, job);
        final LifeCycleHelper lifeCycleHelper = new LifeCycleHelper(injectionManager, true);
        final RowProcessingPublishers publishers = getRowProcessingPublishers(job, lifeCycleHelper);
        final RowProcessingPublisher publisher = getRowProcessingPublisher(publishers);
        publisher.initializeConsumers(new TaskListener() {
            @Override
            public void onError(final Task task, final Throwable throwable) {
                logger.error("Failed to initialize consumers at master node!", throwable);
            }

            @Override
            public void onComplete(final Task task) {
            }

            @Override
            public void onBegin(final Task task) {
            }
        });

        logger.info("Validation passed! Chunking job for distribution amongst slaves: {}", job);

        // since we always use a SingleThreadedTaskRunner, the above operation
        // will be synchronized/blocking.

        final AnalysisJobMetrics analysisJobMetrics = publishers.getAnalysisJobMetrics();
        _analysisListener.jobBegin(job, analysisJobMetrics);

        final RowProcessingMetrics rowProcessingMetrics = publisher.getRowProcessingMetrics();
        _analysisListener.rowProcessingBegin(job, rowProcessingMetrics);

        final AnalysisResultFuture resultFuture;

        try {
            final int expectedRows = rowProcessingMetrics.getExpectedRows();
            if (expectedRows == 0) {
                logger.info("Expected rows of the job was zero. Job will run on a local virtual slave.");

                // when there are no expected rows we still need to build a
                // single slave job, but run it locally, since the job lifecycle
                // still needs to be guaranteed.
                final DistributedJobContext context = new DistributedJobContextImpl(_configuration, job, 0, 1);

                // use a virtual cluster, which just runs the job locally.
                final VirtualClusterManager localCluster = new VirtualClusterManager(_configuration, 1);
                resultFuture = localCluster.dispatchJob(job, context);
            } else {
                final JobDivisionManager jobDivisionManager = _clusterManager.getJobDivisionManager();
                final int chunks = jobDivisionManager.calculateDivisionCount(job, expectedRows);
                final int rowsPerChunk = (expectedRows + 1) / chunks;

                logger.info(
                        "Expected rows was {}. A total number of {} slave jobs will be built, each of approx. {} rows.",
                        expectedRows, chunks, rowsPerChunk);

                final List<AnalysisResultFuture> results = dispatchJobs(job, chunks, rowsPerChunk, publisher);
                final DistributedAnalysisResultReducer reducer =
                        new DistributedAnalysisResultReducer(job, lifeCycleHelper, publisher, _analysisListener);
                resultFuture = new DistributedAnalysisResultFuture(results, reducer);
            }

        } catch (final RuntimeException e) {
            _analysisListener.errorUnknown(job, e);
            throw e;
        }

        if (!_analysisListener.isEmpty()) {
            awaitAndInformListener(job, analysisJobMetrics, rowProcessingMetrics, resultFuture);
        }

        return resultFuture;
    }
840292
public ConverterServerBuilder processTimeout(long processTimeout, TimeUnit timeUnit) {
        assertNumericArgument(processTimeout, false);
        this.processTimeout = timeUnit.toMillis(processTimeout);
        return this;
    }
1035006
public ProcessDefinitionEntity parseProcess(Element processElement) {
    // reset all mappings that are related to one process definition
    sequenceFlows = new HashMap<String, TransitionImpl>();

    ProcessDefinitionEntity processDefinition = new ProcessDefinitionEntity();

    /*
     * Mapping object model - bpmn xml: processDefinition.id -> generated by
     * processDefinition.key -> bpmn id (required) processDefinition.name ->
     * bpmn name (optional)
     */
    processDefinition.setKey(processElement.attribute("id"));
    processDefinition.setName(processElement.attribute("name"));
    processDefinition.setCategory(rootElement.attribute("targetNamespace"));
    processDefinition.setProperty(PROPERTYNAME_DOCUMENTATION, parseDocumentation(processElement));
    processDefinition.setTaskDefinitions(new HashMap<String, TaskDefinition>());
    processDefinition.setDeploymentId(deployment.getId());
    processDefinition.setProperty(PROPERTYNAME_JOB_PRIORITY, parsePriority(processElement, PROPERTYNAME_JOB_PRIORITY));
    processDefinition.setProperty(PROPERTYNAME_TASK_PRIORITY, parsePriority(processElement, PROPERTYNAME_TASK_PRIORITY));
    processDefinition.setVersionTag(processElement.attributeNS(CAMUNDA_BPMN_EXTENSIONS_NS, "versionTag"));

    try {
      String historyTimeToLive = processElement.attributeNS(CAMUNDA_BPMN_EXTENSIONS_NS, "historyTimeToLive",
          Context.getProcessEngineConfiguration().getHistoryTimeToLive());
      processDefinition.setHistoryTimeToLive(ParseUtil.parseHistoryTimeToLive(historyTimeToLive));
    }
    catch (Exception e) {
      addError(new BpmnParseException(e.getMessage(), processElement, e));
    }

    boolean isStartableInTasklist = isStartable(processElement);
    processDefinition.setStartableInTasklist(isStartableInTasklist);

    LOG.parsingElement("process", processDefinition.getKey());

    parseScope(processElement, processDefinition);

    // Parse any laneSets defined for this process
    parseLaneSets(processElement, processDefinition);

    for (BpmnParseListener parseListener : parseListeners) {
      parseListener.parseProcess(processElement, processDefinition);
    }

    // now we have parsed anything we can validate some stuff
    validateActivities(processDefinition.getActivities());

    //unregister delegates
    for (ActivityImpl activity : processDefinition.getActivities()) {
      activity.setDelegateAsyncAfterUpdate(null);
      activity.setDelegateAsyncBeforeUpdate(null);
    }
    return processDefinition;
  }
957830
static ProcessedLayers process(final InstalledConfiguration conf, final List<File> moduleRoots, final List<File> bundleRoots) throws IOException {
        final ProcessedLayers layers = new ProcessedLayers(conf);
        // Process module roots
        final LayerPathSetter moduleSetter = new LayerPathSetter() {
            @Override
            public boolean setPath(final LayerPathConfig pending, final File root) {
                if (pending.modulePath == null) {
                    pending.modulePath = root;
                    return true;
                }
                return false;
            }
        };
        for (final File moduleRoot : moduleRoots) {
            processRoot(moduleRoot, layers, moduleSetter);
        }
        // Process bundle root
        final LayerPathSetter bundleSetter = new LayerPathSetter() {
            @Override
            public boolean setPath(LayerPathConfig pending, File root) {
                if (pending.bundlePath == null) {
                    pending.bundlePath = root;
                    return true;
                }
                return false;
            }
        };
        for (final File bundleRoot : bundleRoots) {
            processRoot(bundleRoot, layers, bundleSetter);
        }
//        if (conf.getInstalledLayers().size() != layers.getLayers().size()) {
//            throw processingError("processed layers don't match expected %s, but was %s", conf.getInstalledLayers(), layers.getLayers().keySet());
//        }
//        if (conf.getInstalledAddOns().size() != layers.getAddOns().size()) {
//            throw processingError("processed add-ons don't match expected %s, but was %s", conf.getInstalledAddOns(), layers.getAddOns().keySet());
//        }
        return layers;
    }
976519
public Long startProcess(Long processId, String masterRequestId, String ownerType,
            Long ownerId, Map<String,String> vars, Map<String,String> headers) throws Exception {
        return startProcess(processId, masterRequestId, ownerType, ownerId, vars, null, null, headers);
    }
393365
@Override
    void processModelNode(OperationContext context, String containerName, ModelNode cache, ConfigurationBuilder builder, List<Dependency<?>> dependencies)
            throws OperationFailedException {

        // process the basic clustered configuration
        super.processModelNode(context, containerName, cache, builder, dependencies);

        final int owners = DistributedCacheConfigurationResource.OWNERS.resolveModelAttribute(context, cache).asInt();
        final int segments = DistributedCacheConfigurationResource.SEGMENTS.resolveModelAttribute(context, cache).asInt();
        final float capacityFactor = (float) DistributedCacheConfigurationResource.CAPACITY_FACTOR.resolveModelAttribute(context,
              cache).asDouble();
        final long lifespan = DistributedCacheConfigurationResource.L1_LIFESPAN.resolveModelAttribute(context, cache).asLong();

        // process the additional distributed attributes and elements
        builder.clustering().hash()
            .numOwners(owners)
            .numSegments(segments)
            .capacityFactor(capacityFactor)
        ;

        if (lifespan > 0) {
            // is disabled by default in L1ConfigurationBuilder
            builder.clustering().l1().enable().lifespan(lifespan);
        } else {
            builder.clustering().l1().disable();
        }
    }
1265186
def build_process_tree(ps_rows):
    
    ps_tree = None
    for row in ps_rows:
        if row.ppid == 0:
            if ps_tree is not None:
                raise PsException("Too many process tree roots (ppid=0) found")
            ps_tree = PsTree(row)
    if ps_tree is None:
        raise PsException("No process tree root (ppid=0) found")
    _build_process_subtree(ps_rows, ps_tree, set([ps_tree.row.pid]))
    if ps_tree.count() < len(ps_rows):
        raise PsException("Unreachable processes detected")
    assert ps_tree.count() == len(ps_rows)
    return ps_tree
683028
public void build(List<JoinableResourceBundle> bundlesToBuild, boolean forceWriteBundleMapping,
			StopWatch stopWatch) {

		stopProcessIfNeeded();

		if (LOGGER.isInfoEnabled()) {
			LOGGER.info("Starting bundle processing");
		}

		notifyStartBundlingProcess();

		boolean mappingFileExists = resourceBundleHandler.isExistingMappingFile();
		boolean processBundleFlag = !config.getUseBundleMapping() || !mappingFileExists;

		// Global preprocessing
		executeGlobalPreprocessing(bundlesToBuild, processBundleFlag, stopWatch);

		for (JoinableResourceBundle bundle : bundlesToBuild) {

			stopProcessIfNeeded();

			if (stopWatch != null) {
				stopWatch.start("Processing bundle '" + bundle.getName() + "'");
			}

			if (!ThreadLocalJawrContext.isBundleProcessingAtBuildTime() && null != bundle.getAlternateProductionURL()) {
				if (LOGGER.isDebugEnabled()) {
					LOGGER.debug("No bundle generated for '" + bundle.getId()
							+ "' because a production URL is defined for this bundle.");
				}
			}
			if (bundle instanceof CompositeResourceBundle) {
				joinAndStoreCompositeResourcebundle((CompositeResourceBundle) bundle);
			} else {
				joinAndStoreBundle(bundle);
			}

			if (config.getUseBundleMapping()) {
				JoinableResourceBundlePropertySerializer.serializeInProperties(bundle,
						resourceBundleHandler.getResourceType(), bundleMapping);
			}

			bundle.setDirty(false);

			if (stopWatch != null) {
				stopWatch.stop();
			}
		}

		executeGlobalPostProcessing(processBundleFlag, stopWatch);
		storeJawrBundleMapping(resourceBundleHandler.isExistingMappingFile(), true);

		// Update the watcher with the path to watch
		try {
			if (watcher != null) {
				watcher.initPathToResourceBundleMap(bundlesToBuild);
			}
		} catch (IOException e) {
			throw new BundlingProcessException(e);
		}

		notifyEndBundlingProcess();
		if (LOGGER.isInfoEnabled()) {
			LOGGER.info("End of bundle processing");
		}

	}