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;
}
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);
}
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();
}
};
}
}
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);
}
}
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();
}
Aggregations