Example usage for javax.servlet.http HttpServletRequest getHeader

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

Introduction

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

Prototype

public String getHeader(String name);

Source Link

Document

Returns the value of the specified request header as a String.

Usage

From source file:com.erudika.para.utils.Utils.java

/**
 * Checks if a request comes from JavaScript.
 * @param request HTTP request// w  ww .  j  a va2 s. com
 * @return true if AJAX
 */
public static boolean isAjaxRequest(HttpServletRequest request) {
    return "XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))
            || "XMLHttpRequest".equalsIgnoreCase(request.getParameter("X-Requested-With"));
}

From source file:com.jsmartframework.web.manager.WebContext.java

/**
 * Returns true if the request being process was triggered by Ajax on client side,
 * false otherwise./*from   w  ww .j a  v a2 s .com*/
 *
 * @return boolean value indicating if request was done using Ajax.
 */
public static boolean isAjaxRequest() {
    HttpServletRequest request = getRequest();
    return request != null ? "XMLHttpRequest".equals(request.getHeader("X-Requested-With")) : false;
}

From source file:grails.plugin.springsecurity.SpringSecurityUtils.java

/**
 * Check if the request was triggered by an Ajax call.
 * @param request the request/*from   w  w w.  j  a  v  a 2 s .c  o  m*/
 * @return <code>true</code> if Ajax
 */
public static boolean isAjax(final HttpServletRequest request) {

    String ajaxHeaderName = (String) ReflectionUtils.getConfigProperty("ajaxHeader");

    // check the current request's headers
    if ("XMLHttpRequest".equals(request.getHeader(ajaxHeaderName))) {
        return true;
    }

    Object ajaxCheckClosure = ReflectionUtils.getConfigProperty("ajaxCheckClosure");
    if (ajaxCheckClosure instanceof Closure) {
        Object result = ((Closure<?>) ajaxCheckClosure).call(request);
        if (result instanceof Boolean && ((Boolean) result)) {
            return true;
        }
    }

    // look for an ajax=true parameter
    if ("true".equals(request.getParameter("ajax"))) {
        return true;
    }

    // process multipart requests
    MultipartHttpServletRequest multipart = ((MultipartHttpServletRequest) request
            .getAttribute("org.springframework.web.multipart.MultipartHttpServletRequest"));
    if (multipart != null && "true".equals(multipart.getParameter("ajax"))) {
        return true;
    }

    // check the SavedRequest's headers
    HttpSession httpSession = request.getSession(false);
    if (httpSession != null) {
        SavedRequest savedRequest = (SavedRequest) httpSession.getAttribute(SAVED_REQUEST);
        if (savedRequest != null) {
            return !savedRequest.getHeaderValues(ajaxHeaderName).isEmpty();
        }
    }

    return false;
}

From source file:io.apiman.test.common.mock.EchoServlet.java

/**
 * Create an echo response from the inbound information in the http server
 * request./*from  w ww .j  a v  a 2s . co m*/
 * @param request the request
 * @param withBody if request is with body
 * @return a new echo response
 */
public static EchoResponse response(HttpServletRequest request, boolean withBody) {
    EchoResponse response = new EchoResponse();
    response.setMethod(request.getMethod());
    if (request.getQueryString() != null) {
        String[] normalisedQueryString = request.getQueryString().split("&");
        Arrays.sort(normalisedQueryString);
        response.setResource(
                request.getRequestURI() + "?" + SimpleStringUtils.join("&", normalisedQueryString));
    } else {
        response.setResource(request.getRequestURI());
    }
    response.setUri(request.getRequestURI());
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = headerNames.nextElement();
        String value = request.getHeader(name);
        response.getHeaders().put(name, value);
    }
    if (withBody) {
        long totalBytes = 0;
        InputStream is = null;
        try {
            is = request.getInputStream();
            MessageDigest sha1 = MessageDigest.getInstance("SHA1");
            byte[] data = new byte[1024];
            int read;
            while ((read = is.read(data)) != -1) {
                sha1.update(data, 0, read);
                totalBytes += read;
            }
            ;

            byte[] hashBytes = sha1.digest();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < hashBytes.length; i++) {
                sb.append(Integer.toString((hashBytes[i] & 0xff) + 0x100, 16).substring(1));
            }
            String fileHash = sb.toString();

            response.setBodyLength(totalBytes);
            response.setBodySha1(fileHash);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
    return response;
}

From source file:com.comcast.cmb.common.util.AuthUtil.java

public static String generateSignatureV4(HttpServletRequest request, URL url, Map<String, String> parameters,
        Map<String, String> headers, String version, String algorithm, String accessSecret) throws Exception {

    /* Example of authorization header value
     * AWS4-HMAC-SHA256 Credential=XK1MWJAYYGQ41ECH06WG/20131126/us-east-1/us-east-1/aws4_request, SignedHeaders=host;user-agent;x-amz-date, Signature=18541c4db00d098414c0bae7394450d1deada902699a45de02849dbcb336f9e3
    *///  w ww.  j a  va 2  s. c o m
    String authorizationHeader = request.getHeader("authorization");
    String credentialPart = authorizationHeader
            .substring(authorizationHeader.indexOf("Credential=") + "Credential=".length());
    String[] credentialPartArray = credentialPart.split("/");

    String regionName = credentialPartArray[2];
    String serviceName = credentialPartArray[3];

    String dateTime = request.getHeader("X-Amz-Date");
    String dateStamp = credentialPartArray[1];

    String scope = credentialPart.substring(credentialPart.indexOf("/") + 1, credentialPart.indexOf(","));

    String payloadString = getPayload(request);
    String contentSha256 = BinaryUtils.toHex(hash(payloadString));
    Map<String, String> filteredHeaders = filterHeader(headers);

    String stringToSign = getStringToSign("AWS4-" + algorithm, dateTime, scope,
            getCanonicalRequest(request, contentSha256, parameters, filteredHeaders));

    byte[] secret = ("AWS4" + accessSecret).getBytes();
    byte[] date = sign(dateStamp, secret, SigningAlgorithm.HmacSHA256);
    byte[] region = sign(regionName, date, SigningAlgorithm.HmacSHA256);
    byte[] service = sign(serviceName, region, SigningAlgorithm.HmacSHA256);
    byte[] signing = sign("aws4_request", service, SigningAlgorithm.HmacSHA256);

    byte[] signatureBytes = sign(stringToSign.getBytes(), signing, SigningAlgorithm.HmacSHA256);

    String signature = BinaryUtils.toHex(signatureBytes);

    return signature;
}

From source file:by.stub.yaml.stubs.StubRequest.java

public static StubRequest createFromHttpServletRequest(final HttpServletRequest request) throws IOException {
    final StubRequest assertionRequest = StubRequest.newStubRequest(request.getPathInfo(),
            HandlerUtils.extractPostRequestBody(request, "stubs"));
    assertionRequest.addMethod(request.getMethod());

    final Enumeration<String> headerNamesEnumeration = request.getHeaderNames();
    final List<String> headerNames = ObjectUtils.isNotNull(headerNamesEnumeration)
            ? Collections.list(request.getHeaderNames())
            : new LinkedList<String>();
    for (final String headerName : headerNames) {
        final String headerValue = request.getHeader(headerName);
        assertionRequest.getHeaders().put(StringUtils.toLower(headerName), headerValue);
    }/*ww w  .j  a  v a  2s.c  om*/

    assertionRequest.getQuery().putAll(CollectionUtils.constructParamMap(request.getQueryString()));
    ConsoleUtils.logAssertingRequest(assertionRequest);

    return assertionRequest;
}

From source file:eionet.cr.util.Util.java

/**
 *
 * @param request// w  w  w  .ja v a  2s.  c  o  m
 * @return
 */
public static boolean isWebBrowser(HttpServletRequest request) {

    // Lazy-loading.
    boolean result = false;
    String userAgentString = request.getHeader("User-Agent");
    if (userAgentString != null && userAgentString.trim().length() > 0) {

        Browser browser = Browser.parseUserAgentString(userAgentString);
        if (browser != null) {

            BrowserType browserType = browser.getBrowserType();
            if (browserType != null) {

                if (browserType.equals(BrowserType.WEB_BROWSER)
                        || browserType.equals(BrowserType.MOBILE_BROWSER)) {
                    result = true;
                }
            }
        }
    }

    return result;
}

From source file:controllers.admin.SigninController.java

@GetMapping("/login")
public String login(HttpServletRequest request) {
    String referrer = request.getHeader("Referer");
    if (referrer != null && referrer.startsWith("/admin")) {
        request.getSession().setAttribute("url_prior_login", referrer);
    }// ww  w.  j  av  a 2s .c om
    return "admin/login";
}

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 localizable and the site.
 * <p>// w  w w.  j  ava  2s.  c  o m
 * The preferred one is defined by the following priorities:
 * <ul>
 * <li>Requested by the client</li>
 * <li>The localizable's original language</li>
 * <li>The site default language</li>
 * <li>The first language of what is supported by both the localizable and the
 * site</li>
 * </ul>
 * 
 * @param localizable
 *          the localizable
 * @param request
 *          the http request
 * @param site
 *          the site
 */
public static Language getPreferredLanguage(Localizable localizable, HttpServletRequest request, Site site) {

    // Path
    String[] pathElements = StringUtils.split(request.getRequestURI(), "/");
    for (String element : pathElements) {
        for (Language l : localizable.languages()) {
            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 (localizable != null && !localizable.supportsLanguage(l))
                    continue;
                if (!site.supportsLanguage(l))
                    continue;
                return l;
            } catch (UnknownLanguageException e) {
                // never mind, some clients will send stuff like "*" as the locale
            }
        }
    }

    // The localizable's original language
    if (localizable != null && localizable instanceof Resource) {
        Resource<?> r = (Resource<?>) localizable;
        if (r.getOriginalContent() != null) {
            if (site.supportsLanguage(r.getOriginalContent().getLanguage()))
                return r.getOriginalContent().getLanguage();
        }
    }

    // Site default language
    if (localizable != null && localizable.supportsLanguage(site.getDefaultLanguage())) {
        return site.getDefaultLanguage();
    }

    // Any match
    if (localizable != null) {
        for (Language l : site.getLanguages()) {
            if (localizable.supportsLanguage(l)) {
                return l;
            }
        }
    }

    return null;
}

From source file:com.poscoict.license.security.AjaxSessionTimeoutFilter.java

private boolean isAjaxRequest(HttpServletRequest req) {
    return req.getHeader(ajaxHeader) != null && req.getHeader(ajaxHeader).equals(Boolean.TRUE.toString());
}