org.kohsuke.stapler.HttpResponses Java Examples

The following examples show how to use org.kohsuke.stapler.HttpResponses. 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: GithubOauthLoginAction.java    From DotCi with MIT License 6 votes vote down vote up
public HttpResponse doFinishLogin(StaplerRequest request, StaplerResponse rsp) throws IOException {

        String code = request.getParameter("code");

        if (code == null || code.trim().length() == 0) {
            Log.info("doFinishLogin: missing code.");
            return HttpResponses.redirectToContextRoot();
        }

        String content = postForAccessToken(code);

        String accessToken = extractToken(content);
        updateOfflineAccessTokenForUser(accessToken);
        request.getSession().setAttribute("access_token", accessToken);

        String newProjectSetupUrl = getJenkinsRootUrl() + "/" + GithubReposController.URL;
        return HttpResponses.redirectTo(newProjectSetupUrl);
    }
 
Example #2
Source File: PushBuildActionTest.java    From gitlab-plugin with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void build() throws IOException {
    try {
        FreeStyleProject testProject = jenkins.createFreeStyleProject();
        when(trigger.getTriggerOpenMergeRequestOnPush()).thenReturn(TriggerOpenMergeRequest.never);
        testProject.addTrigger(trigger);

        exception.expect(HttpResponses.HttpResponseException.class);
        new PushBuildAction(testProject, getJson("PushEvent.json"), null).execute(response);
    } finally {
        ArgumentCaptor<PushHook> pushHookArgumentCaptor = ArgumentCaptor.forClass(PushHook.class);
        verify(trigger).onPost(pushHookArgumentCaptor.capture());
        assertThat(pushHookArgumentCaptor.getValue().getProject(), is(notNullValue()));
        assertThat(pushHookArgumentCaptor.getValue().getProject().getWebUrl(), is(notNullValue()));
        assertThat(pushHookArgumentCaptor.getValue().getUserUsername(), is(notNullValue()));
        assertThat(pushHookArgumentCaptor.getValue().getUserUsername(), containsString("jsmith"));
    }
}
 
Example #3
Source File: MergeRequestBuildActionTest.java    From gitlab-plugin with GNU General Public License v2.0 6 votes vote down vote up
private void executeMergeRequestAction(FreeStyleProject testProject, String json) throws IOException {
    try {
        wouldFire = false;

        trigger.start(testProject, false);

        new MergeRequestBuildAction(testProject, json, null)
            .execute(response);
    } catch (HttpResponses.HttpResponseException hre) {
        // Test for OK status of a response.
        try {
            hre.generateResponse(null, response, null);
            verify(response, atLeastOnce()).setStatus(200);
        } catch (ServletException e) {
            throw new IOException(e);
        }
    }
    // The assumption is, that queue listener have already been invoked when we got back a response.
}
 
Example #4
Source File: NoteBuildActionTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void build_alreadyBuiltMR_alreadyBuiltMR() throws IOException, ExecutionException, InterruptedException {
    FreeStyleProject testProject = jenkins.createFreeStyleProject();
    testProject.addTrigger(trigger);
    testProject.setScm(new GitSCM(gitRepoUrl));
    QueueTaskFuture<?> future = testProject.scheduleBuild2(0, new ParametersAction(new StringParameterValue("gitlabTargetBranch", "master")));
    future.get();

    exception.expect(HttpResponses.HttpResponseException.class);
    new NoteBuildAction(testProject, getJson("NoteEvent_alreadyBuiltMR.json"), null).execute(response);

    verify(trigger).onPost(any(NoteHook.class));
}
 
Example #5
Source File: PushBuildActionTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void invalidToken() throws IOException {
    FreeStyleProject testProject = jenkins.createFreeStyleProject();
    when(trigger.getTriggerOpenMergeRequestOnPush()).thenReturn(TriggerOpenMergeRequest.never);
    when(trigger.getSecretToken()).thenReturn("secret");
    testProject.addTrigger(trigger);

    exception.expect(HttpResponses.HttpResponseException.class);
    new PushBuildAction(testProject, getJson("PushEvent.json"), "wrong-secret").execute(response);

    verify(trigger, never()).onPost(any(PushHook.class));
}
 
Example #6
Source File: PipelineBuildActionTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void doNotBuildOnFailure() throws IOException {
    exception.expect(HttpResponses.HttpResponseException.class);
    new PipelineBuildAction(testProject, getJson("PipelineFailureEvent.json"), null).execute(response);

    verify(trigger, never()).onPost(any(PipelineHook.class));
}
 
Example #7
Source File: PipelineBuildActionTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void buildOnSuccess () throws IOException {
    exception.expect(HttpResponses.HttpResponseException.class);
    new PipelineBuildAction(testProject, getJson("PipelineEvent.json"), null).execute(response);

    verify(trigger).onPost(any(PipelineHook.class));
}
 
Example #8
Source File: NoteBuildActionTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void build_alreadyBuiltMR_differentTargetBranch() throws IOException, ExecutionException, InterruptedException {
    FreeStyleProject testProject = jenkins.createFreeStyleProject();
    testProject.addTrigger(trigger);
    testProject.setScm(new GitSCM(gitRepoUrl));
    QueueTaskFuture<?> future = testProject.scheduleBuild2(0, new GitLabWebHookCause(causeData()
            .withActionType(CauseData.ActionType.NOTE)
            .withSourceProjectId(1)
            .withTargetProjectId(1)
            .withBranch("feature")
            .withSourceBranch("feature")
            .withUserName("")
            .withSourceRepoHomepage("https://gitlab.org/test")
            .withSourceRepoName("test")
            .withSourceNamespace("test-namespace")
            .withSourceRepoUrl("[email protected]:test.git")
            .withSourceRepoSshUrl("[email protected]:test.git")
            .withSourceRepoHttpUrl("https://gitlab.org/test.git")
            .withMergeRequestTitle("Test")
            .withMergeRequestId(1)
            .withMergeRequestIid(1)
            .withTargetBranch("master")
            .withTargetRepoName("test")
            .withTargetNamespace("test-namespace")
            .withTargetRepoSshUrl("[email protected]:test.git")
            .withTargetRepoHttpUrl("https://gitlab.org/test.git")
            .withTriggeredByUser("test")
            .withLastCommit("123")
            .withTargetProjectUrl("https://gitlab.org/test")
            .build()));
    future.get();

    exception.expect(HttpResponses.HttpResponseException.class);
    new NoteBuildAction(testProject, getJson("NoteEvent_alreadyBuiltMR.json"), null).execute(response);

    verify(trigger).onPost(any(NoteHook.class));
}
 
Example #9
Source File: GitLabSCMWebHook.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 5 votes vote down vote up
private String extractListenerId(StaplerRequest req) {
    String path = req.getRestOfPath();
    String id = getListenerId(path.substring(1));
    if (id == null) {
        throw HttpResponses.notFound();
    }

    return id;
}
 
Example #10
Source File: NoteBuildActionTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void build() throws IOException {
    FreeStyleProject testProject = jenkins.createFreeStyleProject();
    testProject.addTrigger(trigger);

    exception.expect(HttpResponses.HttpResponseException.class);
    new NoteBuildAction(testProject, getJson("NoteEvent.json"), null).execute(response);

    verify(trigger).onPost(any(NoteHook.class));
}
 
Example #11
Source File: DockerTraceabilityRootAction.java    From docker-traceability-plugin with MIT License 5 votes vote down vote up
/**
 * Retrieves the latest raw status via API.
 * The output will be retrieved in JSON.
 * @param id ID of the image, for which the info should be retrieved.
 *    Short container IDs are not supported.
 * @throws IOException Processing error
 * @throws ServletException Servlet error
 * @return {@link HttpResponse}
 */
public HttpResponse doRawImageInfo(@QueryParameter(required = true) String id) 
        throws IOException, ServletException {     
    checkPermission(DockerTraceabilityPlugin.READ_DETAILS);
    
    final InspectImageResponse report = DockerTraceabilityHelper.getLastInspectImageResponse(id);
    if (report == null) {   
        return HttpResponses.error(404, "No info available for the imageId=" + id);
    }
    
    // Return raw JSON in the response
    InspectImageResponse[] out = {report};
    return toJSONResponse(out);
}
 
Example #12
Source File: DockerTraceabilityRootAction.java    From docker-traceability-plugin with MIT License 5 votes vote down vote up
/**
 * Removes the container reference from the registry.
 * @param id Container ID. Method supports full 64-char IDs only.
 * @throws IOException Cannot save the updated {@link DockerTraceabilityRootAction}
 * @throws ServletException Servlet exception
 * @return response
 */
@RequirePOST
public HttpResponse doDeleteContainer(@QueryParameter(required = true) String id) 
        throws IOException, ServletException {  
    checkPermission(DockerTraceabilityPlugin.DELETE);
    removeContainerID(id);
    return HttpResponses.ok();
}
 
Example #13
Source File: DockerTraceabilityRootAction.java    From docker-traceability-plugin with MIT License 5 votes vote down vote up
/**
 * Submits a new {@link DockerTraceabilityReport} via API.
 * @param json String representation of {@link DockerTraceabilityReport}
 * @return {@link HttpResponse}
 * @throws ServletException Servlet error
 * @throws IOException Processing error
 */
@RequirePOST
public HttpResponse doSubmitReport(@QueryParameter(required = true) String json) 
        throws IOException, ServletException { 
    checkPermission(DockerTraceabilityPlugin.SUBMIT);
    ObjectMapper mapper = new ObjectMapper();
    final DockerTraceabilityReport report = mapper.readValue(json, DockerTraceabilityReport.class);
    DockerTraceabilityReportListener.fire(report);
    return HttpResponses.ok();
}
 
Example #14
Source File: DockerTraceabilityRootAction.java    From docker-traceability-plugin with MIT License 5 votes vote down vote up
/**
 * Submits a new event through Jenkins API.
 * @param inspectData JSON output of docker inspect container (array of container infos)
 * @param hostName Optional name of the host, which submitted the event
 *      &quot;unknown&quot; by default
 * @param hostId Optional host ID. 
 *      &quot;unknown&quot; by default
 * @param status Optional status of the container. 
 *      By default, an artificial {@link DockerEventType#NONE} will be used.    
 * @param time Optional time when the event happened. 
 *      The time is specified in seconds since January 1, 1970, 00:00:00 GMT
 *      Default value - current time
 * @param environment Optional field, which describes the environment
 * @param imageName Optional field, which provides the name of the image
 * @return {@link HttpResponse}
 * @throws IOException Request processing error
 * @throws ServletException Servlet error
 */
//TODO: parameters check
@RequirePOST
public HttpResponse doSubmitContainerStatus(
        @QueryParameter(required = true) String inspectData,
        @QueryParameter(required = false) String hostId,
        @QueryParameter(required = false) String hostName,
        @QueryParameter(required = false) String status,
        @QueryParameter(required = false) long time,
        @QueryParameter(required = false) @CheckForNull String environment,
        @QueryParameter(required = false) @CheckForNull String imageName
) throws IOException, ServletException { 
    checkPermission(DockerTraceabilityPlugin.SUBMIT);
    final ObjectMapper mapper = new ObjectMapper();
    final InspectContainerResponse[] inspectContainerResponses = mapper.readValue(inspectData, InspectContainerResponse[].class);
    final long eventTime = time != 0 ? time : System.currentTimeMillis()/1000;
    final String effectiveHostName = StringUtils.isNotBlank(hostName) ? hostName : "unknown";
    final String effectiveHostId = StringUtils.isNotBlank(hostId) ? hostId : "unknown";
    final String effectiveStatus = StringUtils.isNotBlank(status) 
            ? status.toUpperCase(Locale.ENGLISH) : DockerEventType.NONE.toString();
    final String effectiveImageName = hudson.Util.fixEmpty(imageName);
    final String effectiveEnvironment = hudson.Util.fixEmpty(environment);
    
    
    for (InspectContainerResponse inspectContainerResponse : inspectContainerResponses) {
        final Event event = new DockerEvent(effectiveStatus, inspectContainerResponse.getImageId(), 
                effectiveHostId, eventTime).toDockerEvent();
        final Info hostInfo = new DockerInfo(effectiveHostId, effectiveHostName).toInfo();

        DockerTraceabilityReport res = new DockerTraceabilityReport(event, hostInfo,
                inspectContainerResponse, 
                inspectContainerResponse.getImageId(), effectiveImageName,
                /* InspectImageResponse */ null, new LinkedList<String>(), effectiveEnvironment);
        DockerTraceabilityReportListener.fire(res);
    }
    return HttpResponses.ok();
}
 
Example #15
Source File: DockerTraceabilityRootAction.java    From docker-traceability-plugin with MIT License 4 votes vote down vote up
/**
 * Queries container statuses via API.
 * The output will be retrieved in JSON. Supports filters.
 * @param id ID of the container, for which the info should be retrieved.
 *    Short container IDs are not supported.
 * @param mode {@link QueryMode}. Default value - {@link QueryMode#inspectContainer}
 * @param since Optional starting time. 
 *      If the value equals to 0, the filter will be ignored (default in {@link QueryParameter}).
 * @param until End time. 
 *      If the value equals to 0, the filter will be ignored (default in {@link QueryParameter}).
 * @throws IOException Processing error
 * @throws ServletException Servlet error
 * @return Response containing the output JSON. may be an error if something breaks.
 */
public HttpResponse doQueryContainer( 
        @QueryParameter(required = true) String id,
        @QueryParameter(required = false) String mode,
        @QueryParameter(required = false) long since,
        @QueryParameter(required = false) long until) 
        throws IOException, ServletException {     
    checkPermission(DockerTraceabilityPlugin.READ_DETAILS);
    
    final QueryMode queryMode = QueryMode.fromString(mode);
    final long maxTime = (until != 0) ? until : Long.MAX_VALUE;
    final long minTime = (since != 0) ? since : Long.MIN_VALUE;
    
    DockerDeploymentFacet facet = DockerDeploymentFacet.getDeploymentFacet(id);
    if (facet == null) {
        return HttpResponses.error(404, "No info available for the containerId=" + id);
    }
    
    final SortedSet<DockerContainerRecord> deploymentRecords = facet.getDeploymentRecords();
    List<Object> result = new ArrayList<Object>(deploymentRecords.size());
    for (DockerContainerRecord record : deploymentRecords) {
        // time filters
        final long eventTime = record.getReport().getEvent().getTime();
        if (eventTime < minTime || eventTime > maxTime) {
            continue;
        }
        
        // Report data
        final DockerTraceabilityReport report = record.getReport();
        switch (queryMode) {
            case all:
                result.add(report);
                break;
            case events:
                result.add(report.getEvent());
                break;
            case inspectContainer:
                InspectContainerResponse containerResponse = report.getContainer();
                if (containerResponse != null) {
                    result.add(containerResponse);
                }
                break;
            case inspectImage:
                InspectImageResponse imageResponse = report.getImage();
                if (imageResponse != null) {
                    result.add(imageResponse);
                }
                break;   
            case hostInfo:
                result.add(report.getHostInfo());
                break;    
            default:
                throw new IllegalStateException("Unsupported query mode: "+queryMode);
        }
    }
    
    // Return raw JSON in the response
    return toJSONResponse(result);
}
 
Example #16
Source File: BranchHistoryWidget.java    From DotCi with MIT License 4 votes vote down vote up
@Override
public void doAjax(final StaplerRequest req, final StaplerResponse rsp, @Header("n") final String n) throws IOException, ServletException {

    if (n == null) {
        throw HttpResponses.error(SC_BAD_REQUEST, new IllegalArgumentException("Missing the 'n' HTTP header"));
    }

    rsp.setContentType("text/html;charset=UTF-8");

    final List<T> items = new LinkedList<>();

    String nn = null;

    // TODO refactor getBuildsAfter and database query to be getBuildsAfterAndEqual
    final Iterable<T> builds = this.model.getBuildsAfter(Integer.parseInt(n) - 1);
    for (final T t : builds) {
        if (this.adapter.compare(t, n) >= 0) {
            items.add(t);
            if (this.adapter.isBuilding(t)) {
                nn = this.adapter.getKey(t);
            }
        } else {
            break;
        }
    }

    if (nn == null) {
        if (items.isEmpty()) {
            nn = n;
        } else {
            nn = this.adapter.getNextKey(this.adapter.getKey(items.get(0)));
        }
    }

    this.baseList = items;
    GReflectionUtils.setField(HistoryWidget.class, "firstTransientBuildKey", this, nn);

    rsp.setHeader("n", nn);

    req.getView(this, "ajaxBuildHistory.jelly").forward(req, rsp);
}
 
Example #17
Source File: GitLabSecurityRealm.java    From gitlab-oauth-plugin with MIT License 4 votes vote down vote up
/**
 * This is where the user comes back to at the end of the OpenID redirect
 * ping-pong.
 */
public HttpResponse doFinishLogin(StaplerRequest request) throws IOException {
    String code = request.getParameter("code");

    if (StringUtils.isBlank(code)) {
        Log.info("doFinishLogin: missing code or private_token.");
        return HttpResponses.redirectToContextRoot();
    }

    String state = request.getParameter("state");

    HttpPost httpPost = new HttpPost(gitlabWebUri + "/oauth/token");
    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    parameters.add(new BasicNameValuePair("client_id", clientID));
    parameters.add(new BasicNameValuePair("client_secret", clientSecret));
    parameters.add(new BasicNameValuePair("code", code));
    parameters.add(new BasicNameValuePair("grant_type", "authorization_code"));
    parameters.add(new BasicNameValuePair("redirect_uri", buildRedirectUrl(request, state)));
    httpPost.setEntity(new UrlEncodedFormEntity(parameters, StandardCharsets.UTF_8));

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpHost proxy = getProxy(httpPost);
    if (proxy != null) {
        RequestConfig config = RequestConfig.custom()
                .setProxy(proxy)
                .build();
        httpPost.setConfig(config);
    }

    org.apache.http.HttpResponse response = httpclient.execute(httpPost);

    HttpEntity entity = response.getEntity();

    String content = EntityUtils.toString(entity);

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.close();

    String accessToken = extractToken(content);

    if (StringUtils.isNotBlank(accessToken)) {
        // only set the access token if it exists.
        GitLabAuthenticationToken auth = new GitLabAuthenticationToken(accessToken, getGitlabApiUri(), TokenType.ACCESS_TOKEN);

        HttpSession session = request.getSession(false);
        if (session != null) {
            // avoid session fixation
            session.invalidate();
        }
        request.getSession(true);

        SecurityContextHolder.getContext().setAuthentication(auth);

        GitlabUser self = auth.getMyself();
        User user = User.current();
        if (user != null) {
            user.setFullName(self.getName());
            // Set email from gitlab only if empty
            if (!user.getProperty(Mailer.UserProperty.class).hasExplicitlyConfiguredAddress()) {
                user.addProperty(new Mailer.UserProperty(auth.getMyself().getEmail()));
            }
        }
        SecurityListener.fireAuthenticated(new GitLabOAuthUserDetails(self, auth.getAuthorities()));
    } else {
        Log.info("Gitlab did not return an access token.");
    }

    if (StringUtils.isNotBlank(state)) {
        return HttpResponses.redirectTo(state);
    }
    return HttpResponses.redirectToContextRoot();
}