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

The following examples show how to use hudson.util.FormValidation#warning() . 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: ProjectBranchesProvider.java    From gitlab-plugin with GNU General Public License v2.0 6 votes vote down vote up
private FormValidation checkMatchingBranches(@QueryParameter String value, List<String> projectBranches) {
    Set<String> matchingSpecs = new HashSet<>();
    Set<String> unknownSpecs = new HashSet<>();
    AntPathMatcherSet projectBranchesMatcherSet = new AntPathMatcherSet(projectBranches);
    for (String branchSpec : Splitter.on(',').omitEmptyStrings().trimResults().split(value)) {
        if (projectBranchesMatcherSet.contains(branchSpec)) {
            matchingSpecs.add(branchSpec);
        } else {
            unknownSpecs.add(branchSpec);
        }
    }

    if (unknownSpecs.isEmpty()) {
        return FormValidation.ok(Messages.GitLabPushTrigger_BranchesMatched(matchingSpecs.size()));
    } else {
        return FormValidation.warning(Messages.GitLabPushTrigger_BranchesNotFound(Joiner.on(", ").join(unknownSpecs)));
    }
}
 
Example 2
Source File: AWSEBDeploymentBuilder.java    From awseb-deployment-plugin with Apache License 2.0 6 votes vote down vote up
public FormValidation doCheckEnvironmentName(@QueryParameter String value, @QueryParameter boolean skipEnvironmentUpdates) {
    if (skipEnvironmentUpdates) {
        return FormValidation.ok("Environment Updates Skipped");
    }

    if (value.contains("$")) {
        return FormValidation.warning("Validation skipped due to parameter usage ('$')");
    }

    if (value.contains(",")) {
        if (!value.matches("^[\\p{Alpha}[\\p{Alnum}\\-]{0,39}]+(,\\p{Space}*[\\p{Alpha}[\\p{Alnum}\\-]{0,39}]+)*$") || value.endsWith("-")) {
            return FormValidation.error(
                    "Doesn't look like properly comma separated environment names. Each must be from 4 to 40 characters in length. The name can contain only letters, numbers, and hyphens. It cannot start or end with a hyphen");
        }
    } else {
        if (!value.matches("^\\p{Alpha}[\\p{Alnum}\\-]{0,39}$") || value.endsWith("-")) {
            return FormValidation.error(
                    "Doesn't look like an environment name. Must be from 4 to 40 characters in length. The name can contain only letters, numbers, and hyphens. It cannot start or end with a hyphen");
        }
    }

    return FormValidation.ok();
}
 
Example 3
Source File: ListGitBranchesParameterDefinition.java    From list-git-branches-parameter-plugin with MIT License 6 votes vote down vote up
public FormValidation doCheckRemoteURL(StaplerRequest req, @AncestorInPath Item context, @QueryParameter String value) {
    String url = Util.fixEmptyAndTrim(value);

    if (url == null) {
        return FormValidation.error("Repository URL is required");
    }

    if (url.indexOf('$') != -1) {
        return FormValidation.warning("This repository URL is parameterized, syntax validation skipped");
    }

    try {
        new URIish(value);
    } catch (URISyntaxException e) {
        return FormValidation.error("Repository URL is illegal");
    }
    return FormValidation.ok();
}
 
Example 4
Source File: GlobalKafkaConfiguration.java    From remoting-kafka-plugin with MIT License 6 votes vote down vote up
private FormValidation checkCredentialsId(@AncestorInPath Item item, @QueryParameter String value) {
    if (item == null) {
        if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
            return FormValidation.ok();
        }
    }
    if (value.startsWith("${") && value.endsWith("}")) {
        return FormValidation.warning("Cannot validate expression based credentials");
    }
    if (CredentialsProvider.listCredentials(
            StandardUsernamePasswordCredentials.class,
            Jenkins.get(),
            ACL.SYSTEM,
            Collections.singletonList(KAFKA_SCHEME),
            CredentialsMatchers.withId(value)
    ).isEmpty()) {
        return FormValidation.error("Cannot find currently selected credentials");
    }
    return FormValidation.ok();
}
 
Example 5
Source File: LambdaUploadBuildStepVariables.java    From aws-lambda-jenkins-plugin with MIT License 5 votes vote down vote up
public FormValidation doCheckTimeout(@QueryParameter String value, @QueryParameter String updateMode) {
    UpdateModeValue updateModeValue = UpdateModeValue.fromString(updateMode);
    if(updateModeValue == UpdateModeValue.Full || updateModeValue == UpdateModeValue.Config) {

        try {
            Integer.parseInt(value);
            return FormValidation.ok();
        } catch (NumberFormatException e) {
            return FormValidation.warning("Not a number, might evaluate to number as environment variable.");
        }
    } else {
        return FormValidation.ok();
    }
}
 
Example 6
Source File: LambdaUploadVariables.java    From aws-lambda-jenkins-plugin with MIT License 5 votes vote down vote up
public FormValidation doCheckTimeout(@QueryParameter String value, @QueryParameter String updateMode) {
    UpdateModeValue updateModeValue = UpdateModeValue.fromString(updateMode);
    if(updateModeValue == UpdateModeValue.Full || updateModeValue == UpdateModeValue.Config) {

        try {
            Integer.parseInt(value);
            return FormValidation.ok();
        } catch (NumberFormatException e) {
            return FormValidation.warning("Not a number, might evaluate to number as environment variable.");
        }
    } else {
        return FormValidation.ok();
    }
}
 
Example 7
Source File: GitHubSCMSource.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class)
public FormValidation doCheckBuildOriginPRHead(@QueryParameter boolean buildOriginBranchWithPR, @QueryParameter boolean buildOriginPRMerge, @QueryParameter boolean buildOriginPRHead) {
    if (buildOriginBranchWithPR && buildOriginPRHead) {
        return FormValidation.warning("Redundant to build an origin PR both as a branch and as an unmerged PR.");
    }
    if (buildOriginPRMerge && buildOriginPRHead) {
        return FormValidation.ok("Merged vs. unmerged PRs will be distinguished in the job name (*-merge vs. *-head).");
    }
    return FormValidation.ok();
}
 
Example 8
Source File: DockerTemplateBase.java    From docker-plugin with MIT License 5 votes vote down vote up
public FormValidation doCheckSecurityOptsString(@QueryParameter String securityOptsString) {
    final List<String> securityOpts = splitAndFilterEmptyList(securityOptsString, "\n");
    for (String securityOpt : securityOpts) {
        if ( !( securityOpt.trim().split("=").length == 2 || securityOpt.trim().startsWith( "no-new-privileges" ) ) ) {
            return FormValidation.warning("Security option may be incorrect. Please double check syntax: '%s'", securityOpt);
        }
    }
    return FormValidation.ok();
}
 
Example 9
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@POST
@Restricted(NoExternalUse.class)
public FormValidation doCheckNewSource(@QueryParameter String newSource) {
    Jenkins.get().checkPermission(Jenkins.ADMINISTER);
    String normalizedSource = Util.fixEmptyAndTrim(newSource);
    File file = new File(Util.fixNull(normalizedSource));
    if (normalizedSource == null) {
        return FormValidation.ok(); // empty, do nothing
    }
    if (!file.exists() && !ConfigurationAsCode.isSupportedURI(normalizedSource)) {
        return FormValidation.error("Configuration cannot be applied. File or URL cannot be parsed or do not exist.");
    }

    List<YamlSource> yamlSources = Collections.emptyList();
    try {
        List<String> sources = Collections.singletonList(normalizedSource);
        yamlSources = getConfigFromSources(sources);
        final Map<Source, String> issues = checkWith(yamlSources);
        final JSONArray errors = collectProblems(issues, "error");
        if (!errors.isEmpty()) {
            return FormValidation.error(errors.toString());
        }
        final JSONArray warnings = collectProblems(issues, "warning");
        if (!warnings.isEmpty()) {
            return FormValidation.warning(warnings.toString());
        }
        return FormValidation.okWithMarkup("The configuration can be applied");
    } catch (ConfiguratorException | IllegalArgumentException e) {
        return FormValidation.error(e, e.getCause() == null ? e.getMessage() : e.getCause().getMessage());
    }
}
 
Example 10
Source File: Endpoint.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
@RequirePOST
@Restricted(NoExternalUse.class)
public FormValidation doCheckApiUri(@QueryParameter String apiUri) {
    Jenkins.get().checkPermission(Jenkins.ADMINISTER);
    if (Util.fixEmptyAndTrim(apiUri) == null) {
        return FormValidation.warning("You must specify the API URL");
    }
    try {
        URL api = new URL(apiUri);
        GitHub github = GitHub.connectToEnterpriseAnonymously(api.toString());
        github.checkApiUrlValidity();
        LOGGER.log(Level.FINE, "Trying to configure a GitHub Enterprise server");
        // For example: https://api.github.com/ or https://github.mycompany.com/api/v3/ (with private mode disabled).
        return FormValidation.ok("GitHub Enterprise server verified");
    } catch (MalformedURLException mue) {
        // For example: https:/api.github.com
        LOGGER.log(Level.WARNING, "Trying to configure a GitHub Enterprise server: " + apiUri, mue.getCause());
        return FormValidation.error("The endpoint does not look like a GitHub Enterprise (malformed URL)");
    } catch (JsonParseException jpe) {
        LOGGER.log(Level.WARNING, "Trying to configure a GitHub Enterprise server: " + apiUri, jpe.getCause());
        return FormValidation.error("The endpoint does not look like a GitHub Enterprise (invalid JSON response)");
    } catch (FileNotFoundException fnt) {
        // For example: https://github.mycompany.com/server/api/v3/ gets a FileNotFoundException
        LOGGER.log(Level.WARNING, "Getting HTTP Error 404 for " + apiUri);
        return FormValidation.error("The endpoint does not look like a GitHub Enterprise (page not found");
    } catch (IOException e) {
        // For example: https://github.mycompany.com/api/v3/ or https://github.mycompany.com/api/v3/mypath
        if (e.getMessage().contains("private mode enabled")) {
            LOGGER.log(Level.FINE, e.getMessage());
            return FormValidation.warning("Private mode enabled, validation disabled");
        }
        LOGGER.log(Level.WARNING, e.getMessage());
        return FormValidation.error("The endpoint does not look like a GitHub Enterprise (verify network and/or try again later)");
    }
}
 
Example 11
Source File: TestRailNotifier.java    From testrail-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
public FormValidation doCheckTestrailSuite(@QueryParameter String value)
        throws IOException, ServletException {
    testrail.setHost(getTestrailHost());
    testrail.setUser(getTestrailUser());
    testrail.setPassword(getTestrailPassword());
    if (getTestrailHost().isEmpty() || getTestrailUser().isEmpty() || getTestrailPassword().isEmpty() || !testrail.serverReachable() || !testrail.authenticationWorks()) {
        return FormValidation.warning("Please fix your TestRail configuration in Manage Jenkins -> Configure System.");
    }
    return FormValidation.ok();
}
 
Example 12
Source File: AWSEBDeploymentBuilder.java    From awseb-deployment-plugin with Apache License 2.0 5 votes vote down vote up
public FormValidation doCheckAwsRegion(@QueryParameter String value) {
    if (value.contains("$")) {
        return FormValidation.warning("Validation skipped due to parameter usage ('$')");
    }

    if (!value.matches("^\\p{Alpha}{2}-(?:gov-)?\\p{Alpha}{4,}-\\d$")) {
        return FormValidation.error("Doesn't look like a region, like {place}-{cardinal}-{number}");
    }
    return FormValidation.ok();
}
 
Example 13
Source File: OpenTasks.java    From warnings-ng-plugin with MIT License 5 votes vote down vote up
/**
 * Validates the example text that will be scanned for open tasks.
 *
 * @param example
 *         the text to be scanned for open tasks
 * @param high
 *         tag identifiers indicating high priority
 * @param normal
 *         tag identifiers indicating normal priority
 * @param low
 *         tag identifiers indicating low priority
 * @param ignoreCase
 *         if case should be ignored during matching
 * @param asRegexp
 *         if the identifiers should be treated as regular expression
 *
 * @return validation result
 */
@SuppressWarnings("PMD.AvoidLiteralsInIfCondition")
public FormValidation doCheckExample(@QueryParameter final String example,
        @QueryParameter final String high,
        @QueryParameter final String normal,
        @QueryParameter final String low,
        @QueryParameter final boolean ignoreCase,
        @QueryParameter final boolean asRegexp) {
    if (StringUtils.isEmpty(example)) {
        return FormValidation.ok();
    }

    TaskScannerBuilder builder = new TaskScannerBuilder();
    TaskScanner scanner = builder.setHighTasks(high)
            .setNormalTasks(normal)
            .setLowTasks(low)
            .setCaseMode(ignoreCase ? CaseMode.IGNORE_CASE : CaseMode.CASE_SENSITIVE)
            .setMatcherMode(asRegexp ? MatcherMode.REGEXP_MATCH : MatcherMode.STRING_MATCH).build();

    if (scanner.isInvalidPattern()) {
        return FormValidation.error(scanner.getErrors());
    }

    try (BufferedReader reader = new BufferedReader(new StringReader(example))) {
        Report tasks = scanner.scanTasks(reader.lines().iterator(), new IssueBuilder().setFileName("UI example"));
        if (tasks.isEmpty()) {
            return FormValidation.warning(Messages.OpenTasks_Validation_NoTask());
        }
        else if (tasks.size() != 1) {
            return FormValidation.warning(Messages.OpenTasks_Validation_MultipleTasks(tasks.size()));
        }
        else {
            Issue task = tasks.get(0);
            return FormValidation.ok(Messages.OpenTasks_Validation_OneTask(task.getType(), task.getMessage()));
        }
    }
    catch (IOException e) {
        return FormValidation.error(e.getMessage()); // should never happen
    }
}
 
Example 14
Source File: KubernetesCloud.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused") // used by jelly
public FormValidation doCheckDirectConnection(@QueryParameter boolean value, @QueryParameter String jenkinsUrl, @QueryParameter boolean webSocket) throws IOException, ServletException {
    int slaveAgentPort = Jenkins.get().getSlaveAgentPort();
    if (slaveAgentPort == -1 && !webSocket) {
        return FormValidation.warning("'TCP port for inbound agents' is disabled in Global Security settings. Connecting Kubernetes agents will not work without this or WebSocket mode!");
    }

    if(value) {
        if (webSocket) {
            return FormValidation.error("Direct connection and WebSocket mode are mutually exclusive");
        }
        if(!isEmpty(jenkinsUrl)) return FormValidation.warning("No need to configure Jenkins URL when direct connection is enabled");

        if(slaveAgentPort == 0) return FormValidation.warning(
                "A random 'TCP port for inbound agents' is configured in Global Security settings. In 'direct connection' mode agents will not be able to reconnect to a restarted master with random port!");
    } else {
        if (isEmpty(jenkinsUrl)) {
            String url = StringUtils.defaultIfBlank(System.getProperty("KUBERNETES_JENKINS_URL", System.getenv("KUBERNETES_JENKINS_URL")), JenkinsLocationConfiguration.get().getUrl());
            if (url != null) {
                return FormValidation.ok("Will connect using " + url);
            } else {
                return FormValidation.warning("Configure either Direct Connection or Jenkins URL");
            }
        }
    }
    return FormValidation.ok();
}
 
Example 15
Source File: TestRailNotifier.java    From testrail-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Performs on-the-fly validation of the form field 'name'.
 *
 * @param value
 *      This parameter receives the value that the user has typed.
 * @return
 *      Indicates the outcome of the validation. This is sent to the browser.
 */
public FormValidation doCheckTestrailProject(@QueryParameter int value)
        throws IOException, ServletException {
    testrail.setHost(getTestrailHost());
    testrail.setUser(getTestrailUser());
    testrail.setPassword(getTestrailPassword());
    if (getTestrailHost().isEmpty() || getTestrailUser().isEmpty() || getTestrailPassword().isEmpty() || !testrail.serverReachable() || !testrail.authenticationWorks()) {
        return FormValidation.warning("Please fix your TestRail configuration in Manage Jenkins -> Configure System.");
    }
    return FormValidation.ok();
}
 
Example 16
Source File: MarathonBuilder.java    From marathonv5 with Apache License 2.0 4 votes vote down vote up
public FormValidation doCheckTestCases(@QueryParameter String testCases, @AncestorInPath AbstractProject<?, ?> project)
        throws IOException, ServletException {
    if (testCases.length() == 0)
        return FormValidation.warning("Please enter test case to run.");
    return FormValidation.ok();
}
 
Example 17
Source File: KafkaComputerLauncher.java    From remoting-kafka-plugin with MIT License 4 votes vote down vote up
public FormValidation doCheckSslKeystoreLocation(@QueryParameter("sslKeystoreLocation") String sslKeystoreLocation) {
    if (StringUtils.isBlank(sslKeystoreLocation)) {
        return FormValidation.warning(Messages.GlobalKafkaConfiguration_KafkaSecurityWarning());
    }
    return FormValidation.ok();
}
 
Example 18
Source File: KafkaComputerLauncher.java    From remoting-kafka-plugin with MIT License 4 votes vote down vote up
public FormValidation doCheckKafkaUsername(@QueryParameter("kafkaUsername") String kafkaUsername) {
    if (StringUtils.isBlank(kafkaUsername)) {
        return FormValidation.warning(Messages.GlobalKafkaConfiguration_KafkaSecurityWarning());
    }
    return FormValidation.ok();
}
 
Example 19
Source File: DashboardViewDescriptor.java    From jenkins-deployment-dashboard-plugin with MIT License 4 votes vote down vote up
public FormValidation doCheckUsername(@QueryParameter final String username) {
    if (StringUtils.hasText(username)) {
        return FormValidation.ok();
    }
    return FormValidation.warning(Messages.DashboardView_artifactoryUsername());
}
 
Example 20
Source File: ZAProxy.java    From zaproxy-plugin with MIT License 3 votes vote down vote up
/**
 * Performs on-the-fly validation of the form field 'filenameReports'.
 *
 * @param filenameReports
 *      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 doCheckFilenameReports(@QueryParameter("filenameReports") final String filenameReports) {
	if(filenameReports.isEmpty())
		return FormValidation.error("Field is required");
	if(!FilenameUtils.getExtension(filenameReports).isEmpty())
		return FormValidation.warning("A file extension is not necessary.");
	return FormValidation.ok();
}