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:net.sourceforge.fenixedu.presentationTier.Action.teacher.onlineTests.TestsManagementAction.java

public ActionForward showImage(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws FenixActionException {
    final String exerciseCode = getStringFromRequest(request, "exerciseCode");
    final Integer imgCode = getCodeFromRequest(request, "imgCode");
    final String imgTypeString = request.getParameter("imgType");
    final String studentCode = getStringFromRequest(request, "studentCode");
    final String optionShuffle = request.getParameter("optionShuffle");
    final String testCode = getStringFromRequest(request, "testCode");
    final Integer itemIndex = getCodeFromRequest(request, "item");
    final Integer feedbackCode = getCodeFromRequest(request, "feedbackCode");
    String img = null;//from   w w w . j a v a 2 s  . c o m
    if (studentCode != null && testCode != null) {
        try {
            img = ReadStudentTestQuestionImage.run(studentCode, testCode, exerciseCode, imgCode, feedbackCode,
                    itemIndex);
        } catch (FenixServiceException e) {
            throw new FenixActionException(e);
        }
    } else if (optionShuffle != null && !Strings.isNullOrEmpty(testCode)) {
        try {
            img = ReadQuestionImage.run(testCode, exerciseCode, optionShuffle, imgCode, feedbackCode);
        } catch (FenixServiceException e) {
            throw new FenixActionException(e);
        }
    } else {

        try {
            img = ReadQuestionImage.run(exerciseCode, imgCode, feedbackCode, itemIndex);
        } catch (FenixServiceException e) {
            throw new FenixActionException(e);
        }
    }
    byte[] imageData = BaseEncoding.base64().decode(img);
    try {
        response.reset();
        response.setContentType(imgTypeString);
        response.setContentLength(imageData.length);
        response.setBufferSize(imageData.length);
        String imageName = "image" + exerciseCode + imgCode + "."
                + imgTypeString.substring(imgTypeString.lastIndexOf("/") + 1, imgTypeString.length());
        response.setHeader("Content-disposition", "attachment; filename=" + imageName);
        DataOutputStream dataOut = new DataOutputStream(response.getOutputStream());
        dataOut.write(imageData);
        response.flushBuffer();
    } catch (java.io.IOException e) {
        throw new FenixActionException(e);
    }
    return null;
}

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

/**
 * Handles requests for user uploaded media file resources.
 *///from  w ww .j  a  v  a2s. c o  m
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    MediaFileManager mfMgr = WebloggerFactory.getWeblogger().getMediaFileManager();

    Weblog weblog = null;
    String ctx = request.getContextPath();
    String servlet = request.getServletPath();
    String reqURI = request.getRequestURI();

    WeblogMediaResourceRequest resourceRequest = null;
    try {
        // parse the incoming request and extract the relevant data
        resourceRequest = new WeblogMediaResourceRequest(request);

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

    } catch (Exception e) {
        // invalid resource request or weblog doesn't exist
        log.debug("error creating weblog resource request", e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    long resourceLastMod = 0;
    InputStream resourceStream = null;
    MediaFile mediaFile = null;

    try {
        mediaFile = mfMgr.getMediaFile(resourceRequest.getResourceId(), true);
        resourceLastMod = mediaFile.getLastModified();

    } catch (Exception ex) {
        // still not found? then we don't have it, 404.
        log.debug("Unable to get resource", ex);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Respond with 304 Not Modified if it is not modified.
    if (ModDateHeaderUtil.respondIfNotModified(request, response, resourceLastMod)) {
        return;
    } else {
        // set last-modified date
        ModDateHeaderUtil.setLastModifiedHeader(response, resourceLastMod);
    }

    // set the content type based on whatever is in our web.xml mime defs
    if (resourceRequest.isThumbnail()) {
        response.setContentType("image/png");
        try {
            resourceStream = mediaFile.getThumbnailInputStream();
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                log.debug("ERROR loading thumbnail for " + mediaFile.getId(), e);
            } else {
                log.warn("ERROR loading thumbnail for " + mediaFile.getId());
            }
        }
    }

    if (resourceStream == null) {
        response.setContentType(mediaFile.getContentType());
        resourceStream = mediaFile.getInputStream();
    }

    OutputStream out = null;
    try {
        // ok, lets serve up the file
        byte[] buf = new byte[8192];
        int length = 0;
        out = response.getOutputStream();
        while ((length = resourceStream.read(buf)) > 0) {
            out.write(buf, 0, length);
        }

        // close output stream
        out.close();

    } catch (Throwable ex) {
        log.error("ERROR", ex);
        if (!response.isCommitted()) {
            response.reset();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    } finally {
        // make sure stream to resource file is closed
        resourceStream.close();
    }

}

From source file:org.openmeetings.servlet.outputhandler.BackupExport.java

public void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        ServletContext servletCtx) throws ServletException, IOException {

    String sid = httpServletRequest.getParameter("sid");
    if (sid == null) {
        sid = "default";
    }// w  ww  . j  a  v a 2 s . c om
    log.debug("sid: " + sid);

    Long users_id = sessionManagement.checkSession(sid);
    Long user_level = userManagement.getUserLevelByID(users_id);

    log.debug("users_id: " + users_id);
    log.debug("user_level: " + user_level);

    if (authLevelManagement.checkAdminLevel(user_level)) {
        // if (true) {

        String includeFileOption = httpServletRequest.getParameter("includeFileOption");
        boolean includeFiles = includeFileOption == null || "yes".equals(includeFileOption);

        String moduleName = httpServletRequest.getParameter("moduleName");
        if (moduleName == null) {
            moduleName = "moduleName";
        }
        log.debug("moduleName: " + moduleName);

        if (moduleName.equals("backup")) {

            /*
             * ##################### Create Base Folder structure
             */

            String current_dir = servletCtx.getRealPath("/");
            File working_dir = new File(new File(current_dir, OpenmeetingsVariables.UPLOAD_DIR), "backup");

            if (!working_dir.exists()) {
                working_dir.mkdir();
            }

            String dateString = "backup_" + CalendarPatterns.getTimeForStreamId(new Date());

            File backup_dir = new File(working_dir, dateString);
            String requestedFile = dateString + ".zip";
            File backupFile = new File(backup_dir, requestedFile);

            String full_path = backupFile.getAbsolutePath();
            try {
                performExport(full_path, backup_dir, includeFiles, current_dir);

                RandomAccessFile rf = new RandomAccessFile(full_path, "r");

                httpServletResponse.reset();
                httpServletResponse.resetBuffer();
                httpServletResponse.setContentType("APPLICATION/OCTET-STREAM");
                httpServletResponse.setHeader("Content-Disposition",
                        "attachment; filename=\"" + requestedFile + "\"");
                httpServletResponse.setHeader("Content-Length", "" + rf.length());

                OutputStream out = httpServletResponse.getOutputStream();

                byte[] buffer = new byte[1024];
                int readed = -1;

                while ((readed = rf.read(buffer, 0, buffer.length)) > -1) {
                    out.write(buffer, 0, readed);
                }

                rf.close();

                out.flush();
                out.close();
            } catch (Exception er) {
                log.error("Error exporting: ", er);
            }

            if (backupFile.exists()) {
                // log.debug("DELETE :1: "+backupFile.getAbsolutePath());
                backupFile.delete();
            }

            deleteDirectory(backup_dir);

        }
    } else {
        log.debug("ERROR LangExport: not authorized FileDownload " + (new Date()));
    }
}

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

/**
 * Handles requests for user uploaded resources.
 *//*from   w ww . j  av  a2 s  .c  o  m*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Weblog weblog = null;
    String ctx = request.getContextPath();
    String servlet = request.getServletPath();
    String reqURI = request.getRequestURI();

    WeblogResourceRequest resourceRequest = null;
    try {
        // parse the incoming request and extract the relevant data
        resourceRequest = new WeblogResourceRequest(request);

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

    } catch (Exception e) {
        // invalid resource request or weblog doesn't exist
        log.debug("error creating weblog resource request", e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    log.debug("Resource requested [" + resourceRequest.getResourcePath() + "]");

    long resourceLastMod = 0;
    InputStream resourceStream = null;

    // first see if resource comes from weblog's shared theme
    try {
        WeblogTheme weblogTheme = weblog.getTheme();
        if (weblogTheme != null) {
            ThemeResource resource = weblogTheme.getResource(resourceRequest.getResourcePath());
            if (resource != null) {
                resourceLastMod = resource.getLastModified();
                resourceStream = resource.getInputStream();
            }
        }
    } catch (Exception ex) {
        // hmmm, some kind of error getting theme.  that's an error.
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    // if not from theme then see if resource is in weblog's upload dir
    if (resourceStream == null) {
        try {
            MediaFileManager mmgr = WebloggerFactory.getWeblogger().getMediaFileManager();
            MediaFile mf = mmgr.getMediaFileByOriginalPath(weblog, resourceRequest.getResourcePath());
            resourceLastMod = mf.getLastModified();
            resourceStream = mf.getInputStream();

        } catch (Exception ex) {
            // still not found? then we don't have it, 404.
            log.debug("Unable to get resource", ex);
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
    }

    // Respond with 304 Not Modified if it is not modified.
    if (ModDateHeaderUtil.respondIfNotModified(request, response, resourceLastMod)) {
        return;
    } else {
        // set last-modified date
        ModDateHeaderUtil.setLastModifiedHeader(response, resourceLastMod);
    }

    // set the content type based on whatever is in our web.xml mime defs
    response.setContentType(this.context.getMimeType(resourceRequest.getResourcePath()));

    OutputStream out = null;
    try {
        // ok, lets serve up the file
        byte[] buf = new byte[8192];
        int length = 0;
        out = response.getOutputStream();
        while ((length = resourceStream.read(buf)) > 0) {
            out.write(buf, 0, length);
        }

        // close output stream
        out.close();

    } catch (Exception ex) {
        if (!response.isCommitted()) {
            response.reset();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    } finally {
        // make sure stream to resource file is closed
        resourceStream.close();
    }

}

From source file:org.flowerplatform.util.servlet.PublicResourcesServlet.java

/**
* @author Cristian Spiescu/*from   w ww  .  ja v  a 2 s .c  om*/
* @author Sebastian Solomon
* @author Cristina Constantinescu
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String requestedFile = request.getPathInfo();
    if (logger.isTraceEnabled()) {
        logger.trace("Resource requested: {}", requestedFile);
    }

    // Check if file is actually supplied to the request URI.
    if (requestedFile == null) {
        send404(request, response);
        return;
    }

    // Decode the file name (might contain spaces and on) and prepare file object.

    // solution for: .../icons/0%.png
    // The URL decoder expects the %to precede a character code
    // replace(%) with %25 before decoding
    // http://stackoverflow.com/questions/6067673/urldecoder-illegal-hex-characters-in-escape-pattern-for-input-string
    requestedFile = requestedFile.replaceAll("%(?![0-9a-fA-F]{2})", "%25");

    requestedFile = URLDecoder.decode(requestedFile, "UTF-8");
    if (requestedFile.startsWith(UtilConstants.PUBLIC_RESOURCES_PATH_PREFIX)) {
        requestedFile = requestedFile.substring(UtilConstants.PUBLIC_RESOURCES_PATH_PREFIX.length());
    }

    // this may be an attempt to see files that are not public, i.e. to go to the
    // parent. From my tests, when you put in the browser (or even telnet) something like
    // parent1/parent2/../bla, it seems to be automatically translated to parent1/bla. However,
    // I wanted to make sure that we are all right
    if (requestedFile.contains("..")) {
        send404(request, response);
        return;
    }

    // we need something like /plugin/file....
    int indexOfSecondSlash = requestedFile.indexOf('/', 1); // 1, i.e. skip the first index
    if (indexOfSecondSlash < 0) {
        send404(request, response);
        return;
    }

    // both variables are prefixed with /
    String plugin = requestedFile.substring(0, indexOfSecondSlash);
    String file = requestedFile.substring(indexOfSecondSlash);

    // if | is supplied => the file is a zip, and we want what's in it
    int indexOfZipSeparator = file.indexOf(UtilConstants.RESOURCE_PATH_SEPARATOR);
    String fileInsideZipArchive = null;
    if (indexOfZipSeparator >= 0 && indexOfZipSeparator < file.length() - 1) { // has | and | is not the last char in the string
        fileInsideZipArchive = file.substring(indexOfZipSeparator + 1);
        file = file.substring(0, indexOfZipSeparator);
    }

    String mapValue = null;
    String mapKey = null;

    // if the file is in a zip, search first in the Temp folder
    if (fileInsideZipArchive != null) {
        mapKey = createMapKey(file, fileInsideZipArchive).intern();
        if (useFilesFromTemporaryDirectory) {
            mapValue = tempFilesMap.get(mapKey);
        }
    } else {
        // we don't need synchronization if the file is not inside archive (so we don't use .intern)
        mapKey = createMapKey(file, fileInsideZipArchive);
    }

    synchronized (mapKey) {
        if (useFilesFromTemporaryDirectory) {
            if (fileInsideZipArchive != null) {
                if (mapValue != null) { // file exists in 'tempFilesMap'
                    if (getTempFile(mapValue).exists()) {
                        response.reset();
                        response.setBufferSize(DEFAULT_BUFFER_SIZE);
                        response.setContentType(fileInsideZipArchive);
                        InputStream input = new FileInputStream(getTempFilePath(mapValue));
                        OutputStream output = response.getOutputStream();
                        IOUtils.copy(input, output);
                        input.close();
                        output.close();
                        logger.debug("File {} served from temp", mapValue);
                        return;
                    } else { // temporary file was deleted from disk
                        logger.debug("File {} found to be missing from temp", mapValue);
                    }
                } else {
                    synchronized (this) {
                        counter++;
                        mapValue = counter + "";
                        tempFilesMap.put(mapKey, mapValue);
                        logger.debug("mapValue '{}' added", mapValue);
                    }
                }
            }
        }

        requestedFile = "platform:/plugin" + plugin + "/" + UtilConstants.PUBLIC_RESOURCES_DIR + file;

        // Get content type by filename from the file or file inside zip
        String contentType = getServletContext()
                .getMimeType(fileInsideZipArchive != null ? fileInsideZipArchive : file);

        // If content type is unknown, then set the default value.
        // For all content types, see:
        // http://www.w3schools.com/media/media_mimeref.asp
        // To add new content types, add new mime-mapping entry in web.xml.
        if (contentType == null) {
            contentType = "application/octet-stream";
        }

        // Init servlet response.
        response.reset();
        response.setBufferSize(DEFAULT_BUFFER_SIZE);
        response.setContentType(contentType);
        //        response.setHeader("Content-Length", String.valueOf(file.length()));
        //        response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

        // Prepare streams.
        URL url;
        InputStream input = null;
        Closeable inputCloseable = null;
        OutputStream output = null;

        try {
            url = new URL(requestedFile);
            try {
                input = url.openConnection().getInputStream();
                inputCloseable = input;
            } catch (IOException e) {
                // may fail if the resource is not available
                send404(request, response);
                return;
            }

            if (fileInsideZipArchive != null) {
                // we need to look for a file in the archive
                Pair<InputStream, Closeable> pair = getInputStreamForFileWithinZip(input, fileInsideZipArchive);
                if (pair == null) {
                    // the file was not found; the input streams are closed in this case
                    send404(request, response);
                    return;
                }

                input = pair.a;
                inputCloseable = pair.b;

                if (useFilesFromTemporaryDirectory) {
                    // write the file from archive in Temp folder
                    if (!UtilConstants.TEMP_FOLDER.exists()) {
                        UtilConstants.TEMP_FOLDER.mkdir();
                    }

                    Files.copy(input, getTempFile(mapValue).toPath(), StandardCopyOption.REPLACE_EXISTING);
                    logger.debug("file '{}' was writen in temp", mapValue);

                    input.close();
                    input = new FileInputStream(getTempFilePath(mapValue));
                }
            }

            output = response.getOutputStream();

            // according to the doc, no need to use Buffered..., because the method buffers internally
            IOUtils.copy(input, output);

        } finally {
            // Gently close streams.
            close(output);
            close(inputCloseable);
            close(input);
        }
    }
}

From source file:fll.web.api.SubjectiveScoresServlet.java

@SuppressFBWarnings(value = {
        "SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING" }, justification = "columns and category are dynamic")
@Override/*from   ww  w  .j  a  v a2s .  c  o m*/
protected final void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException, ServletException {
    final ServletContext application = getServletContext();

    final DataSource datasource = ApplicationAttributes.getDataSource(application);
    Connection connection = null;
    PreparedStatement prep = null;
    ResultSet rs = null;
    try {
        connection = datasource.getConnection();

        final int currentTournament = Queries.getCurrentTournament(connection);

        // category->judge->teamNumber->score
        final Map<String, Map<String, Map<Integer, SubjectiveScore>>> allScores = new HashMap<String, Map<String, Map<Integer, SubjectiveScore>>>();

        final ChallengeDescription challengeDescription = ApplicationAttributes
                .getChallengeDescription(application);
        for (final ScoreCategory sc : challengeDescription.getSubjectiveCategories()) {
            // judge->teamNumber->score
            final Map<String, Map<Integer, SubjectiveScore>> categoryScores = new HashMap<String, Map<Integer, SubjectiveScore>>();

            prep = connection.prepareStatement("SELECT * FROM " + sc.getName() + " WHERE Tournament = ?");
            prep.setInt(1, currentTournament);

            rs = prep.executeQuery();
            while (rs.next()) {
                final SubjectiveScore score = new SubjectiveScore();
                score.setScoreOnServer(true);

                final String judge = rs.getString("Judge");
                final Map<Integer, SubjectiveScore> judgeScores;
                if (categoryScores.containsKey(judge)) {
                    judgeScores = categoryScores.get(judge);
                } else {
                    judgeScores = new HashMap<Integer, SubjectiveScore>();
                    categoryScores.put(judge, judgeScores);
                }

                score.setTeamNumber(rs.getInt("TeamNumber"));
                score.setJudge(judge);
                score.setNoShow(rs.getBoolean("NoShow"));
                score.setNote(rs.getString("note"));

                final Map<String, Double> standardSubScores = new HashMap<String, Double>();
                final Map<String, String> enumSubScores = new HashMap<String, String>();
                for (final AbstractGoal goal : sc.getGoals()) {
                    if (goal.isEnumerated()) {
                        final String value = rs.getString(goal.getName());
                        enumSubScores.put(goal.getName(), value);
                    } else {
                        final double value = rs.getDouble(goal.getName());
                        standardSubScores.put(goal.getName(), value);
                    }
                }
                score.setStandardSubScores(standardSubScores);
                score.setEnumSubScores(enumSubScores);

                judgeScores.put(score.getTeamNumber(), score);
            }

            allScores.put(sc.getName(), categoryScores);

            SQLFunctions.close(rs);
            rs = null;
            SQLFunctions.close(prep);
            prep = null;
        }

        final ObjectMapper jsonMapper = new ObjectMapper();

        response.reset();
        response.setContentType("application/json");
        final PrintWriter writer = response.getWriter();
        jsonMapper.writeValue(writer, allScores);

    } catch (final SQLException e) {
        throw new RuntimeException(e);
    } finally {
        SQLFunctions.close(rs);
        SQLFunctions.close(prep);
        SQLFunctions.close(connection);
    }

}

From source file:com.bst.tags.TableTag.java

/**
 * Will write the export. The default behavior is to write directly to the response. If the ResponseOverrideFilter
 * is configured for this request, will instead write the exported content to a map in the Request object.
 * @param exportView export view//from   w w w . ja v a2s  .co  m
 * @throws JspException for problem in clearing the response or for invalid export views
 * @throws IOException exception thrown when writing content to the response
 */
protected void writeExport(ExportView exportView) throws IOException, JspException {
    String filename = properties.getExportFileName(this.currentMediaType);

    HttpServletResponse response = (HttpServletResponse) this.pageContext.getResponse();
    HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest();

    Map bean = (Map) request.getAttribute(FILTER_CONTENT_OVERRIDE_BODY);
    boolean usingFilter = bean != null;

    String mimeType = exportView.getMimeType();
    // original encoding, be sure to add it back after reset()
    String characterEncoding = response.getCharacterEncoding();

    if (usingFilter) {
        if (!bean.containsKey(TableTagParameters.BEAN_BUFFER)) {
            // We are running under the export filter, call it
            log.debug("Exportfilter enabled in unbuffered mode, setting headers");
            response.addHeader(TableTagParameters.PARAMETER_EXPORTING, TagConstants.EMPTY_STRING);
        } else {
            // We are running under the export filter in buffered mode
            bean.put(TableTagParameters.BEAN_CONTENTTYPE, mimeType);
            bean.put(TableTagParameters.BEAN_FILENAME, filename);

            if (exportView instanceof TextExportView) {
                StringWriter writer = new StringWriter();
                ((TextExportView) exportView).doExport(writer);
                bean.put(TableTagParameters.BEAN_BODY, writer.toString());
            } else if (exportView instanceof BinaryExportView) {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                ((BinaryExportView) exportView).doExport(stream);
                bean.put(TableTagParameters.BEAN_BODY, stream.toByteArray());

            } else {
                throw new JspTagException("Export view " + exportView.getClass().getName()
                        + " must implement TextExportView or BinaryExportView");
            }

            return;
        }
    } else {
        log.debug("Exportfilter NOT enabled");
        // response can't be already committed at this time
        if (response.isCommitted()) {
            throw new ExportException(getClass());
        }

        try {
            response.reset();
            pageContext.getOut().clearBuffer();
        } catch (Exception e) {
            throw new ExportException(getClass());
        }
    }

    if (!usingFilter && characterEncoding != null && mimeType.indexOf("charset") == -1) //$NON-NLS-1$
    {
        mimeType += "; charset=" + characterEncoding; //$NON-NLS-1$
    }

    response.setContentType(mimeType);

    if (StringUtils.isNotEmpty(filename)) {
        response.setHeader("Content-Disposition", //$NON-NLS-1$
                "attachment; filename=\"" + filename + "\""); //$NON-NLS-1$ //$NON-NLS-2$
    }

    if (exportView instanceof TextExportView) {
        Writer writer;
        if (usingFilter) {
            writer = response.getWriter();
        } else {
            writer = pageContext.getOut();
        }

        ((TextExportView) exportView).doExport(writer);
    } else if (exportView instanceof BinaryExportView) {
        // dealing with binary content
        // note that this is not assured to work on any application server if the filter is not enabled. According
        // to the jsp specs response.getOutputStream() should no be called in jsps.
        ((BinaryExportView) exportView).doExport(response.getOutputStream());
    } else {
        throw new JspTagException("Export view " + exportView.getClass().getName()
                + " must implement TextExportView or BinaryExportView");
    }

    log.debug("Export completed");

}

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

/**
 * Handle GET requests for weblog pages.
 */// w ww.ja va  2 s. c  o m
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("Entering");

    Weblog weblog = null;

    WeblogPreviewRequest previewRequest = null;

    String type = null;

    try {
        previewRequest = new WeblogPreviewRequest(request);

        // type of the page we are going to preview
        type = previewRequest.getType();

        // lookup weblog specified by preview request
        weblog = previewRequest.getWeblog();
        if (weblog == null) {
            throw new WebloggerException("unable to lookup weblog: " + previewRequest.getWeblogHandle());
        }
    } catch (Exception e) {
        // some kind of error parsing the request or getting weblog
        log.debug("error creating preview request", e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Get the deviceType from user agent
    MobileDeviceRepository.DeviceType deviceType = MobileDeviceRepository.getRequestType(request);

    // for previews we explicitly set the deviceType attribute
    if (request.getParameter("type") != null) {
        deviceType = request.getParameter("type").equals("standard")
                ? MobileDeviceRepository.DeviceType.standard
                : MobileDeviceRepository.DeviceType.mobile;
    }

    Weblog tmpWebsite = weblog;

    if (previewRequest.getThemeName() != null) {
        // only create temporary weblog object if theme name was specified
        // in request, which indicates we're doing a theme preview

        // try getting the preview theme
        log.debug("preview theme = " + previewRequest.getThemeName());
        Theme previewTheme = previewRequest.getTheme();

        // construct a temporary Website object for this request
        // and set the EditorTheme to our previewTheme
        tmpWebsite = new Weblog();
        tmpWebsite.setData(weblog);
        if (previewTheme != null && previewTheme.isEnabled()) {
            tmpWebsite.setEditorTheme(previewTheme.getId());
        } else if (WeblogTheme.CUSTOM.equals(previewRequest.getThemeName())) {
            tmpWebsite.setEditorTheme(WeblogTheme.CUSTOM);
        }

        // we've got to set the weblog in our previewRequest because that's
        // the object that gets referenced during rendering operations
        previewRequest.setWeblog(tmpWebsite);
    }

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

    Template page = null;
    if ("page".equals(previewRequest.getContext())) {
        page = previewRequest.getWeblogPage();

        // If request specified tags section index, then look for custom template
    } else if ("tags".equals(previewRequest.getContext()) && previewRequest.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 (previewRequest.getWeblogAnchor() != null) {
        try {
            page = weblog.getTheme().getTemplateByAction(ThemeTemplate.ACTION_PERMALINK);
        } catch (Exception e) {
            log.error("Error getting weblog page for action 'permalink'", e);
        }
    }

    if (page == null) {
        try {
            page = tmpWebsite.getTheme().getDefaultTemplate();
        } catch (WebloggerException re) {
            log.error("Error getting default page for preview", re);
        }
    }

    // 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("preview page found, dealing with it");

    // set the content type
    String pageLink = previewRequest.getWeblogPageName();
    String mimeType = pageLink != null ? RollerContext.getServletContext().getMimeType(pageLink) : null;
    String contentType = "text/html; charset=utf-8";
    if (mimeType != null) {
        // we found a match ... set the content type
        contentType = mimeType + "; charset=utf-8";
    } else if ("_css".equals(previewRequest.getWeblogPageName())) {
        // TODO: store content-type for each page so this hack is unnecessary
        contentType = "text/css; charset=utf-8";
    }

    // looks like we need to render content
    Map model = new HashMap();
    try {
        PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(this, request, response, "",
                false, 8192, true);

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

        // populate the rendering model
        Map initData = new HashMap();
        initData.put("parsedRequest", previewRequest);
        initData.put("pageContext", pageContext);

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

        // Load models for page previewing
        String pageModels = WebloggerConfig.getProperty("rendering.previewModels");
        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, previewRequest, WebloggerFactory
                .getWeblogger().getUrlStrategy().getPreviewURLStrategy(previewRequest.getThemeName()));

    } catch (WebloggerException ex) {
        log.error("ERROR loading model 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, deviceType);
    } 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 default size of about 24K for a standard page
    CachedContent rendererOutput = new CachedContent(24567);
    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());

    log.debug("Exiting");
}

From source file:org.displaytag.tags.TableTag.java

/**
 * Will write the export. The default behavior is to write directly to the response. If the ResponseOverrideFilter
 * is configured for this request, will instead write the exported content to a map in the Request object.
 * /*from  w  w w . ja v a2  s .c  om*/
 * @param exportView export view
 * @throws JspException for problem in clearing the response or for invalid export views
 * @throws IOException exception thrown when writing content to the response
 */
protected void writeExport(ExportView exportView) throws IOException, JspException {
    String filename = this.properties.getExportFileName(this.currentMediaType);

    HttpServletResponse response = (HttpServletResponse) this.pageContext.getResponse();
    HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest();

    Map bean = (Map) request.getAttribute(FILTER_CONTENT_OVERRIDE_BODY);
    boolean usingFilter = bean != null;

    String mimeType = exportView.getMimeType();
    // original encoding, be sure to add it back after reset()
    String characterEncoding = response.getCharacterEncoding();

    if (usingFilter) {
        if (!bean.containsKey(TableTagParameters.BEAN_BUFFER)) {
            // We are running under the export filter, call it
            log.debug("Exportfilter enabled in unbuffered mode, setting headers");
            response.addHeader(TableTagParameters.PARAMETER_EXPORTING, TagConstants.EMPTY_STRING);
        } else {
            // We are running under the export filter in buffered mode
            bean.put(TableTagParameters.BEAN_CONTENTTYPE, mimeType);
            bean.put(TableTagParameters.BEAN_FILENAME, filename);

            if (exportView instanceof TextExportView) {
                StringWriter writer = new StringWriter();
                ((TextExportView) exportView).doExport(writer);
                bean.put(TableTagParameters.BEAN_BODY, writer.toString());
            } else if (exportView instanceof BinaryExportView) {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                ((BinaryExportView) exportView).doExport(stream);
                bean.put(TableTagParameters.BEAN_BODY, stream.toByteArray());

            } else {
                throw new JspTagException("Export view " + exportView.getClass().getName()
                        + " must implement TextExportView or BinaryExportView");
            }

            return;
        }
    } else {
        log.debug("Exportfilter NOT enabled");
        // response can't be already committed at this time
        if (response.isCommitted()) {
            throw new ExportException(this.getClass());
        }

        try {
            response.reset();
            this.pageContext.getOut().clearBuffer();
        } catch (Exception e) {
            throw new ExportException(this.getClass());
        }
    }

    if (!usingFilter && characterEncoding != null && mimeType.indexOf("charset") == -1) //$NON-NLS-1$
    {
        mimeType += "; charset=" + characterEncoding; //$NON-NLS-1$
    }

    response.setContentType(mimeType);

    if (StringUtils.isNotEmpty(filename)) {
        response.setHeader("Content-Disposition", //$NON-NLS-1$
                "attachment; filename=\"" + filename + "\""); //$NON-NLS-1$ //$NON-NLS-2$
    }

    if (exportView instanceof TextExportView) {
        Writer writer;
        if (usingFilter) {
            writer = response.getWriter();
        } else {
            writer = this.pageContext.getOut();
        }

        ((TextExportView) exportView).doExport(writer);
    } else if (exportView instanceof BinaryExportView) {
        // dealing with binary content
        // note that this is not assured to work on any application server
        // if the filter is not enabled. According
        // to the jsp specs response.getOutputStream() should no be called
        // in jsps.
        ((BinaryExportView) exportView).doExport(response.getOutputStream());
    } else {
        throw new JspTagException("Export view " + exportView.getClass().getName()
                + " must implement TextExportView or BinaryExportView");
    }

    log.debug("Export completed");

}

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

/**
 * Handles requests for user uploaded resources.
 *//*w  ww .  jav a2s. c om*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Weblog weblog = null;
    String ctx = request.getContextPath();
    String servlet = request.getServletPath();
    String reqURI = request.getRequestURI();

    WeblogPreviewResourceRequest resourceRequest = null;
    try {
        // parse the incoming request and extract the relevant data
        resourceRequest = new WeblogPreviewResourceRequest(request);

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

    } catch (Exception e) {
        // invalid resource request or weblog doesn't exist
        log.debug("error creating weblog resource request", e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    log.debug("Resource requested [" + resourceRequest.getResourcePath() + "]");

    long resourceLastMod = 0;
    InputStream resourceStream = null;

    // first, see if we have a preview theme to operate from
    if (!StringUtils.isEmpty(resourceRequest.getThemeName())) {
        Theme theme = resourceRequest.getTheme();
        ThemeResource resource = theme.getResource(resourceRequest.getResourcePath());
        if (resource != null) {
            resourceLastMod = resource.getLastModified();
            resourceStream = resource.getInputStream();
        }
    }

    // second, see if resource comes from weblog's configured shared theme
    if (resourceStream == null) {
        try {
            WeblogTheme weblogTheme = weblog.getTheme();
            if (weblogTheme != null) {
                ThemeResource resource = weblogTheme.getResource(resourceRequest.getResourcePath());
                if (resource != null) {
                    resourceLastMod = resource.getLastModified();
                    resourceStream = resource.getInputStream();
                }
            }
        } catch (Exception ex) {
            // hmmm, some kind of error getting theme.  that's an error.
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
    }

    // if not from theme then see if resource is in weblog's upload dir
    if (resourceStream == null) {
        try {
            MediaFileManager mmgr = WebloggerFactory.getWeblogger().getMediaFileManager();
            MediaFile mf = mmgr.getMediaFileByOriginalPath(weblog, resourceRequest.getResourcePath());
            resourceLastMod = mf.getLastModified();
            resourceStream = mf.getInputStream();

        } catch (Exception ex) {
            // still not found? then we don't have it, 404.
            log.debug("Unable to get resource", ex);
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
    }

    // Respond with 304 Not Modified if it is not modified.
    if (ModDateHeaderUtil.respondIfNotModified(request, response, resourceLastMod)) {
        return;
    } else {
        // set last-modified date
        ModDateHeaderUtil.setLastModifiedHeader(response, resourceLastMod);
    }

    // set the content type based on whatever is in our web.xml mime defs
    response.setContentType(this.context.getMimeType(resourceRequest.getResourcePath()));

    OutputStream out = null;
    try {
        // ok, lets serve up the file
        byte[] buf = new byte[8192];
        int length = 0;
        out = response.getOutputStream();
        while ((length = resourceStream.read(buf)) > 0) {
            out.write(buf, 0, length);
        }

        // cleanup
        out.close();
        resourceStream.close();

    } catch (Exception ex) {
        log.error("Error writing resource file", ex);
        if (!response.isCommitted()) {
            response.reset();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

}