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:org.auraframework.impl.adapter.ServletUtilAdapterImpl.java

/**
 * check the top level component/app and get dependencies.
 *
 * This routine checks to see that we have a valid top level component. If our top level component is out of sync,
 * we have to ignore it here, but we _must_ force the client to not cache the response.
 *
 * If there is a QFE, we substitute the QFE descriptor for the one given us, and continue. Again, we cannot allow
 * caching.//from   w  ww  .  j  av a2 s .  co m
 *
 * Finally, if there is no descriptor given, we simply ignore the request and give them an empty response. Which is
 * done here by returning null.
 *
 * Also note that this handles the 'if-modified-since' header, as we want to tell the browser that nothing changed
 * in that case.
 *
 * @param request the request (for exception handling)
 * @param response the response (for exception handling)
 * @param context the context to get the definition.
 * @return the set of descriptors we are sending back, or null in the case that we handled the response.
 * @throws IOException if there was an IO exception handling a client out of sync exception
 * @throws ServletException if there was a problem handling the out of sync
 */
@Override
public Set<DefDescriptor<?>> verifyTopLevel(HttpServletRequest request, HttpServletResponse response,
        AuraContext context) throws IOException {
    DefDescriptor<? extends BaseComponentDef> appDesc = context.getApplicationDescriptor();
    MasterDefRegistry mdr = context.getDefRegistry();

    context.setPreloading(true);
    if (appDesc == null) {
        //
        // This means we have nothing to say to the client, so the response is
        // left completely empty.
        //
        return null;
    }
    long ifModifiedSince = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE);
    String uid = context.getUid(appDesc);
    try {
        try {
            definitionService.updateLoaded(appDesc);
            if (uid != null && ifModifiedSince != -1) {
                //
                // In this case, we have an unmodified descriptor, so just tell
                // the client that.
                //
                response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
                return null;
            }
        } catch (ClientOutOfSyncException coose) {
            //
            // We can't actually handle an out of sync here, since we are doing a
            // resource load. We have to ignore it, and continue as if nothing happened.
            // But in the process, we make sure to set 'no-cache' so that the result
            // is thrown away. This may actually not give the right result in bizarre
            // corner cases... beware cache inconsistencies on revert after a QFE.
            //
            // We actually probably should do something different, like send a minimalist
            // set of stuff to make the client re-try.
            //
            this.setNoCache(response);
            String oosUid = mdr.getUid(null, appDesc);
            return mdr.getDependencies(oosUid);
        }
    } catch (QuickFixException qfe) {
        //
        // A quickfix exception means that we couldn't compile something.
        // In this case, we still want to preload things, but we want to preload
        // quick fix values, note that we force NoCache here.
        //
        this.setNoCache(response);
        this.handleServletException(qfe, true, context, request, response, true);
        return null;
    }
    this.setLongCache(response);
    if (uid == null) {
        uid = context.getUid(appDesc);
    }
    return mdr.getDependencies(uid);
}

From source file:it.geosolutions.httpproxy.HTTPProxy.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response back to the client via the given {@link HttpServletResponse}
 * /*from w  w  w.j  av  a  2s . c om*/
 * @param httpMethodProxyRequest An object representing the proxy request to be made
 * @param httpServletResponse An object by which we can send the proxied response back to the client
 * @param digest
 * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException Can be thrown to indicate that another error has occurred
 */
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse, String user, String password, ProxyInfo proxyInfo)
        throws IOException, ServletException {

    if (user != null && password != null) {
        UsernamePasswordCredentials upc = new UsernamePasswordCredentials(user, password);
        httpClient.getState().setCredentials(AuthScope.ANY, upc);
    }

    httpMethodProxyRequest.setFollowRedirects(false);

    InputStream inputStreamServerResponse = null;
    ByteArrayOutputStream baos = null;

    try {

        // //////////////////////////
        // Execute the request
        // //////////////////////////

        int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);

        onRemoteResponse(httpMethodProxyRequest);

        // ////////////////////////////////////////////////////////////////////////////////
        // Check if the proxy response is a redirect
        // The following code is adapted from
        // org.tigris.noodle.filters.CheckForRedirect
        // Hooray for open source software
        // ////////////////////////////////////////////////////////////////////////////////

        if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
                && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {

            String stringStatusCode = Integer.toString(intProxyResponseCode);
            String stringLocation = httpMethodProxyRequest.getResponseHeader(Utils.LOCATION_HEADER).getValue();

            if (stringLocation == null) {
                throw new ServletException("Recieved status code: " + stringStatusCode + " but no "
                        + Utils.LOCATION_HEADER + " header was found in the response");
            }

            // /////////////////////////////////////////////
            // Modify the redirect to go to this proxy
            // servlet rather that the proxied host
            // /////////////////////////////////////////////

            String stringMyHostName = httpServletRequest.getServerName();

            if (httpServletRequest.getServerPort() != 80) {
                stringMyHostName += ":" + httpServletRequest.getServerPort();
            }

            stringMyHostName += httpServletRequest.getContextPath();
            httpServletResponse.sendRedirect(stringLocation.replace(
                    Utils.getProxyHostAndPort(proxyInfo) + proxyInfo.getProxyPath(), stringMyHostName));

            return;

        } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {

            // ///////////////////////////////////////////////////////////////
            // 304 needs special handling. See:
            // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
            // We get a 304 whenever passed an 'If-Modified-Since'
            // header and the data on disk has not changed; server
            // responds w/ a 304 saying I'm not going to send the
            // body because the file has not changed.
            // ///////////////////////////////////////////////////////////////

            httpServletResponse.setIntHeader(Utils.CONTENT_LENGTH_HEADER_NAME, 0);
            httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);

            return;
        }

        // /////////////////////////////////////////////
        // 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) {

            // /////////////////////////
            // Skip GZIP Responses
            // /////////////////////////

            if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_ACCEPT_ENCODING)
                    && header.getValue().toLowerCase().contains("gzip"))
                continue;
            else if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_CONTENT_ENCODING)
                    && header.getValue().toLowerCase().contains("gzip"))
                continue;
            else if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_TRANSFER_ENCODING))
                continue;
            //                else if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_WWW_AUTHENTICATE))
            //                    continue;                
            else
                httpServletResponse.setHeader(header.getName(), header.getValue());
        }

        // ///////////////////////////////////
        // Send the content to the client
        // ///////////////////////////////////

        inputStreamServerResponse = httpMethodProxyRequest.getResponseBodyAsStream();

        if (inputStreamServerResponse != null) {
            byte[] b = new byte[proxyConfig.getDefaultStreamByteSize()];

            baos = new ByteArrayOutputStream(b.length);

            int read = 0;
            while ((read = inputStreamServerResponse.read(b)) > 0) {
                baos.write(b, 0, read);
                baos.flush();
            }

            baos.writeTo(httpServletResponse.getOutputStream());
        }

    } catch (HttpException e) {
        if (LOGGER.isLoggable(Level.SEVERE))
            LOGGER.log(Level.SEVERE, "Error executing HTTP method ", e);
    } finally {
        try {
            if (inputStreamServerResponse != null)
                inputStreamServerResponse.close();
        } catch (IOException e) {
            if (LOGGER.isLoggable(Level.SEVERE))
                LOGGER.log(Level.SEVERE, "Error closing request input stream ", e);
            throw new ServletException(e.getMessage());
        }

        try {
            if (baos != null) {
                baos.flush();
                baos.close();
            }
        } catch (IOException e) {
            if (LOGGER.isLoggable(Level.SEVERE))
                LOGGER.log(Level.SEVERE, "Error closing response stream ", e);
            throw new ServletException(e.getMessage());
        }

        httpMethodProxyRequest.releaseConnection();
    }
}

From source file:com.ibm.sbt.service.basic.ProxyService.java

public void prepareResponse(HttpRequestBase method, HttpServletRequest request, HttpServletResponse response,
        HttpResponse clientResponse, boolean isCopy) throws ServletException {
    Object timedObject = ProxyProfiler.getTimedObject();
    try {/* www.  j  a v a  2 s. co m*/
        int statusCode = clientResponse.getStatusLine().getStatusCode();
        if (statusCode == 401 || statusCode == 403) {
            clientResponse.setHeader("WWW-Authenticate", "");
        }
        response.setStatus(statusCode);
        if (getDebugHook() != null) {
            getDebugHook().getDumpResponse().setStatus(statusCode);
        }

        // Passed back all heads, but process cookies differently.
        Header[] headers = clientResponse.getAllHeaders();
        for (Header header : headers) {
            String headername = header.getName();

            if (headername.equalsIgnoreCase("Set-Cookie")) { // $NON-NLS-1$
                if (forwardCookies(method, request)) {
                    // If cookie, have to rewrite domain/path for browser.
                    String setcookieval = header.getValue();

                    if (setcookieval != null) {
                        String thisserver = request.getServerName();

                        String thisdomain;
                        if (thisserver.indexOf('.') == -1) {
                            thisdomain = "";
                        } else {
                            thisdomain = thisserver.substring(thisserver.indexOf('.'));
                        }
                        String domain = null;

                        // path info = /protocol/server/path-on-server
                        //Matcher m = cookiePathPattern.matcher(request.getPathInfo());
                        String thispath = request.getContextPath() + request.getServletPath();
                        String path = null;

                        String[][] cookparams = getCookieStrings(setcookieval);

                        for (int j = 1; j < cookparams.length; j++) {
                            if ("domain".equalsIgnoreCase(cookparams[j][0])) { // $NON-NLS-1$
                                domain = cookparams[j][1];
                                cookparams[j][1] = null;
                            } else if ("path".equalsIgnoreCase(cookparams[j][0])) { // $NON-NLS-1$
                                path = cookparams[j][1];
                                cookparams[j][1] = null;
                            }
                        }

                        if (domain == null) {
                            domain = method.getURI().getHost();
                        }

                        // Set cookie name
                        String encoded = encodeCookieNameAndPath(cookparams[0][0], path, domain);
                        if (encoded != null) {
                            String newcookiename = PASSTHRUID + encoded;

                            StringBuilder newset = new StringBuilder(newcookiename);
                            newset.append('=');
                            newset.append(cookparams[0][1]);

                            for (int j = 1; j < cookparams.length; j++) {
                                String settingname = cookparams[j][0];
                                String settingvalue = cookparams[j][1];
                                if (settingvalue != null) {
                                    newset.append("; ").append(settingname); // $NON-NLS-1$
                                    newset.append('=').append(settingvalue); // $NON-NLS-1$
                                }
                            }

                            newset.append("; domain=").append(thisdomain); // $NON-NLS-1$
                            newset.append("; path=").append(thispath); // $NON-NLS-1$

                            String newsetcookieval = newset.toString();
                            // this implementation of HttpServletRequest seems to have issues... setHeader works as I would
                            // expect addHeader to.
                            response.setHeader(headername, newsetcookieval);
                            if (getDebugHook() != null) {
                                getDebugHook().getDumpResponse().addCookie(headername, newsetcookieval);
                            }
                        }
                    }
                }
            } else if (!headername.equalsIgnoreCase("Transfer-Encoding")) { // $NON-NLS-1$
                String headerval = header.getValue();

                if (headername.equalsIgnoreCase("content-type")) {
                    int loc = headerval.indexOf(';');
                    String type;
                    if (loc > 0) {
                        type = headerval.substring(0, loc).trim();
                    } else {
                        type = headerval;
                    }
                    if (!isMimeTypeAllowed(type)) {
                        isCopy = false;
                        break;
                    } else {
                        response.setHeader(headername, headerval);
                        if (getDebugHook() != null) {
                            getDebugHook().getDumpResponse().addHeader(headername, headerval);
                        }
                    }
                } else if ((statusCode == 401 || statusCode == 403)
                        && headername.equalsIgnoreCase("WWW-Authenticate")) { // $NON-NLS-1$
                    if (headerval.indexOf("Basic") != -1) { // $NON-NLS-1$
                        String pathInfo = request.getPathInfo();
                        String[] pathParts = (pathInfo.startsWith("/") ? pathInfo.substring(1) : pathInfo)
                                .split("/");
                        if (pathParts.length > 1) {
                            StringBuilder strb = new StringBuilder("Basic realm=\""); // $NON-NLS-1$
                            strb.append(request.getContextPath());
                            strb.append(request.getServletPath());
                            strb.append('/');
                            strb.append(pathParts[0]);
                            strb.append('/');
                            strb.append(pathParts[1]);
                            strb.append('"');
                            headerval = strb.toString();
                            response.setHeader(headername, headerval);
                            if (getDebugHook() != null) {
                                getDebugHook().getDumpResponse().addHeader(headername, headerval);
                            }
                        }
                    }
                } else {
                    response.setHeader(headername, headerval);
                    if (getDebugHook() != null) {
                        getDebugHook().getDumpResponse().addHeader(headername, headerval);
                    }
                }
            }
        }

        // Need to move response body over too
        if (statusCode == HttpServletResponse.SC_NO_CONTENT
                || statusCode == HttpServletResponse.SC_NOT_MODIFIED) {
            response.setHeader("Content-Length", "0");
            if (getDebugHook() != null) {
                getDebugHook().getDumpResponse().addHeader("Content-Length", "0");
            }
        } else if (isCopy) {
            HttpEntity entity = clientResponse.getEntity();
            InputStream inStream = entity.getContent();
            if (inStream != null) {
                OutputStream os = response.getOutputStream();
                if (TRACE) {
                    OutputStream tos = new TraceOutputStream(os, System.out, false);
                    os = tos;
                }
                StreamUtil.copyStream(inStream, os);
                os.flush();
            } else {
                response.setHeader("Content-Length", "0");
                if (getDebugHook() != null) {
                    getDebugHook().getDumpResponse().addHeader("Content-Length", "0");
                }
            }
        }
    } catch (IOException ex) {
        throw new ServletException(ex);
    }
    ProxyProfiler.profileTimedRequest(timedObject, "prepareResponse");
}

From source file:org.apache.ranger.biz.AssetMgr.java

private void createOrUpdatePluginInfo(final RangerPluginInfo pluginInfo, final int httpCode) {
    if (logger.isDebugEnabled()) {
        logger.debug("==> createOrUpdatePluginInfo(pluginInfo=" + pluginInfo + ", httpCode=" + httpCode + ")");
    }//from w ww .  j ava2 s  . c o  m

    if (httpCode == HttpServletResponse.SC_NOT_MODIFIED) {
        // Create or update PluginInfo record after transaction is completed. If it is created in-line here
        // then the TransactionManager will roll-back the changes because the HTTP return code is
        // HttpServletResponse.SC_NOT_MODIFIED
        Runnable commitWork = new Runnable() {
            @Override
            public void run() {
                doCreateOrUpdateXXPluginInfo(pluginInfo);
            }
        };
        activityLogger.commitAfterTransactionComplete(commitWork);
    } else {
        doCreateOrUpdateXXPluginInfo(pluginInfo);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("<== createOrUpdatePluginInfo(pluginInfo=" + pluginInfo + ", httpCode=" + httpCode + ")");
    }

}

From source file:ch.entwine.weblounge.cache.impl.CacheServiceImpl.java

/**
 * Writes the cache element to the response, setting the cache headers
 * according to the settings found on the element.
 * //from w  ww .  j a va2 s .co  m
 * @param element
 *          the cache contents
 * @param handle
 *          the cache handle
 * @param request
 *          the request
 * @param response
 *          the response
 * @throws IOException
 *           if writing the cache contents to the response fails
 */
private void writeCacheEntry(Element element, CacheHandle handle, WebloungeRequest request,
        WebloungeResponse response) throws IOException {
    CacheEntry entry = (CacheEntry) element.getValue();

    // Check what the client has available locally
    String eTag = request.getHeader(HEADER_IF_NONE_MATCH);
    long clientCacheDate = 0;
    try {
        clientCacheDate = request.getDateHeader(HEADER_IF_MODIFIED_SINCE);
    } catch (IllegalArgumentException e) {
        logger.debug("The client provided a malformed '{}' date header: '{}'", HEADER_IF_MODIFIED_SINCE,
                request.getHeader(HEADER_IF_MODIFIED_SINCE));
    }

    // Do we have a more recent version?
    boolean isModified = !entry.notModified(clientCacheDate) && !entry.matches(eTag);

    // Write the response headers
    if (isModified) {
        entry.getHeaders().apply(response);
        writeContentHeaders(response, entry);
    }

    writeCacheHeaders(response, entry, isModified);

    // Add the X-Cache-Key header
    if (debug || request.getHeader(CACHE_DEBUG_HEADER) != null) {
        StringBuffer cacheKeyHeader = new StringBuffer(name);
        cacheKeyHeader.append(" (").append(handle.getKey()).append(")");
        response.addHeader(CACHE_KEY_HEADER, cacheKeyHeader.toString());
    }

    // Check the headers first. Maybe we don't need to send anything but
    // a not-modified back
    if (isModified) {
        response.getOutputStream().write(entry.getContent());
    } else {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
    }

    response.flushBuffer();
}

From source file:org.apereo.portal.portlet.rendering.PortletRendererImpl.java

protected long doResourceReplayBrowserContent(IPortletWindow portletWindow,
        HttpServletRequest httpServletRequest, CacheState<CachedPortletResourceData<Long>, Long> cacheState,
        PortletResourceOutputHandler portletOutputHandler) {

    enforceConfigPermission(httpServletRequest, portletWindow);

    logger.debug("Sending 304 for resource request to {}", portletWindow);

    if (portletOutputHandler.isCommitted()) {
        throw new IllegalStateException("Attempting to send 304 but response is already committed");
    }/*from  ww  w. j  ava  2  s. c  o  m*/

    final long start = System.nanoTime();

    portletOutputHandler.setStatus(HttpServletResponse.SC_NOT_MODIFIED);

    final CachedPortletResourceData<Long> cachedPortletResourceData = cacheState.getCachedPortletData();
    if (cachedPortletResourceData != null) {
        //Freshen up the various caching related headers
        final CachedPortletData<Long> cachedPortletData = cachedPortletResourceData.getCachedPortletData();
        PortletCachingHeaderUtils.setCachingHeaders(cachedPortletData, portletOutputHandler);
    }

    final long executionTime = System.nanoTime() - start;

    publishResourceEvent(portletWindow, httpServletRequest, executionTime, true, false);

    return executionTime;
}

From source file:org.jasig.portal.portlet.rendering.PortletRendererImpl.java

protected long doResourceReplayBrowserContent(IPortletWindow portletWindow,
        HttpServletRequest httpServletRequest, CacheState<CachedPortletResourceData<Long>, Long> cacheState,
        PortletResourceOutputHandler portletOutputHandler) {

    if (logger.isDebugEnabled()) {
        logger.debug("Sending 304 for resource request to " + portletWindow);
    }/* ww  w.j av a 2  s.  c om*/

    if (portletOutputHandler.isCommitted()) {
        throw new IllegalStateException("Attempting to send 304 but response is already committed");
    }

    final long start = System.nanoTime();

    portletOutputHandler.setStatus(HttpServletResponse.SC_NOT_MODIFIED);

    final CachedPortletResourceData<Long> cachedPortletResourceData = cacheState.getCachedPortletData();
    if (cachedPortletResourceData != null) {
        //Freshen up the various caching related headers
        final CachedPortletData<Long> cachedPortletData = cachedPortletResourceData.getCachedPortletData();
        PortletCachingHeaderUtils.setCachingHeaders(cachedPortletData, portletOutputHandler);
    }

    final long executionTime = System.nanoTime() - start;

    publishResourceEvent(portletWindow, httpServletRequest, executionTime, true, false);

    return executionTime;
}

From source file:org.opencms.staticexport.CmsAfterPublishStaticExportHandler.java

/**
 * Exports all template resources found in a list of published resources.<p>
 * /* ww  w. ja v a 2 s  .  c  o  m*/
 * @param cms the cms context, in the root site as Export user
 * @param publishedTemplateResources list of potential candidates to export
 * @param report an I_CmsReport instance to print output message, or null to write messages to the log file    
 */
protected void exportTemplateResources(CmsObject cms, List<String> publishedTemplateResources,
        I_CmsReport report) {

    CmsStaticExportManager manager = OpenCms.getStaticExportManager();
    int size = publishedTemplateResources.size();
    int count = 1;

    if (LOG.isDebugEnabled()) {
        LOG.debug(Messages.get().getBundle().key(Messages.LOG_EXPORT_TEMPLATES_1, new Integer(size)));
    }
    report.println(Messages.get().container(Messages.RPT_STATICEXPORT_TEMPLATE_RESOURCES_BEGIN_0),
            I_CmsReport.FORMAT_HEADLINE);

    StringBuffer cookies = new StringBuffer();
    // now loop through all of them and request them from the server
    Iterator<String> i = publishedTemplateResources.iterator();
    while (i.hasNext()) {
        String rfsName = i.next();
        CmsStaticExportData data = null;
        try {
            data = manager.getVfsNameInternal(cms, rfsName);
        } catch (CmsVfsResourceNotFoundException e) {
            String rfsBaseName = rfsName;
            int pos = rfsName.lastIndexOf('_');
            if (pos >= 0) {
                rfsBaseName = rfsName.substring(0, pos);
            }
            try {
                data = manager.getVfsNameInternal(cms, rfsBaseName);
            } catch (CmsVfsResourceNotFoundException e2) {
                if (LOG.isInfoEnabled()) {
                    LOG.info(Messages.get().getBundle().key(Messages.LOG_NO_INTERNAL_VFS_RESOURCE_FOUND_1,
                            new String[] { rfsName }));
                }
            }
        }
        if (data != null) {
            data.setRfsName(rfsName);
            report.print(
                    org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_SUCCESSION_2,
                            new Integer(count++), new Integer(size)),
                    I_CmsReport.FORMAT_NOTE);
            report.print(Messages.get().container(Messages.RPT_EXPORTING_0), I_CmsReport.FORMAT_NOTE);
            report.print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_ARGUMENT_1,
                    rfsName));
            report.print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_DOTS_0));
        } else {
            // no valid resource found for rfs name (already deleted), skip it
            continue;
        }

        try {
            CmsResource resource = data.getResource();
            try {
                Collection<String> detailPages = CmsDetailPageUtil.getAllDetailPagesWithUrlName(cms, resource);
                for (String detailPageUri : detailPages) {
                    String altRfsName = manager.getRfsName(cms, detailPageUri);
                    CmsStaticExportData detailData = new CmsStaticExportData(data.getVfsName(), altRfsName,
                            data.getResource(), data.getParameters());
                    exportTemplateResource(detailData, cookies);
                }
            } catch (CmsException e) {
                LOG.error(e.getLocalizedMessage(), e);
            }

            int status = exportTemplateResource(data, cookies);

            // write the report
            if (status == HttpServletResponse.SC_OK) {
                report.println(
                        org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0),
                        I_CmsReport.FORMAT_OK);
            } else if (status == HttpServletResponse.SC_NOT_MODIFIED) {
                report.println(
                        org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_SKIPPED_0),
                        I_CmsReport.FORMAT_NOTE);
            } else if (status == HttpServletResponse.SC_SEE_OTHER) {
                report.println(
                        org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_IGNORED_0),
                        I_CmsReport.FORMAT_NOTE);
            } else {
                report.println(org.opencms.report.Messages.get()
                        .container(org.opencms.report.Messages.RPT_ARGUMENT_1, new Integer(status)),
                        I_CmsReport.FORMAT_OK);
            }
        } catch (IOException e) {
            report.println(e);
        }
        //don't lock up the CPU exclusively - allow other Threads to run as well 
        Thread.yield();
    }
    report.println(Messages.get().container(Messages.RPT_STATICEXPORT_TEMPLATE_RESOURCES_END_0),
            I_CmsReport.FORMAT_HEADLINE);
}

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

/**
 * Evaluate pre-conditions, based on the request, as per the http rfc.
 *
 * @param request//  w  w  w  .j  a v a  2 s . c  o  m
 * @param response
 * @return
 * @throws IOException
 */
private boolean checkPreconditions(HttpServletRequest request, HttpServletResponse response,
        long lastModifiedTime, String currentEtag) throws IOException {
    lastModifiedTime = lastModifiedTime - (lastModifiedTime % 1000);
    long ifUnmodifiedSince = request.getDateHeader("if-unmodified-since");
    if (ifUnmodifiedSince > 0 && (lastModifiedTime >= ifUnmodifiedSince)) {
        response.reset();
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return false;
    }

    String ifMatch = request.getHeader("if-match");
    if (ifMatch != null && ifMatch.indexOf(currentEtag) < 0) {
        // ifMatch was present, but the currentEtag didnt match
        response.reset();
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return false;
    }
    String ifNoneMatch = request.getHeader("if-none-match");
    if (ifNoneMatch != null && ifNoneMatch.indexOf(currentEtag) >= 0) {
        if ("GET|HEAD".indexOf(request.getMethod()) >= 0) {
            response.reset();
            response.sendError(HttpServletResponse.SC_NOT_MODIFIED);

        } else {
            // ifMatch was present, but the currentEtag didnt match
            response.reset();
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        }
        return false;
    }
    long ifModifiedSince = request.getDateHeader("if-modified-since");
    if ((ifModifiedSince > 0) && (lastModifiedTime <= ifModifiedSince)) {
        response.reset();
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return false;
    }
    return true;
}

From source file:com.netspective.sparx.navigate.NavigationControllerServlet.java

protected void renderPage(NavigationContext nc) throws ServletException, IOException {
    final HttpServletResponse httpResponse = nc.getHttpResponse();
    if (isSecure()) {
        HttpLoginManager loginManager = getLoginManager();
        LoginDialogMode loginDialogMode = LoginDialogMode.ACCESS_ALLOWED;
        if (loginManager != null) {
            loginDialogMode = loginManager.getLoginDialogMode(nc);

            // if we're getting input or we're denying login it means that the presentation is complete (HTML is already on the screen)
            if (loginDialogMode == LoginDialogMode.GET_INPUT || loginDialogMode == LoginDialogMode.LOGIN_DENIED)
                return;
        }//from w  w w. java  2  s  .co  m

        // if we get to here, it means that the login dialog mode is either LOGIN_ACCEPTED (user has just logged in) or ACCESS_ALLOWED
        // which means that access was previously granted and the user is still valid

        // check to see if the user has recently logged in and is using the wrong navigation tree
        if (loginDialogMode == LoginDialogMode.LOGIN_ACCEPTED) {
            AuthenticatedUser user = nc.getAuthenticatedUser();
            if (user instanceof NavigationControllerAuthenticatedUser) {
                NavigationControllerAuthenticatedUser ncUser = (NavigationControllerAuthenticatedUser) user;
                if (ncUser.hasUserSpecificNavigationTree()) {
                    NavigationTree userTree = ncUser.getUserSpecificNavigationTree(this, nc.getHttpRequest(),
                            httpResponse);
                    if (userTree != null && nc.getOwnerTree() != userTree) {
                        // we want to redirect back to the home page of the navigation tree so that the proper tree
                        // will be picked up by the createContext() method
                        ncUser.redirectToUserTree(nc);
                        return;
                    }
                }
            }
        }
    }

    NavigationPage activePage = nc.getActivePage();
    if (activePage != null) {
        nc.getResponse().setContentType("text/html");
        if (nc.isActivePageValid()) {
            // make any necessary state changes (such as permissions, conditionals, etc).
            activePage.makeStateChanges(nc);

            // check to see if we have static content and we're in development mode (because in development presumably we don't want
            // anything to be static since 'static' is a performance attribute, not functionality
            if (!nc.getRuntimeEnvironmentFlags().isDevelopment()
                    && activePage.getFlags().flagIsSet(NavigationPage.Flags.STATIC_CONTENT)) {
                final HttpServletRequest httpRequest = nc.getHttpRequest();
                String staticPageKey = httpRequest.getServletPath() + httpRequest.getPathInfo();
                Date lastModfTime = (Date) staticPagesRendered.get(staticPageKey);

                // If the client sent an If-Modified-Since header equal or after the
                // servlet's last modified time, send a short "Not Modified" status code
                // Round down to the nearest second since client headers are in seconds
                if (lastModfTime != null && httpRequest.getMethod().equals("GET")
                        && ((lastModfTime.getTime() / 1000 * 1000) <= httpRequest
                                .getDateHeader("If-Modified-Since"))) {
                    httpResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    return;
                } else {
                    Date now = new Date();
                    httpResponse.setDateHeader("Last-Modified", now.getTime());
                    staticPagesRendered.put(staticPageKey, now);
                }
            }

            // if we get to there we're not static content or we're static but being rendered for the first
            // time in this instance of the servlet
            if (activePage.isRawHandler(nc))
                activePage.handlePageRaw(nc);
            else
                activePage.handlePage(nc.getResponse().getWriter(), nc);
        } else
            activePage.handleInvalidPage(nc.getResponse().getWriter(), nc);
    } else {
        Writer writer = nc.getResponse().getWriter();

        NavigationSkin skin = nc.getSkin();
        NavigationTree tree = nc.getOwnerTree();

        skin.renderPageMetaData(writer, nc);
        skin.renderPageHeader(writer, nc);
        writer.write("No page located for path '" + nc.getActivePathFindResults().getSearchedForPath() + "'.");
        if (nc.getRuntimeEnvironmentFlags().flagIsSet(RuntimeEnvironmentFlags.DEVELOPMENT)) {
            writer.write("<pre>\n");
            writer.write(tree.toString());
            writer.write("</pre>\n");
        }
        skin.renderPageFooter(writer, nc);
    }
}