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.whatlookingfor.common.utils.StringUtils.java

/**
 * ?IP/*  ww  w .  j  av a 2  s  . c o m*/
 *
 * @param request 
 * @return ip?
 */
public static final String getHost(HttpServletRequest request) {
    String ip = request.getHeader("X-Forwarded-For");
    if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("Proxy-Client-IP");
    }
    if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("X-Real-IP");
    }
    if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getRemoteAddr();
    }
    if ("127.0.0.1".equals(ip)) {
        InetAddress inet = null;
        try { // ????IP
            inet = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        ip = inet.getHostAddress();
    }
    // ?IPIP,IP','
    if (ip != null && ip.length() > 15) {
        if (ip.indexOf(",") > 0) {
            ip = ip.substring(0, ip.indexOf(","));
        }
    }
    return ip;
}

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

public static Account basicAuthRequest(HttpServletRequest req, boolean allowGuest, boolean isDav)
        throws IOException, ServiceException, UserServletException {
    String auth = req.getHeader(HTTP_AUTH_HEADER);

    // TODO: more liberal parsing of Authorization value...
    if (auth == null || !auth.startsWith("Basic ")) {
        throw new UserServletException(HttpServletResponse.SC_UNAUTHORIZED, "must authenticate");
    }//from   w  w  w .  ja va2s  . co m

    // 6 comes from "Basic ".length();
    String userPass = new String(Base64.decodeBase64(auth.substring(6).getBytes()), "UTF-8");

    int loc = userPass.indexOf(":");
    if (loc == -1) {
        throw new UserServletException(HttpServletResponse.SC_BAD_REQUEST, "invalid basic auth credentials");
    }

    String userPassedIn = userPass.substring(0, loc);
    String user = userPassedIn;
    String pass = userPass.substring(loc + 1);

    Provisioning prov = Provisioning.getInstance();

    if (user.indexOf('@') == -1) {
        String host = HttpUtil.getVirtualHost(req);
        if (host != null) {
            Domain d = prov.get(Key.DomainBy.virtualHostname, host.toLowerCase());
            if (d != null)
                user += "@" + d.getName();
        }
    }

    Account acct = prov.get(AccountBy.name, user);

    if (acct == null) {
        if (allowGuest) {
            return new GuestAccount(user, pass);
        }

        throw new UserServletException(HttpServletResponse.SC_UNAUTHORIZED, "invalid username/password");
    }
    try {
        Map<String, Object> authCtxt = new HashMap<String, Object>();
        authCtxt.put(AuthContext.AC_ORIGINATING_CLIENT_IP, ZimbraServlet.getOrigIp(req));
        authCtxt.put(AuthContext.AC_REMOTE_IP, ZimbraServlet.getClientIp(req));
        authCtxt.put(AuthContext.AC_ACCOUNT_NAME_PASSEDIN, userPassedIn);
        authCtxt.put(AuthContext.AC_USER_AGENT, req.getHeader("User-Agent"));
        Protocol proto = isDav ? Protocol.http_dav : Protocol.http_basic;
        prov.authAccount(acct, pass, proto, authCtxt);
    } catch (ServiceException se) {
        throw new UserServletException(HttpServletResponse.SC_UNAUTHORIZED, "invalid username/password");
    }

    return acct;
}

From source file:net.community.chest.gitcloud.facade.ServletUtils.java

public static final Map<String, String> getRequestHeaders(HttpServletRequest req) {
    // NOTE: map must be case insensitive as per HTTP requirements
    Map<String, String> hdrsMap = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
    for (Enumeration<String> hdrs = req.getHeaderNames(); (hdrs != null) && hdrs.hasMoreElements();) {
        String hdrName = hdrs.nextElement(), hdrValue = req.getHeader(hdrName);
        hdrsMap.put(capitalizeHttpHeaderName(hdrName), StringUtils.trimToEmpty(hdrValue));
    }/*w  w  w  .j a v  a2s  . c  o m*/

    return hdrsMap;
}

From source file:com.concursive.connect.web.webdav.WebdavManager.java

public static int validateUser(Connection db, HttpServletRequest req) throws Exception {
    String argHeader = req.getHeader("Authorization");
    HashMap params = getAuthenticationParams(argHeader);
    String username = (String) params.get("username");

    if (md5Helper == null) {
        md5Helper = MessageDigest.getInstance("MD5");
    }//www.ja  va  2  s. co  m

    int userId = -1;
    String password = null;
    PreparedStatement pst = db.prepareStatement(
            "SELECT user_id, webdav_password " + "FROM users " + "WHERE username = ? " + "AND enabled = ? ");
    pst.setString(1, username);
    pst.setBoolean(2, true);
    ResultSet rs = pst.executeQuery();
    if (rs.next()) {
        userId = rs.getInt("user_id");
        password = rs.getString("webdav_password");
    }
    rs.close();
    pst.close();
    if (userId == -1) {
        return userId;
    }
    String method = req.getMethod();
    String uri = (String) params.get("uri");
    String a2 = MD5Encoder.encode(md5Helper.digest((method + ":" + uri).getBytes()));
    String digest = MD5Encoder
            .encode(md5Helper.digest((password + ":" + params.get("nonce") + ":" + a2).getBytes()));
    if (!digest.equals(params.get("response"))) {
        userId = -1;
    }
    return userId;
}

From source file:com.struts2ext.json.JSONUtil.java

public static boolean isGzipInRequest(HttpServletRequest request) {
    String header = request.getHeader("Accept-Encoding");
    return (header != null) && (header.indexOf("gzip") >= 0);
}

From source file:it.reply.orchestrator.config.filters.CustomRequestLoggingFilter.java

private static String getRemoteAddr(HttpServletRequest request) {
    String remoteAddress = null;/*www  . j  av a 2 s .c  o m*/
    String[] forwardedAddress = Strings.nullToEmpty(request.getHeader(HttpHeaders.X_FORWARDED_FOR))
            .split(", ?");
    if (ArrayUtils.isEmpty(forwardedAddress) || Strings.nullToEmpty(forwardedAddress[0]).trim().isEmpty()) {
        remoteAddress = request.getRemoteAddr();
    } else {
        remoteAddress = forwardedAddress[0];
    }
    return remoteAddress;
}

From source file:org.ambraproject.wombat.util.HttpMessageUtil.java

/**
 * Return a list of headers from a request, using an optional whitelist
 *
 * @param request a request/*from   w w  w.  j  ava2s . co  m*/
 * @return its headers
 */
public static Collection<Header> getRequestHeaders(HttpServletRequest request,
        ImmutableSet<String> headerWhitelist) {
    Enumeration headerNames = request.getHeaderNames();
    List<Header> headers = Lists.newArrayList();
    while (headerNames.hasMoreElements()) {
        String headerName = (String) headerNames.nextElement();
        if (headerWhitelist.contains(headerName)) {
            String headerValue = request.getHeader(headerName);
            headers.add(new BasicHeader(headerName, headerValue));
        }
    }
    return headers;
}

From source file:com.kolich.havalo.filters.HavaloAuthenticationFilter.java

private static final String getStringToSign(final HttpServletRequest request) {
    final StringBuilder sb = new StringBuilder();
    // HTTP-Verb (GET, PUT, POST, or DELETE) + "\n"
    sb.append(request.getMethod().toUpperCase()).append(LINE_SEPARATOR_UNIX);
    // RFC822 Date (from 'Date' request header, must exist) + "\n" +
    final String dateHeader;
    if ((dateHeader = request.getHeader(DATE)) == null) {
        throw new BadCredentialsException(
                "Incoming request missing " + "required '" + DATE + "' request header.");
    }/* ww  w . j av  a  2s  .com*/
    sb.append(dateHeader).append(LINE_SEPARATOR_UNIX);
    // Content-Type (from 'Content-Type' request header, optional) + "\n" +
    final String contentType;
    if ((contentType = request.getHeader(CONTENT_TYPE)) != null) {
        sb.append(contentType);
    }
    sb.append(LINE_SEPARATOR_UNIX);
    // CanonicalizedResource
    sb.append(request.getRequestURI());
    return sb.toString();
}

From source file:com.aaasec.sigserv.csspserver.SpServlet.java

private static boolean needPdfDownloadButton(HttpServletRequest request) {
    boolean button = true;
    String userAgent = request.getHeader("user-agent");
    for (String[] keyArray : PDF_VIEW_USER_AGENT_KEYS) {
        boolean setMatch = true;
        for (String key : keyArray) {
            if (userAgent.indexOf(key) < 0) {
                setMatch = false;// ww  w  .j a va  2  s .c  o  m
            }
        }
        if (setMatch) {
            return false;
        }
    }
    return button;
}

From source file:edu.cornell.mannlib.vitro.webapp.web.MiscWebUtils.java

public static void debugPrintHeaders(HttpServletRequest req) {
    Enumeration hnames = req.getHeaderNames();
    while (hnames.hasMoreElements()) {
        String name = (String) hnames.nextElement();
        log.debug("header " + name);
        String value = req.getHeader(name);
        log.debug("    " + value);
        Enumeration values = req.getHeaders(name);
        if (values == null) {
            log.debug("    enumeration was null");
        } else {//from w w w  . j a va 2 s. c  o  m
            log.debug("    enumeration values");
            while (values.hasMoreElements()) {
                String val = (String) values.nextElement();
                log.debug("    " + value);
            }
        }
    }
}