Example usage for javax.servlet.http HttpServletResponse SC_NOT_MODIFIED

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

Introduction

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

Prototype

int SC_NOT_MODIFIED

To view the source code for javax.servlet.http HttpServletResponse SC_NOT_MODIFIED.

Click Source Link

Document

Status code (304) indicating that a conditional GET operation found that the resource was available and not modified.

Usage

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

/**
 * Execute a request/*from   w  w w .ja v  a  2 s  .co m*/
 *
 * @param httpMethodProxyRequest
 * @param httpServletRequest
 * @param httpServletResponse
 * @param history
 * @param outStream
 * @throws Exception
 */
private void executeRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse, History history, OutputStream outStream) throws Exception {
    int intProxyResponseCode = 999;
    try {
        // Create a default HttpClient
        HttpClient httpClient = new HttpClient();
        httpMethodProxyRequest.setFollowRedirects(false);
        ArrayList<String> headersToRemove = getRemoveHeaders();

        httpClient.getParams().setSoTimeout(60000);

        httpServletRequest.setAttribute("com.groupon.odo.removeHeaders", headersToRemove);
        intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
    } catch (Exception e) {
        requestInformation.get().outputString = "TIMEOUT";
        logRequestHistory(httpMethodProxyRequest, httpServletResponse, history);
        throw e;
    }
    logger.info("Response code: {}, {}", intProxyResponseCode,
            HttpUtilities.getURL(httpMethodProxyRequest.getURI().toString()));
    if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
            && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {

        String stringStatusCode = Integer.toString(intProxyResponseCode);
        processRedirect(stringStatusCode, httpMethodProxyRequest, httpServletRequest, httpServletResponse);
    } else {
        // Pass the response code back to the client
        httpServletResponse.setStatus(intProxyResponseCode);

        // Pass response headers back to the client
        Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
        for (Header header : headerArrayResponse) {
            httpServletResponse.setHeader(header.getName(), header.getValue());
        }

        // there is no data for a HTTP 304
        if (intProxyResponseCode != HttpServletResponse.SC_NOT_MODIFIED) {
            // Send the content to the client
            InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream();
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse);

            int intNextByte;
            // Collect all of the server data
            while ((intNextByte = bufferedInputStream.read()) != -1) {
                outStream.write(intNextByte);
            }
        }
    }
}

From source file:org.protorabbit.servlet.ProtoRabbitServlet.java

@SuppressWarnings("unchecked")
@Override/*from   ww  w .  j a v  a2 s. c  o m*/
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    WebContext wc = null;
    int bytesServed = 0;
    long iStartTime = System.currentTimeMillis();
    String path = req.getServletPath();
    String pathInfo = req.getPathInfo();
    String clientId = req.getRemoteAddr();
    try {

        String command = req.getParameter("command");
        if (command != null) {
            if ("ping".equals(command)) {
                resp.setHeader("pragma", "NO-CACHE");
                resp.setHeader("Cache-Control", "no-cache");
                resp.getWriter().write((new Date()).getTime() + "");
                return;
            } else if ("timeshift".equals(command)) {
                long clientTime = Long.parseLong(req.getParameter("clientTime"));
                resp.setHeader("pragma", "NO-CACHE");
                resp.setHeader("Cache-Control", "no-cache");
                long timeShift = ((new Date()).getTime() - clientTime);
                resp.getWriter().write("timeshift=" + timeShift + ";");
                return;
            } else if ("episodesync".equals(command)) {
                long startTime = Long.parseLong(req.getParameter("timestamp"));
                long transitTime = Long.parseLong(req.getParameter("transitTime"));
                Episode e = jcfg.getEpisodeManager().getEpisode(clientId, startTime);
                if (e == null) {
                    return;
                }
                e.setTransitTime(transitTime);
                Mark m = e.getMark("transit_to");
                long transitStartTime = m.getStartTime();
                long now = (new Date()).getTime();
                long duration = (now - (transitStartTime + transitTime));
                // add the page load directly following the start time  (add 1 to always make sure it is after transit time)
                e.addMark(new Mark("page_load", transitStartTime + transitTime + 1));
                Measure m1 = new Measure("transit_to", transitTime);
                // include transit time for this request and intial page load
                Measure m2 = new Measure("page_load", (duration + transitTime));
                e.addMeasure("transit_to", m1);
                e.addMeasure("page_load", m2);
                // now - duration is assumed transit time to offset call to this command
                resp.getWriter().write("var t_firstbyte=new Number(new Date());"
                        + "window.postMessage(\"EPISODES:mark:firstbyte:\" + t_firstbyte, \"*\");");
                return;
            } else if ("stats".equals(command)) {

                Map<String, Object> stats = new HashMap<String, Object>();
                stats.put("cachedResources", jcfg.getCombinedResourceManager().getResources());
                stats.put("templates", jcfg.getTemplates());
                stats.put("includeFiles", jcfg.getIncludeFiles());
                if (json == null) {
                    SerializationFactory factory = new SerializationFactory();
                    json = factory.getInstance();
                }
                resp.setHeader("pragma", "NO-CACHE");
                resp.setHeader("Cache-Control", "no-cache");
                Object jo = json.serialize(stats);
                resp.getWriter().write(jo.toString());
                return;
            } else if ("recordProfile".equals(command)) {

                long startTime = Long.parseLong(req.getParameter("timestamp"));
                long timeshift = Long.parseLong(req.getParameter("timeshift"));
                long timestamp = (new Date()).getTime();
                long duration = timestamp - startTime;
                Episode e = jcfg.getEpisodeManager().getEpisode(clientId, startTime);
                if (e == null) {
                    getLogger().severe("Unable to find episode " + startTime
                            + " to recourd data into with client " + clientId);
                    return;
                }
                e.setTimeshift(timeshift);
                // make sure to account for transit time
                Measure m = new Measure("full_request", duration - e.getTransitTime());
                e.addMeasure("full_request", m);
                String data = req.getParameter("data");
                JSONObject jo = null;
                try {
                    jo = new JSONObject(data);
                    jcfg.getEpisodeManager().updateEpisode(clientId, startTime, jo);
                } catch (JSONException ex) {
                    ex.printStackTrace();
                }
                resp.getWriter().write("ok");
                return;
            } else if ("episodes".equals(command)) {
                if (json == null) {
                    SerializationFactory factory = new SerializationFactory();
                    json = factory.getInstance();
                }
                Object data = null;
                data = jcfg.getEpisodeManager().getEpisodes();
                resp.setHeader("pragma", "NO-CACHE");
                resp.setHeader("Cache-Control", "no-cache");
                Object jo = json.serialize(data);
                resp.getWriter().write(jo.toString());
                return;
            } else if ("version".equals(command)) {
                resp.getWriter().write(version);
                return;
            } else if ("resetProfiles".equals(command)) {
                jcfg.getEpisodeManager().reset();
                resp.getWriter().write("profiles reset");
                return;
            } else if ("startProfiling".equals(command)) {
                jcfg.setProfile(true);
                resp.getWriter().write("profiling enabled");
                return;
            } else if ("stopProfiling".equals(command)) {
                jcfg.setProfile(false);
                resp.getWriter().write("profiling disabled");
                return;
            }
        } else if (pathInfo != null) {
            for (String t : writeHeaders) {
                if (pathInfo.endsWith(t)) {
                    writeHeaders(req, resp, pathInfo);
                    return;
                }
            }
        }

        // check for updates to the templates.json file
        if (isDevMode) {
            updateConfig();
        }
        boolean canGzip = false;
        // check if client supports gzip
        Enumeration<String> hnum = req.getHeaders("Accept-Encoding");
        while (hnum.hasMoreElements()) {
            String acceptType = hnum.nextElement();
            if (acceptType != null && acceptType.indexOf("gzip") != -1) {
                canGzip = true;
                break;
            }
        }
        wc = new WebContext(jcfg, ctx, req, resp);
        wc.setAttribute(Config.START_TIME, new Long(new Date().getTime()));
        String id = req.getParameter("resourceid");
        if (id != null) {
            processResourceRequest(id, wc, req, resp, canGzip);
            return;
        }

        if (("/" + serviceURI).equals(path)) {
            path = req.getPathInfo();
        }
        int lastSep = -1;
        if (path != null) {
            lastSep = path.lastIndexOf("/");
        }
        String namespace = null;
        if (lastSep != -1 && lastSep < path.length() - 1) {
            int nextDot = path.indexOf(".", lastSep + 1);
            int lastSlash = path.lastIndexOf("/");
            if (nextDot != -1) {
                id = path.substring(lastSep + 1, nextDot);
            } else {
                if (lastSlash != -1 && lastSlash < path.length()) {
                    id = path.substring(lastSlash + 1);
                }
            }
            if (lastSlash != -1 && lastSlash < path.length()) {
                namespace = path.substring(0, lastSlash);
            }
        }
        ITemplate t = null;

        if (id != null) {
            t = jcfg.getTemplate(id, wc);

            if (jcfg.profile()) {
                long timestamp = (new Date()).getTime();
                Episode e = new Episode(timestamp);
                e.setUserAgent(req.getHeader("user-agent"));
                e.setClientId(clientId);
                e.setUri(id);
                e.addMark(new Mark("full_request", timestamp));
                e.addMark(new Mark("server_render", timestamp));
                wc.setAttribute(Config.EPISODE, e);
                wc.setAttribute(Config.DEFAULT_EPISODE_PROCESS, new Boolean(true));
                jcfg.getEpisodeManager().addEpisode(e);
            }
        }
        // make sure that if a namespace is required that is is used to access the template. Also account for "" which can 
        // result from the namespace.
        boolean namespaceOk = true;
        if (t != null && t.getURINamespace(wc) != null) {
            if (namespace == null || (namespace != null && "".equals(namespace))
                    || !t.getURINamespace(wc).startsWith(namespace)) {
                namespaceOk = false;
                getLogger().warning(
                        "request for template " + id + " without matching namespace " + t.getURINamespace(wc));
            }
        }

        if (id == null || t == null || !namespaceOk) {
            getLogger().warning("template " + id + " requested but not found.");
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        // set the template engine
        IEngine renderEngine = null;
        if (t.getTemplateURI(wc).getFullURI().endsWith(".st")) {
            renderEngine = new StringTemplateEngine();
            // build up a list of the session/reqeust attributes for string tempalte
            Map<String, Object> sessionMap = new HashMap<String, Object>();
            HttpSession hs = req.getSession();
            Enumeration en = hs.getAttributeNames();
            while (en.hasMoreElements()) {
                String key = (String) en.nextElement();
                sessionMap.put(key, hs.getAttribute(key));
            }
            Map<String, Object> requestMap = new HashMap<String, Object>();
            Enumeration ren = req.getAttributeNames();
            while (ren.hasMoreElements()) {
                String key = (String) en.nextElement();
                requestMap.put(key, req.getAttribute(key));
            }
            wc.setAttribute("session", sessionMap);
            req.getSession().setAttribute("protorabbitVersion", version);
            req.getSession().setAttribute("protorabbitBuildDate", buildDate);
            wc.setAttribute("request", requestMap);
        } else {
            renderEngine = engine;
        }
        // buffer the output stream
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        ICacheable tr = t.getTemplateResource();
        resp.setHeader("Content-Type", "text/html");
        if (jcfg.profile()) {
            resp.setHeader("pragma", "NO-CACHE");
            resp.setHeader("Cache-Control", "no-cache");
        }

        // get the initial content or get the content if it is expired
        if ((t.getTimeout(wc) != null && (t.getTimeout(wc) > 0)
                && ((tr == null || tr.getCacheContext().isExpired()) || t.requiresRefresh(wc) || jcfg.profile()
                        || t.hasUserAgentPropertyDependencies(wc)))) {
            if (canGzip && t.gzipTemplate(wc) != null && t.gzipTemplate(wc) == true) {
                resp.setHeader("Vary", "Accept-Encoding");
                resp.setHeader("Content-Encoding", "gzip");
            }
            // headers after this point do not get written
            renderEngine.renderTemplate(id, wc, bos);

            String content = bos.toString(jcfg.getEncoding());
            String hash = IOUtil.generateHash(content);
            ICacheable cr = new CacheableResource("text/html", t.getTimeout(wc), hash);

            if (!jcfg.profile()) {
                resp.setHeader("ETag", cr.getContentHash());
            }
            cr.setContent(new StringBuffer(content));
            t.setTemplateResource(cr);

            if (canGzip && t.gzipTemplate(wc) != null && t.gzipTemplate(wc) == true) {
                byte[] bytes = cr.getGZippedContent();
                cr.incrementGzipAccessCount();
                resp.setContentLength(bytes.length);
                OutputStream out = resp.getOutputStream();
                if (bytes != null) {
                    ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
                    bytesServed = bytes.length;
                    IOUtil.writeBinaryResource(bis, out);
                }
            } else {
                OutputStream out = resp.getOutputStream();
                byte[] bytes = cr.getContent().toString().getBytes();
                cr.incrementAccessCount();
                resp.setContentLength(bytes.length);
                bytesServed = bytes.length;
                if (bytes != null) {
                    ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
                    IOUtil.writeBinaryResource(bis, out);
                }
            }

            // write out content / gzip or otherwise from the cache
        } else if (t.getTimeout(wc) != null && t.getTimeout(wc) > 0 && tr != null) {

            // if the client has the same resource as the one on the server return a 304
            // get the If-None-Match header
            String etag = tr.getContentHash();

            String ifNoneMatch = req.getHeader("If-None-Match");
            if (etag != null && ifNoneMatch != null && ifNoneMatch.equals(etag)) {
                resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                if (jcfg.profile()) {
                    profile(wc);
                }
                return;
            }

            resp.setContentType(tr.getContentType());
            if (!jcfg.profile()) {
                resp.setHeader("ETag", etag);
                resp.setHeader("Expires", tr.getCacheContext().getExpires());
                resp.setHeader("Cache-Control", "public,max-age=" + tr.getCacheContext().getMaxAge());
            }

            if (canGzip && t.gzipTemplate(wc) != null && t.gzipTemplate(wc) == true) {

                OutputStream out = resp.getOutputStream();
                resp.setHeader("Content-Encoding", "gzip");
                resp.setHeader("Vary", "Accept-Encoding");

                tr.incrementGzipAccessCount();
                byte[] bytes = tr.getGZippedContent();

                if (bytes != null) {
                    resp.setContentLength(bytes.length);
                    bytesServed = bytes.length;
                    ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
                    IOUtil.writeBinaryResource(bis, out);
                }
            } else {

                OutputStream out = resp.getOutputStream();
                tr.incrementAccessCount();
                byte[] bytes = tr.getContent().toString().getBytes();
                resp.setContentLength(bytes.length);
                if (bytes != null) {
                    ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
                    bytesServed = bytes.length;
                    IOUtil.writeBinaryResource(bis, out);
                }
            }

        } else {
            OutputStream out = resp.getOutputStream();
            //  t.getTemplateResource().incrementAccessCount();
            renderEngine.renderTemplate(id, wc, bos);
            bytesServed = bos.size();
            out.write(bos.toByteArray());
        }
        // increment the total template accesses
        if (t != null) {
            t.incrementAccessCount();
        }
        if (jcfg.profile()) {
            profile(wc);
        }

    } catch (java.net.SocketException jos) {
        logger.warning("Got broken pipe. Ignoring...");
        return;
    } finally {
        if (wc != null) {
            wc.destroy();
        }
    }

    long endTime = System.currentTimeMillis();
    // add more stats stuff
    IStat stat = new StatsItem();
    stat.setTimestamp(System.currentTimeMillis());
    stat.setPath(path);
    stat.setPathInfo(pathInfo);
    stat.setRemoteClient(cg.getClientId(req));
    stat.setType(StatsItem.types.VIEW);
    stat.setRequestURI(req.getRequestURI());
    stat.setProcessTime(new Long(endTime - iStartTime));
    stat.setContentLength(new Long(bytesServed));
    stat.setContentType("text/html");
    statsManager.add(stat);

}

From source file:org.sakaiproject.lessonbuildertool.service.LessonBuilderAccessService.java

public HttpAccess getHttpAccess() {
    return new HttpAccess() {

        public void handleAccess(HttpServletRequest req, HttpServletResponse res, Reference ref,
                Collection copyrightAcceptedRefs) throws EntityPermissionException, EntityNotDefinedException,
                EntityAccessOverloadException, EntityCopyrightException {

            // preauthorized by encrypted key
            boolean isAuth = false;

            // if the id is null, the request was for just ".../content"
            String refId = ref.getId();
            if (refId == null) {
                refId = "";
            }/*from  w ww. j ava  2 s .co  m*/

            if (!refId.startsWith("/item")) {
                throw new EntityNotDefinedException(ref.getReference());
            }

            String itemString = refId.substring("/item/".length());
            // string is of form /item/NNN/url. get the number
            int i = itemString.indexOf("/");
            if (i < 0) {
                throw new EntityNotDefinedException(ref.getReference());
            }

            // get session. The problem here is that some multimedia tools don't reliably
            // pass JSESSIONID

            String sessionParam = req.getParameter("lb.session");

            if (sessionParam != null) {
                try {
                    Cipher sessionCipher = Cipher.getInstance("Blowfish");
                    sessionCipher.init(Cipher.DECRYPT_MODE, sessionKey);
                    byte[] sessionBytes = DatatypeConverter.parseHexBinary(sessionParam);
                    sessionBytes = sessionCipher.doFinal(sessionBytes);
                    String sessionString = new String(sessionBytes);
                    int j = sessionString.indexOf(":");
                    String sessionId = sessionString.substring(0, j);
                    String url = sessionString.substring(j + 1);

                    UsageSession s = UsageSessionService.getSession(sessionId);
                    if (s == null || s.isClosed() || url == null || !url.equals(refId)) {
                        throw new EntityPermissionException(sessionManager.getCurrentSessionUserId(),
                                ContentHostingService.AUTH_RESOURCE_READ, ref.getReference());
                    } else {
                        isAuth = true;
                    }

                } catch (Exception e) {
                    System.out.println("unable to decode lb.session " + e);
                }
            }

            // basically there are two checks to be done: is the item accessible in Lessons,
            // and is the underlying resource accessible in Sakai.
            // This code really does check both. Sort of. 
            // 1) it checks accessibility to the containing page by seeing if it has been visited.
            //  This is stricter than necessary, but there's no obvious reason to let people use this
            //  who aren't following an actual URL we gave them.
            // 2) it checks group access as part of the normal resource permission check. Sakai
            //  should sync the two. We actually don't check it for items in student home directories,
            //  as far as I can tell
            // 3) it checks availability (prerequisites) by calling the code from SimplePageBean
            // We could rewrite this with the new LessonsAccess methods, but since we have to do
            // resource permission checking also, and there's some duplication, it doesn't seem worth
            // rewriting this code. What I've done is review it to make sure it does the same thing.

            String id = itemString.substring(i);
            itemString = itemString.substring(0, i);

            boolean pushedAdvisor = false;

            try {
                securityService.pushAdvisor(allowReadAdvisor);

                pushedAdvisor = true;

                Long itemId = 0L;
                try {
                    itemId = (Long) Long.parseLong(itemString);
                } catch (Exception e) {
                    throw new EntityNotDefinedException(ref.getReference());
                }

                // say we've read this
                if (itemId != 0L)
                    track(itemId.longValue(), sessionManager.getCurrentSessionUserId());

                // code here is also in simplePageBean.isItemVisible. change it there
                // too if you change this logic

                SimplePageItem item = simplePageToolDao.findItem(itemId.longValue());
                SimplePage currentPage = simplePageToolDao.getPage(item.getPageId());
                String owner = currentPage.getOwner(); // if student content
                String group = currentPage.getGroup(); // if student content
                if (group != null)
                    group = "/site/" + currentPage.getSiteId() + "/group/" + group;
                String currentSiteId = currentPage.getSiteId();

                // first let's make sure the user is allowed to access
                // the containing page

                if (!isAuth && !canReadPage(currentSiteId)) {
                    throw new EntityPermissionException(sessionManager.getCurrentSessionUserId(),
                            ContentHostingService.AUTH_RESOURCE_READ, ref.getReference());
                }

                // If the resource is the actual one in the item, or
                // it is in the containing folder, then do lesson builder checking.
                // otherwise do normal resource checking

                if (!isAuth) {

                    boolean useLb = false;

                    // I've seen sakai id's with //, not sure why. they work but will mess up the comparison
                    String itemResource = item.getSakaiId().replace("//", "/");

                    // only use lb security if the user has visited the page
                    // this handles the various page release issues, although
                    // it's not quite as flexible as the real code. But I don't
                    // see any reason to help the user follow URLs that they can't
                    // legitimately have seen.

                    if (simplePageToolDao.isPageVisited(item.getPageId(),
                            sessionManager.getCurrentSessionUserId(), owner)) {
                        if (id.equals(itemResource))
                            useLb = true;
                        else {
                            // not exact, but see if it's in the containing folder
                            int endFolder = itemResource.lastIndexOf("/");
                            if (endFolder > 0) {
                                String folder = itemResource.substring(0, endFolder + 1);
                                if (id.startsWith(folder))
                                    useLb = true;
                            }
                        }
                    }

                    if (useLb) {
                        // key into access cache
                        String accessKey = itemString + ":" + sessionManager.getCurrentSessionUserId();
                        // special access if we have a student site and item is in worksite of one of the students
                        // Normally we require that the person doing the access be able to see the file, but in
                        // that specific case we allow the access. Note that in order to get a sakaiid pointing
                        // into the user's space, the person editing the page must have been able to read the file.
                        // this allows a user in your group to share any of your resources that he can see.
                        String usersite = null;
                        if (owner != null && group != null && id.startsWith("/user/")) {
                            String username = id.substring(6);
                            int slash = username.indexOf("/");
                            if (slash > 0)
                                usersite = username.substring(0, slash);
                            // normally it is /user/EID, so convert to userid
                            try {
                                usersite = UserDirectoryService.getUserId(usersite);
                            } catch (Exception e) {
                            }
                            ;
                            String itemcreator = item.getAttribute("addedby");
                            // suppose a member of the group adds a resource from another member of
                            // the group. (This will only work if they have read access to it.)
                            // We don't want to gimick access in that case. I think if you
                            // add your own item, you've given consent. But not if someone else does.
                            // itemcreator == null is for items added before this patch. I'm going to
                            // continue to allow access for them, to avoid breaking existing content.
                            if (usersite != null && itemcreator != null && !usersite.equals(itemcreator))
                                usersite = null;
                        }

                        // code here is also in simplePageBean.isItemVisible. change it there
                        // too if you change this logic

                        // for a student page, if it's in one of the groups' worksites, allow it
                        // The assumption is that only one of those people can put content in the
                        // page, and then only if the can see it.

                        if (owner != null && usersite != null
                                && authzGroupService.getUserRole(usersite, group) != null) {
                            // OK
                        } else if (owner != null && group == null && id.startsWith("/user/" + owner)) {
                            // OK
                        } else {
                            // do normal checking for other content
                            if (pushedAdvisor) {
                                securityService.popAdvisor();
                                pushedAdvisor = false;
                            }
                            // our version of allowget does not check hidden but does everything else
                            // if it's a student page, however use the normal check so students can't
                            // use this to bypass release control
                            if (owner == null && !allowGetResource(id, currentSiteId)
                                    || owner != null && !contentHostingService.allowGetResource(id)) {
                                throw new EntityPermissionException(sessionManager.getCurrentSessionUserId(),
                                        ContentHostingService.AUTH_RESOURCE_READ, ref.getReference());
                            }

                            securityService.pushAdvisor(allowReadAdvisor);
                            pushedAdvisor = true;

                        }

                        // now enforce LB access restrictions if any
                        if (item != null && item.isPrerequisite()
                                && !"true".equals((String) accessCache.get(accessKey))) {
                            // computing requirements is so messy that it's worth
                            // instantiating
                            // a SimplePageBean to do it. Otherwise we have to duplicate
                            // lots of
                            // code that changes. And we want it to be a transient bean
                            // because there are
                            // caches that we aren't trying to manage in the long term
                            // but don't do this unless the item needs checking

                            if (!canSeeAll(currentPage.getSiteId())) {
                                SimplePageBean simplePageBean = new SimplePageBean();
                                simplePageBean.setMessageLocator(messageLocator);
                                simplePageBean.setToolManager(toolManager);
                                simplePageBean.setSecurityService(securityService);
                                simplePageBean.setSessionManager(sessionManager);
                                simplePageBean.setSiteService(siteService);
                                simplePageBean.setContentHostingService(contentHostingService);
                                simplePageBean.setSimplePageToolDao(simplePageToolDao);
                                simplePageBean.setForumEntity(forumEntity);
                                simplePageBean.setQuizEntity(quizEntity);
                                simplePageBean.setAssignmentEntity(assignmentEntity);
                                simplePageBean.setBltiEntity(bltiEntity);
                                simplePageBean.setGradebookIfc(gradebookIfc);
                                simplePageBean.setMemoryService(memoryService);
                                simplePageBean.setCurrentSiteId(currentPage.getSiteId());
                                simplePageBean.setCurrentPage(currentPage);
                                simplePageBean.setCurrentPageId(currentPage.getPageId());
                                simplePageBean.init();

                                if (!simplePageBean.isItemAvailable(item, item.getPageId())) {
                                    throw new EntityPermissionException(null, null, null);
                                }
                            }
                            accessCache.put(accessKey, "true");

                        }
                    } else {

                        // normal security. no reason to use advisor
                        if (pushedAdvisor)
                            securityService.popAdvisor();
                        pushedAdvisor = false;

                        // not uselb -- their allowget, not ours. theirs checks hidden
                        if (!contentHostingService.allowGetResource(id)) {
                            throw new EntityPermissionException(sessionManager.getCurrentSessionUserId(),
                                    ContentHostingService.AUTH_RESOURCE_READ, ref.getReference());
                        }
                    }

                }

                // access checks are OK, get the thing

                // first see if it's not in resources, i.e.
                // if it doesn't start with /access/content it's something odd. redirect to it.
                // probably resources access control won't apply to it
                String url = contentHostingService.getUrl(id);
                // https://heidelberg.rutgers.edu/access/citation/content/group/24da8519-08c2-4c8c-baeb-8abdfd6c69d7/New%20Citation%20List

                int n = url.indexOf("//");
                if (n > 0) {
                    n = url.indexOf("/", n + 2);
                    if (n > 0) {
                        String path = url.substring(n);
                        if (!path.startsWith("/access/content")) {
                            res.sendRedirect(url);
                            return;
                        }
                    }
                }

                ContentResource resource = null;
                try {
                    resource = contentHostingService.getResource(id);
                } catch (IdUnusedException e) {
                    throw new EntityNotDefinedException(e.getId());
                } catch (PermissionException e) {
                    throw new EntityPermissionException(e.getUser(), e.getLock(), e.getResource());
                } catch (TypeException e) {
                    throw new EntityNotDefinedException(id);
                }

                // we only do copyright on resources. I.e. not on inline things,which are MULTIMEDIA
                if (item.getType() == SimplePageItem.RESOURCE && needsCopyright(resource)) {
                    throw new EntityCopyrightException(resource.getReference());
                }
                try {
                    // Wrap it in any filtering needed.
                    resource = contentFilterService.wrap(resource);

                    // following cast is redundant is current kernels, but is needed for Sakai 2.6.1
                    long len = (long) resource.getContentLength();
                    String contentType = resource.getContentType();

                    //    for url resource type, encode a redirect to the body URL
                    // in 2.10 have to check resourcetype, but in previous releasese
                    // it doesn't get copied in site copy, so check content type. 10 doesn't set the contenttype to url
                    // so we have to check both to work in all versions
                    if (contentType.equalsIgnoreCase(ResourceProperties.TYPE_URL)
                            || "org.sakaiproject.content.types.urlResource"
                                    .equalsIgnoreCase(resource.getResourceType())) {
                        if (len < MAX_URL_LENGTH) {
                            byte[] content = resource.getContent();
                            if ((content == null) || (content.length == 0)) {
                                throw new IdUnusedException(ref.getReference());
                            }
                            //    An invalid URI format will get caught by the
                            //    outermost catch block
                            URI uri = new URI(new String(content, "UTF-8"));
                            eventTrackingService.post(
                                    eventTrackingService.newEvent(ContentHostingService.EVENT_RESOURCE_READ,
                                            resource.getReference(null), false));
                            res.sendRedirect(uri.toASCIIString());
                        } else {
                            //    we have a text/url mime type, but the body is too
                            //    long to issue as a redirect
                            throw new EntityNotDefinedException(ref.getReference());
                        }
                    } else {

                        //    use the last part, the file name part of the id, for
                        //    the download file name
                        String fileName = Web.encodeFileName(req, Validator.getFileName(ref.getId()));

                        String disposition = null;

                        boolean inline = false;
                        if (Validator.letBrowserInline(contentType)) {
                            // type can be inline, but if HTML we have more checks to do
                            if (inlineHtml || (!"text/html".equalsIgnoreCase(contentType)
                                    && !"application/xhtml+xml".equals(contentType)))
                                // easy cases: not HTML or HTML always OK
                                inline = true;
                            else {
                                // HTML and html is not allowed globally. code copied from BaseContentServices
                                ResourceProperties rp = resource.getProperties();

                                boolean fileInline = false;
                                boolean folderInline = false;

                                try {
                                    fileInline = rp.getBooleanProperty(ResourceProperties.PROP_ALLOW_INLINE);
                                } catch (EntityPropertyNotDefinedException e) {
                                    // we expect this so nothing to do!
                                }

                                if (!fileInline)
                                    try {
                                        folderInline = resource.getContainingCollection().getProperties()
                                                .getBooleanProperty(ResourceProperties.PROP_ALLOW_INLINE);
                                    } catch (EntityPropertyNotDefinedException e) {
                                        // we expect this so nothing to do!
                                    }

                                if (fileInline || folderInline) {
                                    inline = true;
                                }
                            }
                        }

                        if (inline) {
                            disposition = "inline; filename=\"" + fileName + "\"";
                        } else {
                            disposition = "attachment; filename=\"" + fileName + "\"";
                        }

                        // NOTE: Only set the encoding on the content we have
                        // to.
                        // Files uploaded by the user may have been created with
                        // different encodings, such as ISO-8859-1;
                        // rather than (sometimes wrongly) saying its UTF-8, let
                        // the browser auto-detect the encoding.
                        // If the content was created through the WYSIWYG
                        // editor, the encoding does need to be set (UTF-8).
                        String encoding = resource.getProperties()
                                .getProperty(ResourceProperties.PROP_CONTENT_ENCODING);
                        if (encoding != null && encoding.length() > 0) {
                            contentType = contentType + "; charset=" + encoding;
                        }

                        // from contenthosting

                        res.addHeader("Cache-Control", "must-revalidate, private");
                        res.addHeader("Expires", "-1");
                        ResourceProperties rp = resource.getProperties();
                        long lastModTime = 0;

                        try {
                            Time modTime = rp.getTimeProperty(ResourceProperties.PROP_MODIFIED_DATE);
                            lastModTime = modTime.getTime();
                        } catch (Exception e1) {
                            M_log.info("Could not retrieve modified time for: " + resource.getId());
                        }

                        // KNL-1316 tell the browser when our file was last modified for caching reasons
                        if (lastModTime > 0) {
                            SimpleDateFormat rfc1123Date = new SimpleDateFormat(RFC1123_DATE, LOCALE_US);
                            rfc1123Date.setTimeZone(TimeZone.getTimeZone("GMT"));
                            res.addHeader("Last-Modified", rfc1123Date.format(lastModTime));
                        }

                        // KNL-1316 let's see if the user already has a cached copy. Code copied and modified from Tomcat DefaultServlet.java
                        long headerValue = req.getDateHeader("If-Modified-Since");
                        if (headerValue != -1 && (lastModTime < headerValue + 1000)) {
                            // The entity has not been modified since the date specified by the client. This is not an error case.
                            res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                            return;
                        }

                        ArrayList<Range> ranges = parseRange(req, res, len);

                        if (req.getHeader("Range") == null || (ranges == null) || (ranges.isEmpty())) {

                            // stream the content using a small buffer to keep memory managed
                            InputStream content = null;
                            OutputStream out = null;

                            try {
                                content = resource.streamContent();
                                if (content == null) {
                                    throw new IdUnusedException(ref.getReference());
                                }

                                res.setContentType(contentType);
                                res.addHeader("Content-Disposition", disposition);
                                res.addHeader("Accept-Ranges", "bytes");

                                // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4187336
                                if (len <= Integer.MAX_VALUE) {
                                    res.setContentLength((int) len);
                                } else {
                                    res.addHeader("Content-Length", Long.toString(len));
                                }

                                // set the buffer of the response to match what we are reading from the request
                                if (len < STREAM_BUFFER_SIZE) {
                                    res.setBufferSize((int) len);
                                } else {
                                    res.setBufferSize(STREAM_BUFFER_SIZE);
                                }

                                out = res.getOutputStream();

                                copyRange(content, out, 0, len - 1);
                            } catch (ServerOverloadException e) {
                                throw e;
                            } catch (Exception ignore) {
                            } finally {
                                // be a good little program and close the stream - freeing up valuable system resources
                                if (content != null) {
                                    content.close();
                                }

                                if (out != null) {
                                    try {
                                        out.close();
                                    } catch (Exception ignore) {
                                    }
                                }
                            }

                            // Track event - only for full reads
                            eventTrackingService.post(
                                    eventTrackingService.newEvent(ContentHostingService.EVENT_RESOURCE_READ,
                                            resource.getReference(null), false));

                        } else {
                            // Output partial content. Adapted from Apache Tomcat 5.5.27 DefaultServlet.java

                            res.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

                            if (ranges.size() == 1) {

                                // Single response

                                Range range = (Range) ranges.get(0);
                                res.addHeader("Content-Range",
                                        "bytes " + range.start + "-" + range.end + "/" + range.length);
                                long length = range.end - range.start + 1;
                                if (length < Integer.MAX_VALUE) {
                                    res.setContentLength((int) length);
                                } else {
                                    // Set the content-length as String to be able to use a long
                                    res.setHeader("content-length", "" + length);
                                }

                                res.addHeader("Content-Disposition", disposition);

                                if (contentType != null) {
                                    res.setContentType(contentType);
                                }

                                // stream the content using a small buffer to keep memory managed
                                InputStream content = null;
                                OutputStream out = null;

                                try {
                                    content = resource.streamContent();
                                    if (content == null) {
                                        throw new IdUnusedException(ref.getReference());
                                    }

                                    // set the buffer of the response to match what we are reading from the request
                                    if (len < STREAM_BUFFER_SIZE) {
                                        res.setBufferSize((int) len);
                                    } else {
                                        res.setBufferSize(STREAM_BUFFER_SIZE);
                                    }

                                    out = res.getOutputStream();

                                    copyRange(content, out, range.start, range.end);

                                } catch (ServerOverloadException e) {
                                    throw e;
                                } catch (SocketException e) {
                                    //a socket exception usualy means the client aborted the connection or similar
                                    if (M_log.isDebugEnabled()) {
                                        M_log.debug("SocketExcetion", e);
                                    }
                                } catch (Exception ignore) {
                                } finally {
                                    // be a good little program and close the stream - freeing up valuable system resources
                                    IOUtils.closeQuietly(content);
                                    IOUtils.closeQuietly(out);
                                }

                            } else {

                                // Multipart response

                                res.setContentType("multipart/byteranges; boundary=" + MIME_SEPARATOR);

                                // stream the content using a small buffer to keep memory managed
                                OutputStream out = null;

                                try {
                                    // set the buffer of the response to match what we are reading from the request
                                    if (len < STREAM_BUFFER_SIZE) {
                                        res.setBufferSize((int) len);
                                    } else {
                                        res.setBufferSize(STREAM_BUFFER_SIZE);
                                    }

                                    out = res.getOutputStream();

                                    copyRanges(resource, out, ranges.iterator(), contentType);

                                } catch (SocketException e) {
                                    //a socket exception usualy means the client aborted the connection or similar
                                    if (M_log.isDebugEnabled()) {
                                        M_log.debug("SocketExcetion", e);
                                    }
                                } catch (Exception ignore) {
                                    M_log.error("Swallowing exception", ignore);
                                } finally {
                                    // be a good little program and close the stream - freeing up valuable system resources
                                    IOUtils.closeQuietly(out);
                                }

                            } // output multiple ranges

                        } // output partial content 

                    }

                } catch (Exception t) {
                    throw new EntityNotDefinedException(ref.getReference());
                    // following won't work in 2.7.1
                    // throw new EntityNotDefinedException(ref.getReference(), t);
                }

                // not sure why we're trapping exceptions and calling them not defined, but
                // a few types are needed by the caller
            } catch (EntityCopyrightException ce) {
                // copyright exception needs to go as is, to give copyright alert
                throw ce;
            } catch (EntityPermissionException pe) {
                // also want permission exceptions; it will generate a login page
                throw pe;
            } catch (Exception ex) {
                throw new EntityNotDefinedException(ref.getReference());
            } finally {
                if (pushedAdvisor)
                    securityService.popAdvisor();
            }
        }
    };
}

From source file:org.apache.slide.webdav.method.AbstractWebdavMethod.java

/**
 * Check if the conditions specified in the optional If headers are
 * satisfied./*from   ww  w.  j a  v a 2s  .  c  om*/
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 * @param resourceInfo File object
 * @return boolean true if the resource meets all the specified conditions,
 * and false if any of the conditions is not satisfied, in which case
 * request processing is stopped
 */
protected boolean checkIfHeaders(HttpServletRequest request, HttpServletResponse response,
        ResourceInfo resourceInfo) throws IOException {
    // the ETag without apostrophes ("), we use apostrophes as delimiters
    // to because some clients provide If header with out apostrophes
    String eTag = getETagValue(resourceInfo, true);
    long lastModified = resourceInfo.date;

    StringTokenizer commaTokenizer;

    String headerValue;

    // Checking If-Match
    headerValue = request.getHeader("If-Match");
    if (headerValue != null) {
        if (headerValue.indexOf("*") == -1) {

            commaTokenizer = new StringTokenizer(headerValue, ", \"");
            boolean matchingTagFound = false;

            while (!matchingTagFound && commaTokenizer.hasMoreTokens()) {
                matchingTagFound = commaTokenizer.nextToken().equals(eTag);
            }

            // If none of the given ETags match, 412 Precodition failed is
            // sent back
            if (!matchingTagFound) {
                response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                return false;
            }
        } else {
            if (!resourceInfo.exists()) {
                response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                return false;
            }
        }
    }

    // Checking If-Modified-Since
    headerValue = request.getHeader("If-Modified-Since");
    if (headerValue != null) {

        // If an If-None-Match header has been specified, if modified since
        // is ignored.
        if (request.getHeader("If-None-Match") == null) {
            Date date = parseHttpDate(headerValue);

            if ((date != null) && (lastModified <= (date.getTime() + 1000))) {
                // The entity has not been modified since the date
                // specified by the client. This is not an error case.
                response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
                return false;
            }
        }
    }

    // Checking If-None-Match
    headerValue = request.getHeader("If-None-Match");
    if (headerValue != null) {
        if (headerValue.indexOf("*") == -1) {

            commaTokenizer = new StringTokenizer(headerValue, ", \"");
            while (commaTokenizer.hasMoreTokens()) {
                if (commaTokenizer.nextToken().equals(eTag)) {
                    // For GET and HEAD, we respond with  304 Not Modified.
                    // For every other method, 412 Precondition Failed
                    if (("GET".equals(request.getMethod())) || ("HEAD".equals(request.getMethod()))) {
                        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
                        return false;
                    } else {
                        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                        return false;
                    }
                }
            }
        } else {
            if (resourceInfo.exists()) {
                response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                return false;
            }
        }
    }

    // Checking If-Unmodified-Since
    headerValue = request.getHeader("If-Unmodified-Since");
    if (headerValue != null) {
        Date date = parseHttpDate(headerValue);

        if ((date != null) && (lastModified > date.getTime())) {
            // The entity has not been modified since the date
            // specified by the client. This is not an error case.
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return false;
        }
    }
    return true;
}

From source file:org.opencms.loader.CmsJspLoader.java

/**
 * Dispatches the current request to the OpenCms internal JSP.<p>
 * //from   w w w . j  a v  a 2  s .com
 * @param controller the current controller
 * 
 * @return the content of the processed JSP
 * 
 * @throws ServletException if inclusion does not work
 * @throws IOException if inclusion does not work
 */
protected byte[] dispatchJsp(CmsFlexController controller) throws ServletException, IOException {

    // get request / response wrappers
    CmsFlexRequest f_req = controller.getCurrentRequest();
    CmsFlexResponse f_res = controller.getCurrentResponse();

    try {
        f_req.getRequestDispatcher(controller.getCmsObject().getSitePath(controller.getCmsResource()))
                .include(f_req, f_res);
    } catch (SocketException e) {
        // uncritical, might happen if client (browser) does not wait until end of page delivery
        LOG.debug(Messages.get().getBundle().key(Messages.LOG_IGNORING_EXC_1, e.getClass().getName()), e);
    }

    byte[] result = null;
    HttpServletResponse res = controller.getTopResponse();

    if (!controller.isStreaming() && !f_res.isSuspended()) {
        try {
            // if a JSP error page was triggered the response will be already committed here
            if (!res.isCommitted() || m_errorPagesAreNotCommitted) {

                // check if the current request was done by a workplace user
                boolean isWorkplaceUser = CmsWorkplaceManager.isWorkplaceUser(f_req);

                // check if the content was modified since the last request
                if (controller.isTop() && !isWorkplaceUser
                        && CmsFlexController.isNotModifiedSince(f_req, controller.getDateLastModified())) {
                    if (f_req.getParameterMap().size() == 0) {
                        // only use "expires" header on pages that have no parameters,
                        // otherwise some browsers (e.g. IE 6) will not even try to request 
                        // updated versions of the page
                        CmsFlexController.setDateExpiresHeader(res, controller.getDateExpires(),
                                m_clientCacheMaxAge);
                    }
                    res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    return null;
                }

                // get the result byte array
                result = f_res.getWriterBytes();
                HttpServletRequest req = controller.getTopRequest();
                if (req.getHeader(CmsRequestUtil.HEADER_OPENCMS_EXPORT) != null) {
                    // this is a non "on-demand" static export request, don't write to the response stream
                    req.setAttribute(CmsRequestUtil.HEADER_OPENCMS_EXPORT,
                            new Long(controller.getDateLastModified()));
                } else if (controller.isTop()) {
                    // process headers and write output if this is the "top" request/response                                  
                    res.setContentLength(result.length);
                    // check for preset error code
                    Integer errorCode = (Integer) req.getAttribute(CmsRequestUtil.ATTRIBUTE_ERRORCODE);
                    if (errorCode == null) {
                        // set last modified / no cache headers only if this is not an error page
                        if (isWorkplaceUser) {
                            res.setDateHeader(CmsRequestUtil.HEADER_LAST_MODIFIED, System.currentTimeMillis());
                            CmsRequestUtil.setNoCacheHeaders(res);
                        } else {
                            // set date last modified header                        
                            CmsFlexController.setDateLastModifiedHeader(res, controller.getDateLastModified());
                            if ((f_req.getParameterMap().size() == 0)
                                    && (controller.getDateLastModified() > -1)) {
                                // only use "expires" header on pages that have no parameters
                                // and that are cachable (i.e. 'date last modified' is set)
                                // otherwise some browsers (e.g. IE 6) will not even try to request 
                                // updated versions of the page
                                CmsFlexController.setDateExpiresHeader(res, controller.getDateExpires(),
                                        m_clientCacheMaxAge);
                            }
                        }
                        // set response status to "200 - OK" (required for static export "on-demand")
                        res.setStatus(HttpServletResponse.SC_OK);
                    } else {
                        // set previously saved error code
                        res.setStatus(errorCode.intValue());
                    }
                    // process the headers
                    CmsFlexResponse.processHeaders(f_res.getHeaders(), res);
                    res.getOutputStream().write(result);
                    res.getOutputStream().flush();
                }
            }
        } catch (IllegalStateException e) {
            // uncritical, might happen if JSP error page was used
            LOG.debug(Messages.get().getBundle().key(Messages.LOG_IGNORING_EXC_1, e.getClass().getName()), e);
        } catch (SocketException e) {
            // uncritical, might happen if client (browser) does not wait until end of page delivery
            LOG.debug(Messages.get().getBundle().key(Messages.LOG_IGNORING_EXC_1, e.getClass().getName()), e);
        }
    }

    return result;
}

From source file:org.apache.ranger.rest.TagREST.java

@GET
@Path(TagRESTConstants.TAGS_DOWNLOAD + "{serviceName}")
@Produces({ "application/json", "application/xml" })
public ServiceTags getServiceTagsIfUpdated(@PathParam("serviceName") String serviceName,
        @QueryParam(TagRESTConstants.LAST_KNOWN_TAG_VERSION_PARAM) Long lastKnownVersion,
        @DefaultValue("0") @QueryParam(TagRESTConstants.LAST_ACTIVATION_TIME) Long lastActivationTime,
        @QueryParam("pluginId") String pluginId, @Context HttpServletRequest request) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> TagREST.getServiceTagsIfUpdated(" + serviceName + ", " + lastKnownVersion + ", "
                + lastActivationTime + ", " + pluginId + ")");
    }//from ww  w  . j  a  v a2 s. c o  m

    ServiceTags ret = null;
    int httpCode = HttpServletResponse.SC_OK;
    String logMsg = null;

    try {
        ret = tagStore.getServiceTagsIfUpdated(serviceName, lastKnownVersion);
        Long downloadedVersion;

        if (ret == null) {
            downloadedVersion = lastKnownVersion;
            httpCode = HttpServletResponse.SC_NOT_MODIFIED;
            logMsg = "No change since last update";
        } else {
            downloadedVersion = ret.getTagVersion();
            httpCode = HttpServletResponse.SC_OK;
            logMsg = "Returning " + (ret.getTags() != null ? ret.getTags().size() : 0) + " tags. Tag version="
                    + ret.getTagVersion();
        }
        assetMgr.createPluginInfo(serviceName, pluginId, request, RangerPluginInfo.ENTITY_TYPE_TAGS,
                downloadedVersion, lastKnownVersion, lastActivationTime, httpCode);
    } catch (Exception excp) {
        LOG.error("getServiceTagsIfUpdated(" + serviceName + ") failed", excp);

        httpCode = HttpServletResponse.SC_BAD_REQUEST;
        logMsg = excp.getMessage();
    }

    if (httpCode != HttpServletResponse.SC_OK) {
        boolean logError = httpCode != HttpServletResponse.SC_NOT_MODIFIED;
        throw restErrorUtil.createRESTException(httpCode, logMsg, logError);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== TagREST.getServiceTagsIfUpdated(" + serviceName + ", " + lastKnownVersion + ", "
                + lastActivationTime + ", " + pluginId + ")");
    }

    return ret;
}

From source file:org.apache.ranger.rest.TagREST.java

@GET
@Path(TagRESTConstants.TAGS_SECURE_DOWNLOAD + "{serviceName}")
@Produces({ "application/json", "application/xml" })
public ServiceTags getSecureServiceTagsIfUpdated(@PathParam("serviceName") String serviceName,
        @QueryParam(TagRESTConstants.LAST_KNOWN_TAG_VERSION_PARAM) Long lastKnownVersion,
        @DefaultValue("0") @QueryParam(TagRESTConstants.LAST_ACTIVATION_TIME) Long lastActivationTime,
        @QueryParam("pluginId") String pluginId, @Context HttpServletRequest request) {

    if (LOG.isDebugEnabled()) {
        LOG.debug("==> TagREST.getSecureServiceTagsIfUpdated(" + serviceName + ", " + lastKnownVersion + ", "
                + lastActivationTime + ", " + pluginId + ")");
    }//from  w w  w. j  av a  2s .  c  om

    ServiceTags ret = null;
    int httpCode = HttpServletResponse.SC_OK;
    String logMsg = null;
    boolean isAllowed = false;
    boolean isAdmin = bizUtil.isAdmin();
    boolean isKeyAdmin = bizUtil.isKeyAdmin();

    try {
        XXService xService = daoManager.getXXService().findByName(serviceName);
        XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(xService.getType());
        RangerService rangerService = svcStore.getServiceByName(serviceName);

        if (StringUtils.equals(xServiceDef.getImplclassname(), EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME)) {
            if (isKeyAdmin) {
                isAllowed = true;
            } else {
                isAllowed = bizUtil.isUserAllowed(rangerService, Allowed_User_List_For_Tag_Download);
            }
        } else {
            if (isAdmin) {
                isAllowed = true;
            } else {
                isAllowed = bizUtil.isUserAllowed(rangerService, Allowed_User_List_For_Tag_Download);
            }
        }
        if (isAllowed) {
            ret = tagStore.getServiceTagsIfUpdated(serviceName, lastKnownVersion);
            Long downloadedVersion;

            if (ret == null) {
                downloadedVersion = lastKnownVersion;
                httpCode = HttpServletResponse.SC_NOT_MODIFIED;
                logMsg = "No change since last update";
            } else {
                downloadedVersion = ret.getTagVersion();
                httpCode = HttpServletResponse.SC_OK;
                logMsg = "Returning " + (ret.getTags() != null ? ret.getTags().size() : 0)
                        + " tags. Tag version=" + ret.getTagVersion();
            }
            assetMgr.createPluginInfo(serviceName, pluginId, request, RangerPluginInfo.ENTITY_TYPE_TAGS,
                    downloadedVersion, lastKnownVersion, lastActivationTime, httpCode);
        } else {
            LOG.error("getSecureServiceTagsIfUpdated(" + serviceName + ", " + lastKnownVersion + ", "
                    + lastActivationTime + ") failed as User doesn't have permission to download tags");
            httpCode = HttpServletResponse.SC_UNAUTHORIZED;
            logMsg = "User doesn't have permission to download tags";
        }
    } catch (Exception excp) {
        LOG.error("getSecureServiceTagsIfUpdated(" + serviceName + ") failed", excp);

        httpCode = HttpServletResponse.SC_BAD_REQUEST;
        logMsg = excp.getMessage();
    } finally {
        // Placeholder to avoid PMD violations
        if (LOG.isDebugEnabled()) {
            LOG.debug("httpCode=" + httpCode);
        }
        // createOrUpdatePluginTagVersion(serviceName, lastKnownVersion, pluginId, lastActivationTime);
    }

    if (httpCode != HttpServletResponse.SC_OK) {
        boolean logError = httpCode != HttpServletResponse.SC_NOT_MODIFIED;
        throw restErrorUtil.createRESTException(httpCode, logMsg, logError);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== TagREST.getSecureServiceTagsIfUpdated(" + serviceName + ", " + lastKnownVersion + ", "
                + lastActivationTime + ", " + pluginId + ")");
    }

    return ret;
}

From source file:org.structr.web.servlet.HtmlServlet.java

private static boolean notModifiedSince(final HttpServletRequest request, HttpServletResponse response,
        final AbstractNode node, final boolean dontCache) {

    boolean notModified = false;
    final Date lastModified = node.getLastModifiedDate();

    // add some caching directives to header
    // see http://weblogs.java.net/blog/2007/08/08/expires-http-header-magic-number-yslow
    final DateFormat httpDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    httpDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

    response.setHeader("Date", httpDateFormat.format(new Date()));

    final Calendar cal = new GregorianCalendar();
    final Integer seconds = node.getProperty(Page.cacheForSeconds);

    if (!dontCache && seconds != null) {

        cal.add(Calendar.SECOND, seconds);
        response.setHeader("Cache-Control", "max-age=" + seconds + ", s-maxage=" + seconds + "");
        response.setHeader("Expires", httpDateFormat.format(cal.getTime()));

    } else {/* w w  w . j a  v  a 2 s  .  c om*/

        if (!dontCache) {
            response.setHeader("Cache-Control", "no-cache, must-revalidate, proxy-revalidate");
        } else {
            response.setHeader("Cache-Control",
                    "private, no-cache, no-store, max-age=0, s-maxage=0, must-revalidate, proxy-revalidate");
        }

    }

    if (lastModified != null) {

        final Date roundedLastModified = DateUtils.round(lastModified, Calendar.SECOND);
        response.setHeader("Last-Modified", httpDateFormat.format(roundedLastModified));

        final String ifModifiedSince = request.getHeader("If-Modified-Since");

        if (StringUtils.isNotBlank(ifModifiedSince)) {

            try {

                Date ifModSince = httpDateFormat.parse(ifModifiedSince);

                // Note that ifModSince has not ms resolution, so the last digits are always 000
                // That requires the lastModified to be rounded to seconds
                if ((ifModSince != null)
                        && (roundedLastModified.equals(ifModSince) || roundedLastModified.before(ifModSince))) {

                    notModified = true;

                    response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    response.setHeader("Vary", "Accept-Encoding");

                }

            } catch (ParseException ex) {
                logger.log(Level.WARNING, "Could not parse If-Modified-Since header", ex);
            }

        }

    }

    return notModified;
}

From source file:org.jahia.bin.Render.java

public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    if (isDisabled()) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }/*from www .j a va  2  s  .c om*/
    String method = req.getMethod();
    if (req.getParameter(METHOD_TO_CALL) != null) {
        method = req.getParameter(METHOD_TO_CALL).toUpperCase();
    }
    if (!isMethodAllowed(method)) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return null;
    }
    long startTime = System.currentTimeMillis();
    String sessionId = null;
    try {
        final HttpSession session = req.getSession();
        if (logger.isInfoEnabled()) {
            sessionId = session.getId();
        }
        URLResolver urlResolver = urlResolverFactory.createURLResolver(req.getPathInfo(), req.getServerName(),
                workspace, req);

        req.setAttribute("urlResolver", urlResolver);

        session.setAttribute("workspace", urlResolver.getWorkspace());

        if (sessionExpiryTime != null && session.getMaxInactiveInterval() != sessionExpiryTime * 60) {
            session.setMaxInactiveInterval(sessionExpiryTime * 60);
        }

        RenderContext renderContext = createRenderContext(req, resp, jcrSessionFactory.getCurrentUser());
        renderContext.setWorkspace(urlResolver.getWorkspace());

        urlResolver.setRenderContext(renderContext);
        req.getSession().setAttribute(Constants.SESSION_LOCALE, urlResolver.getLocale());
        jcrSessionFactory.setCurrentLocale(urlResolver.getLocale());
        if (renderContext.isPreviewMode() && req.getParameter(ALIAS_USER) != null
                && !JahiaUserManagerService.isGuest(jcrSessionFactory.getCurrentUser())) {
            JahiaUserManagerService userManagerService = ServicesRegistry.getInstance()
                    .getJahiaUserManagerService();
            JCRUserNode userNode = userManagerService.lookupUser(req.getParameter(ALIAS_USER),
                    urlResolver.getSiteKey());
            if (userNode != null) {
                jcrSessionFactory.setCurrentAliasedUser(userNode.getJahiaUser());
            }
        }

        // check permission
        try {
            if (!hasAccess(urlResolver.getNode())) {
                if (JahiaUserManagerService.isGuest(jcrSessionFactory.getCurrentUser())) {
                    throw new JahiaUnauthorizedException();
                } else {
                    throw new JahiaForbiddenAccessException();
                }
            }
        } catch (PathNotFoundException e) {

        }

        renderContext.setSiteInfo(urlResolver.getSiteInfo());

        if (renderContext.isPreviewMode() && req.getParameter(PREVIEW_DATE) != null
                && !JahiaUserManagerService.isGuest(jcrSessionFactory.getCurrentUser())) {
            Calendar previewDate = Calendar.getInstance();
            previewDate.setTime(new Date(new Long(req.getParameter(PREVIEW_DATE))));
            jcrSessionFactory.setCurrentPreviewDate(previewDate);
        }
        if (method.equals(METHOD_GET)) {
            Resource resource;
            resource = urlResolver.getResource();
            if (!StringUtils.isEmpty(urlResolver.getRedirectUrl())
                    && (StringUtils.isEmpty(resource.getTemplate())
                            || StringUtils.equals(resource.getTemplate(), "default"))) {
                Map<String, List<String>> parameters = new HashMap<String, List<String>>();
                parameters.put(NEW_NODE_OUTPUT_FORMAT, LIST_WITH_EMPTY_STRING);
                parameters.put(REDIRECT_HTTP_RESPONSE_CODE, REDIRECT_CODE_MOVED_PERMANENTLY);

                performRedirect(urlResolver.getRedirectUrl(),
                        StringUtils.isEmpty(urlResolver.getVanityUrl())
                                ? "/" + urlResolver.getLocale().toString() + urlResolver.getPath()
                                : urlResolver.getVanityUrl(),
                        req, resp, parameters, false);
            } else {
                renderContext.setMainResource(resource);
                if (renderContext.getSite() == null) {
                    // If Site has not been resolved by the servlet (so far only dashboard mode is doing that
                    JCRSiteNode site = resource.getNode().getResolveSite();
                    if (!Url.isLocalhost(req.getServerName()) && !renderContext.isEditMode()) {
                        JCRSessionWrapper session1 = resource.getNode().getSession();
                        if (urlResolver.getSiteKey() != null
                                && (site == null || !site.getSiteKey().equals(urlResolver.getSiteKey()))) {
                            site = (JCRSiteNode) session1.getNode("/sites/" + urlResolver.getSiteKey());
                        } else if (renderContext.isLiveMode() && urlResolver.getSiteKeyByServerName() != null
                                && (site == null
                                        || !site.getSiteKey().equals(urlResolver.getSiteKeyByServerName()))) {
                            site = (JCRSiteNode) session1
                                    .getNode("/sites/" + urlResolver.getSiteKeyByServerName());
                        }
                    }
                    String jsite = null;
                    HttpServletRequest request = renderContext.getRequest();
                    if (request != null) {
                        jsite = request.getParameter("jsite");
                    }
                    if (jsite == null && renderContext.getMainResource() != null) {
                        jsite = (String) renderContext.getMainResource().getModuleParams().get("jsite");
                    }
                    if (jsite != null) {
                        try {
                            site = (JCRSiteNode) resource.getNode().getSession().getNodeByIdentifier(jsite);
                        } catch (ItemNotFoundException e) {
                            if (JahiaUserManagerService.isGuest(jcrSessionFactory.getCurrentUser())) {
                                throw new JahiaUnauthorizedException();
                            } else {
                                throw new JahiaForbiddenAccessException();
                            }
                        }
                    }
                    if (resource.getNode().getPath().startsWith("/sites/") && (site == null || (!site.getPath()
                            .startsWith("/modules/")
                            && !site.isAllowsUnlistedLanguages()
                            && !(renderContext.isLiveMode()
                                    ? site.getActiveLiveLanguagesAsLocales().contains(urlResolver.getLocale())
                                    : site.getLanguagesAsLocales().contains(urlResolver.getLocale()))))) {
                        throw new PathNotFoundException("This language does not exist on this site");
                    }
                    renderContext.setSite(site);
                }
                //                    resource.pushWrapper("wrapper.fullpage");

                if (urlResolver.getPath().endsWith(".do")) {
                    Action action = templateService.getActions().get(resource.getResolvedTemplate());
                    Map<String, List<String>> parameters = toParameterMapOfListOfString(req);
                    if (action != null) {
                        doAction(req, resp, urlResolver, renderContext, resource, action, parameters);
                    } else {
                        logger.error("Action {} does not exist", resource.getResolvedTemplate());
                        throw new PathNotFoundException("Action does not exist");
                    }
                } else {
                    long lastModified = getLastModified(resource, renderContext);

                    if (lastModified == -1) {
                        // servlet doesn't support if-modified-since, no reason
                        // to go through further expensive logic
                        doGet(req, resp, renderContext, resource, startTime);
                    } else {
                        long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
                        if (ifModifiedSince < (lastModified / 1000 * 1000)) {
                            // If the servlet mod time is later, call doGet()
                            // Round down to the nearest second for a proper compare
                            // A ifModifiedSince of -1 will always be less
                            maybeSetLastModified(resp, lastModified);
                            doGet(req, resp, renderContext, resource, startTime);
                        } else {
                            resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                        }
                    }
                }
            }
        } else if (method.equals(METHOD_HEAD)) {
            doHead(req, resp);

        } else if (method.equals(METHOD_POST)) {
            doPost(req, resp, renderContext, urlResolver);

        } else if (method.equals(METHOD_PUT)) {
            doPut(req, resp, renderContext, urlResolver);

        } else if (method.equals(METHOD_DELETE)) {
            doDelete(req, resp, renderContext, urlResolver);

        } else if (method.equals(METHOD_OPTIONS)) {
            doOptions(req, resp);

        } else if (method.equals(METHOD_TRACE)) {
            doTrace(req, resp);

        } else {
            //
            // Note that this means NO servlet supports whatever
            // method was requested, anywhere on this server.
            //
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }
    } catch (Exception e) {
        List<ErrorHandler> handlers = templateService.getErrorHandler();
        for (ErrorHandler handler : handlers) {
            if (handler.handle(e, req, resp)) {
                return null;
            }
        }
        DefaultErrorHandler.getInstance().handle(e, req, resp);
    } finally {
        if (logger.isInfoEnabled()) {
            StringBuilder sb = new StringBuilder(100);
            sb.append("Rendered [").append(req.getRequestURI());
            if (jcrSessionFactory.getCurrentUser() != null) {
                sb.append("] user=[").append(jcrSessionFactory.getCurrentUser().getUsername());
            }
            sb.append("] ip=[").append(req.getRemoteAddr()).append("] sessionID=[").append(sessionId)
                    .append("] in [").append(System.currentTimeMillis() - startTime).append("ms]");
            logger.info(sb.toString());
        }
    }
    return null;
}