org.kohsuke.accmod.restrictions.NoExternalUse Java Examples

The following examples show how to use org.kohsuke.accmod.restrictions.NoExternalUse. 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: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
/**
 * Recursive search for all {@link #YAML_FILES_PATTERN} in provided base path
 *
 * @param path base path to start (can be file or directory)
 * @return list of all paths matching pattern. Only base file itself if it is a file matching pattern
 */
@Restricted(NoExternalUse.class)
public List<Path> configs(String path) throws ConfiguratorException {
    final Path root = Paths.get(path);

    if (!Files.exists(root)) {
        throw new ConfiguratorException("Invalid configuration: '"+path+"' isn't a valid path.");
    }

    if (Files.isRegularFile(root) && Files.isReadable(root)) {
        return Collections.singletonList(root);
    }

    final PathMatcher matcher = FileSystems.getDefault().getPathMatcher(YAML_FILES_PATTERN);
    try (Stream<Path> stream = Files.find(Paths.get(path), Integer.MAX_VALUE,
            (next, attrs) -> !attrs.isDirectory() && !isHidden(next) && matcher.matches(next), FileVisitOption.FOLLOW_LINKS)) {
        return stream.sorted().collect(toList());
    } catch (IOException e) {
        throw new IllegalStateException("failed config scan for " + path, e);
    }
}
 
Example #2
Source File: GitLabServer.java    From gitlab-branch-source-plugin with 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 #3
Source File: GiteaServer.java    From gitea-plugin with MIT License 6 votes vote down vote up
/**
 * Stapler form completion.
 *
 * @param serverUrl the server URL.
 * @return the available credentials.
 */
@Restricted(NoExternalUse.class) // stapler
@SuppressWarnings("unused")
public ListBoxModel doFillCredentialsIdItems(@QueryParameter String serverUrl) {
    Jenkins.get().checkPermission(Jenkins.ADMINISTER);
    StandardListBoxModel result = new StandardListBoxModel();
    serverUrl = GiteaServers.normalizeServerUrl(serverUrl);
    result.includeMatchingAs(
            ACL.SYSTEM,
            Jenkins.get(),
            StandardCredentials.class,
            URIRequirementBuilder.fromUri(serverUrl).build(),
            AuthenticationTokens.matcher(GiteaAuth.class)
    );
    return result;
}
 
Example #4
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 #5
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
@RequirePOST
@Restricted(NoExternalUse.class)
public void doCheck(StaplerRequest req, StaplerResponse res) throws Exception {

    if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
        res.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    final Map<Source, String> issues = checkWith(YamlSource.of(req));
    res.setContentType("application/json");
    final JSONArray warnings = new JSONArray();
    issues.entrySet().stream().map(e -> new JSONObject().accumulate("line", e.getKey().line).accumulate("warning", e.getValue()))
            .forEach(warnings::add);
    warnings.write(res.getWriter());
}
 
Example #6
Source File: GitLabSCMSource.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Restricted(NoExternalUse.class)
public ListBoxModel doFillProjectPathItems(@QueryParameter @RelativePath("sourceSettings") String connectionName) throws GitLabAPIException {
    ListBoxModel items = new ListBoxModel();
    // TODO: respect settings in nearest GitLabSCMNavigator
    for (GitLabProject project : gitLabAPI(connectionName).findProjects(VISIBLE, ALL, "")) {
        items.add(project.getPathWithNamespace());
    }
    return items;
}
 
Example #7
Source File: GitLabSCMBranchMonitorStrategy.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 5 votes vote down vote up
@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 #8
Source File: GitLabLogoutAction.java    From gitlab-oauth-plugin with MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class) // jelly only
public String getGitLabURL() {
    Jenkins j = Jenkins.getInstance();
    assert j != null;
    SecurityRealm r = j.getSecurityRealm();
    if (r instanceof GitLabSecurityRealm) {
        GitLabSecurityRealm glsr = (GitLabSecurityRealm) r;
        return glsr.getGitlabWebUri();
    }
    // only called from the Jelly if the GithubSecurityRealm is set...
    return "";
}
 
Example #9
Source File: ViolationsToGitHubConfiguration.java    From violation-comments-to-github-plugin with MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class)
public ListBoxModel doFillMinSeverityItems() {
  final ListBoxModel items = new ListBoxModel();
  for (final SEVERITY severity : SEVERITY.values()) {
    items.add(severity.name());
  }
  return items;
}
 
Example #10
Source File: ViolationsToGitHubConfig.java    From violation-comments-to-github-plugin with MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class)
public ListBoxModel doFillMinSeverityItems() {
  final ListBoxModel items = new ListBoxModel();
  items.add("Default, Global Config or Info", "");
  for (final SEVERITY severity : SEVERITY.values()) {
    items.add(severity.name());
  }
  return items;
}
 
Example #11
Source File: ViolationConfig.java    From violation-comments-to-github-plugin with MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class)
public ListBoxModel doFillParserItems() {
  final ListBoxModel items = new ListBoxModel();
  for (final Parser parser : Parser.values()) {
    items.add(parser.name());
  }
  return items;
}
 
Example #12
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class)
public static String printThrowable(@NonNull Throwable t) {
    String s = Functions.printThrowable(t)
        .split("at io.jenkins.plugins.casc.ConfigurationAsCode.export")[0]
        .replaceAll("\t", "  ");
    return s.substring(0, s.lastIndexOf(")") + 1);
}
 
Example #13
Source File: VaultConfiguration.java    From hashicorp-vault-plugin with MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class)
public static ListBoxModel engineVersions(Item context) {
    ListBoxModel options = new ListBoxModel(
        new Option("2", "2"),
        new Option("1", "1")
    );
    if (context != null) {
        Option option = new Option("Default", "");
        options.add(0, option);
    }
    return options;
}
 
Example #14
Source File: GitLabSCMSourceSettings.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Restricted(NoExternalUse.class)
public ListBoxModel doFillConnectionNameItems() {
    ListBoxModel items = new ListBoxModel();
    for (String name : gitLabConnectionNames()) {
        items.add(name, name);
    }
    return items;
}
 
Example #15
Source File: GitLabSCMSourceSettings.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Restricted(NoExternalUse.class)
public BuildStatusPublishMode determineBuildStatusPublishMode(SCMHead head) {
    if (head instanceof GitLabSCMMergeRequestHead) {
        return ((GitLabSCMMergeRequestHead) head).fromOrigin()
                ? originMonitorStrategy.getBuildStatusPublishMode()
                : forksMonitorStrategy.getBuildStatusPublishMode();
    } else if (head instanceof TagSCMHead) {
        return tagMonitorStrategy.getBuildStatusPublishMode();
    }

    return branchMonitorStrategy.getBuildStatusPublishMode();
}
 
Example #16
Source File: WithMavenStep.java    From pipeline-maven-plugin with MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class) // Only for UI calls
public ListBoxModel doFillJdkItems() {
    ListBoxModel r = new ListBoxModel();
    r.add("--- Use system default JDK ---",null);
    for (JDK installation : getJDKDescriptor().getInstallations()) {
        r.add(installation.getName());
    }
    return r;
}
 
Example #17
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
/**
 * Retrieve which plugin do provide this extension point, used in documentation.jelly
 *
 * @return String representation of the extension source, usually artifactId.
 */
@Restricted(NoExternalUse.class)
@CheckForNull
public String getExtensionSource(Configurator c) throws IOException {
    final Class e = c.getImplementedAPI();
    final String jar = Which.jarFile(e).getName();
    if (jar.startsWith("jenkins-core-")) { // core jar has version in name
        return "jenkins-core";
    }
    return jar.substring(0, jar.lastIndexOf('.'));
}
 
Example #18
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@VisibleForTesting
@Restricted(NoExternalUse.class)
public static void serializeYamlNode(Node root, Writer writer) throws IOException {
    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(BLOCK);
    options.setDefaultScalarStyle(PLAIN);
    options.setSplitLines(true);
    options.setPrettyFlow(true);
    Serializer serializer = new Serializer(new Emitter(writer, options), new Resolver(),
            options, null);
    serializer.open();
    serializer.serialize(root);
    serializer.close();
}
 
Example #19
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@RequirePOST
@Restricted(NoExternalUse.class)
public void doViewExport(StaplerRequest req, StaplerResponse res) throws Exception {
    if (!Jenkins.get().hasPermission(Jenkins.SYSTEM_READ)) {
        res.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    export(out);

    req.setAttribute("export", out.toString(StandardCharsets.UTF_8.name()));
    req.getView(this, "viewExport.jelly").forward(req, res);
}
 
Example #20
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
/**
 * Export JSONSchema to URL
 * @throws Exception
 */
@Restricted(NoExternalUse.class)
public void doSchema(StaplerRequest req, StaplerResponse res) throws Exception {
    if (!Jenkins.get().hasPermission(Jenkins.SYSTEM_READ)) {
        res.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    res.setContentType("application/json; charset=utf-8");
    res.getWriter().print(writeJSONSchema());
}
 
Example #21
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
/**
 * Export live jenkins instance configuration as Yaml
 * @throws Exception
 */
@RequirePOST
@Restricted(NoExternalUse.class)
public void doExport(StaplerRequest req, StaplerResponse res) throws Exception {
    if (!Jenkins.get().hasPermission(Jenkins.SYSTEM_READ)) {
        res.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    res.setContentType("application/x-yaml; charset=utf-8");
    res.addHeader("Content-Disposition", "attachment; filename=jenkins.yaml");
    export(res.getOutputStream());
}
 
Example #22
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@RequirePOST
@Restricted(NoExternalUse.class)
public void doApply(StaplerRequest req, StaplerResponse res) throws Exception {

    if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
        res.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    configureWith(YamlSource.of(req));
}
 
Example #23
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 #24
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@RequirePOST
@Restricted(NoExternalUse.class)
public void doReplace(StaplerRequest request, StaplerResponse response) throws Exception {
    if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    String newSource = request.getParameter("_.newSource");
    String normalizedSource = Util.fixEmptyAndTrim(newSource);
    File file = new File(Util.fixNull(normalizedSource));
    if (file.exists() || ConfigurationAsCode.isSupportedURI(normalizedSource)) {
        List<String> candidatePaths = Collections.singletonList(normalizedSource);
        List<YamlSource> candidates = getConfigFromSources(candidatePaths);
        if (canApplyFrom(candidates)) {
            sources = candidatePaths;
            configureWith(getConfigFromSources(getSources()));
            CasCGlobalConfig config = GlobalConfiguration.all().get(CasCGlobalConfig.class);
            if (config != null) {
                config.setConfigurationPath(normalizedSource);
                config.save();
            }
            LOGGER.log(Level.FINE, "Replace configuration with: " + normalizedSource);
        } else {
            LOGGER.log(Level.WARNING, "Provided sources could not be applied");
            // todo: show message in UI
        }
    } else {
        LOGGER.log(Level.FINE, "No such source exists, applying default");
        // May be do nothing instead?
        configure();
    }
    response.sendRedirect("");
}
 
Example #25
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@RequirePOST
@Restricted(NoExternalUse.class)
public void doReload(StaplerRequest request, StaplerResponse response) throws Exception {
    if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    configure();
    response.sendRedirect("");
}
 
Example #26
Source File: OriginPullRequestDiscoveryTrait.java    From gitea-plugin with MIT License 5 votes vote down vote up
/**
 * Populates the strategy options.
 *
 * @return the stategy options.
 */
@NonNull
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // stapler
public ListBoxModel doFillStrategyIdItems() {
    ListBoxModel result = new ListBoxModel();
    result.add(Messages.ForkPullRequestDiscoveryTrait_mergeOnly(), "1");
    result.add(Messages.ForkPullRequestDiscoveryTrait_headOnly(), "2");
    result.add(Messages.ForkPullRequestDiscoveryTrait_headAndMerge(), "3");
    return result;
}
 
Example #27
Source File: ForkPullRequestDiscoveryTrait.java    From gitea-plugin with MIT License 5 votes vote down vote up
/**
 * Populates the strategy options.
 *
 * @return the stategy options.
 */
@NonNull
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // stapler
public ListBoxModel doFillStrategyIdItems() {
    ListBoxModel result = new ListBoxModel();
    result.add(Messages.ForkPullRequestDiscoveryTrait_mergeOnly(), "1");
    result.add(Messages.ForkPullRequestDiscoveryTrait_headOnly(), "2");
    result.add(Messages.ForkPullRequestDiscoveryTrait_headAndMerge(), "3");
    return result;
}
 
Example #28
Source File: CukedoctorPublisher.java    From cucumber-living-documentation-plugin with MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class) // Only for UI calls
public ListBoxModel doFillFormatItems() {
    ListBoxModel items = new ListBoxModel();
    for (FormatType formatType : FormatType.values()) {
        items.add(formatType.getFormat(), formatType.name());
    }
    return items;
}
 
Example #29
Source File: WithMavenStep.java    From pipeline-maven-plugin with MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class) // Only for UI calls
public ListBoxModel doFillMavenSettingsConfigItems(@AncestorInPath ItemGroup context) {
    ListBoxModel r = new ListBoxModel();
    r.add("--- Use system default settings or file path ---",null);
    for (Config config : ConfigFiles.getConfigsInContext(context, MavenSettingsConfigProvider.class)) {
        r.add(config.name, config.id);
    }
    return r;
}
 
Example #30
Source File: CukedoctorPublisher.java    From cucumber-living-documentation-plugin with MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class) // Only for UI calls
public ListBoxModel doFillTocItems() {
    ListBoxModel items = new ListBoxModel();
    for (TocType tocType : TocType.values()) {
        items.add(tocType.getToc(), tocType.name());
    }
    return items;
}