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:$.ResourceServlet.java

private void prepareResponse(HttpServletResponse response, URL resource, long lastModified, int contentLength)
            throws IOException {
        String resourcePath = resource.getPath();
        String mimeType = null;/*  w w w .java2 s .co m*/

        int offset = resourcePath.lastIndexOf('.');
        if (-1 != offset) {
            String extension = resource.getPath().substring(offset);
            mimeType = mimeTypes.get(extension);
        }

        if (mimeType == null) {
            mimeType = getServletContext().getMimeType(resourcePath);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Fallback to the mimeType '{}' from servlet context for {}.", mimeType, resourcePath);
            }
        }

        if (mimeType == null) {
            if (LOG.isWarnEnabled()) {
                LOG.warn("No mime-type mapping for resource path: {}. Fallback to 'application/octet-stream'.",
                        resourcePath);
            }
            mimeType = "application/octet-stream";
        }

        response.setDateHeader(HTTP_LAST_MODIFIED_HEADER, lastModified);
        response.setContentLength(contentLength);
        response.setContentType(mimeType);

        if (cacheTimeout > 0) {
            // Http 1.0 header
            response.setDateHeader(HTTP_EXPIRES_HEADER, System.currentTimeMillis() + cacheTimeout * 1000L);
            // Http 1.1 header
            response.setHeader(HTTP_CACHE_CONTROL_HEADER, "max-age=" + cacheTimeout);
        } else {
            // Http 1.0 header
            response.setDateHeader(HTTP_EXPIRES_HEADER, -1);
            // Http 1.1 header
            response.setHeader(HTTP_CACHE_CONTROL_HEADER, "no-cache");
        }
    }

From source file:com.cemso.action.DeviceAction.java

@JSON(serialize = false)
public String getDevice() {
    try {/*ww w  .j a  va 2 s .  com*/
        if (log.isDebugEnabled()) {
            log.debug("start to get device list...");
        }
        ActionContext context = ActionContext.getContext();
        HttpServletResponse response = (HttpServletResponse) context.get(ServletActionContext.HTTP_RESPONSE);

        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        deviceList = deviceService.getDevices();

        if (log.isDebugEnabled()) {
            log.debug("get device list successfully");
        }
        return "devicelist";
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error(e.getMessage());
        }
        e.printStackTrace();
        return ERROR;
    }
}

From source file:com.skilrock.lms.web.scratchService.inventoryMgmt.common.BODispatchGameAction.java

/**
 * This method is called when the Add Book button is pressed
 * //from  w ww. j a va  2 s.  co  m
 * @return String
 */
public String addBook() {

    System.out.println("---------I am in ADD Book--------------");

    // reInitialize();

    HttpServletResponse response = getResponse();
    response.setHeader("Pragma", "no-cache"); // HTTP 1.0
    response.setHeader("Cache-Control", "no-cache"); // HTTP 1.1
    response.setDateHeader("Expires", 0); // prevents caching at the proxy
    // server
    response.setHeader("Cache-Control", "private"); // HTTP 1.1
    response.setHeader("Cache-Control", "no-store"); // HTTP 1.1
    response.setHeader("Cache-Control", "max-stale=0"); // HTTP 1.1

    // System.out.println("add bookkkkkkkkkkkkk::" +
    // request.getParameter("hidBookNbr"));

    // System.out.println("add bookkkkkkkkkkkkk::" + getHidBookNbr());

    HttpSession session = getRequest().getSession();
    List<BookBean> bookList = (List<BookBean>) session.getAttribute("BOOK_LIST");
    List<PackBean> packList = (List<PackBean>) session.getAttribute("PACK_LIST");

    BookBean bookBean = null;
    if (bookList != null) {

        copyBookValues(bookList);
        bookBean = new BookBean();
        bookBean.setValid(true);
        bookList.add(bookBean);
        setBookList(bookList);
    }

    /*
     * try { PrintWriter out = getResponse().getWriter(); out.write("This is
     * Aman Chawla"); } catch (IOException e) { // TODO Auto-generated catch
     * block e.printStackTrace(); }
     */

    return SUCCESS;

}

From source file:io.fabric8.maven.proxy.impl.MavenProxyServletSupportTest.java

private void testDownload(Handler serverHandler) throws Exception {
    final String old = System.getProperty("karaf.data");
    System.setProperty("karaf.data", new File("target").getCanonicalPath());
    FileUtils.deleteDirectory(new File("target/tmp"));

    Server server = new Server(0);
    server.setHandler(serverHandler);/*from w w  w  . j a v a  2  s.co m*/
    server.start();

    try {
        int localPort = server.getConnectors()[0].getLocalPort();
        List<String> remoteRepos = Arrays.asList("http://relevant.not/maven2@id=central");
        RuntimeProperties props = new MockRuntimeProperties();
        // TODO: local repo should point to target/tmp
        MavenResolver resolver = createResolver("target/tmp", remoteRepos, "http", "localhost", localPort,
                "fuse", "fuse", null);
        MavenDownloadProxyServlet servlet = new MavenDownloadProxyServlet(resolver, props, projectDeployer, 5);

        AsyncContext context = EasyMock.createMock(AsyncContext.class);

        HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
        EasyMock.expect(request.getPathInfo())
                .andReturn("org.apache.camel/camel-core/2.13.0/camel-core-2.13.0-sources.jar");
        EasyMock.expect(request.startAsync()).andReturn(context);
        context.setTimeout(EasyMock.anyInt());
        EasyMock.expectLastCall();

        HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        EasyMock.expect(response.getOutputStream()).andReturn(new ServletOutputStream() {
            @Override
            public void write(int b) throws IOException {
                baos.write(b);
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                baos.write(b, off, len);
            }
        }).anyTimes();
        response.setStatus(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentLength(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentType((String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();
        response.setDateHeader((String) EasyMock.anyObject(), EasyMock.anyLong());
        EasyMock.expectLastCall().anyTimes();
        response.setHeader((String) EasyMock.anyObject(), (String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();

        final CountDownLatch latch = new CountDownLatch(1);
        context.complete();
        EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
            @Override
            public Object answer() throws Throwable {
                latch.countDown();
                return null;
            }
        });

        EasyMock.makeThreadSafe(context, true);
        EasyMock.replay(request, response, context);

        servlet.start();
        servlet.doGet(request, response);

        latch.await();

        Assert.assertArrayEquals(new byte[] { 0x42 }, baos.toByteArray());

        EasyMock.verify(request, response, context);
    } finally {
        server.stop();
        if (old != null) {
            System.setProperty("karaf.data", old);
        }
    }
}

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

/**
 * /*from   www .  j  a  v  a2 s  . c  o m*/
 * ?dataIdgroupId
 * @param request
 * @param response
 * @param probeModify
 * @return
 */
@RequestMapping(method = RequestMethod.POST)
public String getProbeModifyResult(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(Constants.PROBE_MODIFY_REQUEST) String probeModify) {
    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";
    }

    final List<ConfigKey> configKeyList = getConfigKeyList(probeModify);

    StringBuilder resultBuilder = new StringBuilder();
    for (ConfigKey key : configKeyList) {
        String md5 = this.configService.getContentMD5(key.getDataId(), key.getGroup());
        if (!StringUtils.equals(md5, key.getMd5())) {
            resultBuilder.append(key.getDataId()).append(Constants.WORD_SEPARATOR).append(key.getGroup())
                    .append(Constants.LINE_SEPARATOR);
        }
    }

    String returnHeader = resultBuilder.toString();
    try {
        returnHeader = URLEncoder.encode(resultBuilder.toString(), "UTF-8");
    } catch (Exception e) {
        // ignore
    }

    request.setAttribute("content", returnHeader);
    // ?
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setHeader("Cache-Control", "no-cache,no-store");
    return "200";
}

From source file:org.springframework.js.resource.ResourceServlet.java

private void prepareResponse(HttpServletResponse response, URL[] resources, String rawResourcePath)
        throws IOException {
    long lastModified = -1;
    int contentLength = 0;
    String mimeType = null;//  w w w.  j  ava  2  s  . co  m
    for (URL resource : resources) {
        URLConnection resourceConn = resource.openConnection();
        if (resourceConn.getLastModified() > lastModified) {
            lastModified = resourceConn.getLastModified();
        }

        String currentMimeType = getServletContext().getMimeType(resource.getPath());
        if (currentMimeType == null) {
            String extension = resource.getPath().substring(resource.getPath().lastIndexOf('.'));
            currentMimeType = defaultMimeTypes.get(extension);
        }
        if (mimeType == null) {
            mimeType = currentMimeType;
        } else if (!mimeType.equals(currentMimeType)) {
            throw new MalformedURLException("Combined resource path: " + rawResourcePath
                    + " is invalid. All resources in a combined resource path must be of the same mime type.");
        }
        contentLength += resourceConn.getContentLength();
    }

    response.setContentType(mimeType);
    response.setHeader(HTTP_CONTENT_LENGTH_HEADER, Long.toString(contentLength));
    response.setDateHeader(HTTP_LAST_MODIFIED_HEADER, lastModified);
    if (cacheTimeout > 0) {
        configureCaching(response, cacheTimeout);
    }
}

From source file:org.shept.services.jcaptcha.ImageCaptchaServlet.java

@SuppressWarnings("unchecked")
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {
    BufferedImage challenge = null;
    try {//from   ww w  .j  a  v a2  s .  c om
        // get the session id that will identify the generated captcha.
        // the same id must be used to validate the response, the session id
        // is a good candidate!
        String captchaId = httpServletRequest.getSession().getId();

        // If we have an explicit configuration for an ImageService we use this
        // else we use the predefined default
        ImageCaptchaService captchaService = CaptchaServiceSingleton.getInstance();
        Map services = ctx.getBeansOfType(ImageCaptchaService.class);
        // there must be exactly on service configured
        if (services.size() == 1) {
            for (Iterator iterator = services.values().iterator(); iterator.hasNext();) {
                captchaService = (ImageCaptchaService) iterator.next();
            }
        }

        // call the ImageCaptchaService getChallenge method
        challenge = captchaService.getImageChallengeForID(captchaId, httpServletRequest.getLocale());

    } catch (IllegalArgumentException e) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    } catch (CaptchaServiceException e) {
        httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    // flush it in the response
    httpServletResponse.setHeader("Cache-Control", "no-store");
    httpServletResponse.setHeader("Pragma", "no-cache");
    httpServletResponse.setDateHeader("Expires", 0);
    httpServletResponse.setContentType("image/jpeg");
    ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
    ImageIO.write(challenge, "jpeg", responseOutputStream);
    responseOutputStream.flush();
    responseOutputStream.close();
}

From source file:org.openbravo.erpCommon.utility.ImageUtils.java

/**
 * Outputs the image/content to the response
 *//*from  www. ja  v  a  2 s . c  o  m*/
public static void outputImageResource(final HttpServletRequest req, final HttpServletResponse resp,
        final String imageType) throws IOException, ServletException {
    try {
        OBContext.setAdminMode(true);

        // enforce cache validation/checks every time
        resp.addHeader(RESPONSE_HEADER_CACHE_CONTROL, RESPONSE_NO_CACHE);
        VariablesSecureApp vars = new VariablesSecureApp(req);

        Image img = null;
        if (imageType == "logo") {
            String logo = vars.getStringParameter("logo");
            String org = vars.getStringParameter("orgId");
            img = Utility.getImageLogoObject(logo, org);
            if (img == null) {
                byte[] imageFileContent = Utility.getImageLogo(logo, org);
                String mimeType = MimeTypeUtil.getInstance().getMimeTypeName(imageFileContent);
                resp.setContentType(mimeType);
                OutputStream out = resp.getOutputStream();
                resp.setContentLength(imageFileContent.length);
                out.write(imageFileContent);
                out.close();
                return;
            }
        } else {
            img = Utility.getImageObject(vars.getStringParameter("id"));
        }

        if (img != null) {
            String imageID = "IMGTAG" + img.getUpdated().toString();

            if (ImageUtils.isImageResponseRequired(req, resp, imageID)) {

                // read the image data
                byte[] imgByte = img.getBindaryData();

                // write the mimetype
                String mimeType = img.getMimetype();// write the mimetype
                if (mimeType == null) {
                    mimeType = MimeTypeUtil.getInstance().getMimeTypeName(img.getBindaryData());
                    if (img != null) {
                        // If there is an OBContext, we attempt to save the MIME type of the image
                        updateMimeType(img.getId(), mimeType);
                    }
                }

                if (!mimeType.equals("")) {
                    resp.setContentType(mimeType);
                }

                // write the image
                OutputStream out = resp.getOutputStream();
                resp.setContentLength(imgByte.length);
                out.write(imgByte);
                out.close();

            } else {
                resp.sendError(HttpServletResponse.SC_NOT_MODIFIED);
                resp.setDateHeader(RESPONSE_HEADER_LASTMODIFIED,
                        req.getDateHeader(REQUEST_HEADER_IFMODIFIEDSINCE));

            }

        }
    } finally {
        OBContext.restorePreviousMode();
    }

}

From source file:org.komodo.web.backend.server.servlets.DataVirtDownloadServlet.java

protected void doDownloadJar(HttpServletResponse httpResponse) throws Exception {
    FileInputStream fileInputStream = null;

    // Access the teiid jdbc jar in the jboss directory structure
    String homeDir = System.getProperty("jboss.home.dir");

    try {/*from   ww  w. jav  a2  s.  c om*/
        String jdbcJarName = DV600_JDBC_JAR;
        String jarDir = null;
        if (isOpenShift()) {
            jarDir = homeDir + "/versions/6.1.0/standalone/configuration/";
        } else {
            jarDir = homeDir + "/dataVirtualization/jdbc/";
        }
        String jdbcJarFileName = jarDir + DV600_JDBC_JAR;
        // Assume DV600 jarFile name.  If it doesnt exist, then go with DV610
        File jarFile = new File(jdbcJarFileName);
        if (!jarFile.exists()) {
            jdbcJarName = DV610_JDBC_JAR;
            jdbcJarFileName = jarDir + DV610_JDBC_JAR;
            jarFile = new File(jdbcJarFileName);
        }

        try {
            fileInputStream = new FileInputStream(jarFile);
        } catch (Exception e) {
            throw new KomodoUiException(e.getMessage());
        }

        // Set the content-disposition
        String disposition = String.format("attachment; filename=\"%1$s\"", jdbcJarName); //$NON-NLS-1$
        httpResponse.setHeader("Content-Disposition", disposition); //$NON-NLS-1$

        // Set the content-type
        httpResponse.setHeader("Content-Type", "application/java-archive"); //$NON-NLS-1$

        // Make sure the browser doesn't cache it
        Date now = new Date();
        httpResponse.setDateHeader("Date", now.getTime()); //$NON-NLS-1$
        httpResponse.setDateHeader("Expires", now.getTime() - 86400000L); //$NON-NLS-1$
        httpResponse.setHeader("Pragma", "no-cache"); //$NON-NLS-1$ //$NON-NLS-2$
        httpResponse.setHeader("Cache-control", "no-cache, no-store, must-revalidate"); //$NON-NLS-1$ //$NON-NLS-2$

        IOUtils.copy(fileInputStream, httpResponse.getOutputStream());
    } finally {
        IOUtils.closeQuietly(fileInputStream);
    }
}

From source file:com.skilrock.lms.web.scratchService.inventoryMgmt.common.BODispatchGameAction.java

/**
 * This method verifies the pack entered by the user
 * /*from  w  w w  . ja  v  a  2s.  c om*/
 * @return String
 * @throws Exception
 */
public String verifyPack() throws Exception {

    boolean isValid = false;
    int gameId = getGameId();
    boolean isBlank = false;
    boolean isDuplicate = false;

    HttpSession session = getRequest().getSession();
    List<PackBean> packList = (List<PackBean>) session.getAttribute("PACK_LIST");
    String packNbr = getPackNbrToVerify();

    try {
        if (packNbr != null && !packNbr.trim().equals("")) {

            if (packNbr.indexOf("-") == -1) {
                OrderedGameBean orderedGameBean = (OrderedGameBean) session.getAttribute("ORDERED_GAME");

                packNbr = packNbr.substring(0, orderedGameBean.getGameNbrDigits()) + "-"
                        + packNbr.substring(orderedGameBean.getGameNbrDigits());

                System.out.println("New pack nbr:::" + packNbr);

            }

            BODispatchGameHelper helper = new BODispatchGameHelper();
            isValid = helper.verifyPack(gameId, packNbr);
        } else {
            isValid = true;
        }

        // when the user changes the packNbr to blanks
        if (packNbr != null && packNbr.trim().equals("")) {
            System.out.println("--For Blank--------");
            isBlank = true;
            PackBean blankBean = packList.get(packCountId - 1);
            blankBean.setPackNumber("");
            blankBean.setValid(true);
            blankBean.setStatus(null);
        }

    } catch (Exception le) {
        le.printStackTrace();
    }

    /*
     * try { PrintWriter out = getResponse().getWriter(); if (isValid) {
     * out.write("valid"); } } catch (IOException e) { // TODO
     * Auto-generated catch block e.printStackTrace(); }
     */

    if (!isBlank) {

        System.out.println("--If Not Blank--------");
        if (packList != null) {
            copyPackValues(packList);

            // for duplicate check

            int dupCount = 0;

            int packCountId = getPackCountId();
            System.out.println("PackCountId:::::::::::" + packCountId);

            for (PackBean bean : packList) {
                if (packNbr.equals(bean.getPackNumber())) {
                    dupCount++;
                }

                if (dupCount > 1) {
                    isDuplicate = true;
                    PackBean dupBean = packList.get(packCountId - 1);
                    dupBean.setValid(false);
                    dupBean.setStatus("Duplicate Pack");
                    break;
                }
            }

            if (dupCount <= 1) {
                PackBean dupBean = packList.get(packCountId - 1);
                dupBean.setValid(true);
                dupBean.setStatus(null);
            }

            if (!isDuplicate) {
                for (PackBean bean : packList) {
                    if (packNbr.equals(bean.getPackNumber())) {
                        if (!isValid) {
                            bean.setValid(false);
                            bean.setStatus("Wrong Pack Number");
                            break;
                        } else {
                            bean.setValid(true);
                            bean.setStatus(null);
                            break;
                        }
                    }
                }
            }

        }
    }

    setPackList(packList);
    changeDispatchBooks();

    System.out.println("---------Trying to prevent caching------");
    HttpServletResponse response = getResponse();
    response.setHeader("Pragma", "no-cache"); // HTTP 1.0
    response.setHeader("Cache-Control", "no-cache"); // HTTP 1.1
    response.setDateHeader("Expires", 0); // prevents caching at the proxy
    // server
    response.setHeader("Cache-Control", "private"); // HTTP 1.1
    response.setHeader("Cache-Control", "no-store"); // HTTP 1.1
    response.setHeader("Cache-Control", "max-stale=0"); // HTTP 1.1

    return SUCCESS;
}