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

The following examples show how to use javax.servlet.http.HttpServletResponse#getHeaderNames() . 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: CallImpl.java    From heimdall with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, String> getAll() {

     HttpServletResponse r = context.getResponse();
     List<String> names = new ArrayList<>(r.getHeaderNames());
     
     Map<String, String> headers = new HashMap<>();
     names.forEach(name -> {
          
          if (r.getHeader(name) != null) {
               
               headers.put(name, r.getHeader(name));
          }
     });
     
     return headers; 
}
 
Example 2
Source File: HttpUtilities.java    From odo with Apache License 2.0 6 votes vote down vote up
/**
 * Obtain newline-delimited headers from response
 *
 * @param response HttpServletResponse to scan
 * @return newline-delimited headers
 */
public static String getHeaders(HttpServletResponse response) {
    String headerString = "";
    Collection<String> headerNames = response.getHeaderNames();
    for (String headerName : headerNames) {
        // there may be multiple headers per header name
        for (String headerValue : response.getHeaders(headerName)) {
            if (headerString.length() != 0) {
                headerString += "\n";
            }

            headerString += headerName + ": " + headerValue;
        }
    }

    return headerString;
}
 
Example 3
Source File: ApmAsyncListener.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
private void endTransaction(AsyncEvent event) {
    // To ensure transaction is ended only by a single event
    if (completed.getAndSet(true) || transaction == null) {
        return;
    }

    try {
        HttpServletRequest request = (HttpServletRequest) event.getSuppliedRequest();
        request.removeAttribute(TRANSACTION_ATTRIBUTE);

        HttpServletResponse response = (HttpServletResponse) event.getSuppliedResponse();
        final Response resp = transaction.getContext().getResponse();
        if (transaction.isSampled() && servletTransactionHelper.isCaptureHeaders()) {
            for (String headerName : response.getHeaderNames()) {
                resp.addHeader(headerName, response.getHeaders(headerName));
            }
        }
        // request.getParameterMap() may allocate a new map, depending on the servlet container implementation
        // so only call this method if necessary
        final String contentTypeHeader = request.getHeader("Content-Type");
        final Map<String, String[]> parameterMap;
        if (transaction.isSampled() && servletTransactionHelper.captureParameters(request.getMethod(), contentTypeHeader)) {
            parameterMap = request.getParameterMap();
        } else {
            parameterMap = null;
        }
        Throwable throwableToSend = event.getThrowable();
        if (throwableToSend == null) {
            throwableToSend = throwable;
        }
        servletTransactionHelper.onAfter(transaction, throwableToSend,
            response.isCommitted(), response.getStatus(), true, request.getMethod(), parameterMap,
            request.getServletPath(), request.getPathInfo(), contentTypeHeader, false
        );
    } finally {
        asyncContextAdviceHelperImpl.recycle(this);
    }
}
 
Example 4
Source File: IpcServletFilter.java    From spectator with Apache License 2.0 5 votes vote down vote up
private void addResponseHeaders(HttpServletResponse httpRes, IpcLogEntry entry) {
  Collection<String> headers = httpRes.getHeaderNames();
  for (String header : headers) {
    Collection<String> values = httpRes.getHeaders(header);
    for (String value : values) {
      entry.addResponseHeader(header, value);
    }
  }
}
 
Example 5
Source File: RepositoryHttpServlet.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
private void logResponse(HttpServletResponse resp) {

    Collection<String> headerNames = resp.getHeaderNames();
    for (String headerName : headerNames) {
      Collection<String> values = resp.getHeaders(headerName);
      log.debug("  Header {}: {}", headerName, values);
    }
  }
 
Example 6
Source File: DebugRequestAndResponseFilter.java    From es with Apache License 2.0 5 votes vote down vote up
private void debugResponse(HttpServletResponse response) {
    log.debug("=====================response begin==========================");
    log.debug("status:{}", response.getStatus(), response.getContentType());
    log.debug("contentType:{}, characterEncoding:{}", response.getContentType(), response.getCharacterEncoding());
    log.debug("===header begin============================================");
    Collection<String> headerNames = response.getHeaderNames();
    for (String name : headerNames) {
        String value = StringUtils.join(response.getHeaders(name), "||");
        log.debug("{}={}", name, value);
    }
    log.debug("===header   end============================================");
    log.debug("=====================response   end==========================");
}
 
Example 7
Source File: FrameworkServlet.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private void logResult(HttpServletRequest request, HttpServletResponse response,
		@Nullable Throwable failureCause, WebAsyncManager asyncManager) {

	if (!logger.isDebugEnabled()) {
		return;
	}

	String dispatchType = request.getDispatcherType().name();
	boolean initialDispatch = request.getDispatcherType().equals(DispatcherType.REQUEST);

	if (failureCause != null) {
		if (!initialDispatch) {
			// FORWARD/ERROR/ASYNC: minimal message (there should be enough context already)
			if (logger.isDebugEnabled()) {
				logger.debug("Unresolved failure from \"" + dispatchType + "\" dispatch: " + failureCause);
			}
		}
		else if (logger.isTraceEnabled()) {
			logger.trace("Failed to complete request", failureCause);
		}
		else {
			logger.debug("Failed to complete request: " + failureCause);
		}
		return;
	}

	if (asyncManager.isConcurrentHandlingStarted()) {
		logger.debug("Exiting but response remains open for further handling");
		return;
	}

	int status = response.getStatus();
	String headers = ""; // nothing below trace

	if (logger.isTraceEnabled()) {
		Collection<String> names = response.getHeaderNames();
		if (this.enableLoggingRequestDetails) {
			headers = names.stream().map(name -> name + ":" + response.getHeaders(name))
					.collect(Collectors.joining(", "));
		}
		else {
			headers = names.isEmpty() ? "" : "masked";
		}
		headers = ", headers={" + headers + "}";
	}

	if (!initialDispatch) {
		logger.debug("Exiting from \"" + dispatchType + "\" dispatch, status " + status + headers);
	}
	else {
		HttpStatus httpStatus = HttpStatus.resolve(status);
		logger.debug("Completed " + (httpStatus != null ? httpStatus : status) + headers);
	}
}
 
Example 8
Source File: FrameworkServlet.java    From java-technology-stack with MIT License 4 votes vote down vote up
private void logResult(HttpServletRequest request, HttpServletResponse response,
		@Nullable Throwable failureCause, WebAsyncManager asyncManager) {

	if (!logger.isDebugEnabled()) {
		return;
	}

	String dispatchType = request.getDispatcherType().name();
	boolean initialDispatch = request.getDispatcherType().equals(DispatcherType.REQUEST);

	if (failureCause != null) {
		if (!initialDispatch) {
			// FORWARD/ERROR/ASYNC: minimal message (there should be enough context already)
			if (logger.isDebugEnabled()) {
				logger.debug("Unresolved failure from \"" + dispatchType + "\" dispatch: " + failureCause);
			}
		}
		else if (logger.isTraceEnabled()) {
			logger.trace("Failed to complete request", failureCause);
		}
		else {
			logger.debug("Failed to complete request: " + failureCause);
		}
		return;
	}

	if (asyncManager.isConcurrentHandlingStarted()) {
		logger.debug("Exiting but response remains open for further handling");
		return;
	}

	int status = response.getStatus();
	String headers = ""; // nothing below trace

	if (logger.isTraceEnabled()) {
		Collection<String> names = response.getHeaderNames();
		if (this.enableLoggingRequestDetails) {
			headers = names.stream().map(name -> name + ":" + response.getHeaders(name))
					.collect(Collectors.joining(", "));
		}
		else {
			headers = names.isEmpty() ? "" : "masked";
		}
		headers = ", headers={" + headers + "}";
	}

	if (!initialDispatch) {
		logger.debug("Exiting from \"" + dispatchType + "\" dispatch, status " + status + headers);
	}
	else {
		HttpStatus httpStatus = HttpStatus.resolve(status);
		logger.debug("Completed " + (httpStatus != null ? httpStatus : status) + headers);
	}
}
 
Example 9
Source File: ServletApiAdvice.java    From apm-agent-java with Apache License 2.0 4 votes vote down vote up
@Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class)
public static void onExitServletService(@Advice.Argument(0) ServletRequest servletRequest,
                                        @Advice.Argument(1) ServletResponse servletResponse,
                                        @Advice.Local("transaction") @Nullable Transaction transaction,
                                        @Advice.Local("scope") @Nullable Scope scope,
                                        @Advice.Thrown @Nullable Throwable t,
                                        @Advice.This Object thiz) {
    if (tracer == null) {
        return;
    }
    excluded.set(Boolean.FALSE);
    if (scope != null) {
        scope.close();
    }
    if (thiz instanceof HttpServlet && servletRequest instanceof HttpServletRequest) {
        Transaction currentTransaction = tracer.currentTransaction();
        if (currentTransaction != null) {
            final HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
            ServletTransactionHelper.setTransactionNameByServletClass(httpServletRequest.getMethod(), thiz.getClass(), currentTransaction);
            final Principal userPrincipal = httpServletRequest.getUserPrincipal();
            ServletTransactionHelper.setUsernameIfUnset(userPrincipal != null ? userPrincipal.getName() : null, currentTransaction.getContext());
        }
    }
    if (servletTransactionHelper != null &&
        transaction != null &&
        servletRequest instanceof HttpServletRequest &&
        servletResponse instanceof HttpServletResponse) {

        final HttpServletRequest request = (HttpServletRequest) servletRequest;
        if (request.getAttribute(ServletTransactionHelper.ASYNC_ATTRIBUTE) != null) {
            // HttpServletRequest.startAsync was invoked on this request.
            // The transaction should be handled from now on by the other thread committing the response
            transaction.deactivate();
        } else {
            // this is not an async request, so we can end the transaction immediately
            final HttpServletResponse response = (HttpServletResponse) servletResponse;
            if (transaction.isSampled() && tracer.getConfig(CoreConfiguration.class).isCaptureHeaders()) {
                final Response resp = transaction.getContext().getResponse();
                for (String headerName : response.getHeaderNames()) {
                    resp.addHeader(headerName, response.getHeaders(headerName));
                }
            }
            // request.getParameterMap() may allocate a new map, depending on the servlet container implementation
            // so only call this method if necessary
            final String contentTypeHeader = request.getHeader("Content-Type");
            final Map<String, String[]> parameterMap;
            if (transaction.isSampled() && servletTransactionHelper.captureParameters(request.getMethod(), contentTypeHeader)) {
                parameterMap = request.getParameterMap();
            } else {
                parameterMap = null;
            }

            Throwable t2 = null;
            boolean overrideStatusCodeOnThrowable = true;
            if (t == null) {
                final int size = requestExceptionAttributes.size();
                for (int i = 0; i < size; i++) {
                    String attributeName = requestExceptionAttributes.get(i);
                    Object throwable = request.getAttribute(attributeName);
                    if (throwable instanceof Throwable) {
                        t2 = (Throwable) throwable;
                        if (!attributeName.equals("javax.servlet.error.exception")) {
                            overrideStatusCodeOnThrowable = false;
                        }
                        break;
                    }
                }
            }

            servletTransactionHelper.onAfter(transaction, t == null ? t2 : t, response.isCommitted(), response.getStatus(),
                overrideStatusCodeOnThrowable, request.getMethod(), parameterMap, request.getServletPath(),
                request.getPathInfo(), contentTypeHeader, true
            );
        }
    }
}
 
Example 10
Source File: ResponseHelper.java    From heimdall with Apache License 2.0 4 votes vote down vote up
public static Map<String, String> getResponseHeaders(RequestContext context) {

        Map<String, String> headers = new HashMap<>();

        final HttpServletResponse response = context.getResponse();

        context.getZuulResponseHeaders().forEach(pair -> headers.put(pair.first(), pair.second()));

        final Collection<String> headerNames = response.getHeaderNames();

        headerNames.forEach(s -> headers.putIfAbsent(s, response.getHeader(s)));

        if (!headers.containsKey(HttpHeaders.CONTENT_TYPE)) {
            headers.put(HttpHeaders.CONTENT_TYPE, context.getResponse().getContentType());
        }

        headers.remove("X-Application-Context");

        return headers;
    }
 
Example 11
Source File: IdempotentInterceptor.java    From springcloud-idempotent-starter with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 在DispatcherServlet完全处理完请求后被调用,可用于清理资源等
 * 
 * 当有拦截器抛出异常时,会从当前拦截器往回执行所有的拦截器的afterCompletion()
 */
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
		throws Exception {
	String requestUri = request.getRequestURI();
	int respStatus = response.getStatus();
	logger.info("[afterCompletion] {}, {},{}", requestUri, respStatus, ex == null);

	IdempotentVo idempotentVo = IdempotentHolder.getIdempotentVo();

	if (idempotentVo == null || idempotentVo.getIdempotentKey() == null) {
		IdempotentHolder.clear();
		return;
	}

	String idempotentKey = idempotentVo.getIdempotentKey();
	// 重定向
	if (respStatus >= 300 && respStatus < 400) {
		logger.info("[afterCompletion] a redirect , httpStatusCode:{}", respStatus);
		idempotentVo.setIdempotentStatus(IdempotentVo.IDEMPOMENT_STATUS_REDIRECT);
		idempotentCacheInterface.setCache(idempotentKey, idempotentVo);
	}

	if (IdempotentVo.IDEMPOMENT_STATUS_FINISIED.equals(idempotentVo.getIdempotentStatus())) {

		idempotentVo.setStatusCode(response.getStatus());

		Collection<String> headerNames = response.getHeaderNames();
		if (headerNames != null && headerNames.size() != 0) {
			Map<String, String> headers = new HashMap<>();
			for (String name : headerNames) {
				if (name.equals("Date") || name.equals("Connection") || name.equals("Transfer-Encoding")
						|| name.equals("X-Application-Context")) {
					continue;
				}

				headers.put(name, response.getHeader(name));

			}
			idempotentVo.setHeaders(headers);
		}
		idempotentCacheInterface.setCache(idempotentKey, idempotentVo);
	}

	IdempotentHolder.clear();
}
 
Example 12
Source File: ServerSpanAdapter.java    From uavstack with Apache License 2.0 4 votes vote down vote up
/**
 * 根据HttpServletRequest获取指定格式的headers
 * 
 * @param request
 * @return
 */
private String getResponHeaders(HttpServletResponse response) {

    Map<String, String> result = new HashMap<String, String>();

    try {
        for (String key : response.getHeaderNames()) {
            result.put(key, response.getHeader(key));
        }
    }
    catch (Error e) {
        Object resp = response;
        // 重调用链开启时,获取到原生response
        if (HttpServletResponseWrapper.class.isAssignableFrom(response.getClass())) {
            resp = TransformWrapperUtil.moveWrapper("", response);
        }
        if (resp == null) {
            return JSONHelper.toString(result);
        }
        // for tomcat 6.0.4x
        if ("org.apache.catalina.connector.ResponseFacade".equals(resp.getClass().getName())) {
            resp = ReflectionHelper.getField(resp.getClass(), resp, "response");
            if (resp == null) {
                return JSONHelper.toString(result);
            }

            String[] headerNames = (String[]) ReflectionHelper.invoke(resp.getClass().getName(), resp,
                    "getHeaderNames", null, null, response.getClass().getClassLoader());
            if (headerNames == null) {
                return JSONHelper.toString(result);
            }

            for (String headerName : headerNames) {
                String headerValue = (String) ReflectionHelper.invoke(resp.getClass().getName(), resp, "getHeader",
                        new Class[] { String.class }, new Object[] { headerName },
                        response.getClass().getClassLoader());
                if (headerValue != null) {
                    result.put(headerName, headerValue);
                }
            }
        }
    }
    return JSONHelper.toString(result);
}