Java Code Examples for hudson.util.FormValidation#error()

The following examples show how to use hudson.util.FormValidation#error() . 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: UpdateField.java    From jira-ext-plugin with Apache License 2.0 6 votes vote down vote up
public HttpResponse doQueryJiraFields(@QueryParameter String issueKey)
{
    try
    {
        if (!Config.getGlobalConfig().isJiraConfigComplete())
        {
            return FormValidation.error("JIRA settings are not set in global config");
        }
        final Map<String, String> jiraFields = getJiraClientSvc().getJiraFields(issueKey);
        return new ForwardToView(this, "/org/jenkinsci/plugins/jiraext/view/UpdateField/jiraFields.jelly")
                .with("jiraFieldMap", jiraFields);
    }
    catch (Throwable t)
    {
        String message =  "Error finding FieldIds for issueKey: " + issueKey;
        logger.log(Level.WARNING, message, t);
        return FormValidation.error(t, message);
    }
}
 
Example 2
Source File: GroovyParser.java    From warnings-ng-plugin with MIT License 6 votes vote down vote up
/**
 * Performs on-the-fly validation on the regular expression.
 *
 * @param regexp
 *         the regular expression
 *
 * @return the validation result
 */
public FormValidation doCheckRegexp(@QueryParameter(required = true) final String regexp) {
    try {
        if (StringUtils.isBlank(regexp)) {
            return FormValidation.error(Messages.GroovyParser_Error_Regexp_isEmpty());
        }
        Pattern pattern = Pattern.compile(regexp);
        Ensure.that(pattern).isNotNull();

        return FormValidation.ok();
    }
    catch (PatternSyntaxException exception) {
        return FormValidation.error(
                Messages.GroovyParser_Error_Regexp_invalid(exception.getLocalizedMessage()));
    }
}
 
Example 3
Source File: CodeBuildBaseCredentials.java    From aws-codebuild-jenkins-plugin with Apache License 2.0 6 votes vote down vote up
public FormValidation doCheckIamRoleArn(@QueryParameter("proxyHost") final String proxyHost,
                                        @QueryParameter("proxyPort") final String proxyPort,
                                        @QueryParameter("accessKey") final String accessKey,
                                        @QueryParameter("secretKey") final String secretKey,
                                        @QueryParameter("iamRoleArn") final String iamRoleArn,
                                        @QueryParameter("externalId") final String externalId) {

    if (accessKey.isEmpty() || secretKey.isEmpty()) {
        return FormValidation.error("AWS access and secret keys are required to use an IAM role for authorization");
    }

    if(iamRoleArn.isEmpty()) {
        return FormValidation.ok();
    }

    try {

        AWSCredentials initialCredentials = new BasicAWSCredentials(accessKey, secretKey);

        AssumeRoleRequest assumeRequest = new AssumeRoleRequest()
                .withRoleArn(iamRoleArn)
                .withExternalId(externalId)
                .withDurationSeconds(3600)
                .withRoleSessionName(ROLE_SESSION_NAME);

        new AWSSecurityTokenServiceClient(initialCredentials, getClientConfiguration(proxyHost, proxyPort)).assumeRole(assumeRequest);

    } catch (Exception e) {
        String errorMessage = e.getMessage();
        if(errorMessage.length() >= ERROR_MESSAGE_MAX_LENGTH) {
            errorMessage = errorMessage.substring(ERROR_MESSAGE_MAX_LENGTH);
        }
        return FormValidation.error("Authorization failed: " + errorMessage);
    }
    return FormValidation.ok("IAM role authorization successful.");
}
 
Example 4
Source File: GitLabServer.java    From gitlab-branch-source-plugin with MIT License 6 votes vote down vote up
/**
 * Checks that the supplied URL looks like a valid Jenkins root URL.
 *
 * @param hooksRootUrl the URL to check.
 * @return the validation results.
 */
public static FormValidation doCheckHooksRootUrl(@QueryParameter String hooksRootUrl) {
    if (StringUtils.isBlank(hooksRootUrl)) {
        return FormValidation.ok();
    }
    try {
        new URL(hooksRootUrl);
    } catch (MalformedURLException e) {
        LOGGER.log(Level.FINEST, "Malformed hooks root URL: {0}", hooksRootUrl);
        return FormValidation.error("Malformed url (%s)", e.getMessage());
    }
    if (hooksRootUrl.endsWith("/post")
            || hooksRootUrl.contains("/gitlab-webhook")
            || hooksRootUrl.contains("/gitlab-systemhook")) {
        LOGGER.log(Level.FINEST, "Dubious hooks root URL: {0}", hooksRootUrl);
        return FormValidation.warning("This looks like a full webhook URL, it should only be a root URL.");
    }
    return FormValidation.ok();
}
 
Example 5
Source File: ZAProxy.java    From zaproxy-plugin with MIT License 6 votes vote down vote up
/**
 * Performs on-the-fly validation of the form field 'filenameSaveSession'.
 * <p>
 * If the user wants to save session whereas a session is already loaded, 
 * the relative path to the saved session must be different from the relative path to the loaded session.
 *
 * @param filenameLoadSession
 *      Parameter to compare with filenameSaveSession.
 * @param filenameSaveSession
 *      This parameter receives the value that the user has typed.
 * @return
 *      Indicates the outcome of the validation. This is sent to the browser.
 *      <p>
 *      Note that returning {@link FormValidation#error(String)} does not
 *      prevent the form from being saved. It just means that a message
 *      will be displayed to the user.
 */
public FormValidation doCheckFilenameSaveSession(
		@QueryParameter("filenameLoadSession") final String filenameLoadSession,
		@QueryParameter("filenameSaveSession") final String filenameSaveSession) {
	// Contains just the name of the session (without workspace path and extension)
	String cleanFilenameLoadSession = null;
	if(workspace != null) {
		cleanFilenameLoadSession = filenameLoadSession
				.replace(workspace.getRemote(), "") // Remove workspace path
				.replaceFirst("\\\\", "") // Remove separator after workspace path if windows
				.replaceFirst("/", ""); // Remove separator after workspace path if Unix
			
		if(!cleanFilenameLoadSession.isEmpty() && 
				(filenameSaveSession.equals(cleanFilenameLoadSession) 
						|| filenameSaveSession.equals(cleanFilenameLoadSession.replace(FILE_SESSION_EXTENSION, ""))) )
			return FormValidation.error("The saved session filename is the same of the loaded session filename.");
	}
	
	if(!filenameLoadSession.isEmpty())
		return FormValidation.warning("A session is loaded, so it's not necessary to save session");
	
	if(!FilenameUtils.getExtension(filenameSaveSession).isEmpty())
		return FormValidation.warning("A file extension is not necessary. A default file extension will be added (.session)");
	return FormValidation.ok();
}
 
Example 6
Source File: PersonalAccessTokenImpl.java    From gitea-plugin with MIT License 6 votes vote down vote up
/**
 * Sanity check for a Gitea access token.
 *
 * @param value the token.
 * @return the resulst of the sanity check.
 */
@Restricted(NoExternalUse.class) // stapler
@SuppressWarnings("unused") // stapler
public FormValidation doCheckToken(@QueryParameter String value) {
    if (value == null || value.isEmpty()) {
        return FormValidation.error(Messages.PersonalAccessTokenImpl_tokenRequired());
    }
    Secret secret = Secret.fromString(value);
    if (StringUtils.equals(value, secret.getPlainText())) {
        if (value.length() != 40) {
            return FormValidation.error(Messages.PersonalAccessTokenImpl_tokenWrongLength());
        }
    } else if (secret.getPlainText().length() != 40) {
        return FormValidation.warning(Messages.PersonalAccessTokenImpl_tokenWrongLength());
    }
    return FormValidation.ok();
}
 
Example 7
Source File: NomadCloud.java    From jenkins-nomad with MIT License 5 votes vote down vote up
public FormValidation doTestConnection(@QueryParameter("nomadUrl") String nomadUrl) {
    try {
        Request request = new Request.Builder()
                .url(nomadUrl + "/v1/agent/self")
                .build();

        OkHttpClient client = new OkHttpClient();
        client.newCall(request).execute().body().close();

        return FormValidation.ok("Nomad API request succeeded.");
    } catch (Exception e) {
        return FormValidation.error(e.getMessage());
    }
}
 
Example 8
Source File: DingTalkRobotConfig.java    From dingtalk-plugin with MIT License 5 votes vote down vote up
/**
 * webhook 字段必填
 *
 * @param value webhook
 * @return 是否校验成功
 */
public FormValidation doCheckWebhook(@QueryParameter String value) {
  if (StringUtils.isBlank(value)) {
    return FormValidation.error(
        Messages.RobotConfigFormValidation_webhook()
    );
  }
  return FormValidation.ok();
}
 
Example 9
Source File: SQSScmConfig.java    From aws-codecommit-trigger-plugin with Apache License 2.0 5 votes vote down vote up
public FormValidation doCheckUrl(@QueryParameter final String url) {
    if (StringUtils.isBlank(url)) {
        return FormValidation.warning(Messages.warningBlankUrl());
    }

    return com.ribose.jenkins.plugin.awscodecommittrigger.utils.StringUtils.isCodeCommitRepo(url)
        ? FormValidation.ok()
        : FormValidation.error(Messages.errorCodeCommitUrlInvalid());
}
 
Example 10
Source File: GridParameter.java    From at.info-knowledge-base with MIT License 5 votes vote down vote up
public FormValidation doCheckNodeJsonPath(@QueryParameter final String value) {
    if (value.length() == 0) {
        return FormValidation.error("Please set a valid path");
    }

    return FormValidation.ok();
}
 
Example 11
Source File: DockerBuilderPublisher.java    From docker-plugin with MIT License 5 votes vote down vote up
public FormValidation doCheckTagsString(@QueryParameter String tagsString) {
    try {
        verifyTags(tagsString);
    } catch (Throwable t) {
        return FormValidation.error(t.getMessage());
    }
    return FormValidation.ok();
}
 
Example 12
Source File: KubernetesCloud.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
public FormValidation doCheckWebSocket(@QueryParameter boolean webSocket, @QueryParameter boolean directConnection, @QueryParameter String jenkinsTunnel) {
    if (webSocket) {
        if (!WebSockets.isSupported()) {
            return FormValidation.error("WebSocket support is not enabled in this Jenkins installation");
        }
        if (Util.fixEmpty(jenkinsTunnel) != null) {
            return FormValidation.error("Tunneling is not currently supported in WebSocket mode");
        }
    }
    return FormValidation.ok();
}
 
Example 13
Source File: GitHubBranchRepository.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@RequirePOST
public FormValidation doBuild(StaplerRequest req) throws IOException {
    FormValidation result;

    try {
        if (!job.hasPermission(Item.BUILD)) {
            return FormValidation.error("Forbidden");
        }

        final String param = "branchName";
        String branchName = null;
        if (req.hasParameter(param)) {
            branchName = req.getParameter(param);
        }
        if (isNull(branchName) || !getBranches().containsKey(branchName)) {
            return FormValidation.error("No branch to build");
        }

        final GitHubBranch localBranch = getBranches().get(branchName);
        final GitHubBranchCause cause = new GitHubBranchCause(localBranch, this, "Manual run.", false);
        final JobRunnerForBranchCause runner = new JobRunnerForBranchCause(getJob(),
                ghBranchTriggerFromJob(job));
        final QueueTaskFuture<?> queueTaskFuture = runner.startJob(cause);

        if (nonNull(queueTaskFuture)) {
            result = FormValidation.ok("Build scheduled");
        } else {
            result = FormValidation.warning("Build not scheduled");
        }
    } catch (Exception e) {
        LOG.error("Can't start build", e.getMessage());
        result = FormValidation.error(e, "Can't start build: " + e.getMessage());
    }

    return result;
}
 
Example 14
Source File: DockerConnector.java    From yet-another-docker-plugin with MIT License 5 votes vote down vote up
@SuppressFBWarnings(value = "REC_CATCH_EXCEPTION", justification = "docker-java uses runtime exceptions")
@RequirePOST
public FormValidation doTestConnection(
        @QueryParameter String serverUrl,
        @QueryParameter String apiVersion,
        @QueryParameter String credentialsId,
        @QueryParameter ConnectorType connectorType,
        @QueryParameter Integer connectTimeout,
        @QueryParameter Integer readTimeout
) throws IOException, ServletException, DockerException {
    try {
        DefaultDockerClientConfig.Builder configBuilder = new DefaultDockerClientConfig.Builder()
                .withApiVersion(apiVersion)
                .withDockerHost(serverUrl);

        final DockerClient testClient = newClientBuilderForConnector()
                .withConfigBuilder(configBuilder)
                .withConnectorType(connectorType)
                .withCredentialsId(credentialsId)
                .withConnectTimeout(connectTimeout)
                .withReadTimeout(readTimeout)
                .build();

        Version verResult = testClient.versionCmd().exec();

        return ok(reflectionToString(verResult, MULTI_LINE_STYLE));
    } catch (Exception e) {
        return FormValidation.error(e, e.getMessage());
    }
}
 
Example 15
Source File: AppCenterRecorder.java    From appcenter-plugin with MIT License 5 votes vote down vote up
@SuppressWarnings("unused")
public FormValidation doCheckOwnerName(@QueryParameter String value) {
    if (value.isEmpty()) {
        return FormValidation.error(Messages.AppCenterRecorder_DescriptorImpl_errors_missingOwnerName());
    }

    final Validator validator = new UsernameValidator();

    if (!validator.isValid(value)) {
        return FormValidation.error(Messages.AppCenterRecorder_DescriptorImpl_errors_invalidOwnerName());
    }

    return FormValidation.ok();
}
 
Example 16
Source File: ModelValidation.java    From warnings-ng-plugin with MIT License 5 votes vote down vote up
/**
 * Performs on-the-fly validation of the reference job.
 *
 * @param referenceJobName
 *         the reference job
 *
 * @return the validation result
 */
public FormValidation validateJob(final String referenceJobName) {
    if (NO_REFERENCE_JOB.equals(referenceJobName)
            || StringUtils.isBlank(referenceJobName)
            || jenkins.getJob(referenceJobName).isPresent()) {
        return FormValidation.ok();
    }
    return FormValidation.error(Messages.FieldValidator_Error_ReferenceJobDoesNotExist());
}
 
Example 17
Source File: SignArtifactPlugin.java    From jenkins-android-signing with Apache License 2.0 5 votes vote down vote up
public FormValidation doCheckSelection(@AncestorInPath AbstractProject project, @QueryParameter String value) throws IOException, InterruptedException {
    if (project.getSomeWorkspace() != null) {
        String msg = project.getSomeWorkspace().validateAntFileMask(value);
        if (msg != null) {
            return FormValidation.error(msg);
        }
        return FormValidation.ok();
    } else {
        return FormValidation.warning(Messages.noworkspace());
    }
}
 
Example 18
Source File: ParamVerify.java    From jenkins-plugin with Apache License 2.0 4 votes vote down vote up
public static FormValidation doCheckProdTag(@QueryParameter String value) {
    if (value.length() == 0)
        return FormValidation
                .error("Please set the name of the image stream tag that serves as the destination or target of the operation");
    return FormValidation.ok();
}
 
Example 19
Source File: OicSecurityRealm.java    From oic-auth-plugin with MIT License 4 votes vote down vote up
public FormValidation doCheckClientSecret(@QueryParameter String clientSecret) {
    if (clientSecret == null || clientSecret.trim().length() == 0) {
        return FormValidation.error("Client secret is required.");
    }
    return FormValidation.ok();
}
 
Example 20
Source File: DashboardBuilder.java    From environment-dashboard-plugin with MIT License 4 votes vote down vote up
public FormValidation doCheckBuildNumber(@QueryParameter String value) throws IOException, ServletException {
	if (value.length() == 0)
		return FormValidation.error("Please set the Build variable e.g: ${BUILD_NUMBER}.");
	return FormValidation.ok();
}