public HttpResponse doProvision(@QueryParameter String template) throws ServletException, IOException { checkPermission(PROVISION); if (template == null) { throw HttpResponses.error(SC_BAD_REQUEST, "The 'template' query parameter is missing"); } SlaveTemplate t = getTemplate(template); if (t == null) { throw HttpResponses.error(SC_BAD_REQUEST, "No such template: " + template); } StringWriter sw = new StringWriter(); StreamTaskListener listener = new StreamTaskListener(sw); try { EC2AbstractSlave node = t.provision(listener); Hudson.getInstance().addNode(node); return HttpResponses.redirectViaContextPath("/computer/" + node.getNodeName()); } catch (AmazonClientException e) { throw HttpResponses.error(SC_INTERNAL_SERVER_ERROR, e); } }
@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())); } }
@Test public void testEvaluationWorksEvenThoughWeUsedEqualsInParameterValues() throws IOException { GroovyScript listScript = new GroovyScript(new SecureGroovyScript(SCRIPT_LIST, Boolean.FALSE, null), new SecureGroovyScript(FALLBACK_SCRIPT_LIST, Boolean.FALSE, null)); GroovyScript listSelectionScript = new GroovyScript( new SecureGroovyScript(SCRIPT_LIST_SELECTION, Boolean.FALSE, null), new SecureGroovyScript(FALLBACK_SCRIPT_LIST_SELECTION, Boolean.FALSE, null)); ChoiceParameter listParam = new ChoiceParameter("LIST", "description...", "random-name1", listScript, CascadeChoiceParameter.PARAMETER_TYPE_SINGLE_SELECT, true, 1); DynamicReferenceParameter listSelectionParam = new DynamicReferenceParameter("LIST_SELECTION", "description...", "random-name2", listSelectionScript, CascadeChoiceParameter.ELEMENT_TYPE_FORMATTED_HIDDEN_HTML, "LIST", true); // should be a String String listValue = listParam.getDefaultParameterValue().getValue().toString(); try { listSelectionParam.doUpdate(String.format(String.format("%s=%s", listParam.getName(), listValue))); } catch (HttpResponses.HttpResponseException response) { // ignore } // as this is a formatted hidden HTML... String listSelectionValue = listSelectionParam.getChoicesAsString(); // by default, the plug-in returns the first element in the list... assertEquals("Value returned from selection list doesn't match first element in list parameter", "A=1", listSelectionValue); }
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); }
private String extractListenerId(StaplerRequest req) { String path = req.getRestOfPath(); String id = getListenerId(path.substring(1)); if (id == null) { throw HttpResponses.notFound(); } return id; }
public HttpResponse doFinishLogin(StaplerRequest request) throws IOException { String code = request.getParameter("code"); if (StringUtils.isBlank(code)) { LOGGER.log(Level.SEVERE, "doFinishLogin() code = null"); return HttpResponses.redirectToContextRoot(); } DeepinToken token = new DeepinOAuthApiService(clientID, clientSecret).getTokenByAuthorizationCode(code); if (!token.accessToken.isEmpty()) { DeepinAuthenticationToken auth = new DeepinAuthenticationToken(token, clientID, clientSecret); SecurityContextHolder.getContext().setAuthentication(auth); User u = User.current(); u.setFullName(auth.getName()); } else { LOGGER.log(Level.SEVERE, "doFinishLogin() accessToken = null"); } // redirect to referer String referer = (String) request.getSession().getAttribute(REFERER_ATTRIBUTE); if (referer != null) { return HttpResponses.redirectTo(referer); } else { return HttpResponses.redirectToContextRoot(); } }
/** * 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 * "unknown" by default * @param hostId Optional host ID. * "unknown" 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(); }
/** * 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(); }
/** * 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(); }
/** * 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); }
public HttpResponse doBuildJob(@QueryParameter String issueId) { @SuppressWarnings("rawtypes") AbstractProject project = PayLoadInterceptorAction.getMatchingJob(issueId); if (project != null && project.isBuildable()) { project.scheduleBuild2(0); } return HttpResponses.plainText("Buld triggered: "+issueId); }
@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)); }
@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)); }
@Test public void build() throws IOException { try { FreeStyleProject testProject = jenkins.createFreeStyleProject(); testProject.addTrigger(trigger); exception.expect(HttpResponses.HttpResponseException.class); new MergeRequestBuildAction(testProject, getJson("MergeRequestEvent.json"), null).execute(response); } finally { ArgumentCaptor<MergeRequestHook> pushHookArgumentCaptor = ArgumentCaptor.forClass(MergeRequestHook.class); verify(trigger).onPost(pushHookArgumentCaptor.capture()); assertThat(pushHookArgumentCaptor.getValue().getProject(), is(notNullValue())); assertThat(pushHookArgumentCaptor.getValue().getProject().getWebUrl(), is(notNullValue())); } }
@Test public void skip_closedMR() throws IOException { FreeStyleProject testProject = jenkins.createFreeStyleProject(); testProject.addTrigger(trigger); exception.expect(HttpResponses.HttpResponseException.class); new MergeRequestBuildAction(testProject, getJson("MergeRequestEvent_closedMR.json"), null).execute(response); verify(trigger, never()).onPost(any(MergeRequestHook.class)); }
@Test public void skip_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 MergeRequestBuildAction(testProject, getJson("MergeRequestEvent_alreadyBuiltMR.json"), null).execute(response); verify(trigger, never()).onPost(any(MergeRequestHook.class)); }
@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)); }
@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)); }
@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)); }
/** * This is where the user comes back to at the end of the OpenID redirect * ping-pong. * * @throws HttpFailure * @throws VerificationException */ public HttpResponse doFinishLogin(StaplerRequest request) { String redirect = redirectUrl(request); try { AccessTokenResponse tokenResponse = ServerRequest.invokeAccessCodeToToken(getKeycloakDeployment(), request.getParameter("code"), redirect, null); String tokenString = tokenResponse.getToken(); String idTokenString = tokenResponse.getIdToken(); String refreashToken = tokenResponse.getRefreshToken(); AccessToken token = AdapterRSATokenVerifier.verifyToken(tokenString, getKeycloakDeployment()); if (idTokenString != null) { JWSInput input = new JWSInput(idTokenString); IDToken idToken = input.readJsonContent(IDToken.class); SecurityContextHolder.getContext() .setAuthentication(new KeycloakAuthentication(idToken, token, refreashToken)); User currentUser = User.current(); if (currentUser != null) { currentUser.setFullName(idToken.getPreferredUsername()); if (!currentUser.getProperty(Mailer.UserProperty.class).hasExplicitlyConfiguredAddress()) { currentUser.addProperty(new Mailer.UserProperty(idToken.getEmail())); } } } } catch (Exception e) { LOGGER.log(Level.SEVERE, "Authentication Exception ", e); } String referer = (String) request.getSession().getAttribute(REFERER_ATTRIBUTE); if (referer != null) { return HttpResponses.redirectTo(referer); } return HttpResponses.redirectToContextRoot(); }
/** * 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); }
@Override public HttpResponse doDoDelete() throws IOException { throw HttpResponses.forwardToView(this, "index"); }
@Override public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { throw HttpResponses.forwardToView(this, "index"); }
@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); }
@RequirePOST public HttpResponse doInstall(@QueryParameter PluginImpl.InstallMode installMode) throws Exception { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); PluginImpl.installPlugins(installMode); return HttpResponses.redirectToDot(); }