下面列出了hudson.model.Descriptor.FormException#org.kohsuke.stapler.interceptor.RequirePOST 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@SuppressWarnings("unused")
@RequirePOST
public FormValidation doCreateTokenByPassword(
@QueryParameter String serverUrl,
@QueryParameter String login,
@QueryParameter String password) {
Jenkins.get().checkPermission(Jenkins.ADMINISTER);
try {
String tokenName = UUID.randomUUID().toString();
String token = AccessTokenUtils.createPersonalAccessToken(
defaultIfBlank(serverUrl, GitLabServer.GITLAB_SERVER_URL),
login,
password,
tokenName,
GL_PLUGIN_REQUIRED_SCOPE
);
tokenName = getShortName(tokenName);
createCredentials(serverUrl, token, login, tokenName);
return FormValidation.ok(
"Created credentials with id %s", tokenName
);
} catch (GitLabApiException e) {
return FormValidation
.error(e, "Can't create GL token for %s - %s", login, e.getMessage());
}
}
@RequirePOST
public FormValidation doValidateTestDockerApiConnection(@QueryParameter("uri") String uri,
@QueryParameter("credentialsId") String credentialsId) throws IOException {
if (uri.endsWith("/")) {
return FormValidation.error("URI must not have trailing /");
}
Object response = new PingRequest(uri).execute();
if (response instanceof ApiException) {
return FormValidation.error(((ApiException) response).getCause(),
"Couldn't ping docker api: " + uri + "/_ping");
}
if (response instanceof ApiError) {
return FormValidation.error(((ApiError) response).getMessage());
}
return FormValidation.ok("Connection successful");
}
/**
* Performs on-the-fly validation on the Groovy script.
*
* @param script
* the script
*
* @return the validation result
*/
@RequirePOST
public FormValidation doCheckScript(@QueryParameter(required = true) final String script) {
if (isNotAllowedToRunScripts()) {
return NO_RUN_SCRIPT_PERMISSION_WARNING;
}
try {
if (StringUtils.isBlank(script)) {
return FormValidation.error(Messages.GroovyParser_Error_Script_isEmpty());
}
GroovyExpressionMatcher matcher = new GroovyExpressionMatcher(script);
Script compiled = matcher.compile();
Ensure.that(compiled).isNotNull();
return FormValidation.ok();
}
catch (CompilationFailedException exception) {
return FormValidation.error(
Messages.GroovyParser_Error_Script_invalid(exception.getLocalizedMessage()));
}
}
/**
* Parses the example message with the specified regular expression and script.
*
* @param example
* example that should be resolve to a warning
* @param regexp
* the regular expression
* @param script
* the script
*
* @return the validation result
*/
@RequirePOST
public FormValidation doCheckExample(@QueryParameter final String example,
@QueryParameter final String regexp, @QueryParameter final String script) {
if (isNotAllowedToRunScripts()) {
return NO_RUN_SCRIPT_PERMISSION_WARNING;
}
if (StringUtils.isNotBlank(example) && StringUtils.isNotBlank(regexp) && StringUtils.isNotBlank(script)) {
FormValidation response = parseExample(script, example, regexp, containsNewline(regexp));
if (example.length() <= MAX_EXAMPLE_SIZE) {
return response;
}
return FormValidation.aggregate(Arrays.asList(
FormValidation.warning(Messages.GroovyParser_long_examples_will_be_truncated()), response));
}
else {
return FormValidation.ok();
}
}
@RequirePOST
public FormValidation doTestZookeeperConnection(@QueryParameter("zookeeperURL") final String zookeeperURL)
throws IOException, ServletException {
if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
return FormValidation.error("Need admin permission to perform this action");
}
try {
String[] hostport = zookeeperURL.split(":");
String host = hostport[0];
int port = Integer.parseInt(hostport[1]);
testConnection(host, port);
return FormValidation.ok("Success");
} catch (Exception e) {
return FormValidation.error("Connection error : " + e.getMessage());
}
}
@RequirePOST
public FormValidation doTestBrokerConnection(@QueryParameter("brokerURL") final String brokerURL)
throws IOException, ServletException {
if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
return FormValidation.error("Need admin permission to perform this action");
}
try {
String[] hostport = brokerURL.split(":");
String host = hostport[0];
int port = Integer.parseInt(hostport[1]);
testConnection(host, port);
return FormValidation.ok("Success");
} catch (Exception e) {
return FormValidation.error("Connection error : " + e.getMessage());
}
}
@RequirePOST
public ListBoxModel doFillKubernetesCredentialsIdItems() {
Jenkins.get().checkPermission(Jenkins.ADMINISTER);
return new StandardListBoxModel().withEmptySelection()
.withMatching(
CredentialsMatchers.anyOf(
CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
CredentialsMatchers.instanceOf(FileCredentials.class),
CredentialsMatchers.instanceOf(TokenProducer.class),
CredentialsMatchers.instanceOf(StandardCertificateCredentials.class),
CredentialsMatchers.instanceOf(StringCredentials.class)),
CredentialsProvider.lookupCredentials(StandardCredentials.class,
Jenkins.get(),
ACL.SYSTEM,
Collections.EMPTY_LIST
));
}
@RequirePOST
public ListBoxModel doFillCredentialsIdItems(@QueryParameter String serverUrl) {
Jenkins.get().checkPermission(Jenkins.ADMINISTER);
return new StandardListBoxModel().withEmptySelection()
.withMatching(
CredentialsMatchers.anyOf(
CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
CredentialsMatchers.instanceOf(FileCredentials.class),
CredentialsMatchers.instanceOf(TokenProducer.class),
CredentialsMatchers.instanceOf(StandardCertificateCredentials.class),
CredentialsMatchers.instanceOf(StringCredentials.class)),
CredentialsProvider.lookupCredentials(StandardCredentials.class,
Jenkins.get(),
ACL.SYSTEM,
serverUrl != null ? URIRequirementBuilder.fromUri(serverUrl).build()
: Collections.EMPTY_LIST
));
}
@RequirePOST
@Restricted(NoExternalUse.class)
public void doCheck(StaplerRequest req, StaplerResponse res) throws Exception {
if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
res.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
final Map<Source, String> issues = checkWith(YamlSource.of(req));
res.setContentType("application/json");
final JSONArray warnings = new JSONArray();
issues.entrySet().stream().map(e -> new JSONObject().accumulate("line", e.getKey().line).accumulate("warning", e.getValue()))
.forEach(warnings::add);
warnings.write(res.getWriter());
}
@RequirePOST
public void doIndex(StaplerRequest request, StaplerResponse response) throws IOException {
String token = getReloadTokenProperty();
if (Strings.isNullOrEmpty(token)) {
response.sendError(404);
LOGGER.warning("Configuration reload via token is not enabled");
} else {
String requestToken = getRequestToken(request);
if (token.equals(requestToken)) {
LOGGER.info("Configuration reload triggered via token");
try (ACLContext ignored = ACL.as(ACL.SYSTEM)) {
ConfigurationAsCode.get().configure();
}
} else {
response.sendError(401);
LOGGER.warning("Invalid token received, not reloading configuration");
}
}
}
@RequirePOST
@SuppressWarnings("unused") // used by jelly
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context, @QueryParameter String serverUrl) {
Jenkins.get().checkPermission(Jenkins.ADMINISTER);
StandardListBoxModel result = new StandardListBoxModel();
result.includeEmptyValue();
result.includeMatchingAs(
ACL.SYSTEM,
context,
StandardCredentials.class,
serverUrl != null ? URIRequirementBuilder.fromUri(serverUrl).build()
: Collections.EMPTY_LIST,
CredentialsMatchers.anyOf(
AuthenticationTokens.matcher(KubernetesAuth.class)
)
);
return result;
}
@RequirePOST
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context) {
AccessControlled ac = (context instanceof AccessControlled ? (AccessControlled) context : Jenkins.getInstance());
if (!ac.hasPermission(Jenkins.ADMINISTER)) {
return new ListBoxModel();
}
List<StandardCredentials> credentials =
CredentialsProvider.lookupCredentials(StandardCredentials.class,
context,
ACL.SYSTEM,
Collections.emptyList());
return new CredentialsListBoxModel()
.includeEmptyValue()
.withMatching(CredentialsMatchers.always(), credentials);
}
@RequirePOST
public FormValidation doClearRepo() throws IOException {
FormValidation result;
try {
if (job.hasPermission(Item.DELETE)) {
pulls.clear();
save();
result = FormValidation.ok("Pulls deleted");
} else {
result = FormValidation.error("Forbidden");
}
} catch (Exception e) {
LOG.error("Can\'t delete repository file '{}'",
configFile.getFile().getAbsolutePath(), e);
result = FormValidation.error(e, "Can't delete: %s", e.getMessage());
}
return result;
}
/**
* Run trigger from web.
*/
@RequirePOST
public FormValidation doRunTrigger() {
FormValidation result;
try {
if (job.hasPermission(Item.BUILD)) {
GitHubPRTrigger trigger = JobHelper.ghPRTriggerFromJob(job);
if (trigger != null) {
trigger.run();
result = FormValidation.ok("GitHub PR trigger run");
LOG.debug("GitHub PR trigger run for {}", job);
} else {
LOG.error("GitHub PR trigger not available for {}", job);
result = FormValidation.error("GitHub PR trigger not available");
}
} else {
LOG.warn("No permissions to run GitHub PR trigger");
result = FormValidation.error("Forbidden");
}
} catch (Exception e) {
LOG.error("Can't run trigger", e);
result = FormValidation.error(e, "Can't run trigger: %s", e.getMessage());
}
return result;
}
@RequirePOST
public FormValidation doRebuildAllFailed() throws IOException {
FormValidation result;
try {
if (job.hasPermission(Item.BUILD)) {
Map<Integer, List<Run<?, ?>>> builds = getAllPrBuilds();
for (List<Run<?, ?>> buildList : builds.values()) {
if (!buildList.isEmpty() && Result.FAILURE.equals(buildList.get(0).getResult())) {
Run<?, ?> lastBuild = buildList.get(0);
rebuild(lastBuild);
}
}
result = FormValidation.ok("Rebuild scheduled");
} else {
result = FormValidation.error("Forbidden");
}
} catch (Exception e) {
LOG.error("Can't start rebuild", e);
result = FormValidation.error(e, "Can't start rebuild: %s", e.getMessage());
}
return result;
}
@Override
@RequirePOST
public FormValidation doClearRepo() throws IOException {
LOG.debug("Got clear GitHub Branch repo request for {}", getJob().getFullName());
FormValidation result;
try {
if (job.hasPermission(Item.DELETE)) {
branches.clear();
save();
result = FormValidation.ok("Branches deleted");
} else {
result = FormValidation.error("Forbidden");
}
} catch (Exception e) {
LOG.error("Can't delete repository file '{}'.",
configFile.getFile().getAbsolutePath(), e);
result = FormValidation.error(e, "Can't delete: " + e.getMessage());
}
return result;
}
@Override
@RequirePOST
public FormValidation doRunTrigger() throws IOException {
FormValidation result;
try {
if (job.hasPermission(Item.BUILD)) {
GitHubBranchTrigger trigger = ghBranchTriggerFromJob(job);
if (trigger != null) {
trigger.run();
result = FormValidation.ok("GitHub Branch trigger run");
LOG.debug("GitHub Branch trigger run for {}", job);
} else {
LOG.error("GitHub Branch trigger not available for {}", job);
result = FormValidation.error("GitHub Branch trigger not available");
}
} else {
LOG.warn("No permissions to run GitHub Branch trigger");
result = FormValidation.error("Forbidden");
}
} catch (Exception e) {
LOG.error("Can't run trigger", e.getMessage());
result = FormValidation.error(e, "Can't run trigger: %s", e.getMessage());
}
return result;
}
@Override
@RequirePOST
public FormValidation doRebuildAllFailed() throws IOException {
FormValidation result;
try {
if (job.hasPermission(Item.BUILD)) {
Map<String, List<Run<?, ?>>> builds = getAllBranchBuilds();
for (List<Run<?, ?>> buildList : builds.values()) {
if (!buildList.isEmpty() && Result.FAILURE.equals(buildList.get(0).getResult())) {
Run<?, ?> lastBuild = buildList.get(0);
rebuild(lastBuild);
}
}
result = FormValidation.ok("Rebuild scheduled");
} else {
result = FormValidation.error("Forbidden");
}
} catch (Exception e) {
LOG.error("Can't start rebuild", e.getMessage());
result = FormValidation.error(e, "Can't start rebuild: %s", e.getMessage());
}
return result;
}
@RequirePOST
public void doPurgeSubmit(final StaplerRequest req, StaplerResponse res)
throws IOException, ServletException, FormException {
checkPermission(Jenkins.ADMINISTER);
Connection conn = null;
Statement stat = null;
conn = DBConnection.getConnection();
try {
assert conn != null;
stat = conn.createStatement();
stat.execute("TRUNCATE TABLE env_dashboard");
} catch (SQLException e) {
System.out.println("E15: Could not truncate table env_dashboard.\n" + e.getMessage());
} finally {
DBConnection.closeConnection();
}
res.forwardToPreviousPage(req);
}
@RequirePOST
@Restricted(DoNotUse.class) // WebOnly
@SuppressWarnings("unused")
public FormValidation doTestConnection(
@QueryParameter final String site,
@QueryParameter final String clientId,
@QueryParameter final String credentialsId) {
Jenkins.get().checkPermission(Jenkins.ADMINISTER);
final Optional<String> maybeCloudId = cloudIdResolver.getCloudId("https://" + site);
if (!maybeCloudId.isPresent()) {
return FormValidation.error("Failed to resolve Jira Cloud site: " + site);
}
final Optional<String> maybeSecret = secretRetriever.getSecretFor(credentialsId);
if (!maybeSecret.isPresent()) {
return FormValidation.error("Failed to retrieve secret");
}
final AppCredential appCredential = new AppCredential(clientId, maybeSecret.get());
final Optional<String> accessToken = accessTokenRetriever.getAccessToken(appCredential);
if (!accessToken.isPresent()) {
return FormValidation.error("Failed to validate site credentials");
}
return FormValidation.ok("Successfully validated site credentials");
}
@RequirePOST
@Restricted(NoExternalUse.class)
public void doReload(StaplerRequest request, StaplerResponse response) throws Exception {
if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
configure();
response.sendRedirect("");
}
@RequirePOST
@Restricted(NoExternalUse.class)
public void doReplace(StaplerRequest request, StaplerResponse response) throws Exception {
if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
String newSource = request.getParameter("_.newSource");
String normalizedSource = Util.fixEmptyAndTrim(newSource);
File file = new File(Util.fixNull(normalizedSource));
if (file.exists() || ConfigurationAsCode.isSupportedURI(normalizedSource)) {
List<String> candidatePaths = Collections.singletonList(normalizedSource);
List<YamlSource> candidates = getConfigFromSources(candidatePaths);
if (canApplyFrom(candidates)) {
sources = candidatePaths;
configureWith(getConfigFromSources(getSources()));
CasCGlobalConfig config = GlobalConfiguration.all().get(CasCGlobalConfig.class);
if (config != null) {
config.setConfigurationPath(normalizedSource);
config.save();
}
LOGGER.log(Level.FINE, "Replace configuration with: " + normalizedSource);
} else {
LOGGER.log(Level.WARNING, "Provided sources could not be applied");
// todo: show message in UI
}
} else {
LOGGER.log(Level.FINE, "No such source exists, applying default");
// May be do nothing instead?
configure();
}
response.sendRedirect("");
}
@RequirePOST
@Restricted(NoExternalUse.class)
public void doApply(StaplerRequest req, StaplerResponse res) throws Exception {
if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
res.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
configureWith(YamlSource.of(req));
}
/**
* Export live jenkins instance configuration as Yaml
* @throws Exception
*/
@RequirePOST
@Restricted(NoExternalUse.class)
public void doExport(StaplerRequest req, StaplerResponse res) throws Exception {
if (!Jenkins.get().hasPermission(Jenkins.SYSTEM_READ)) {
res.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
res.setContentType("application/x-yaml; charset=utf-8");
res.addHeader("Content-Disposition", "attachment; filename=jenkins.yaml");
export(res.getOutputStream());
}
@RequirePOST
@Restricted(NoExternalUse.class)
public void doViewExport(StaplerRequest req, StaplerResponse res) throws Exception {
if (!Jenkins.get().hasPermission(Jenkins.SYSTEM_READ)) {
res.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
export(out);
req.setAttribute("export", out.toString(StandardCharsets.UTF_8.name()));
req.getView(this, "viewExport.jelly").forward(req, res);
}
@RequirePOST
public FormValidation doTestConnection(@QueryParameter ("credentialsId") final String credentialsId, @QueryParameter ("gitApiUrl") final String gitApiUrl, @AncestorInPath Item context) {
context.checkPermission(Item.CONFIGURE);
try {
getGitHubIfValid(credentialsId, gitApiUrl, context);
return FormValidation.ok("Success");
} catch (Exception e) {
return FormValidation.error(e.getMessage());
}
}
@RequirePOST
public FormValidation doCheckRepo(@QueryParameter ("credentialsId") final String credentialsId,
@QueryParameter ("repo") final String repo, @QueryParameter ("account") final String account, @QueryParameter ("gitApiUrl") final String gitApiUrl, @AncestorInPath Item context) {
context.checkPermission(Item.CONFIGURE);
try {
getRepoIfValid(credentialsId, gitApiUrl, account, repo, context);
return FormValidation.ok("Success");
} catch (Exception e) {
return FormValidation.error(e.getMessage());
}
}
@RequirePOST
public FormValidation doCheckSha(@QueryParameter ("credentialsId") final String credentialsId, @QueryParameter ("repo") final String repo,
@QueryParameter ("sha") final String sha, @QueryParameter ("account") final String account, @QueryParameter ("gitApiUrl") final String gitApiUrl, @AncestorInPath Item context) {
context.checkPermission(Item.CONFIGURE);
try {
getCommitIfValid(credentialsId, gitApiUrl, account, repo, sha, context);
return FormValidation.ok("Commit seems valid");
} catch (Exception e) {
return FormValidation.error(e.getMessage());
}
}
/**
* Depending on whether the user said "yes" or "no", send him to the right place.
*/
@RequirePOST
public void doAct(StaplerRequest req, StaplerResponse rsp) throws IOException {
if (req.hasParameter("no")) {
disable(true);
rsp.sendRedirect(req.getContextPath() + "/manage");
} else {
rsp.sendRedirect(req.getContextPath() + "/configureTools");
}
}
@RequirePOST
@Restricted(NoExternalUse.class)
public FormValidation doCheckCredentialsId(@CheckForNull @AncestorInPath Item context,
@QueryParameter String apiUri,
@QueryParameter String value) {
return Connector.checkScanCredentials(context, apiUri, value);
}