hudson.model.Action Java Examples

The following examples show how to use hudson.model.Action. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GitLabSCMSource.java    From gitlab-branch-source-plugin with MIT License 6 votes vote down vote up
@NonNull
@Override
protected List<Action> retrieveActions(SCMSourceEvent event, @NonNull TaskListener listener) {
    List<Action> result = new ArrayList<>();
    getGitlabProject();
    GitLabSCMSourceContext ctx = new GitLabSCMSourceContext(null, SCMHeadObserver.none()).withTraits(traits);
    String projectUrl = gitlabProject.getWebUrl();
    String name = StringUtils.isBlank(projectName) ? gitlabProject.getNameWithNamespace() : projectName;
    result.add(new ObjectMetadataAction(name, gitlabProject.getDescription(), projectUrl));
    String avatarUrl = gitlabProject.getAvatarUrl();
    if (!ctx.projectAvatarDisabled() && StringUtils.isNotBlank(avatarUrl)) {
        result.add(new GitLabAvatar(avatarUrl));
    }
    result.add(GitLabLink.toProject(projectUrl));
    return result;
}
 
Example #2
Source File: DockerTraceabilityRootAction.java    From docker-traceability-plugin with MIT License 6 votes vote down vote up
/**
 * Gets the {@link DockerTraceabilityRootAction} of Jenkins instance.
 * @return Instance or null if it is not available
 */
public static @CheckForNull DockerTraceabilityRootAction getInstance() {
    Jenkins j = Jenkins.getInstance();
    if (j == null) {
        return null;
    }
    
    @CheckForNull DockerTraceabilityRootAction action = null;
    for (Action rootAction : j.getActions()) {
        if (rootAction instanceof DockerTraceabilityRootAction) {
            action = (DockerTraceabilityRootAction) rootAction;
            break;
        }
    } 
    return action;
}
 
Example #3
Source File: SourceActions.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 6 votes vote down vote up
@Nonnull
private List<Action> retrieve(@Nonnull SCMRevisionImpl revision, @CheckForNull SCMHeadEvent event, @Nonnull TaskListener listener) throws IOException, InterruptedException {
    List<Action> actions = new ArrayList<>();

    String hash = revision.getHash();
    Action linkAction = GitLabLinkAction.toCommit(source.getProject(), hash);
    actions.add(linkAction);

    SCMHead head = revision.getHead();
    if (head instanceof GitLabSCMMergeRequestHead) {
        actions.add(createHeadMetadataAction(head.getName(), ((GitLabSCMMergeRequestHead) head).getSource(), hash, linkAction.getUrlName()));
    } else if (head instanceof GitLabSCMHead) {
        actions.add(createHeadMetadataAction(head.getName(), (GitLabSCMHead) head, hash, linkAction.getUrlName()));
    }

    if (event instanceof GitLabSCMEvent) {
        actions.add(new GitLabSCMCauseAction(((GitLabSCMEvent) event).getCause()));
    }

    return actions;
}
 
Example #4
Source File: TryBlueOceanMenu.java    From blueocean-plugin with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Nonnull
@Override
public Collection<? extends Action> createFor(@Nonnull ModelObject target) {
    // we do not report actions as it might appear multiple times, we simply add it to Actionable
    BlueOceanUrlObjectFactory f = getFirst();
    if(f != null) {
        // TODO remove this if block once we are using a core > 2.126
        // Work around JENKINS-51584
        if (target instanceof hudson.model.Queue.Item) {
            return Collections.emptyList();
        }
        BlueOceanUrlObject blueOceanUrlObject = f.get(target);
        BlueOceanUrlAction a = new BlueOceanUrlAction(blueOceanUrlObject);
        return Collections.singleton(a);
    }
    return Collections.emptyList();
}
 
Example #5
Source File: OrganizationImpl.java    From blueocean-plugin with MIT License 6 votes vote down vote up
/**
 * Give plugins chance to handle this API route.
 *
 * @param route URL path that needs handling. e.g. for requested url /rest/organizations/:id/xyz,  route param value will be 'xyz'
 * @return stapler object that can handle give route. Could be null
 */
public Object getDynamic(String route){
    //First look for OrganizationActions
    for(OrganizationRoute organizationRoute: ExtensionList.lookup(OrganizationRoute.class)){
        if(organizationRoute.getUrlName() != null && organizationRoute.getUrlName().equals(route)){
            return wrap(organizationRoute);
        }
    }

    // No OrganizationRoute found, now lookup in available actions from Jenkins instance serving root
    for(Action action:Jenkins.getInstance().getActions()) {
        String urlName = action.getUrlName();
        if (urlName != null && urlName.equals(route)) {
            return wrap(action);
        }
    }
    return null;
}
 
Example #6
Source File: BuildFlowAction.java    From yet-another-build-visualizer-plugin with MIT License 5 votes vote down vote up
@Override
public Collection<? extends Action> createFor(@Nonnull Job target) {
  Run build = target.getLastBuild();
  if (build == null) {
    return Collections.emptyList();
  } else {
    return Collections.singleton(new BuildFlowAction(build));
  }
}
 
Example #7
Source File: GitHubPRRepositoryFactoryTest.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@CheckForNull
public static GitHubPRRepository getRepo(Collection<? extends Action> repoCollection) {
    GitHubPRRepository repo = null;
    for (Iterator<GitHubPRRepository> iterator = (Iterator<GitHubPRRepository>) repoCollection.iterator(); iterator.hasNext(); ) {
        repo = iterator.next();
    }
    return repo;
}
 
Example #8
Source File: SourceActions.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Nonnull
List<Action> retrieve(@CheckForNull SCMSourceEvent event, @Nonnull TaskListener listener) throws IOException {
    GitLabProject project = source.getProject();
    return asList(
            new ObjectMetadataAction(project.getNameWithNamespace(), project.getDescription(), project.getWebUrl()),
            new GitLabProjectAvatarMetadataAction(project.getId(), source.getSourceSettings().getConnectionName()),
            GitLabLinkAction.toProject(project));
}
 
Example #9
Source File: IntegrationTest.java    From warnings-ng-plugin with MIT License 5 votes vote down vote up
@SuppressWarnings({"illegalcatch", "OverlyBroadCatchBlock"})
protected Run<?, ?> buildWithResult(final ParameterizedJob<?, ?> job, final Result expectedResult) {
    try {
        Run<?, ?> build = getJenkins().assertBuildStatus(expectedResult,
                Objects.requireNonNull(job.scheduleBuild2(0, new Action[0])));
        printConsoleLog(build);
        return build;
    }
    catch (Exception e) {
        throw new AssertionError(e);
    }
}
 
Example #10
Source File: AggregationActionTest.java    From warnings-ng-plugin with MIT License 5 votes vote down vote up
@Test
void shouldNeverReturnMultipleProjectActions() {
    AggregationAction action = new AggregationAction();
    action.onLoad(mock(Run.class));

    Collection<? extends Action> projectActions = action.getProjectActions();

    assertThat(projectActions).hasSize(1);
    assertThat(projectActions.iterator().next()).isInstanceOf(AggregatedTrendAction.class);
}
 
Example #11
Source File: GitHubBranchRepositoryFactory.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Nonnull
@Override
public Collection<? extends Action> createFor(@Nonnull Job job) {
    try {
        if (nonNull(ghBranchTriggerFromJob(job))) {
            return Collections.singleton(forProject(job));
        }
    } catch (Exception ex) {
        LOGGER.warn("Bad configured project {} - {}", job.getFullName(), ex.getMessage(), ex);
    }

    return Collections.emptyList();
}
 
Example #12
Source File: GitHubPRRepositoryFactoryTest.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Test
    public void createForNullTrigger() {
//        when(job.getTrigger(GitHubPRTrigger.class)).thenReturn(null);
        PowerMockito.mockStatic(JobHelper.class);
        given(ghPRTriggerFromJob(job))
                .willReturn(null);

        Collection<? extends Action> repoCollection = new GitHubPRRepositoryFactory().createFor(job);
        Assert.assertTrue(repoCollection instanceof List);
        Assert.assertTrue(repoCollection.isEmpty());
    }
 
Example #13
Source File: SourceActions.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Nonnull
private List<Action> retrieve(@Nonnull GitLabSCMHead head, @CheckForNull SCMHeadEvent event, @Nonnull TaskListener listener) throws IOException, InterruptedException {
    List<Action> actions = new ArrayList<>();

    actions.add(new GitLabSCMPublishAction(head, source.getSourceSettings()));

    Action linkAction;

    if (head instanceof ChangeRequestSCMHead) {
        GitLabMergeRequest mr = retrieveMergeRequest((ChangeRequestSCMHead) head, listener);
        linkAction = GitLabLinkAction.toMergeRequest(mr.getWebUrl());
        actions.add(createAuthorMetadataAction(mr));
        actions.add(createHeadMetadataAction(((GitLabSCMMergeRequestHead) head).getDescription(), ((GitLabSCMMergeRequestHead) head).getSource(), null, linkAction.getUrlName()));
        if (acceptMergeRequest(head)) {
            boolean removeSourceBranch = mr.getRemoveSourceBranch() || removeSourceBranch(head);
            actions.add(new GitLabSCMAcceptMergeRequestAction(mr, mr.getIid(), source.getSourceSettings().getMergeCommitMessage(), removeSourceBranch));
        }
    } else {
        linkAction = (head instanceof TagSCMHead) ? GitLabLinkAction.toTag(source.getProject(), head.getName()) : GitLabLinkAction.toBranch(source.getProject(), head.getName());
        if (head instanceof GitLabSCMBranchHead && StringUtils.equals(source.getProject().getDefaultBranch(), head.getName())) {
            actions.add(new PrimaryInstanceMetadataAction());
        }
    }

    actions.add(linkAction);
    return actions;
}
 
Example #14
Source File: SourceActions.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Nonnull
List<Action> retrieve(@Nonnull SCMRevision revision, @CheckForNull SCMHeadEvent event, @Nonnull TaskListener listener) throws IOException, InterruptedException {
    if (revision instanceof SCMRevisionImpl) {
        return retrieve((SCMRevisionImpl) revision, event, listener);
    }

    return emptyList();
}
 
Example #15
Source File: Export.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
public Object getValue(Property property, Object model, ExportConfig config) throws IOException {
    if(model instanceof Action){
        try {
            return property.getValue(model);
        } catch (Throwable e) {
            printError(model.getClass(), e);
            return SKIP;
        }
    } else if (model instanceof Item || model instanceof Run) {
        // We should skip any models that are Jenkins Item or Run objects as these are known to be evil
        return SKIP;
    }
    return ExportInterceptor.DEFAULT.getValue(property, model, config);
}
 
Example #16
Source File: ActionProxiesImpl.java    From blueocean-plugin with MIT License 5 votes vote down vote up
/**
 * Finds all the actions and proxys them so long as they are annotated with ExportedBean
 * @param actions to proxy
 * @param parent reachable
 * @return actionProxies
 */
public static Collection<BlueActionProxy> getActionProxies(List<? extends Action> actions, Reachable parent){
    if(isTreeRequest()){
        return getActionProxies(actions, Predicates.<Action>alwaysFalse(), parent);
    }
    return Collections.emptyList();

}
 
Example #17
Source File: AbstractRunImpl.java    From blueocean-plugin with MIT License 5 votes vote down vote up
/**
 * Handles HTTP path handled by actions or other extensions
 *
 * @param token path token that an action or extension can handle
 *
 * @return action or extension that handles this path.
 */
public Object getDynamic(String token) {
    for (Action a : run.getAllActions()) {
        if (token.equals(a.getUrlName()))
            return new GenericResource<>(a);
    }

    return null;
}
 
Example #18
Source File: PipelineNodeImpl.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
public Collection<BlueActionProxy> getActions() {

    HashSet<Action> actions = new HashSet<>();

    // Actions attached to the node we use for the graph
    actions.addAll(node.getNode().getActions());

    // Actions from any child nodes
    actions.addAll(node.getPipelineActions(NodeDownstreamBuildAction.class));

    return ActionProxiesImpl.getActionProxies(actions,
                                              input -> input instanceof LogAction || input instanceof NodeDownstreamBuildAction,
                                              this);
}
 
Example #19
Source File: FlowNodeWrapper.java    From blueocean-plugin with MIT License 5 votes vote down vote up
/**
 * Returns Action instances that were attached to the associated FlowNode, or to any of its children
 * not represented in the graph.
 * Filters by class to mimic Item.getActions(class).
 */
public <T extends Action> Collection<T> getPipelineActions(Class<T> clazz) {
    if (pipelineActions == null) {
        return Collections.emptyList();
    }
    ArrayList<T> filtered = new ArrayList<>();
    for (Action a : pipelineActions) {
        if (clazz.isInstance(a)) {
            filtered.add(clazz.cast(a));
        }
    }
    return filtered;
}
 
Example #20
Source File: GitLabSCMNavigator.java    From gitlab-branch-source-plugin with MIT License 5 votes vote down vote up
@NonNull
@Override
protected List<Action> retrieveActions(@NonNull SCMNavigatorOwner owner,
    SCMNavigatorEvent event,
    @NonNull TaskListener listener) throws IOException, InterruptedException {
    getGitlabOwner();
    String fullName = gitlabOwner.getFullName();
    String webUrl = gitlabOwner.getWebUrl();
    String avatarUrl = gitlabOwner.getAvatarUrl();
    String description = null;
    if (gitlabOwner instanceof GitLabGroup) {
        description = ((GitLabGroup) gitlabOwner).getDescription();
    }
    List<Action> result = new ArrayList<>();
    result.add(new ObjectMetadataAction(
        Util.fixEmpty(fullName),
        description,
        webUrl)
    );
    if (StringUtils.isNotBlank(avatarUrl)) {
        result.add(new GitLabAvatar(avatarUrl));
    }
    result.add(GitLabLink.toGroup(webUrl));
    if (StringUtils.isBlank(webUrl)) {
        listener.getLogger().println("Web URL unspecified");
    } else {
        listener.getLogger().printf("%s URL: %s%n", gitlabOwner.getWord(),
            HyperlinkNote
                .encodeTo(webUrl, StringUtils.defaultIfBlank(fullName, webUrl)));
    }
    return result;
}
 
Example #21
Source File: PipelineNodeGraphVisitor.java    From blueocean-plugin with MIT License 5 votes vote down vote up
/**
 * Find any Actions on this node, and add them to the pipelineActions collection until we can attach
 * them to a FlowNodeWrapper.
 */
protected void accumulatePipelineActions(FlowNode node) {
    final List<Action> actions = node.getActions(Action.class);
    pipelineActions.addAll(actions);
    if (isNodeVisitorDumpEnabled) {
        dump(String.format("\t\taccumulating actions - added %d, total is %d", actions.size(), pipelineActions.size()));
    }
}
 
Example #22
Source File: PipelineNodeGraphVisitor.java    From blueocean-plugin with MIT License 5 votes vote down vote up
/**
 * Empty the pipelineActions buffer, returning its contents.
 */
protected Set<Action> drainPipelineActions() {
    if (isNodeVisitorDumpEnabled) {
        dump(String.format("\t\tdraining accumulated actions - total is %d", pipelineActions.size()));
    }

    if (pipelineActions.size() == 0) {
        return Collections.emptySet();
    }

    Set<Action> drainedActions = pipelineActions;
    pipelineActions = new HashSet<>();
    return drainedActions;
}
 
Example #23
Source File: PipelineNodeUtil.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@CheckForNull
public static TagsAction getSyntheticStage(@Nullable FlowNode node){
    if(node != null) {
        for (Action action : node.getActions()) {
            if (action instanceof TagsAction && ((TagsAction) action).getTagValue(SyntheticStage.TAG_NAME) != null) {
                return (TagsAction) action;
            }
        }
    }
    return null;
}
 
Example #24
Source File: GitHubSCMSource.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Nonnull
@Override
protected List<Action> retrieveActions(@Nonnull SCMRevision revision, @CheckForNull SCMHeadEvent event,
                                       @Nonnull TaskListener listener) throws IOException, InterruptedException {
    GitHubSCMRevision gitHubSCMRevision = (GitHubSCMRevision) revision;
    GitHubCause<?> cause = gitHubSCMRevision.getCause();
    if (nonNull(cause)) {
        List<ParameterValue> params = new ArrayList<>();
        cause.fillParameters(params);
        return Arrays.asList(new CauseAction(cause), new GitHubParametersAction(params));
    }

    return Collections.emptyList();
}
 
Example #25
Source File: EC2FleetAutoResubmitComputerLauncherTest.java    From ec2-spot-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void taskCompleted_should_resubmit_task_if_offline_and_cause_disconnect() {
    when(computer.getExecutors()).thenReturn(Arrays.asList(executor1));
    when(computer.getOfflineCause()).thenReturn(new OfflineCause.ChannelTermination(null));
    new EC2FleetAutoResubmitComputerLauncher(baseComputerLauncher)
            .afterDisconnect(computer, taskListener);
    verify(queue).schedule2(eq(task1), anyInt(), eq(Collections.<Action>emptyList()));
    verifyZeroInteractions(queue);
}
 
Example #26
Source File: EC2FleetAutoResubmitComputerLauncherTest.java    From ec2-spot-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void taskCompleted_should_resubmit_task_for_all_executors() {
    when(computer.getOfflineCause()).thenReturn(new OfflineCause.ChannelTermination(null));
    new EC2FleetAutoResubmitComputerLauncher(baseComputerLauncher)
            .afterDisconnect(computer, taskListener);
    verify(queue).schedule2(eq(task1), anyInt(), eq(Collections.<Action>emptyList()));
    verify(queue).schedule2(eq(task2), anyInt(), eq(Collections.<Action>emptyList()));
    verifyZeroInteractions(queue);
}
 
Example #27
Source File: DockerTraceabilityRootActionTest.java    From docker-traceability-plugin with MIT License 5 votes vote down vote up
@Test
public void containerIDs_CRUD() throws Exception {
    // TODO: replace by a helper method from the branch
    JenkinsRule.WebClient client = j.createWebClient();
    @CheckForNull DockerTraceabilityRootAction action = null;
    for (Action rootAction : j.getInstance().getActions()) {
        if (rootAction instanceof DockerTraceabilityRootAction) {
            action = (DockerTraceabilityRootAction) rootAction;
            break;
        }
    }    
    assertNotNull(action);
    
    final String id1 = FingerprintTestUtil.generateDockerId("1");
    final String id2 = FingerprintTestUtil.generateDockerId("2");
    final String id3 = FingerprintTestUtil.generateDockerId("3");
    
    // Check consistency of create/update commands
    action.addContainerID(id1);
    assertEquals(1, action.getContainerIDs().size());
    action.addContainerID(id2);
    assertEquals(2, action.getContainerIDs().size());
    action.addContainerID(id2);
    assertEquals(2, action.getContainerIDs().size());
    
    // Remove data using API. First entry is non-existent
    action.doDeleteContainer(id3);
    assertEquals(2, action.getContainerIDs().size());
    action.doDeleteContainer(id1);
    assertEquals(1, action.getContainerIDs().size());
    action.doDeleteContainer(id1);
    assertEquals(1, action.getContainerIDs().size());
    
    // Reload the data and ensure the status has been persisted correctly
    action = new DockerTraceabilityRootAction();
    assertEquals(1, action.getContainerIDs().size());
    for (String id : action.getContainerIDs()) {
        assertEquals(id2, id);
    }
}
 
Example #28
Source File: GitHubTrigger.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Nonnull
@Override
public Collection<? extends Action> getProjectActions() {
    final ArrayList<Action> actions = new ArrayList<>();

    if (nonNull(getPollingLogAction())) {
        actions.add(getPollingLogAction());
    }
    actions.add(getErrorsAction());
    return actions;
}
 
Example #29
Source File: GitHubSCMSource.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@NonNull
@Override
protected List<Action> retrieveActions(@CheckForNull SCMSourceEvent event,
                                       @NonNull TaskListener listener) throws IOException {
    // TODO when we have support for trusted events, use the details from event if event was from trusted source
    List<Action> result = new ArrayList<>();
    result.add(new GitHubRepoMetadataAction());
    String repository = this.repository;

    StandardCredentials credentials = Connector.lookupScanCredentials((Item) getOwner(), apiUri, credentialsId);
    GitHub hub = Connector.connect(apiUri, credentials);
    try {
        Connector.checkConnectionValidity(apiUri, listener, credentials, hub);
        try {
            ghRepository = hub.getRepository(getRepoOwner() + '/' + repository);
            resolvedRepositoryUrl = ghRepository.getHtmlUrl();
        } catch (FileNotFoundException e) {
            throw new AbortException(
                    String.format("Invalid scan credentials when using %s to connect to %s/%s on %s",
                            credentials == null ? "anonymous access" : CredentialsNameProvider.name(credentials), repoOwner, repository, apiUri));
        }
        result.add(new ObjectMetadataAction(null, ghRepository.getDescription(), Util.fixEmpty(ghRepository.getHomepage())));
        result.add(new GitHubLink("icon-github-repo", ghRepository.getHtmlUrl()));
        if (StringUtils.isNotBlank(ghRepository.getDefaultBranch())) {
            result.add(new GitHubDefaultBranch(getRepoOwner(), repository, ghRepository.getDefaultBranch()));
        }
        return result;
    } finally {
        Connector.release(hub);
    }
}
 
Example #30
Source File: GitHubSCMNavigator.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@NonNull
@Override
public List<Action> retrieveActions(@NonNull SCMNavigatorOwner owner,
                                    @CheckForNull SCMNavigatorEvent event,
                                    @NonNull TaskListener listener) throws IOException, InterruptedException {
    // TODO when we have support for trusted events, use the details from event if event was from trusted source
    listener.getLogger().printf("Looking up details of %s...%n", getRepoOwner());
    List<Action> result = new ArrayList<>();
    StandardCredentials credentials = Connector.lookupScanCredentials((Item)owner, getApiUri(), credentialsId);
    GitHub hub = Connector.connect(getApiUri(), credentials);
    try {
        Connector.checkApiRateLimit(listener, hub);
        GHUser u = hub.getUser(getRepoOwner());
        String objectUrl = u.getHtmlUrl() == null ? null : u.getHtmlUrl().toExternalForm();
        result.add(new ObjectMetadataAction(
                Util.fixEmpty(u.getName()),
                null,
                objectUrl)
        );
        result.add(new GitHubOrgMetadataAction(u));
        result.add(new GitHubLink("icon-github-logo", u.getHtmlUrl()));
        if (objectUrl == null) {
            listener.getLogger().println("Organization URL: unspecified");
        } else {
            listener.getLogger().printf("Organization URL: %s%n",
                    HyperlinkNote.encodeTo(objectUrl, StringUtils.defaultIfBlank(u.getName(), objectUrl)));
        }
        return result;
    } finally {
        Connector.release(hub);
    }
}