hudson.util.FormValidation Java Examples

The following examples show how to use hudson.util.FormValidation. 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: 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 #2
Source File: AWSEBDeploymentBuilder.java    From awseb-deployment-plugin with Apache License 2.0 6 votes vote down vote up
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 #3
Source File: RequiredResourcesProperty.java    From lockable-resources-plugin with MIT License 6 votes vote down vote up
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 #4
Source File: Site.java    From jira-steps-plugin with 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 #5
Source File: ZipFileBinding.java    From credentials-binding-plugin with 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 #6
Source File: KafkaKubernetesCloudTest.java    From remoting-kafka-plugin with 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 #7
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 #8
Source File: CodeBuildBaseCredentials.java    From aws-codebuild-jenkins-plugin with Apache License 2.0 6 votes vote down vote up
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 #9
Source File: GitLabConnectionConfigTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void doCheckConnection_proxy() {
    jenkins.getInstance().proxy = new ProxyConfiguration("0.0.0.0", 80);
    GitLabConnection.DescriptorImpl descriptor = (DescriptorImpl) jenkins.jenkins.getDescriptor(GitLabConnection.class);
    FormValidation result = descriptor.doTestConnection(gitLabUrl, API_TOKEN_ID, "v3", false, 10, 10);
    assertThat(result.getMessage(), containsString("Connection refused"));
}
 
Example #10
Source File: GitLabConnectionConfigSSLTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@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 #11
Source File: TouchStep.java    From pipeline-utility-steps-plugin with 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();
    }
}
 
Example #12
Source File: FabricBetaPublisher.java    From fabric-beta-publisher-plugin with 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 #13
Source File: DockerCreateContainer.java    From yet-another-docker-plugin with 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 #14
Source File: AWSLambdaDescriptor.java    From aws-lambda-jenkins-plugin with 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 #15
Source File: MattermostNotifierTest.java    From jenkins-mattermost-plugin with 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 #16
Source File: ContainerTemplate.java    From kubernetes-plugin with 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 #17
Source File: AbstractAnsibleBuilderDescriptor.java    From ansible-plugin with Apache License 2.0 5 votes vote down vote up
protected FormValidation checkNotNullOrEmpty(String parameter, String errorMessage) {
    if (StringUtils.isNotBlank(parameter)) {
        return FormValidation.ok();
    } else {
        return FormValidation.error(errorMessage);
    }
}
 
Example #18
Source File: DockerAPI.java    From docker-plugin with 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 #19
Source File: AWSDeviceFarmRecorder.java    From aws-device-farm-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Validate the user entered artifact for Appium Python test content.
 *
 * @param appiumPythonTest The path to the test file.
 * @return Whether or not the form was ok.
 */
@SuppressWarnings("unused")
public FormValidation doCheckAppiumPythonTest(@QueryParameter String appiumPythonTest) {
    if (appiumPythonTest == null || appiumPythonTest.isEmpty()) {
        return FormValidation.error("Required!");
    }
    return FormValidation.ok();
}
 
Example #20
Source File: GitHubPRRepositoryTest.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Test
public void doRebuildWarnNotScheduled() throws IOException {
    GitHubPRRepositoryFactoryTest.createForCommonExpectations(job, trigger);
    doRebuildCommonExpectations(false, true);
    getAllPrBuildsCommonExpectations(BUILD_MAP_SIZE);
    getAllPrBuildsNonNullCauseExpectations(BUILD_MAP_SIZE);

    when(run.getParent()).thenReturn(job);

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

    Assert.assertEquals(FormValidation.Kind.WARNING, formValidation.kind);
}
 
Example #21
Source File: DockerTemplateBase.java    From docker-plugin with MIT License 5 votes vote down vote up
public FormValidation doCheckExtraGroupsString(@QueryParameter String extraGroupsString) {
    final List<String> extraGroups = splitAndFilterEmptyList(extraGroupsString, "\n");
    Pattern pat = Pattern.compile("^(\\d+|[a-z_][a-z0-9_-]*[$]?)$");
    for (String extraGroup : extraGroups) {
        if (!pat.matcher(extraGroup.trim()).matches()) {
            return FormValidation.error("Wrong extraGroup format: '%s'", extraGroup);
        }
    }
    return FormValidation.ok();
}
 
Example #22
Source File: NodeConfiguration.java    From at.info-knowledge-base with MIT License 5 votes vote down vote up
public FormValidation doCheckNodePort(@QueryParameter String value) throws IOException, ServletException {
    if (value.length() == 0 || !StringUtils.isNumeric(value)) {
        return FormValidation.error("Please set a valid port");
    }

    return FormValidation.ok();
}
 
Example #23
Source File: DockerCreateContainer.java    From yet-another-docker-plugin with MIT License 5 votes vote down vote up
public FormValidation doCheckLinksString(@QueryParameter String linksString) {
    final List<String> links = splitAndFilterEmpty(linksString);
    for (String linkString : links) {
        try {
            Link.parse(linkString);
        } catch (Exception ex) {
            return FormValidation.error("Bad link configuration: " + linkString, ex);
        }
    }

    return FormValidation.ok();
}
 
Example #24
Source File: GitHubSCMSource.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class)
public FormValidation doCheckBuildOriginBranchWithPR(
    @QueryParameter boolean buildOriginBranch,
    @QueryParameter boolean buildOriginBranchWithPR,
    @QueryParameter boolean buildOriginPRMerge,
    @QueryParameter boolean buildOriginPRHead,
    @QueryParameter boolean buildForkPRMerge,
    @QueryParameter boolean buildForkPRHead
) {
    if (buildOriginBranch && !buildOriginBranchWithPR && !buildOriginPRMerge && !buildOriginPRHead && !buildForkPRMerge && !buildForkPRHead) {
        // TODO in principle we could make doRetrieve populate originBranchesWithPR without actually including any PRs, but it would be more work and probably never wanted anyway.
        return FormValidation.warning("If you are not building any PRs, all origin branches will be built.");
    }
    return FormValidation.ok();
}
 
Example #25
Source File: SelectJobsBallColorFolderIcon.java    From multi-branch-project-plugin with MIT License 5 votes vote down vote up
/**
 * Form validation method.  Similar to
 * {@link hudson.tasks.BuildTrigger.DescriptorImpl#doCheck(AbstractProject, String)}.
 *
 * @param folder the folder being configured
 * @param value  the user-entered value
 * @return validation result
 */
public FormValidation doCheck(@AncestorInPath AbstractFolder folder, @QueryParameter String value) {
    // Require CONFIGURE permission on this project
    if (!folder.hasPermission(Item.CONFIGURE)) {
        return FormValidation.ok();
    }

    boolean hasJobs = false;

    StringTokenizer tokens = new StringTokenizer(Util.fixNull(value), ",");
    while (tokens.hasMoreTokens()) {
        String jobName = tokens.nextToken().trim();

        if (StringUtils.isNotBlank(jobName)) {
            Item item = Jenkins.getActiveInstance().getItem(jobName, (ItemGroup) folder, Item.class);

            if (item == null) {
                Job nearest = Items.findNearest(Job.class, jobName, folder);
                String alternative = nearest != null ? nearest.getRelativeNameFrom((ItemGroup) folder) : "?";
                return FormValidation.error(
                        hudson.tasks.Messages.BuildTrigger_NoSuchProject(jobName, alternative));
            }

            if (!(item instanceof Job)) {
                return FormValidation.error(hudson.tasks.Messages.BuildTrigger_NotBuildable(jobName));
            }

            hasJobs = true;
        }
    }

    if (!hasJobs) {
        return FormValidation.error(hudson.tasks.Messages.BuildTrigger_NoProjectSpecified());
    }

    return FormValidation.ok();
}
 
Example #26
Source File: GlobalKafkaConfigurationTest.java    From remoting-kafka-plugin with MIT License 5 votes vote down vote up
@Test
public void testTestZookeeperConnection() throws Exception {
    GlobalKafkaConfiguration g = GlobalKafkaConfiguration.get();
    FormValidation result = g.doTestZookeeperConnection("");
    assertThat(result.kind, is(FormValidation.Kind.ERROR));

    try (MockWebServer server = new MockWebServer()) {
        server.start();
        result = g.doTestZookeeperConnection(server.getHostName() + ":" + server.getPort());
        assertThat(result.kind, is(FormValidation.Kind.OK));
    }
}
 
Example #27
Source File: SeleniumBuilder.java    From at.info-knowledge-base with MIT License 5 votes vote down vote up
public FormValidation doCheckHubPort(@QueryParameter String value) throws IOException, ServletException {
    if (value.length() == 0 || !StringUtils.isNumeric(value)) {
        return FormValidation.error("Please set a valid port");
    }

    return FormValidation.ok();
}
 
Example #28
Source File: LockStepResource.java    From lockable-resources-plugin with MIT License 5 votes vote down vote up
public static FormValidation doCheckLabel(@QueryParameter String value, @QueryParameter String resource) {
	String resourceLabel = Util.fixEmpty(value);
	String resourceName = Util.fixEmpty(resource);
	if (resourceLabel != null && resourceName != null) {
		return FormValidation.error("Label and resource name cannot be specified simultaneously.");
	}
	if ((resourceLabel == null) && (resourceName == null)) {
		return FormValidation.error("Either label or resource name must be specified.");
	}
	if (resourceLabel != null && !LockableResourcesManager.get().isValidLabel(resourceLabel)) {
		return FormValidation.error("The label does not exist: " + resourceLabel);
	}
	return FormValidation.ok();
}
 
Example #29
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 #30
Source File: OicSecurityRealm.java    From oic-auth-plugin with MIT License 5 votes vote down vote up
public FormValidation doCheckTokenServerUrl(@QueryParameter String tokenServerUrl) {
    if (tokenServerUrl == null) {
        return FormValidation.error("Token Server Url Key is required.");
    }
    try {
        new URL(tokenServerUrl);
        return FormValidation.ok();
    } catch (MalformedURLException e) {
        return FormValidation.error(e,"Not a valid url.");
    }
}