Example usage for javax.servlet.http HttpServletRequest getRequestURI

List of usage examples for javax.servlet.http HttpServletRequest getRequestURI

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getRequestURI.

Prototype

public String getRequestURI();

Source Link

Document

Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request.

Usage

From source file:alpine.filters.WhitelistUrlFilter.java

/**
 * Check for allowed URLs being requested.
 *
 * @param request The request object.//ww w. j a v  a  2 s  .  c  o m
 * @param response The response object.
 * @param chain Refers to the {@code FilterChain} object to pass control to the next {@code Filter}.
 * @throws IOException a IOException
 * @throws ServletException a ServletException
 */
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {

    final HttpServletRequest req = (HttpServletRequest) request;
    final HttpServletResponse res = (HttpServletResponse) response;

    final String requestUri = req.getRequestURI();
    if (requestUri != null) {
        boolean allowed = false;
        for (String url : allowUrls) {
            if (requestUri.equals("/")) {
                if (url.trim().equals("/")) {
                    allowed = true;
                }
            } else if (requestUri.startsWith(url.trim())) {
                allowed = true;
            }
        }
        if (!allowed) {
            res.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
    }
    chain.doFilter(request, response);
}

From source file:com.adeptj.modules.oauth.http.OAuthCallbackServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String code = req.getParameter("code");
    LOGGER.info("OAuth2 code: [{}]", code);
    String provider = StringUtils.substringAfterLast(req.getRequestURI(), "/");
    LOGGER.info("Provider: [{}]", provider);
    OAuth20Service oAuth2Service = this.providerFactory.getOAuth2Service(provider);
    OAuth2AccessToken token = null;//from  w  w  w  . j a  va  2s . c  om
    try {
        token = oAuth2Service.getAccessToken(code);
        LOGGER.info("OAuth2AccessToken: [{}]", token);
        OAuthRequest oReq = new OAuthRequest(Verb.GET, "https://api.linkedin.com/v1/people/~?format=json");
        oAuth2Service.signRequest(token, oReq);
        Response oResp = oAuth2Service.execute(oReq);
        LOGGER.info("Linkedin Profile: [{}]", oResp.getBody());
        resp.getOutputStream().write(oResp.getBody().getBytes(StandardCharsets.UTF_8));
    } catch (InterruptedException | ExecutionException ex) {
    }
}

From source file:com.excella.deploy.agent.core.DynamicCommandServlet.java

/**
 * {@inheritDoc}/*from   ww w.ja v  a 2 s  . co  m*/
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.info("Recieved command over http [" + request.getRequestURI() + "]");
    String argument = grabArguments(request);
    Command command = findCommand(request);
    try {
        success(command.execute(argument), request, response);
    } catch (Exception e) {
        fail(command, e, request, response);
    }
}

From source file:com.google.sampling.experiential.server.MigrationBackendServlet.java

private void redirectUserToLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
}

From source file:com.qcadoo.view.internal.controllers.FileResolverController.java

@RequestMapping(value = "{tenantId:\\d+}/{firstLevel:\\d+}/{secondLevel:\\d+}/{fileName}", method = RequestMethod.GET)
public void resolve(final HttpServletRequest request, final HttpServletResponse response,
        @PathVariable("tenantId") final String tenantId) {
    String path = fileService.getPathFromUrl(request.getRequestURI());

    boolean removeFileAfterProcessing = request.getParameterMap().containsKey("clean");

    if (Integer.valueOf(tenantId) != MultiTenantUtil.getCurrentTenantId()) {
        try {//from  w ww. j a  va2  s . com
            response.sendRedirect("/error.html?code=404");
        } catch (IOException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }

    InputStream input = null;

    try {
        input = fileService.getInputStream(path);

        if (input == null) {
            response.sendRedirect("/error.html?code=404");
        } else {
            OutputStream output = response.getOutputStream();

            int bytes = IOUtils.copy(input, output);

            response.setHeader("Content-disposition", "inline; filename=" + fileService.getName(path));
            response.setContentType(fileService.getContentType(path));
            response.setContentLength(bytes);

            output.flush();
        }
    } catch (IOException e) {
        IOUtils.closeQuietly(input);
        throw new IllegalStateException(e.getMessage(), e);
    }

    if (removeFileAfterProcessing) {
        fileService.remove(path);
    }
}

From source file:info.magnolia.cms.filters.HostSecurityFilter.java

@Override
public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    String uri = request.getRequestURI();
    String host = request.getServerName();
    Boolean isHostValid = null;//from   ww  w . j  a  v  a 2s. c  om

    for (String[] mapping : uriToHost) {
        if (uri.startsWith(mapping[0])) {
            // set to false only if exist at least one matching pattern
            if (isHostValid == null) {
                isHostValid = false;
            }
            // url allowed on this host
            if (host.endsWith(mapping[1])) {
                isHostValid = true;
                break;
            }

        }
    }
    if (isHostValid != null && !isHostValid.booleanValue()) {
        response.setStatus(404);
        return;
    }

    chain.doFilter(request, response);

}

From source file:com.yahoo.dba.perf.myperf.springmvc.SigninController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse resp)
        throws Exception {
    logger.info("receive url path: " + request.getContextPath() + "," + request.getRequestURI() + ", "
            + request.getServletPath() + ", parameters: " + request.getQueryString());
    boolean failed = false;
    String username = request.getParameter("name");
    if (username != null) {
        username = username.trim().toLowerCase();
        //find the user from the system cache
        AppUser appUser = this.frameworkContext.getAuth().findUserByName(username);

        //sign in process
        boolean authed = this.frameworkContext.getAuth().login(appUser, request);

        if (authed)//display
        {/*  w  w  w . j av  a 2 s  .  co m*/
            String view = getLoginSuccessView();
            //if admin user, and setup not done yet, send to setup.
            if (appUser.isAdminUser() && !frameworkContext.getMyperfConfig().isConfigured())
                view = this.getSetupView();
            logger.info(appUser.getName() + " login, redirect to " + view);
            return new ModelAndView(new RedirectView(view));
        } //if(appUser!=null && appUser.match(request.getParameter("pd"))
        else {
            failed = true;
        }
    } //if(username!=null)

    //not authenticated? Try again
    //TODO add retry count
    long server_ts = System.currentTimeMillis();
    int seed = (int) (Math.random() * Integer.MAX_VALUE);
    ModelAndView mv = new ModelAndView(getLoginFormView());
    mv.addObject("name", username);
    if (failed)
        mv.addObject("message", DEFAULT_ERROR);
    mv.addObject("help_key", "start");
    mv.addObject("server_ts", server_ts);
    mv.addObject("ars", seed);//ars: authentication random seed
    //add store them in session
    request.getSession(true).setAttribute(AppUser.SERVER_TS, new Long(server_ts));
    request.getSession().setAttribute(AppUser.RANDOM_SEED, new Integer(seed));

    return mv;
}

From source file:de.digiway.rapidbreeze.client.infrastructure.cnl.ClickAndLoadHandler.java

private void handlePost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String requestURI = request.getRequestURI();
    switch (requestURI) {
    case ADD_LINKS_URI:
        if (addLinks(request)) {
            try (PrintWriter writer = response.getWriter()) {
                writer.write("success");
            }/*from w  w w.j  a  v a2 s.com*/
        }
        break;
    default:
        response.sendError(Response.SC_NOT_FOUND);
        break;
    }
}

From source file:com.consol.citrus.admin.web.ProjectSetupInterceptor.java

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    if (projectService.getActiveProject() == null
            && !request.getRequestURI().startsWith(request.getContextPath() + redirect)
            && !request.getRequestURI().startsWith(redirect)
            && !isExcluded(request.getRequestURI(), request.getContextPath())) {
        log.debug("Intercept " + request.getRequestURI() + " as project home is not set properly");
        log.debug("Redirecting to " + request.getContextPath() + redirect);
        response.sendRedirect(request.getContextPath() + redirect);
        return false;
    }//from   w  ww  .j  a v  a 2  s  . c  om

    return true;
}

From source file:net.solarnetwork.node.setup.web.SolarInHttpProxy.java

/**
 * Proxy an HTTP request to SolarIn and return the result on a given HTTP
 * response./*ww w .  j  a  v a  2 s  .c o m*/
 * 
 * @param request
 *        the request to proxy
 * @param response
 *        the response to return the proxy response to
 * @throws IOException
 *         if an IO error occurs
 */
@RequestMapping(value = { "/api/v1/sec/location", "/api/v1/sec/location/price",
        "/api/v1/sec/location/weather" }, method = RequestMethod.GET)
public void proxy(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String context = request.getContextPath();
    String path = request.getRequestURI();
    if (path.startsWith(context)) {
        path = path.substring(context.length());
    }
    String query = request.getQueryString();
    String url = getIdentityService().getSolarInBaseUrl() + path;
    if (query != null) {
        url += '?' + query;
    }
    String accept = request.getHeader("Accept");
    if (accept == null) {
        accept = ACCEPT_JSON;
    }
    try {
        URLConnection conn = getURLConnection(url, request.getMethod(), accept);
        if (conn instanceof HttpURLConnection) {
            final HttpURLConnection httpConn = (HttpURLConnection) conn;
            for (Map.Entry<String, List<String>> me : httpConn.getHeaderFields().entrySet()) {
                final String headerName = me.getKey();
                if (headerName == null) {
                    continue;
                }
                for (String val : me.getValue()) {
                    response.addHeader(headerName, val);
                }
            }
            final String msg = httpConn.getResponseMessage();
            if (msg != null && !msg.equalsIgnoreCase("OK")) {
                response.sendError(httpConn.getResponseCode(), msg);
            } else {
                response.setStatus(httpConn.getResponseCode());
            }
        }
        FileCopyUtils.copy(conn.getInputStream(), response.getOutputStream());
        response.flushBuffer();
    } catch (IOException e) {
        log.debug("Error proxying SolarIn URL [{}]", url, e);
        response.sendError(502, "Problem communicating with SolarIn: " + e.getMessage());
    }
}