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.jahia.bin.Render.java

/**
 * Sets the Last-Modified entity header field, if it has not already been set and if the value is meaningful. Called before doGet, to
 * ensure that headers are set before response data is written. A subclass might have set this header already, so we check.
 *///from   ww w  .  j  av a  2s.c o m
protected void maybeSetLastModified(HttpServletResponse resp, long lastModified) {
    if (resp.containsHeader(HEADER_LASTMOD)) {
        return;
    }
    if (lastModified >= 0) {
        resp.setDateHeader(HEADER_LASTMOD, lastModified);
    }
}

From source file:org.duracloud.duradmin.control.ContentItemDownloadController.java

@RequestMapping(value = "/download/contentItem", method = RequestMethod.GET)
public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    String storeId = request.getParameter("storeID");
    if (storeId == null) {
        storeId = request.getParameter("storeId");
    }/*from ww w. ja va2  s.c  o  m*/

    if (storeId == null) {
        storeId = controllerSupport.getContentStoreManager().getPrimaryContentStore().getStoreId();
    }

    String spaceId = request.getParameter("spaceId");
    String contentId = request.getParameter("contentId");
    String attachment = request.getParameter("attachment");

    if (Boolean.valueOf(attachment)) {
        StringBuffer contentDisposition = new StringBuffer();
        contentDisposition.append("attachment;");
        contentDisposition.append("filename=\"");
        contentDisposition.append(contentId);
        contentDisposition.append("\"");
        response.setHeader(CONTENT_DISPOSITION_HEADER, contentDisposition.toString());
    }

    ContentStore store = controllerSupport.getContentStoreManager().getContentStore(storeId);
    try {
        SpaceUtil.streamContent(store, response, spaceId, contentId);

    } catch (ContentStoreException ex) {
        if (response.containsHeader(CONTENT_DISPOSITION_HEADER)) {
            response.setHeader(CONTENT_DISPOSITION_HEADER, null);
        }

        if (ex instanceof ContentStateException) {
            response.setStatus(HttpStatus.SC_CONFLICT);
        } else if (ex instanceof UnauthorizedException) {
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        }

        Throwable t = ex;
        if (t.getCause() != null) {
            t = ex.getCause();
        }
        response.getWriter().println(t.getMessage());
    }

    return null;
}

From source file:org.springframework.extensions.webscripts.servlet.mvc.ResourceController.java

protected void applyHeaders(final String path, final HttpServletResponse response, final long contentLength,
        final long lastModified) {
    // determine mimetype
    String mimetype = getServletContext().getMimeType(path);
    if (mimetype == null) {
        String extension = ".bin";
        final int extIndex = path.lastIndexOf('.');
        if (extIndex != -1) {
            extension = path.substring(extIndex);
            mimetype = (String) defaultMimeTypes.get(extension.toLowerCase());
        }//from  ww  w  .  java2s  . c  o  m
    }

    // set response headers
    if (mimetype != null && mimetype.startsWith("text/")) {
        // ensure text encoding is applied
        mimetype += ";charset=UTF-8";
    }
    response.setContentType(mimetype);
    response.setHeader(HTTP_HEADER_CONTENT_LENGTH, Long.toString(contentLength));
    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:org.opencms.loader.CmsDumpLoader.java

/**
 * @see org.opencms.loader.I_CmsResourceLoader#load(org.opencms.file.CmsObject, org.opencms.file.CmsResource, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///from   w w  w .ja v a 2s  .co  m
public void load(CmsObject cms, CmsResource resource, HttpServletRequest req, HttpServletResponse res)
        throws IOException, CmsException {

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

    // make sure we have the file contents available
    CmsFile file = cms.readFile(resource);

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

    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, file.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, file, req, res);
}

From source file:com.groupon.odo.Proxy.java

/**
 * @param httpServletResponse/*from   w  w  w  .ja  v a2s .co m*/
 * @param outStream
 * @param jsonpCallback
 * @throws IOException
 */
private void writeResponseOutput(HttpServletResponse httpServletResponse, OutputStream outStream,
        String jsonpCallback) throws IOException {
    RequestInformation requestInfo = requestInformation.get();

    // check to see if this is chunked
    boolean chunked = false;
    if (httpServletResponse.containsHeader(HttpUtilities.STRING_TRANSFER_ENCODING) && httpServletResponse
            .getHeader(HttpUtilities.STRING_TRANSFER_ENCODING).compareTo("chunked") == 0) {
        httpServletResponse.setHeader(HttpUtilities.STRING_CONNECTION, HttpUtilities.STRING_CHUNKED);
        chunked = true;
    }

    // reattach JSONP if needed
    if (requestInfo.outputString != null && jsonpCallback != null) {
        requestInfo.outputString = jsonpCallback + "(" + requestInfo.outputString + ");";
    }

    // don't do this if we got a HTTP 304 since there is no data to send back
    if (httpServletResponse.getStatus() != HttpServletResponse.SC_NOT_MODIFIED) {
        logger.info("Chunked: {}, {}", chunked, httpServletResponse.getBufferSize());
        if (!chunked) {
            // change the content length header to the new length
            if (requestInfo.outputString != null) {
                httpServletResponse.setContentLength(requestInfo.outputString.getBytes().length);
            } else {
                httpServletResponse.setContentLength(((ByteArrayOutputStream) outStream).toByteArray().length);
            }
        }

        OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();

        if (requestInfo.outputString != null) {
            outputStreamClientResponse.write(requestInfo.outputString.getBytes());
        } else {
            outputStreamClientResponse.write(((ByteArrayOutputStream) outStream).toByteArray());
        }
        httpServletResponse.flushBuffer();

        logger.info("Done writing");
    }

    // outstr might still be null.. let's try to set it from outStream
    if (requestInfo.outputString == null) {
        try {
            requestInfo.outputString = outStream.toString();
        } catch (Exception e) {
            // can ignore any issues.. worst case outstr is still null
        }
    }
}

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

/**
 * Eventually update response headers for image resources
 * @param target the query target//from  w  w w  . ja v  a 2 s  . co m
 * @param response servlet response to eventually update
 */
private void updateRespHeadersForImages(String target, HttpServletResponse response) {
    if (target.equals("/ViewImage.png") || target.equals("/ViewFavicon.png")) {
        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
    }
}

From source file:org.exist.http.urlrewrite.XQueryURLRewrite.java

private void response(DBBroker broker, HttpServletResponse response, Properties outputProperties,
        Sequence resultSequence) throws IOException {

    final String encoding = outputProperties.getProperty(OutputKeys.ENCODING);
    final ServletOutputStream sout = response.getOutputStream();
    final PrintWriter output = new PrintWriter(new OutputStreamWriter(sout, encoding));
    if (!response.containsHeader("Content-Type")) {
        String mimeType = outputProperties.getProperty(OutputKeys.MEDIA_TYPE);
        if (mimeType != null) {
            final int semicolon = mimeType.indexOf(';');
            if (semicolon != Constants.STRING_NOT_FOUND) {
                mimeType = mimeType.substring(0, semicolon);
            }//from  w w  w.j a va 2s .  com
            response.setContentType(mimeType + "; charset=" + encoding);
        }
    }

    //        response.addHeader( "pragma", "no-cache" );
    //        response.addHeader( "Cache-Control", "no-cache" );

    final Serializer serializer = broker.getSerializer();
    serializer.reset();

    final SerializerPool serializerPool = SerializerPool.getInstance();

    final SAXSerializer sax = (SAXSerializer) serializerPool.borrowObject(SAXSerializer.class);
    try {
        sax.setOutput(output, outputProperties);

        serializer.setProperties(outputProperties);
        serializer.setSAXHandlers(sax, sax);
        serializer.toSAX(resultSequence, 1, resultSequence.getItemCount(), false, false);

    } catch (final SAXException e) {
        throw new IOException(e);
    } finally {
        serializerPool.returnObject(sax);
    }
    output.flush();
    output.close();
}

From source file:org.wings.externalizer.AbstractExternalizeManager.java

public void deliver(ExternalizedResource extInfo, HttpServletResponse response, Device out) throws IOException {
    /* FIXME: re-implement.
    if ( extInfo.deliverOnce() ) {/*  w  w w  . j av  a  2  s .  co m*/
    removeExternalizedResource(identifier);
    }
    */

    if (extInfo.getMimeType() != null) {
        response.setContentType(extInfo.getMimeType());
    }

    // FIXME find out, if this is correct: if the content length
    // is not size preserving (like a gzip-device), then we must not
    // send the content size we know..
    if (out.isSizePreserving()) {
        int resourceLen = extInfo.getExternalizer().getLength(extInfo.getObject());
        if (resourceLen > 0) {
            LOG.debug(extInfo.getMimeType() + ": " + resourceLen);
            response.setContentLength(resourceLen);
        }
    }

    Collection headers = extInfo.getHeaders();
    if (headers != null) {
        for (Object header : headers) {
            Map.Entry entry = (Map.Entry) header;
            if (entry.getValue() instanceof String) {
                response.addHeader((String) entry.getKey(), (String) entry.getValue());
            } else if (entry.getValue() instanceof Date) {
                response.addDateHeader((String) entry.getKey(), ((Date) entry.getValue()).getTime());

            } else if (entry.getValue() instanceof Integer) {
                response.addIntHeader((String) entry.getKey(), ((Integer) entry.getValue()).intValue());

            } // end of if ()
        }
    }

    if (!response.containsHeader("Expires")) {
        /*
        * This would be the correct way to do it; alas, that means, that
        * for static resources, after a day or so, no caching could take
        * place, since the last modification was at the first time, the
        * resource was externalized (since it doesn't change).
        * .. have to think about it.
        */
        //response.setDateHeader("Expires",
        //                      (1000*FINAL_EXPIRES)
        //                       + extInfo.getLastModified());
        // .. so do this for now, which is the best approximation of what
        // we want.
        response.setDateHeader("Expires", System.currentTimeMillis() + (1000 * FINAL_EXPIRES));
    }

    try {
        extInfo.getExternalizer().write(extInfo.getObject(), out);
    } catch (ResourceNotFoundException e) {
        LOG.debug("Unable to deliver resource due to:  " + e.getMessage() + ". Sending 404!");
        response.reset();
        response.sendError(404, e.getMessage());
    }
    out.flush();
}

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

/**
 * send static content/*from w w  w.j a v a 2s .c  o 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();
    }
}

From source file:org.alfresco.module.vti.web.VtiFilter.java

/**
 * <p>/*from w w w .j a  va 2 s  . c  o  m*/
 * Process the specified HTTP request, check authentication, resource existence, access to document workspace and write specific protocol headers to response.
 * </p>
 * 
 * @param request HTTP request
 * @param response HTTP response
 * @param chain filter chain
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    validSiteUri(httpRequest);
    Object validSiteUrl = httpRequest.getAttribute("VALID_SITE_URL");
    if (logger.isDebugEnabled()) {
        logger.debug("Checking request for VTI");
    }
    String uri = httpRequest.getRequestURI();
    HttpSession session = httpRequest.getSession(false);
    if (session == null) {
        if (validSiteUrl == null && !uri.endsWith(".vti")) {
            session = httpRequest.getSession();
        } else {
            chain.doFilter(request, response);
            return;
        }
    }

    String httpMethod = httpRequest.getMethod();

    String ifHeader = httpRequest.getHeader("If");
    String ifNonMatchHeader = httpRequest.getHeader("If-None-Match");
    boolean checkResourceExistence = false;
    if ((METHOD_GET.equals(httpMethod) || METHOD_HEAD.equals(httpMethod)) && !uri.equals("/_vti_inf.html")
            && !uri.contains("_vti_bin") && !uri.contains("/_vti_history")
            && !uri.startsWith(getAlfrescoContext() + "/resources") && ifHeader == null
            && ifNonMatchHeader == null) {
        if (validSiteUrl != null || uri.endsWith(".vti")) {
            writeHeaders(httpRequest, httpResponse);
            chain.doFilter(httpRequest, httpResponse);
            return;
        } else {
            checkResourceExistence = true;
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Check authentication");
    }

    SessionUser user = null;

    try {
        user = authenticationHandler.authenticateRequest(this.context, httpRequest, httpResponse,
                getAlfrescoContext());
    } catch (SiteMemberMappingException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("An exception occurred during authenticating request.", e);
        }
        httpResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
        httpResponse.getOutputStream().close();
        return;
    }

    if (user == null) {
        if (!httpResponse.containsHeader(AUTHENTICATE_HEADER)) {
            httpResponse.setHeader(AUTHENTICATE_HEADER, "Basic realm=\"Alfresco Server\"");
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            httpResponse.getOutputStream().close();
        }
        if (logger.isDebugEnabled())
            logger.debug("No authentication details found, requesting they authenticate");
        return;
    } else {
        if (logger.isDebugEnabled())
            logger.debug("User was authenticated successfully");
    }

    if (checkResourceExistence) {
        if (logger.isDebugEnabled()) {
            logger.debug("Checking if resource exists");
        }

        if (!vtiHandler.existResource(httpRequest, httpResponse)) {
            return;
        }
    }

    writeHeaders(httpRequest, httpResponse);
    chain.doFilter(request, response);
}