Java Code Examples for org.kohsuke.stapler.StaplerRequest#getParameter()

The following examples show how to use org.kohsuke.stapler.StaplerRequest#getParameter() . 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: BuildMonitorView.java    From jenkins-build-monitor-plugin with MIT License 6 votes vote down vote up
@Override
protected void submit(StaplerRequest req) throws ServletException, IOException, FormException {
    super.submit(req);

    JSONObject json = req.getSubmittedForm();

    synchronized (this) {

        String requestedOrdering = req.getParameter("order");
        title                    = req.getParameter("title");

        currentConfig().setDisplayCommitters(json.optBoolean("displayCommitters", true));
        currentConfig().setBuildFailureAnalyzerDisplayedField(req.getParameter("buildFailureAnalyzerDisplayedField"));
        
        try {
            currentConfig().setOrder(orderIn(requestedOrdering));
        } catch (Exception e) {
            throw new FormException("Can't order projects by " + requestedOrdering, "order");
        }
    }
}
 
Example 2
Source File: GithubScm.java    From blueocean-plugin with MIT License 6 votes vote down vote up
protected @Nonnull String getCustomApiUri() {
    StaplerRequest request = Stapler.getCurrentRequest();
    Preconditions.checkNotNull(request, "Must be called in HTTP request context");
    String apiUri = request.getParameter("apiUrl");

    // if "apiUrl" parameter was supplied, parse and trim trailing slash
    if (!StringUtils.isEmpty(apiUri)) {
        try {
            new URI(apiUri);
        } catch (URISyntaxException ex) {
            throw new ServiceException.BadRequestException(new ErrorMessage(400, "Invalid URI: " + apiUri));
        }
        apiUri = normalizeUrl(apiUri);
    } else {
        apiUri = "";
    }

    return apiUri;
}
 
Example 3
Source File: LockableResourcesRootAction.java    From lockable-resources-plugin with MIT License 6 votes vote down vote up
public void doReserve(StaplerRequest req, StaplerResponse rsp)
	throws IOException, ServletException {
	Jenkins.get().checkPermission(RESERVE);

	String name = req.getParameter("resource");
	LockableResource r = LockableResourcesManager.get().fromName(name);
	if (r == null) {
		rsp.sendError(404, "Resource not found " + name);
		return;
	}

	List<LockableResource> resources = new ArrayList<>();
	resources.add(r);
	String userName = getUserName();
	if (userName != null)
		LockableResourcesManager.get().reserve(resources, userName);

	rsp.forwardToPreviousPage(req);
}
 
Example 4
Source File: EzScrumRoot.java    From ezScrum with GNU General Public License v2.0 6 votes vote down vote up
public void doRemovePlugin(StaplerRequest request, StaplerResponse response) throws Exception {
	String pluginName = request.getParameter("pluginName");// it is unique

	PluginModifier pluginModifier = new PluginModifier();
	try {
		// remove import.jsp which in plugin to host
		pluginModifier.removePluginImportPath(FilenameUtils.removeExtension(pluginName));
	} catch (Exception e) {
		throw e;
	}
	final String pluginPath = "./WebContent/pluginWorkspace/" + pluginName;

	PluginManager pluginManager = new PluginManager();
	// uninstall plugin 
	pluginManager.removePlugin(pluginPath);
}
 
Example 5
Source File: LogResource.java    From blueocean-plugin with MIT License 6 votes vote down vote up
private void writeLog(StaplerRequest req, StaplerResponse rsp) {
    try {
        String download = req.getParameter("download");

        if("true".equalsIgnoreCase(download)) {
            rsp.setHeader("Content-Disposition", "attachment; filename=log.txt");
        }

        rsp.setContentType("text/plain;charset=UTF-8");
        rsp.setStatus(HttpServletResponse.SC_OK);

        writeLogs(req, rsp);
    } catch (IOException e) {
        throw new ServiceException.UnexpectedErrorException("Failed to get logText: " + e.getMessage(), e);
    }
}
 
Example 6
Source File: FavoriteContainerImpl.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Override
public Iterator<BlueFavorite> iterator() {
    StaplerRequest request = Stapler.getCurrentRequest();
    int start=0;
    int limit = PagedResponse.DEFAULT_LIMIT;

    if(request != null) {
        String startParam = request.getParameter("start");
        if (StringUtils.isNotBlank(startParam)) {
            start = Integer.parseInt(startParam);
        }

        String limitParam = request.getParameter("limit");
        if (StringUtils.isNotBlank(limitParam)) {
            limit = Integer.parseInt(limitParam);
        }
    }

    return iterator(start, limit);
}
 
Example 7
Source File: BlueTestResultContainerImpl.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Nonnull
@Override
public Iterator<BlueTestResult> iterator() {
    Result resolved = resolve();
    if (resolved.summary == null || resolved.results == null) {
        throw new NotFoundException("no tests");
    }
    StaplerRequest request = Stapler.getCurrentRequest();
    if (request != null) {
        String status = request.getParameter("status");
        String state = request.getParameter("state");
        String age = request.getParameter("age");
        return getBlueTestResultIterator(resolved.results, status, state, age);

    }
    return resolved.results.iterator();
}
 
Example 8
Source File: GitReadSaveService.java    From blueocean-plugin with MIT License 5 votes vote down vote up
private GitReadSaveRequest makeSaveRequest(Item item, StaplerRequest req) {
    String branch = req.getParameter("branch");
    return makeSaveRequest(item,
                           branch,
                           req.getParameter("commitMessage"),
                           ObjectUtils.defaultIfNull(req.getParameter("sourceBranch"), branch),
                           req.getParameter("path"),
                           Base64.decode(req.getParameter("contents"))
    );
}
 
Example 9
Source File: OrganizationFolderPipelineImpl.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
public void getUrl() {
    StaplerRequest req = Stapler.getCurrentRequest();
    String s = req.getParameter("s");
    if (s == null) {
        s = Integer.toString(DEFAULT_ICON_SIZE);
    }
    StaplerResponse resp = Stapler.getCurrentResponse();
    try {
        resp.setHeader("Cache-Control", "max-age=" + TimeUnit.DAYS.toDays(7));
        resp.sendRedirect(action.getAvatarImageOf(s));
    } catch (IOException e) {
        throw new UnexpectedErrorException("Could not provide icon", e);
    }
}
 
Example 10
Source File: GitHubBranchRepository.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Override
@RequirePOST
public FormValidation doRebuild(StaplerRequest req) throws IOException {
    FormValidation result;

    try {
        if (!job.hasPermission(Item.BUILD)) {
            return FormValidation.error("Forbidden");
        }

        final String param = "branchName";
        String branchName = "";
        if (req.hasParameter(param)) {
            branchName = req.getParameter(param);
        }

        Map<String, List<Run<?, ?>>> allBuilds = getAllBranchBuilds();
        List<Run<?, ?>> branchBuilds = allBuilds.get(branchName);
        if (branchBuilds != null && !allBuilds.isEmpty()) {
            if (rebuild(branchBuilds.get(0))) {
                result = FormValidation.ok("Rebuild scheduled");
            } else {
                result = FormValidation.warning("Rebuild not scheduled");
            }
        } else {
            result = FormValidation.warning("Build not found");
        }
    } catch (Exception e) {
        LOG.error("Can't start rebuild", e.getMessage());
        result = FormValidation.error(e, "Can't start rebuild: " + e.getMessage());
    }
    return result;
}
 
Example 11
Source File: ContainerFilter.java    From blueocean-plugin with MIT License 5 votes vote down vote up
private static String[] filterNames(){
    StaplerRequest req = Stapler.getCurrentRequest();
    if (req == null) {
        return new String[0];
    }
    String itemFilter = req.getParameter("filter");
    if (itemFilter == null) {
        return new String[0];
    }
    return itemFilter.split(",");
}
 
Example 12
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 13
Source File: ActionResolver.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
private WebHookAction onGetStatusPng(Job<?, ?> project, StaplerRequest request) {
    if (request.hasParameter("ref")) {
        return new BranchStatusPngAction(project, request.getParameter("ref"));
    } else {
        return new CommitStatusPngAction(project, request.getParameter("sha1"));
    }
}
 
Example 14
Source File: DynamicProject.java    From DotCi with MIT License 5 votes vote down vote up
public void doRemoveBranchTab(final StaplerRequest req, final StaplerResponse rsp) throws IOException, ServletException, InterruptedException {
    final String tabRegex = req.getParameter("tabRegex");
    if (StringUtils.isBlank(tabRegex))
        throw new RuntimeException("Branch Regex cannot be exmpty");
    final DynamicProjectBranchTabsProperty branchTabsProperty = getProperty(DynamicProjectBranchTabsProperty.class);
    branchTabsProperty.removeBranch(tabRegex);
    save();
}
 
Example 15
Source File: NonConfigurableKubernetesCloud.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public Cloud newInstance(StaplerRequest req, JSONObject formData) throws Descriptor.FormException {
    if (req != null) {
        // We prevent the cloud reconfiguration from the web UI
        String cloudName = req.getParameter("cloudName");
        return Jenkins.getInstance().getCloud(cloudName);
    } else {
        throw new IllegalStateException("Expecting req to be non-null");
    }
}
 
Example 16
Source File: DynamicProject.java    From DotCi with MIT License 5 votes vote down vote up
public void doAddBranchTab(final StaplerRequest req, final StaplerResponse rsp) throws IOException, ServletException, InterruptedException {
    final String tabRegex = req.getParameter("tabRegex");
    if (StringUtils.isBlank(tabRegex))
        throw new RuntimeException("Branch Regex cannot be exmpty");
    final DynamicProjectBranchTabsProperty branchTabsProperty = getProperty(DynamicProjectBranchTabsProperty.class);
    branchTabsProperty.addBranch(tabRegex);
    save();
}
 
Example 17
Source File: Project.java    From ezScrum with GNU General Public License v2.0 5 votes vote down vote up
public void doSetProjectPluginConfig(StaplerRequest request, StaplerResponse response) {
	String pluginName = request.getParameter("pluginName");
	String available = request.getParameter("available");
	PluginConfigManager configManager = new PluginConfigManager(mProjectName);
	Gson gson = new Gson();
	List<PluginConfig> pluginConfigList = gson.fromJson(configManager.readFileContent(), new TypeToken<List<PluginConfig>>() {}.getType());
	boolean isFound = false;
	for (PluginConfig pluginConfig : pluginConfigList) {
		if (pluginConfig.getId().contentEquals(pluginName)) {
			pluginConfig.setAvailable(Boolean.parseBoolean(available));
			isFound = true;
			break;
		}
	}
	if (!isFound) {
		PluginConfig config = new PluginConfig();
		config.setId(pluginName);
		config.setAvailable(Boolean.parseBoolean(available));
		pluginConfigList.add(config);
	}
	String content = gson.toJson(pluginConfigList);
	configManager.replaceFileContent(content);

	try {
		response.getWriter().write(this.mProjectName);
		response.getWriter().close();
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 18
Source File: GitHubBranchRepository.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@RequirePOST
public FormValidation doBuild(StaplerRequest req) throws IOException {
    FormValidation result;

    try {
        if (!job.hasPermission(Item.BUILD)) {
            return FormValidation.error("Forbidden");
        }

        final String param = "branchName";
        String branchName = null;
        if (req.hasParameter(param)) {
            branchName = req.getParameter(param);
        }
        if (isNull(branchName) || !getBranches().containsKey(branchName)) {
            return FormValidation.error("No branch to build");
        }

        final GitHubBranch localBranch = getBranches().get(branchName);
        final GitHubBranchCause cause = new GitHubBranchCause(localBranch, this, "Manual run.", false);
        final JobRunnerForBranchCause runner = new JobRunnerForBranchCause(getJob(),
                ghBranchTriggerFromJob(job));
        final QueueTaskFuture<?> queueTaskFuture = runner.startJob(cause);

        if (nonNull(queueTaskFuture)) {
            result = FormValidation.ok("Build scheduled");
        } else {
            result = FormValidation.warning("Build not scheduled");
        }
    } catch (Exception e) {
        LOG.error("Can't start build", e.getMessage());
        result = FormValidation.error(e, "Can't start build: " + e.getMessage());
    }

    return result;
}
 
Example 19
Source File: Export.java    From blueocean-plugin with MIT License 4 votes vote down vote up
private static void serveExposedBean(StaplerRequest req, StaplerResponse resp, Object exposedBean, ExportConfig config) throws ServletException, IOException {
    Flavor flavor = config.getFlavor();
    String pad=null;
    resp.setContentType(flavor.contentType);
    Writer w = resp.getCompressedWriter(req);

    if (flavor== Flavor.JSON || flavor== Flavor.JSONP) { // for compatibility reasons, accept JSON for JSONP as well.
        pad = req.getParameter("jsonp");
        if(pad!=null) w.write(pad+'(');
    }

    TreePruner pruner;
    String tree = req.getParameter("tree");
    if (tree != null) {
        try {
            pruner = new NamedPathPruner(tree);
        } catch (IllegalArgumentException x) {
            throw new ServletException("Malformed tree expression: " + x, x);
        }
    } else {
        int depth = 0;
        try {
            String s = req.getParameter("depth");
            if (s != null) {
                depth = Integer.parseInt(s);
            }
        } catch (NumberFormatException e) {
            throw new ServletException("Depth parameter must be a number");
        }
        pruner = new ByDepth(1 - depth);
    }

    DataWriter dw = flavor.createDataWriter(exposedBean, w, config);
    if (exposedBean instanceof Object[]) {
        // TODO: extend the contract of DataWriter to capture this
        // TODO: make this work with XML flavor (or at least reject this better)
        dw.startArray();
        for (Object item : (Object[])exposedBean)
            writeOne(pruner, dw, item);
        dw.endArray();
    } else {
        writeOne(pruner, dw, exposedBean);
    }

    if(pad!=null) w.write(')');
    w.close();
}
 
Example 20
Source File: GithubRepositories.java    From blueocean-plugin with MIT License 4 votes vote down vote up
public GithubRepositories(StandardUsernamePasswordCredentials credentials, String orgUrl, GithubRepositoryContainer parent) {
    this.self = parent.getLink().rel("repositories");
    this.accessToken = credentials.getPassword().getPlainText();
    this.credential = credentials;
    this.parent = parent;

    StaplerRequest request = Stapler.getCurrentRequest();
    int pageNumber = 0;
    if (request.getParameter("pageNumber") != null) {
        pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
    }
    int pageSize = 0;
    if (request.getParameter("pageSize") != null) {
        pageSize = Integer.parseInt(request.getParameter("pageSize"));
    }
    try {
        if (pageNumber == 0) {
            pageNumber = 1; //default
        }
        if (pageSize == 0) {
            pageSize = 100;
        }

        HttpURLConnection connection;
        connection = GithubScm.connect(String.format("%s/repos?type=%s&per_page=%s&page=%s",
                orgUrl,
                parent.getRepoType(),
                pageSize, pageNumber), accessToken);

        this.repositories = GithubScm.getMappingObjectReader().forType(GH_REPO_EX_LIST_TYPE)
            .readValue(HttpRequest.getInputStream(connection));

        String link = connection.getHeaderField("Link");

        int nextPage = 0;
        int lastPage = 0;

        if (link != null) {
            for (String token : link.split(", ")) {
                if (token.endsWith("rel=\"next\"") || token.endsWith("rel=\"last\"")) {

                    // <https://api.github.com/repos?page=3&per_page=100>; rel="next"
                    // <https://api.github.com/repos?page=3&per_page=100>; rel="next"
                    int idx = token.indexOf('>');
                    URL url = new URL(token.substring(1, idx));
                    for (String q : url.getQuery().split("&")) {
                        if (q.trim().startsWith("page=")) {
                            int i = q.indexOf('=');
                            if (q.length() >= i + 1) {
                                if (token.endsWith("rel=\"next\"")) {
                                    nextPage = Integer.parseInt(q.substring(i + 1));
                                }
                                if (token.endsWith("rel=\"last\"")) {
                                    lastPage = Integer.parseInt(q.substring(i + 1));
                                }
                            }
                        }
                    }
                }
            }
        }

        this.nextPage = nextPage > 0 ? nextPage : null;
        this.lastPage = lastPage > 0 ? lastPage : null;
        this.pageSize = pageSize;
    } catch (IOException e) {
        throw new ServiceException.UnexpectedErrorException(e.getMessage(), e);
    }
}