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:io.apiman.test.common.mock.EchoResponse.java

/**
 * Create an echo response from the inbound information in the http server
 * request.//from   ww w .  j a v a2  s  .c om
 * @param request
 * @param withBody 
 * @return a new echo response
 */
public static EchoResponse from(HttpServletRequest request, boolean withBody) {
    EchoResponse response = new EchoResponse();
    response.setMethod(request.getMethod());
    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"); //$NON-NLS-1$
            byte[] data = new byte[1024];
            int read = 0;
            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:net.siegmar.japtproxy.JaptProxy.java

/**
 * Analyzes (validates) request url and extract required information.
 *
 * @param request the object to populate with extracted information.
 * @throws net.siegmar.japtproxy.exception.InvalidRequestException is thrown if requested url is invalid.
 *//*from w  ww  .j a va 2 s.  c  o  m*/
private static RequestedData buildRequestedData(final HttpServletRequest request,
        final Configuration configuration) throws InvalidRequestException {
    final String resource = request.getPathInfo();
    final RequestedData requestedData = new RequestedData();
    requestedData.setRequestedResource(resource);
    requestedData.setRequestModifiedSince(request.getDateHeader(HttpHeaderConstants.IF_MODIFIED_SINCE));

    requestedData.setUserAgent(request.getHeader(HttpHeaderConstants.USER_AGENT));
    requestedData.setUrl(getURL(request, configuration));
    requestedData.setHostUrl(getURL(request, true, configuration));
    requestedData.setScheme(request.getScheme());
    requestedData.setServerName(request.getServerName());
    requestedData.setServerPort(request.getServerPort());

    final String requestedResource = requestedData.getRequestedResource();

    // Reject if no requested resource is specified
    if (requestedResource == null) {
        throw new InvalidRequestException("Rejected request because it doesn't contain a resource request");
    }

    // Reject requests that contain /../ for security reason
    if (requestedResource.contains("/../")) {
        throw new InvalidRequestException(
                "Rejected request '" + requestedResource + "' because it contains /../");
    }

    // Reject requests that doesn't contain a backend
    final int endIdx = requestedResource.indexOf('/', 1);
    if (endIdx <= 1) {
        throw new InvalidRequestException(
                "Rejected request '" + requestedResource + "' because it doesn't specify a backend");
    }

    // Reject requests that doesn't contain a target resource
    if (requestedResource.length() == endIdx + 1) {
        throw new InvalidRequestException("Rejected request '" + requestedResource
                + "' because it doesn't specify a target " + "resource");
    }

    // Extract the backend and target resource parts of the request
    final String requestedBackend = requestedResource.substring(1, endIdx);
    final String requestedTarget = requestedResource.substring(endIdx);

    // Set requestedData
    requestedData.setRequestedTarget(requestedTarget);
    requestedData.setRequestedBackend(requestedBackend);

    return requestedData;
}

From source file:cn.guoyukun.spring.web.utils.DownloadUtils.java

public static void download(HttpServletRequest request, HttpServletResponse response, String filePath,
        String displayName) throws IOException {
    File file = new File(filePath);

    if (StringUtils.isEmpty(displayName)) {
        displayName = file.getName();/* w w  w . j  ava2  s .  c o  m*/
    }

    if (!file.exists() || !file.canRead()) {
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("??");
        return;
    }

    String userAgent = request.getHeader("User-Agent");
    boolean isIE = (userAgent != null) && (userAgent.toLowerCase().indexOf("msie") != -1);

    response.reset();
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "must-revalidate, no-transform");
    response.setDateHeader("Expires", 0L);

    response.setContentType("application/x-download");
    response.setContentLength((int) file.length());

    String displayFilename = displayName.substring(displayName.lastIndexOf("_") + 1);
    displayFilename = displayFilename.replace(" ", "_");
    if (isIE) {
        displayFilename = URLEncoder.encode(displayFilename, "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=\"" + displayFilename + "\"");
    } else {
        displayFilename = new String(displayFilename.getBytes("UTF-8"), "ISO8859-1");
        response.setHeader("Content-Disposition", "attachment;filename=" + displayFilename);
    }
    BufferedInputStream is = null;
    OutputStream os = null;
    try {

        os = response.getOutputStream();
        is = new BufferedInputStream(new FileInputStream(file));
        IOUtils.copy(is, os);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(is);
    }
}

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

/**
 * Returns the language out of <code>choices</code> that matches the client's
 * requirements as indicated through the <code>Accept-Language</code> header.
 * If no match is possible, <code>null</code> is returned.
 * //from   ww  w.j  av a 2s.com
 * @param choices
 *          the available locales
 * @param request
 *          the http request
 */
public static Language getPreferredLanguage(Set<Language> choices, HttpServletRequest request) {
    if (request.getHeader("Accept-Language") != null) {
        Enumeration<?> locales = request.getLocales();
        while (locales.hasMoreElements()) {
            try {
                Language l = getLanguage((Locale) locales.nextElement());
                if (choices.contains(l))
                    return l;
            } catch (UnknownLanguageException e) {
                // never mind, some clients will send stuff like "*" as the locale
            }

        }
    }
    return null;
}

From source file:com.zimbra.common.util.HttpUtil.java

/**
 * bug 32207// w  ww .ja v  a2s  .co m
 *
 * The apache reverse proxy is re-writing the Host header to be the MBS IP.  It sets
 * the original request hostname in the X-Forwarded-Host header.  To work around it,
 * we first check for X-Forwarded-Host and then fallback to Host.
 *
 * @param req
 * @return the original request hostname
 */
public static String getVirtualHost(HttpServletRequest req) {
    String virtualHost = req.getHeader("X-Forwarded-Host");
    if (virtualHost != null)
        return virtualHost;
    else
        return req.getServerName();
}

From source file:ch.entwine.weblounge.common.content.ResourceUtils.java

/**
 * Returns <code>true</code> if the resource either is more recent than the
 * cached version on the client side or the request does not contain caching
 * information.// w w w .  ja  v  a 2 s .  c om
 * <p>
 * The calculation is made based on the availability of either the
 * <code>If-None-Match</code> or the <code>If-Modified-Since</code> header (in
 * this order).
 * 
 * @param request
 *          the client request
 * @param resource
 *          the resource
 * @param language
 *          the language
 * @return <code>true</code> if the resource is more recent than the version
 *         that is cached at the client.
 * @throws IllegalArgumentException
 *           if the <code>If-Modified-Since</code> header cannot be converted
 *           to a date.
 */
public static boolean hasChanged(HttpServletRequest request, Resource<?> resource, Language language)
        throws IllegalArgumentException {
    if (request.getHeader("If-None-Match") != null) {
        return isMismatch(request, getETagValue(resource));
    } else if (request.getHeader("If-Modified-Since") != null) {
        return isModified(request, resource, language);
    }
    return true;
}

From source file:net.oneandone.jasmin.main.Servlet.java

private static String referer(HttpServletRequest request) {
    if (request == null) {
        return null;
    }//  ww  w.jav  a2 s .com
    return request.getHeader("Referer");
}

From source file:org.artifactory.util.HttpUtils.java

@SuppressWarnings({ "IfMayBeConditional" })
public static String getRemoteClientAddress(HttpServletRequest request) {
    String remoteAddress;// w  ww.  j  av  a 2 s .  co  m
    //Check if there is a remote address coming from a proxied request
    //(http://httpd.apache.org/docs/2.2/mod/mod_proxy.html#proxypreservehost)
    String header = request.getHeader("X-Forwarded-For");
    if (StringUtils.isNotBlank(header)) {
        //Might contain multiple entries - take the first
        remoteAddress = new StringTokenizer(header, ",").nextToken();
    } else {
        //Take it the standard way
        remoteAddress = request.getRemoteAddr();
    }
    return remoteAddress;
}

From source file:com.meltmedia.cadmium.servlets.FileServletTest.java

public static HttpServletRequest mockGet(String pathInfo) {
    HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getMethod()).thenReturn(GET_METHOD);
    when(request.getRequestURI()).thenReturn(pathInfo);
    when(request.getDateHeader(anyString())).thenReturn(new Long(-1));
    when(request.getHeader(anyString())).thenReturn(null);
    return request;
}

From source file:com.meltmedia.cadmium.servlets.FileServletTest.java

public static HttpServletRequest mockGetWithGzip(String pathInfo) {
    HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getMethod()).thenReturn(GET_METHOD);
    when(request.getRequestURI()).thenReturn(pathInfo);
    when(request.getDateHeader(anyString())).thenReturn(new Long(-1));
    when(request.getHeader(ACCEPT_ENCODING_HEADER)).thenReturn("gzip");
    return request;
}