Java Code Examples for javax.servlet.http.HttpServletResponse#containsHeader()

The following examples show how to use javax.servlet.http.HttpServletResponse#containsHeader() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebContentGenerator.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Set HTTP headers to allow caching for the given number of seconds.
 * Tells the browser to revalidate the resource if mustRevalidate is
 * {@code true}.
 * @param response the current HTTP response
 * @param seconds number of seconds into the future that the response
 * should be cacheable for
 * @param mustRevalidate whether the client should revalidate the resource
 * (typically only necessary for controllers with last-modified support)
 * @deprecated as of 4.2, in favor of {@link #applyCacheControl}
 */
@Deprecated
protected final void cacheForSeconds(HttpServletResponse response, int seconds, boolean mustRevalidate) {
	if (this.useExpiresHeader) {
		// HTTP 1.0 header
		response.setDateHeader(HEADER_EXPIRES, System.currentTimeMillis() + seconds * 1000L);
	}
	else if (response.containsHeader(HEADER_EXPIRES)) {
		// Reset HTTP 1.0 Expires header if present
		response.setHeader(HEADER_EXPIRES, "");
	}

	if (this.useCacheControlHeader) {
		// HTTP 1.1 header
		String headerValue = "max-age=" + seconds;
		if (mustRevalidate || this.alwaysMustRevalidate) {
			headerValue += ", must-revalidate";
		}
		response.setHeader(HEADER_CACHE_CONTROL, headerValue);
	}

	if (response.containsHeader(HEADER_PRAGMA)) {
		// Reset HTTP 1.0 Pragma header if present
		response.setHeader(HEADER_PRAGMA, "");
	}
}
 
Example 2
Source File: WebContentGenerator.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private Collection<String> getVaryRequestHeadersToAdd(HttpServletResponse response, String[] varyByRequestHeaders) {
	if (!response.containsHeader(HttpHeaders.VARY)) {
		return Arrays.asList(varyByRequestHeaders);
	}
	Collection<String> result = new ArrayList<>(varyByRequestHeaders.length);
	Collections.addAll(result, varyByRequestHeaders);
	for (String header : response.getHeaders(HttpHeaders.VARY)) {
		for (String existing : StringUtils.tokenizeToStringArray(header, ",")) {
			if ("*".equals(existing)) {
				return Collections.emptyList();
			}
			for (String value : varyByRequestHeaders) {
				if (value.equalsIgnoreCase(existing)) {
					result.remove(value);
				}
			}
		}
	}
	return result;
}
 
Example 3
Source File: FrameworkServlet.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Delegate OPTIONS requests to {@link #processRequest}, if desired.
 * <p>Applies HttpServlet's standard OPTIONS processing otherwise,
 * and also if there is still no 'Allow' header set after dispatching.
 * @see #doService
 */
@Override
protected void doOptions(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {

	if (this.dispatchOptionsRequest || CorsUtils.isPreFlightRequest(request)) {
		processRequest(request, response);
		if (response.containsHeader("Allow")) {
			// Proper OPTIONS response coming from a handler - we're done.
			return;
		}
	}

	// Use response wrapper in order to always add PATCH to the allowed methods
	super.doOptions(request, new HttpServletResponseWrapper(response) {
		@Override
		public void setHeader(String name, String value) {
			if ("Allow".equals(name)) {
				value = (StringUtils.hasLength(value) ? value + ", " : "") + HttpMethod.PATCH.name();
			}
			super.setHeader(name, value);
		}
	});
}
 
Example 4
Source File: FrameworkServlet.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Delegate OPTIONS requests to {@link #processRequest}, if desired.
 * <p>Applies HttpServlet's standard OPTIONS processing otherwise,
 * and also if there is still no 'Allow' header set after dispatching.
 * @see #doService
 */
@Override
protected void doOptions(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {

	if (this.dispatchOptionsRequest || CorsUtils.isPreFlightRequest(request)) {
		processRequest(request, response);
		if (response.containsHeader("Allow")) {
			// Proper OPTIONS response coming from a handler - we're done.
			return;
		}
	}

	// Use response wrapper for Servlet 2.5 compatibility where
	// the getHeader() method does not exist
	super.doOptions(request, new HttpServletResponseWrapper(response) {
		@Override
		public void setHeader(String name, String value) {
			if ("Allow".equals(name)) {
				value = (StringUtils.hasLength(value) ? value + ", " : "") + HttpMethod.PATCH.name();
			}
			super.setHeader(name, value);
		}
	});
}
 
Example 5
Source File: JerseyModule.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Provides
 @Singleton
 public Filter apiOriginFilter() {
     return new Filter(){

@Override
public void init(FilterConfig filterConfig) throws ServletException {}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
       HttpServletResponse res = (HttpServletResponse) response;
       if (!res.containsHeader("Access-Control-Allow-Origin")) {
           res.setHeader("Access-Control-Allow-Origin", "*");
       }
       res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
       res.addHeader("Access-Control-Allow-Headers", "Content-Type, api_key, Authorization");
       
       chain.doFilter(request, response);
   }
@Override
public void destroy() {}
     	
     };
 }
 
Example 6
Source File: WebContentGenerator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private Collection<String> getVaryRequestHeadersToAdd(HttpServletResponse response) {
	if (!response.containsHeader(HttpHeaders.VARY)) {
		return Arrays.asList(getVaryByRequestHeaders());
	}
	Collection<String> result = new ArrayList<String>(getVaryByRequestHeaders().length);
	Collections.addAll(result, getVaryByRequestHeaders());
	for (String header : response.getHeaders(HttpHeaders.VARY)) {
		for (String existing : StringUtils.tokenizeToStringArray(header, ",")) {
			if ("*".equals(existing)) {
				return Collections.emptyList();
			}
			for (String value : getVaryByRequestHeaders()) {
				if (value.equalsIgnoreCase(existing)) {
					result.remove(value);
				}
			}
		}
	}
	return result;
}
 
Example 7
Source File: WebContentGenerator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Set HTTP headers to allow caching for the given number of seconds.
 * Tells the browser to revalidate the resource if mustRevalidate is
 * {@code true}.
 * @param response the current HTTP response
 * @param seconds number of seconds into the future that the response
 * should be cacheable for
 * @param mustRevalidate whether the client should revalidate the resource
 * (typically only necessary for controllers with last-modified support)
 * @deprecated as of 4.2, in favor of {@link #applyCacheControl}
 */
@Deprecated
protected final void cacheForSeconds(HttpServletResponse response, int seconds, boolean mustRevalidate) {
	if (this.useExpiresHeader) {
		// HTTP 1.0 header
		response.setDateHeader(HEADER_EXPIRES, System.currentTimeMillis() + seconds * 1000L);
	}
	else if (response.containsHeader(HEADER_EXPIRES)) {
		// Reset HTTP 1.0 Expires header if present
		response.setHeader(HEADER_EXPIRES, "");
	}

	if (this.useCacheControlHeader) {
		// HTTP 1.1 header
		String headerValue = "max-age=" + seconds;
		if (mustRevalidate || this.alwaysMustRevalidate) {
			headerValue += ", must-revalidate";
		}
		response.setHeader(HEADER_CACHE_CONTROL, headerValue);
	}

	if (response.containsHeader(HEADER_PRAGMA)) {
		// Reset HTTP 1.0 Pragma header if present
		response.setHeader(HEADER_PRAGMA, "");
	}
}
 
Example 8
Source File: HttpUtils.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public static void addSecurityHeaders(final HttpServletResponse resp) {
    if (resp.containsHeader("X-Content-Type-Options")) {
        resp.setHeader("X-Content-Type-Options", "nosniff");
    }
    else {
        resp.addHeader("X-Content-Type-Options", "nosniff");
    }
    if (resp.containsHeader("X-XSS-Protection")) {
        resp.setHeader("X-XSS-Protection", "1;mode=block");
    }
    else {
        resp.addHeader("X-XSS-Protection", "1;mode=block");
    }

    if (resp.containsHeader("content-security-policy")) {
        resp.setIntHeader("content-security-policy", 1);
    }else {
        resp.addIntHeader("content-security-policy", 1);
    }
    resp.addHeader("content-security-policy","default-src=none");
    resp.addHeader("content-security-policy","script-src=self");
    resp.addHeader("content-security-policy","connect-src=self");
    resp.addHeader("content-security-policy","img-src=self");
    resp.addHeader("content-security-policy","style-src=self");
}
 
Example 9
Source File: LogsearchKRBAuthenticationFilter.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
private String getUsernameFromResponse(HttpServletResponse response) {
  String userName = null;
  boolean checkCookie = response.containsHeader("Set-Cookie");
  if (checkCookie) {
    Collection<String> cookiesCollection = response.getHeaders("Set-Cookie");
    if (cookiesCollection != null) {
      Iterator<String> iterator = cookiesCollection.iterator();
      while (iterator.hasNext()) {
        String cookie = iterator.next();
        if (StringUtils.isNotEmpty(cookie)) {
          if (cookie.toLowerCase().startsWith(AUTH_COOKIE_NAME.toLowerCase())) {
            Matcher m = usernamePattern.matcher(cookie);
            if (m.find()) {
              userName = m.group(1);
            }
          }
        }
        if (StringUtils.isNotEmpty(userName)) {
          break;
        }
      }
    }
  }
  logger.debug("kerberos username  from  response >>>>>>>>" + userName);
  return userName;
}
 
Example 10
Source File: WebContentGenerator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Set the HTTP Cache-Control header according to the given settings.
 * @param response current HTTP response
 * @param cacheControl the pre-configured cache control settings
 * @since 4.2
 */
protected final void applyCacheControl(HttpServletResponse response, CacheControl cacheControl) {
	String ccValue = cacheControl.getHeaderValue();
	if (ccValue != null) {
		// Set computed HTTP 1.1 Cache-Control header
		response.setHeader(HEADER_CACHE_CONTROL, ccValue);

		if (response.containsHeader(HEADER_PRAGMA)) {
			// Reset HTTP 1.0 Pragma header if present
			response.setHeader(HEADER_PRAGMA, "");
		}
		if (response.containsHeader(HEADER_EXPIRES)) {
			// Reset HTTP 1.0 Expires header if present
			response.setHeader(HEADER_EXPIRES, "");
		}
	}
}
 
Example 11
Source File: WebContentGenerator.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Set HTTP headers to allow caching for the given number of seconds.
 * Tells the browser to revalidate the resource if mustRevalidate is
 * {@code true}.
 * @param response the current HTTP response
 * @param seconds number of seconds into the future that the response
 * should be cacheable for
 * @param mustRevalidate whether the client should revalidate the resource
 * (typically only necessary for controllers with last-modified support)
 * @deprecated as of 4.2, in favor of {@link #applyCacheControl}
 */
@Deprecated
protected final void cacheForSeconds(HttpServletResponse response, int seconds, boolean mustRevalidate) {
	if (this.useExpiresHeader) {
		// HTTP 1.0 header
		response.setDateHeader(HEADER_EXPIRES, System.currentTimeMillis() + seconds * 1000L);
	}

	if (this.useCacheControlHeader) {
		// HTTP 1.1 header
		String headerValue = "max-age=" + seconds;
		if (mustRevalidate || this.alwaysMustRevalidate) {
			headerValue += ", must-revalidate";
		}
		response.setHeader(HEADER_CACHE_CONTROL, headerValue);
	}

	if (response.containsHeader(HEADER_PRAGMA)) {
		// Reset HTTP 1.0 Pragma header if present
		response.setHeader(HEADER_PRAGMA, "");
	}
}
 
Example 12
Source File: InjectionAttackFilter.java    From spring-boot-start-current with Apache License 2.0 5 votes vote down vote up
/**
 * 跨域攻击处理
 *
 * @param response
 */
private void filterClickJack ( HttpServletResponse response ) {
    if ( ! response.containsHeader( X_FRAME_HEADER ) ) {
        /** 使用 X-Frame-Options 防止被iframe 造成跨域iframe 提交挂掉 **/
        response.addHeader( X_FRAME_HEADER , X_FRAME_VALUE );
    }
}
 
Example 13
Source File: RequestMappingHandlerAdapter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected ModelAndView handleInternal(HttpServletRequest request,
		HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {
	// 注释 10. 调用适配器方法
	ModelAndView mav;
	checkRequest(request);

	// Execute invokeHandlerMethod in synchronized block if required.
	// 判断 synchronizeOnSession 是否开启,开启的话,同一个 session 的请求将会串行执行
	if (this.synchronizeOnSession) {
		HttpSession session = request.getSession(false);
		if (session != null) {
			Object mutex = WebUtils.getSessionMutex(session);
			synchronized (mutex) {
				mav = invokeHandlerMethod(request, response, handlerMethod);
			}
		}
		else {
			// No HttpSession available -> no mutex necessary
			mav = invokeHandlerMethod(request, response, handlerMethod);
		}
	}
	else {
		// No synchronization on session demanded at all...
		// 执行适配中真正的方法
		mav = invokeHandlerMethod(request, response, handlerMethod);
	}

	if (!response.containsHeader(HEADER_CACHE_CONTROL)) {
		if (getSessionAttributesHandler(handlerMethod).hasSessionAttributes()) {
			applyCacheSeconds(response, this.cacheSecondsForSessionAttributeHandlers);
		}
		else {
			prepareResponse(response);
		}
	}

	return mav;
}
 
Example 14
Source File: PluginHelper.java    From odo with Apache License 2.0 5 votes vote down vote up
public static void writeResponseContent(HttpServletResponse response, String content) throws IOException {
    // check to see if this is chunked
    boolean chunked = false;
    if (response.containsHeader(PluginHelper.STRING_TRANSFER_ENCODING)
            && response.getHeader(PluginHelper.STRING_TRANSFER_ENCODING).compareTo("chunked") == 0) {
        response.setHeader(PluginHelper.STRING_CONNECTION, PluginHelper.STRING_CHUNKED);
        chunked = true;
    }

    // check to see if this content is supposed to be compressed
    // if so recompress it
    boolean isEncoded = false;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    if (response.getHeader("content-encoding") != null &&
            response.getHeader("content-encoding").equals("gzip")) {
        // GZIP the data
        isEncoded = true;
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        gzip.write(content.getBytes());
        gzip.close();
        out.close();
    } else if (response.getHeader("content-encoding") != null &&
            response.getHeader("content-encoding").equals("deflate")) {
        // Deflate the data
        isEncoded = true;
        Deflater compressor = new Deflater();
        compressor.setInput(content.getBytes());
        compressor.finish();

        byte[] buffer = new byte[1024];
        while (!compressor.finished()) {
            int count = compressor.deflate(buffer);
            out.write(buffer, 0, count);
        }
        out.close();
        compressor.end();
    }


    // don't do this if we got a HTTP 304 since there is no data to send back
    if (response.getStatus() != HttpServletResponse.SC_NOT_MODIFIED) {
        if (!chunked) {
            // change the content length header to the new length
            if (content != null && !isEncoded) {
                response.setContentLength(content.getBytes().length);
            } else if (isEncoded) {
                response.setContentLength(out.toByteArray().length);
            }
        }

        OutputStream outputStreamClientResponse = response.getOutputStream();
        response.resetBuffer();

        if (content != null && !isEncoded) {
            outputStreamClientResponse.write(content.getBytes());
        } else if (isEncoded) {
            outputStreamClientResponse.write(out.toByteArray());
        }
    }
}
 
Example 15
Source File: HttpUtils.java    From scoold with Apache License 2.0 5 votes vote down vote up
/**
 * Fetches an avatar at a given URL.
 * @param url image URL
 * @param res response
 * @return the content of the image or null
 */
public static void getAvatar(String url, HttpServletResponse res) {
	if (StringUtils.isBlank(url)) {
		getDefaultAvatarImage(res);
		return;
	}
	HttpGet get = new HttpGet(url);
	get.setHeader(HttpHeaders.USER_AGENT, "Scoold Image Validator, https://scoold.com");
	try (CloseableHttpResponse img = HttpUtils.getHttpClient().execute(get)) {
		if (img.getStatusLine().getStatusCode() == HttpStatus.SC_OK && img.getEntity() != null) {
			String contentType = img.getEntity().getContentType().getValue();
			if (StringUtils.equalsAnyIgnoreCase(contentType, "image/gif", "image/jpeg", "image/jpg", "image/png",
					"image/webp", "image/bmp", "image/svg+xml")) {
				for (Header header : img.getAllHeaders()) {
					res.setHeader(header.getName(), header.getValue());
				}
				if (!res.containsHeader(org.apache.http.HttpHeaders.CACHE_CONTROL)) {
					res.setHeader(org.apache.http.HttpHeaders.CACHE_CONTROL, "max-age=" + TimeUnit.HOURS.toSeconds(24));
				}
				IOUtils.copy(img.getEntity().getContent(), res.getOutputStream());
			}
		} else {
			LoggerFactory.getLogger(HttpUtils.class).debug("Failed to get user avatar from {}, status: {} {}", url,
					img.getStatusLine().getStatusCode(), img.getStatusLine().getReasonPhrase());
			getDefaultAvatarImage(res);
		}
	} catch (IOException ex) {
		getDefaultAvatarImage(res);
		LoggerFactory.getLogger(HttpUtils.class).debug("Failed to get user avatar from {}: {}", url, ex.getMessage());
	}
}
 
Example 16
Source File: WebContentGenerator.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Set the HTTP Cache-Control header according to the given settings.
 * @param response current HTTP response
 * @param cacheControl the pre-configured cache control settings
 * @since 4.2
 */
protected final void applyCacheControl(HttpServletResponse response, CacheControl cacheControl) {
	String ccValue = cacheControl.getHeaderValue();
	if (ccValue != null) {
		// Set computed HTTP 1.1 Cache-Control header
		response.setHeader(HEADER_CACHE_CONTROL, ccValue);

		if (response.containsHeader(HEADER_PRAGMA)) {
			// Reset HTTP 1.0 Pragma header if present
			response.setHeader(HEADER_PRAGMA, "");
		}
	}
}
 
Example 17
Source File: HttpUtils.java    From cosmic with Apache License 2.0 5 votes vote down vote up
public static void addSecurityHeaders(final HttpServletResponse resp) {
    if (resp.containsHeader("X-Content-Type-Options")) {
        resp.setHeader("X-Content-Type-Options", "nosniff");
    } else {
        resp.addHeader("X-Content-Type-Options", "nosniff");
    }
    if (resp.containsHeader("X-XSS-Protection")) {
        resp.setHeader("X-XSS-Protection", "1;mode=block");
    } else {
        resp.addHeader("X-XSS-Protection", "1;mode=block");
    }
}
 
Example 18
Source File: AtlasAuthenticationFilter.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
private static String readUserFromCookie(HttpServletResponse response1) {
    String userName = null;
    boolean isCookieSet = response1.containsHeader("Set-Cookie");
    if (isCookieSet) {
        Collection<String> authUserName = response1.getHeaders("Set-Cookie");
        if (authUserName != null) {
            for (String cookie : authUserName) {
                if (!StringUtils.isEmpty(cookie)) {
                    if (cookie.toLowerCase().startsWith(AuthenticatedURL.AUTH_COOKIE.toLowerCase()) && cookie.contains("u=")) {
                        String[] split = cookie.split(";");
                        if (split != null) {
                            for (String s : split) {
                                if (!StringUtils.isEmpty(s) && s.toLowerCase().startsWith(AuthenticatedURL.AUTH_COOKIE.toLowerCase())) {
                                    int ustr = s.indexOf("u=");
                                    if (ustr != -1) {
                                        int andStr = s.indexOf("&", ustr);
                                        if (andStr != -1) {
                                            try {
                                                userName = s.substring(ustr + 2, andStr);
                                                break;
                                            } catch (Exception e) {
                                                userName = null;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return userName;
}
 
Example 19
Source File: WebConfig.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 4 votes vote down vote up
@Bean
public Filter addMissingHeadersFilter()
{
	return new Filter()
	{

		@Override
		public void init(final FilterConfig filterConfig) throws ServletException
		{
		}

		@Override
		public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException
		{
			try
			{
				chain.doFilter(request, response);
			}
			finally
			{
				if (response instanceof HttpServletResponse)
				{
					final HttpServletResponse httpResponse = (HttpServletResponse)response;
					
					//
					// If the Cache-Control is not set then set it to no-cache.
					// In this way we precisely tell to browser that it shall not cache our REST calls.
					// The Cache-Control is usually defined by features like ETag
					if (!httpResponse.containsHeader("Cache-Control"))
					{
						httpResponse.setHeader("Cache-Control", "no-cache");
					}
				}
			}
		}

		@Override
		public void destroy()
		{
		}
	};
}
 
Example 20
Source File: GZipResponseUtil.java    From ServiceCutter with Apache License 2.0 3 votes vote down vote up
/**
 * Adds the gzip HTTP header to the response.
 * <p/>
 * <p>
 * This is need when a gzipped body is returned so that browsers can properly decompress it.
 * </p>
 *
 * @param response the response which will have a header added to it. I.e this method changes its parameter
 * @throws GzipResponseHeadersNotModifiableException Either the response is committed or we were called using the include method
 *                                                   from a {@link javax.servlet.RequestDispatcher#include(javax.servlet.ServletRequest, javax.servlet.ServletResponse)}
 *                                                   method and the set header is ignored.
 */
public static void addGzipHeader(HttpServletResponse response) throws GzipResponseHeadersNotModifiableException {
    response.setHeader("Content-Encoding", "gzip");
    boolean containsEncoding = response.containsHeader("Content-Encoding");
    if (!containsEncoding) {
        throw new GzipResponseHeadersNotModifiableException("Failure when attempting to set "
                + "Content-Encoding: gzip");
    }
}