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:info.magnolia.module.servletsanity.support.ServletAssert.java

public static void printRequestInfo(HttpServletRequest request, HttpServletResponse response, String location)
        throws IOException {
    append("");/*  w  ww .  j a v  a 2  s. c  o m*/
    append("");
    append("###################################");
    append("##");
    append("## " + location);
    append("##");
    append("##############");
    append("");

    appendRequestChain(request);

    appendResponseChain(response);

    append("Path elements:");
    append("    RequestUri  = " + request.getRequestURI());
    append("    ContextPath = " + request.getContextPath());
    append("    ServletPath = " + request.getServletPath());
    append("    PathInfo    = " + request.getPathInfo());
    append("    QueryString = " + request.getQueryString());
    String x = request.getContextPath() + request.getServletPath()
            + StringUtils.defaultString(request.getPathInfo());
    if (!request.getRequestURI().equals(x)) {
        append("ERROR RequestURI is [" + request.getRequestURI() + "] according to spec it should be [" + x
                + "]");
    } else {
        append("    Request path elements are in sync (requestURI = contextPath + servletPath + pathInfo) (SRV 3.4)");
    }
    append("");

    append("Forward attributes:");
    printAttribute(request, "javax.servlet.forward.request_uri");
    printAttribute(request, "javax.servlet.forward.context_path");
    printAttribute(request, "javax.servlet.forward.servlet_path");
    printAttribute(request, "javax.servlet.forward.path_info");
    printAttribute(request, "javax.servlet.forward.query_string");
    append("");

    append("Include attributes:");
    printAttribute(request, "javax.servlet.include.request_uri");
    printAttribute(request, "javax.servlet.include.context_path");
    printAttribute(request, "javax.servlet.include.servlet_path");
    printAttribute(request, "javax.servlet.include.path_info");
    printAttribute(request, "javax.servlet.include.query_string");
    append("");
}

From source file:ru.org.linux.csrf.CSRFProtectionService.java

/**
 * Check if user is authorized for request
 * @param request/*ww  w. j  a  va  2s. co m*/
 * @return true when ok, false when not authorized
 */
public static boolean checkCSRF(HttpServletRequest request) {
    String cookieValue = (String) request.getAttribute(CSRF_ATTRIBUTE);

    if (Strings.isNullOrEmpty(cookieValue)) {
        logger.info("Missing CSRF cookie");
        return false;
    }

    String inputValue = request.getParameter(CSRF_INPUT_NAME);

    if (Strings.isNullOrEmpty(inputValue)) {
        logger.info("Missing CSRF input");
        return false;
    }

    boolean r = inputValue.trim().equals(cookieValue.trim());

    if (!r) {
        logger.info(String.format("Flood protection (CSRF cookie differs: cookie=%s param=%s) ip=%s url=%s",
                cookieValue, inputValue, request.getRemoteAddr(), request.getRequestURI()));
    }

    return r;
}

From source file:ch.entwine.weblounge.common.impl.language.LanguageUtils.java

/**
 * Returns the preferred one out of of those languages that are requested by
 * the client through the <code>Accept-Language</code> header and are
 * supported by both the resource in that there is resource content in that
 * language and the site.//  w ww  .  j  a v a 2 s .c  o m
 * <p>
 * The preferred one is defined by the following priorities:
 * <ul>
 * <li>Requested by the client</li>
 * <li>The resource's original language</li>
 * <li>The site default language</li>
 * <li>The first language of what is supported by both the resource and the
 * site</li>
 * </ul>
 * 
 * @param resource
 *          the resource
 * @param request
 *          the http request
 * @param site
 *          the site
 */
public static Language getPreferredContentLanguage(Resource<?> resource, HttpServletRequest request,
        Site site) {

    if (resource == null)
        throw new IllegalArgumentException("Resource must not be null");

    // Path
    String[] pathElements = StringUtils.split(request.getRequestURI(), "/");
    for (String element : pathElements) {
        for (Language l : resource.contentLanguages()) {
            if (l.getIdentifier().equals(element)) {
                return l;
            }
        }
    }

    // Accept-Language header
    if (request.getHeader("Accept-Language") != null) {
        Enumeration<?> locales = request.getLocales();
        while (locales.hasMoreElements()) {
            try {
                Language l = getLanguage((Locale) locales.nextElement());
                if (l == null)
                    continue;
                if (!resource.supportsContentLanguage(l))
                    continue;
                if (!site.supportsLanguage(l))
                    continue;
                return l;
            } catch (UnknownLanguageException e) {
                // never mind, some clients will send stuff like "*" as the locale
            }
        }
    }

    // Original content
    if (resource.getOriginalContent() != null) {
        if (site.supportsLanguage(resource.getOriginalContent().getLanguage()))
            return resource.getOriginalContent().getLanguage();
    }

    // Site default language
    if (resource.supportsContentLanguage(site.getDefaultLanguage())) {
        return site.getDefaultLanguage();
    }

    // Any match
    for (Language l : site.getLanguages()) {
        if (resource.supportsContentLanguage(l)) {
            return l;
        }
    }

    return null;
}

From source file:com.jpeterson.littles3.S3ObjectRequest.java

/**
 * Create an <code>S3Object</code> based on the request supporting virtual
 * hosting of buckets.//from   www .  j  ava 2s . co  m
 * 
 * @param req
 *            The original request.
 * @param baseHost
 *            The <code>baseHost</code> is the HTTP Host header that is
 *            "expected". This is used to help determine how the bucket name
 *            will be interpreted. This is used to implement the "Virtual
 *            Hosting of Buckets".
 * @param authenticator
 *            The authenticator to use to authenticate this request.
 * @return An object initialized from the request.
 * @throws IllegalArgumentException
 *             Invalid request.
 */
@SuppressWarnings("unchecked")
public static S3ObjectRequest create(HttpServletRequest req, String baseHost, Authenticator authenticator)
        throws IllegalArgumentException, AuthenticatorException {
    S3ObjectRequest o = new S3ObjectRequest();
    String pathInfo = req.getPathInfo();
    String contextPath = req.getContextPath();
    String requestURI = req.getRequestURI();
    String undecodedPathPart = null;
    int pathInfoLength;
    String requestURL;
    String serviceEndpoint;
    String bucket = null;
    String key = null;
    String host;
    String value;
    String timestamp;

    baseHost = baseHost.toLowerCase();

    host = req.getHeader("Host");
    if (host != null) {
        host = host.toLowerCase();
    }

    try {
        requestURL = URLDecoder.decode(req.getRequestURL().toString(), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // should never happen
        e.printStackTrace();
        IllegalArgumentException t = new IllegalArgumentException("Unsupport encoding: UTF-8");
        t.initCause(e);
        throw t;
    }

    if (!requestURL.endsWith(pathInfo)) {
        String m = "requestURL [" + requestURL + "] does not end with pathInfo [" + pathInfo + "]";
        throw new IllegalArgumentException(m);
    }

    pathInfoLength = pathInfo.length();

    serviceEndpoint = requestURL.substring(0, requestURL.length() - pathInfoLength);

    if (debug) {
        System.out.println("---------------");
        System.out.println("requestURI: " + requestURI);
        System.out.println("serviceEndpoint: " + serviceEndpoint);
        System.out.println("---------------");
    }

    if ((host == null) || // http 1.0 form
            (host.equals(baseHost))) { // ordinary method
        // http 1.0 form
        // bucket first part of path info
        // key second part of path info
        if (pathInfoLength > 1) {
            int index = pathInfo.indexOf('/', 1);
            if (index > -1) {
                bucket = pathInfo.substring(1, index);

                if (pathInfoLength > (index + 1)) {
                    key = pathInfo.substring(index + 1);
                    undecodedPathPart = requestURI.substring(contextPath.length() + 1 + bucket.length(),
                            requestURI.length());
                }
            } else {
                bucket = pathInfo.substring(1);
            }
        }
    } else if (host.endsWith("." + baseHost)) {
        // bucket prefix of host
        // key is path info
        bucket = host.substring(0, host.length() - 1 - baseHost.length());
        if (pathInfoLength > 1) {
            key = pathInfo.substring(1);
            undecodedPathPart = requestURI.substring(contextPath.length(), requestURI.length());
        }
    } else {
        // bucket is host
        // key is path info
        bucket = host;
        if (pathInfoLength > 1) {
            key = pathInfo.substring(1);
            undecodedPathPart = requestURI.substring(contextPath.length(), requestURI.length());
        }
    }

    // timestamp
    timestamp = req.getHeader("Date");

    // CanonicalizedResource
    StringBuffer canonicalizedResource = new StringBuffer();

    canonicalizedResource.append('/');
    if (bucket != null) {
        canonicalizedResource.append(bucket);
    }
    if (undecodedPathPart != null) {
        canonicalizedResource.append(undecodedPathPart);
    }
    if (req.getParameter(PARAMETER_ACL) != null) {
        canonicalizedResource.append("?").append(PARAMETER_ACL);
    }

    // CanonicalizedAmzHeaders
    StringBuffer canonicalizedAmzHeaders = new StringBuffer();
    Map<String, String> headers = new TreeMap<String, String>();
    String headerName;
    String headerValue;

    for (Enumeration headerNames = req.getHeaderNames(); headerNames.hasMoreElements();) {
        headerName = ((String) headerNames.nextElement()).toLowerCase();

        if (headerName.startsWith("x-amz-")) {
            for (Enumeration headerValues = req.getHeaders(headerName); headerValues.hasMoreElements();) {
                headerValue = (String) headerValues.nextElement();
                String currentValue = headers.get(headerValue);

                if (currentValue != null) {
                    // combine header fields with the same name
                    headers.put(headerName, currentValue + "," + headerValue);
                } else {
                    headers.put(headerName, headerValue);
                }

                if (headerName.equals("x-amz-date")) {
                    timestamp = headerValue;
                }
            }
        }
    }

    for (Iterator<String> iter = headers.keySet().iterator(); iter.hasNext();) {
        headerName = iter.next();
        headerValue = headers.get(headerName);
        canonicalizedAmzHeaders.append(headerName).append(":").append(headerValue).append("\n");
    }

    StringBuffer stringToSign = new StringBuffer();

    stringToSign.append(req.getMethod()).append("\n");
    value = req.getHeader("Content-MD5");
    if (value != null) {
        stringToSign.append(value);
    }
    stringToSign.append("\n");
    value = req.getHeader("Content-Type");
    if (value != null) {
        stringToSign.append(value);
    }
    stringToSign.append("\n");
    value = req.getHeader("Date");
    if (value != null) {
        stringToSign.append(value);
    }
    stringToSign.append("\n");
    stringToSign.append(canonicalizedAmzHeaders);
    stringToSign.append(canonicalizedResource);

    if (debug) {
        System.out.println(":v:v:v:v:");
        System.out.println("undecodedPathPart: " + undecodedPathPart);
        System.out.println("canonicalizedAmzHeaders: " + canonicalizedAmzHeaders);
        System.out.println("canonicalizedResource: " + canonicalizedResource);
        System.out.println("stringToSign: " + stringToSign);
        System.out.println(":^:^:^:^:");
    }

    o.setServiceEndpoint(serviceEndpoint);
    o.setBucket(bucket);
    o.setKey(key);
    try {
        if (timestamp == null) {
            o.setTimestamp(null);
        } else {
            o.setTimestamp(DateUtil.parseDate(timestamp));
        }
    } catch (DateParseException e) {
        o.setTimestamp(null);
    }
    o.setStringToSign(stringToSign.toString());
    o.setRequestor(authenticate(req, o));

    return o;
}

From source file:org.itracker.web.util.LoginUtilities.java

public static boolean checkAutoLogin(HttpServletRequest request, boolean allowSaveLogin) {
    boolean foundLogin = false;

    if (request != null) {
        int authType = getRequestAuthType(request);

        // Check for auto login in request
        if (authType == AuthenticationConstants.AUTH_TYPE_REQUEST) {
            String redirectURL = request.getRequestURI().substring(request.getContextPath().length())
                    + (request.getQueryString() != null ? "?" + request.getQueryString() : "");
            request.setAttribute(Constants.AUTH_TYPE_KEY, AuthenticationConstants.AUTH_TYPE_REQUEST);
            request.setAttribute(Constants.AUTH_REDIRECT_KEY, redirectURL);
            request.setAttribute("processLogin", "true");
            foundLogin = true;//from  ww w .j  a  v a2  s  . com

        }

        // Add in check for client certs

        // Check for auto login with cookies, this will only happen if users
        // are allowed to save
        // their logins to cookies
        if (allowSaveLogin && !foundLogin) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (Constants.COOKIE_NAME.equals(cookie.getName())) {
                        int seperator = cookie.getValue().indexOf('~');
                        final String login;
                        if (seperator > 0) {
                            login = cookie.getValue().substring(0, seperator);
                            if (logger.isDebugEnabled()) {
                                logger.debug("Attempting autologin for user " + login + ".");
                            }

                            String redirectURL = request.getRequestURI()
                                    .substring(request.getContextPath().length())
                                    + (request.getQueryString() != null ? "?" + request.getQueryString() : "");
                            request.setAttribute(Constants.AUTH_LOGIN_KEY,
                                    cookie.getValue().substring(0, seperator));
                            request.setAttribute(Constants.AUTH_TYPE_KEY,
                                    AuthenticationConstants.AUTH_TYPE_PASSWORD_ENC);

                            request.setAttribute(Constants.AUTH_VALUE_KEY,
                                    cookie.getValue().substring(seperator + 1));
                            request.setAttribute(Constants.AUTH_REDIRECT_KEY, redirectURL);
                            request.setAttribute("processLogin", "true");
                            foundLogin = true;
                        }
                    }
                }
            }
        }

    }

    return foundLogin;
}

From source file:org.impalaframework.extension.mvc.util.RequestModelHelper.java

/**
 * /*from w w w.  jav  a  2s .  co m*/
 * @param logger
 * @param request
 */
public static void maybeDebugRequest(Log logger, HttpServletRequest request) {

    if (logger.isDebugEnabled()) {

        logger.debug("#####################################################################################");
        logger.debug("---------------------------- Request details ---------------------------------------");
        logger.debug("Request context path: " + request.getContextPath());
        logger.debug("Request path info: " + request.getPathInfo());
        logger.debug("Request path translated: " + request.getPathTranslated());
        logger.debug("Request query string: " + request.getQueryString());
        logger.debug("Request servlet path: " + request.getServletPath());
        logger.debug("Request request URI: " + request.getRequestURI());
        logger.debug("Request request URL: " + request.getRequestURL());
        logger.debug("Request session ID: " + request.getRequestedSessionId());

        logger.debug("------------------------------------------------ ");
        logger.debug("Parameters ------------------------------------- ");
        final Enumeration<String> parameterNames = request.getParameterNames();

        Map<String, String> parameters = new TreeMap<String, String>();

        while (parameterNames.hasMoreElements()) {
            String name = parameterNames.nextElement();
            String value = request.getParameter(name);
            final String lowerCase = name.toLowerCase();
            if (lowerCase.contains("password") || lowerCase.contains("cardnumber")) {
                value = "HIDDEN";
            }
            parameters.put(name, value);
        }

        //now output            
        final Set<String> parameterKeys = parameters.keySet();
        for (String key : parameterKeys) {
            logger.debug(key + ": " + parameters.get(key));
        }

        logger.debug("------------------------------------------------ ");

        Map<String, Object> attributes = new TreeMap<String, Object>();

        logger.debug("Attributes ------------------------------------- ");
        final Enumeration<String> attributeNames = request.getAttributeNames();
        while (attributeNames.hasMoreElements()) {
            String name = attributeNames.nextElement();
            Object value = request.getAttribute(name);
            final String lowerCase = name.toLowerCase();
            if (lowerCase.contains("password") || lowerCase.contains("cardnumber")) {
                value = "HIDDEN";
            }
            attributes.put(name, value);
        }

        //now output
        final Set<String> keys = attributes.keySet();
        for (String name : keys) {
            Object value = attributes.get(name);
            logger.debug(name + ": " + (value != null ? value.toString() : value));
        }

        logger.debug("------------------------------------------------ ");
        logger.debug("#####################################################################################");
    } else {
        if (logger.isInfoEnabled()) {
            logger.info(
                    "#####################################################################################");
            logger.info("Request query string: " + request.getQueryString());
            logger.info("Request request URI: " + request.getRequestURI());
            logger.info(
                    "#####################################################################################");
        }
    }
}

From source file:com.google.appengine.tools.mapreduce.MapReduceServletTest.java

private static HttpServletRequest createMockRequest(String handler, boolean taskQueueRequest,
        boolean ajaxRequest) {
    HttpServletRequest request = createMock(HttpServletRequest.class);
    if (taskQueueRequest) {
        expect(request.getHeader("X-AppEngine-QueueName")).andReturn("default").anyTimes();
    } else {//from ww w. j a  v  a2s .co  m
        expect(request.getHeader("X-AppEngine-QueueName")).andReturn(null).anyTimes();
    }
    if (ajaxRequest) {
        expect(request.getHeader("X-Requested-With")).andReturn("XMLHttpRequest").anyTimes();
    } else {
        expect(request.getHeader("X-Requested-With")).andReturn(null).anyTimes();
    }
    expect(request.getRequestURI()).andReturn("/mapreduce/" + handler).anyTimes();
    return request;
}

From source file:com.google.appengine.tools.mapreduce.MapReduceServlet.java

/**
 * Returns the portion of the URL from the end of the TLD (exclusive) to the
 * handler portion (exclusive)./*w  ww  . ja  v a 2 s .com*/
 *
 * For example, getBase(https://www.google.com/foo/bar) -> /foo/
 * However, there are handler portions that take more than segment
 * (currently only the command handlers). So in that case, we have:
 * getBase(https://www.google.com/foo/command/bar) -> /foo/
 */
static String getBase(HttpServletRequest request) {
    String fullPath = request.getRequestURI();
    int baseEnd = getDividingIndex(fullPath);
    return fullPath.substring(0, baseEnd + 1);
}

From source file:com.google.appengine.tools.mapreduce.MapReduceServlet.java

/**
 * Returns the handler portion of the URL path.
 *
 * For example, getHandler(https://www.google.com/foo/bar) -> bar
 * Note that for command handlers,/*  w  ww .jav  a2s . co m*/
 * getHandler(https://www.google.com/foo/command/bar) -> command/bar
 */
static String getHandler(HttpServletRequest request) {
    String requestURI = request.getRequestURI();
    return requestURI.substring(getDividingIndex(requestURI) + 1);
}

From source file:com.zimbra.cs.servlet.util.CsrfUtil.java

/**
 *
 * @param req//from  www  .j  a v a2  s .  c o  m
 * @param authToken
 * @return
 * @throws MalformedURLException
 */
public static boolean doCsrfCheck(final HttpServletRequest req, final AuthToken authToken)
        throws MalformedURLException {

    boolean csrfReq = true;
    csrfReq = isPostReq(req);
    if (csrfReq) {
        if (authToken != null) {
            if (!authToken.isCsrfTokenEnabled()) {
                csrfReq = isCsrfTokenCreated(authToken);
            }
        } else {
            csrfReq = false;
        }
    }
    if (ZimbraLog.misc.isDebugEnabled()) {
        String reqUrl = req.getRequestURI();
        ZimbraLog.misc.debug("ReqURL : " + reqUrl + (csrfReq ? " needs to " : " does not need to ")
                + "pass through CSRF check");
    }
    return csrfReq;
}