hudson.model.Describable#org.kohsuke.stapler.Stapler源码实例Demo

下面列出了hudson.model.Describable#org.kohsuke.stapler.Stapler 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: blueocean-plugin   文件: AbstractBitbucketScm.java
@Override
public Object getState() {
    StaplerRequest request = Stapler.getCurrentRequest();
    Preconditions.checkNotNull(request, "Must be called in HTTP request context");

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

    ErrorMessage message = new ErrorMessage(400, "Invalid request");
    if(StringUtils.isBlank(apiUrl)) {
        message.add(new ErrorMessage.Error("apiUrl", ErrorMessage.Error.ErrorCodes.MISSING.toString(),
                "apiUrl is required parameter"));
    }
    try {
        new URL(apiUrl);
    } catch (MalformedURLException e) {
        message.add(new ErrorMessage.Error("apiUrl", ErrorMessage.Error.ErrorCodes.INVALID.toString(),
                "apiUrl parameter must be a valid URL"));
    }
    if(!message.getErrors().isEmpty()){
        throw new ServiceException.BadRequestException(message);
    }
    validateExistingCredential(apiUrl);
    return super.getState();
}
 
@Nonnull
@Override
public Iterator<BlueTestResult> iterator() {
    Result resolved = resolve();
    if (resolved.summary == null || resolved.results == null) {
        throw new NotFoundException("no tests");
    }
    StaplerRequest request = Stapler.getCurrentRequest();
    if (request != null) {
        String status = request.getParameter("status");
        String state = request.getParameter("state");
        String age = request.getParameter("age");
        return getBlueTestResultIterator(resolved.results, status, state, age);

    }
    return resolved.results.iterator();
}
 
源代码3 项目: blueocean-plugin   文件: FavoriteContainerImpl.java
@Override
public Iterator<BlueFavorite> iterator() {
    StaplerRequest request = Stapler.getCurrentRequest();
    int start=0;
    int limit = PagedResponse.DEFAULT_LIMIT;

    if(request != null) {
        String startParam = request.getParameter("start");
        if (StringUtils.isNotBlank(startParam)) {
            start = Integer.parseInt(startParam);
        }

        String limitParam = request.getParameter("limit");
        if (StringUtils.isNotBlank(limitParam)) {
            limit = Integer.parseInt(limitParam);
        }
    }

    return iterator(start, limit);
}
 
源代码4 项目: blueocean-plugin   文件: ApiHead.java
/**
 * Exposes all {@link ApiRoutable}s to URL space.
 *
 * @param route current URL route handled by ApiHead
 * @return {@link ApiRoutable} object
 */
public ApiRoutable getDynamic(String route) {
    setApis();
    StaplerRequest request = Stapler.getCurrentRequest();
    String m = request.getMethod();
    if(m.equalsIgnoreCase("POST") || m.equalsIgnoreCase("PUT") || m.equalsIgnoreCase("PATCH")) {
        String header = request.getHeader("Content-Type");
        if(header == null || !header.contains("application/json")) {
            throw new ServiceException(415, "Content-Type: application/json required");
        }
    }

    ApiRoutable apiRoutable = apis.get(route);

    //JENKINS-46025 - Avoid caching REST API responses for IE
    StaplerResponse response = Stapler.getCurrentResponse();
    if (response != null && !response.containsHeader("Cache-Control")) {
        response.setHeader("Cache-Control", "no-cache, no-store, no-transform");
    }

    return apiRoutable;
}
 
源代码5 项目: blueocean-plugin   文件: GithubScm.java
protected @Nonnull String getCustomApiUri() {
    StaplerRequest request = Stapler.getCurrentRequest();
    Preconditions.checkNotNull(request, "Must be called in HTTP request context");
    String apiUri = request.getParameter("apiUrl");

    // if "apiUrl" parameter was supplied, parse and trim trailing slash
    if (!StringUtils.isEmpty(apiUri)) {
        try {
            new URI(apiUri);
        } catch (URISyntaxException ex) {
            throw new ServiceException.BadRequestException(new ErrorMessage(400, "Invalid URI: " + apiUri));
        }
        apiUri = normalizeUrl(apiUri);
    } else {
        apiUri = "";
    }

    return apiUri;
}
 
源代码6 项目: blueocean-plugin   文件: BlueUrlTokenizer.java
/**
 * Parse the {@link Stapler#getCurrentRequest() current Stapler request} and return a {@link BlueUrlTokenizer} instance
 * iff the URL is a Blue Ocean UI URL.
 *
 * @return A {@link BlueUrlTokenizer} instance iff the URL is a Blue Ocean UI URL, otherwise {@code null}.
 * @throws IllegalStateException Called outside the scope of an active {@link StaplerRequest}.
 */
public static @CheckForNull
BlueUrlTokenizer parseCurrentRequest() throws IllegalStateException {
    StaplerRequest currentRequest = Stapler.getCurrentRequest();

    if (currentRequest == null) {
        throw new IllegalStateException("Illegal call to BlueoceanUrl.parseCurrentRequest outside the scope of an active StaplerRequest.");
    }

    String path = currentRequest.getOriginalRequestURI();
    String contextPath = currentRequest.getContextPath();

    path = path.substring(contextPath.length());

    return parse(path);
}
 
源代码7 项目: jenkins-test-harness   文件: JenkinsRule.java
/**
 * Executes the given closure on the server, by the servlet request handling thread,
 * in the context of an HTTP request.
 *
 * <p>
 * In {@link JenkinsRule}, a thread that's executing the test code is different from the thread
 * that carries out HTTP requests made through {@link WebClient}. But sometimes you want to
 * make assertions and other calls with side-effect from within the request handling thread.
 *
 * <p>
 * This method allows you to do just that. It is useful for testing some methods that
 * require {@link org.kohsuke.stapler.StaplerRequest} and {@link org.kohsuke.stapler.StaplerResponse}, or getting the credential
 * of the current user (via {@link jenkins.model.Jenkins#getAuthentication()}, and so on.
 *
 * @param c
 *      The closure to be executed on the server.
 * @return
 *      The return value from the closure.
 * @throws Exception
 *      If a closure throws any exception, that exception will be carried forward.
 */
public <V> V executeOnServer(final Callable<V> c) throws Exception {
    final Exception[] t = new Exception[1];
    final List<V> r = new ArrayList<V>(1);  // size 1 list

    ClosureExecuterAction cea = jenkins.getExtensionList(RootAction.class).get(ClosureExecuterAction.class);
    UUID id = UUID.randomUUID();
    cea.add(id,new Runnable() {
        public void run() {
            try {
                StaplerResponse rsp = Stapler.getCurrentResponse();
                rsp.setStatus(200);
                rsp.setContentType("text/html");
                r.add(c.call());
            } catch (Exception e) {
                t[0] = e;
            }
        }
    });
    goTo("closures/?uuid="+id);

    if (t[0]!=null)
        throw t[0];
    return r.get(0);
}
 
源代码8 项目: jenkins-test-harness   文件: HudsonTestCase.java
/**
 * Executes the given closure on the server, by the servlet request handling thread,
 * in the context of an HTTP request.
 *
 * <p>
 * In {@link HudsonTestCase}, a thread that's executing the test code is different from the thread
 * that carries out HTTP requests made through {@link WebClient}. But sometimes you want to
 * make assertions and other calls with side-effect from within the request handling thread.
 *
 * <p>
 * This method allows you to do just that. It is useful for testing some methods that
 * require {@link StaplerRequest} and {@link StaplerResponse}, or getting the credential
 * of the current user (via {@link jenkins.model.Jenkins#getAuthentication()}, and so on.
 *
 * @param c
 *      The closure to be executed on the server.
 * @return
 *      The return value from the closure.
 * @throws Exception
 *      If a closure throws any exception, that exception will be carried forward.
 */
public <V> V executeOnServer(final Callable<V> c) throws Exception {
    final Exception[] t = new Exception[1];
    final List<V> r = new ArrayList<V>(1);  // size 1 list

    ClosureExecuterAction cea = jenkins.getExtensionList(RootAction.class).get(ClosureExecuterAction.class);
    UUID id = UUID.randomUUID();
    cea.add(id,new Runnable() {
        public void run() {
            try {
                StaplerResponse rsp = Stapler.getCurrentResponse();
                rsp.setStatus(200);
                rsp.setContentType("text/html");
                r.add(c.call());
            } catch (Exception e) {
                t[0] = e;
            }
        }
    });
    goTo("closures/?uuid="+id);

    if (t[0]!=null)
        throw t[0];
    return r.get(0);
}
 
/**
 * {@inheritDoc}
 */
@Override
public String getAvatarImageOf(String size) {
    if (avatar == null) {
        // fall back to the generic github org icon
        String image = avatarIconClassNameImageOf(getAvatarIconClassName(), size);
        return image != null
                ? image
                : (Stapler.getCurrentRequest().getContextPath() + Hudson.RESOURCE_PATH
                        + "/plugin/github-branch-source/images/" + size + "/github-logo.png");
    } else {
        String[] xy = size.split("x");
        if (xy.length == 0) return avatar;
        if (avatar.contains("?")) return avatar + "&s=" + xy[0];
        else return avatar + "?s=" + xy[0];
    }
}
 
源代码10 项目: junit-plugin   文件: History.java
/**
 * Graph of # of tests over time.
 *
 * @return a graph of number of tests over time.
 */
public Graph getCountGraph() {
    return new GraphImpl("") {
        protected DataSetBuilder<String, ChartLabel> createDataSet() {
            DataSetBuilder<String, ChartLabel> data = new DataSetBuilder<String, ChartLabel>();

            List<TestResult> list;
            try {
            	list = getList(
            			Integer.parseInt(Stapler.getCurrentRequest().getParameter("start")), 
            			Integer.parseInt(Stapler.getCurrentRequest().getParameter("end")));
            } catch (NumberFormatException e) {
            	list = getList();
            }
            
            for (TestResult o: list) {
                data.add(o.getPassCount(), "2Passed", new ChartLabel(o));
                data.add(o.getFailCount(), "1Failed", new ChartLabel(o));
                data.add(o.getSkipCount(), "0Skipped", new ChartLabel(o));
            }
            return data;
        }
    };
}
 
源代码11 项目: DotCi   文件: DynamicSubBuild.java
@Override
public String getUpUrl() {
    final StaplerRequest req = Stapler.getCurrentRequest();
    if (req != null) {
        final List<Ancestor> ancs = req.getAncestors();
        for (int i = 1; i < ancs.size(); i++) {
            if (ancs.get(i).getObject() == this) {
                final Object parentObj = ancs.get(i - 1).getObject();
                if (parentObj instanceof DynamicBuild || parentObj instanceof DynamicSubProject) {
                    return ancs.get(i - 1).getUrl() + '/';
                }
            }
        }
    }
    return super.getDisplayName();
}
 
/**
 * Redirects to the same page that initiated the request.
 */
private void redirect() {
    try {
        Stapler.getCurrentResponse().forwardToPreviousPage(Stapler.getCurrentRequest());
    } catch (ServletException | IOException e) {
        LOGGER.log(Level.WARNING, "Unable to redirect to previous page.");
    }
}
 
源代码13 项目: gitlab-branch-source-plugin   文件: GitLabLink.java
@Override
public String getIconFileName() {
    String iconClassName = getIconClassName();
    Icon icon = IconSet.icons.getIconByClassSpec(iconClassName + " icon-md");
    if (icon != null) {
        JellyContext ctx = new JellyContext();
        ctx.setVariable("resURL",
            Stapler.getCurrentRequest().getContextPath() + Jenkins.RESOURCE_PATH);
        return icon.getQualifiedUrl(ctx);
    }
    return null;
}
 
源代码14 项目: gitlab-branch-source-plugin   文件: GitLabIcons.java
public static String iconFileName(String name, Size size) {
    Icon icon = icons.getIconByClassSpec(classSpec(name, size));
    if (icon == null) {
        return null;
    }

    JellyContext ctx = new JellyContext();
    ctx.setVariable("resURL",
        Stapler.getCurrentRequest().getContextPath() + Jenkins.RESOURCE_PATH);
    return icon.getQualifiedUrl(ctx);
}
 
源代码15 项目: gerrit-code-review-plugin   文件: GerritWebHook.java
@SuppressWarnings({"unused", "deprecation"})
public void doIndex() throws IOException {
  HttpServletRequest req = Stapler.getCurrentRequest();
  getBody(req)
      .ifPresent(
          projectEvent -> {
            String username = "anonymous";
            Authentication authentication = getJenkinsInstance().getAuthentication();
            if (authentication != null) {
              username = authentication.getName();
            }

            log.info("GerritWebHook invoked by user '{}' for event: {}", username, projectEvent);

            try (ACLContext acl = ACL.as(ACL.SYSTEM)) {
              List<WorkflowMultiBranchProject> jenkinsItems =
                  getJenkinsInstance().getAllItems(WorkflowMultiBranchProject.class);
              log.info("Scanning {} Jenkins items", jenkinsItems.size());
              for (SCMSourceOwner scmJob : jenkinsItems) {
                log.info("Scanning job " + scmJob);
                List<SCMSource> scmSources = scmJob.getSCMSources();
                for (SCMSource scmSource : scmSources) {
                  if (scmSource instanceof GerritSCMSource) {
                    GerritSCMSource gerritSCMSource = (GerritSCMSource) scmSource;
                    log.debug("Checking match for SCM source: " + gerritSCMSource.getRemote());
                    if (projectEvent.matches(gerritSCMSource.getRemote())) {
                      log.info(
                          "Triggering SCM event for source "
                              + scmSources.get(0)
                              + " on job "
                              + scmJob);
                      scmJob.onSCMSourceUpdated(scmSource);
                    }
                  }
                }
              }
            }
          });
}
 
源代码16 项目: gitea-plugin   文件: GiteaLink.java
/**
 * {@inheritDoc}
 */
@Override
public String getIconFileName() {
    String iconClassName = getIconClassName();
    if (iconClassName != null) {
        Icon icon = IconSet.icons.getIconByClassSpec(iconClassName + " icon-md");
        if (icon != null) {
            JellyContext ctx = new JellyContext();
            ctx.setVariable("resURL", Stapler.getCurrentRequest().getContextPath() + Jenkins.RESOURCE_PATH);
            return icon.getQualifiedUrl(ctx);
        }
    }
    return null;
}
 
源代码17 项目: jira-steps-plugin   文件: JiraStepsConfig.java
@Override
public boolean configure(StaplerRequest req, JSONObject formData) {
  Stapler.CONVERT_UTILS.deregister(java.net.URL.class);
  Stapler.CONVERT_UTILS.register(new EmptyFriendlyURLConverter(), java.net.URL.class);
  sites.replaceBy(req.bindJSONToList(Site.class, formData.get("sites")));
  save();
  return true;
}
 
public static String iconFileName(String name, Size size) {
    Icon icon = icons.getIconByClassSpec(classSpec(name, size));
    if (icon == null) {
        return null;
    }

    JellyContext ctx = new JellyContext();
    ctx.setVariable("resURL", Stapler.getCurrentRequest().getContextPath() + Jenkins.RESOURCE_PATH);
    return icon.getQualifiedUrl(ctx);
}
 
源代码19 项目: hubot-steps-plugin   文件: GlobalConfig.java
@Override
public boolean configure(StaplerRequest req, JSONObject formData) {
  Stapler.CONVERT_UTILS.deregister(java.net.URL.class);
  Stapler.CONVERT_UTILS.register(new EmptyFriendlyURLConverter(), java.net.URL.class);

  sites.replaceBy(req.bindJSONToList(HubotSite.class, formData.get("sites")));
  save();
  return true;
}
 
源代码20 项目: hubot-steps-plugin   文件: HubotFolderProperty.java
@Override
public AbstractFolderProperty<?> reconfigure(StaplerRequest req, JSONObject formData) {
  if (formData == null) {
    return null;
  }
  Stapler.CONVERT_UTILS.deregister(java.net.URL.class);
  Stapler.CONVERT_UTILS.register(new EmptyFriendlyURLConverter(), java.net.URL.class);

  sites.replaceBy(req.bindJSONToList(HubotSite.class, formData.get("sites")));
  return this;
}
 
/**
 * Generates the Anchore trend graph
 * @return graph object
 */
public Graph getTrendGraph() {
  final AnchoreAction a = getLastAnchoreAction();
  if (a != null) {
    return new AnchoreTrendGraph(a, getRelPath(Stapler.getCurrentRequest()));
  }else{
    Stapler.getCurrentResponse().setStatus(HttpServletResponse.SC_NOT_FOUND);
    return null;
  }
}
 
public BitbucketRepositories() {
    this.self = BitbucketRepositoryContainer.this.getLink().rel("repositories");
    StaplerRequest request = Stapler.getCurrentRequest();
    int pageNumber = 0;

    if (!StringUtils.isBlank(request.getParameter("pageNumber"))) {
        pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
    }
    if(pageNumber <=0){
        pageNumber = 1;//default
    }
    int pageSize = 0;
    if (request.getParameter("pageSize") != null) {
        pageSize = Integer.parseInt(request.getParameter("pageSize"));
    }
    if(pageSize <=0){
        pageSize = 100;//default
    }

    BbPage<BbRepo> repos = api.getRepos(project.getKey(), pageNumber, pageSize);
    for (BbRepo repo : repos.getValues()) {
        repositories.add(repo.toScmRepository(api, this));
    }
    this.isLastPage = repos.isLastPage();
    this.pageSize = repos.getLimit();

    if (!repos.isLastPage()) {
        this.nextPage = pageNumber+1;
    }else{
        this.nextPage = null;
    }

}
 
private StaplerRequest mockStapler() {
    mockStatic(Stapler.class);
    StaplerRequest staplerRequest = mock(StaplerRequest.class);
    when(Stapler.getCurrentRequest()).thenReturn(staplerRequest);
    when(staplerRequest.getRequestURI()).thenReturn("http://localhost:8080/jenkins/blue/rest/");
    when(staplerRequest.getParameter("path")).thenReturn("Jenkinsfile");
    when(staplerRequest.getParameter("repo")).thenReturn("demo1");
    when(staplerRequest.getParameter("scmId")).thenReturn(BitbucketCloudScm.ID);
    return staplerRequest;
}
 
private StaplerRequest mockStapler() {
    mockStatic(Stapler.class);
    StaplerRequest staplerRequest = mock(StaplerRequest.class);
    when(Stapler.getCurrentRequest()).thenReturn(staplerRequest);
    when(staplerRequest.getRequestURI()).thenReturn("http://localhost:8080/jenkins/blue/rest/");
    when(staplerRequest.getParameter("path")).thenReturn("Jenkinsfile");
    when(staplerRequest.getParameter("repo")).thenReturn("pipeline-demo-test");
    return staplerRequest;
}
 
源代码25 项目: blueocean-plugin   文件: BlueOceanRootAction.java
@Override
public Object getTarget() {

    StaplerRequest request = Stapler.getCurrentRequest();

    if(request.getOriginalRestOfPath().startsWith("/rest/")) {
        /**
         * If JWT is enabled, authenticate request using JWT token and set authentication context
         */
        if (enableJWT && !JwtAuthenticationFilter.didRequestHaveValidatedJwtToken()) {
            throw new ServiceException.UnauthorizedException("Unauthorized: Jwt token verification failed, no valid authentication instance found");
        }
        /**
         * Check overall read permission. This will make sure we have all rest api protected in case request
         * doesn't carry overall read permission.
         *
         * @see Jenkins#getTarget()
         */
        Authentication a = Jenkins.getAuthentication();
        if(!Jenkins.getInstance().getACL().hasPermission(a,Jenkins.READ)){
            throw new ServiceException.ForbiddenException("Forbidden");
        }
    }else{
        //If user doesn't have overall Jenkins read permission then return 403, which results in classic UI redirecting
        // user to login page
        Jenkins.getInstance().checkPermission(Jenkins.READ);
    }

    // frontend uses this to determine when to reload
    Stapler.getCurrentResponse().setHeader("X-Blueocean-Refresher", Jenkins.SESSION_HASH);

    return app;
}
 
源代码26 项目: blueocean-plugin   文件: ContainerFilter.java
private static String[] filterNames(){
    StaplerRequest req = Stapler.getCurrentRequest();
    if (req == null) {
        return new String[0];
    }
    String itemFilter = req.getParameter("filter");
    if (itemFilter == null) {
        return new String[0];
    }
    return itemFilter.split(",");
}
 
源代码27 项目: blueocean-plugin   文件: APIHeadTest.java
@Override
@SuppressWarnings("unchecked")
public Iterator<String> iterator() {
    StaplerResponse response = Stapler.getCurrentResponse();
    response.setHeader("Cache-Control", "max-age=10");
    return new ArrayList<String>().iterator();
}
 
private BrowserAndOperatingSystemAnalyticsProperties setup(String userAgent) {
    StaplerRequest request = mock(StaplerRequest.class);
    when(request.getHeader("User-Agent")).thenReturn(userAgent);
    mockStatic(Stapler.class);
    when(Stapler.getCurrentRequest()).thenReturn(request);
    return new BrowserAndOperatingSystemAnalyticsProperties();
}
 
源代码29 项目: blueocean-plugin   文件: BlueOceanUI.java
/**
 * Get the language associated with the current page.
 * @return The language string.
 */
public String getLang() {
    StaplerRequest currentRequest = Stapler.getCurrentRequest();

    if (currentRequest != null) {
        Locale locale = currentRequest.getLocale();
        if (locale != null) {
            return locale.toLanguageTag();
        }
    }

    return null;
}
 
源代码30 项目: blueocean-plugin   文件: Links.java
private String getBasePath(){
    String path = Stapler.getCurrentRequest().getPathInfo();
    String contextPath = Stapler.getCurrentRequest().getContextPath().trim();

    if(!contextPath.isEmpty() || !contextPath.equals("/")){
        int i = path.indexOf(contextPath);
        if(i >= 0){
            if(path.length() > i){
                int j = path.indexOf('/', i+1);
                return path.substring(j);
            }
        }
    }
    return path;
}