Java 类org.kohsuke.stapler.StaplerResponse 实例源码

项目:no-agent-job-purge-plugin    文件:PurgeNoAgentJobs.java   
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);
        }
    }
项目:embeddable-badges-plugin    文件:PublicBadgeAction.java   
/**
    * 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);
   }
项目:embeddable-badges-plugin    文件:PublicBadgeAction.java   
/**
 * 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);
}
项目:embeddable-badges-plugin    文件:StatusImage.java   
/**
 * 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);
}
项目:plot-plugin    文件:Plot.java   
/**
 * 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());
}
项目:plot-plugin    文件:Plot.java   
/**
 * 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));
}
项目:gogs-webhook-plugin    文件:GogsWebHookTest.java   
@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.");
}
项目:gogs-webhook-plugin    文件:GogsWebHookTest.java   
@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.");
}
项目:gogs-webhook-plugin    文件:GogsWebHookTest.java   
@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.");
}
项目:gogs-webhook-plugin    文件:GogsWebHookTest.java   
@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.");
}
项目:gogs-webhook-plugin    文件:GogsWebHookTest.java   
@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.");
}
项目:gogs-webhook-plugin    文件:GogsWebHookTest.java   
@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.");
}
项目:gogs-webhook-plugin    文件:GogsWebHookTest.java   
@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.");
}
项目:donut-jenkins-plugin    文件:DonutAction.java   
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);
}
项目:github-pr-coverage-status    文件:CoverageStatusIconAction.java   
/**
 * 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);
}
项目:CI-Jenkins-Plugin    文件:GitHubTargetParameterAction.java   
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("../");
}
项目:cloudbees-disk-usage-simple-plugin    文件:QuickDiskUsagePlugin.java   
@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);
}
项目:fabric8-jenkins-workflow-steps    文件:AnnotatedLargeText.java   
@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);
    }
}
项目:docker-traceability-plugin    文件:FingerprintTestUtil.java   
/**
 * 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());
}
项目:aws-device-farm-jenkins-plugin    文件:AWSDeviceFarmProjectAction.java   
/**
 * 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);
}
项目:aws-device-farm-jenkins-plugin    文件:AWSDeviceFarmTestResult.java   
/**
 * 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);
}
项目:aws-device-farm-jenkins-plugin    文件:AWSDeviceFarmTestResult.java   
/**
 * 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);
}
项目:jenkins-fossil-adapter    文件:FossilTagAction.java   
/**
 * 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(".");
}
项目:jenkins-fossil-adapter    文件:FossilTagAction.java   
/**
 * 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(".");
}
项目:DotCi    文件:DynamicBuild.java   
@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);
}
项目:grapes-jenkins-plugin    文件:AdministrateResendAction.java   
/**
 *  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;
}
项目:yaml-project-plugin    文件:YamlProject.java   
/** {@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());
  }
}
项目:leroy_jenkins    文件:ConfigurationProject.java   
@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();
}
项目:p4-jenkins    文件:P4Hook.java   
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("../");
    }
}
项目:metrics-plugin    文件:MetricsAccessKey.java   
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);
        }
    };
}
项目:DotCi    文件:GithubOauthLoginAction.java   
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);
    }
项目:jenkins-status-badges-plugin    文件:BuildStatus.java   
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;
}
项目:jenkins-status-badges-plugin    文件:StatusImage.java   
@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() );
}
项目:codedx-plugin    文件:CodeDxProjectAction.java   
/**
 * 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);
}
项目:Jenkins-Plugin-Examples    文件:DropdownList.java   
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());
}
项目:Jenkins-Plugin-Examples    文件:UISample.java   
/**
 * 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);
}
项目:Jenkins-Plugin-Examples    文件:NavigationContextMenu.java   
/**
 * 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"));
    }
}
项目:Jenkins-Plugin-Examples    文件:NavigationContextMenu.java   
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");
}
项目:jenkins-keycloak-plugin    文件:KeycloakSecurityRealm.java   
@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);
}
项目:embeddable-badges-plugin    文件:PublicBadgeAction.java   
/**
 * 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);
}