Example usage for javax.servlet.http HttpServletResponse getHeaders

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

Introduction

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

Prototype

public Collection<String> getHeaders(String name);

Source Link

Document

Gets the values of the response header with the given name.

Usage

From source file:it.greenvulcano.gvesb.adapter.http.utils.DumpUtils.java

public static void dump(HttpServletResponse response, ByteArrayOutputStream body, StringBuffer log) {

    log.append("-- DUMP HttpServletResponse START").append("\n");
    log.append("Status: ").append(response.getStatus()).append("\n");
    log.append("---- Headers START\n");

    response.getHeaderNames().stream()/*w w w  .j a  va  2 s .c  o  m*/
            .map(headerName -> "[" + headerName + "]=[" + response.getHeaders(headerName) + "]")
            .forEach(h -> log.append(h));

    log.append("---- Headers END\n");

    log.append("---- Body START\n");
    log.append(body.toString()).append("\n");
    log.append("---- Body END\n");

    log.append("-- DUMP HttpServletResponse END \n");
}

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

/**
 * @param resp// w w w  .ja v a 2  s  .c  o  m
 * @return
 * @throws AuthTokenException
 */
public static AuthToken getAuthTokenFromResponse(HttpServletResponse resp) throws AuthTokenException {
    List<String> headers = (List<String>) resp.getHeaders("Set-Cookie");
    AuthToken at = null;
    for (String s : headers) {
        if (!StringUtil.isNullOrEmpty(s) && s.contains("ZM_AUTH_TOKEN")) {
            String temp[] = s.split("=");
            int index = temp[1].indexOf(";");
            String token = temp[1].substring(0, index);
            at = AuthToken.getAuthToken(token);
        }
    }
    return at;
}

From source file:cn.guoyukun.spring.web.filter.DebugRequestAndResponseFilter.java

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);
    }//from ww w. j  a va 2  s .com
    log.debug("===header   end============================================");
    log.debug("=====================response   end==========================");
}

From source file:com.zimbra.cs.dav.service.DavServlet.java

public static StringBuilder addResponseHeaderLoggingInfo(HttpServletResponse resp, StringBuilder sb) {
    if (!ZimbraLog.dav.isDebugEnabled()) {
        return sb;
    }//w  ww.  j  a va  2s . c o  m
    sb.append("DAV RESPONSE:\n");
    String statusLine = DavResponse.sStatusTextMap.get(resp.getStatus());
    if (statusLine != null) {
        sb.append(statusLine);
    } else {
        sb.append("HTTP/1.1 ").append(resp.getStatus());
    }
    Collection<String> hdrNames = resp.getHeaderNames();
    if (hdrNames != null && !hdrNames.isEmpty()) {
        for (String hdrName : hdrNames) {
            if (hdrName.contains("Auth") || (hdrName.contains(HttpHeaders.COOKIE))) {
                sb.append("\n").append(hdrName).append(": *** REPLACED ***");
                continue;
            }
            Collection<String> vals = resp.getHeaders(hdrName);
            for (String val : vals) {
                sb.append("\n").append(hdrName).append(": ").append(val);
            }
        }
    }
    sb.append("\n\n");
    return sb;
}

From source file:com.usefullc.platform.common.log.LogHandlerInterceptor.java

@Override
public void afterHandler(ActionHandler actionHandler) {
    if (!this.monitor) { // ?
        return;//  www .ja  va  2  s . c  om
    }
    Long userId = OnlineUserManager.getUserId();
    if (userId == null) { // 
        return;
    }
    // logInfo
    LogInfoDto domain = threadLocal.get();
    if (domain == null) {
        return;
    }
    HttpServletResponse response = actionHandler.getResponse();

    domain.setActionState(actionHandler.getState());

    // ?
    if (!actionHandler.getState()) {
        domain.setErrMsg(actionHandler.getErrMsg());
    }

    // request headers
    JSONObject jsonObj = new JSONObject();

    Collection<String> headerNames = response.getHeaderNames(); //
    for (String headerName : headerNames) {
        Collection<String> headerValues = response.getHeaders(headerName);
        StringBuilder sb = new StringBuilder();
        for (String headerValue : headerValues) {
            sb.append(headerValue);
            sb.append(",");
        }
        if (sb.length() > 0) {
            sb.substring(0, sb.length() - 1);
        }
        jsonObj.put(headerName, sb.toString());
    }
    domain.setResponseHeader(jsonObj.toString());

    domain.setStatus(String.valueOf(response.getStatus()));

    // ??
    logInfoRemoteService.insertLogInfo(domain);

    // ?
    threadLocal.set(null);
}

From source file:com.codename1.corsproxy.CORSProxy.java

@Override
protected void copyResponseHeaders(final HttpResponse proxyResponse, final HttpServletRequest servletRequest,
        final HttpServletResponse servletResponse) {

    HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(servletResponse) {

        @Override/*from   www. j ava 2s.co  m*/
        public void addHeader(String name, String value) {
            if ("Location".equalsIgnoreCase(name)) {
                super.addHeader("X-CN1-" + name, value);

            } else if ("Content-Security-Policy".equalsIgnoreCase(name)) {

            } else {
                super.addHeader(name, value);
            }
        }

    };
    super.copyResponseHeaders(proxyResponse, servletRequest, responseWrapper); //To change body of generated methods, choose Tools | Templates.
    servletResponse.setHeader("Access-Control-Expose-Headers", "Set-Cookie, Set-Cookie2");
    Collection<String> cookies = servletResponse.getHeaders("Set-Cookie");
    if (cookies != null) {
        for (String cookie : cookies) {
            servletResponse.addHeader("X-CN1-Set-Cookie", cookie);
        }
    }

    //servletResponse.setHeader("Access-Control-Allow-Origin", "*");

}

From source file:com.kurento.kmf.repository.internal.http.RepositoryHttpServlet.java

private void logResponse(HttpServletResponse resp) {

    Collection<String> headerNames = resp.getHeaderNames();
    for (String headerName : headerNames) {
        Collection<String> values = resp.getHeaders(headerName);
        log.info("  Header {}: {}", headerName, values);
    }/*from   w  w w.  j a  v a2s  . c  o m*/
}

From source file:net.yacy.http.servlets.YaCyDefaultServlet.java

/**
 * send static content/*from  w ww .  ja va 2 s.  co m*/
 * 
 * @param request
 * @param response
 * @param include  is a include file (send without changing/adding headers)
 * @param resource the static content
 * @param reqRanges
 * @throws IOException 
 */
protected void sendData(HttpServletRequest request, HttpServletResponse response, boolean include,
        Resource resource, Enumeration<String> reqRanges) throws IOException {

    final long content_length = resource.length();

    // Get the output stream (or writer)
    OutputStream out;
    try {
        out = response.getOutputStream();
    } catch (IllegalStateException e) {
        out = new WriterOutputStream(response.getWriter());
    }

    // remove the last-modified field since caching otherwise does not work
    /*
       https://www.ietf.org/rfc/rfc2616.txt
       "if the response does have a Last-Modified time, the heuristic
       expiration value SHOULD be no more than some fraction of the interval
       since that time. A typical setting of this fraction might be 10%."
    */
    if (response.containsHeader(HeaderFramework.LAST_MODIFIED)) {
        response.getHeaders(HeaderFramework.LAST_MODIFIED).clear(); // if this field is present, the reload-time is a 10% fraction of ttl and other caching headers do not work
    }

    // cache-control: allow shared caching (i.e. proxies) and set expires age for cache
    response.setHeader(HeaderFramework.CACHE_CONTROL, "public, max-age=" + Integer.toString(600)); // seconds; ten minutes

    if (reqRanges == null || !reqRanges.hasMoreElements() || content_length < 0) {
        //  if there were no ranges, send entire entity
        if (include) {
            resource.writeTo(out, 0, content_length);
        } else {
            writeHeaders(response, resource, content_length);
            resource.writeTo(out, 0, content_length);
        }
    } else {
        // Parse the satisfiable ranges
        List<?> ranges = InclusiveByteRange.satisfiableRanges(reqRanges, content_length);

        //  if there are no satisfiable ranges, send 416 response
        if (ranges == null || ranges.isEmpty()) {
            writeHeaders(response, resource, content_length);
            response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            response.setHeader(HttpHeader.CONTENT_RANGE.asString(),
                    InclusiveByteRange.to416HeaderRangeString(content_length));
            resource.writeTo(out, 0, content_length);
            out.close();
            return;
        }

        //  if there is only a single valid range (must be satisfiable
        //  since were here now), send that range with a 216 response
        if (ranges.size() == 1) {
            InclusiveByteRange singleSatisfiableRange = (InclusiveByteRange) ranges.get(0);
            long singleLength = singleSatisfiableRange.getSize(content_length);
            writeHeaders(response, resource, singleLength);
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
            response.setHeader(HttpHeader.CONTENT_RANGE.asString(),
                    singleSatisfiableRange.toHeaderRangeString(content_length));
            resource.writeTo(out, singleSatisfiableRange.getFirst(content_length), singleLength);
            out.close();
            return;
        }

        //  multiple non-overlapping valid ranges cause a multipart
        //  216 response which does not require an overall
        //  content-length header
        //
        writeHeaders(response, resource, -1);
        String mimetype = response.getContentType();
        if (mimetype == null) {
            ConcurrentLog.warn("FILEHANDLER",
                    "YaCyDefaultServlet: Unknown mimetype for " + request.getRequestURI());
        }
        MultiPartOutputStream multi = new MultiPartOutputStream(out);
        response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

        // If the request has a "Request-Range" header then we need to
        // send an old style multipart/x-byteranges Content-Type. This
        // keeps Netscape and acrobat happy. This is what Apache does.
        String ctp;
        if (request.getHeader(HttpHeader.REQUEST_RANGE.asString()) != null) {
            ctp = "multipart/x-byteranges; boundary=";
        } else {
            ctp = "multipart/byteranges; boundary=";
        }
        response.setContentType(ctp + multi.getBoundary());

        InputStream in = resource.getInputStream();
        long pos = 0;

        // calculate the content-length
        int length = 0;
        String[] header = new String[ranges.size()];
        for (int i = 0; i < ranges.size(); i++) {
            InclusiveByteRange ibr = (InclusiveByteRange) ranges.get(i);
            header[i] = ibr.toHeaderRangeString(content_length);
            length += ((i > 0) ? 2 : 0) + 2 + multi.getBoundary().length() + 2
                    + (mimetype == null ? 0 : HeaderFramework.CONTENT_TYPE.length() + 2 + mimetype.length()) + 2
                    + HeaderFramework.CONTENT_RANGE.length() + 2 + header[i].length() + 2 + 2
                    + (ibr.getLast(content_length) - ibr.getFirst(content_length)) + 1;
        }
        length += 2 + 2 + multi.getBoundary().length() + 2 + 2;
        response.setContentLength(length);

        for (int i = 0; i < ranges.size(); i++) {
            InclusiveByteRange ibr = (InclusiveByteRange) ranges.get(i);
            multi.startPart(mimetype, new String[] { HeaderFramework.CONTENT_RANGE + ": " + header[i] });

            long start = ibr.getFirst(content_length);
            long size = ibr.getSize(content_length);
            if (in != null) {
                // Handle non cached resource
                if (start < pos) {
                    in.close();
                    in = resource.getInputStream();
                    pos = 0;
                }
                if (pos < start) {
                    in.skip(start - pos);
                    pos = start;
                }

                FileUtils.copy(in, multi, size);
                pos += size;
            } else // Handle cached resource
            {
                (resource).writeTo(multi, start, size);
            }

        }
        if (in != null)
            in.close();
        multi.close();
    }
}