Example usage for javax.servlet.http HttpServletResponse containsHeader

List of usage examples for javax.servlet.http HttpServletResponse containsHeader

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse containsHeader.

Prototype

public boolean containsHeader(String name);

Source Link

Document

Returns a boolean indicating whether the named response header has already been set.

Usage

From source file:org.toobsframework.pres.base.HandlerBase.java

@Override
public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("handleRequestInternal(" + request.getRequestURI() + ")");
    }/*from  ww  w.  j  a  va2  s.c  o  m*/
    UrlDispatchInfo dispatchInfo = dispatchStrategy.resolveDispatchInfo(request);
    if (dispatchInfo == null) {
        dispatchInfo = new UrlDispatchInfo(request.getRequestURI(), null, null);
        dispatchInfo.setError(true);
        request.setAttribute(PresConstants.TOOBS_EXCEPTION_ATTR_NAME,
                new DispatchException(request.getRequestURI()));
    }
    if (response.containsHeader(PresConstants.TOOBS_EXCEPTION_HEADER_NAME)) {
        dispatchInfo.setError(true);
    }

    return handleRequestInternal(request, response, dispatchInfo);
}

From source file:org.craftercms.engine.http.impl.HttpProxyImpl.java

protected void copyActualResponseHeaders(HttpUriRequest httpRequest, HttpServletResponse response) {
    Header[] headers = httpRequest.getAllHeaders();
    for (Header header : headers) {
        String headerName = header.getName();
        String headerValue = header.getValue();

        if (!headerName.equals("Transfer-Encoding") && !header.equals("chunked")) {
            if (logger.isTraceEnabled()) {
                logger.trace(getRequestDescription(httpRequest) + " copying response header " + headerName
                        + ": " + headerValue);
            }//  w  w w  .  ja  va  2  s .c  o m

            if (response.containsHeader(headerName)) {
                response.setHeader(headerName, headerValue);
            } else {
                response.addHeader(headerName, headerValue);
            }
        }
    }
}

From source file:org.apache.ranger.security.web.filter.RangerKRBAuthenticationFilter.java

@Override
protected void doFilter(FilterChain filterChain, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String authType = PropertiesUtil.getProperty(RANGER_AUTH_TYPE);
    String userName = null;/*from  www  . ja  va  2s  . co  m*/
    boolean checkCookie = response.containsHeader("Set-Cookie");
    if (checkCookie) {
        Collection<String> authUserName = response.getHeaders("Set-Cookie");
        if (authUserName != null) {
            Iterator<String> i = authUserName.iterator();
            while (i.hasNext()) {
                String cookie = i.next();
                if (!StringUtils.isEmpty(cookie)) {
                    if (cookie.toLowerCase().startsWith(AUTH_COOKIE_NAME.toLowerCase())
                            && cookie.contains("u=")) {
                        String[] split = cookie.split(";");
                        if (split != null) {
                            for (String s : split) {
                                if (!StringUtils.isEmpty(s)
                                        && s.toLowerCase().startsWith(AUTH_COOKIE_NAME.toLowerCase())) {
                                    int ustr = s.indexOf("u=");
                                    if (ustr != -1) {
                                        int andStr = s.indexOf("&", ustr);
                                        if (andStr != -1) {
                                            try {
                                                userName = s.substring(ustr + 2, andStr);
                                            } catch (Exception e) {
                                                userName = null;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    String sessionUserName = request.getParameter(S_USER);
    String pathInfo = request.getPathInfo();
    if (!StringUtils.isEmpty(sessionUserName) && sessionUserName.equalsIgnoreCase("keyadmin")
            && !StringUtils.isEmpty(pathInfo) && pathInfo.contains("public/v2/api/service")) {
        LOG.info("Session will be created by : " + sessionUserName);
        userName = sessionUserName;
    }

    if ((isSpnegoEnable(authType) && (!StringUtils.isEmpty(userName)))) {
        Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
        if (existingAuth == null || !existingAuth.isAuthenticated()) {
            //--------------------------- To Create Ranger Session --------------------------------------
            String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER");
            //if we get the userName from the token then log into ranger using the same user
            final List<GrantedAuthority> grantedAuths = new ArrayList<>();
            grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole));
            final UserDetails principal = new User(userName, "", grantedAuths);
            final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, "",
                    grantedAuths);
            WebAuthenticationDetails webDetails = new WebAuthenticationDetails(request);
            ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails);
            RangerAuthenticationProvider authenticationProvider = new RangerAuthenticationProvider();
            Authentication authentication = authenticationProvider.authenticate(finalAuthentication);
            authentication = getGrantedAuthority(authentication);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            request.setAttribute("spnegoEnabled", true);
            LOG.info("Logged into Ranger as = " + userName);
            filterChain.doFilter(request, response);
        } else {
            try {
                super.doFilter(filterChain, request, response);
            } catch (Exception e) {
                throw restErrorUtil
                        .createRESTException("RangerKRBAuthenticationFilter Failed : " + e.getMessage());
            }
        }
    } else {
        filterChain.doFilter(request, response);
    }
}

From source file:fedora.server.security.servletfilters.FilterEnforceAuthn.java

@Override
public boolean doThisSubclass(ExtendedHttpServletRequest request, HttpServletResponse response)
        throws Throwable {
    String method = "doThisSubclass() ";
    if (log.isDebugEnabled()) {
        log.debug(enter(method));/*from www  .  j a  v a 2 s. co m*/
    }
    super.doThisSubclass(request, response);
    request.lockWrapper();

    boolean terminateServletFilterChain = request.getUserPrincipal() == null;
    if (terminateServletFilterChain) {
        if (log.isDebugEnabled()) {
            log.debug(format(method, "no principal found, sending 401"));
        }
        String realm = "fedora";
        String value = "BASIC realm=\"" + realm + "\"";
        String name = "WWW-Authenticate";
        int sc = HttpServletResponse.SC_UNAUTHORIZED;
        response.reset();
        //httpServletResponse.sendError(sc, "supply credentials"); //same as after
        if (response.containsHeader(name)) {
            response.setHeader(name, value);
        } else {
            response.addHeader(name, value);
        }
        try {
            response.sendError(sc, "supply credentials");
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } //here, no bad auth msg at wget
        response.setContentType("text/plain");
        try {
            response.flushBuffer();
        } catch (IOException e) {
            showThrowable(e, log, "response flush error");
        }
    }
    return terminateServletFilterChain;
}

From source file:org.apache.click.extras.filter.PerformanceFilter.java

/**
 * Return true if the response should be GZIP compressed.
 *
 * @param request the request to test/*from w  w w .ja  v  a 2  s  .c om*/
 * @param response the response to test
 * @param path the request path to test
 * @return true if the response should be GZIP compressed
 */
protected boolean useGzipCompression(HttpServletRequest request, HttpServletResponse response, String path) {

    if (!compressionEnabled) {
        return false;
    }

    // If Content-Encoding header is already set on response, skip compression
    if (response.containsHeader("Content-Encoding")) {
        return false;
    }

    if (compressionThreshold > 0) {
        path = path.toLowerCase();

        if (path.endsWith(".gif") || path.endsWith(".png") || path.endsWith(".jpg")) {
            return false;
        }

        Enumeration<?> e = request.getHeaders("Accept-Encoding");

        while (e.hasMoreElements()) {
            String name = (String) e.nextElement();
            if (name.indexOf("gzip") != -1) {
                return true;
            }
        }
    }

    return false;
}

From source file:org.opengeo.gsr.core.controller.ImageResourceController.java

protected void writeHeaders(File imageFile, HttpServletResponse response) {

    // determine mimetype
    String imagePath = imageFile.getPath();
    String mimetype = getServletContext().getMimeType(imagePath);
    if (mimetype == null) {
        final int extIndex = imagePath.lastIndexOf('.');
        if (extIndex != -1) {
            String extension = imagePath.substring(extIndex);
            mimetype = (String) defaultMimeTypes.get(extension.toLowerCase());
        }//from  w  w w . j  a v  a  2s . c  o  m
    }

    long length = imageFile.length();
    long lastModified = imageFile.lastModified();

    response.setContentType(mimetype);
    response.setHeader(HTTP_HEADER_CONTENT_LENGTH, Long.toString(length));
    if (lastModified != 0) {
        response.setHeader(HTTP_HEADER_ETAG, '"' + Long.toString(lastModified) + '"');
        response.setDateHeader(HTTP_HEADER_LAST_MODIFIED, lastModified);
    }
    if (!response.containsHeader(HTTP_HEADER_CACHE_CONTROL)) {
        response.setHeader(HTTP_HEADER_CACHE_CONTROL, "max-age=86400");
    }
}

From source file:com.codeabovelab.dm.gateway.proxy.common.HttpProxy.java

/**
 * Copy proxied response headers back to the servlet client.
 *//* w w w .j a  v a2s.com*/
private void copyResponseHeaders(HttpResponse proxyResponse, HttpServletRequest servletRequest,
        HttpServletResponse servletResponse) {
    Header[] allHeaders = proxyResponse.getAllHeaders();
    for (int i = 0, l = allHeaders.length; i < l; i++) {
        Header header = allHeaders[i];
        String name = header.getName();
        if (hopByHopHeaders.containsHeader(name)) {
            continue;
        }
        String value = header.getValue();
        if (name.equalsIgnoreCase(org.apache.http.cookie.SM.SET_COOKIE)
                || name.equalsIgnoreCase(org.apache.http.cookie.SM.SET_COOKIE2)) {
            copyProxyCookie(servletRequest, servletResponse, header);
        } else {
            if (!servletResponse.containsHeader(name)) {
                servletResponse.addHeader(name, value);
            }
        }
    }
}

From source file:org.openqa.grid.internal.TestSession.java

private void writeRawBody(HttpServletResponse response, byte[] rawBody) throws IOException {
    OutputStream out = response.getOutputStream();
    try {//from   ww  w  . ja v  a2 s .  com
        // We need to set the Content-Length header before we write to the output stream. Usually
        // the
        // Content-Length header is already set because we take it from the proxied request. But, it
        // won't
        // be set when we consume chunked content, since that doesn't use Content-Length. As we're
        // not
        // going to send a chunked response, we need to set the Content-Length in order for the
        // response
        // to be valid.
        if (!response.containsHeader("Content-Length")) {
            response.setIntHeader("Content-Length", rawBody.length);
        }

        out.write(rawBody);
    } catch (IOException e) {
        throw new ClientGoneException(e);
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:com.metamesh.opencms.rfs.RfsFileLoader.java

/**
 * @see org.opencms.loader.I_CmsResourceLoader#load(org.opencms.file.CmsObject, org.opencms.file.CmsResource, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///ww  w . j  ava2s.com
public void load(CmsObject cms, CmsResource resource, HttpServletRequest req, HttpServletResponse res)
        throws IOException, CmsException {

    if (canSendLastModifiedHeader(resource, req, res)) {
        // no further processing required
        return;
    }

    // set response status to "200 - OK" (required for static export "on-demand")
    res.setStatus(HttpServletResponse.SC_OK);
    // set content length header
    res.setContentLength(resource.getLength());

    if (CmsWorkplaceManager.isWorkplaceUser(req)) {
        // prevent caching for Workplace users
        res.setDateHeader(CmsRequestUtil.HEADER_LAST_MODIFIED, System.currentTimeMillis());
        CmsRequestUtil.setNoCacheHeaders(res);
    } else {
        // set date last modified header
        res.setDateHeader(CmsRequestUtil.HEADER_LAST_MODIFIED, resource.getDateLastModified());

        // set "Expires" only if cache control is not already set
        if (!res.containsHeader(CmsRequestUtil.HEADER_CACHE_CONTROL)) {
            long expireTime = resource.getDateExpired();
            if (expireTime == CmsResource.DATE_EXPIRED_DEFAULT) {
                expireTime--;
                // flex controller will automatically reduce this to a reasonable value
            }
            // now set "Expires" header        
            CmsFlexController.setDateExpiresHeader(res, expireTime, m_clientCacheMaxAge);
        }
    }

    service(cms, resource, req, res);
}