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.skilrock.lms.web.scratchService.inventoryMgmt.common.BODispatchGameAction.java

public String verifyBookSeries() throws LMSException {

    // global connection to be used everywhere
    Connection connection = null;

    connection = DBConnect.getConnection();

    boolean isValid = false;
    boolean isSeriesValid = true;
    int gameId = getGameId();
    HttpSession session = getRequest().getSession();
    int roleId = ((UserInfoBean) session.getAttribute("USER_INFO")).getRoleId();
    List<BookBean> bookList = new ArrayList();
    List<BookBean> bookSeriesList = new ArrayList();
    List bookSeriesAll = new ArrayList();
    session.setAttribute("BOOK_SERIES_ALL", bookSeriesAll);
    session.setAttribute("BOOK_LIST", bookList);
    session.setAttribute("BOOK_SERIES_LIST", bookSeriesList);
    StringTokenizer bookNbrFrmTok = new StringTokenizer(((String[]) bookNbrFromArr)[0], ",");
    StringTokenizer bookNbrToTok = new StringTokenizer(((String[]) bookNbrToArr)[0], ",");
    bookNbrFrmStr = new String[bookNbrFrmTok.countTokens()];
    bookNbrToStr = new String[bookNbrToTok.countTokens()];
    int frmTok = 0;
    while (bookNbrFrmTok.hasMoreTokens()) {
        bookNbrFrmStr[frmTok] = bookNbrFrmTok.nextToken();
        bookNbrToStr[frmTok] = bookNbrToTok.nextToken();
        frmTok = frmTok + 1;//from  w  w w.  j  av a2s .co  m
    }
    System.out.println("---Series length" + bookNbrFrmStr);

    if (bookNbrFrmStr != null) {
        for (int seriesNo = 0; seriesNo < bookNbrFrmStr.length; seriesNo++) {
            if (bookNbrFrmStr[seriesNo] != "") {

                String bookNbrFrom = bookNbrFrmStr[seriesNo];
                String bookNbrTo = bookNbrToStr[seriesNo];

                int bookNbrFrmInt = Integer.parseInt(bookNbrFrom.replaceAll("-", ""));
                int bookNbrToInt = Integer.parseInt(bookNbrTo.replaceAll("-", ""));
                int noOfbooks = bookNbrToInt - bookNbrFrmInt;
                BookSeriesBean bookSeBean = new BookSeriesBean();
                bookSeBean.setBookNbrFrom(bookNbrFrom);
                bookSeBean.setBookNbrTo(bookNbrTo);
                bookSeBean.setStatus("");
                bookSeBean.setValid(isValid);
                for (int i = 0; i < noOfbooks + 1; i++) {
                    String bookNbr = String.valueOf(bookNbrFrmInt);

                    if (bookNbr != null && !bookNbr.trim().equals("")) {
                        // add hyphens if necessary

                        System.out.println(":::::::::" + bookNbr.indexOf("-"));

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

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

                            System.out.println("New book nbr:::" + bookNbr);

                        }

                        System.out.println("---------------vvvvvvvvvvvvv----------" + bookNbr);
                        BODispatchGameHelper helper = new BODispatchGameHelper();
                        isValid = helper.verifyBook(gameId, bookNbr, connection, roleId);

                        if (isValid) {
                            BookBean bookBean = new BookBean();
                            bookBean.setValid(true);
                            bookBean.setBookNumber(bookNbr);
                            for (BookBean bean : bookSeriesList) {
                                if (bookNbr.equals(bean.getBookNumber())) {
                                    isSeriesValid = false;
                                    bookSeBean.setStatus("Series Contains Tickets of Another Series");
                                    break;// New series contains ticket of
                                    // old series
                                }
                            }
                            if (isSeriesValid) {
                                bookSeriesList.add(bookBean);
                            }

                        } else {
                            isSeriesValid = false;
                            bookSeBean.setStatus("Series Not Valid");
                            break;// Series not valid
                        }
                    }
                    System.out.println("inside for of verifyBookSeries");

                    bookNbrFrmInt++;

                }
                if (isSeriesValid) {
                    bookSeBean.setValid(true);
                    session.setAttribute("BOOK_SERIES_LIST", bookSeriesList);
                }
                bookSeriesAll.add(bookSeBean);
                session.setAttribute("BOOK_SERIES_ALL", bookSeriesAll);
                // changeDispatchBooks();
                System.out.println("@@@@@@@@@@@@@################$$$$$$$$$$$$$%%%%%%%%%%%%%%%%");
            }
        }
    }
    verifyIndividualBooks(bookList, connection, roleId);

    for (int i = 0; i < bookSeriesList.size(); i++) {
        for (int j = 0; j < bookList.size(); j++) {
            // System.out.println(bookSeriesList.size()+"-Gaura
            // Test--"+bookList.size());
            if (((BookBean) bookList.get(j)).getBookNumber()
                    .equals(((BookBean) bookSeriesList.get(i)).getBookNumber())) {
                BookBean bean = (BookBean) bookList.get(j);
                bean.setValid(false);
                bean.setStatus("Book Number already in Book Series");
            }
        }
    }
    setBookList(bookList);
    session.setAttribute("BOOK_LIST", bookList);
    changeDispatchBooks();
    System.out.println("---------Trying to prevent caching------" + bookList);
    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;

}

From source file:org.impalaframework.web.servlet.ResourceServlet.java

private void prepareResponse(HttpServletResponse response, URL[] resources, String rawResourcePath)
        throws IOException {
    long lastModified = -1;
    int contentLength = 0;
    String mimeType = null;/*from   ww w . jav a 2 s .co  m*/
    for (int i = 0; i < resources.length; i++) {
        URLConnection resourceConn = resources[i].openConnection();
        if (resourceConn.getLastModified() > lastModified) {
            lastModified = resourceConn.getLastModified();
        }

        String currentMimeType = getServletContext().getMimeType(resources[i].getPath());
        if (currentMimeType == null) {
            String extension = resources[i].getPath().substring(resources[i].getPath().lastIndexOf('.'));
            currentMimeType = (String) 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:com.sjc.cc.login.action.LoginAction.java

/**
 * //from w  w  w.  j a v a  2 s .  c o m
 * 
 * @return
 */
public String login() throws Exception {
    HttpServletResponse response = ServletActionContext.getResponse();
    HttpServletRequest request = ServletActionContext.getRequest();
    // 
    TccSkin tCcSkin = loginService.getSkindflt();
    if (null != tCcSkin) {
        String dirString = tCcSkin.getSkinDir();
        if (null == dirString || dirString.equals("")) {
            dirString = "";
        }
        request.getSession().setAttribute("changeskin", dirString);
    } else {
        request.getSession().setAttribute("changeskin", "");
    }
    TCcBasicCfg basicCfg = loginService.getBasicCfg();
    request.getSession().setAttribute("basicCfg", basicCfg);

    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires ", -1);
    if (null == loginUserInfo) {
        return "login";
    }

    // ladp?
    // Properties properties =
    // ResourceUtil.getInstance().getProperties("ldap_configinfos.properties");
    // String url = properties.getProperty("url");
    // String root = properties.getProperty("root");
    SessionUserAccessor.logoutSession(request.getSession());
    // if(LdapHelper.getCtx(loginUserInfo.getAccountNo(),
    // loginUserInfo.getAccountPassword(), root, url)){
    /**
     * ******************************************?*******************
     * ************
     */
    // TccEmployee tccEmployee =
    // loginService.getUserByAccountNo(loginUserInfo);
    // if(tccEmployee==null){
    // String accountNo = loginUserInfo.getAccountNo();
    // List<LdapUserBean> ldapUserBeans =
    // LdapHelper.getLdapUserInfos("uid="+accountNo);
    // if(ldapUserBeans!=null&&ldapUserBeans.size()>0){
    // TccEmployee newTccEmployee = new TccEmployee();
    // newTccEmployee.setAccountNo(ldapUserBeans.get(0).getUid());
    // newTccEmployee.setAccountPassword(loginUserInfo.getAccountPassword())
    // }
    // }
    /**
     * *********************************************************************
     * ***************
     */
    if (null == LoginUserInfoHolder.getInstance()
            || null == LoginUserInfoHolder.getInstance().getCurrentUser()) {

        /** ??password */
        // MD5 md5Password=new MD5(loginUserInfo.getAccountPassword());
        // String passWord = md5Password.compute();
        // loginUserInfo.setAccountPassword(passWord);

        if (StringUtils.isEmpty(loginUserInfo.getAccountNo())
                && StringUtils.isEmpty(loginUserInfo.getAccountPassword())) {
            request.setAttribute("errorMessage", "???");
            return "login";
        }

        if (StringUtils.isEmpty(loginUserInfo.getAccountNo())) {
            request.setAttribute("errorMessage", "??");
            return "login";
        }
        if (StringUtils.isEmpty(loginUserInfo.getAccountPassword())) {
            request.setAttribute("errorMessage", "?");
            return "login";
        }

        try {
            loginUserInfo.setLoginIP(request.getRemoteAddr());
            logger.debug("<<<<<<<<<<<<<<<<<<?IP?:" + loginUserInfo.getLoginIP());
            loginUserInfo = loginService.verifyUserPassword(loginUserInfo);
        } catch (Exception ex) {
            // logger.error("<<<<<<<<<<<LDAP?!", ex);
            if ("Pool not open".equals(ex.getMessage())) {
                if (LicenseValidator.getErrorType() == 1) {
                    request.setAttribute("errorMessage",
                            "?Licese???");
                } else {
                    request.setAttribute("errorMessage",
                            "Licese?????");
                }
            } else {
                if (StringUtil.isContainChinese(ex.getMessage())) {
                    request.setAttribute("errorMessage", ex.getMessage());
                } else {
                    request.setAttribute("errorMessage",
                            "?????? ");
                }
            }
            return "login";
        }
        sessionUserAccessor.setSessionUser(request.getSession(), loginUserInfo);
        setCloudUserIdCookie(loginUserInfo.getUserPartyId());
        loginUserInfo.setLoginTime(new Long(new Date().getTime()));
        // ?JS??
        List<?> jsFileList = dynamicJSService.getDynamicJSList(loginUserInfo);
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "[" + loginUserInfo.getAccountNo() + "]?JS" + jsFileList);
        }
        request.setAttribute("jsFileList", jsFileList);
        // }else{
        // loginUserInfo=LoginUserInfoHolder.getInstance().getCurrentUser();
        // }
        request.getSession().setAttribute("loginUserInfo", loginUserInfo);
        logService.saveOperLog("?", "" + loginUserInfo.getEmpName() + ""
                + BusinessEnvironment.OPER_RESULT_SUCCESS, loginUserInfo, 3);
        return "main";
    } else {
        logService.saveOperLog("?", "" + loginUserInfo.getEmpName() + ""
                + BusinessEnvironment.OPER_RESULT_SUCCESS, loginUserInfo, 3);
        return "login";
    }
}

From source file:axiom.servlet.AbstractServletClient.java

protected void writeResponse(HttpServletRequest req, HttpServletResponse res, RequestTrans axiomreq,
        ResponseTrans axiomres) throws IOException {
    if (axiomres.getForward() != null) {
        sendForward(res, req, axiomres);
        return;//from   ww w .  ja  v a  2s. c o m
    }

    if (axiomres.getETag() != null) {
        res.setHeader("ETag", axiomres.getETag());
    }

    if (axiomres.getRedirect() != null) {
        sendRedirect(req, res, axiomres.getRedirect());
    } else if (axiomres.getNotModified()) {
        res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
    } else {
        if (!axiomres.isCacheable() || !caching) {
            // Disable caching of response.
            // for HTTP 1.0
            res.setDateHeader("Expires", System.currentTimeMillis() - 10000);
            res.setHeader("Pragma", "no-cache");

            // for HTTP 1.1
            res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=0");
        }

        if (axiomres.getStatus() > 0) {
            res.setStatus(axiomres.getStatus());
        }

        // set last-modified header to now
        long modified = axiomres.getLastModified();
        if (modified > -1) {
            res.setDateHeader("Last-Modified", modified);
        }
        res.setDateHeader("Date", System.currentTimeMillis());

        res.setContentLength(axiomres.getContentLength());
        res.setContentType(axiomres.getContentType());

        if ("HEAD".equalsIgnoreCase(req.getMethod())) {
            return;
        }

        try {
            OutputStream out = res.getOutputStream();

            InputStream istream = axiomres.getInputStream();
            if (istream != null) {
                try {
                    byte[] buf = new byte[8192];
                    int len;
                    while ((len = istream.read(buf)) != -1) {
                        out.write(buf, 0, len);
                    }
                    out.flush();
                } finally {
                    axiomres.closeInputStream();
                }
            } else {
                out.write(axiomres.getContent());
                out.flush();
            }
        } catch (Exception io_e) {
            log("Exception in writeResponse: " + io_e);
        }
    }
}

From source file:helma.servlet.AbstractServletClient.java

protected void writeResponse(HttpServletRequest req, HttpServletResponse res, RequestTrans hopreq,
        ResponseTrans hopres) throws IOException {
    if (hopres.getForward() != null) {
        sendForward(res, req, hopres);/*  w w  w .j  a  va 2  s . co m*/
        return;
    }

    if (hopres.getETag() != null) {
        res.setHeader("ETag", hopres.getETag());
    }

    if (hopres.getRedirect() != null) {
        sendRedirect(req, res, hopres.getRedirect(), hopres.getStatus());
    } else if (hopres.getNotModified()) {
        res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
    } else {
        if (!hopres.isCacheable() || !caching) {
            // Disable caching of response.
            if (isOneDotOne(req.getProtocol())) {
                // for HTTP 1.1
                res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=0");
            } else {
                // for HTTP 1.0
                res.setDateHeader("Expires", System.currentTimeMillis() - 10000);
                res.setHeader("Pragma", "no-cache");
            }
        }

        if (hopres.getRealm() != null) {
            res.setHeader("WWW-Authenticate", "Basic realm=\"" + hopres.getRealm() + "\"");
        }

        if (hopres.getStatus() > 0) {
            res.setStatus(hopres.getStatus());
        }

        // set last-modified header to now
        long modified = hopres.getLastModified();
        if (modified > -1) {
            res.setDateHeader("Last-Modified", modified);
        }

        res.setContentLength(hopres.getContentLength());
        res.setContentType(hopres.getContentType());

        if (!"HEAD".equalsIgnoreCase(req.getMethod())) {
            byte[] content = hopres.getContent();
            if (content != null) {
                try {
                    OutputStream out = res.getOutputStream();
                    out.write(content);
                    out.flush();
                } catch (Exception iox) {
                    log("Exception in writeResponse: " + iox);
                }
            }
        }
    }
}

From source file:org.polymap.rap.openlayers.util.ProxyServlet.java

private void doProxy(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (getServletConfig().getInitParameter("host_list") == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "There is no Host-List for this Servlet");
        return;//ww  w  . j ava 2s .  c om

    }

    List<String> host_list = Arrays.asList(getServletConfig().getInitParameter("host_list").split(","));

    String url_param = null;
    url_param = request.getParameter("url");

    if (url_param == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "URL Parameter Missing");
        return;
    }

    try {
        URL url = new URL(url_param);

        /* Check if the host is in the list of allowed hosts */
        if (!host_list.contains(url.getHost())) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "URL Parameter Bad - the Host " + url.getHost() + " is not in my list of valid Hosts!");
            return;
        }

        URLConnection con = url.openConnection();

        if (con.getContentType() != null)
            response.setContentType(con.getContentType());
        else
            response.setContentType("text/xml");

        /* check if the client accepts gzip Encoding */
        boolean client_accepts_gzip = false; // be pessimistic

        if (request.getHeader("Accept-Encoding") != null) {
            List<String> encoding_list = Arrays.asList(request.getHeader("Accept-Encoding").split(","));
            client_accepts_gzip = (encoding_list.contains("gzip"));
        }
        response.setDateHeader("Date", System.currentTimeMillis());

        if (client_accepts_gzip) {
            response.setHeader("Content-Encoding", "gzip");
            ByteArrayOutputStream output_to_tmp = new ByteArrayOutputStream();
            IOUtils.copy(url.openStream(), output_to_tmp);

            OutputStream output_to_response = new GZIPOutputStream(response.getOutputStream());
            output_to_response.write(output_to_tmp.toByteArray());
            output_to_response.close();

        } else { // client will not accept gzip -> dont compress
            IOUtils.copy(url.openStream(), response.getOutputStream());
        }

    } catch (IOException e) {
        System.out.println("Err" + e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "Err:" + e);
    }

}

From source file:org.shredzone.cilla.view.FeedView.java

/**
 * Fetches the pages by query and returns a feed.
 *
 * @param filter//from   ww w.  j a  v a  2  s. co m
 *            {@link FilterModel} with the query parameters
 * @param context
 *            {@link ViewContext} with the view context
 * @param req
 *            the {@link HttpServletRequest}
 * @param resp
 *            the {@link HttpServletResponse}
 * @param selfUrl
 *            freshly generated link to this feed
 * @param feedId
 *            a unique id for this feed
 * @param type
 *            feed type, any type supported by ROME.
 */
@SuppressWarnings("unchecked")
private void fetchPages(FilterModel filter, ViewContext context, HttpServletRequest req,
        HttpServletResponse resp, String selfUrl, String feedId, String type)
        throws ViewException, CillaServiceException {
    Date lastModified = pageDao.fetchMinMaxModification()[1];

    if (isNotModifiedSince(req, lastModified)) {
        throw new ErrorResponseException(HttpServletResponse.SC_NOT_MODIFIED);
    }

    SearchResult result = searchService.search(filter);
    result.setPaginator(new PaginatorModel(maxEntries));

    String contentType = "application/xml";
    if (type.startsWith("atom_")) {
        contentType = "application/atom+xml";
    } else if (type.startsWith("rss_")) {
        contentType = "application/rss+xml";
    }

    String uriPrefix = context.getRequestServerUrl() + '/';

    SyndFeed feed = new SyndFeedImpl();
    feed.setFeedType(type);
    feed.setTitle(title);
    feed.setDescription(description);
    feed.setLink(linkService.linkTo().absolute().toString());
    feed.setUri(uriPrefix + feedId);
    feed.setPublishedDate(lastModified);

    SyndLink selfLink = new SyndLinkImpl();
    selfLink.setRel("self");
    selfLink.setType(contentType);
    selfLink.setHref(selfUrl);
    feed.getLinks().add(selfLink);
    feed.getEntries().addAll(result.getPages().stream().filter(page -> !page.isRestricted()) // do not show restricted pages
            .map(page -> createEntry(page, uriPrefix)).collect(Collectors.toList()));

    resp.setContentType(contentType);
    resp.setDateHeader("Last-Modified", lastModified.getTime());
    resp.setCharacterEncoding("utf-8");

    try {
        SyndFeedOutput output = new SyndFeedOutput();
        output.output(feed, resp.getWriter());
    } catch (FeedException | IOException ex) {
        throw new ViewException("Could not create feed", ex);
    }
}

From source file:com.smartgwt.extensions.fileuploader.server.TestServiceImpl.java

private void processFiles(HttpServletRequest request, HttpServletResponse response) {
    HashMap<String, String> args = new HashMap<String, String>();
    try {//  w ww  .  j a va  2  s. c  om
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);
        FileItemStream fileItem = null;
        // pick up parameters first and note actual FileItem
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            if (item.isFormField()) {
                args.put(name, Streams.asString(item.openStream()));
            } else {
                fileItem = item;
            }
        }
        if (fileItem != null) {
            args.put("contentType", fileItem.getContentType());
            args.put("fileName", FileUtils.filename(fileItem.getName()));
            System.out.println("uploading args " + args);
            String context = args.get("context");
            String model = args.get("model");
            String xq = args.get("xq");
            System.out.println(context + "," + model + "," + xq);
            File f = new File(args.get("fileName"));
            System.out.println(f.getAbsolutePath());
            /*
             * TODO: pboysen get the state, context and fileManager and store the
             * stream in fileName.  Parameters should be passed to locate state 
             * and conversion options.
             */
            response.setContentType("text/html");
            response.setHeader("Pragma", "No-cache");
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-cache");
            PrintWriter out = response.getWriter();
            out.println("<html>");
            out.println("<body>");
            out.println("<script>");
            out.println("top.uploadComplete('" + args.get("fileName") + "');");
            out.println("</script>");
            out.println("</body>");
            out.println("</html>");
            out.flush();
        } else {
            //TODO: add error code
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:com.asual.lesscss.ResourceServlet.java

public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException {

    try {/*from   ww  w  .j  a v  a2 s  . c o  m*/

        String pkg = request.getParameter("pack");
        String[] uri = (pkg != null) ? pkg.split(separator)
                : new String[] { request.getRequestURI().replaceAll("/+", "/") };
        String mimeType = getResourceMimeType(uri[0]);

        long lastModified = 0;
        byte[] content = new byte[0];

        for (String resource : uri) {
            resource = resource.replaceAll("^" + request.getContextPath(), "");
            try {
                content = mergeContent(content, getResourceContent(resource));
            } catch (FileNotFoundException e) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            } catch (ResourceNotFoundException e) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
            lastModified = Math.max(lastModified, getResourceLastModified(resource));
        }

        long ifModifiedSince = request.getDateHeader("If-Modified-Since");
        if (ifModifiedSince != 0 && ifModifiedSince / milliseconds == lastModified / milliseconds) {
            logger.debug("Return with SC_NOT_MODIFIED, since " + ifModifiedSince + " == " + lastModified);
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            return;
        }

        response.setContentType(mimeType + (mimeType.startsWith("text/") ? ";charset=" + charset : ""));
        if (cache) {
            response.setDateHeader("Expires", System.currentTimeMillis() + maxAge * milliseconds);
            response.setDateHeader("Last-Modified", lastModified);
            response.setHeader("Cache-control", "max-age=" + maxAge);
        } else {
            response.setDateHeader("Expires", System.currentTimeMillis());
            response.setDateHeader("Last-Modified", System.currentTimeMillis());
            response.setHeader("Cache-control", "max-age=0");
        }
        response.setContentLength(content.length);
        response.getOutputStream().write(content);
        response.getOutputStream().flush();
        response.getOutputStream().close();

    } catch (Exception e) {
        throw new ServletException(e.getMessage(), e);
    }
}

From source file:org.apache.catalina.core.ApplicationDispatcher.java

/**
 * Ask the resource represented by this RequestDispatcher to process
 * the associated request, and create (or append to) the associated
 * response.//from  w w w  .ja va2s  .  c o  m
 * <p>
 * <strong>IMPLEMENTATION NOTE</strong>: This implementation assumes
 * that no filters are applied to a forwarded or included resource,
 * because they were already done for the original request.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
private void invoke(ServletRequest request, ServletResponse response) throws IOException, ServletException {

    // Checking to see if the context classloader is the current context
    // classloader. If it's not, we're saving it, and setting the context
    // classloader to the Context classloader
    ClassLoader oldCCL = Thread.currentThread().getContextClassLoader();
    ClassLoader contextClassLoader = context.getLoader().getClassLoader();

    if (oldCCL != contextClassLoader) {
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    } else {
        oldCCL = null;
    }

    // Initialize local variables we may need
    HttpServletRequest hrequest = null;
    if (request instanceof HttpServletRequest)
        hrequest = (HttpServletRequest) request;
    HttpServletResponse hresponse = null;
    if (response instanceof HttpServletResponse)
        hresponse = (HttpServletResponse) response;
    Servlet servlet = null;
    IOException ioException = null;
    ServletException servletException = null;
    RuntimeException runtimeException = null;
    boolean unavailable = false;

    // Check for the servlet being marked unavailable
    if (wrapper.isUnavailable()) {
        log(sm.getString("applicationDispatcher.isUnavailable", wrapper.getName()));
        if (hresponse == null) {
            ; // NOTE - Not much we can do generically
        } else {
            long available = wrapper.getAvailable();
            if ((available > 0L) && (available < Long.MAX_VALUE))
                hresponse.setDateHeader("Retry-After", available);
            hresponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                    sm.getString("applicationDispatcher.isUnavailable", wrapper.getName()));
        }
        unavailable = true;
    }

    // Allocate a servlet instance to process this request
    try {
        if (!unavailable) {
            //                if (debug >= 2)
            //                    log("  Allocating servlet instance");
            servlet = wrapper.allocate();
            //                if ((debug >= 2) && (servlet == null))
            //                    log("    No servlet instance returned!");
        }
    } catch (ServletException e) {
        log(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e);
        servletException = e;
        servlet = null;
    } catch (Throwable e) {
        log(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e);
        servletException = new ServletException(
                sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e);
        servlet = null;
    }

    // Get the FilterChain Here
    ApplicationFilterFactory factory = ApplicationFilterFactory.getInstance();
    ApplicationFilterChain filterChain = factory.createFilterChain(request, wrapper, servlet);
    // Call the service() method for the allocated servlet instance
    try {
        String jspFile = wrapper.getJspFile();
        if (jspFile != null)
            request.setAttribute(Globals.JSP_FILE_ATTR, jspFile);
        else
            request.removeAttribute(Globals.JSP_FILE_ATTR);
        support.fireInstanceEvent(InstanceEvent.BEFORE_DISPATCH_EVENT, servlet, request, response);
        // for includes/forwards
        if ((servlet != null) && (filterChain != null)) {
            filterChain.doFilter(request, response);
        }
        // Servlet Service Method is called by the FilterChain
        request.removeAttribute(Globals.JSP_FILE_ATTR);
        support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response);
    } catch (ClientAbortException e) {
        request.removeAttribute(Globals.JSP_FILE_ATTR);
        support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response);
        ioException = e;
    } catch (IOException e) {
        request.removeAttribute(Globals.JSP_FILE_ATTR);
        support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response);
        log(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e);
        ioException = e;
    } catch (UnavailableException e) {
        request.removeAttribute(Globals.JSP_FILE_ATTR);
        support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response);
        log(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e);
        servletException = e;
        wrapper.unavailable(e);
    } catch (ServletException e) {
        request.removeAttribute(Globals.JSP_FILE_ATTR);
        support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response);
        Throwable rootCause = e;
        Throwable rootCauseCheck = null;

        // Extra aggressive rootCause finding
        do {
            try {
                rootCauseCheck = (Throwable) PropertyUtils.getProperty(rootCause, "rootCause");
                if (rootCauseCheck != null)
                    rootCause = rootCauseCheck;

            } catch (ClassCastException ex) {
                rootCauseCheck = null;
            } catch (IllegalAccessException ex) {
                rootCauseCheck = null;
            } catch (NoSuchMethodException ex) {
                rootCauseCheck = null;
            } catch (java.lang.reflect.InvocationTargetException ex) {
                rootCauseCheck = null;
            }
        } while (rootCauseCheck != null);

        log(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), rootCause);
        servletException = e;
    } catch (RuntimeException e) {
        request.removeAttribute(Globals.JSP_FILE_ATTR);
        support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response);
        log(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e);
        runtimeException = e;
    }

    // Release the filter chain (if any) for this request
    try {
        if (filterChain != null)
            filterChain.release();
    } catch (Throwable e) {
        log.error(sm.getString("standardWrapper.releaseFilters", wrapper.getName()), e);
        //FIXME Exception handling needs to be simpiler to what is in the StandardWrapperValue
    }

    // Deallocate the allocated servlet instance
    try {
        if (servlet != null) {
            wrapper.deallocate(servlet);
        }
    } catch (ServletException e) {
        log(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e);
        servletException = e;
    } catch (Throwable e) {
        log(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e);
        servletException = new ServletException(
                sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e);
    }

    // Reset the old context class loader
    if (oldCCL != null)
        Thread.currentThread().setContextClassLoader(oldCCL);

    // Rethrow an exception if one was thrown by the invoked servlet
    if (ioException != null)
        throw ioException;
    if (servletException != null)
        throw servletException;
    if (runtimeException != null)
        throw runtimeException;

}