Search in sources :

Example 71 with User

use of hudson.model.User in project hudson-2.x by hudson.

the class BaseBuildResultMail method createEmptyMail.

/**
     * Creates empty mail.
     *
     * @param build build.
     * @param listener listener.
     * @return empty mail.
     * @throws MessagingException exception if any.
     */
protected MimeMessage createEmptyMail(AbstractBuild<?, ?> build, BuildListener listener) throws MessagingException {
    MimeMessage msg = new HudsonMimeMessage(Mailer.descriptor().createSession());
    // TODO: I'd like to put the URL to the page in here,
    // but how do I obtain that?
    msg.setContent("", "text/plain");
    msg.setFrom(new InternetAddress(Mailer.descriptor().getAdminAddress()));
    msg.setSentDate(new Date());
    Set<InternetAddress> rcp = new LinkedHashSet<InternetAddress>();
    StringTokenizer tokens = new StringTokenizer(getRecipients());
    while (tokens.hasMoreTokens()) {
        String address = tokens.nextToken();
        if (address.startsWith("upstream-individuals:")) {
            // people who made a change in the upstream
            String projectName = address.substring("upstream-individuals:".length());
            AbstractProject up = Hudson.getInstance().getItemByFullName(projectName, AbstractProject.class);
            if (up == null) {
                listener.getLogger().println("No such project exist: " + projectName);
                continue;
            }
            includeCulpritsOf(up, build, listener, rcp);
        } else {
            // ordinary address
            try {
                rcp.add(new InternetAddress(address));
            } catch (AddressException e) {
                // report bad address, but try to send to other addresses
                e.printStackTrace(listener.error(e.getMessage()));
            }
        }
    }
    if (CollectionUtils.isNotEmpty(upstreamProjects)) {
        for (AbstractProject project : upstreamProjects) {
            includeCulpritsOf(project, build, listener, rcp);
        }
    }
    if (sendToIndividuals) {
        Set<User> culprits = build.getCulprits();
        if (debug)
            listener.getLogger().println("Trying to send e-mails to individuals who broke the build. sizeof(culprits)==" + culprits.size());
        rcp.addAll(buildCulpritList(listener, culprits));
    }
    msg.setRecipients(Message.RecipientType.TO, rcp.toArray(new InternetAddress[rcp.size()]));
    AbstractBuild<?, ?> pb = build.getPreviousBuild();
    if (pb != null) {
        MailMessageIdAction b = pb.getAction(MailMessageIdAction.class);
        if (b != null) {
            msg.setHeader("In-Reply-To", b.messageId);
            msg.setHeader("References", b.messageId);
        }
    }
    return msg;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) InternetAddress(javax.mail.internet.InternetAddress) User(hudson.model.User) HudsonMimeMessage(hudson.tasks.HudsonMimeMessage) Date(java.util.Date) MailMessageIdAction(hudson.tasks.MailMessageIdAction) StringTokenizer(java.util.StringTokenizer) MimeMessage(javax.mail.internet.MimeMessage) HudsonMimeMessage(hudson.tasks.HudsonMimeMessage) AddressException(javax.mail.internet.AddressException) AbstractProject(hudson.model.AbstractProject)

Example 72 with User

use of hudson.model.User in project hudson-2.x by hudson.

the class FunctionsTest method testIsAuthorJobCreatedByNull.

@Test
@PrepareForTest(User.class)
public void testIsAuthorJobCreatedByNull() throws Exception {
    mockStatic(User.class);
    User user = createMock(User.class);
    expect(User.current()).andReturn(user);
    Job job = createMock(FreeStyleProject.class);
    expect(job.getCreatedBy()).andReturn(null);
    replay(User.class, user, job);
    boolean result = Functions.isAuthor(job);
    verify(User.class, user, job);
    assertFalse(result);
}
Also used : User(hudson.model.User) Job(hudson.model.Job) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 73 with User

use of hudson.model.User in project blueocean-plugin by jenkinsci.

the class AbstractBitbucketScm method getOrganizations.

@Override
public Container<ScmOrganization> getOrganizations() {
    User authenticatedUser = getAuthenticatedUser();
    StaplerRequest request = Stapler.getCurrentRequest();
    Preconditions.checkNotNull(request, "This request must be made in HTTP context");
    String credentialId = BitbucketCredentialUtils.computeCredentialId(getCredentialIdFromRequest(request), getId(), getUri());
    List<ErrorMessage.Error> errors = new ArrayList<>();
    StandardUsernamePasswordCredentials credential = null;
    if (credentialId == null) {
        errors.add(new ErrorMessage.Error("credentialId", ErrorMessage.Error.ErrorCodes.MISSING.toString(), "Missing credential id. It must be provided either as HTTP header: " + X_CREDENTIAL_ID + " or as query parameter 'credentialId'"));
    } else {
        credential = CredentialsUtils.findCredential(credentialId, StandardUsernamePasswordCredentials.class, new BlueOceanDomainRequirement());
        if (credential == null) {
            errors.add(new ErrorMessage.Error("credentialId", ErrorMessage.Error.ErrorCodes.INVALID.toString(), String.format("credentialId: %s not found in user %s's credential store", credentialId, authenticatedUser.getId())));
        }
    }
    String apiUrl = request.getParameter("apiUrl");
    if (StringUtils.isBlank(apiUrl)) {
        errors.add(new ErrorMessage.Error("apiUrl", ErrorMessage.Error.ErrorCodes.MISSING.toString(), "apiUrl is required parameter"));
    }
    if (!errors.isEmpty()) {
        throw new ServiceException.BadRequestException(new ErrorMessage(400, "Failed to return Bitbucket organizations").addAll(errors));
    } else {
        apiUrl = normalizeApiUrl(apiUrl);
        BitbucketApiFactory apiFactory = BitbucketApiFactory.resolve(this.getId());
        if (apiFactory == null) {
            throw new ServiceException.UnexpectedErrorException("BitbucketApiFactory to handle apiUrl " + apiUrl + " not found");
        }
        Preconditions.checkNotNull(credential);
        final BitbucketApi api = apiFactory.create(apiUrl, credential);
        return new Container<ScmOrganization>() {

            @Override
            public ScmOrganization get(String name) {
                return new BitbucketOrg(api.getOrg(name), api, getLink());
            }

            @Override
            public Link getLink() {
                return AbstractBitbucketScm.this.getLink().rel("organizations");
            }

            @Override
            public Iterator<ScmOrganization> iterator() {
                return iterator(0, 100);
            }

            @Override
            public Iterator<ScmOrganization> iterator(int start, int limit) {
                if (limit <= 0) {
                    limit = PagedResponse.DEFAULT_LIMIT;
                }
                if (start < 0) {
                    start = 0;
                }
                int page = (start / limit) + 1;
                return Lists.transform(api.getOrgs(page, limit).getValues(), new Function<BbOrg, ScmOrganization>() {

                    @Nullable
                    @Override
                    public ScmOrganization apply(@Nullable BbOrg input) {
                        if (input != null) {
                            return new BitbucketOrg(input, api, getLink());
                        }
                        return null;
                    }
                }).iterator();
            }
        };
    }
}
Also used : User(hudson.model.User) StaplerRequest(org.kohsuke.stapler.StaplerRequest) ArrayList(java.util.ArrayList) BbOrg(io.jenkins.blueocean.blueocean_bitbucket_pipeline.model.BbOrg) StandardUsernamePasswordCredentials(com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials) Function(com.google.common.base.Function) Container(io.jenkins.blueocean.rest.model.Container) ScmOrganization(io.jenkins.blueocean.rest.impl.pipeline.scm.ScmOrganization) BlueOceanDomainRequirement(io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainRequirement) ErrorMessage(io.jenkins.blueocean.commons.ErrorMessage) Nullable(javax.annotation.Nullable)

Example 74 with User

use of hudson.model.User in project blueocean-plugin by jenkinsci.

the class GitReadSaveService method saveContent.

@Override
public Object saveContent(@Nonnull StaplerRequest req, @Nonnull Item item) {
    item.checkPermission(Item.CONFIGURE);
    User user = User.current();
    if (user == null) {
        throw new ServiceException.UnauthorizedException("Not authenticated");
    }
    try {
        // parse json...
        JSONObject json = JSONObject.fromObject(IOUtils.toString(req.getReader()));
        GitReadSaveRequest r = makeSaveRequest(item, json);
        r.save();
        return new GitFile(new GitContent(r.filePath, user.getId(), r.gitSource.getRemote(), r.filePath, 0, "sha", null, "", r.branch, r.sourceBranch, true, ""));
    } catch (IOException e) {
        throw new ServiceException.UnexpectedErrorException("Unable to save file content", e);
    }
}
Also used : User(hudson.model.User) JSONObject(net.sf.json.JSONObject) ServiceException(io.jenkins.blueocean.commons.ServiceException) IOException(java.io.IOException) GitContent(io.jenkins.blueocean.rest.impl.pipeline.scm.GitContent)

Example 75 with User

use of hudson.model.User in project blueocean-plugin by jenkinsci.

the class GitScm method validateAndCreate.

@Override
public HttpResponse validateAndCreate(@JsonBody JSONObject request) {
    boolean requirePush = request.has("requirePush");
    final String repositoryUrl;
    final AbstractGitSCMSource scmSource;
    if (request.has("repositoryUrl")) {
        scmSource = null;
        repositoryUrl = request.getString("repositoryUrl");
    } else {
        try {
            String fullName = request.getJSONObject("pipeline").getString("fullName");
            SCMSourceOwner item = Jenkins.getInstance().getItemByFullName(fullName, SCMSourceOwner.class);
            if (item != null) {
                scmSource = (AbstractGitSCMSource) item.getSCMSources().iterator().next();
                repositoryUrl = scmSource.getRemote();
            } else {
                return HttpResponses.errorJSON("No repository found for: " + fullName);
            }
        } catch (JSONException e) {
            return HttpResponses.errorJSON("No repositoryUrl or pipeline.fullName specified in request.");
        } catch (RuntimeException e) {
            return HttpResponses.errorWithoutStack(ServiceException.INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }
    try {
        String credentialId = request.getString("credentialId");
        User user = User.current();
        if (user == null) {
            throw new ServiceException.UnauthorizedException("Not authenticated");
        }
        final StandardCredentials creds = CredentialsMatchers.firstOrNull(CredentialsProvider.lookupCredentials(StandardCredentials.class, Jenkins.getInstance(), Jenkins.getAuthentication(), (List<DomainRequirement>) null), CredentialsMatchers.allOf(CredentialsMatchers.withId(credentialId)));
        if (creds == null) {
            throw new ServiceException.NotFoundException("No credentials found for: " + credentialId);
        }
        if (requirePush) {
            String branch = request.getString("branch");
            new GitBareRepoReadSaveRequest(scmSource, branch, null, branch, null, null).invokeOnScm(new GitSCMFileSystem.FSFunction<Void>() {

                @Override
                public Void invoke(Repository repository) throws IOException, InterruptedException {
                    GitUtils.validatePushAccess(repository, repositoryUrl, creds);
                    return null;
                }
            });
        } else {
            List<ErrorMessage.Error> errors = GitUtils.validateCredentials(repositoryUrl, creds);
            if (!errors.isEmpty()) {
                throw new ServiceException.UnauthorizedException(errors.get(0).getMessage());
            }
        }
    } catch (Exception e) {
        return HttpResponses.errorWithoutStack(ServiceException.PRECONDITION_REQUIRED, e.getMessage());
    }
    return HttpResponses.okJSON();
}
Also used : User(hudson.model.User) SCMSourceOwner(jenkins.scm.api.SCMSourceOwner) GitSCMFileSystem(jenkins.plugins.git.GitSCMFileSystem) JSONException(net.sf.json.JSONException) IOException(java.io.IOException) JSONException(net.sf.json.JSONException) IOException(java.io.IOException) ServiceException(io.jenkins.blueocean.commons.ServiceException) Repository(org.eclipse.jgit.lib.Repository) AbstractGitSCMSource(jenkins.plugins.git.AbstractGitSCMSource) List(java.util.List) StandardCredentials(com.cloudbees.plugins.credentials.common.StandardCredentials)

Aggregations

User (hudson.model.User)105 Test (org.junit.Test)71 Map (java.util.Map)42 ImmutableMap (com.google.common.collect.ImmutableMap)38 PipelineBaseTest (io.jenkins.blueocean.rest.impl.pipeline.PipelineBaseTest)26 Mailer (hudson.tasks.Mailer)24 ServiceException (io.jenkins.blueocean.commons.ServiceException)21 StaplerRequest (org.kohsuke.stapler.StaplerRequest)14 MultiBranchProject (jenkins.branch.MultiBranchProject)13 List (java.util.List)12 JSONObject (net.sf.json.JSONObject)12 GitContent (io.jenkins.blueocean.rest.impl.pipeline.scm.GitContent)8 IOException (java.io.IOException)8 Domain (com.cloudbees.plugins.credentials.domains.Domain)7 BlueOceanDomainRequirement (io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainRequirement)7 Authentication (org.acegisecurity.Authentication)7 CredentialsStore (com.cloudbees.plugins.credentials.CredentialsStore)6 StandardUsernamePasswordCredentials (com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials)6 BufferedReader (java.io.BufferedReader)6 StringReader (java.io.StringReader)6