Search in sources :

Example 56 with Jenkins

use of jenkins.model.Jenkins in project promoted-builds-plugin by jenkinsci.

the class ItemPathResolver method getByPath.

/**
 * Gets an {@link Item} of the specified type by absolute or relative path.
 * <p>
 * The implementation retains the original behavior in {@link PromotedBuildParameterDefinition},
 * but this method also provides a support of multi-level addressing including special markups
 * for the relative addressing.
 * </p>
 * Effectively, the resolution order is following:
 * <ul>
 *   <li><b>Optional</b> Legacy behavior, which can be enabled by {@link #ENABLE_LEGACY_RESOLUTION_AGAINST_ROOT}.
 *       If an item for the name exists on the top Jenkins level, it will be returned</li>
 *   <li>If the path starts with &quot;/&quot;, a global addressing will be used</li>
 *   <li>If the path starts with &quot;./&quot; or &quot;../&quot;, a relative addressing will be used</li>
 *   <li>If there is no prefix, a relative addressing will be tried. If it
 *       fails, the method falls back to a global one</li>
 * </ul>
 * For the relative and absolute addressing the engine supports &quot;.&quot; and
 * &quot;..&quot; markers within the path.
 * The first one points to the current element, the second one - to the upper element.
 * If the search cannot get a new top element (e.g. reached the root), the method returns {@code null}.
 *
 * @param <T> Type of the {@link Item} to be retrieved
 * @param path Path string to the item.
 * @param baseItem Base {@link Item} for the relative addressing. If null,
 *      this addressing approach will be skipped
 * @param type Type of the {@link Item} to be retrieved
 * @return Found {@link Item}. Null if it has not been found by all addressing modes
 *  or the type differs.
 */
@CheckForNull
@SuppressWarnings("unchecked")
@Restricted(NoExternalUse.class)
public static <T extends Item> T getByPath(@Nonnull String path, @CheckForNull Item baseItem, @Nonnull Class<T> type) {
    final Jenkins jenkins = Jenkins.getInstanceOrNull();
    if (jenkins == null) {
        return null;
    }
    // Legacy behavior
    if (isEnableLegacyResolutionAgainstRoot()) {
        TopLevelItem topLevelItem = jenkins.getItem(path);
        if (topLevelItem != null && type.isAssignableFrom(topLevelItem.getClass())) {
            return (T) topLevelItem;
        }
    }
    // Explicit global addressing
    if (path.startsWith("/")) {
        return findPath(jenkins, path.substring(1), type);
    }
    // Try the relative addressing if possible
    if (baseItem != null) {
        final ItemGroup<?> relativeRoot = baseItem instanceof ItemGroup<?> ? (ItemGroup<?>) baseItem : baseItem.getParent();
        final T item = findPath(relativeRoot, path, type);
        if (item != null) {
            return item;
        }
    }
    // Fallback to the default behavior (addressing from the Jenkins root)
    return findPath(jenkins, path, type);
}
Also used : Jenkins(jenkins.model.Jenkins) TopLevelItem(hudson.model.TopLevelItem) Restricted(org.kohsuke.accmod.Restricted) CheckForNull(javax.annotation.CheckForNull)

Example 57 with Jenkins

use of jenkins.model.Jenkins in project promoted-builds-plugin by jenkinsci.

the class JobDslPromotionProcessConverter method obtainClassOwnership.

@CheckForNull
private String obtainClassOwnership() {
    if (this.classOwnership != null) {
        return this.classOwnership;
    }
    if (pm == null) {
        Jenkins j = Jenkins.getInstanceOrNull();
        pm = j != null ? j.getPluginManager() : null;
    }
    if (pm == null) {
        return null;
    }
    // TODO: possibly recursively scan super class to discover dependencies
    PluginWrapper p = pm.whichPlugin(hudson.plugins.promoted_builds.PromotionProcess.class);
    this.classOwnership = p != null ? p.getShortName() + '@' + trimVersion(p.getVersion()) : null;
    return this.classOwnership;
}
Also used : Jenkins(jenkins.model.Jenkins) PluginWrapper(hudson.PluginWrapper) CheckForNull(javax.annotation.CheckForNull)

Example 58 with Jenkins

use of jenkins.model.Jenkins in project blueocean-plugin by jenkinsci.

the class BlueRunChangesetPreloader method getPipeline.

private BluePipeline getPipeline(BlueUrlTokenizer blueUrl) {
    Jenkins jenkins = Jenkins.getInstanceOrNull();
    if (jenkins == null) {
        return null;
    }
    String pipelineFullName = blueUrl.getPart(BlueUrlTokenizer.UrlPart.PIPELINE);
    try {
        Item pipelineJob = jenkins.getItemByFullName(pipelineFullName);
        return (BluePipeline) BluePipelineFactory.resolve(pipelineJob);
    } catch (Exception e) {
        LOGGER.log(Level.FINE, String.format("Unable to find Job named '%s'.", pipelineFullName), e);
        return null;
    }
}
Also used : Jenkins(jenkins.model.Jenkins) Item(hudson.model.Item) BluePipeline(io.jenkins.blueocean.rest.model.BluePipeline) IOException(java.io.IOException)

Example 59 with Jenkins

use of jenkins.model.Jenkins in project blueocean-plugin by jenkinsci.

the class FavoriteListStatePreloader method getStateJson.

@CheckForNull
@Override
public String getStateJson() {
    User jenkinsUser = User.current();
    if (jenkinsUser == null) {
        return null;
    }
    FavoriteUserProperty fup = jenkinsUser.getProperty(FavoriteUserProperty.class);
    if (fup == null) {
        return null;
    }
    Set<String> favorites = fup.getAllFavorites();
    if (favorites == null) {
        return null;
    }
    final Jenkins jenkins = Jenkins.get();
    final List<FavoritPreload> favoritPreloads = favorites.stream().map(name -> {
        final Item item = jenkins.getItemByFullName(name);
        if (item instanceof Job) {
            final Job<?, ?> job = (Job<?, ?>) item;
            if (job.getAction(PrimaryInstanceMetadataAction.class) != null) {
                return new FavoritPreload(name, true);
            }
        }
        return new FavoritPreload(name, false);
    }).collect(Collectors.toList());
    return JSONArray.fromObject(favoritPreloads).toString();
}
Also used : FavoriteUserProperty(hudson.plugins.favorite.user.FavoriteUserProperty) Jenkins(jenkins.model.Jenkins) Jenkins(jenkins.model.Jenkins) FavoriteUserProperty(hudson.plugins.favorite.user.FavoriteUserProperty) Set(java.util.Set) Collectors(java.util.stream.Collectors) List(java.util.List) PageStatePreloader(io.jenkins.blueocean.commons.PageStatePreloader) PrimaryInstanceMetadataAction(jenkins.scm.api.metadata.PrimaryInstanceMetadataAction) JSONArray(net.sf.json.JSONArray) Item(hudson.model.Item) Extension(hudson.Extension) Job(hudson.model.Job) User(hudson.model.User) CheckForNull(javax.annotation.CheckForNull) Nonnull(javax.annotation.Nonnull) Item(hudson.model.Item) User(hudson.model.User) Job(hudson.model.Job) CheckForNull(javax.annotation.CheckForNull)

Example 60 with Jenkins

use of jenkins.model.Jenkins in project blueocean-plugin by jenkinsci.

the class PipelineNodeTest method sequentialParallelStages.

@Test
@Issue("JENKINS-49050")
public void sequentialParallelStages() throws Exception {
    WorkflowJob p = createWorkflowJobWithJenkinsfile(getClass(), "sequentialParallel.jenkinsfile");
    Slave s = j.createOnlineSlave();
    s.setNumExecutors(2);
    // Run until completed
    WorkflowRun run = p.scheduleBuild2(0).waitForStart();
    j.waitForCompletion(run);
    PipelineNodeGraphVisitor pipelineNodeGraphVisitor = new PipelineNodeGraphVisitor(run);
    assertTrue(pipelineNodeGraphVisitor.isDeclarative());
    List<FlowNodeWrapper> wrappers = pipelineNodeGraphVisitor.getPipelineNodes();
    assertEquals(9, wrappers.size());
    Optional<FlowNodeWrapper> optionalFlowNodeWrapper = wrappers.stream().filter(nodeWrapper -> nodeWrapper.getDisplayName().equals("first-sequential-stage")).findFirst();
    // we ensure "multiple-stages" is parent of "first-sequential-stage"
    assertTrue(optionalFlowNodeWrapper.isPresent());
    assertEquals(1, optionalFlowNodeWrapper.get().edges.size());
    assertEquals("second-sequential-stage", optionalFlowNodeWrapper.get().edges.get(0).getDisplayName());
    final String parentId = optionalFlowNodeWrapper.get().getFirstParent().getId();
    optionalFlowNodeWrapper = wrappers.stream().filter(nodeWrapper -> nodeWrapper.getId().equals(parentId)).findFirst();
    assertTrue(optionalFlowNodeWrapper.isPresent());
    assertEquals("multiple-stages", optionalFlowNodeWrapper.get().getDisplayName());
    assertEquals(1, optionalFlowNodeWrapper.get().edges.size());
    optionalFlowNodeWrapper.get().edges.stream().filter(nodeWrapper -> nodeWrapper.getDisplayName().equals("first-sequential-stage")).findFirst();
    assertTrue(optionalFlowNodeWrapper.isPresent());
    optionalFlowNodeWrapper = wrappers.stream().filter(nodeWrapper -> nodeWrapper.getDisplayName().equals("other-single-stage")).findFirst();
    assertTrue(optionalFlowNodeWrapper.isPresent());
    final String otherParentId = optionalFlowNodeWrapper.get().getFirstParent().getId();
    optionalFlowNodeWrapper = wrappers.stream().filter(nodeWrapper -> nodeWrapper.getId().equals(otherParentId)).findFirst();
    assertTrue(optionalFlowNodeWrapper.isPresent());
    assertEquals("parent", optionalFlowNodeWrapper.get().getDisplayName());
    assertEquals(3, optionalFlowNodeWrapper.get().edges.size());
    optionalFlowNodeWrapper = wrappers.stream().filter(nodeWrapper -> nodeWrapper.getDisplayName().equals("second-sequential-stage")).findFirst();
    assertTrue(optionalFlowNodeWrapper.isPresent());
    assertEquals(1, optionalFlowNodeWrapper.get().edges.size());
    assertEquals("third-sequential-stage", optionalFlowNodeWrapper.get().edges.get(0).getDisplayName());
    optionalFlowNodeWrapper = wrappers.stream().filter(nodeWrapper -> nodeWrapper.getDisplayName().equals("third-sequential-stage")).findFirst();
    assertTrue(optionalFlowNodeWrapper.isPresent());
    assertEquals(1, optionalFlowNodeWrapper.get().edges.size());
    assertEquals("second-solo", optionalFlowNodeWrapper.get().edges.get(0).getDisplayName());
    List<Map> nodes = get("/organizations/jenkins/pipelines/" + p.getName() + "/runs/1/nodes/", List.class);
    assertEquals(9, nodes.size());
    Optional<Map> firstSeqStage = nodes.stream().filter(map -> map.get("displayName").equals("first-sequential-stage")).findFirst();
    assertTrue(firstSeqStage.isPresent());
    String firstParentId = (String) firstSeqStage.get().get("firstParent");
    Optional<Map> parentStage = nodes.stream().filter(map -> map.get("id").equals(firstParentId)).findFirst();
    assertTrue(parentStage.isPresent());
    assertEquals("multiple-stages", parentStage.get().get("displayName"));
    // ensure no issue getting steps for each node
    for (Map<String, String> node : nodes) {
        String id = node.get("id");
        List<Map> steps = get("/organizations/jenkins/pipelines/" + p.getName() + "/runs/1/nodes/" + id + "/steps/", List.class);
        assertFalse(steps.get(0).isEmpty());
    }
}
Also used : CpsFlowDefinition(org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition) Arrays(java.util.Arrays) CoreMatchers.hasItem(org.hamcrest.CoreMatchers.hasItem) Issue(org.jvnet.hudson.test.Issue) QueueTaskFuture(hudson.model.queue.QueueTaskFuture) URL(java.net.URL) InputAction(org.jenkinsci.plugins.workflow.support.steps.input.InputAction) PARAMETERS_ELEMENT(io.jenkins.blueocean.rest.impl.pipeline.PipelineStepImpl.PARAMETERS_ELEMENT) StringUtils(org.apache.commons.lang3.StringUtils) RunList(hudson.util.RunList) MemoryFlowChunk(org.jenkinsci.plugins.workflow.graphanalysis.MemoryFlowChunk) Map(java.util.Map) FlowExecution(org.jenkinsci.plugins.workflow.flow.FlowExecution) BluePipelineNode(io.jenkins.blueocean.rest.model.BluePipelineNode) Jenkins(jenkins.model.Jenkins) MapsHelper(io.jenkins.blueocean.commons.MapsHelper) TypeSafeMatcher(org.hamcrest.TypeSafeMatcher) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Run(hudson.model.Run) IOUtils(org.apache.commons.io.IOUtils) List(java.util.List) NodeDownstreamBuildAction(io.jenkins.blueocean.listeners.NodeDownstreamBuildAction) FilePath(hudson.FilePath) Result(hudson.model.Result) JSONObject(net.sf.json.JSONObject) WorkflowMultiBranchProject(org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject) Optional(java.util.Optional) WorkflowRun(org.jenkinsci.plugins.workflow.job.WorkflowRun) Link(io.jenkins.blueocean.rest.hal.Link) FlowNode(org.jenkinsci.plugins.workflow.graph.FlowNode) BeforeClass(org.junit.BeforeClass) SemaphoreStep(org.jenkinsci.plugins.workflow.test.steps.SemaphoreStep) FreeStyleProject(hudson.model.FreeStyleProject) CpsFlowExecution(org.jenkinsci.plugins.workflow.cps.CpsFlowExecution) FlowGraphTable(org.jenkinsci.plugins.workflow.support.visualization.table.FlowGraphTable) UnstableStep(org.jenkinsci.plugins.workflow.steps.UnstableStep) GitSampleRepoRule(jenkins.plugins.git.GitSampleRepoRule) Unirest(com.mashape.unirest.http.Unirest) SCMSource(jenkins.scm.api.SCMSource) Util(hudson.Util) WorkflowJob(org.jenkinsci.plugins.workflow.job.WorkflowJob) Description(org.hamcrest.Description) Iterator(java.util.Iterator) BluePipelineStep(io.jenkins.blueocean.rest.model.BluePipelineStep) BlueRun(io.jenkins.blueocean.rest.model.BlueRun) Test(org.junit.Test) BranchSource(jenkins.branch.BranchSource) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) Rule(org.junit.Rule) Ignore(org.junit.Ignore) Matcher(org.hamcrest.Matcher) Assert(org.junit.Assert) Slave(hudson.model.Slave) ExtensionList(hudson.ExtensionList) GitSCMSource(jenkins.plugins.git.GitSCMSource) WorkflowRun(org.jenkinsci.plugins.workflow.job.WorkflowRun) Slave(hudson.model.Slave) WorkflowJob(org.jenkinsci.plugins.workflow.job.WorkflowJob) Map(java.util.Map) Issue(org.jvnet.hudson.test.Issue) Test(org.junit.Test)

Aggregations

Jenkins (jenkins.model.Jenkins)73 Test (org.junit.Test)22 ConfiguredWithCode (org.jenkinsci.plugins.casc.misc.ConfiguredWithCode)13 IOException (java.io.IOException)10 File (java.io.File)9 WorkflowRun (org.jenkinsci.plugins.workflow.job.WorkflowRun)9 FlowExecution (org.jenkinsci.plugins.workflow.flow.FlowExecution)8 ArrayList (java.util.ArrayList)7 List (java.util.List)7 Map (java.util.Map)7 Statement (org.junit.runners.model.Statement)7 CheckForNull (javax.annotation.CheckForNull)6 FilePath (hudson.FilePath)5 Computer (hudson.model.Computer)5 URL (java.net.URL)5 FlowNode (org.jenkinsci.plugins.workflow.graph.FlowNode)5 Issue (org.jvnet.hudson.test.Issue)5 Item (hudson.model.Item)4 Node (hudson.model.Node)4 Date (java.util.Date)4