Example usage for javax.servlet.http HttpServletResponse reset

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

Introduction

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

Prototype

public void reset();

Source Link

Document

Clears any data that exists in the buffer as well as the status code, headers.

Usage

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

@Override
public void doDelete(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from w ww  . ja va 2  s  .  c  o m*/

        snoopRequest(request);

        ResourceDefinition rp = resourceDefinitionFactory.getSpec(request);
        Node n = jcrNodeFactory.getNode(rp.getRepositoryPath());
        if (n == null) {
            response.reset();
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        NodeType nt = n.getPrimaryNodeType();

        long lastModifiedTime = -10;
        if (JCRConstants.NT_FILE.equals(nt.getName())) {

            Node resource = n.getNode(JCRConstants.JCR_CONTENT);
            Property lastModified = resource.getProperty(JCRConstants.JCR_LASTMODIFIED);
            lastModifiedTime = lastModified.getDate().getTimeInMillis();

            if (!checkPreconditions(request, response, lastModifiedTime, String.valueOf(lastModifiedTime))) {
                return;
            }
        }

        Session s = n.getSession();
        n.remove();
        s.save();
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);

    } catch (Exception e) {
        sendError(request, response, e);

        snoopRequest(request);
        LOG.error("Failed  TO service Request ", e);
    }
}

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

/**
 * Evaluate pre-conditions, based on the request, as per the http rfc.
 *
 * @param request/*w  ww  .j a  v a  2 s  .  co 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:org.sakaiproject.sdata.tool.JCRHandler.java

/**
 * Perform a mime multipart upload into the JCR repository based on a location specified
 * by the rp parameter. The parts of the multipart upload are relative to the current
 * request path/*ww  w  . j  a v a 2s.com*/
 *
 * @param request
 *          the request object of the current request.
 * @param response
 *          the response object of the current request
 * @param rp
 *          the resource definition for the current request
 * @throws ServletException
 * @throws IOException
 */
private void doMumtipartUpload(HttpServletRequest request, HttpServletResponse response, ResourceDefinition rp)
        throws ServletException, IOException {
    try {
        try {
            Node n = jcrNodeFactory.createFolder(rp.getRepositoryPath());
            if (n == null) {
                response.reset();
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Unable to uplaod to location " + rp.getRepositoryPath());
                return;
            }
        } catch (Exception ex) {
            sendError(request, response, ex);
            snoopRequest(request);
            LOG.error("Failed  TO service Request ", ex);
            return;
        }

        // Check that we have a file upload request

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload();
        List<String> errors = new ArrayList<String>();

        // Parse the request
        FileItemIterator iter = upload.getItemIterator(request);
        Map<String, Object> responseMap = new HashMap<String, Object>();
        Map<String, Object> uploads = new HashMap<String, Object>();
        Map<String, List<String>> values = new HashMap<String, List<String>>();
        int uploadNumber = 0;
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            LOG.debug("Got Upload through Uploads");
            String name = item.getName();
            String fieldName = item.getFieldName();
            LOG.info("    Name is " + name + " field Name " + fieldName);
            for (String headerName : item.getHeaderNames()) {
                LOG.info("Header " + headerName + " is " + item.getHeader(headerName));
            }
            InputStream stream = item.openStream();
            if (!item.isFormField()) {
                try {
                    if (name != null && name.trim().length() > 0) {

                        List<String> realNames = values.get(REAL_UPLOAD_NAME);
                        String finalName = name;
                        if (realNames != null && realNames.size() > uploadNumber) {
                            finalName = realNames.get(uploadNumber);
                        }

                        String path = rp.convertToAbsoluteRepositoryPath(finalName);
                        // pooled uploads never overwrite.
                        List<String> pooled = values.get(POOLED);
                        if (pooled != null && pooled.size() > 0 && "1".equals(pooled.get(0))) {
                            path = rp.convertToAbsoluteRepositoryPath(PathUtils.getPoolPrefix(finalName));
                            int i = 0;
                            String basePath = path;
                            try {
                                while (true) {
                                    Node n = jcrNodeFactory.getNode(path);
                                    if (n == null) {
                                        break;
                                    }
                                    int lastStop = basePath.lastIndexOf('.');
                                    path = basePath.substring(0, lastStop) + "_" + i
                                            + basePath.substring(lastStop);
                                    i++;
                                }
                            } catch (JCRNodeFactoryServiceException ex) {
                                // the path does not exist which is good.
                            }
                        }

                        String mimeType = ContentTypes.getContentType(finalName, item.getContentType());
                        Node target = jcrNodeFactory.createFile(path, mimeType);
                        GregorianCalendar lastModified = new GregorianCalendar();
                        lastModified.setTime(new Date());
                        long size = saveStream(target, stream, mimeType, "UTF-8", lastModified);
                        Map<String, Object> uploadMap = new HashMap<String, Object>();
                        if (size > Integer.MAX_VALUE) {
                            uploadMap.put("contentLength", String.valueOf(size));
                        } else {
                            uploadMap.put("contentLength", (int) size);
                        }
                        uploadMap.put("name", finalName);
                        uploadMap.put("url", rp.convertToExternalPath(path));
                        uploadMap.put("mimeType", mimeType);
                        uploadMap.put("lastModified", lastModified.getTime());
                        uploadMap.put("status", "ok");

                        uploads.put(fieldName, uploadMap);
                    }
                } catch (Exception ex) {
                    LOG.error("Failed to Upload Content", ex);
                    Map<String, Object> uploadMap = new HashMap<String, Object>();
                    uploadMap.put("mimeType", "text/plain");
                    uploadMap.put("encoding", "UTF-8");
                    uploadMap.put("contentLength", -1);
                    uploadMap.put("lastModified", 0);
                    uploadMap.put("status", "Failed");
                    uploadMap.put("cause", ex.getMessage());
                    List<String> stackTrace = new ArrayList<String>();
                    for (StackTraceElement ste : ex.getStackTrace()) {
                        stackTrace.add(ste.toString());
                    }
                    uploadMap.put("stacktrace", stackTrace);
                    uploads.put(fieldName, uploadMap);
                    uploadMap = null;

                }

            } else {
                String value = Streams.asString(stream);
                List<String> valueList = values.get(name);
                if (valueList == null) {
                    valueList = new ArrayList<String>();
                    values.put(name, valueList);

                }
                valueList.add(value);
            }
        }

        responseMap.put("success", true);
        responseMap.put("errors", errors.toArray(new String[1]));
        responseMap.put("uploads", uploads);
        sendMap(request, response, responseMap);
        LOG.info("Response Complete Saved to " + rp.getRepositoryPath());
    } catch (Throwable ex) {
        LOG.error("Failed  TO service Request ", ex);
        sendError(request, response, ex);
        return;
    }
}

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

@Override
public void doHead(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from www  . j a  v  a2  s  . c  o m*/
        LOG.info("Doing Head ");
        snoopRequest(request);

        ResourceDefinition rp = resourceDefinitionFactory.getSpec(request);
        Node n = jcrNodeFactory.getNode(rp.getRepositoryPath());
        if (n == null) {
            response.reset();
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        String version = rp.getVersion();
        if (version != null) {
            try {
                n = n.getVersionHistory().getVersion(version);
            } catch (VersionException e) {
                throw new SDataAccessException(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
            }
            n = n.getNode(JCRConstants.JCR_FROZENNODE);
        }

        Node resource = n.getNode(JCRConstants.JCR_CONTENT);
        Property lastModified = resource.getProperty(JCRConstants.JCR_LASTMODIFIED);
        Property mimeType = resource.getProperty(JCRConstants.JCR_MIMETYPE);
        Property content = resource.getProperty(JCRConstants.JCR_DATA);

        response.setContentType(mimeType.getString());
        if (mimeType.getString().startsWith("text")) {
            if (resource.hasProperty(JCRConstants.JCR_ENCODING)) {
                Property encoding = resource.getProperty(JCRConstants.JCR_ENCODING);
                response.setCharacterEncoding(encoding.getString());
            }
        }
        response.setDateHeader(LAST_MODIFIED, lastModified.getDate().getTimeInMillis());
        // we need to do something about huge files
        response.setContentLength((int) content.getLength());
        response.setStatus(HttpServletResponse.SC_OK);

    } catch (Exception e) {
        sendError(request, response, e);

        snoopRequest(request);
        LOG.error("Failed  TO service Request ", e);
    }
}

From source file:se.vgregion.webbisar.web.MediaServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Get requested image by path info.
    String requestedFile = request.getPathInfo();
    LOGGER.info("requestedFile: " + requestedFile);

    if (requestedFile == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
        return;/*from w  w w .  j av  a2 s  .  c om*/
    }

    File file = new File(baseFilePath, URLDecoder.decode(requestedFile, "UTF-8"));
    LOGGER.info("filePath: " + file.getAbsolutePath());
    LOGGER.info("fileName: " + file.getName());

    // Check if file exists
    if (!file.exists()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
        return;
    }

    // Get content type by filename.
    String contentType = getServletContext().getMimeType(file.getName().replace(".JPG", ".jpg"));
    if (contentType == null && file.getName().endsWith("3gp")) {
        contentType = "video/3gpp";
    }

    if (contentType == null || !(contentType.startsWith("image") || contentType.startsWith("video"))) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
        return;
    }

    // Init servlet response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.addHeader("Content-Type", contentType);
    response.addHeader("Content-Length", String.valueOf(file.length()));

    response.addHeader("Expires", "Sun, 17 Jan 2038 19:14:07 GMT");
    response.addHeader("Cache-Control", "public");

    response.addHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");

    // Prepare streams.
    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {
        // Open streams.
        input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
        output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

        // Write file contents to response.
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int length;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }

        // Finalize task.
        output.flush();
    } finally {
        // Gently close streams.
        close(output);
        close(input);
    }
}

From source file:org.andromda.presentation.gui.FileDownloadServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///  w  ww .  j  a v  a  2 s . c  o m
@Override
public void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    try {
        final String action = request.getParameter(ACTION);
        final FacesContext context = FacesContextUtils.getFacesContext(request, response);
        if (action != null && action.trim().length() > 0) {
            final MethodBinding methodBinding = context.getApplication()
                    .createMethodBinding("#{" + action + "}", null);
            methodBinding.invoke(context, null);
        }

        final Object form = context.getApplication().getVariableResolver().resolveVariable(context, "form");
        final Boolean prompt = Boolean.valueOf(request.getParameter(PROMPT));
        final String fileNameProperty = request.getParameter(FILE_NAME);
        final String outputProperty = request.getParameter(OUTPUT);
        if (form != null && outputProperty != null && fileNameProperty.trim().length() > 0) {
            final OutputStream stream = response.getOutputStream();

            // - reset the response to clear out any any headers (i.e. so
            //   the user doesn't get "unable to open..." when using IE.)
            response.reset();

            Object output = PropertyUtils.getProperty(form, outputProperty);
            final String fileName = ObjectUtils.toString(PropertyUtils.getProperty(form, fileNameProperty));
            final String contentType = this.getContentType(context, request.getParameter(CONTENT_TYPE),
                    fileName);

            if (prompt.booleanValue() && fileName != null && fileName.trim().length() > 0) {
                response.addHeader("Content-disposition", "attachment; filename=\"" + fileName + '"');
            }

            // - for IE we need to set the content type, content length and buffer size and
            //   then the flush the response right away because it seems as if there is any lag time
            //   IE just displays a blank page. With mozilla based clients reports display correctly regardless.
            if (contentType != null && contentType.length() > 0) {
                response.setContentType(contentType);
            }
            if (output instanceof String) {
                output = ((String) output).getBytes();
            }
            if (output instanceof byte[]) {
                byte[] file = (byte[]) output;
                response.setBufferSize(file.length);
                response.setContentLength(file.length);
                response.flushBuffer();
                stream.write(file);
            } else if (output instanceof InputStream) {
                final InputStream report = (InputStream) output;
                final byte[] buffer = new byte[BUFFER_SIZE];
                response.setBufferSize(BUFFER_SIZE);
                response.flushBuffer();
                for (int ctr = 0; (ctr = report.read(buffer)) > 0;) {
                    stream.write(buffer, 0, ctr);
                }
            }
            stream.flush();
        }
        if (form != null) {
            // - remove the output now that we're done with it (in case its large)
            PropertyUtils.setProperty(form, outputProperty, null);
        }
    } catch (Throwable throwable) {
        throw new ServletException(throwable);
    }
}

From source file:org.jcommon.com.wechat.servlet.MediaServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String path = request.getPathInfo();
    logger.info("path:" + path);

    String errormsg = null;/* w w w  . j  a va  2  s . co  m*/
    if (path == null)
        errormsg = "access path is null";
    else {
        Media media = MediaManager.getMedia_factory().getMediaFromUrl(path);
        String file_name = media.getMedia_name();
        String content_type = media.getContent_type();
        java.io.File file = media.getMedia();
        if (file == null || !file.exists()) {
            logger.warn("file not found:" + file.getAbsolutePath());
            errormsg = "file not found";
        } else {
            try {
                String user_agent = request.getHeader("User-Agent");
                if (user_agent.toLowerCase().indexOf("msie") != -1) {
                    file_name = org.jcommon.com.util.CoderUtils.encode(file_name);
                } else {
                    file_name = file_name.replaceAll(" ", "");
                    file_name = new String(file_name.getBytes("utf-8"), "iso-8859-1");
                }
                logger.info(file_name);
                response.reset();
                response.setContentType(content_type);
                response.addHeader("Content-Disposition", "attachment;filename=\"" + file_name + "\"");
                response.addHeader("Content-Length", "" + file.length());

                InputStream is = new FileInputStream(file);
                OutputStream out = response.getOutputStream();

                byte[] b = new byte[1024];
                int nRead;
                while ((nRead = is.read(b, 0, 1024)) > 0) {
                    out.write(b, 0, nRead);
                }
                try {
                    is.close();
                    out.close();
                    out.flush();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    throw e1;
                }
            } catch (IOException e) {
                logger.error("", e);
                errormsg = e.getMessage();
            }
        }
    }
    if (errormsg != null) {
        logger.info(errormsg);
        response.getWriter().print(errormsg);
    }
}

From source file:org.apache.roller.weblogger.ui.rendering.servlets.PageServlet.java

/**
 * Handle GET requests for weblog pages.
 *///from ww  w.j a va2s  .c  o  m
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("Entering");

    // do referrer processing, if it's enabled
    // NOTE: this *must* be done first because it triggers a hibernate flush
    // which will close the active session and cause lazy init exceptions
    // otherwise
    if (this.processReferrers) {
        boolean spam = this.processReferrer(request);
        if (spam) {
            log.debug("spammer, giving 'em a 403");
            if (!response.isCommitted()) {
                response.reset();
            }
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }
    }

    Weblog weblog = null;
    boolean isSiteWide = false;

    WeblogPageRequest pageRequest = null;
    try {
        pageRequest = new WeblogPageRequest(request);

        weblog = pageRequest.getWeblog();
        if (weblog == null) {
            throw new WebloggerException("unable to lookup weblog: " + pageRequest.getWeblogHandle());
        }

        // is this the site-wide weblog?
        isSiteWide = WebloggerRuntimeConfig.isSiteWideWeblog(pageRequest.getWeblogHandle());
    } catch (Exception e) {
        // some kind of error parsing the request or looking up weblog
        log.debug("error creating page request", e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // determine the lastModified date for this content
    long lastModified = System.currentTimeMillis();
    if (isSiteWide) {
        lastModified = siteWideCache.getLastModified().getTime();
    } else if (weblog.getLastModified() != null) {
        lastModified = weblog.getLastModified().getTime();
    }

    // 304 Not Modified handling.
    // We skip this for logged in users to avoid the scenerio where a user
    // views their weblog, logs in, then gets a 304 without the 'edit' links

    if (!pageRequest.isLoggedIn()) {
        if (ModDateHeaderUtil.respondIfNotModified(request, response, lastModified)) {
            return;
        } else {
            // set last-modified date
            ModDateHeaderUtil.setLastModifiedHeader(response, lastModified);
        }
    }

    // generate cache key
    String cacheKey = null;
    if (isSiteWide) {
        cacheKey = siteWideCache.generateKey(pageRequest);
    } else {
        cacheKey = weblogPageCache.generateKey(pageRequest);
    }

    // Development only. Reload if theme has been modified
    if (themeReload && !weblog.getEditorTheme().equals(WeblogTemplate.ACTION_CUSTOM)
            && (pageRequest.getPathInfo() == null || pageRequest.getPathInfo() != null)) {
        try {
            ThemeManager manager = WebloggerFactory.getWeblogger().getThemeManager();
            boolean reloaded = manager.reLoadThemeFromDisk(weblog.getEditorTheme());
            if (reloaded) {
                if (isSiteWide) {
                    siteWideCache.clear();
                } else {
                    weblogPageCache.clear();
                }
                I18nMessages.reloadBundle(weblog.getLocaleInstance());
            }

        } catch (Exception ex) {
            log.error("ERROR - reloading theme " + ex);
        }
    }

    // cached content checking
    if ((!this.excludeOwnerPages || !pageRequest.isLoggedIn()) && request.getAttribute("skipCache") == null) {

        CachedContent cachedContent = null;
        if (isSiteWide) {
            cachedContent = (CachedContent) siteWideCache.get(cacheKey);
        } else {
            cachedContent = (CachedContent) weblogPageCache.get(cacheKey, lastModified);
        }

        if (cachedContent != null) {
            log.debug("HIT " + cacheKey);

            // allow for hit counting
            if (!isSiteWide) {
                this.processHit(weblog, request.getRequestURL().toString(), request.getHeader("referer"));
            }

            response.setContentLength(cachedContent.getContent().length);
            response.setContentType(cachedContent.getContentType());
            response.getOutputStream().write(cachedContent.getContent());
            return;
        } else {
            log.debug("MISS " + cacheKey);
        }
    }

    log.debug("Looking for template to use for rendering");

    // figure out what template to use
    ThemeTemplate page = null;

    // If this is a popup request, then deal with it specially
    // TODO: do we really need to keep supporting this?
    if (request.getParameter("popup") != null) {
        try {
            // Does user have a popupcomments page?
            page = weblog.getTheme().getTemplateByName("_popupcomments");
        } catch (Exception e) {
            // ignored ... considered page not found
        }

        // User doesn't have one so return the default
        if (page == null) {
            page = new StaticThemeTemplate("templates/weblog/popupcomments.vm", "velocity");
        }

        // If request specified the page, then go with that
    } else if ("page".equals(pageRequest.getContext())) {
        page = pageRequest.getWeblogPage();

        // if we don't have this page then 404, we don't let
        // this one fall through to the default template
        if (page == null) {
            if (!response.isCommitted()) {
                response.reset();
            }
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // If request specified tags section index, then look for custom
        // template
    } else if ("tags".equals(pageRequest.getContext()) && pageRequest.getTags() != null) {
        try {
            page = weblog.getTheme().getTemplateByAction(ThemeTemplate.ACTION_TAGSINDEX);
        } catch (Exception e) {
            log.error("Error getting weblog page for action 'tagsIndex'", e);
        }

        // if we don't have a custom tags page then 404, we don't let
        // this one fall through to the default template
        if (page == null) {
            if (!response.isCommitted()) {
                response.reset();
            }
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // If this is a permalink then look for a permalink template
    } else if (pageRequest.getWeblogAnchor() != null) {
        try {
            page = weblog.getTheme().getTemplateByAction(ThemeTemplate.ACTION_PERMALINK);
        } catch (Exception e) {
            log.error("Error getting weblog page for action 'permalink'", e);
        }
    }

    // if we haven't found a page yet then try our default page
    if (page == null) {
        try {
            page = weblog.getTheme().getDefaultTemplate();
        } catch (Exception e) {
            log.error("Error getting default page for weblog = " + weblog.getHandle(), e);
        }
    }

    // Still no page? Then that is a 404
    if (page == null) {
        if (!response.isCommitted()) {
            response.reset();
        }
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    log.debug("page found, dealing with it");

    // validation. make sure that request input makes sense.
    boolean invalid = false;
    if (pageRequest.getWeblogPageName() != null && page.isHidden()) {
        invalid = true;
    }
    if (pageRequest.getLocale() != null) {

        // locale view only allowed if weblog has enabled it
        if (!pageRequest.getWeblog().isEnableMultiLang()) {
            invalid = true;
        }
    }
    if (pageRequest.getWeblogAnchor() != null) {

        // permalink specified.
        // entry must exist, be published before current time, and locale
        // must match
        WeblogEntry entry = pageRequest.getWeblogEntry();
        if (entry == null) {
            invalid = true;
        } else if (pageRequest.getLocale() != null && !entry.getLocale().startsWith(pageRequest.getLocale())) {
            invalid = true;
        } else if (!entry.isPublished()) {
            invalid = true;
        } else if (new Date().before(entry.getPubTime())) {
            invalid = true;
        }
    } else if (pageRequest.getWeblogCategoryName() != null) {

        // category specified. category must exist.
        if (pageRequest.getWeblogCategory() == null) {
            invalid = true;
        }
    } else if (pageRequest.getTags() != null && pageRequest.getTags().size() > 0) {

        try {
            // tags specified. make sure they exist.
            WeblogEntryManager wmgr = WebloggerFactory.getWeblogger().getWeblogEntryManager();
            invalid = !wmgr.getTagComboExists(pageRequest.getTags(), (isSiteWide) ? null : weblog);
        } catch (WebloggerException ex) {
            invalid = true;
        }
    }

    if (invalid) {
        log.debug("page failed validation, bailing out");
        if (!response.isCommitted()) {
            response.reset();
        }
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // do we need to force a specific locale for the request?
    if (pageRequest.getLocale() == null && !weblog.isShowAllLangs()) {
        pageRequest.setLocale(weblog.getLocale());
    }

    // allow for hit counting
    if (!isSiteWide) {
        this.processHit(weblog, request.getRequestURL().toString(), request.getHeader("referer"));
    }

    // looks like we need to render content
    // set the content deviceType
    String contentType = "text/html; charset=utf-8";
    if (StringUtils.isNotEmpty(page.getOutputContentType())) {
        contentType = page.getOutputContentType() + "; charset=utf-8";
    } else {
        String mimeType = RollerContext.getServletContext().getMimeType(page.getLink());
        if (mimeType != null) {
            // we found a match ... set the content deviceType
            contentType = mimeType + "; charset=utf-8";
        } else {
            contentType = "text/html; charset=utf-8";
        }
    }

    HashMap model = new HashMap();
    try {
        PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(this, request, response, "",
                false, 8192, true);

        // special hack for menu tag
        request.setAttribute("pageRequest", pageRequest);

        // populate the rendering model
        Map initData = new HashMap();
        initData.put("requestParameters", request.getParameterMap());
        initData.put("parsedRequest", pageRequest);
        initData.put("pageContext", pageContext);

        // define url strategy
        initData.put("urlStrategy", WebloggerFactory.getWeblogger().getUrlStrategy());

        // if this was a comment posting, check for comment form
        WeblogEntryCommentForm commentForm = (WeblogEntryCommentForm) request.getAttribute("commentForm");
        if (commentForm != null) {
            initData.put("commentForm", commentForm);
        }

        // Load models for pages
        String pageModels = WebloggerConfig.getProperty("rendering.pageModels");
        ModelLoader.loadModels(pageModels, model, initData, true);
        // Load special models for site-wide blog
        if (WebloggerRuntimeConfig.isSiteWideWeblog(weblog.getHandle())) {
            String siteModels = WebloggerConfig.getProperty("rendering.siteModels");
            ModelLoader.loadModels(siteModels, model, initData, true);
        }

        // Load weblog custom models
        ModelLoader.loadCustomModels(weblog, model, initData);

        // ick, gotta load pre-3.0 model stuff as well :(
        ModelLoader.loadOldModels(model, request, response, pageContext, pageRequest,
                WebloggerFactory.getWeblogger().getUrlStrategy());
    } catch (WebloggerException ex) {
        log.error("Error loading model objects for page", ex);

        if (!response.isCommitted()) {
            response.reset();
        }
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    // lookup Renderer we are going to use
    Renderer renderer = null;
    try {
        log.debug("Looking up renderer");
        renderer = RendererManager.getRenderer(page, pageRequest.getDeviceType());
    } catch (Exception e) {
        // nobody wants to render my content :(
        log.error("Couldn't find renderer for page " + page.getId(), e);

        if (!response.isCommitted()) {
            response.reset();
        }
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // render content. use size of about 24K for a standard page
    CachedContent rendererOutput = new CachedContent(24567, contentType);
    try {
        log.debug("Doing rendering");
        renderer.render(model, rendererOutput.getCachedWriter());

        // flush rendered output and close
        rendererOutput.flush();
        rendererOutput.close();
    } catch (Exception e) {
        // bummer, error during rendering
        log.error("Error during rendering for page " + page.getId(), e);

        if (!response.isCommitted()) {
            response.reset();
        }
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // post rendering process
    // flush rendered content to response
    log.debug("Flushing response output");
    response.setContentType(contentType);
    response.setContentLength(rendererOutput.getContent().length);
    response.getOutputStream().write(rendererOutput.getContent());

    // cache rendered content. only cache if user is not logged in?
    if ((!this.excludeOwnerPages || !pageRequest.isLoggedIn()) && request.getAttribute("skipCache") == null) {
        log.debug("PUT " + cacheKey);

        // put it in the right cache
        if (isSiteWide) {
            siteWideCache.put(cacheKey, rendererOutput);
        } else {
            weblogPageCache.put(cacheKey, rendererOutput);
        }
    } else {
        log.debug("SKIPPED " + cacheKey);
    }

    log.debug("Exiting");
}

From source file:com.scooter1556.sms.server.service.AdaptiveStreamingService.java

public void sendHLSPlaylist(UUID id, String type, Integer extra, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    // Get the request base URL so we can use it in our playlist
    String baseUrl = request.getRequestURL().toString().replaceFirst("/stream(.*)", "");

    List<String> playlist;

    // Get playlist as a string array
    if (type == null) {
        playlist = generateHLSVariantPlaylist(id, baseUrl);
    } else {/*from  w w  w . j av  a 2  s  . c om*/
        playlist = generateHLSPlaylist(id, baseUrl, type, extra);
    }

    if (playlist == null) {
        LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME,
                "Unable to generate HLS playlist.", null);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to generate HLS playlist.");
        return;
    }

    // Write playlist to buffer so we can get the content length
    StringWriter playlistWriter = new StringWriter();
    for (String line : playlist) {
        playlistWriter.write(line + "\n");
    }

    // Set Header Parameters
    response.reset();
    response.setContentType("application/x-mpegurl");
    response.setContentLength(playlistWriter.toString().length());

    // Enable CORS
    response.setHeader(("Access-Control-Allow-Origin"), "*");
    response.setHeader("Access-Control-Allow-Methods", "GET");
    response.setIntHeader("Access-Control-Max-Age", 3600);

    // Write playlist out to the client
    response.getWriter().write(playlistWriter.toString());

    /*********************** DEBUG: Response Headers *********************************/
    String requestHeader = "\n***************\nResponse Header:\n***************\n";
    Collection<String> responseHeaderNames = response.getHeaderNames();

    for (int i = 0; i < responseHeaderNames.size(); i++) {
        String header = (String) responseHeaderNames.toArray()[i];
        String value = response.getHeader(header);
        requestHeader += header + ": " + value + "\n";
    }

    // Log Headers
    LogService.getInstance().addLogEntry(LogService.Level.INSANE, CLASS_NAME, requestHeader, null);

    /********************************************************************************/

    // Log playlist
    LogService.getInstance().addLogEntry(LogService.Level.INSANE, CLASS_NAME,
            "\n************\nHLS Playlist\n************\n" + playlistWriter.toString(), null);
}

From source file:xx.tream.chengxin.ms.action.TrainReportAction.java

@RequestMapping({ "/toExport" })
public String toExport(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response,
        FormMap formMap, Integer currentPage, Integer pageSize) throws IOException {
    Map<String, Object> qm = formMap.getFormMap();
    List<Map<String, Object>> list = this.trainService.queryForParam(qm);
    //Map<String, Object> statisticsMap = this.trainService.statistics(qm);
    String trainIds = this.getTrainIds(list);
    List<Map<String, Object>> payingList = this.payingService.queryByTrainIds(trainIds);
    List<Map<String, Object>> incomeList = this.incomeService.queryByTrainIds(trainIds);
    List<Map<String, Object>> payoutList = this.payoutService.queryByTrainIds(trainIds);
    Map<Long, List<Map<String, Object>>> payingMap = converList(payingList);
    Map<Long, List<Map<String, Object>>> incomeMap = converList(incomeList);
    Map<Long, List<Map<String, Object>>> payoutMap = converList(payoutList);

    OutputStream os = response.getOutputStream();
    response.reset();
    response.setCharacterEncoding("UTF-8");
    String title = "?" + getDateFile() + ".xls";
    response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(title, "UTF-8"));
    response.setContentType("application/vnd.ms-excel");
    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFSheet sheet = workbook.createSheet("?");
    HSSFRow headrow = sheet.createRow(0);
    HSSFCellStyle headcell = workbook.createCellStyle();

    HSSFFont font = workbook.createFont();
    font.setFontName("");
    font.setFontHeightInPoints((short) 10);
    headcell.setFont(font);/*from  www. j  a  v  a 2  s .com*/
    headrow.setRowStyle(headcell);
    String payingValue[] = { "", "paying", "createUserName", "createTime", "createTime", "", "auditUserName",
            "auditTime", "auditTime" };
    String incomeValue[] = { "type", "income", "createUserName", "createTime", "createTime", "note",
            "auditUserName", "auditTime", "auditTime" };
    String payoutValue[] = { "type", "payout", "createUserName", "createTime", "createTime", "",
            "auditUserName", "auditTime", "auditTime" };
    String[] heads = { "", "?", "?", "??", "??", "",
            "", "", "", "", "/", "/?", "C1/C2",
            "", "", "", "", "", "?", "?",
            "?", "?", "", "", "", "" };
    String[] values = { "", "id", "autumnNumber", "name", "idcard", "pay", "allpaying", "count_all", "allip",
            "canpay", "newOrOld", "type", "licenseTag", "createUserName", "createTime", "createTime", "note" };
    HSSFCellStyle headStyle = ExcelUtil.headCell(workbook);
    HSSFCell cell = null;
    //
    int cr = 0;
    for (int i = 0; i < heads.length; i++) {
        cell = headrow.createCell(cr);
        cell.setCellValue(heads[i]);
        cell.setCellStyle(headStyle);
        sheet.setColumnWidth(cr, 5000);
        cr++;
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm");
    HSSFCellStyle rowStyle = ExcelUtil.leftCell(workbook);
    HSSFCellStyle paleBlueStyle = ExcelUtil.paleBlueForgroundCell(workbook);
    //HSSFCellStyle redFontStyle = ExcelUtil.leftFontRedCell(workbook);
    //HSSFCellStyle redFontForegroudStyle = ExcelUtil.leftFontRedForegroudCell(workbook);
    HSSFCellStyle rightStyle = ExcelUtil.rightCell(workbook);
    HSSFCellStyle rightForegroudStyle = ExcelUtil.rightPaleBlueForgroundCell(workbook);
    HSSFCellStyle rightredFontStyle = ExcelUtil.rightFontRedCell(workbook);
    HSSFCellStyle rightredFontForegroudStyle = ExcelUtil.rightFontRedForegroudCell(workbook);
    double ac[] = new double[5];

    //
    int rn = 1;
    HSSFRow row = null;
    //??
    for (int i = 0; i < list.size(); i++) {
        int a = 0;
        //
        int pb = 0;
        //
        cr = 0;
        row = sheet.createRow(rn++);
        Map<String, Object> trainMap = (Map<String, Object>) list.get(i);
        List<Map<String, Object>> payL = (List<Map<String, Object>>) payingMap.get((Long) trainMap.get("id"));
        List<Map<String, Object>> incomeL = (List<Map<String, Object>>) incomeMap
                .get((Long) trainMap.get("id"));
        List<Map<String, Object>> payoutL = (List<Map<String, Object>>) payoutMap
                .get((Long) trainMap.get("id"));
        for (int v = 0; v < values.length; v++) {
            cell = row.createCell(cr++);
            if (trainMap.get(values[v]) != null) {
                if (v == 14) {
                    cell.setCellValue(sdf.format((Date) trainMap.get(values[v])));
                } else if (v == 15) {
                    cell.setCellValue(sdf2.format((Date) trainMap.get(values[v])));
                } else if (v == 5 || v == 6 || v == 7 || v == 8 || v == 9) {
                    Double d = trainMap.get(values[v]) == null ? 0 : (Double) trainMap.get(values[v]);
                    ac[a] += d;
                    a++;
                    cell.setCellValue((Double) trainMap.get(values[v]));
                } else if (v == 1) {
                    cell.setCellValue((Long) trainMap.get(values[v]));
                } else {
                    cell.setCellValue((String) trainMap.get(values[v]));
                }
            } else {
                if (v == 0) {
                    cell.setCellValue(i + 1);
                } else {
                    cell.setCellValue("");
                }
            }
            if (v == 5 || v == 6 || v == 7 || v == 8 || v == 9) {//?
                cell.setCellStyle(rightForegroudStyle);
            } else {
                cell.setCellStyle(paleBlueStyle);
            }

        }

        //
        if (payL != null && payL.size() > 0) {
            for (int p = 0; p < payL.size(); p++) {
                Map<String, Object> pMap = payL.get(p);
                cr = values.length;
                for (int v = 0; v < payingValue.length; v++) {
                    cell = row.createCell(cr++);
                    if (v == 0) {
                        cell.setCellValue("" + (p + 1));
                    } else {
                        if (pMap.get(payingValue[v]) != null) {
                            if (v == 3 || v == 7) {
                                cell.setCellValue(sdf.format((Date) pMap.get(payingValue[v])));
                            } else if (v == 4 || v == 8) {
                                cell.setCellValue(sdf2.format((Date) pMap.get(payingValue[v])));
                            } else if (v == 1) {
                                Double nv = (Double) pMap.get(payingValue[v]);
                                cell.setCellValue(nv);
                            } else {
                                cell.setCellValue((String) pMap.get(payingValue[v]));
                            }
                        } else {
                            cell.setCellValue("");
                        }
                    }
                    if (v == 1) {//?
                        if (pb == 0) {
                            cell.setCellStyle(rightForegroudStyle);
                        } else {
                            cell.setCellStyle(rightStyle);
                        }
                    } else {
                        if (pb == 0) {
                            cell.setCellStyle(paleBlueStyle);

                        } else {
                            cell.setCellStyle(rowStyle);
                        }
                    }
                }
                pb++;
                row = sheet.createRow(rn++);

            }

        }
        //
        if (incomeL != null && incomeL.size() > 0) {
            for (int p = 0; p < incomeL.size(); p++) {
                Map<String, Object> iMap = incomeL.get(p);
                cr = values.length;
                for (int v = 0; v < incomeValue.length; v++) {
                    cell = row.createCell(cr++);
                    if (v == 0) {
                        cell.setCellValue(iMap.get(incomeValue[v]) + "()");
                    } else {
                        if (iMap.get(incomeValue[v]) != null) {
                            if (v == 3 || v == 7) {
                                cell.setCellValue(sdf.format((Date) iMap.get(incomeValue[v])));
                            } else if (v == 4 || v == 8) {
                                cell.setCellValue(sdf2.format((Date) iMap.get(incomeValue[v])));
                            } else if (v == 1) {
                                cell.setCellValue((Double) iMap.get(incomeValue[v]));
                            } else {
                                cell.setCellValue((String) iMap.get(incomeValue[v]));
                            }
                        } else {
                            cell.setCellValue("");
                        }
                    }
                    if (v == 1) {//?
                        if (pb == 0) {
                            cell.setCellStyle(rightForegroudStyle);
                        } else {
                            cell.setCellStyle(rightStyle);
                        }
                    } else {
                        if (pb == 0) {
                            cell.setCellStyle(paleBlueStyle);

                        } else {
                            cell.setCellStyle(rowStyle);
                        }
                    }
                }
                pb++;
                row = sheet.createRow(rn++);
            }
        }
        boolean flag = false;
        //
        if (payoutL != null && payoutL.size() > 0) {
            for (int p = 0; p < payoutL.size(); p++) {
                Map<String, Object> pMap = payoutL.get(p);
                cr = values.length;
                for (int v = 0; v < payoutValue.length; v++) {
                    cell = row.createCell(cr++);
                    if (v == 0) {
                        cell.setCellValue(pMap.get(payoutValue[v]) + "()");
                    } else {
                        if (pMap.get(payoutValue[v]) != null) {
                            if (v == 3 || v == 7) {
                                cell.setCellValue(sdf.format((Date) pMap.get(payoutValue[v])));
                            } else if (v == 4 || v == 8) {
                                cell.setCellValue(sdf2.format((Date) pMap.get(payoutValue[v])));
                            } else if (v == 1) {
                                flag = true;
                                cell.setCellValue(0 - (Double) pMap.get(payoutValue[v]));
                            } else {
                                cell.setCellValue((String) pMap.get(payoutValue[v]));
                            }
                        } else {
                            cell.setCellValue("");
                        }
                    }
                    if (pb == 0 && flag) {
                        flag = false;
                        cell.setCellStyle(rightredFontForegroudStyle);
                    } else if (flag) {
                        flag = false;
                        cell.setCellStyle(rightredFontStyle);
                    } else if (pb == 0) {
                        cell.setCellStyle(paleBlueStyle);
                    } else {
                        cell.setCellStyle(rowStyle);
                    }
                }
                pb++;
                if (p != payoutL.size() - 1) {
                    row = sheet.createRow(rn++);
                }
            }
        }
    }
    if (list != null && list.size() > 0) {
        row = sheet.createRow(rn++);
        cell = row.createCell(0);
        cell.setCellValue("?");
        cell.setCellStyle(headStyle);
        for (int i = 0; i < ac.length; i++) {
            cell = row.createCell(5 + i);
            cell.setCellValue(ac[i]);
            cell.setCellStyle(rightStyle);
        }
    }

    workbook.write(os);
    os.flush();
    os.close();
    return null;
}