Example usage for javax.servlet.http HttpServletRequest getRequestURL

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

Introduction

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

Prototype

public StringBuffer getRequestURL();

Source Link

Document

Reconstructs the URL the client used to make the request.

Usage

From source file:ch.gadp.alfresco.OAuthSSOAuthenticationFilter.java

protected void processNoRequestToken(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String requestUrl = req.getRequestURL().toString();
    logger.debug("processNoRequestToken requestUrl=" + requestUrl);
    OAuthService oauthService = this.getOAuthService(requestUrl);
    logger.debug("got oauthService");
    /*//from  w  w  w.j av a 2s  . c  o  m
    Token requestToken = oauthService.getRequestToken();
    req.getSession().setAttribute(ATTR_OAUTH_REQUEST_TOKEN, requestToken);
    */
    String authorizationUrl = oauthService.getAuthorizationUrl(null);
    logger.warn("Redirecting to " + authorizationUrl);
    resp.sendRedirect(authorizationUrl);
}

From source file:net.sourceforge.subsonic.ajax.PlaylistService.java

private PlaylistInfo convert(HttpServletRequest request, Player player, boolean sendM3U, int offset)
        throws Exception {
    String url = request.getRequestURL().toString();

    if (sendM3U && player.isJukebox()) {
        jukeboxService.updateJukebox(player, offset);
    }/* w w w. java 2 s  .  c o m*/
    boolean isCurrentPlayer = player.getIpAddress() != null
            && player.getIpAddress().equals(request.getRemoteAddr());

    boolean m3uSupported = player.isExternal() || player.isExternalWithPlaylist();
    sendM3U = player.isAutoControlEnabled() && m3uSupported && isCurrentPlayer && sendM3U;
    Locale locale = RequestContextUtils.getLocale(request);

    List<PlaylistInfo.Entry> entries = new ArrayList<PlaylistInfo.Entry>();
    Playlist playlist = player.getPlaylist();
    for (MediaFile file : playlist.getFiles()) {
        String albumUrl = url.replaceFirst("/dwr/.*",
                "/main.view?pathUtf8Hex=" + StringUtil.utf8HexEncode(file.getParentPath()));
        String streamUrl = url.replaceFirst("/dwr/.*", "/stream?player=" + player.getId() + "&pathUtf8Hex="
                + StringUtil.utf8HexEncode(file.getPath()));

        // Rewrite URLs in case we're behind a proxy.
        if (settingsService.isRewriteUrlEnabled()) {
            String referer = request.getHeader("referer");
            albumUrl = StringUtil.rewriteUrl(albumUrl, referer);
            streamUrl = StringUtil.rewriteUrl(streamUrl, referer);
        }

        String format = formatFormat(player, file);
        entries.add(new PlaylistInfo.Entry(file.getTrackNumber(), file.getTitle(), file.getArtist(),
                file.getAlbumName(), file.getGenre(), file.getYear(), formatBitRate(file),
                file.getDurationSeconds(), file.getDurationString(), format, formatContentType(format),
                formatFileSize(file.getFileSize(), locale), albumUrl, streamUrl));
    }
    boolean isStopEnabled = playlist.getStatus() == Playlist.Status.PLAYING && !player.isExternalWithPlaylist();
    float gain = jukeboxService.getGain();
    return new PlaylistInfo(entries, playlist.getIndex(), isStopEnabled, playlist.isRepeatEnabled(), sendM3U,
            gain);
}

From source file:ca.uhn.fhir.rest.server.IncomingRequestAddressStrategy.java

@Override
public String determineServerBase(ServletContext theServletContext, HttpServletRequest theRequest) {
    String requestFullPath = StringUtils.defaultString(theRequest.getRequestURI());

    String servletPath;//ww w .  ja  v  a  2 s . c  o  m
    if (myServletPath != null) {
        servletPath = myServletPath;
    } else {
        servletPath = StringUtils.defaultString(theRequest.getServletPath());
    }

    StringBuffer requestUrl = theRequest.getRequestURL();
    String servletContextPath = StringUtils.defaultString(theRequest.getContextPath());

    String requestPath = requestFullPath.substring(servletContextPath.length() + servletPath.length());
    if (requestPath.length() > 0 && requestPath.charAt(0) == '/') {
        requestPath = requestPath.substring(1);
    }

    int startOfPath = requestUrl.indexOf("//");
    int requestUrlLength = requestUrl.length();

    if (startOfPath != -1 && (startOfPath + 2) < requestUrlLength) {
        startOfPath = requestUrl.indexOf("/", startOfPath + 2);
    }
    if (startOfPath == -1) {
        startOfPath = 0;
    }

    int contextIndex;
    if (servletPath.length() == 0 || servletPath.equals("/")) {
        if (requestPath.length() == 0) {
            contextIndex = requestUrlLength;
        } else {
            contextIndex = requestUrl.indexOf(requestPath, startOfPath);
        }
    } else {
        //servletContextPath can start with servletPath 
        contextIndex = requestUrl.indexOf(servletPath + "/", startOfPath);
        if (contextIndex == -1) {
            contextIndex = requestUrl.indexOf(servletPath, startOfPath);
        }
    }

    String fhirServerBase;
    int length = contextIndex + servletPath.length();
    if (length > requestUrlLength) {
        length = requestUrlLength;
    }
    fhirServerBase = requestUrl.substring(0, length);
    return fhirServerBase;
}

From source file:com.bsb.cms.moss.controller.login.LoginController.java

/**
 * ???// ww  w .j a v a2s .c  o  m
 * 
 * @param request
 * @return
 */
@ResponseBody
@RequestMapping("/moss/login/treeMenu.htm")
public List<EasyUiTreeObj> getMenu(HttpServletRequest request) {
    List<SysModelDTO> modelList;
    List<EasyTreeAdapter> menus = new ArrayList<EasyUiUtils.EasyTreeAdapter>();
    List<EasyUiTreeObj> menuTrees = new ArrayList<EasyUiTreeObj>();
    String contextPath = request.getContextPath();
    log.debug(request.getRequestURL());

    try {
        modelList = MossActionUtils.getUser().getMenus();
        if (CollectionUtils.isEmpty(modelList)) {
            if (MossActionUtils.isAdmin()) {
                modelList = sysModelService.findByRoleId(null);
            } else {
                modelList = sysModelService
                        .findModelByRoleId(Long.valueOf(MossActionUtils.getUser().getSysUser().getRoleId()));
            }
            MossActionUtils.getUser().setMenus(modelList);
        }

        if (CollectionUtils.isNotEmpty(modelList)) {
            EasyTreeAdapter easyTree;
            for (SysModelDTO o : modelList) {
                easyTree = new EasyUiUtils().new EasyTreeAdapter();
                easyTree.setId(o.getSysModelId());
                easyTree.setNodeName(o.getModelName());
                easyTree.setParentId(o.getParentId());
                easyTree.setType(o.getType());
                easyTree.setHtmlA(EasyUiUtils.getHref(o.getModelName(), o.getUrl(), contextPath, null));

                menus.add(easyTree);
            }
        }
        menuTrees = EasyUiUtils.getLeftMenu(menus, contextPath);
    } catch (Exception e) {
        e.printStackTrace();
        log.error(e.getMessage());
    }

    return menuTrees;
}

From source file:org.jamwiki.servlets.RecentChangesFeedServlet.java

/**
 * TODO cache feed to avoid high load caused by RSS aggregators
 *
 * @throws Exception/*from w w  w.j a v  a 2 s. co  m*/
 */
private SyndFeed getFeed(HttpServletRequest request) throws Exception {
    List<RecentChange> changes = getChanges(request);
    SyndFeed feed = new SyndFeedImpl();
    feed.setEncoding(FEED_ENCODING);
    feed.setTitle(Environment.getValue(Environment.PROP_RSS_TITLE));
    StringBuffer requestURL = request.getRequestURL();
    String feedURL = feedUrlPrefix
            + requestURL.substring(0, requestURL.length() - WikiUtil.getTopicFromURI(request).length());
    feed.setLink(feedURL);
    feed.setDescription("List of the last " + changes.size() + " changed wiki pages.");
    boolean includeMinorEdits = ServletRequestUtils.getBooleanParameter(request, MINOR_EDITS,
            defaultIncludeMinorEdits);
    boolean linkToVersion = ServletRequestUtils.getBooleanParameter(request, LINK_TO_VERSION,
            defaultLinkToVersion);
    feed.setEntries(getFeedEntries(changes, includeMinorEdits, linkToVersion, feedURL));
    return feed;
}

From source file:com.googlesource.gerrit.plugins.github.oauth.OAuthGitFilter.java

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

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = new OAuthGitWrappedResponse((HttpServletResponse) response);
    GitHubLogin ghLogin = ghLoginProvider.get(httpRequest);
    log.debug("OAuthGitFilter(" + httpRequest.getRequestURL() + ") ghLogin=" + ghLogin);

    String username = getAuthenticatedUserFromGitRequestUsingOAuthToken(httpRequest, httpResponse);
    if (username != null) {
        String gerritPassword = accountCache.getByUsername(username).getPassword(username);

        if (gerritPassword == null) {
            gerritPassword = generateRandomGerritPassword(username, httpRequest, httpResponse, chain);
            if (Strings.isNullOrEmpty(gerritPassword)) {
                httpResponse.sendError(SC_FORBIDDEN, "Unable to generate Gerrit password for Git Basic-Auth");
            } else {
                httpResponse.sendRedirect(getRequestPathWithQueryString(httpRequest));
            }/*from ww w  .j  a  v  a2s .  c  o m*/
            return;
        }

        httpRequest = new BasicAuthHttpRequest(httpRequest, username, gerritPassword);
    }

    chain.doFilter(httpRequest, httpResponse);
}

From source file:com.versatus.jwebshield.filter.SecurityFilter.java

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

    // Assume its HTTP
    HttpServletRequest httpReq = (HttpServletRequest) request;

    String reqInfo = "J-WebShield Alert: CSRF attack detected! request URL="
            + httpReq.getRequestURL().toString() + "| from IP address=" + httpReq.getRemoteAddr();

    logger.debug("doFilter: IP address=" + httpReq.getRemoteAddr());
    logger.debug("doFilter: pathInfo=" + httpReq.getPathInfo());
    logger.debug("doFilter: queryString=" + httpReq.getQueryString());
    logger.debug("doFilter: requestURL=" + httpReq.getRequestURL().toString());
    logger.debug("doFilter: method=" + httpReq.getMethod());
    logger.debug("doFilter: Origin=" + httpReq.getHeader("Origin"));
    logger.info("doFilter: Referer=" + httpReq.getHeader("Referer"));
    logger.info("doFilter: " + csrfHeaderName + "=" + httpReq.getHeader(csrfHeaderName));

    UrlExclusionList exclList = (UrlExclusionList) request.getServletContext()
            .getAttribute(SecurityConstant.CSRF_CHECK_URL_EXCL_LIST_ATTR_NAME);
    HttpSession session = httpReq.getSession(false);
    if (session == null) {
        chain.doFilter(request, response);
        return;// ww  w  . ja  v a  2s.c  o m
    }

    logger.debug("doFilter: matching " + httpReq.getRequestURI() + " to exclusions list "
            + exclList.getExclusionMap());

    try {
        if (!exclList.isEmpty() && exclList.isMatch(httpReq.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }
    } catch (Exception e) {
        logger.error("doFilter", e);
    }
    // check CSRF cookie/header
    boolean csrfHeaderPassed = false;
    String rawCsrfHeaderVal = httpReq.getHeader(csrfHeaderName);
    if (useCsrfToken && StringUtils.isNotBlank(rawCsrfHeaderVal)) {
        String csrfHeader = StringUtils.strip(httpReq.getHeader(csrfHeaderName), "\"");
        logger.debug("doFilter: csrfHeader after decoding" + csrfHeader);
        Cookie[] cookies = httpReq.getCookies();
        for (Cookie c : cookies) {
            String name = c.getName();

            if (StringUtils.isNotBlank(csrfCookieName) && csrfCookieName.equals(name)) {

                logger.debug("doFilter: cookie domain=" + c.getDomain() + "|name=" + name + "|value="
                        + c.getValue() + "|path=" + c.getPath() + "|maxage=" + c.getMaxAge() + "|httpOnly="
                        + c.isHttpOnly());

                logger.debug("doFilter: string comp:" + StringUtils.difference(csrfHeader, c.getValue()));

                if (StringUtils.isNotBlank(csrfHeader) && csrfHeader.equals(c.getValue())) {

                    csrfHeaderPassed = true;
                    logger.info("Header " + csrfHeaderName + " value matches the cookie " + csrfCookieName);
                    break;
                } else {
                    logger.info(
                            "Header " + csrfHeaderName + " value does not match the cookie " + csrfCookieName);
                }
            }

        }
        // String csrfCookieVal = (String) session
        // .getAttribute(SecurityConstant.CSRFCOOKIE_VALUE_PARAM);
        // if (csrfCookieVal != null && csrfCookieVal.equals(csrfHeader)) {
        // // chain.doFilter(request, response);
        // // return;
        // csrfHeaderPassed = true;
        // } else {
        // // logger.info(reqInfo);
        // // sendSecurityReject(response);
        // }
    }

    if (useCsrfToken && csrfHeaderPassed) {
        chain.doFilter(request, response);
        return;
    }

    // Validate that the salt is in the cache
    Cache<SecurityInfo, SecurityInfo> csrfPreventionSaltCache = (Cache<SecurityInfo, SecurityInfo>) httpReq
            .getSession().getAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME);

    if (csrfPreventionSaltCache != null) {
        // Get the salt sent with the request
        String saltName = (String) httpReq.getSession().getAttribute(SecurityConstant.SALT_PARAM_NAME);

        logger.debug("doFilter: csrf saltName=" + saltName);

        if (saltName != null) {

            String salt = httpReq.getParameter(saltName);

            logger.debug("doFilter: csrf salt=" + salt);

            if (salt != null) {

                SecurityInfo si = new SecurityInfo(saltName, salt);

                logger.debug("doFilter: csrf token=" + csrfPreventionSaltCache.getIfPresent(si));

                SecurityInfo cachedSi = csrfPreventionSaltCache.getIfPresent(si);
                if (cachedSi != null) {
                    // csrfPreventionSaltCache.invalidate(si);
                    if (SecurityTokenFilter.checkReferer) {
                        String refHeader = StringUtils.defaultString(httpReq.getHeader("Referer"));
                        logger.debug("doFilter: refHeader=" + refHeader);
                        if (StringUtils.isNotBlank(refHeader)) {
                            try {
                                URL refUrl = new URL(refHeader);
                                refHeader = refUrl.getHost();
                            } catch (MalformedURLException mex) {
                                logger.debug("doFilter: parsing referer header failed", mex);
                            }
                        }
                        if (!cachedSi.getRefererHost().isEmpty()
                                && !refHeader.equalsIgnoreCase(cachedSi.getRefererHost())) {
                            logger.info("Potential CSRF detected - Referer host does not match orignal! "
                                    + refHeader + " != " + cachedSi.getRefererHost());
                            sendSecurityReject(response);
                        }
                    }

                    chain.doFilter(request, response);
                } else {
                    logger.info(reqInfo);
                    sendSecurityReject(response);
                }
            } else if (httpMethodMatch(httpReq.getMethod())) {
                // let flow through
                chain.doFilter(request, response);
            } else {
                logger.info(reqInfo);
                sendSecurityReject(response);
            }
        }
    } else {
        chain.doFilter(request, response);
    }

}

From source file:org.realityforge.proxy_servlet.AbstractProxyServlet.java

/**
 * For a redirect response from the target server, this translates {@code theUrl} to redirect to
 * and translates it to one the original client can use.
 *//*from ww w .j  a v a  2  s. co m*/
private String rewriteUrlFromResponse(final HttpServletRequest servletRequest, final String url) {
    if (url.startsWith(_target)) {
        String curUrl = servletRequest.getRequestURL().toString(); //no query
        final String pathInfo = servletRequest.getPathInfo();
        if (null != pathInfo) {
            assert curUrl.endsWith(pathInfo);
            //take pathInfo off
            curUrl = curUrl.substring(0, curUrl.length() - pathInfo.length());
        }
        return curUrl + url.substring(_target.length());
    } else {
        return url;
    }
}

From source file:br.com.mv.modulo.web.ExceptionController.java

@ExceptionHandler(Exception.class)
@RequestMapping("/exception")
public ModelAndView handleException(HttpServletRequest req, Exception e) throws Exception {
    log.trace("Exceo capturada:", e);
    e.printStackTrace();//  w  ww. j av  a  2s  .  co m
    if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
        throw e;
    }

    ModelAndView mav = new ModelAndView("exception");
    mav.addObject("exception", e);
    exception = e;

    mav.addObject("timestamp", new Date());
    mav.addObject("url", req.getRequestURL());
    mav.addObject("status", 500);
    return mav;
}

From source file:com.sonicle.webtop.core.app.servlet.Login.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean redirect = false;

    if (logger.isTraceEnabled()) {
        logger.trace("X-REQUEST-URI: {}", request.getHeader("X-REQUEST-URI"));
        logger.trace("requestUrl: {}", request.getRequestURL().toString());
        logger.trace("pathInfo: {}", request.getPathInfo());
        logger.trace("baseUrl: {}", getBaseUrl(request));
        logger.trace("forwardServletPath: {}", getRequestForwardServletPath(request));
    }/*from  w  ww. ja  v a2s . co  m*/

    if (ServletUtils.isForwarded(request)) {
        String forwardServletPath = getRequestForwardServletPath(request);
        if (StringUtils.startsWithIgnoreCase(forwardServletPath, Login.URL)
                || StringUtils.startsWithIgnoreCase(forwardServletPath, Logout.URL)) {
            redirect = true;
        }
        if (StringUtils.startsWithIgnoreCase(forwardServletPath, PushEndpoint.URL)) {
            WebUtils.getAndClearSavedRequest(request);
            redirect = true;
        }
    } else {
        String requestUrl = request.getRequestURL().toString();
        if (StringUtils.endsWithIgnoreCase(requestUrl, Login.URL)) {
            redirect = true;
        }
    }

    if (redirect) {
        WebUtils.issueRedirect(request, response, "/");
    } else {
        super.doGet(request, response);
    }
}