Example usage for javax.servlet.http HttpServletResponse setDateHeader

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

Introduction

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

Prototype

public void setDateHeader(String name, long date);

Source Link

Document

Sets a response header with the given name and date-value.

Usage

From source file:com.haulmont.cuba.web.controllers.FileDownloadController.java

@RequestMapping(value = "/download", method = RequestMethod.GET)
public ModelAndView download(HttpServletRequest request, HttpServletResponse response) throws IOException {
    UserSession userSession = getSession(request, response);
    if (userSession == null) {
        error(response);/*from  ww w  . jav a2  s.  c  o m*/
        return null;
    }

    AppContext.setSecurityContext(new SecurityContext(userSession));
    try {
        UUID fileId;
        try {
            fileId = UUID.fromString(request.getParameter("f"));
        } catch (Exception e) {
            log.error(e.toString());
            error(response);
            return null;
        }

        FileDescriptor fd = dataService.load(LoadContext.create(FileDescriptor.class).setId(fileId));
        if (fd == null) {
            log.warn("Unable to find file with id {}", fileId);
            error(response);
            return null;
        }

        String fileName = URLEncodeUtils.encodeUtf8(fd.getName());

        response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache");
        response.setDateHeader(HttpHeaders.EXPIRES, 0);
        response.setHeader(HttpHeaders.CONTENT_TYPE, getContentType(fd));
        response.setHeader(HttpHeaders.PRAGMA, "no-cache");

        boolean attach = Boolean.valueOf(request.getParameter("a"));
        response.setHeader("Content-Disposition",
                (attach ? "attachment" : "inline") + "; filename=" + fileName);

        downloadFromMiddlewareAndWriteResponse(fd, response);
    } finally {
        AppContext.setSecurityContext(null);
    }
    return null;
}

From source file:org.osaf.cosmo.atom.AtomServlet.java

private void output(HttpServletRequest request, HttpServletResponse response, ResponseContext context)
        throws IOException {
    if (context != null) {
        response.setStatus(context.getStatus());
        long cl = context.getContentLength();
        String cc = context.getCacheControl();
        if (cl > -1)
            response.setHeader("Content-Length", Long.toString(cl));
        if (cc != null && cc.length() > 0)
            response.setHeader("Cache-Control", cc);
        try {//from  w w  w.j  av  a  2  s.c  o m
            MimeType ct = context.getContentType();
            if (ct != null)
                response.setContentType(ct.toString());
        } catch (Exception e) {
        }
        String[] names = context.getHeaderNames();
        for (String name : names) {
            Object[] headers = context.getHeaders(name);
            for (Object value : headers) {
                if (value instanceof Date)
                    response.setDateHeader(name, ((Date) value).getTime());
                else
                    response.setHeader(name, value.toString());
            }
        }

        if (!request.getMethod().equals("HEAD") && context.hasEntity()) {
            context.writeTo(response.getOutputStream());
        }
    } else {
        error("Internal Server Error", null, response);
    }
}

From source file:it.scoppelletti.programmerpower.web.resources.EmbeddedResourceFilter.java

/**
 * Invio di una risorsa su una risposta.
 * /*from  w  ww .ja v  a 2  s .  co m*/
 * @param path Percorso.
 * @param in   Flusso di input.
 * @param req  Richiesta.
 * @param resp Risposta.
 */
private void filter(String path, InputStream in, HttpServletRequest req, HttpServletResponse resp)
        throws IOException {
    long expires, now;
    String contentType;
    Calendar cal;

    contentType = myMimetypeMap.getContentType(path);
    if (Strings.isNullOrEmpty(contentType)) {
        myLogger.warn("Content-type of {} is undefined.", path);
    } else {
        myLogger.debug("Content-type of {} is {}.", path, contentType);
        resp.setContentType(contentType);
    }

    if (myTimeout > 0) {
        cal = Calendar.getInstance();
        now = cal.getTimeInMillis();
        cal.add(Calendar.DAY_OF_MONTH, myTimeout);
        expires = cal.getTimeInMillis();

        resp.setDateHeader(EmbeddedResourceFilter.HEADER_DATE, now);
        resp.setDateHeader(EmbeddedResourceFilter.HEADER_EXPIRES, expires);
        resp.setDateHeader(EmbeddedResourceFilter.HEADER_RETRYAFTER, expires);
        resp.setHeader(EmbeddedResourceFilter.HEADER_CACHECONTROL, EmbeddedResourceFilter.CACHE_PUBLIC);
        resp.setDateHeader(EmbeddedResourceFilter.HEADER_LASTMODIFIED, myLastModified);
    } else {
        resp.setHeader(EmbeddedResourceFilter.HEADER_CACHECONTROL, EmbeddedResourceFilter.CACHE_NOCACHE);
        resp.setHeader(EmbeddedResourceFilter.HEADER_PRAGMA, EmbeddedResourceFilter.CACHE_NOCACHE);
        resp.setHeader(EmbeddedResourceFilter.HEADER_EXPIRES, EmbeddedResourceFilter.EXPIRES_NOCACHE);
    }

    IOUtils.copy(in, resp.getOutputStream());
}

From source file:org.apache.stratos.theme.mgt.ui.servlets.ThemeResourceServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {//from ww  w  .  j a  v  a  2s.  com
        ThemeMgtServiceClient client = new ThemeMgtServiceClient(servletConfig, request.getSession());
        String path = request.getParameter("path");
        String viewImage = request.getParameter("viewImage");
        if (path == null) {
            String msg = "Could not get the resource content. Path is not specified.";
            log.error(msg);
            response.setStatus(400);
            return;
        }

        ContentDownloadBean bean = client.getContentDownloadBean(path);

        InputStream contentStream = null;
        if (bean.getContent() != null) {
            contentStream = bean.getContent().getInputStream();
        } else {
            String msg = "The resource content was empty.";
            log.error(msg);
            response.setStatus(204);
            return;
        }

        response.setDateHeader("Last-Modified", bean.getLastUpdatedTime().getTime().getTime());
        String ext = "jpg";
        if (path.lastIndexOf(".") < path.length() - 1 && path.lastIndexOf(".") > 0) {
            ext = path.substring(path.lastIndexOf(".") + 1);
        }

        if (viewImage != null && viewImage.equals("1")) {
            response.setContentType("img/" + ext);
        } else {
            if (bean.getMediatype() != null && bean.getMediatype().length() > 0) {
                response.setContentType(bean.getMediatype());
            } else {
                response.setContentType("application/download");
            }

            if (bean.getResourceName() != null) {
                response.setHeader("Content-Disposition",
                        "attachment; filename=\"" + bean.getResourceName() + "\"");
            }
        }

        if (contentStream != null) {

            ServletOutputStream servletOutputStream = null;
            try {
                servletOutputStream = response.getOutputStream();

                byte[] contentChunk = new byte[1024];
                int byteCount;
                while ((byteCount = contentStream.read(contentChunk)) != -1) {
                    servletOutputStream.write(contentChunk, 0, byteCount);
                }

                response.flushBuffer();
                servletOutputStream.flush();

            } finally {
                contentStream.close();

                if (servletOutputStream != null) {
                    servletOutputStream.close();
                }
            }
        }
    } catch (Exception e) {

        String msg = "Failed to get resource content. " + e.getMessage();
        log.error(msg, e);
        response.setStatus(500);
    }
}

From source file:fi.aluesarjat.prototype.ContextAccessServlet.java

@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifModifiedSince >= LAST_MODIFIED) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;/*from  w  ww.  ja  v a2  s .  c o m*/
    }

    String context = request.getRequestURL().toString();
    RDFConnection connection = repository.openConnection();
    try {
        SPARQLQuery query = connection.createQuery(QueryLanguage.SPARQL,
                "CONSTRUCT { ?s ?p ?o } WHERE { GRAPH ?context { ?s ?p ?o } }");
        query.setBinding("context", new UID(context));

        String contentType = null;
        String format = request.getParameter("format");
        if ("turtle".equals(format)) {
            contentType = Format.TURTLE.getMimetype();
        } else if ("ntriples".equals(format)) {
            contentType = Format.NTRIPLES.getMimetype();
        } else {
            contentType = getAcceptedType(request, Format.RDFXML);
        }
        response.setDateHeader("Last-Modified", System.currentTimeMillis());
        response.setContentType(contentType);
        query.streamTriples(response.getWriter(), contentType);
    } finally {
        connection.close();
    }
}

From source file:freeciv.servlet.ProxyServlet.java

/**
 * Performs an HTTP POST request/*from w w w.j a v a2  s.co  m*/
 * @param httpServletRequest The {@link HttpServletRequest} object passed
 *                            in by the servlet engine representing the
 *                            client request to be proxied
 * @param httpServletResponse The {@link HttpServletResponse} object by which
 *                             we can send a proxied response to the client 
 */
public void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws IOException, ServletException {

    // Create a standard POST request
    PostMethod postMethodProxyRequest = new PostMethod(this.getProxyURL(httpServletRequest));
    // Forward the request headers
    setProxyRequestHeaders(httpServletRequest, postMethodProxyRequest);
    // don't change Content-type header from client.
    //postMethodProxyRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    postMethodProxyRequest.setRequestBody(httpServletRequest.getInputStream());

    this.executeProxyRequest(postMethodProxyRequest, httpServletRequest, httpServletResponse);
    httpServletResponse.setHeader("Cache-Control", "no-cache"); //HTTP 1.1
    httpServletResponse.setHeader("Pragma", "no-cache"); //HTTP 1.0
    httpServletResponse.setDateHeader("Expires", 0); //prevents caching at the proxy server
}

From source file:org.openiot.gsn.http.OutputStructureHandler.java

public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setStatus(HttpServletResponse.SC_OK);
    String vsName = request.getParameter("name");
    VSensorConfig sensorConfig = Mappings.getVSensorConfig(vsName);
    if (logger.isInfoEnabled())
        logger.info(new StringBuilder().append("Structure request for *").append(vsName).append("* received.")
                .toString());/*from w ww . j a  v a2 s  .  co m*/
    StringBuilder sb = new StringBuilder("<virtual-sensor name=\"").append(vsName).append("\">\n");
    for (DataField df : sensorConfig.getOutputStructure())
        sb.append("<field name=\"").append(df.getName()).append("\" ").append("type=\"").append(df.getType())
                .append("\" ").append("description=\"").append(StringEscapeUtils.escapeXml(df.getDescription()))
                .append("\" />\n");
    sb.append(
            "<field name=\"timed\" type=\"string\" description=\"The timestamp associated with the stream element\" />\n");
    sb.append("</virtual-sensor>");
    response.setHeader("Cache-Control", "no-store");
    response.setDateHeader("Expires", 0);
    response.setHeader("Pragma", "no-cache");
    response.getWriter().write(sb.toString());
}

From source file:biz.webgate.dominoext.poi.component.kernel.simpleviewexport.CSVExportProcessor.java

public void process2HTTP(ExportModel expModel, UISimpleViewExport uis, HttpServletResponse hsr,
        DateTimeHelper dth) {/*from w  ww . j  a  v a 2  s  .c  o m*/
    try {
        ByteArrayOutputStream csvBAOS = new ByteArrayOutputStream();
        OutputStreamWriter csvWriter = new OutputStreamWriter(csvBAOS);
        CSVPrinter csvPrinter = new CSVPrinter(csvWriter, CSVFormat.DEFAULT);

        // BUILDING HEADER
        if (uis.isIncludeHeader()) {
            for (ExportColumn expColumn : expModel.getColumns()) {
                csvPrinter.print(expColumn.getColumnName());
            }
            csvPrinter.println();
        }
        // Processing Values
        for (ExportDataRow expRow : expModel.getRows()) {
            for (ExportColumn expColumn : expModel.getColumns()) {
                csvPrinter.print(convertValue(expRow.getValue(expColumn.getPosition()), expColumn, dth));
            }
            csvPrinter.println();
        }
        csvPrinter.flush();

        hsr.setContentType("text/csv");
        hsr.setHeader("Cache-Control", "no-cache");
        hsr.setDateHeader("Expires", -1);
        hsr.setContentLength(csvBAOS.size());
        hsr.addHeader("Content-disposition", "inline; filename=\"" + uis.getDownloadFileName() + "\"");
        OutputStream os = hsr.getOutputStream();
        csvBAOS.writeTo(os);
        os.close();
    } catch (Exception e) {
        ErrorPageBuilder.getInstance().processError(hsr, "Error during SVE-Generation (CSV Export)", e);
    }
}

From source file:com.googlecode.jtiger.modules.ecside.filter.ECSideFilter.java

public void setResponseHeaders(HttpServletRequest request, HttpServletResponse response,
        String exportFileName) {//from www .j a v a 2 s  .  c  om
    String mimeType = MimeUtils.getFileMimeType(exportFileName);
    // response.reset();
    if (StringUtils.isNotBlank(mimeType)) {
        response.setContentType(mimeType);
    }
    // response.setHeader("Content-Type",mimeType);
    try {
        exportFileName = RequestUtils.encodeFileName(request, exportFileName);

    } catch (UnsupportedEncodingException e) {
        String errorMessage = "Unsupported response.getCharacterEncoding() [" + "UTF-8" + "].";
        logger.error(errorMessage);
        e.printStackTrace();
    }
    // ec:
    response.setHeader("Content-Disposition", "attachment;filename=\"" + exportFileName + "\"");
    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "public");
    response.setDateHeader("Expires", (System.currentTimeMillis() + 1000));

}

From source file:org.fao.unredd.portal.ApplicationController.java

@RequestMapping("/static/**")
public void getCustomStaticFile(HttpServletRequest request, HttpServletResponse response) throws IOException {

    // Get path to file
    String fileName = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);

    // Verify file exists
    File file = new File(config.getDir() + "/static/" + fileName);
    if (!file.isFile()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;//from   ww w .ja  v a 2  s.  c om
    }

    // Manage cache headers: Last-Modified and If-Modified-Since
    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    long lastModified = file.lastModified();
    if (ifModifiedSince >= (lastModified / 1000 * 1000)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }
    response.setDateHeader("Last-Modified", lastModified);

    // Set content type
    FileNameMap fileNameMap = URLConnection.getFileNameMap();
    String type = fileNameMap.getContentTypeFor(fileName);
    response.setContentType(type);

    // Send contents
    try {
        InputStream is = new FileInputStream(file);
        IOUtils.copy(is, response.getOutputStream());
        response.flushBuffer();
    } catch (IOException e) {
        logger.error("Error reading file", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}