Java Code Examples for org.kohsuke.stapler.StaplerRequest

The following examples show how to use org.kohsuke.stapler.StaplerRequest. 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
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 2
Source Project: DotCi   Source File: DynamicBuild.java    License: MIT License 6 votes vote down vote up
@Override
public Object getDynamic(final String token, final StaplerRequest req, final StaplerResponse rsp) {
    try {
        final Build item = getRun(Combination.fromString(token));
        if (item != null) {
            if (item.getNumber() == this.getNumber()) {
                return item;
            } else {
                // redirect the user to the correct URL
                String url = Functions.joinPath(item.getUrl(), req.getRestOfPath());
                final String qs = req.getQueryString();
                if (qs != null) {
                    url += '?' + qs;
                }
                throw HttpResponses.redirectViaContextPath(url);
            }
        }
    } catch (final IllegalArgumentException e) {
        // failed to parse the token as Combination. Must be something else
    }
    return super.getDynamic(token, req, rsp);
}
 
Example 3
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 4
Source Project: ezScrum   Source File: EzScrumRoot.java    License: 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 Project: jenkins-client-plugin   Source File: ResourceSelector.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ResourceSelector newInstance(StaplerRequest req,
        JSONObject formData) throws FormException {
    ResourceSelector s = super.newInstance(req, formData);

    String selectionType = formData.getString("selectionType");
    System.out.println("parms2: " + selectionType);

    if (SELECT_BY_KIND.equals(selectionType)) {
        s.names = null;
    }
    if (SELECT_BY_NAMES.equals(selectionType)) {
        s.kind = null;
        s.labels = null;
    }
    return s;
}
 
Example 6
Source Project: jenkins-build-monitor-plugin   Source File: BuildMonitorView.java    License: 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 7
Source Project: blueocean-plugin   Source File: LogResource.java    License: 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 8
Source Project: configuration-as-code-plugin   Source File: TokenReloadAction.java    License: MIT License 6 votes vote down vote up
@RequirePOST
public void doIndex(StaplerRequest request, StaplerResponse response) throws IOException {
    String token = getReloadTokenProperty();

    if (Strings.isNullOrEmpty(token)) {
        response.sendError(404);
        LOGGER.warning("Configuration reload via token is not enabled");
    } else {
        String requestToken = getRequestToken(request);

        if (token.equals(requestToken)) {
            LOGGER.info("Configuration reload triggered via token");

            try (ACLContext ignored = ACL.as(ACL.SYSTEM)) {
                ConfigurationAsCode.get().configure();
            }
        } else {
            response.sendError(401);
            LOGGER.warning("Invalid token received, not reloading configuration");
        }
    }
}
 
Example 9
@Override
public SCM newInstance(final StaplerRequest req,
                       final JSONObject formData) throws FormException {
    return new AWSCodePipelineSCM(
            req.getParameter("name"),
            req.getParameter("clearWorkspace") != null,
            req.getParameter("region"),
            req.getParameter("awsAccessKey"),
            req.getParameter("awsSecretKey"),
            req.getParameter("proxyHost"),
            req.getParameter("proxyPort"),
            req.getParameter("category"),
            req.getParameter("provider"),
            req.getParameter("version"),
            new AWSClientFactory());
}
 
Example 10
@Test
public void unauthorizedAccessToContentShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    String aliceCredentialId = createCredential(BitbucketCloudScm.ID, "cloud", alice);

    StaplerRequest staplerRequest = mockStapler();

    MultiBranchProject mbp = mockMbp(aliceCredentialId, alice);

    try {
        //Bob trying to access content but his credential is not setup so should fail
        new BitbucketCloudScmContentProvider().getContent(staplerRequest, mbp);
    } catch (ServiceException.PreconditionRequired e) {
        assertEquals("Can't access content from Bitbucket: no credential found", e.getMessage());
        return;
    }
    fail("Should have failed with PreConditionException");
}
 
Example 11
Source Project: DotCi   Source File: GithubWebhookTest.java    License: MIT License 6 votes vote down vote up
protected void kickOffBuildTrigger(final StaplerRequest request, final DynamicProject projectForRepo) throws IOException, InterruptedException {
    final PushAndPullRequestPayload payload = mock(PushAndPullRequestPayload.class);

    final DynamicProjectRepository projectRepo = mock(DynamicProjectRepository.class);

    when(payload.needsBuild(any(DynamicProject.class))).thenReturn(true);
    when(payload.getProjectUrl()).thenReturn("[email protected]");
    when(payload.getCause()).thenReturn(mock(GithubPushPullWebhookCause.class));
    when(projectRepo.getJobsFor("[email protected]")).thenReturn(newArrayList(projectForRepo));

    doReturn(payload).when(this.githubWebhook).makePayload(anyString(), anyString());
    doReturn(projectRepo).when(this.githubWebhook).makeDynamicProjectRepo();

    this.githubWebhook.doIndex(request, null);
    Thread.sleep(2000);
}
 
Example 12
Source Project: blueocean-plugin   Source File: GithubScmContentProviderTest.java    License: MIT License 5 votes vote down vote up
@Test
public void getContentForOrgFolderGHE() throws UnirestException {
    String credentialId = createGithubEnterpriseCredential();

    StaplerRequest staplerRequest = mockStapler(GithubEnterpriseScm.ID);

    MultiBranchProject mbp = mockMbp(credentialId, user, GithubEnterpriseScm.DOMAIN_NAME);

    GithubFile content = (GithubFile) new GithubScmContentProvider().getContent(staplerRequest, mbp);
    assertEquals("Jenkinsfile", content.getContent().getName());
    assertEquals("e23b8ef5c2c4244889bf94db6c05cc08ea138aef", content.getContent().getSha());
    assertEquals("PR-demo", content.getContent().getRepo());
    assertEquals("cloudbeers", content.getContent().getOwner());
}
 
Example 13
Source Project: docker-plugin   Source File: DockerManagementServer.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("unused")
@RequirePOST
public void doControlSubmit(@QueryParameter("stopId") String stopId, StaplerRequest req, StaplerResponse rsp) throws IOException {
    Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
    final DockerAPI dockerApi = theCloud.getDockerApi();
    try(final DockerClient client = dockerApi.getClient()) {
        client.stopContainerCmd(stopId).exec();
    }
    rsp.sendRedirect(".");
}
 
Example 14
Source Project: jenkins-status-badges-plugin   Source File: PublicBuildAction.java    License: MIT License 5 votes vote down vote up
public HttpResponse doIcon( StaplerRequest req, StaplerResponse rsp, @QueryParameter String job,
                            @QueryParameter String style )
    throws IOException, FontFormatException
{
    Job<?, ?> project = buildStatus.getProject( job, req, rsp );
    return iconResolver.getBuildImage( project.getIconColor(), style );
}
 
Example 15
Source Project: pipeline-maven-plugin   Source File: GlobalPipelineMavenConfig.java    License: MIT License 5 votes vote down vote up
@Override
public boolean configure(StaplerRequest req, JSONObject json) throws FormException {
    req.bindJSON(this, json);
    // stapler oddity, empty lists coming from the HTTP request are not set on bean by  "req.bindJSON(this, json)"
    this.publisherOptions = req.bindJSONToList(MavenPublisher.class, json.get("publisherOptions"));
    save();
    return true;
}
 
Example 16
Source Project: blueocean-plugin   Source File: GithubScmContentProviderTest.java    License: MIT License 5 votes vote down vote up
@Test
public void unauthorizedSaveContentToOrgFolderGHEShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    String aliceCredentialId = createGithubEnterpriseCredential(alice);


    StaplerRequest staplerRequest = mockStapler(GithubEnterpriseScm.ID);

    GitContent content = new GitContent.Builder().autoCreateBranch(true).base64Data("c2xlZXAgMTUKbm9kZSB7CiAgY2hlY2tvdXQgc2NtCiAgc2ggJ2xzIC1sJwp9\\nCnNsZWVwIDE1Cg==\\n")
            .branch("test1").message("another commit").owner("cloudbeers").path("Jankinsfile").repo("PR-demo").sha("e23b8ef5c2c4244889bf94db6c05cc08ea138aef").build();

    when(staplerRequest.bindJSON(Mockito.eq(GithubScmSaveFileRequest.class), Mockito.any(JSONObject.class))).thenReturn(new GithubScmSaveFileRequest(content));

    MultiBranchProject mbp = mockMbp(aliceCredentialId, user, GithubEnterpriseScm.DOMAIN_NAME);

    String request = "{\n" +
            "  \"content\" : {\n" +
            "    \"message\" : \"first commit\",\n" +
            "    \"path\" : \"Jenkinsfile\",\n" +
            "    \"branch\" : \"test1\",\n" +
            "    \"repo\" : \"PR-demo\",\n" +
            "    \"sha\" : \"e23b8ef5c2c4244889bf94db6c05cc08ea138aef\",\n" +
            "    \"base64Data\" : "+"\"c2xlZXAgMTUKbm9kZSB7CiAgY2hlY2tvdXQgc2NtCiAgc2ggJ2xzIC1sJwp9\\nCnNsZWVwIDE1Cg==\\n\""+
            "  }\n" +
            "}";

    when(staplerRequest.getReader()).thenReturn(new BufferedReader(new StringReader(request), request.length()));
    try {
        //Bob trying to access content but his credential is not setup so should fail
        new GithubScmContentProvider().saveContent(staplerRequest, mbp);
    }catch (ServiceException.PreconditionRequired e){
        assertEquals("Can't access content from github: no credential found", e.getMessage());
        return;
    }
    fail("Should have failed with PreConditionException");
}
 
Example 17
Source Project: blueocean-plugin   Source File: OrganizationFolderTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testOrganizationFolderFactory() throws Exception{
    List<OrganizationFolderPipelineImpl.OrganizationFolderFactory> organizationFolderFactoryList = ExtensionList.lookup(OrganizationFolderPipelineImpl.OrganizationFolderFactory.class);
    OrganizationFolderFactoryTestImpl organizationFolderFactoryTest = ((ExtensionList<OrganizationFolderPipelineImpl.OrganizationFolderFactory>) organizationFolderFactoryList).get(OrganizationFolderFactoryTestImpl.class);
    assertNotNull(organizationFolderFactoryTest);

    OrganizationFolderPipelineImpl folderPipeline = organizationFolderFactoryTest.getFolder(orgFolder, new Reachable() {
        @Override
        public Link getLink() {
            return organization.getLink().rel("/pipelines/");
        }
    }, mockOrganization());
    assertNotNull(folderPipeline);

    assertNotNull(folderPipeline.getQueue());
    assertNotNull(folderPipeline.getQueue().iterator());

    //Make sure the user does has permissions to that folder
    PowerMockito.when(orgFolder.getACL()).thenReturn(new ACL() {
        @Override
        public boolean hasPermission(Authentication arg0, Permission arg1) {
            return true;
        }
    });

    ScmResourceImpl scmResource = new ScmResourceImpl(orgFolder, folderPipeline);
    StaplerRequest staplerRequest = PowerMockito.mock(StaplerRequest.class);
    assertEquals("hello", scmResource.getContent(staplerRequest));
}
 
Example 18
Source Project: DotCi   Source File: GithubWebhook.java    License: MIT License 5 votes vote down vote up
public void doIndex(final StaplerRequest req, final StaplerResponse response) throws IOException {
    String payload = req.getParameter("payload");
    if (StringUtils.isEmpty(payload) && "POST".equalsIgnoreCase(req.getMethod())) {
        payload = getRequestPayload(req);
    }
    if (StringUtils.isEmpty(payload)) {
        throw new IllegalArgumentException("Not intended to be browsed interactively (must specify payload parameter)");
    }
    processGitHubPayload(req.getHeader("X-GitHub-Event"), payload);
}
 
Example 19
public HttpResponse doIcon( StaplerRequest req, StaplerResponse rsp, @QueryParameter String job,
                            @QueryParameter String style )
    throws IOException, FontFormatException
{
    Job<?, ?> project = coverageStatus.getProject( job, req, rsp );
    int coverage = coverageStatus.getCoverage( project );
    return iconResolver.getCoverageImage( coverage, style );
}
 
Example 20
Source Project: DotCi   Source File: DynamicProject.java    License: 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 21
Source Project: aws-lambda-jenkins-plugin   Source File: LambdaUploadPublisher.java    License: MIT License 5 votes vote down vote up
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
    req.bindJSON(this, formData);

    save();

    return super.configure(req,formData);
}
 
Example 22
Source Project: sonar-quality-gates-plugin   Source File: GlobalConfig.java    License: MIT License 5 votes vote down vote up
@Override
public boolean configure(StaplerRequest req, JSONObject json) throws FormException {

    listOfGlobalConfigData = globalConfigurationService.instantiateGlobalConfigData(json);
    save();

    return true;
}
 
Example 23
Source Project: blueocean-plugin   Source File: RepositoryCloneProgressEndpoint.java    License: MIT License 5 votes vote down vote up
@DELETE
@WebMethod(name="")
public HttpResponse cancelClone(StaplerRequest req) {
    String repositoryUrl = req.getOriginalRestOfPath();
    CloneProgressMonitor progress = CloneProgressMonitor.get(repositoryUrl);
    if (progress != null) {
        progress.cancel();
    }
    return HttpResponses.ok();
}
 
Example 24
@Override
public boolean configure(
        final StaplerRequest req,
        final JSONObject formData)
        throws FormException {
    req.bindJSON(this, formData);
    save();

    return super.configure(req, formData);
}
 
Example 25
Source Project: aws-codecommit-trigger-plugin   Source File: SQSTrigger.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean configure(final StaplerRequest req, final JSONObject json) throws FormException {
    Object sqsQueues = json.get("sqsQueues");
    if (json.size() == 1) {
        String key = json.keys().next().toString();
        sqsQueues = json.getJSONObject(key).get("sqsQueues");
    }
    this.sqsQueues = req.bindJSONToList(SQSTriggerQueue.class, sqsQueues);
    this.initQueueMap();

    this.save();

    EventBroker.getInstance().post(new ConfigurationChangedEvent());
    return true;
}
 
Example 26
@Override
public boolean configure(StaplerRequest req, JSONObject json) throws FormException {
    json = json.getJSONObject("config");
    webhookSecret = json.getString("webhookSecret");
    save();
    return true;
}
 
Example 27
Source Project: DotCi   Source File: DbBackedProject.java    License: MIT License 5 votes vote down vote up
@Override
public B getLastBuild() {
    String branch = "master";
    final StaplerRequest currentRequest = Stapler.getCurrentRequest();
    if (currentRequest != null && StringUtils.isNotEmpty(currentRequest.getParameter("branch"))) {
        branch = currentRequest.getParameter("branch");
    }
    return this.dynamicBuildRepository.<B>getLastBuild(this, branch);
}
 
Example 28
Source Project: blueocean-plugin   Source File: GithubScmContentProviderTest.java    License: MIT License 5 votes vote down vote up
@Test
public void unauthorizedSaveContentToMbpShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    String aliceCredentialId = createGithubCredential(alice);

    StaplerRequest staplerRequest = mockStapler();

    GitContent content = new GitContent.Builder().autoCreateBranch(true).base64Data("c2xlZXAgMTUKbm9kZSB7CiAgY2hlY2tvdXQgc2NtCiAgc2ggJ2xzIC1sJwp9\\nCnNsZWVwIDE1Cg==\\n")
            .branch("test1").message("another commit").owner("cloudbeers").path("Jankinsfile").repo("PR-demo").sha("e23b8ef5c2c4244889bf94db6c05cc08ea138aef").build();

    when(staplerRequest.bindJSON(Mockito.eq(GithubScmSaveFileRequest.class), Mockito.any(JSONObject.class))).thenReturn(new GithubScmSaveFileRequest(content));


    MultiBranchProject mbp = mockMbp(aliceCredentialId, user, GithubScm.DOMAIN_NAME);

    String request = "{\n" +
            "  \"content\" : {\n" +
            "    \"message\" : \"first commit\",\n" +
            "    \"path\" : \"Jenkinsfile\",\n" +
            "    \"branch\" : \"test1\",\n" +
            "    \"repo\" : \"PR-demo\",\n" +
            "    \"sha\" : \"e23b8ef5c2c4244889bf94db6c05cc08ea138aef\",\n" +
            "    \"base64Data\" : "+"\"c2xlZXAgMTUKbm9kZSB7CiAgY2hlY2tvdXQgc2NtCiAgc2ggJ2xzIC1sJwp9\\nCnNsZWVwIDE1Cg==\\n\""+
            "  }\n" +
            "}";

    when(staplerRequest.getReader()).thenReturn(new BufferedReader(new StringReader(request), request.length()));

    try {
        //Bob trying to access content but his credential is not setup so should fail
        new GithubScmContentProvider().saveContent(staplerRequest, mbp);
    }catch (ServiceException.PreconditionRequired e){
        assertEquals("Can't access content from github: no credential found", e.getMessage());
        return;
    }
    fail("Should have failed with PreConditionException");
}
 
Example 29
Source Project: aws-codebuild-jenkins-plugin   Source File: CodeBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
    req.bindJSON(this, formData);
    this.minSleepTime = formData.optInt("minSleepTime", 0);
    this.maxSleepTime = formData.optInt("maxSleepTime", 0);
    this.sleepJitter = formData.optInt("sleepJitter", 0);
    save();
    return super.configure(req, formData);
}
 
Example 30
/**
 * Constructs this extension of {@link RequestImpl} under the assumption that {@link RequestImpl} is also the
 * underlying type of the {@link StaplerRequest}.
 *
 * @param request the request submitted the {@link TemplateDrivenMultiBranchProject}
 */
TemplateStaplerRequestWrapper(StaplerRequest request) {
    /*
     * Ugly casts to RequestImpl... but should be ok since it will throw
     * errors, which we want anyway if it's not that type.
     */
    super(request.getStapler(), request, ((RequestImpl) request).ancestors,
            ((RequestImpl) request).tokens);
}