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

项目:Jenkins-Ranorex-Plugin    文件:RanorexRunnerBuilder.java   
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException
{
    useSummarize = formData.getBoolean("useSummarize");
    save();
    return super.configure(req, formData); //To change body of generated methods, choose Tools | Templates.
}
项目:microcks-jenkins-plugin    文件:TimedBuildStepDescriptor.java   
@Override
public synchronized boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
   wait = formData.getString("wait");
   waitUnit = ITimedMicrocksPlugin.TimeoutUnit.normalize(formData.getString("waitUnit"));
   if (wait == null || wait.isEmpty()) {
      // If someone clears the value, go back to default and use seconds
      wait = "" + getStaticDefaultWaitTime() / ITimedMicrocksPlugin.TimeoutUnit.SECONDS.multiplier;
      waitUnit = ITimedMicrocksPlugin.TimeoutUnit.SECONDS.name;
   }
   wait = wait.trim();
   save();
   return true;
}
项目:gitea-plugin    文件:GiteaWebhookAction.java   
public HttpResponse doPost(StaplerRequest request) throws IOException {
    if (!request.getMethod().equals("POST")) {
        return HttpResponses
                .error(HttpServletResponse.SC_BAD_REQUEST,
                        "Only POST requests are supported, this was a " + request.getMethod() + " request");
    }
    if (!"application/json".equals(request.getContentType())) {
        return HttpResponses
                .error(HttpServletResponse.SC_BAD_REQUEST,
                        "Only application/json content is supported, this was " + request.getContentType());
    }
    String type = request.getHeader("X-Gitea-Event");
    if (StringUtils.isBlank(type)) {
        return HttpResponses.error(HttpServletResponse.SC_BAD_REQUEST,
                "Expecting a Gitea event, missing expected X-Gitea-Event header");
    }
    String origin = SCMEvent.originOf(request);
    boolean processed = false;
    for (GiteaWebhookHandler<?, ?> h : ExtensionList.lookup(GiteaWebhookHandler.class)) {
        if (h.matches(type)) {
            h.process(request.getInputStream(), origin);
            processed = true;
        }
    }
    return HttpResponses.plainText(processed ? "Processed" : "Ignored");
}
项目:jenkins-client-plugin    文件:ResourceSelector.java   
@Override
public ResourceSelector newInstance(StaplerRequest req,
        JSONObject formData) throws FormException {
    ResourceSelector s = super.newInstance(req, formData);

    String selectionType = formData.getString("selectionType");
    System.out.println("parms2: " + selectionType);

    if (SELECT_BY_KIND.equals(selectionType)) {
        s.names = null;
    }
    if (SELECT_BY_NAMES.equals(selectionType)) {
        s.kind = null;
        s.labels = null;
    }
    return s;
}
项目:cppchecker    文件:Cppchecker.java   
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
    // To persist global configuration information,
    // set that to properties and call save().
    useDefault = formData.getBoolean("useDefault");
    exePath = formData.getString("exePath");
    // ^Can also use req.bindJSON(this, formData);
    //  (easier when there are many fields; need set* methods for this, like setUseDefault)
    save();
    return super.configure(req, formData);
}
项目:aws-batch    文件:AwsBatchBuilder.java   
@Override
public boolean configure(StaplerRequest staplerRequest, JSONObject json) throws FormException {
    // to persist global configuration information,
    // set that to properties and call save().
    //System.out.println(json.toString());
    if(json.containsKey("logPollingFreq")) {
        logPollingFreq = json.getInt("logPollingFreq");
    }
    else {
        logPollingFreq = 15;
    }
    save();
    return true; // indicate that everything is good so far
}
项目:Jenkins-Plugin-Examples    文件:EnvStep.java   
@Override public Step newInstance(StaplerRequest req, JSONObject formData) throws FormException {
    String overridesS = formData.getString("overrides");
    List<String> overrides = new ArrayList<>();
    for (String line : overridesS.split("\r?\n")) {
        line = line.trim();
        if (!line.isEmpty()) {
            overrides.add(line);
        }
    }
    return new EnvStep(overrides);
}
项目: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);
        }
    }
项目:aws-codecommit-trigger-plugin    文件:SQSTrigger.java   
@Override
public Trigger newInstance(StaplerRequest req, @Nonnull JSONObject jsonObject) throws FormException {
    if (jsonObject.has("subscribeInternalScm")) {
        jsonObject.put("subscribeInternalScm", Boolean.TRUE);
    }
    return super.newInstance(req, jsonObject);
}
项目:aws-codecommit-trigger-plugin    文件:SQSTrigger.java   
@Override
public boolean configure(final StaplerRequest req, final JSONObject json) throws FormException {
    Object sqsQueues = json.get("sqsQueues");
    if (json.size() == 1) {
        String key = json.keys().next().toString();
        sqsQueues = json.getJSONObject(key).get("sqsQueues");
    }
    this.sqsQueues = req.bindJSONToList(SQSTriggerQueue.class, sqsQueues);
    this.initQueueMap();

    this.save();

    EventBroker.getInstance().post(new ConfigurationChangedEvent());
    return true;
}
项目:aws-codecommit-trigger-plugin    文件:SQSScmConfig.java   
@Override
public SQSScmConfig newInstance(StaplerRequest req, @Nonnull JSONObject jsonObject) throws FormException {
    JSONObject json = jsonObject.getJSONObject("type");
    json.put("type", json.getString("value"));
    json.remove("value");
    return super.newInstance(req, json);//req.bindJSON(SQSScmConfig.class, json);
}
项目:jenkins-keycloak-plugin    文件:KeycloakSecurityRealm.java   
@Override
public boolean configure(StaplerRequest req, JSONObject json) throws hudson.model.Descriptor.FormException {
    json = json.getJSONObject("keycloak");
    keycloakJson = json.getString("keycloakJson");
    save();
    return true;
}
项目:jenkins-github-webhook-build-trigger-plugin    文件:GithubWebhookBuildTriggerPluginBuilder.java   
@Override
public boolean configure(StaplerRequest req, JSONObject json) throws FormException {
    json = json.getJSONObject("config");
    webhookSecret = json.getString("webhookSecret");
    save();
    return true;
}
项目: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));
}
项目:plot-plugin    文件:SeriesFactory.java   
/**
 * Using file and label and the Stapler request, create a subclass of series
 * that can process the type selected.
 * 
 * @param formData
 *            JSON data for series
 */
public static Series createSeries(JSONObject formData, StaplerRequest req) {
    String file = formData.getString("file");
    formData = formData.getJSONObject("fileType");
    formData.put("file", file);
    String type = formData.getString("value");
    Class<? extends Series> typeClass = null;

    if ("properties".equals(type))
        typeClass = PropertiesSeries.class;
    else if ("csv".equals(type))
        typeClass = CSVSeries.class;
    else if ("xml".equals(type))
        typeClass = XMLSeries.class;

    return typeClass != null ? req.bindJSON(typeClass, formData) : null;
}
项目:impersonation-plugin    文件:ImpersonationAction.java   
@RequirePOST
public HttpResponse doImpersonate(StaplerRequest req, @QueryParameter String name) {
    Authentication auth = Jenkins.getAuthentication();
    GrantedAuthority[] authorities = auth.getAuthorities();
    if (authorities == null || StringUtils.isBlank(name)) {
        return HttpResponses.redirectToContextRoot();
    }
    GrantedAuthority authority = null;
    for (GrantedAuthority a : authorities) {
        if (a.getAuthority().equals(name)) {
            authority = a;
            break;
        }
    }
    if (authority == null) {
        return HttpResponses.redirectToContextRoot();
    }
    if (!SecurityRealm.AUTHENTICATED_AUTHORITY.equals(authority)) {
        ACL.impersonate(new ImpersonationAuthentication(auth, authority, SecurityRealm.AUTHENTICATED_AUTHORITY));
    } else {
        ACL.impersonate(new ImpersonationAuthentication(auth, SecurityRealm.AUTHENTICATED_AUTHORITY));
    }
    return HttpResponses.redirectToContextRoot();
}
项目: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);
}
项目:jenkins-telegram-plugin    文件:TelegramNotifier.java   
@Override
public TelegramNotifier newInstance(StaplerRequest sr, JSONObject json) {
    String token = sr.getParameter("telegramToken");
    String chatId = sr.getParameter("telegramChatId");
    boolean startNotification = "true".equals(sr.getParameter("telegramStartNotification"));
    boolean notifySuccess = "true".equals(sr.getParameter("telegramNotifySuccess"));
    boolean notifyAborted = "true".equals(sr.getParameter("telegramNotifyAborted"));
    boolean notifyNotBuilt = "true".equals(sr.getParameter("telegramNotifyNotBuilt"));
    boolean notifyUnstable = "true".equals(sr.getParameter("telegramNotifyUnstable"));
    boolean notifyFailure = "true".equals(sr.getParameter("telegramNotifyFailure"));
    boolean notifyBackToNormal = "true".equals(sr.getParameter("telegramNotifyBackToNormal"));
    boolean notifyRepeatedFailure = "true".equals(sr.getParameter("telegramNotifyRepeatedFailure"));
    boolean includeTestSummary = "true".equals(sr.getParameter("includeTestSummary"));
    boolean includeFailedTests = "true".equals(sr.getParameter("includeFailedTests"));
    CommitInfoChoice commitInfoChoice = CommitInfoChoice.forDisplayName(sr.getParameter("telegramCommitInfoChoice"));
    boolean includeCustomMessage = "on".equals(sr.getParameter("includeCustomMessage"));
    String customMessage = sr.getParameter("customMessage");
    return new TelegramNotifier(token, chatId, buildServerUrl, sendAs, startNotification, notifyAborted,
            notifyFailure, notifyNotBuilt, notifySuccess, notifyUnstable, notifyBackToNormal, notifyRepeatedFailure,
            includeTestSummary,includeFailedTests, commitInfoChoice, includeCustomMessage, customMessage);
}
项目:jenkins-telegram-plugin    文件:TelegramNotifier.java   
@Override
public boolean configure(StaplerRequest sr, JSONObject formData) throws FormException {
    token = sr.getParameter("telegramToken");
    chatId = sr.getParameter("telegramChatId");
    buildServerUrl = sr.getParameter("telegramBuildServerUrl");
    sendAs = sr.getParameter("telegramSendAs");
    if(buildServerUrl == null  || buildServerUrl.equals("")) {
        JenkinsLocationConfiguration jenkinsConfig = new JenkinsLocationConfiguration();
        buildServerUrl = jenkinsConfig.getUrl();
    }
    if (buildServerUrl != null && !buildServerUrl.endsWith("/")) {
        buildServerUrl = buildServerUrl + "/";
    }
    save();
    return super.configure(sr, formData);
}
项目: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);
}
项目:display-url-api-plugin    文件:AbstractDisplayAction.java   
DisplayURLProvider lookupProvider(StaplerRequest req) {
    final String providerName = req.getParameter("provider");
    if(providerName != null && !providerName.isEmpty()) {
        Iterable<DisplayURLProvider> providers = DisplayURLProvider.all();
        Iterable<DisplayURLProvider> filtered = Iterables.filter(providers, new Predicate<DisplayURLProvider>() {
            @Override
            public boolean apply(@Nullable DisplayURLProvider displayURLProvider) {
                if(displayURLProvider == null) {
                    return false;
                }

                return displayURLProvider.getName().equals(providerName);
            }
        });

        DisplayURLProvider provider = Iterables.getFirst(filtered, null);
        if(provider != null) {
            return provider;
        }
    }

    return lookupProvider();
}
项目:ontrack-plugin    文件:OntrackChoiceParameterDefinition.java   
@Override
public ParameterValue createValue(StaplerRequest req) {
    String[] value = req.getParameterValues(getName());
    if (value == null) {
        return getDefaultParameterValue();
    } else if (value.length != 1) {
        throw new IllegalArgumentException(String.format(
                "Illegal number of parameter values for %s: %d",
                getName(),
                value.length));
    } else {
        List<String> choices = getChoices();
        if (choices.contains(value[0])) {
            return new StringParameterValue(getName(), value[0], getDescription());
        } else {
            throw new IllegalArgumentException(String.format(
                    "Value %s for parameter %s is not a valid choice.",
                    value[0],
                    getName()));
        }
    }
}
项目: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("../");
}
项目:jenkins-plugin    文件:TimedBuildStepDescriptor.java   
@Override
public synchronized boolean configure(StaplerRequest req,
        JSONObject formData) throws FormException {
    wait = formData.getString("wait");
    waitUnit = ITimedOpenShiftPlugin.TimeoutUnit.normalize(formData
            .getString("waitUnit"));
    if (wait == null || wait.isEmpty()) {
        // If someone clears the value, go back to default and use seconds
        wait = "" + getStaticDefaultWaitTime()
                / ITimedOpenShiftPlugin.TimeoutUnit.SECONDS.multiplier;
        waitUnit = ITimedOpenShiftPlugin.TimeoutUnit.SECONDS.name;
    }
    wait = wait.trim();
    save();
    return true;
}
项目:dockerhub-notification-plugin    文件:JSONWebHook.java   
private WebHookPayload parse(StaplerRequest req) throws IOException {
    //TODO Actually test what duckerhub is really sending
    String body = IOUtils.toString(req.getInputStream(), req.getCharacterEncoding());
    String contentType = req.getContentType();
    if (contentType != null && contentType.startsWith("application/x-www-form-urlencoded")) {
        body = URLDecoder.decode(body, req.getCharacterEncoding());
    }
    logger.log(Level.FINER, "Received commit hook notification : {0}", body);
    try {
        JSONObject payload = JSONObject.fromObject(body);
        return createPushNotification(payload);
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Could not parse the web hook payload!", e);
        return null;
    }
}
项目:jenkins-mattermost-plugin    文件:MattermostNotifier.java   
@Override
public MattermostNotifier newInstance(StaplerRequest sr, JSONObject json) {
    if (sr == null) {
        return null;
    }
    String endpoint = sr.getParameter("mattermostEndpoint");
    String room = sr.getParameter("mattermostRoom");
    String icon = sr.getParameter("mattermostIcon");
    boolean startNotification = "true".equals(sr.getParameter("mattermostStartNotification"));
    boolean notifySuccess = "true".equals(sr.getParameter("mattermostNotifySuccess"));
    boolean notifyAborted = "true".equals(sr.getParameter("mattermostNotifyAborted"));
    boolean notifyNotBuilt = "true".equals(sr.getParameter("mattermostNotifyNotBuilt"));
    boolean notifyUnstable = "true".equals(sr.getParameter("mattermostNotifyUnstable"));
    boolean notifyFailure = "true".equals(sr.getParameter("mattermostNotifyFailure"));
    boolean notifyBackToNormal = "true".equals(sr.getParameter("mattermostNotifyBackToNormal"));
    boolean notifyRepeatedFailure = "true".equals(sr.getParameter("mattermostNotifyRepeatedFailure"));
    boolean includeTestSummary = "true".equals(sr.getParameter("includeTestSummary"));
    CommitInfoChoice commitInfoChoice = CommitInfoChoice.forDisplayName(sr.getParameter("slackCommitInfoChoice"));
    boolean includeCustomAttachmentMessage = "on".equals(sr.getParameter("includeCustomAttachmentMessage"));
    String customAttachmentMessage = sr.getParameter("mattermostCustomAttachmentMessage");
    boolean includeCustomMessage = "on".equals(sr.getParameter("includeCustomMessage"));
    String customMessage = sr.getParameter("mattermostCustomMessage");
    return new MattermostNotifier(endpoint, room, icon, buildServerUrl, sendAs, startNotification, notifyAborted,
            notifyFailure, notifyNotBuilt, notifySuccess, notifyUnstable, notifyBackToNormal, notifyRepeatedFailure,
            includeTestSummary, commitInfoChoice, includeCustomAttachmentMessage, customAttachmentMessage, includeCustomMessage, customMessage);
}
项目:jenkins-mattermost-plugin    文件:MattermostNotifier.java   
@Override
public boolean configure(StaplerRequest sr, JSONObject formData) throws FormException {
    endpoint = sr.getParameter("mattermostEndpoint");
    room = sr.getParameter("mattermostRoom");
    icon = sr.getParameter("mattermostIcon");
    buildServerUrl = sr.getParameter("mattermostBuildServerUrl");
    sendAs = sr.getParameter("mattermostSendAs");
    if (buildServerUrl == null || buildServerUrl.equals("")) {
        JenkinsLocationConfiguration jenkinsConfig = new JenkinsLocationConfiguration();
        buildServerUrl = jenkinsConfig.getUrl();
    }
    if (buildServerUrl != null && !buildServerUrl.endsWith("/")) {
        buildServerUrl = buildServerUrl + "/";
    }
    save();
    return super.configure(sr, formData);
}
项目:aws-codepipeline-plugin-for-jenkins    文件:AWSCodePipelineSCM.java   
@Override
public SCM newInstance(final StaplerRequest req,
                       final JSONObject formData) throws FormException {
    return new AWSCodePipelineSCM(
            req.getParameter("name"),
            req.getParameter("clearWorkspace") != null,
            req.getParameter("region"),
            req.getParameter("awsAccessKey"),
            req.getParameter("awsSecretKey"),
            req.getParameter("proxyHost"),
            req.getParameter("proxyPort"),
            req.getParameter("category"),
            req.getParameter("provider"),
            req.getParameter("version"),
            new AWSClientFactory());
}
项目:ec2-plugin    文件:EC2OndemandSlave.java   
@Override
public Node newInstance(StaplerRequest req, JSONObject formData) throws FormException {
    EC2OndemandSlave ec2AbstractSlave = (EC2OndemandSlave) super.newInstance(req, formData);

    if (!ec2AbstractSlave.isAlive(true)) {
        LOGGER.info("EC2 instance terminated externally: " + ec2AbstractSlave.getInstanceId());
        try {
            Hudson.getInstance().removeNode(ec2AbstractSlave);
        } catch (IOException ioe) {
            LOGGER.log(Level.WARNING, "Attempt to reconfigure EC2 instance which has been externally terminated: " + ec2AbstractSlave.getInstanceId(), ioe);
        }

        return null;
    }

    return ec2AbstractSlave;
}