Java Code Examples for org.kohsuke.stapler.QueryParameter

The following examples show how to use org.kohsuke.stapler.QueryParameter. 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: remoting-kafka-plugin   Source File: KafkaKubernetesCloud.java    License: MIT License 6 votes vote down vote up
@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
                    ));
}
 
Example 2
@SuppressWarnings("unused")
public ListBoxModel doFillCredentialsIdItems(@QueryParameter final String credentialsId) {
    Jenkins instance = Jenkins.get();
    if (!instance.hasPermission(Jenkins.ADMINISTER)) {
        return new StandardListBoxModel().includeCurrentValue(credentialsId);
    }

    return new StandardListBoxModel()
            .includeEmptyValue()
            .includeMatchingAs(
                    ACL.SYSTEM,
                    instance,
                    StringCredentials.class,
                    URIRequirementBuilder.fromUri(ATLASSIAN_API_URL).build(),
                    CredentialsMatchers.always());
}
 
Example 3
Source Project: appcenter-plugin   Source File: AppCenterRecorder.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("unused")
public FormValidation doCheckPathToApp(@QueryParameter String value) {
    if (value.isEmpty()) {
        return FormValidation.error(Messages.AppCenterRecorder_DescriptorImpl_errors_missingPathToApp());
    }

    final Validator pathToAppValidator = new PathToAppValidator();

    if (!pathToAppValidator.isValid(value)) {
        return FormValidation.error(Messages.AppCenterRecorder_DescriptorImpl_errors_invalidPath());
    }

    final Validator pathPlaceholderValidator = new PathPlaceholderValidator();

    if (!pathPlaceholderValidator.isValid(value)) {
        return FormValidation.warning(Messages.AppCenterRecorder_DescriptorImpl_warnings_mustNotStartWithEnvVar());
    }

    return FormValidation.ok();
}
 
Example 4
Source Project: appcenter-plugin   Source File: AppCenterRecorder.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("unused")
public FormValidation doCheckPathToDebugSymbols(@QueryParameter String value) {
    if (value.trim().isEmpty()) {
        return FormValidation.ok();
    }

    final Validator pathToDebugSymbolsValidator = new PathToDebugSymbolsValidator();

    if (!pathToDebugSymbolsValidator.isValid(value)) {
        return FormValidation.error(Messages.AppCenterRecorder_DescriptorImpl_errors_invalidPath());
    }

    final Validator pathPlaceholderValidator = new PathPlaceholderValidator();

    if (!pathPlaceholderValidator.isValid(value)) {
        return FormValidation.warning(Messages.AppCenterRecorder_DescriptorImpl_warnings_mustNotStartWithEnvVar());
    }

    return FormValidation.ok();
}
 
Example 5
Source Project: appcenter-plugin   Source File: AppCenterRecorder.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("unused")
public FormValidation doCheckPathToReleaseNotes(@QueryParameter String value) {
    if (value.trim().isEmpty()) {
        return FormValidation.ok();
    }

    final Validator pathToReleaseNotesValidator = new PathToReleaseNotesValidator();

    if (!pathToReleaseNotesValidator.isValid(value)) {
        return FormValidation.error(Messages.AppCenterRecorder_DescriptorImpl_errors_invalidPath());
    }

    final Validator pathPlaceholderValidator = new PathPlaceholderValidator();

    if (!pathPlaceholderValidator.isValid(value)) {
        return FormValidation.warning(Messages.AppCenterRecorder_DescriptorImpl_warnings_mustNotStartWithEnvVar());
    }

    return FormValidation.ok();
}
 
Example 6
@SuppressWarnings("unused")
public ListBoxModel doFillCredentialsIdItems(@QueryParameter String serverUrl,
    @QueryParameter String credentialsId) {
    Jenkins jenkins = Jenkins.get();
    if (!jenkins.hasPermission(Jenkins.ADMINISTER)) {
        return new StandardListBoxModel().includeCurrentValue(credentialsId);
    }
    return new StandardUsernameListBoxModel()
        .includeEmptyValue()
        .includeMatchingAs(
            ACL.SYSTEM,
            jenkins,
            StandardUsernamePasswordCredentials.class,
            fromUri(defaultIfBlank(serverUrl, GitLabServer.GITLAB_SERVER_URL)).build(),
            CredentialsMatchers.always()
        ).includeMatchingAs(
            Jenkins.getAuthentication(),
            jenkins,
            StandardUsernamePasswordCredentials.class,
            fromUri(defaultIfBlank(serverUrl, GitLabServer.GITLAB_SERVER_URL)).build(),
            CredentialsMatchers.always()
        );
}
 
Example 7
Source Project: gitlab-branch-source-plugin   Source File: GitLabServer.java    License: MIT License 6 votes vote down vote up
/**
 * Stapler form completion.
 *
 * @param serverUrl the server URL.
 * @param credentialsId the credentials Id
 * @return the available credentials.
 */
@Restricted(NoExternalUse.class) // stapler
@SuppressWarnings("unused")
public ListBoxModel doFillCredentialsIdItems(@QueryParameter String serverUrl,
    @QueryParameter String credentialsId) {
    Jenkins jenkins = Jenkins.get();
    if (!jenkins.hasPermission(Jenkins.ADMINISTER)) {
        return new StandardListBoxModel().includeCurrentValue(credentialsId);
    }
    return new StandardListBoxModel()
        .includeEmptyValue()
        .includeMatchingAs(ACL.SYSTEM,
            jenkins,
            StandardCredentials.class,
            fromUri(serverUrl).build(),
            CREDENTIALS_MATCHER
        );
}
 
Example 8
Source Project: remoting-kafka-plugin   Source File: GlobalKafkaConfiguration.java    License: MIT License 6 votes vote down vote up
private ListBoxModel fillCredentialsIdItems(@AncestorInPath Item item, @QueryParameter String credentialsId) {
    StandardListBoxModel result = new StandardListBoxModel();
    if (item == null) {
        if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
            return result.includeCurrentValue(credentialsId);
        }
    }
    return result
            .includeMatchingAs(
                    ACL.SYSTEM,
                    Jenkins.get(),
                    StandardUsernamePasswordCredentials.class,
                    Collections.singletonList(KAFKA_SCHEME),
                    CredentialsMatchers.always()
            )
            .includeCurrentValue(credentialsId);
}
 
Example 9
Source Project: gitlab-branch-source-plugin   Source File: GitLabSCMSource.java    License: MIT License 6 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath SCMSourceOwner context,
        @QueryParameter String serverName, @QueryParameter String credentialsId) {
    StandardListBoxModel result = new StandardListBoxModel();
    if (context == null) {
        // must have admin if you want the list without a context
        if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
            result.includeCurrentValue(credentialsId);
            return result;
        }
    } else {
        if (!context.hasPermission(Item.EXTENDED_READ)
                && !context.hasPermission(CredentialsProvider.USE_ITEM)) {
            // must be able to read the configuration or use the item credentials if you
            // want the list
            result.includeCurrentValue(credentialsId);
            return result;
        }
    }
    result.includeEmptyValue();
    result.includeMatchingAs(
            context instanceof Queue.Task ? ((Queue.Task) context).getDefaultAuthentication() : ACL.SYSTEM,
            context, StandardUsernameCredentials.class, fromUri(getServerUrlFromName(serverName)).build(),
            GitClient.CREDENTIALS_MATCHER);
    return result;
}
 
Example 10
Source Project: gitlab-branch-source-plugin   Source File: GitLabSCMSource.java    License: MIT License 6 votes vote down vote up
public int getProjectId(@QueryParameter String projectPath, @QueryParameter String serverName) {
    List<GitLabServer> gitLabServers = GitLabServers.get().getServers();
    if (gitLabServers.size() == 0) {
        return -1;
    }
    try {
        GitLabApi gitLabApi;
        if (StringUtils.isBlank(serverName)) {
            gitLabApi = apiBuilder(gitLabServers.get(0).getName());
        } else {
            gitLabApi = apiBuilder(serverName);
        }
        if (StringUtils.isNotBlank(projectPath)) {
            return gitLabApi.getProjectApi().getProject(projectPath).getId();
        }
    } catch (GitLabApiException e) {
        return -1;
    }
    return -1;
}
 
Example 11
Source Project: remoting-kafka-plugin   Source File: GlobalKafkaConfiguration.java    License: MIT License 6 votes vote down vote up
@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());
    }
}
 
Example 12
Source Project: warnings-ng-plugin   Source File: AxivionSuite.java    License: MIT License 6 votes vote down vote up
/**
 * Shows the user all available credential id items.
 *
 * @param item
 *         jenkins configuration
 * @param credentialsId
 *         current used credentials
 *
 * @return a list view of all credential ids
 */
public ListBoxModel doFillCredentialsIdItems(
        @AncestorInPath final Item item, @QueryParameter final String credentialsId) {
    StandardListBoxModel result = new StandardListBoxModel();
    if (item == null) {
        if (!new JenkinsFacade().hasPermission(Jenkins.ADMINISTER)) {
            return result.includeCurrentValue(credentialsId);
        }
    }
    else {
        if (!item.hasPermission(Item.EXTENDED_READ)
                && !item.hasPermission(CredentialsProvider.USE_ITEM)) {
            return result.includeCurrentValue(credentialsId);
        }
    }
    return result.includeAs(
            ACL.SYSTEM,
            item,
            StandardUsernamePasswordCredentials.class,
            Collections.emptyList())
            .includeCurrentValue(credentialsId);
}
 
Example 13
Source Project: warnings-ng-plugin   Source File: GroovyParser.java    License: 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 14
Source Project: warnings-ng-plugin   Source File: GroovyParser.java    License: MIT License 6 votes vote down vote up
/**
 * 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()));
    }
}
 
Example 15
Source Project: warnings-ng-plugin   Source File: GroovyParser.java    License: MIT License 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 16
Source Project: remoting-kafka-plugin   Source File: GlobalKafkaConfiguration.java    License: MIT License 6 votes vote down vote up
@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());
    }
}
 
Example 17
Source Project: warnings-ng-plugin   Source File: ModelValidation.java    License: MIT License 6 votes vote down vote up
/**
 * Performs on-the-fly validation on the ant pattern for input files.
 *
 * @param project
 *         the project
 * @param pattern
 *         the file pattern
 *
 * @return the validation result
 */
public FormValidation doCheckPattern(@AncestorInPath final AbstractProject<?, ?> project,
        @QueryParameter final String pattern) {
    if (project != null) { // there is no workspace in pipelines
        try {
            FilePath workspace = project.getSomeWorkspace();
            if (workspace != null && workspace.exists()) {
                return validatePatternInWorkspace(pattern, workspace);
            }
        }
        catch (InterruptedException | IOException ignore) {
            // ignore and return ok
        }
    }

    return FormValidation.ok();
}
 
Example 18
Source Project: warnings-ng-plugin   Source File: ModelValidation.java    License: MIT License 6 votes vote down vote up
/**
 * Performs on-the-fly validation on the source code directory.
 *
 * @param project
 *         the project
 * @param sourceDirectory
 *         the file pattern
 *
 * @return the validation result
 */
public FormValidation doCheckSourceDirectory(@AncestorInPath final AbstractProject<?, ?> project,
        @QueryParameter final String sourceDirectory) {
    if (project != null) { // there is no workspace in pipelines
        try {
            FilePath workspace = project.getSomeWorkspace();
            if (workspace != null && workspace.exists()) {
                return validateRelativePath(sourceDirectory, workspace);
            }
        }
        catch (InterruptedException | IOException ignore) {
            // ignore and return ok
        }
    }

    return FormValidation.ok();
}
 
Example 19
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 20
public ListBoxModel doFillValueItems(@AncestorInPath Job<?, ?> context, @QueryParameter String param)
        throws IOException, InterruptedException {
    ListBoxModel items = new ListBoxModel();
    if (context != null && context.hasPermission(Item.BUILD)) {
        ParametersDefinitionProperty prop = context.getProperty(ParametersDefinitionProperty.class);
        if (prop != null) {
            ParameterDefinition def = prop.getParameterDefinition(param);
            if (def instanceof ListGitBranchesParameterDefinition) {
                Map<String, String> paramList = ((ListGitBranchesParameterDefinition) def).generateContents(context);
                for (Map.Entry<String, String> entry : paramList.entrySet()) {
                    items.add(entry.getValue(), entry.getKey());
                }
            }
        }
    }
    return items;
}
 
Example 21
public FormValidation doCheckSite(@QueryParameter final String value) {
    if (StringUtils.isEmpty(value)) {
        return FormValidation.error(
                "Site name can't be empty. Paste your Jira Cloud site name here.");
    }

    if (!SiteValidator.isValid(value)) {
        return FormValidation.error(
                "Site name is invalid. Paste a valid site name, e.g. sitename.atlassian.net.");
    }

    return FormValidation.ok();
}
 
Example 22
@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 23
Source Project: appcenter-plugin   Source File: AppCenterRecorder.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("unused")
public FormValidation doCheckApiToken(@QueryParameter String value) {
    if (value.isEmpty()) {
        return FormValidation.error(Messages.AppCenterRecorder_DescriptorImpl_errors_missingApiToken());
    }

    final Validator validator = new ApiTokenValidator();

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

    return FormValidation.ok();
}
 
Example 24
Source Project: appcenter-plugin   Source File: AppCenterRecorder.java    License: 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 25
Source Project: appcenter-plugin   Source File: AppCenterRecorder.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("unused")
public FormValidation doCheckAppName(@QueryParameter String value) {
    if (value.isEmpty()) {
        return FormValidation.error(Messages.AppCenterRecorder_DescriptorImpl_errors_missingAppName());
    }

    final Validator validator = new AppNameValidator();

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

    return FormValidation.ok();
}
 
Example 26
Source Project: appcenter-plugin   Source File: AppCenterRecorder.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("unused")
public FormValidation doCheckDistributionGroups(@QueryParameter String value) {
    if (value.isEmpty()) {
        return FormValidation.error(Messages.AppCenterRecorder_DescriptorImpl_errors_missingDistributionGroups());
    }

    final Validator validator = new DistributionGroupsValidator();

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

    return FormValidation.ok();
}
 
Example 27
Source Project: appcenter-plugin   Source File: AppCenterRecorder.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("unused")
public FormValidation doCheckBuildVersion(@QueryParameter String value) {
    if (value.trim().isEmpty()) {
        return FormValidation.ok();
    }

    final Validator buildVersionValidator = new BuildVersionValidator();

    if (!buildVersionValidator.isValid(value)) {
        return FormValidation.error(Messages.AppCenterRecorder_DescriptorImpl_errors_invalidBuildVersion());
    }

    return FormValidation.ok();
}
 
Example 28
/**
 * 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 doCheckTimeout(@QueryParameter String value) throws IOException, ServletException {
	try {
		Integer.parseInt(value);
		return FormValidation.ok();
	} catch (NumberFormatException e) {
		return FormValidation.error("Must be a number");
	}
}
 
Example 29
/**
 * 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 30
Source Project: gitlab-branch-source-plugin   Source File: GitLabSCMNavigator.java    License: MIT License 5 votes vote down vote up
public static FormValidation doCheckProjectOwner(@QueryParameter String projectOwner,
    @QueryParameter String serverName) {
    if (projectOwner.equals("")) {
        return FormValidation.ok();
    }
    GitLabApi gitLabApi = null;
    try {
        gitLabApi = apiBuilder(serverName);
        GitLabOwner gitLabOwner = GitLabOwner.fetchOwner(gitLabApi, projectOwner);
        return FormValidation.ok(projectOwner + " is a valid " + gitLabOwner.getWord());
    } catch (IllegalStateException e) {
        return FormValidation.error(e, e.getMessage());
    }
}