org.kohsuke.stapler.Stapler Java Examples

The following examples show how to use org.kohsuke.stapler.Stapler. 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: AbstractBitbucketScm.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@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();
}
 
Example #2
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 #3
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 #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: 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 #6
Source File: ApiHead.java    From blueocean-plugin with MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example #7
Source File: GithubScm.java    From blueocean-plugin with MIT License 6 votes vote down vote up
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;
}
 
Example #8
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 6 votes vote down vote up
/**
 * 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);
}
 
Example #9
Source File: History.java    From junit-plugin with MIT License 6 votes vote down vote up
/**
 * 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;
        }
    };
}
 
Example #10
Source File: HudsonTestCase.java    From jenkins-test-harness with MIT License 6 votes vote down vote up
/**
 * 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);
}
 
Example #11
Source File: GitHubOrgMetadataAction.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
/**
 * {@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];
    }
}
 
Example #12
Source File: JobInfo.java    From DotCi with MIT License 5 votes vote down vote up
@Exported
public List<JobMetric> getMetrics() {
    final StaplerRequest req = Stapler.getCurrent().getCurrentRequest();
    final String branchTab = req.getParameter("branchTab");
    final String buildCount = req.getParameter("count");
    return JobMetric.getApplicableJobMetrics(this.dynamicProject, branchTab, Integer.parseInt(buildCount));
}
 
Example #13
Source File: FolderAuthorizationStrategyManagementLink.java    From folder-auth-plugin with MIT License 5 votes vote down vote up
/**
 * 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.");
    }
}
 
Example #14
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 #15
Source File: DbBackedProject.java    From DotCi with MIT License 5 votes vote down vote up
@Override
public B getLastBuild() {
    String branch = "master";
    final StaplerRequest currentRequest = Stapler.getCurrentRequest();
    if (currentRequest != null && StringUtils.isNotEmpty(currentRequest.getParameter("branch"))) {
        branch = currentRequest.getParameter("branch");
    }
    return this.dynamicBuildRepository.<B>getLastBuild(this, branch);
}
 
Example #16
Source File: DynamicRunPtr.java    From DotCi with MIT License 5 votes vote down vote up
public String getNearestRunUrl() {
    final
    Build r = getRun();
    if (r == null) {
        return null;
    }
    if (this.dynamicBuild.getNumber() == r.getNumber()) {
        return getShortUrl() + "/console";
    }
    return Stapler.getCurrentRequest().getContextPath() + '/' + r.getUrl();
}
 
Example #17
Source File: GitHubLink.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
@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;
}
 
Example #18
Source File: JobInfo.java    From DotCi with MIT License 5 votes vote down vote up
@Exported
public List<Build> getBuilds() {
    final StaplerRequest req = Stapler.getCurrent().getCurrentRequest();
    final String branchTab = req.getParameter("branchTab");
    final String buildCount = req.getParameter("count");
    return Lists.newArrayList(new BuildHistory(this.dynamicProject).getBuilds(branchTab, Integer.parseInt(buildCount)));
}
 
Example #19
Source File: History.java    From junit-plugin with MIT License 5 votes vote down vote up
/**
  * Graph of duration of tests over time.
  *
  * @return a graph of duration of tests over time.
  */
 public Graph getDurationGraph() {
    return new GraphImpl("seconds") {
 	   
        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 (hudson.tasks.test.TestResult o: list) {
                data.add(((double) o.getDuration()), "", new ChartLabel(o)  {
                    @Override
                    public Color getColor() {
                        if (o.getFailCount() > 0)
                            return ColorPalette.RED;
                        else if (o.getSkipCount() > 0)
                            return ColorPalette.YELLOW;
                        else
                            return ColorPalette.BLUE;
                    }
                });
            }
            return data;
        }
        
    };
 }
 
Example #20
Source File: OicSession.java    From oic-auth-plugin with MIT License 5 votes vote down vote up
/**
 * Starts the login session.
 * @return an {@link HttpResponse}
 */
@SuppressFBWarnings("J2EE_STORE_OF_NON_SERIALIZABLE_OBJECT_INTO_SESSION")
public HttpResponse doCommenceLogin() {
    // remember this in the session
    Stapler.getCurrentRequest().getSession().setAttribute(SESSION_NAME, this);
    AuthorizationCodeRequestUrl authorizationCodeRequestUrl = flow.newAuthorizationUrl().setState(state).setRedirectUri(redirectUrl);
    return new HttpRedirect(authorizationCodeRequestUrl.toString());
}
 
Example #21
Source File: APIHeadTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Iterator<String> iterator() {
    StaplerResponse response = Stapler.getCurrentResponse();
    response.setHeader("Cache-Control", "max-age=10");
    return new ArrayList<String>().iterator();
}
 
Example #22
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 #23
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 #24
Source File: GithubScmTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void getOrganizations() {
    mockStatic(Stapler.class);
    StaplerRequest staplerRequest = mock(StaplerRequest.class);
    when(Stapler.getCurrentRequest()).thenReturn(staplerRequest);

    when(staplerRequest.getParameter(CREDENTIAL_ID)).thenReturn("12345");

}
 
Example #25
Source File: GithubMockBase.java    From blueocean-plugin with MIT License 5 votes vote down vote up
protected 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("PR-demo");
    return staplerRequest;
}
 
Example #26
Source File: GithubScmContentProviderTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
private StaplerRequest mockStapler(String scmId){
    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("PR-demo");

    // GithubScmContentProvider determines SCM using apiUrl but with wiremock
    // apiUrl is localhost and not github so we use this parameter from test only to tell scm id
    when(staplerRequest.getParameter("scmId")).thenReturn(scmId);
    when(staplerRequest.getParameter("apiUrl")).thenReturn(githubApiUrl);
    return staplerRequest;
}
 
Example #27
Source File: Links.java    From blueocean-plugin with MIT License 5 votes vote down vote up
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;
}
 
Example #28
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 #29
Source File: BrowserAndOperatingSystemAnalyticsPropertiesTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
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();
}
 
Example #30
Source File: WebAppMain.java    From ezScrum with GNU General Public License v2.0 5 votes vote down vote up
public void contextInitialized(ServletContextEvent event) {
      Stapler.setRoot(event,EzScrumRoot.ezScrumRoot);
      
      /**
 * comment by Sam Huang
 * 系統跑起來便去檢查資料庫連線並且建資料庫與表格,有例外產生直接離開系統。
 */
Configuration config = new Configuration();
MantisService dbService = new MantisService(config);
if (!dbService.testAndInitDatabase()) {
	System.exit(0);
}
  }