Java Code Examples for hudson.util.FormValidation

The following examples show how to use hudson.util.FormValidation. These examples are extracted from open source projects. 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 Project: jira-ext-plugin   Source File: UpdateField.java    License: 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 Project: credentials-binding-plugin   Source File: ZipFileBinding.java    License: MIT License 6 votes vote down vote up
public FormValidation doCheckCredentialsId(@AncestorInPath Item owner, @QueryParameter String value) {
    for (FileCredentials c : CredentialsProvider.lookupCredentials(FileCredentials.class, owner, null, Collections.<DomainRequirement>emptyList())) {
        if (c.getId().equals(value)) {
            InputStream is = null;
            try {
                is = c.getContent();
                byte[] data = new byte[4];
                if (is.read(data) == 4 && data[0] == 'P' && data[1] == 'K' && data[2] == 3 && data[3] == 4) {
                    return FormValidation.ok();
                } else {
                    return FormValidation.error(Messages.ZipFileBinding_NotZipFile());
                }
            } catch (IOException x) {
                return FormValidation.warning(Messages.ZipFileBinding_CouldNotVerifyFileFormat());
            }
            finally {
                if (is != null) {
                    IOUtils.closeQuietly(is);
                }
            }
        }
    }
    return FormValidation.error(Messages.ZipFileBinding_NoSuchCredentials());
}
 
Example 3
public FormValidation doCheckSecretKey(@QueryParameter("proxyHost") final String proxyHost,
                                       @QueryParameter("proxyPort") final String proxyPort,
                                       @QueryParameter("accessKey") final String accessKey,
                                       @QueryParameter("secretKey") final String secretKey) {

    try {
        AWSCredentials initialCredentials = getBasicCredentialsOrDefaultChain(accessKey, secretKey).getCredentials();
        new AWSCodeBuildClient(initialCredentials, getClientConfiguration(proxyHost, proxyPort)).listProjects(new ListProjectsRequest());

    } 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("AWS access and secret key authorization successful.");
}
 
Example 4
Source Project: remoting-kafka-plugin   Source File: KafkaKubernetesCloudTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testTestKubernetesConnection() {
    KafkaKubernetesCloud.DescriptorImpl descriptor = new KafkaKubernetesCloud.DescriptorImpl();
    FormValidation result = descriptor.doTestConnection(
            "",
            "",
            "",
            true,
            ""
    );
    assertThat(result.kind, is(FormValidation.Kind.ERROR));

    result = descriptor.doTestConnection(
            k.getMockServer().url("/").toString(),
            "",
            "",
            true,
            ""
    );
    assertThat(result.kind, is(FormValidation.Kind.OK));
}
 
Example 5
Source Project: jira-steps-plugin   Source File: Site.java    License: Apache License 2.0 6 votes vote down vote up
public FormValidation doCheckCredentialsId(@AncestorInPath Item item,
    final @QueryParameter String credentialsId,
    final @QueryParameter String url) {

  if (item == null) {
    if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
      return FormValidation.ok();
    }
  } else if (!item.hasPermission(Item.EXTENDED_READ) && !item.hasPermission(CredentialsProvider.USE_ITEM)) {
    return FormValidation.ok();
  }
  if (StringUtils.isBlank(credentialsId)) {
    return FormValidation.warning(Messages.Site_emptyCredentialsId());
  }

  List<DomainRequirement> domainRequirements = URIRequirementBuilder.fromUri(url).build();
  if (CredentialsProvider.listCredentials(StandardUsernameCredentials.class, item, getAuthentication(item), domainRequirements, CredentialsMatchers.withId(credentialsId)).isEmpty()) {
    return FormValidation.error(Messages.Site_invalidCredentialsId());
  }
  return FormValidation.ok();
}
 
Example 6
public FormValidation doCheckLabelName(
		@QueryParameter String value,
		@QueryParameter String resourceNames,
		@QueryParameter boolean script) {
	String label = Util.fixEmptyAndTrim(value);
	String names = Util.fixEmptyAndTrim(resourceNames);

	if (label == null) {
		return FormValidation.ok();
	} else if (names != null || script) {
		return FormValidation.error(
				"Only label, groovy expression, or resources can be defined, not more than one.");
	} else {
		if (LockableResourcesManager.get().isValidLabel(label)) {
			return FormValidation.ok();
		} else {
			return FormValidation.error(
					"The label does not exist: " + label);
		}
	}
}
 
Example 7
public FormValidation doValidateUpload(@QueryParameter("applicationName") String applicationName,
                                       @QueryParameter("bucketName") String bucketName,
                                       @QueryParameter("keyPrefix") String keyPrefix,
                                       @QueryParameter("versionLabelFormat") String versionLabelFormat) {

    String objectKey = Utils.formatPath("%s/%s-%s.zip",
            defaultIfBlank(keyPrefix, "<ERROR: MISSING KEY PREFIX>"),
            defaultIfBlank(applicationName, "<ERROR: MISSING APPLICATION NAME>"),
            defaultIfBlank(versionLabelFormat, "<ERROR: MISSING VERSION LABEL FORMAT>"));

    String targetPath = Util.escape(String.format("s3://%s/%s",
            defaultIfBlank(bucketName, "[default account bucket for region]"),
            objectKey));

    final String resultingMessage = format("Your object will be uploaded to S3 as: <code>%s</code> (<i>note replacements will apply</i>)", targetPath);

    return FormValidation.okWithMarkup(resultingMessage);
}
 
Example 8
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 9
@Restricted(NoExternalUse.class)
public FormValidation doCheckIncludes(@QueryParameter String includes) {
    if (includes.isEmpty()) {
        return FormValidation.warning(Messages.GitLabSCMBranchMonitorStrategy_did_you_mean_to_use_to_match_all_branches());
    }
    return FormValidation.ok();
}
 
Example 10
Source Project: docker-plugin   Source File: DockerAPI.java    License: MIT License 5 votes vote down vote up
@RequirePOST
public FormValidation doTestConnection(
        @AncestorInPath Item context,
        @QueryParameter String uri,
        @QueryParameter String credentialsId,
        @QueryParameter String apiVersion,
        @QueryParameter int connectTimeout,
        @QueryParameter int readTimeout
) {
    throwIfNoPermission(context);
    final FormValidation credentialsIdCheckResult = doCheckCredentialsId(context, uri, credentialsId);
    if (credentialsIdCheckResult != FormValidation.ok()) {
        return FormValidation.error("Invalid credentials");
    }
    try {
        final DockerServerEndpoint dsep = new DockerServerEndpoint(uri, credentialsId);
        final DockerAPI dapi = new DockerAPI(dsep, connectTimeout, readTimeout, apiVersion, null);
        try(final DockerClient dc = dapi.getClient()) {
            final VersionCmd vc = dc.versionCmd();
            final Version v = vc.exec();
            final String actualVersion = v.getVersion();
            final String actualApiVersion = v.getApiVersion();
            return FormValidation.ok("Version = " + actualVersion + ", API Version = " + actualApiVersion);
        }
    } catch (Exception e) {
        return FormValidation.error(e, e.getMessage());
    }
}
 
Example 11
@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");
}
 
Example 12
private String doCheckConnection(String clientBuilderId, Response.Status status) {
    HttpRequest request = request().withPath("/gitlab/api/" + clientBuilderId + "/.*").withHeader("PRIVATE-TOKEN", API_TOKEN);
    mockServerClient.when(request).respond(response().withStatusCode(status.getStatusCode()));

    GitLabConnection.DescriptorImpl descriptor = (DescriptorImpl) jenkins.jenkins.getDescriptor(GitLabConnection.class);
    FormValidation formValidation = descriptor.doTestConnection(gitLabUrl, API_TOKEN_ID, clientBuilderId, false, 10, 10);
    mockServerClient.verify(request);
    return formValidation.getMessage();
}
 
Example 13
Source Project: docker-plugin   Source File: DockerTemplateBase.java    License: MIT License 5 votes vote down vote up
public FormValidation doCheckExtraHostsString(@QueryParameter String extraHostsString) {
    final List<String> extraHosts = splitAndFilterEmptyList(extraHostsString, "\n");
    for (String extraHost : extraHosts) {
        if (extraHost.trim().split(":").length < 2) {
            return FormValidation.error("Wrong extraHost format: '%s'", extraHost);
        }
    }
    return FormValidation.ok();
}
 
Example 14
@Test
public void testSuccessfullyTestConnection() throws Exception {
    // given
    setupCredentials(CREDENTIALS_ID, "secret");

    // when
    final FormValidation result =
            classUnderTest.doTestConnection(SITE, CLIENT_ID, CREDENTIALS_ID);

    // then
    assertThat(result.kind).isEqualTo(FormValidation.Kind.OK);
}
 
Example 15
Source Project: github-integration-plugin   Source File: GitHubPRRepositoryTest.java    License: MIT License 5 votes vote down vote up
@Test
public void doRebuildFailedWithException() throws IOException {
    GitHubPRRepositoryFactoryTest.createForCommonExpectations(job, trigger);
    hasPermissionExpectation(Item.BUILD, true);
    getAllPrBuildsCommonExpectations(BUILD_MAP_SIZE);
    getAllPrBuildsNonNullCauseExpectations(BUILD_MAP_SIZE);

    when(run.getResult()).thenThrow(new RuntimeException("run.getResult() test exception"));

    GitHubPRRepository repo = GitHubPRRepositoryFactoryTest.getRepo(factory.createFor(job));
    FormValidation formValidation = repo.doRebuildAllFailed();

    Assert.assertEquals(FormValidation.Kind.ERROR, formValidation.kind);
}
 
Example 16
public FormValidation doCheckLabels(@AncestorInPath final Job<?, ?> project, @QueryParameter final String value) {
    if (!project.hasPermission(Item.CONFIGURE) || containsNoLabel(value)) {
        return FormValidation.ok();
    }

    try {
        return checkMatchingLabels(value, getProjectLabels(project));
    } catch (GitLabProjectBranchesService.BranchLoadingException e) {
        return FormValidation.warning(project.hasPermission(Jenkins.ADMINISTER) ? e : null, Messages.GitLabPushTrigger_CannotCheckBranches());
    }
}
 
Example 17
protected FormValidation checkNotNullOrEmpty(String parameter, String errorMessage) {
    if (StringUtils.isNotBlank(parameter)) {
        return FormValidation.ok();
    } else {
        return FormValidation.error(errorMessage);
    }
}
 
Example 18
@Test
public void doCheckConnection_ignoreCertificateErrors() {
    GitLabConnection.DescriptorImpl descriptor = (DescriptorImpl) jenkins.jenkins.getDescriptor(GitLabConnection.class);

    FormValidation formValidation = descriptor.doTestConnection("https://localhost:" + port + "/gitlab", API_TOKEN_ID, "v3", true, 10, 10);
    assertThat(formValidation.getMessage(), is(Messages.connection_success()));
}
 
Example 19
@Test
public void testTestKafkaConnection() throws Exception {
    GlobalKafkaConfiguration g = GlobalKafkaConfiguration.get();
    FormValidation result = g.doTestBrokerConnection("");
    assertThat(result.kind, is(FormValidation.Kind.ERROR));

    try (MockWebServer server = new MockWebServer()) {
        server.start();
        result = g.doTestBrokerConnection(server.getHostName() + ":" + server.getPort());
        assertThat(result.kind, is(FormValidation.Kind.OK));
    }
}
 
Example 20
Source Project: jenkins-mattermost-plugin   Source File: MattermostNotifierTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testDoTestConnection() {
  if (mattermostServiceStub != null) {
    mattermostServiceStub.setResponse(response);
  }

  descriptor.setMattermostService(mattermostServiceStub);
  try {
    FormValidation result = descriptor.doTestConnection("host", "room", "", "buildServerUrl");
    assertEquals(result.kind, expectedResult);
  } catch (Descriptor.FormException e) {
    e.printStackTrace();
    assertTrue(false);
  }
}
 
Example 21
Source Project: github-branch-source-plugin   Source File: GitHubSCMSource.java    License: MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class)
public FormValidation doCheckIncludes(@QueryParameter String value) {
    if (value.isEmpty()) {
        return FormValidation.warning(Messages.GitHubSCMSource_did_you_mean_to_use_to_match_all_branches());
    }
    return FormValidation.ok();
}
 
Example 22
/**
 * Sanity check for a Gitlab access token.
 *
 * @param value the personal access token.
 * @return the results of the sanity check.
 */
@Restricted(NoExternalUse.class) // stapler
@SuppressWarnings("unused")
public FormValidation doCheckToken(@QueryParameter String value) {
    Secret secret = Secret.fromString(value);
    if (StringUtils.equals(value, secret.getPlainText())) {
        if (value.length() != GITLAB_ACCESS_TOKEN_LENGTH) {
            return FormValidation
                .error(Messages.PersonalAccessTokenImpl_tokenWrongLength());
        }
    } else if (secret.getPlainText().length() != GITLAB_ACCESS_TOKEN_LENGTH) {
        return FormValidation.error(Messages.PersonalAccessTokenImpl_tokenWrongLength());
    }
    return FormValidation.ok();
}
 
Example 23
Source Project: jira-steps-plugin   Source File: Site.java    License: Apache License 2.0 5 votes vote down vote up
public FormValidation doCheckUrl(final @QueryParameter String url) {
  if (StringUtils.isBlank(url)) {
    return FormValidation.error(Messages.required());
  }
  try {
    new URL(url);
    return FormValidation.ok();
  } catch (MalformedURLException e) {
    return FormValidation.error(e.getMessage());
  }
}
 
Example 24
Source Project: warnings-ng-plugin   Source File: OpenTasks.java    License: 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 25
Source Project: kubernetes-plugin   Source File: ContainerTemplate.java    License: Apache License 2.0 5 votes vote down vote up
public FormValidation doCheckImage(@QueryParameter String value) {
    if (StringUtils.isEmpty(value)) {
        return FormValidation.ok("Image is mandatory");
    } else if (PodTemplateUtils.validateImage(value)) {
        return FormValidation.ok();
    } else {
        return FormValidation.error("Malformed image");
    }
}
 
Example 26
Source Project: jenkins-mattermost-plugin   Source File: MattermostNotifierTest.java    License: MIT License 5 votes vote down vote up
public MattermostNotifierTest(
    MattermostServiceStub mattermostServiceStub,
    boolean response,
    FormValidation.Kind expectedResult) {
  this.mattermostServiceStub = mattermostServiceStub;
  this.response = response;
  this.expectedResult = expectedResult;
}
 
Example 27
Source Project: aws-lambda-jenkins-plugin   Source File: AWSLambdaDescriptor.java    License: MIT License 5 votes vote down vote up
public FormValidation doCheckAwsRegion(@QueryParameter String value) {
    if(StringUtils.isEmpty(value)){
        return FormValidation.error("Please fill in AWS Region.");
    } else {
        return FormValidation.ok();
    }
}
 
Example 28
Source Project: yet-another-docker-plugin   Source File: DockerCreateContainer.java    License: MIT License 5 votes vote down vote up
public FormValidation doCheckDevicesString(@QueryParameter String devicesString) {
    final List<String> devicesStrings = splitAndFilterEmpty(devicesString);
    for (String deviceString : devicesStrings) {
        try {
            Device.parse(deviceString);
        } catch (Exception ex) {
            return FormValidation.error("Bad device configuration: " + deviceString, ex);
        }
    }

    return FormValidation.ok();
}
 
Example 29
Source Project: fabric-beta-publisher-plugin   Source File: FabricBetaPublisher.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("unused")
public FormValidation doCheckApiKey(@QueryParameter String value) {
    if (value.length() == 0) {
        return FormValidation.error("Please input a Fabric API key");
    }
    return FormValidation.ok();
}
 
Example 30
Source Project: pipeline-utility-steps-plugin   Source File: TouchStep.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("unused")
public FormValidation doCheckFile(@QueryParameter String value) {
    if (StringUtils.isBlank(value)) {
        return FormValidation.error("Needs a value");
    } else {
        return FormValidation.ok();
    }
}