org.kohsuke.stapler.StaplerRequest Java Examples

The following examples show how to use org.kohsuke.stapler.StaplerRequest. 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: BitbucketCloudScmContentProviderTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@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 #2
Source File: DynamicBuild.java    From DotCi with 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
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 #4
Source File: TokenReloadAction.java    From configuration-as-code-plugin with 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 #5
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 #6
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 #7
Source File: GithubWebhookTest.java    From DotCi with 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("git@repo");
    when(payload.getCause()).thenReturn(mock(GithubPushPullWebhookCause.class));
    when(projectRepo.getJobsFor("git@repo")).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 #8
Source File: ResourceSelector.java    From jenkins-client-plugin with 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 #9
Source File: AWSCodePipelineSCM.java    From aws-codepipeline-plugin-for-jenkins with Apache License 2.0 6 votes vote down vote up
@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
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 #11
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 #12
Source File: AWSCodePipelinePublisher.java    From aws-codepipeline-plugin-for-jenkins with Apache License 2.0 5 votes vote down vote up
@Override
public boolean configure(
        final StaplerRequest req,
        final JSONObject formData)
        throws FormException {
    req.bindJSON(this, formData);
    save();

    return super.configure(req, formData);
}
 
Example #13
Source File: LambdaEventSourceBuildStep.java    From aws-lambda-jenkins-plugin with 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 #14
Source File: PackerJenkinsPluginTest.java    From packer-plugin with MIT License 5 votes vote down vote up
@Test
public void testPluginInJobAbsPathExec() throws Exception {

    final String jsonText = "{ \"here\": \"i am\"}";
    PackerInstallation installation = new PackerInstallation(name, home,
            params, createTemplateModeJson(TemplateMode.TEXT, jsonText), emptyFileEntries, null);

    PackerPublisher placeHolder = new PackerPublisher(name,
            null, null, PLUGIN_HOME, localParams, emptyFileEntries, false, null);

    PackerInstallation[] installations = new PackerInstallation[1];
    installations[0] = installation;

    placeHolder.getDescriptor().setInstallations(installations);

    StaplerRequest mockReq = mock(StaplerRequest.class);
    when(mockReq.bindJSON(any(Class.class), any(JSONObject.class))).thenReturn(placeHolder);

    JSONObject formJson = new JSONObject();
    formJson.put("templateMode", createTemplateModeJson(TemplateMode.TEXT, jsonText));
    PackerPublisher plugin = placeHolder.getDescriptor().newInstance(mockReq, formJson);

    assertEquals(PLUGIN_HOME, plugin.getPackerHome());
    assertEquals(localParams, plugin.getParams());

    assertTrue(plugin.isTextTemplate());
    assertFalse(plugin.isFileTemplate());
    assertFalse(plugin.isGlobalTemplate());
    assertEquals(jsonText, plugin.getJsonTemplateText());

    FreeStyleProject project = jenkins.createFreeStyleProject();
    FreeStyleBuild build = project.scheduleBuild2(0).get();

    Launcher launcherMock = mock(Launcher.class);
    TaskListener listenerMock = mock(TaskListener.class);

    String exec = plugin.getRemotePackerExec(build, launcherMock, listenerMock);

    assertEquals(PLUGIN_HOME + "/packer", exec);
}
 
Example #15
Source File: SQSTrigger.java    From aws-codecommit-trigger-plugin with 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 #16
Source File: RepositoryCloneProgressEndpoint.java    From blueocean-plugin with 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 #17
Source File: RepositoryCloneProgressEndpoint.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@GET
@WebMethod(name="")
public HttpResponse getProgress(StaplerRequest req) {
    String repositoryUrl = req.getOriginalRestOfPath();
    CloneProgressMonitor progress = CloneProgressMonitor.get(repositoryUrl);
    if (progress == null) {
        return null;
    }
    return HttpResponses.okJSON(ImmutableMap.of("progress", progress.getPercentComplete()));
}
 
Example #18
Source File: GlobalConfig.java    From sonar-quality-gates-plugin with 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 #19
Source File: OrganizationFolderTest.java    From blueocean-plugin with 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 #20
Source File: LambdaUploadPublisher.java    From aws-lambda-jenkins-plugin with 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 #21
Source File: ServiceException.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException {
    rsp.setStatus(status);
    rsp.setContentType("application/json");
    PrintWriter w = rsp.getWriter();
    w.write(toJson());
    w.close();
}
 
Example #22
Source File: GithubWebhookBuildTriggerPluginBuilder.java    From jenkins-github-webhook-build-trigger-plugin with MIT License 5 votes vote down vote up
@Override
public boolean configure(StaplerRequest req, JSONObject json) throws FormException {
    json = json.getJSONObject("config");
    webhookSecret = json.getString("webhookSecret");
    save();
    return true;
}
 
Example #23
Source File: DbBackedProject.java    From DotCi with 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 #24
Source File: GithubScmContentProviderTest.java    From blueocean-plugin with 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 #25
Source File: CodeBuilder.java    From aws-codebuild-jenkins-plugin with 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 #26
Source File: TemplateStaplerRequestWrapper.java    From multi-branch-project-plugin with MIT License 5 votes vote down vote up
/**
 * 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);
}
 
Example #27
Source File: PhabricatorBuildWrapperDescriptor.java    From phabricator-jenkins-plugin with MIT License 5 votes vote down vote up
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
    // To persist global configuration information,
    // set that to properties and call save().
    req.bindJSON(this, formData.getJSONObject("phabricator"));
    save();
    return super.configure(req, formData);
}
 
Example #28
Source File: GithubScmContentProviderTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
private StaplerRequest mockStapler(String scmId){
    mockStatic(Stapler.class);
    StaplerRequest staplerRequest = mock(StaplerRequest.class);
    when(Stapler.getCurrentRequest()).thenReturn(staplerRequest);
    when(staplerRequest.getRequestURI()).thenReturn("http://localhost:8080/jenkins/blue/rest/");
    when(staplerRequest.getParameter("path")).thenReturn("Jenkinsfile");
    when(staplerRequest.getParameter("repo")).thenReturn("PR-demo");

    // GithubScmContentProvider determines SCM using apiUrl but with wiremock
    // apiUrl is localhost and not github so we use this parameter from test only to tell scm id
    when(staplerRequest.getParameter("scmId")).thenReturn(scmId);
    when(staplerRequest.getParameter("apiUrl")).thenReturn(githubApiUrl);
    return staplerRequest;
}
 
Example #29
Source File: GitHubPollingLogAction.java    From github-integration-plugin with MIT License 5 votes vote down vote up
/**
 * TODO is it secure?
 */
public void doPollingLog(StaplerRequest req, StaplerResponse rsp) throws IOException {
    rsp.setContentType("text/plain;charset=UTF-8");
    // Prevent jelly from flushing stream so Content-Length header can be added afterwards
    FlushProofOutputStream out = new FlushProofOutputStream(rsp.getCompressedOutputStream(req));
    try {
        getPollingLogText().writeLogTo(0, out);
    } finally {
        closeQuietly(out);
    }
}
 
Example #30
Source File: RelativeLocation.java    From jenkins-build-monitor-plugin with MIT License 5 votes vote down vote up
public String name() {
    ItemGroup ig = null;

    StaplerRequest request = Stapler.getCurrentRequest();
    for( Ancestor a : request.getAncestors() ) {
        if(a.getObject() instanceof BuildMonitorView) {
            ig = ((View) a.getObject()).getOwnerItemGroup();
        }
    }

    return Functions.getRelativeDisplayNameFrom(job, ig);
}