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:de.blizzy.documentr.web.page.PageController.java

@RequestMapping(value = "/{projectName:" + DocumentrConstants.PROJECT_NAME_PATTERN + "}/" + "{branchName:"
        + DocumentrConstants.BRANCH_NAME_PATTERN + "}/" + "{path:" + DocumentrConstants.PAGE_PATH_URL_PATTERN
        + "}", method = { RequestMethod.GET, RequestMethod.HEAD })
@PreAuthorize("hasPagePermission(#projectName, #branchName, #path, VIEW)")
public String getPage(@PathVariable String projectName, @PathVariable String branchName,
        @PathVariable String path, Model model, HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    try {/*w  w w.ja v  a 2s.c o m*/
        path = Util.toRealPagePath(path);
        PageMetadata metadata = pageStore.getPageMetadata(projectName, branchName, path);

        long lastEdited = metadata.getLastEdited().getTime();
        long authenticationCreated = AuthenticationUtil.getAuthenticationCreationTime(request.getSession());
        long projectEditTime = PageUtil.getProjectEditTime(projectName);
        long lastModified = Math.max(lastEdited, authenticationCreated);
        if (projectEditTime >= 0) {
            lastModified = Math.max(lastModified, projectEditTime);
        }

        long modifiedSince = request.getDateHeader("If-Modified-Since"); //$NON-NLS-1$
        if ((modifiedSince >= 0) && (lastModified <= modifiedSince)) {
            return ErrorController.notModified();
        }

        response.setDateHeader("Last-Modified", lastModified); //$NON-NLS-1$
        response.setDateHeader("Expires", 0); //$NON-NLS-1$
        response.setHeader("Cache-Control", "must-revalidate, private"); //$NON-NLS-1$ //$NON-NLS-2$

        Page page = pageStore.getPage(projectName, branchName, path, false);
        model.addAttribute("path", path); //$NON-NLS-1$
        model.addAttribute("pageName", //$NON-NLS-1$
                path.contains("/") ? StringUtils.substringAfterLast(path, "/") : path); //$NON-NLS-1$ //$NON-NLS-2$
        model.addAttribute("parentPagePath", page.getParentPagePath()); //$NON-NLS-1$
        model.addAttribute("title", page.getTitle()); //$NON-NLS-1$
        String viewRestrictionRole = page.getViewRestrictionRole();
        model.addAttribute("viewRestrictionRole", //$NON-NLS-1$
                (viewRestrictionRole != null) ? viewRestrictionRole : StringUtils.EMPTY);
        model.addAttribute("commit", metadata.getCommit()); //$NON-NLS-1$
        return "/project/branch/page/view"; //$NON-NLS-1$
    } catch (PageNotFoundException e) {
        return ErrorController.notFound("page.notFound"); //$NON-NLS-1$
    }
}

From source file:com.taobao.diamond.server.controller.ConfigController.java

public String getConfig(HttpServletRequest request, HttpServletResponse response, String dataId, String group) {
    response.setHeader("Content-Type", "text/html;charset=GBK");
    final String address = getRemortIP(request);
    if (address == null) {
        // 400/*from   ww  w  .j a v a  2 s  .c o m*/
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return "400";
    }

    if (GlobalCounter.getCounter().decrementAndGet() >= 0) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return "503";
    }

    String md5 = this.configService.getContentMD5(dataId, group);
    if (md5 == null) {
        return "404";
    }

    response.setHeader(Constants.CONTENT_MD5, md5);

    // 304double-check
    if (diskService.isModified(dataId, group)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return "304";
    }
    String path = configService.getConfigInfoPath(dataId, group);
    // 
    if (diskService.isModified(dataId, group)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return "304";
    }
    // 
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setHeader("Cache-Control", "no-cache,no-store");
    return "forward:" + path;
}

From source file:org.ms123.common.docbook.BaseDocbookServiceImpl.java

protected void _getAsset(String namespace, String name, String type, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    if (!m_assetList.contains(type)) {
        response.setStatus(403);/*from w  w  w.j  av  a2s .com*/
        return;
    }
    File asset = null;
    String contentType = type;
    try {
        if ("image/svg".equals(type)) {
            type = "image/svg+xml";
            contentType = "image/svg+xml";
        }
        if ("image/swf".equals(type)) {
            contentType = "application/x-shockwave-flash";
        }
        if ("image/pdf".equals(type)) {
            contentType = "application/pdf";
        }
        asset = m_gitService.searchFile(namespace, name, type);
    } catch (Exception e) {
        e.printStackTrace();
        response.setStatus(404);
        return;
    }
    Date sinceDate = new Date(request.getDateHeader("If-Modified-Since") + 1000);
    long modTime = asset.lastModified();
    if (modTime < sinceDate.getTime()) {
        response.setStatus(304);
        return;
    } else {
        response.setContentType(contentType);
        response.setContentLength((int) asset.length());
        response.setDateHeader("Last-Modified", modTime + 10000);
        response.setStatus(HttpServletResponse.SC_OK);
        OutputStream os = response.getOutputStream();
        IOUtils.copy(new FileInputStream(asset), os);
        os.close();
    }
}

From source file:org.clothocad.phagebook.controllers.PersonController.java

protected void processPostRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, Exception {
    // Disable the cache once and for all
    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
    response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
    response.setDateHeader("Expires", 0);
    System.out.println("Reached the Do post part.. Wohhoo");
    String filename = getValue(request.getPart("profilePictureName"));
    File profilePic = partConverter(request.getPart("profilePicture"), filename);

    String clothoId = getValue(request.getPart("clothoId"));
    S3Adapter.uploadProfilePicture(clothoId, profilePic);

    System.out.println(filename);

}

From source file:com.ultrapower.eoms.common.plugin.ecside.filter.ECSideFilter.java

    public void setResponseHeaders(HttpServletRequest request,HttpServletResponse response, String exportFileName) {
        String mimeType = MimeUtils.getFileMimeType(exportFileName);
//        response.reset(); 
        if (StringUtils.isNotBlank(mimeType)) {
            response.setContentType(mimeType);
        }//from  w  ww. ja  va 2  s  . co m
//        response.setHeader("Content-Type",mimeType);
        try {
            exportFileName= RequestUtils.encodeFileName(request,exportFileName);

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

    }

From source file:org.sakaiproject.sdata.tool.JCRHandler.java

/**
 * Set the cache control headers suitable for all HTTP protocol versions
 *
 * @param response//from   w  ww.j  av a 2  s  .c om
 */
private void setGetCacheControl(HttpServletResponse response, boolean isprivate) {
    if (isprivate) {
        response.addHeader("Cache-Control", "must-revalidate");
        response.addHeader("Cache-Control", "private");
        response.addHeader("Cache-Control", "no-store");
    } else {
        // response.addHeader("Cache-Control", "must-revalidate");
        response.addHeader("Cache-Control", "public");
    }
    response.addHeader("Cache-Control", "max-age=600");
    response.addHeader("Cache-Control", "s-maxage=600");
    response.setDateHeader("Date", System.currentTimeMillis());
    response.setDateHeader("Expires", System.currentTimeMillis() + 600000);

}

From source file:com.github.thorqin.webapi.FileManager.java

/**
 * Download file by specified file id//from   w  w w . j av a  2  s .co m
 *
 * @param response Servlet response
 * @param request Pass request parameter to provide user agent information
 * to properly process utf-8 filename
 * @param fileId File ID which generated by uploaded or manually created
 * file
 * @throws ServletException
 * @throws IOException
 */
public void downloadFile(String fileId, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setCharacterEncoding("utf-8");

    File dataFile = new File(uploadDir + "/" + fileId + ".data");
    if (!dataFile.exists()) {
        Dispatcher.send(response, HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    FileInfo info;
    try {
        String jsonFile = uploadDir + "/" + fileId + ".json";
        info = Serializer.loadJsonFile(jsonFile, FileInfo.class);
    } catch (Exception ex) {
        Dispatcher.send(response, HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    String filename;
    try {
        if (info.fileName != null) {
            filename = URLEncoder.encode(info.fileName, "utf-8").replace("+", "%20");
        } else {
            filename = "download.dat";
        }
    } catch (UnsupportedEncodingException e1) {
        filename = "download.dat";
        e1.printStackTrace();
    }
    response.setHeader("Cache-Control", "no-store");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setContentType(info.mimeType == null ? unknowMimeType : info.mimeType);

    UserAgentInfo uaInfo = UserAgentUtil.parse(request);
    if (uaInfo.browser == BrowserType.FIREFOX) {
        response.addHeader("Content-Disposition", "attachment; filename*=\"utf-8''" + filename + "\"");
    } else {
        response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
    }
    try (OutputStream os = response.getOutputStream()) {
        try (InputStream is = new FileInputStream(dataFile)) {
            int length;
            byte[] buffer = new byte[4096];
            while ((length = is.read(buffer)) != -1) {
                os.write(buffer, 0, length);
            }
        }
    }
}

From source file:cn.leancloud.diamond.server.controller.ConfigController.java

public String getConfig(HttpServletRequest request, HttpServletResponse response, String dataId, String group) {
    response.setHeader("Content-Type", "text/html;charset=UTF-8");
    final String address = getRemortIP(request);
    if (address == null) {
        // ?400//from   w ww  .ja v a2 s  .c  om
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return "400";
    }

    if (GlobalCounter.getCounter().decrementAndGet() >= 0) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return "503";
    }

    String md5 = this.configService.getContentMD5(dataId, group);
    if (md5 == null) {
        return "404";
    }

    response.setHeader(Constants.CONTENT_MD5, md5);

    // 304???double-check??
    if (diskService.isModified(dataId, group)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return "304";
    }
    String path = configService.getConfigInfoPath(dataId, group);
    // ?
    if (diskService.isModified(dataId, group)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return "304";
    }
    // ?
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setHeader("Cache-Control", "no-cache,no-store");
    return "forward:" + path;
}

From source file:com.mengka.diamond.server.controller.ConfigController.java

/**
 * ???//  w w w . j  a  v a 2 s  .c om
 * 
 * @param request
 * @param dataId
 * @param group
 *            ?
 * @return
 */
@RequestMapping(method = RequestMethod.GET)
public String getConfig(HttpServletRequest request, HttpServletResponse response, String dataId, String group) {
    response.setHeader("Content-Type", "text/html;charset=utf-8");
    final String address = getRemortIP(request);
    if (address == null) {
        // ?400
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return "400";
    }

    if (GlobalCounter.getCounter().decrementAndGet() >= 0) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return "503";
    }

    String md5 = this.configService.getContentMD5(dataId, group);
    if (md5 == null) {
        return "404";
    }

    response.setHeader(Constants.CONTENT_MD5, md5);

    // 304???double-check??
    if (diskService.isModified(dataId, group)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return "304";
    }
    String path = configService.getConfigInfoPath(dataId, group);
    // ?
    if (diskService.isModified(dataId, group)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return "304";
    }
    // ?
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setHeader("Cache-Control", "no-cache,no-store");
    return "forward:" + path;
}

From source file:com.nabla.dc.server.ImageService.java

private boolean exportImage(final String imageId, final HttpServletResponse response)
        throws IOException, SQLException, InternalErrorException {
    final Connection conn = db.getConnection();
    try {/*from  w  w w.  j  a  v  a  2  s .co  m*/
        final PreparedStatement stmt = StatementFormat.prepare(conn, "SELECT * FROM image WHERE id=?;",
                imageId);
        try {
            final ResultSet rs = stmt.executeQuery();
            try {
                if (!rs.next()) {
                    if (log.isDebugEnabled())
                        log.debug("failed to find report ID= " + imageId);
                    return false;
                }
                if (log.isTraceEnabled())
                    log.trace("exporting image " + imageId);
                response.reset();
                response.setBufferSize(DEFAULT_BUFFER_SIZE);
                response.setContentType(rs.getString("content_type"));
                response.setHeader("Content-Length", String.valueOf(rs.getInt("length")));
                response.setHeader("Content-Disposition",
                        MessageFormat.format("inline; filename=\"{0}\"", rs.getString("name")));
                // to prevent images to be downloaded every time user hovers one image
                final Calendar cal = Calendar.getInstance();
                cal.setTime(new Date());
                cal.add(Calendar.MONTH, 2);
                response.setDateHeader("Expires", cal.getTime().getTime());
                final BufferedInputStream input = new BufferedInputStream(rs.getBinaryStream("content"),
                        DEFAULT_BUFFER_SIZE);
                try {
                    final BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream(),
                            DEFAULT_BUFFER_SIZE);
                    try {
                        final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
                        int length;
                        while ((length = input.read(buffer)) > 0)
                            output.write(buffer, 0, length);
                    } finally {
                        output.close();
                    }
                } finally {
                    input.close();
                }
            } finally {
                rs.close();
            }
        } finally {
            stmt.close();
        }
    } finally {
        conn.close();
    }
    return true;
}