Java Code Examples for org.kohsuke.stapler.Stapler#getCurrentRequest()

The following examples show how to use org.kohsuke.stapler.Stapler#getCurrentRequest() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BlueUrlTokenizer.java    From blueocean-plugin with MIT License 6 votes vote down vote up
/**
 * 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);
}
 
Example 2
Source File: DynamicSubBuild.java    From DotCi with MIT License 6 votes vote down vote up
@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();
}
 
Example 3
Source File: FavoriteContainerImpl.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@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);
}
 
Example 4
Source File: BlueTestResultContainerImpl.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@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();
}
 
Example 5
Source File: OrganizationFolderPipelineImpl.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
public void getUrl() {
    StaplerRequest req = Stapler.getCurrentRequest();
    String s = req.getParameter("s");
    if (s == null) {
        s = Integer.toString(DEFAULT_ICON_SIZE);
    }
    StaplerResponse resp = Stapler.getCurrentResponse();
    try {
        resp.setHeader("Cache-Control", "max-age=" + TimeUnit.DAYS.toDays(7));
        resp.sendRedirect(action.getAvatarImageOf(s));
    } catch (IOException e) {
        throw new UnexpectedErrorException("Could not provide icon", e);
    }
}
 
Example 6
Source File: GerritWebHook.java    From gerrit-code-review-plugin with Apache License 2.0 5 votes vote down vote up
@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);
                    }
                  }
                }
              }
            }
          });
}
 
Example 7
Source File: OrganizationContainer.java    From DotCi with MIT License 5 votes vote down vote up
@Override
public Object getTarget() {
    final StaplerRequest currentRequest = Stapler.getCurrentRequest();
    //@formatter:off
    if (!currentRequest.getRequestURI().matches(".*(api/(json|xml)).*")
        && !currentRequest.getRequestURI().contains("buildWithParameters")
        && !currentRequest.getRequestURI().contains("logTail")
        && !currentRequest.getRequestURI().contains("artifact")) {
        //@formatter:on
        authenticate();
    }

    return this;
}
 
Example 8
Source File: GitLabPushTrigger.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
private Job<?, ?> retrieveCurrentJob() {
    StaplerRequest request = Stapler.getCurrentRequest();
    if (request != null) {
        Ancestor ancestor = request.findAncestor(Job.class);
        return ancestor == null ? null : (Job<?, ?>) ancestor.getObject();
    }
    return null;
}
 
Example 9
Source File: BlueOceanUI.java    From blueocean-plugin with MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example 10
Source File: BlueOceanRootAction.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@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;
}
 
Example 11
Source File: GithubReposController.java    From DotCi with MIT License 5 votes vote down vote up
@Override
public Object getTarget() {
    final StaplerRequest currentRequest = Stapler.getCurrentRequest();
    if (getAccessToken(currentRequest) == null)
        return new GithubOauthLoginAction();
    return this;
}
 
Example 12
Source File: BitbucketRepositoryContainer.java    From blueocean-plugin with MIT License 5 votes vote down vote up
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;
    }

}
 
Example 13
Source File: RelativeLocation.java    From jenkins-build-monitor-plugin with MIT License 5 votes vote down vote up
public String name() {
    ItemGroup ig = null;

    StaplerRequest request = Stapler.getCurrentRequest();
    for( Ancestor a : request.getAncestors() ) {
        if(a.getObject() instanceof BuildMonitorView) {
            ig = ((View) a.getObject()).getOwnerItemGroup();
        }
    }

    return Functions.getRelativeDisplayNameFrom(job, ig);
}
 
Example 14
Source File: GitLabRequireOrganizationMembershipACL.java    From gitlab-oauth-plugin with MIT License 4 votes vote down vote up
private String requestURI() {
    StaplerRequest currentRequest = Stapler.getCurrentRequest();
    return (currentRequest == null) ? null : currentRequest.getOriginalRequestURI();
}
 
Example 15
Source File: BrowserAndOperatingSystemAnalyticsProperties.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Override
public Map<String, Object> properties(TrackRequest req) {
    StaplerRequest httpReq = Stapler.getCurrentRequest();
    if (PARSER == null || httpReq == null) {
        return null;
    }
    String userAgent = httpReq.getHeader("User-Agent");
    if (userAgent == null) {
        return null;
    }
    Client client = PARSER.parse(userAgent);
    String browserFamily = client.userAgent.family;
    // If we can't find the browser family then we shouldn't record anything
    if (browserFamily == null) {
        return null;
    }
    Map<String, Object> props = Maps.newHashMap();
    props.put("browserFamily", browserFamily);
    String browserVersionMajor = client.userAgent.major;
    // Versions are useful if they are available
    if (isNotEmpty(browserVersionMajor)) {
        props.put("browserVersionMajor", browserVersionMajor);
    }
    String browserVersionMinor = client.userAgent.minor;
    if (isNotEmpty(browserVersionMinor)) {
        props.put("browserVersionMinor", browserVersionMinor);
    }
    // If the operating system is available lets use that
    String operatingSystemFamily = client.os.family;
    if (isNotEmpty(operatingSystemFamily)) {
        props.put("osFamily", operatingSystemFamily);
        String osVersionMajor = client.os.major;
        if (isNotEmpty(osVersionMajor)) {
            props.put("osVersionMajor", osVersionMajor);
        }
        String osVersionMinor = client.os.minor;
        if (isNotEmpty(osVersionMinor)) {
            props.put("osVersionMinor", osVersionMinor);
        }
    }
    return props;
}
 
Example 16
Source File: GithubScmContentProvider.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Override
protected StandardUsernamePasswordCredentials getCredentialForUser(final Item item, String apiUrl){
    User user = User.current();
    if(user == null){ //ensure this session has authenticated user
        throw new ServiceException.UnauthorizedException("No logged in user found");
    }

    StaplerRequest request = Stapler.getCurrentRequest();
    String scmId = request.getParameter("scmId");

    //get credential for this user
    GithubScm scm;
    final BlueOrganization organization = OrganizationFactory.getInstance().getContainingOrg(item);
    if(apiUrl.startsWith(GitHubSCMSource.GITHUB_URL)
            //tests might add scmId to indicate which Scm should be used to find credential
            //We have to do this because apiUrl might be of WireMock server and not Github
            || (StringUtils.isNotBlank(scmId) && scmId.equals(GithubScm.ID))) {
        scm = new GithubScm(new Reachable() {
            @Override
            public Link getLink() {
                Preconditions.checkNotNull(organization);
                return organization.getLink().rel("scm");
            }
        });
    }else{ //GHE
        scm = new GithubEnterpriseScm((new Reachable() {
            @Override
            public Link getLink() {
                Preconditions.checkNotNull(organization);
                return organization.getLink().rel("scm");
            }
        }));
    }

    //pick up github credential from user's store
    StandardUsernamePasswordCredentials githubCredential = scm.getCredential(GithubScm.normalizeUrl(apiUrl));
    if(githubCredential == null){
        throw new ServiceException.PreconditionRequired("Can't access content from github: no credential found");
    }
    return githubCredential;
}
 
Example 17
Source File: GithubScm.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Override
public Container<ScmOrganization> getOrganizations() {
    StaplerRequest request = Stapler.getCurrentRequest();
    String credentialId = GithubCredentialUtils.computeCredentialId(getCredentialIdFromRequest(request), getId(), getUri());

    User authenticatedUser = getAuthenticatedUser();
    final StandardUsernamePasswordCredentials credential = CredentialsUtils.findCredential(credentialId, StandardUsernamePasswordCredentials.class, new BlueOceanDomainRequirement());

    if(credential == null){
        throw new ServiceException.BadRequestException(String.format("Credential id: %s not found for user %s", credentialId, authenticatedUser.getId()));
    }

    String accessToken = credential.getPassword().getPlainText();

    try {
        GitHub github = GitHubFactory.connect(accessToken, getUri());

        final Link link = getLink().rel("organizations");

        Map<String, ScmOrganization> orgMap = new LinkedHashMap<>(); // preserve the same order that github org api returns

        for(Map.Entry<String, GHOrganization> entry: github.getMyOrganizations().entrySet()){
                orgMap.put(entry.getKey(),
                        new GithubOrganization(GithubScm.this, entry.getValue(), credential, link));
        }

        GHMyself user = github.getMyself();
        if(orgMap.get(user.getLogin()) == null){ //this is to take care of case if/when github starts reporting user login as org later on
            orgMap = new HashMap<>(orgMap);
            orgMap.put(user.getLogin(), new GithubUserOrganization(user, credential, this));
        }
        final Map<String, ScmOrganization> orgs = orgMap;
        return new Container<ScmOrganization>() {
            @Override
            public ScmOrganization get(String name) {
                ScmOrganization org = orgs.get(name);
                if(org == null){
                    throw new ServiceException.NotFoundException(String.format("GitHub organization %s not found", name));
                }
                return org;
            }

            @Override
            public Link getLink() {
                return link;
            }

            @Override
            public Iterator<ScmOrganization> iterator() {
                return orgs.values().iterator();
            }
        };
    } catch (IOException e) {
        if(e instanceof HttpException) {
            HttpException ex = (HttpException) e;
            if (ex.getResponseCode() == 401) {
                throw new ServiceException
                        .PreconditionRequired("Invalid GitHub accessToken", ex);
            }else if(ex.getResponseCode() == 403){
                throw new ServiceException
                        .PreconditionRequired("GitHub accessToken does not have required scopes. Expected scopes 'user:email, repo'", ex);
            }
        }
        throw new ServiceException.UnexpectedErrorException(e.getMessage(), e);
    }
}
 
Example 18
Source File: AbstractBitbucketScm.java    From blueocean-plugin with MIT License 4 votes vote down vote up
protected StaplerRequest getStaplerRequest(){
    StaplerRequest request = Stapler.getCurrentRequest();
    Preconditions.checkNotNull(request, "Must be called in HTTP request context");
    return request;
}
 
Example 19
Source File: MultibranchPipelineRunContainer.java    From blueocean-plugin with MIT License 4 votes vote down vote up
/**
 * Fetches maximum up to  MAX_MBP_RUNS_ROWS rows from each branch and does pagination on that.
 *
 * JVM property MAX_MBP_RUNS_ROWS can be used to tune this value to optimize performance for given setup
 */
@Override
public Iterator<BlueRun> iterator(int start, int limit) {
    List<BlueRun> c = new ArrayList<>();

    List<BluePipeline> branches;

    // Check for branch filter
    StaplerRequest req = Stapler.getCurrentRequest();
    String branchFilter = null;
    if (req != null) {
        branchFilter = req.getParameter("branch");
    }

    if (!StringUtils.isEmpty(branchFilter)) {
        BluePipeline pipeline = blueMbPipeline.getBranches().get(branchFilter);
        if (pipeline != null) {
            branches = Collections.singletonList(pipeline);
        } else {
            branches = Collections.emptyList();
        }
    } else {
        branches = Lists.newArrayList(blueMbPipeline.getBranches().list());
        sortBranchesByLatestRun(branches);
    }

    for (final BluePipeline b : branches) {
        BlueRunContainer blueRunContainer = b.getRuns();
        if(blueRunContainer==null){
            continue;
        }
        Iterator<BlueRun> it = blueRunContainer.iterator(0, MAX_MBP_RUNS_ROWS);
        int count = 0;
        Utils.skip(it, start);
        while (it.hasNext() && count++ < limit) {
            c.add(it.next());
        }
    }

    Collections.sort(c, LATEST_RUN_START_TIME_COMPARATOR);

    return Iterators.limit(c.iterator(), limit);
}
 
Example 20
Source File: AbstractBitbucketScm.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Override
public Container<ScmOrganization> getOrganizations() {
    User authenticatedUser = getAuthenticatedUser();

    StaplerRequest request = Stapler.getCurrentRequest();
    Preconditions.checkNotNull(request, "This request must be made in HTTP context");
    String credentialId = BitbucketCredentialUtils.computeCredentialId(getCredentialIdFromRequest(request), getId(), getUri());

    List<ErrorMessage.Error> errors = new ArrayList<>();
    StandardUsernamePasswordCredentials credential = null;
    if(credentialId == null){
        errors.add(new ErrorMessage.Error("credentialId", ErrorMessage.Error.ErrorCodes.MISSING.toString(),
                "Missing credential id. It must be provided either as HTTP header: " + X_CREDENTIAL_ID+" or as query parameter 'credentialId'"));
    }else {
        credential = CredentialsUtils.findCredential(credentialId,
                StandardUsernamePasswordCredentials.class, new BlueOceanDomainRequirement());
        if (credential == null) {
            errors.add(new ErrorMessage.Error("credentialId", ErrorMessage.Error.ErrorCodes.INVALID.toString(),
                    String.format("credentialId: %s not found in user %s's credential store", credentialId, authenticatedUser.getId())));
        }
    }
    String apiUrl  =  request.getParameter("apiUrl");
    if(StringUtils.isBlank(apiUrl)){
        errors.add(new ErrorMessage.Error("apiUrl", ErrorMessage.Error.ErrorCodes.MISSING.toString(),
                "apiUrl is required parameter"));
    }
    if(!errors.isEmpty()){
        throw new ServiceException.BadRequestException(new ErrorMessage(400, "Failed to return Bitbucket organizations").addAll(errors));
    }else {
        apiUrl = normalizeApiUrl(apiUrl);
        BitbucketApiFactory apiFactory = BitbucketApiFactory.resolve(this.getId());
        if (apiFactory == null) {
            throw new ServiceException.UnexpectedErrorException("BitbucketApiFactory to handle apiUrl " + apiUrl + " not found");
        }

        Preconditions.checkNotNull(credential);
        final BitbucketApi api = apiFactory.create(apiUrl, credential);
        return new Container<ScmOrganization>() {
            @Override
            public ScmOrganization get(String name) {
                return new BitbucketOrg(api.getOrg(name), api, getLink());
            }

            @Override
            public Link getLink() {
                return AbstractBitbucketScm.this.getLink().rel("organizations");
            }

            @Override
            public Iterator<ScmOrganization> iterator() {
                return iterator(0, 100);
            }

            @Override
            public Iterator<ScmOrganization> iterator(int start, int limit) {
                if(limit <= 0){
                    limit = PagedResponse.DEFAULT_LIMIT;
                }
                if(start <0){
                    start = 0;
                }
                int page =  (start/limit) + 1;
                return Lists.transform(api.getOrgs(page, limit).getValues(), new Function<BbOrg, ScmOrganization>() {
                    @Nullable
                    @Override
                    public ScmOrganization apply(@Nullable BbOrg input) {
                        if (input != null) {
                            return new BitbucketOrg(input, api, getLink());
                        }
                        return null;
                    }
                }).iterator();
            }
        };
    }
}