Java Code Examples for org.kohsuke.stapler.StaplerResponse

The following are top voted examples for showing how to use org.kohsuke.stapler.StaplerResponse. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: no-agent-job-purge-plugin   File: PurgeNoAgentJobs.java   Source Code and License 6 votes vote down vote up
public void doEndOfflineAgentJobs(final StaplerRequest request, final StaplerResponse response) {

		Jenkins j;
		if ((j = Jenkins.getInstance()) != null) {
			Queue queue = j.getQueue();
			if (queue != null) {
				for (Item job : queue.getItems()) {
					if (job.getCauseOfBlockage() instanceof BecauseNodeIsOffline
							|| job.getCauseOfBlockage() instanceof BecauseLabelIsOffline) {
						queue.cancel(job);
					}
				}
			}
		}

		try {
			response.sendRedirect2(request.getRootPath());
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
 
Example 2
Project: embeddable-badges-plugin   File: PublicBadgeAction.java   Source Code and License 6 votes vote down vote up
/**
    * Serves the testCoverage badge image. TO DO
    * @param req
    * @param rsp
    * @param job
    * @return
    */
   @SuppressWarnings("rawtypes")
public HttpResponse doTestIcon(StaplerRequest req, StaplerResponse rsp, @QueryParameter String job) {
       Job<?, ?> project = getProject(job);
       Integer testPass = null;
       Integer testTotal = null;

       if (project.getLastCompletedBuild() != null) {
       	AbstractTestResultAction testAction =  project.getLastCompletedBuild().getAction(AbstractTestResultAction.class);
		if(testAction != null){
			int total = testAction.getTotalCount();
			int pass = total - testAction.getFailCount() - testAction.getSkipCount();
			
			testTotal = total;
			testPass = pass;
		}
       }
       return iconResolver.getTestResultImage(testPass, testTotal);
   }
 
Example 3
Project: embeddable-badges-plugin   File: PublicBadgeAction.java   Source Code and License 6 votes vote down vote up
/**
 * Serves the Build Description badge image.
 * @param req
 * @param rsp
 * @param job
 * @return
 */
public HttpResponse doBuildDescriptionIcon(StaplerRequest req, StaplerResponse rsp, @QueryParameter String job) {
    Job<?, ?> project = getProject(job);
    String buildDescription = null;
    
    /*if (project.getLastSuccessfulBuild() != null) {
        buildDescription = project.getLastSuccessfulBuild().getDescription();
    }*/
    
    /*if (project.getLastBuild() != null) {
        buildDescription = project.getLastBuild().getDescription();
    }*/
    
    if (project.getLastCompletedBuild() != null) {
        buildDescription = project.getLastCompletedBuild().getDescription();
    }
    
    return iconResolver.getBuildDescriptionImage(buildDescription);
}
 
Example 4
Project: embeddable-badges-plugin   File: StatusImage.java   Source Code and License 6 votes vote down vote up
/**
 * TO DO
 * @param req
 * @param rsp
 * @param node
 * @throws IOException
 * @throws ServletException
 */
@Override
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException {
    // Check if the latest badge is already cached
	String v = req.getHeader("If-None-Match");
    if (etag.equals(v)) {
        rsp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    rsp.setHeader("ETag", etag);
    rsp.setHeader("Expires", "Fri, 01 Jan 1984 00:00:00 GMT");
    rsp.setHeader("Cache-Control", "no-cache, private");
    rsp.setHeader("Content-Type", "image/svg+xml;charset=utf-8");
    rsp.setHeader("Content-Length", length);
    rsp.getOutputStream().write(payload);
}
 
Example 5
Project: plot-plugin   File: Plot.java   Source Code and License 6 votes vote down vote up
/**
 * Generates and writes the plotpipeline to the response output stream.
 *
 * @param req
 *            the incoming request
 * @param rsp
 *            the response stream
 * @throws IOException
 */
public void plotGraph(StaplerRequest req, StaplerResponse rsp)
        throws IOException {
    if ( ChartUtil.awtProblemCause != null) {
        // Not available. Send out error message.
        rsp.sendRedirect2(req.getContextPath() + "/images/headless.png");
        return;
    }
    setWidth(req);
    setHeight(req);
    setNumBuilds(req);
    setRightBuildNum(req);
    setHasLegend(req);
    setTitle(req);
    setStyle(req);
    setUseDescr(req);
    // need to force regenerate the plotpipeline in case build
    // descriptions (used for tool tips) have changed
    generatePlot(true);
    ChartUtil.generateGraph(req, rsp, plot, getWidth(), getHeight());
}
 
Example 6
Project: plot-plugin   File: Plot.java   Source Code and License 6 votes vote down vote up
/**
 * Generates and writes the plotpipeline's clickable map to the response output
 * stream.
 *
 * @param req
 *            the incoming request
 * @param rsp
 *            the response stream
 * @throws IOException
 */
public void plotGraphMap(StaplerRequest req, StaplerResponse rsp)
        throws IOException {
    if ( ChartUtil.awtProblemCause != null) {
        // not available. send out error message
        rsp.sendRedirect2(req.getContextPath() + "/images/headless.png");
        return;
    }
    setWidth(req);
    setHeight(req);
    setNumBuilds(req);
    setRightBuildNum(req);
    setHasLegend(req);
    setTitle(req);
    setStyle(req);
    setUseDescr(req);
    generatePlot(false);
    ChartRenderingInfo info = new ChartRenderingInfo();
    plot.createBufferedImage(getWidth(), getHeight(), info);
    rsp.setContentType("text/plain;charset=UTF-8");
    rsp.getWriter().println(
            ChartUtilities.getImageMap(getCsvFileName(), info));
}
 
Example 7
Project: gogs-webhook-plugin   File: GogsWebHookTest.java   Source Code and License 6 votes vote down vote up
@Test
public void whenEmptyHeaderTypeMustReturnError() throws Exception {
    //Prepare the SUT
    File uniqueFile = File.createTempFile("webHookTest_", ".txt", new File("target"));

    StaplerRequest staplerRequest = Mockito.mock(RequestImpl.class);
    StaplerResponse staplerResponse = Mockito.mock(ResponseImpl.class);

    //perform the test
    performDoIndexTest(staplerRequest, staplerResponse, uniqueFile);

    //validate that everything was done as planed
    verify(staplerResponse).setStatus(403);

    String expectedOutput = "Only push event can be accepted.";
    isExpectedOutput(uniqueFile, expectedOutput);

    log.info("Test succeeded.");
}
 
Example 8
Project: gogs-webhook-plugin   File: GogsWebHookTest.java   Source Code and License 6 votes vote down vote up
@Test
public void whenWrongHeaderTypeMustReturnError() throws Exception {
    //Prepare the SUT
    File uniqueFile = File.createTempFile("webHookTest_", ".txt", new File("target"));

    StaplerRequest staplerRequest = Mockito.mock(RequestImpl.class);
    StaplerResponse staplerResponse = Mockito.mock(ResponseImpl.class);
    when(staplerRequest.getHeader("X-Gogs-Event")).thenReturn("junk");

    //perform the testÎ
    performDoIndexTest(staplerRequest, staplerResponse, uniqueFile);

    //validate that everything was done as planed
    verify(staplerResponse).setStatus(403);

    String expectedOutput = "Only push event can be accepted.";
    isExpectedOutput(uniqueFile, expectedOutput);

    log.info("Test succeeded.");
}
 
Example 9
Project: gogs-webhook-plugin   File: GogsWebHookTest.java   Source Code and License 6 votes vote down vote up
@Test
public void whenQueryStringIsNullMustThrowException() throws Exception {
    //Prepare the SUT
    StaplerRequest staplerRequest = Mockito.mock(RequestImpl.class);
    StaplerResponse staplerResponse = Mockito.mock(ResponseImpl.class);
    when(staplerRequest.getHeader("X-Gogs-Event")).thenReturn("push");
    when(staplerRequest.getQueryString()).thenReturn(null);
    GogsWebHook gogsWebHook = new GogsWebHook();


    try {
        gogsWebHook.doIndex(staplerRequest, staplerResponse);
    } catch (NullPointerException e) {
        String expectedErrMsg = "The queryString in the request is null";
        assertEquals("Not the expected error message.", expectedErrMsg, e.getMessage());
        log.info("call failed as expected.");
        return;
    }
    fail("The call should have failed.");
}
 
Example 10
Project: gogs-webhook-plugin   File: GogsWebHookTest.java   Source Code and License 6 votes vote down vote up
@Test
public void whenNoJobInQueryStringMustReturnError() throws Exception {
    //Prepare the SUT
    File uniqueFile = File.createTempFile("webHookTest_", ".txt", new File("target"));

    StaplerRequest staplerRequest = Mockito.mock(RequestImpl.class);
    StaplerResponse staplerResponse = Mockito.mock(ResponseImpl.class);
    when(staplerRequest.getHeader("X-Gogs-Event")).thenReturn("push");
    when(staplerRequest.getQueryString()).thenReturn("foo=bar&blaah=blaah");

    //perform the testÎ
    performDoIndexTest(staplerRequest, staplerResponse, uniqueFile);

    //validate that everything was done as planed
    verify(staplerResponse).setStatus(404);

    String expectedOutput = "Parameter 'job' is missing.";
    isExpectedOutput(uniqueFile, expectedOutput);

    log.info("Test succeeded.");
}
 
Example 11
Project: gogs-webhook-plugin   File: GogsWebHookTest.java   Source Code and License 6 votes vote down vote up
@Test
public void whenEmptyJobInQueryStringMustReturnError() throws Exception {
    //Prepare the SUT
    File uniqueFile = File.createTempFile("webHookTest_", ".txt", new File("target"));

    StaplerRequest staplerRequest = Mockito.mock(RequestImpl.class);
    StaplerResponse staplerResponse = Mockito.mock(ResponseImpl.class);
    when(staplerRequest.getHeader("X-Gogs-Event")).thenReturn("push");
    when(staplerRequest.getQueryString()).thenReturn("job&foo=bar");

    //perform the testÎ
    performDoIndexTest(staplerRequest, staplerResponse, uniqueFile);

    //validate that everything was done as planed
    verify(staplerResponse).setStatus(404);

    String expectedOutput = "No value assigned to parameter 'job'";
    isExpectedOutput(uniqueFile, expectedOutput);

    log.info("Test succeeded.");
}
 
Example 12
Project: gogs-webhook-plugin   File: GogsWebHookTest.java   Source Code and License 6 votes vote down vote up
@Test
public void whenEmptyJob2InQueryStringMustReturnError() throws Exception {
    //Prepare the SUT
    File uniqueFile = File.createTempFile("webHookTest_", ".txt", new File("target"));

    StaplerRequest staplerRequest = Mockito.mock(RequestImpl.class);
    StaplerResponse staplerResponse = Mockito.mock(ResponseImpl.class);
    when(staplerRequest.getHeader("X-Gogs-Event")).thenReturn("push");
    when(staplerRequest.getQueryString()).thenReturn("job=&foo=bar");

    //perform the testÎ
    performDoIndexTest(staplerRequest, staplerResponse, uniqueFile);

    //validate that everything was done as planed
    verify(staplerResponse).setStatus(404);

    String expectedOutput = "No value assigned to parameter 'job'";
    isExpectedOutput(uniqueFile, expectedOutput);

    log.info("Test succeeded.");
}
 
Example 13
Project: gogs-webhook-plugin   File: GogsWebHookTest.java   Source Code and License 6 votes vote down vote up
@Test
public void whenUriDoesNotContainUrlNameMustReturnError() throws Exception {
    //Prepare the SUT
    File uniqueFile = File.createTempFile("webHookTest_", ".txt", new File("target"));

    StaplerRequest staplerRequest = Mockito.mock(RequestImpl.class);
    StaplerResponse staplerResponse = Mockito.mock(ResponseImpl.class);
    when(staplerRequest.getHeader("X-Gogs-Event")).thenReturn("push");
    when(staplerRequest.getQueryString()).thenReturn("job=myJob");


    MockServletInputStream inputStream = new MockServletInputStream("body");
    when(staplerRequest.getInputStream()).thenReturn(inputStream);
    when(staplerRequest.getRequestURI()).thenReturn("/badUri/aaa");

    //perform the testÎ
    performDoIndexTest(staplerRequest, staplerResponse, uniqueFile);

    //validate that everything was done as planed
    verify(staplerResponse).setStatus(404);

    String expectedOutput = "No payload or URI contains invalid entries.";
    isExpectedOutput(uniqueFile, expectedOutput);

    log.info("Test succeeded.");
}
 
Example 14
Project: donut-jenkins-plugin   File: DonutAction.java   Source Code and License 6 votes vote down vote up
public void doDynamic(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
    // Relax the Content Security Policy
    System.setProperty("hudson.model.DirectoryBrowserSupport.CSP", "");
    System.setProperty("jenkins.model.DirectoryBrowserSupport.CSP", "");

    DirectoryBrowserSupport dbs = new DirectoryBrowserSupport(this, new FilePath(this.dir()), this.getTitle(), getUrlName(), false);
    File report = new File(dir(), DONUT_REPORT_FILENAME);

    if (!report.exists()) {
        rsp.sendRedirect(Functions.getResourcePath() + "/plugin/donut-jenkins-plugin/error.html");
        return;
    }

    dbs.setIndexFileName(DONUT_REPORT_FILENAME);
    dbs.generateResponse(req, rsp, this);
}
 
Example 15
Project: github-pr-coverage-status   File: CoverageStatusIconAction.java   Source Code and License 6 votes vote down vote up
/**
 * Used by Jenkins Stapler service when get request on URL jenkins_host/getUrlName()
 *
 * @param request - request
 * @param response - response
 * @throws IOException
 */
@SuppressWarnings("unused")
public void doIndex(StaplerRequest request, StaplerResponse response) throws IOException {
    final float coverage = Float.parseFloat(request.getParameter("coverage"));
    final float masterCoverage = Float.parseFloat(request.getParameter("masterCoverage"));

    response.setContentType("image/svg+xml");

    String svg = IOUtils.toString(this.getClass().getResourceAsStream(
            "/com/github/terma/jenkins/githubprcoveragestatus/Icon/icon.svg"));

    final Message message = new Message(coverage, masterCoverage);
    svg = StringUtils.replace(svg, "{{ message }}", message.forIcon());

    final int coveragePercent = Percent.of(coverage);
    String color;
    if (coveragePercent < Configuration.getYellowThreshold()) color = "#b94947"; // red
    else if (coveragePercent < Configuration.getGreenThreshold()) color = "#F89406"; // yellow
    else color = "#97CA00"; // green
    svg = StringUtils.replace(svg, "{{ color }}", color);

    response.getWriter().write(svg);
}
 
Example 16
Project: CI-Jenkins-Plugin   File: GitHubTargetParameterAction.java   Source Code and License 6 votes vote down vote up
public void doParamsSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
    List<BuildTargetParameter> buildTargetParams;
    TargetParameterBuildAction paramAction;
    JSONObject jsonObject;
    TargetBuildParameterUtil buildParamUtil = new TargetBuildParameterUtil();
    jsonObject = req.getSubmittedForm();
    buildTargetParams = buildParamUtil.parse(jsonObject);
    if (buildTargetParams == null) {
        rsp.sendRedirect(400, "Invalid Parameters - All Fields must be filed");
        return;
    } else {
        paramAction = new TargetParameterBuildAction();
        paramAction.setBaseBranch(jsonObject.getString("baseBranch"));
        paramAction.setParameters(buildTargetParams);
        Hudson.getInstance().getQueue().schedule2(project, 0, paramAction, new CauseAction(new Cause.UserIdCause()));
    }
    rsp.sendRedirect("../");
}
 
Example 17
Project: cloudbees-disk-usage-simple-plugin   File: QuickDiskUsagePlugin.java   Source Code and License 6 votes vote down vote up
@RequirePOST
public void doClean(StaplerRequest req, StaplerResponse res) throws IOException, ServletException {
    // TODO switch to Jenkins.getActiveInstance() once 1.590+ is the baseline
    Jenkins jenkins = Jenkins.getInstance();
    if (jenkins == null) {
        throw new IllegalStateException("Jenkins has not been started, or was already shut down");
    }
    final Job job = jenkins.getItemByFullName(req.getParameter("job"), Job.class);
    Timer.get().submit(new Runnable() {
        @Override
        public void run() {
            try {
                job.logRotate();
            } catch (Exception e) {
                logger.log(Level.WARNING, "logRotate failed", e);
            }
        }
    });
    res.forwardToPreviousPage(req);
}
 
Example 18
Project: fabric8-jenkins-workflow-steps   File: AnnotatedLargeText.java   Source Code and License 6 votes vote down vote up
@Override
public long writeLogTo(long start, int size, Writer w) throws IOException {
    if (isHtml()) {
        ConsoleAnnotationOutputStream caw = new ConsoleAnnotationOutputStream(w, this.createAnnotator(Stapler.getCurrentRequest()), this.context, this.charset);
        long r = super.writeLogTo(start, size, caw);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Cipher sym = PASSING_ANNOTATOR.encrypt();
        ObjectOutputStream oos = new ObjectOutputStream(new GZIPOutputStream(new CipherOutputStream(baos, sym)));
        oos.writeLong(System.currentTimeMillis());
        oos.writeObject(caw.getConsoleAnnotator());
        oos.close();
        StaplerResponse rsp = Stapler.getCurrentResponse();
        if(rsp != null) {
            rsp.setHeader("X-ConsoleAnnotator", new String(Base64.encode(baos.toByteArray())));
        }
        return r;
    } else {
        return super.writeLogTo(start, size, w);
    }
}
 
Example 19
Project: docker-traceability-plugin   File: FingerprintTestUtil.java   Source Code and License 6 votes vote down vote up
/**
 * A stub method, which emulates the submission of the image reference 
 * from the web interface
 * @param req Incoming request
 * @param rsp Response
 * @param imageId image id
 * @param jobName job name, to which the facet should be attached
 * @throws IOException Request processing error
 * @throws ServletException Servlet error
 */
public static void doTestSubmitBuildRef(StaplerRequest req, StaplerResponse rsp,
        @QueryParameter(required = true) String imageId,
        @QueryParameter(required = true) String jobName) throws IOException, ServletException {
    final Jenkins j = Jenkins.getInstance();
    if (j == null) {
        throw new IOException("Jenkins instance is not active");
    }
    j.checkPermission(Jenkins.ADMINISTER);
    
    final AbstractProject item = j.getItem(jobName, j, AbstractProject.class);
    final Run latest = item != null ? item.getLastBuild() : null;
    if (latest == null) {
        throw new IOException("Cannot find a project or run to modify"); 
    }
    
    DockerFingerprints.addFromFacet(null,imageId, latest);
    rsp.sendRedirect2(j.getRootUrl());
}
 
Example 20
Project: aws-device-farm-jenkins-plugin   File: AWSDeviceFarmProjectAction.java   Source Code and License 6 votes vote down vote up
/**
 * Return trend graph of all AWS Device Farm results for this project.
 *
 * @param request  The request object.
 * @param response The response object.
 * @throws IOException
 */
@SuppressWarnings("unused")
public void doGraph(StaplerRequest request, StaplerResponse response) throws IOException {
    // Abort if having Java AWT issues.
    if (ChartUtil.awtProblemCause != null) {
        response.sendRedirect2(String.format("%s/images/headless.png", request.getContextPath()));
        return;
    }

    // Get previous AWS Device Farm build and results.
    AWSDeviceFarmTestResultAction prev = getLastBuildAction();
    if (prev == null) {
        return;
    }
    AWSDeviceFarmTestResult result = prev.getResult();
    if (result == null) {
        return;
    }

    // Create new graph for the AWS Device Farm results of all runs in this project.
    Graph graph = AWSDeviceFarmGraph.createResultTrendGraph(prev.getOwner(), false, result.getPreviousResults());
    graph.doPng(request, response);
}
 
Example 21
Project: aws-device-farm-jenkins-plugin   File: AWSDeviceFarmTestResult.java   Source Code and License 6 votes vote down vote up
/**
 * Create the graph image for the number of pass/warn/fail results in a test run, for the previous three Jenkins runs.
 *
 * @param request
 * @param response
 * @throws IOException
 */
@SuppressWarnings("unused")
public void doGraph(StaplerRequest request, StaplerResponse response) throws IOException {
    // Abort if having Java AWT issues.
    if (ChartUtil.awtProblemCause != null) {
        response.sendRedirect2(String.format("%s/images/headless.png", request.getContextPath()));
        return;
    }

    // Check the "If-Modified-Since" header and abort if we don't need re-create the graph.
    if (isCompleted()) {
        Calendar timestamp = getOwner().getTimestamp();
        if (request.checkIfModified(timestamp, response)) {
            return;
        }
    }

    // Create new graph for this AWS Device Farm result.
    Graph graph = AWSDeviceFarmGraph.createResultTrendGraph(build, isCompleted(), getPreviousResults(DefaultTrendGraphSize));
    graph.doPng(request, response);
}
 
Example 22
Project: aws-device-farm-jenkins-plugin   File: AWSDeviceFarmTestResult.java   Source Code and License 6 votes vote down vote up
/**
 * Create the graph image for the number of device minutes used in a test run, for the previous three Jenkins runs.
 *
 * @param request
 * @param response
 * @throws IOException
 */
@SuppressWarnings("unused")
public void doDurationGraph(StaplerRequest request, StaplerResponse response) throws IOException {
    // Abort if having Java AWT issues.
    if (ChartUtil.awtProblemCause != null) {
        response.sendRedirect2(String.format("%s/images/headless.png", request.getContextPath()));
        return;
    }

    // Check the "If-Modified-Since" header and abort if we don't need re-create the graph.
    if (isCompleted()) {
        Calendar timestamp = getOwner().getTimestamp();
        if (request.checkIfModified(timestamp, response)) {
            return;
        }
    }

    // Create new duration graph for this AWS Device Farm result.
    Graph graph = AWSDeviceFarmGraph.createDurationTrendGraph(build, isCompleted(), getPreviousResults(DefaultTrendGraphSize));
    graph.doPng(request, response);
}
 
Example 23
Project: jenkins-fossil-adapter   File: FossilTagAction.java   Source Code and License 6 votes vote down vote up
/**
 * handles the add request for multiple Fossil Tags
 * 
 * @param req the form request
 * @param rsp the form response
 * @throws IOException
 * @throws ServletException 
 */
public synchronized void doSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
    getACL().checkPermission(getPermission());

    MultipartFormDataParser parser = new MultipartFormDataParser(req);

    Map<FossilCheckinWithTags, String> newTags = new HashMap<FossilCheckinWithTags, String>();

    int i=-1;
    for (FossilCheckinWithTags e : this.revisions) {
        ++i;
        if (parser.get("tag" + i) != null && ! parser.get("name" + i).isEmpty()) {
            newTags.put(e, parser.get("name" + i));
        }
    }

    new TagWorkerThread(newTags, parser.get("force") != null).start();

    rsp.sendRedirect(".");
}
 
Example 24
Project: jenkins-fossil-adapter   File: FossilTagAction.java   Source Code and License 6 votes vote down vote up
/**
 * Handles the deletion request for a Fossil tag.
 * 
 * @param req the form request
 * @param rsp the form response
 * @throws IOException
 * @throws ServletException 
 */
public synchronized void doDelete(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
    getACL().checkPermission(getPermission());

    if (req.getParameter("tag") != null) {
        FossilCheckinWithTags revision = null;
        String tag = null;

        for (FossilCheckinWithTags e : this.revisions) {
            if (e.getRevId().equals(req.getParameter("revid"))) {
                revision = e;
                tag = req.getParameter("tag");
            }
        }

        new TagDeletionWorkerThread(revision, tag).start();
    }

    rsp.sendRedirect(".");
}
 
Example 25
Project: DotCi   File: DynamicBuild.java   Source Code and 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 26
Project: grapes-jenkins-plugin   File: AdministrateResendAction.java   Source Code and License 6 votes vote down vote up
/**
 *  Performs the notification on 'POST' action named "perform"
 *
 * @param req StaplerRequest
 * @param rsp StaplerResponse
 * @return HttpResponse
 */
public HttpResponse do_perform(final StaplerRequest req, final StaplerResponse rsp)  {
    // Only administrator can create a new site.
    Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);

    // TODO: display the progression

    for(ResendProjectAction resendProjectAction: resendActions){
        try {
            final NotificationHandler notifHandler = new NotificationHandler(resendProjectAction.getConfig());
            for(Map.Entry<AbstractBuild<?,?>, List<ResendBuildAction>> resendBuildAction: resendProjectAction.getResendActionPerBuild().entrySet()){
                notifHandler.send(resendBuildAction.getKey(), resendBuildAction.getValue());
            }

        } catch (Exception e ){
            GrapesPlugin.getLogger().log(Level.SEVERE, "[GRAPES] Failed to re-send notification: ", e);
        }
    }

    refresh();

    return HttpRedirect.DOT;
}
 
Example 27
Project: yaml-project-plugin   File: YamlProject.java   Source Code and License 6 votes vote down vote up
/** {@inheritDoc} */
@Override
protected void submit(StaplerRequest req, StaplerResponse rsp)
    throws IOException, ServletException, FormException {
  super.submit(req, rsp);

  final JSONObject json = req.getSubmittedForm();

  setYamlPath(json.optString("yamlPath"));

  if (json.containsKey("restriction")) {
    setRestriction(req.bindJSON(AbstractRestriction.class,
            json.getJSONObject("restriction")));
  } else {
    setRestriction(new NoRestriction());
  }
}
 
Example 28
Project: leroy_jenkins   File: ConfigurationProject.java   Source Code and License 6 votes vote down vote up
@Override
public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, Descriptor.FormException {

    super.doConfigSubmit(req, rsp);
    // set assigned node
    JSONObject json = req.getSubmittedForm();
    String jsonStr = json.toString();
    String leroyBuilderJson = JsonUtils.getLeroyConfigurationBuilderJSON(jsonStr);
    String leroyNode = JsonPath.read(leroyBuilderJson, "$.leroyNode");
    String assignedNodeName = leroyNode == null ? "" : leroyNode;
    Node n = LeroyUtils.findNodeByName(assignedNodeName);
    if (n != null) {
        setAssignedNode(n);
    }
    save();
}
 
Example 29
Project: p4-jenkins   File: P4Hook.java   Source Code and License 6 votes vote down vote up
public void doChangeSubmit(StaplerRequest req, StaplerResponse rsp)
		throws IOException, ServletException {

	JSONObject formData = req.getSubmittedForm();
	if (!formData.isEmpty()) {
		String port = req.getParameter("_.p4port");
		//String change = req.getParameter("_.change");
		List<Job> jobs = getJobs();

		LOGGER.info("Manual trigger event: ");
		if (port != null) {
			probeJobs(port, jobs);
		} else {
			LOGGER.warning("p4port must be specified");
		}

		// send the user back.
		rsp.sendRedirect("../");
	}
}
 
Example 30
Project: metrics-plugin   File: MetricsAccessKey.java   Source Code and License 6 votes vote down vote up
public HttpResponse cors(@CheckForNull String accessKey, final HttpResponse resp) {
    final MetricsAccessKey key = getAccessKey(accessKey);
    return key == null ? resp : new HttpResponse() {
        public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node)
                throws IOException, ServletException {
            String origin = req.getHeader("Origin");
            if (StringUtils.isNotBlank(origin) && key.isOriginAllowed(origin)) {
                rsp.addHeader("Access-Control-Allow-Origin", origin);
                rsp.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
                rsp.addHeader("Access-Control-Allow-Headers", "Accept, Authorization");
                if ("OPTIONS".equals(req.getMethod())) {
                    rsp.setStatus(200);
                    return;
                }
            }
            resp.generateResponse(req, rsp, node);
        }
    };
}
 
Example 31
Project: DotCi   File: GithubOauthLoginAction.java   Source Code and 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 32
Project: jenkins-status-badges-plugin   File: BuildStatus.java   Source Code and License 6 votes vote down vote up
public Job<?, ?> getProject( String job, StaplerRequest req, StaplerResponse rsp )
    throws HttpResponses.HttpResponseException
{
    Job<?, ?> p;

    SecurityContext orig = ACL.impersonate( ACL.SYSTEM );
    try
    {
        p = Jenkins.getInstance().getItemByFullName( job, Job.class );
    }
    finally
    {
        SecurityContextHolder.setContext( orig );
    }

    if ( p == null )
    {
        throw org.kohsuke.stapler.HttpResponses.notFound();
    }

    return p;
}
 
Example 33
Project: jenkins-status-badges-plugin   File: StatusImage.java   Source Code and License 6 votes vote down vote up
@Override
public void generateResponse( StaplerRequest req, StaplerResponse rsp, Object node )
    throws IOException, ServletException
{
    String v = req.getHeader( "If-None-Match" );
    if ( etag.equals( v ) )
    {
        rsp.setStatus( SC_NOT_MODIFIED );
        return;
    }

    rsp.setHeader( "ETag", etag );
    rsp.setHeader( "Expires", "Fri, 01 Jan 1984 00:00:00 GMT" );
    rsp.setHeader( "Cache-Control", "no-cache, private" );
    rsp.setHeader( "Content-Type", "image/svg+xml;charset=utf-8" );
    rsp.setHeader( "Content-Length", length );
    rsp.getOutputStream().write( payload.getBytes() );
}
 
Example 34
Project: codedx-plugin   File: CodeDxProjectAction.java   Source Code and License 6 votes vote down vote up
/**
 * Display the severity trend graph.
 *
 * @param request Stapler request
 * @param response Stapler response
 * @throws IOException in case of an error
 */
public void doSeverityTrend(final StaplerRequest request, final StaplerResponse response) throws IOException {
	AbstractBuild<?,?> lastBuild = this.getLastFinishedBuild();
	final CodeDxBuildAction lastAction = lastBuild.getAction(CodeDxBuildAction.class);

	final Map<String,Color> colorMap = new HashMap<String,Color>();

	colorMap.put(Filter.SEVERITY_CRITICAL, new Color(0x610a14));
	colorMap.put(Filter.SEVERITY_HIGH, new Color(0xbd0026));
	colorMap.put(Filter.SEVERITY_MEDIUM, new Color(0xfd8d3c));
	colorMap.put(Filter.SEVERITY_LOW, new Color(0xfed976));
	colorMap.put(Filter.SEVERITY_INFO, new Color(0x888888));
	colorMap.put(Filter.SEVERITY_UNSPECIFIED, new Color(0xadadad));

	(new Graph(-1L, CHART_WIDTH, CHART_HEIGHT){
		@Override
		protected JFreeChart createGraph() {
			return CodeDxChartBuilder.buildChart(lastAction, analysisResultConfiguration.getNumBuildsInGraph(),"severity",colorMap);
		}
	}).doPng(request, response);
}
 
Example 35
Project: Jenkins-Plugin-Examples   File: DropdownList.java   Source Code and License 5 votes vote down vote up
public void doSubmit(StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException {
    // '$class' in form data tells Stapler which Fruit subclass to use,
    // older versions of Jenkins/Stapler used 'stapler-class'
    Fruit fruit = req.bindJSON(Fruit.class, req.getSubmittedForm().getJSONObject("fruit"));
    rsp.setContentType("text/plain");
    new XStream2().toXML(fruit, rsp.getWriter());
}
 
Example 36
Project: Jenkins-Plugin-Examples   File: UISample.java   Source Code and License 5 votes vote down vote up
/**
 * Binds {@link SourceFile}s into URL.
 */
public void doSourceFile(StaplerRequest req, StaplerResponse rsp) throws IOException {
    String name = req.getRestOfPath().substring(1); // Remove leading /
    for (SourceFile sf : getSourceFiles())
        if (sf.name.equals(name)) {
            sf.doIndex(rsp);
            return;
        }
    rsp.sendError(rsp.SC_NOT_FOUND);
}
 
Example 37
Project: Jenkins-Plugin-Examples   File: NavigationContextMenu.java   Source Code and License 5 votes vote down vote up
/**
 * This method is called via AJAX to obtain the context menu for this model object.
 */
public ContextMenu doContextMenu(StaplerRequest request, StaplerResponse response) throws Exception {
    if (false) {
        // this implementation is suffice for most ModelObjects. It uses sidepanel.jelly/.groovy to
        // generate the context menu
        return new ContextMenu().from(this,request,response);
    } else {
        // otherwise you can also programatically create them.
        // see the javadoc for various convenience methods to add items
        return new ContextMenu()
                .add("http://jenkins-ci.org/","Jenkins project")
                .add("http://www.cloudbees.com/","CloudBees")
                .add(new MenuItem().withContextRelativeUrl("/").withStockIcon("gear.png").withDisplayName("top page"));
    }
}
 
Example 38
Project: Jenkins-Plugin-Examples   File: NavigationContextMenu.java   Source Code and License 5 votes vote down vote up
public ContextMenu doChildrenContextMenu(StaplerRequest request, StaplerResponse response) throws Exception {
    // You implement this method in much the same way you do doContextMenu
    return new ContextMenu()
            .add("http://yahoo.com/","Yahoo")
            .add("http://google.com/","Google")
            .add("http://microsoft.com/","Microsoft");
}
 
Example 39
Project: jenkins-keycloak-plugin   File: KeycloakSecurityRealm.java   Source Code and License 5 votes vote down vote up
@Override
public void doLogout(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
	final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	if (authentication instanceof KeycloakAuthentication) {
		KeycloakAuthentication keycloakAuthentication = (KeycloakAuthentication) authentication;
		try {
			ServerRequest.invokeLogout(getKeycloakDeployment(), keycloakAuthentication.getRefreashToken());
		} catch (HttpFailure e) {
			LOGGER.log(Level.SEVERE, "Logout Exception ", e);
		}
	}
	super.doLogout(req, rsp);
}
 
Example 40
Project: embeddable-badges-plugin   File: PublicBadgeAction.java   Source Code and License 5 votes vote down vote up
/**
 * Serves the codeCoverage badge image.
 *
 * @param req
 * @param rsp
 * @param job
 * @return
 */
public HttpResponse doCoverageIcon(StaplerRequest req, StaplerResponse rsp, @QueryParameter String job) {
    Job<?, ?> project = getProject(job);
    Integer codeCoverage = null;

    if (project.getLastSuccessfulBuild() != null) {
        PluginWrapper jacocoInstalled = getInstance().pluginManager.getPlugin("jacoco");
        // Checks for Jacoco
        if (jacocoInstalled != null && jacocoInstalled.isActive()) {
            JacocoBuildAction jacocoAction = project.getLastSuccessfulBuild().getAction(JacocoBuildAction.class);
            if (jacocoAction != null) {
                if (jacocoAction.getInstructionCoverage() != null){
                codeCoverage = jacocoAction.getInstructionCoverage().getPercentage();
                }
            }
        }
        PluginWrapper coberturaInstalled = getInstance().pluginManager.getPlugin("cobertura");
        // Checks for Cobertura
        if (coberturaInstalled != null && coberturaInstalled.isActive()) {
            CoberturaBuildAction coverageAction = project.getLastSuccessfulBuild().getAction(CoberturaBuildAction.class);
            if (coverageAction != null) {
                if (coverageAction.getBuildHealth() != null){
                    codeCoverage = coverageAction.getResults().get(CoverageMetric.LINE).getPercentage();
                }
            }
        }
        PluginWrapper cloverInstalled = getInstance().pluginManager.getPlugin("clover");
        // Checks for Clover
        if (cloverInstalled != null && cloverInstalled.isActive()) {
            CloverBuildAction cloverAction = project.getLastSuccessfulBuild().getAction(CloverBuildAction.class);
            if (cloverAction != null){
                if (cloverAction.getBuildHealth() != null){
                    codeCoverage = cloverAction.getElementCoverage().getPercentage();
                }
            }
        }
    }

    return iconResolver.getCoverageImage(codeCoverage);
}