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.apache.roller.weblogger.ui.rendering.servlets.PreviewThemeImageServlet.java

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

    String theme = request.getParameter("theme");

    log.debug("Theme requested [" + theme + "]");

    long resourceLastMod = 0;
    InputStream resourceStream = null;
    String previewImagePath = null;

    // try looking up selected theme
    try {
        ThemeManager tmgr = WebloggerFactory.getWeblogger().getThemeManager();
        SharedTheme previewTheme = tmgr.getTheme(theme);
        ThemeResource previewImage = previewTheme.getPreviewImage();
        if (previewImage != null) {
            previewImagePath = previewImage.getPath();
            resourceLastMod = previewImage.getLastModified();
            resourceStream = previewImage.getInputStream();
        }
    } catch (Exception ex) {
        log.debug("error looking up preview image", ex);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // if we don't have a stream to the file then we can't continue
    if (resourceStream == null) {
        log.debug("Unable to get theme preview for theme - " + theme);
        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);
    }

    log.debug("Everything is cool, sending image");

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

    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);
        }
    }

}

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

@Override
protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    try {//from   w ww  .  ja v a2  s.c  o  m

        if (getUserManagement() == null || getSessionManagement() == null || getUsersDao() == null) {
            return;
        }

        String sid = httpServletRequest.getParameter("sid");
        if (sid == null) {
            sid = "default";
        }
        System.out.println("sid: " + sid);

        Long users_id = getSessionManagement().checkSession(sid);
        Long user_level = getUserManagement().getUserLevelByID(users_id);

        System.out.println("users_id: " + users_id);
        System.out.println("user_level: " + user_level);

        // if (user_level!=null && user_level > 0) {
        if (getAuthLevelManagement().checkUserLevel(user_level)) {

            String moduleName = httpServletRequest.getParameter("moduleName");
            if (moduleName == null) {
                moduleName = "moduleName";
            }
            System.out.println("moduleName: " + moduleName);

            if (moduleName.equals("users") || moduleName.equals("userorganisations")) {
                String organisation = httpServletRequest.getParameter("organisation");
                if (organisation == null) {
                    organisation = "0";
                }
                Long organisation_id = Long.valueOf(organisation).longValue();
                System.out.println("organisation_id: " + organisation_id);

                List<Users> uList = null;
                String downloadName = "users";
                if (moduleName.equals("userorganisations")) {
                    Organisation orga = getOrganisationmanagement().getOrganisationById(organisation_id);
                    downloadName += "_" + orga.getName();
                    uList = getOrganisationmanagement().getUsersByOrganisationId(organisation_id);
                } else {
                    uList = getUsersDao().getAllUsers();
                }

                if (uList != null) {
                    Document doc = this.createDocument(uList);

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

                    this.serializetoXML(out, "UTF-8", doc);

                    out.flush();
                    out.close();
                }

            }
        } else {
            System.out.println("ERROR LangExport: not authorized FileDownload " + (new Date()));
        }
    } catch (Exception er) {
        log.error("ERROR ", er);
        System.out.println("Error exporting: " + er);
        er.printStackTrace();
    }
}

From source file:org.apache.roller.planet.ui.rendering.servlets.FeedServlet.java

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

    log.debug("Entering");

    Planet planet = null;
    PlanetGroup group = null;

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

        planet = feedRequest.getPlanet();
        if (planet == null) {
            throw new PlanetException("unable to lookup planet: " + feedRequest.getPlanetHandle());
        }

        group = feedRequest.getGroup();
        if (group == null) {
            throw new PlanetException("unable to lookup group: " + feedRequest.getGroupHandle());
        }

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

    // set content type
    String accepts = request.getHeader("Accept");
    String userAgent = request.getHeader("User-Agent");
    if (accepts != null && accepts.indexOf("*/*") != -1 && userAgent != null
            && userAgent.startsWith("Mozilla")) {
        // client is a browser and feed style is enabled so we want 
        // browsers to load the page rather than popping up the download 
        // dialog, so we provide a content-type that browsers will display
        response.setContentType("text/xml");
    } else if ("rss".equals(feedRequest.getFormat())) {
        response.setContentType("application/rss+xml; charset=utf-8");
    } else if ("atom".equals(feedRequest.getFormat())) {
        response.setContentType("application/atom+xml; charset=utf-8");
    }

    // looks like we need to render content
    HashMap model = new HashMap();
    try {
        // populate the rendering model
        Map initData = new HashMap();
        initData.put("planetRequest", feedRequest);

        // Load models for feeds
        String feedModels = PlanetConfig.getProperty("rendering.feedModels");
        ModelLoader.loadModels(feedModels, model, initData, true);

    } catch (PlanetException 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");

        String templateFile = null;
        if ("rss".equals(feedRequest.getFormat())) {
            templateFile = "group-rss.vm";
        } else if ("atom".equals(feedRequest.getFormat())) {
            templateFile = "group-atom.vm";
        }

        Template template = new StaticTemplate(templateFile, null, "velocity");
        renderer = RendererManager.getRenderer(template);
    } catch (Exception e) {
        // nobody wants to render my content :(

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

    // render content.  use default size of about 24K for a standard page
    try {
        log.debug("Doing rendering");
        renderer.render(model, response.getWriter());
    } catch (Exception e) {
        // bummer, error during rendering
        log.error("Error during rendering for group-atom.vm", 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.setContentLength(rendererOutput.getContent().length);
    //response.getOutputStream().write(rendererOutput.getContent());

    log.debug("Exiting");
}

From source file:mercury.DigitalMediaController.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
        try {/*w  w w . java  2  s  .co  m*/
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();

            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (!item.isFormField()) {
                    Integer serial = (new DigitalMediaDAO()).uploadToDigitalMedia(item);

                    String filename = item.getName();
                    if (filename.lastIndexOf('\\') != -1) {
                        filename = filename.substring(filename.lastIndexOf('\\') + 1);
                    }
                    if (filename.lastIndexOf('/') != -1) {
                        filename = filename.substring(filename.lastIndexOf('/') + 1);
                    }

                    String id = serial + ":" + filename;
                    String encodedId = new String(new Base64().encode(id.getBytes()));
                    encodedId = encodedId.replaceAll("\\\\", "_");
                    if (serial != null && serial != 0) {
                        response.getWriter().write("{success: true, id: \"" + encodedId + "\"}");
                        return;
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        response.getWriter().write("{success: false}");
    } else {
        String decodedId = null;
        DigitalMediaDTO dto = null;

        try {
            String id = request.getParameter("id");
            id = id.replaceAll("_", "\\\\");
            decodedId = new String(new Base64().decode(id.getBytes()));

            String[] splitId = decodedId.split(":");
            if (splitId.length == 2 && splitId[0].matches("^\\d+$")) {
                dto = (new DigitalMediaDAO()).getDigitalMedia(Integer.valueOf(splitId[0]), splitId[1]);
            }
        } catch (Exception e) {
            // dto should be null here
        }

        InputStream in = null;
        byte[] bytearray = null;
        int length = 0;
        String defaultFile = request.getParameter("default");
        response.reset();
        try {
            if (dto != null && dto.getIn() != null) {
                response.setContentType(dto.getMimeType());
                response.setHeader("Content-Disposition", "filename=" + dto.getFileName());
                length = dto.getLength();
                in = dto.getIn();
            }

            if (in == null && StringUtils.isNotBlank(defaultFile)) {
                String path = getServletContext().getRealPath("/");
                File file = new File(path + defaultFile);
                length = (int) file.length();
                in = new FileInputStream(file);
            }

            if (in != null) {
                bytearray = new byte[length];
                int index = 0;
                OutputStream os = response.getOutputStream();
                while ((index = in.read(bytearray)) != -1) {
                    os.write(bytearray, 0, index);
                }
                in.close();
            } else {
                response.getWriter().write("{success: false}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("{success: false}");
        }
        response.flushBuffer();
    }
}

From source file:org.tightblog.rendering.processors.MediaFileProcessor.java

@RequestMapping(method = { RequestMethod.GET, RequestMethod.HEAD })
void getMediaFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
    WeblogRequest incomingRequest = WeblogRequest.create(request);

    Weblog weblog = weblogRepository.findByHandleAndVisibleTrue(incomingRequest.getWeblogHandle());
    if (weblog == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;/*w w w.  j av  a2  s  .  c  o  m*/
    } else {
        incomingRequest.setWeblog(weblog);
    }

    MediaFile mediaFile = null;
    // path info here is the resourceId
    String pathInfo = incomingRequest.getExtraPathInfo();
    if (StringUtils.isNotBlank(pathInfo)) {
        mediaFile = mediaManager.getMediaFileWithContent(pathInfo);
    }

    if (mediaFile == null) {
        log.info("Could not obtain media file for resource path: ", request.getRequestURL());
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    weblogMediaCache.incrementIncomingRequests();

    // DB stores last modified in millis, browser if-modified-since in seconds, so need to truncate millis from the former.
    long inDb = mediaFile.getLastUpdated().truncatedTo(ChronoUnit.SECONDS).toEpochMilli();
    long inBrowser = getBrowserCacheExpireDate(request);

    if (inDb <= inBrowser) {
        weblogMediaCache.incrementRequestsHandledBy304();
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    boolean useThumbnail = false;
    if (mediaFile.isImageFile() && "true".equals(request.getParameter("tn"))) {
        useThumbnail = true;
    }

    File desiredFile = useThumbnail ? mediaFile.getThumbnail() : mediaFile.getContent();
    if (desiredFile == null) {
        log.info("Could not obtain {} file content for resource path: ", useThumbnail ? "thumbnail" : "",
                request.getRequestURL());
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    try (InputStream resourceStream = new FileInputStream(desiredFile);
            OutputStream out = response.getOutputStream()) {

        byte[] buf = new byte[Utilities.EIGHT_KB_IN_BYTES];
        int length;
        while ((length = resourceStream.read(buf)) > 0) {
            out.write(buf, 0, length);
        }
        response.setContentType(useThumbnail ? MediaFile.THUMBNAIL_CONTENT_TYPE : mediaFile.getContentType());
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Last-Modified", mediaFile.getLastUpdated().toEpochMilli());
    } catch (IOException ex) {
        log.error("Error obtaining media file {}", desiredFile.getAbsolutePath(), ex);
        if (!response.isCommitted()) {
            response.reset();
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
}

From source file:org.flowerplatform.communication.public_resources.PublicResourcesServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String requestedFile = request.getPathInfo();
    if (logger.isTraceEnabled()) {
        logger.trace("Resource requested: {}", requestedFile);
    }//from  w  ww  . j a v  a2s  . c om

    // 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.
    requestedFile = URLDecoder.decode(requestedFile, "UTF-8");
    if (requestedFile.startsWith(PATH_PREFIX)) {
        requestedFile = requestedFile.substring(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('|');
    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);
    }

    requestedFile = "platform:/plugin" + plugin + "/" + AbstractFlowerJavaPlugin.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;
        }

        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);
    }

}

From source file:org.wings.externalizer.AbstractExternalizeManager.java

public void deliver(ExternalizedResource extInfo, HttpServletResponse response, Device out) throws IOException {
    /* FIXME: re-implement.
    if ( extInfo.deliverOnce() ) {//ww w . j  a  v a  2s  .  c om
    removeExternalizedResource(identifier);
    }
    */

    if (extInfo.getMimeType() != null) {
        response.setContentType(extInfo.getMimeType());
    }

    // FIXME find out, if this is correct: if the content length
    // is not size preserving (like a gzip-device), then we must not
    // send the content size we know..
    if (out.isSizePreserving()) {
        int resourceLen = extInfo.getExternalizer().getLength(extInfo.getObject());
        if (resourceLen > 0) {
            LOG.debug(extInfo.getMimeType() + ": " + resourceLen);
            response.setContentLength(resourceLen);
        }
    }

    Collection headers = extInfo.getHeaders();
    if (headers != null) {
        for (Object header : headers) {
            Map.Entry entry = (Map.Entry) header;
            if (entry.getValue() instanceof String) {
                response.addHeader((String) entry.getKey(), (String) entry.getValue());
            } else if (entry.getValue() instanceof Date) {
                response.addDateHeader((String) entry.getKey(), ((Date) entry.getValue()).getTime());

            } else if (entry.getValue() instanceof Integer) {
                response.addIntHeader((String) entry.getKey(), ((Integer) entry.getValue()).intValue());

            } // end of if ()
        }
    }

    if (!response.containsHeader("Expires")) {
        /*
        * This would be the correct way to do it; alas, that means, that
        * for static resources, after a day or so, no caching could take
        * place, since the last modification was at the first time, the
        * resource was externalized (since it doesn't change).
        * .. have to think about it.
        */
        //response.setDateHeader("Expires",
        //                      (1000*FINAL_EXPIRES)
        //                       + extInfo.getLastModified());
        // .. so do this for now, which is the best approximation of what
        // we want.
        response.setDateHeader("Expires", System.currentTimeMillis() + (1000 * FINAL_EXPIRES));
    }

    try {
        extInfo.getExternalizer().write(extInfo.getObject(), out);
    } catch (ResourceNotFoundException e) {
        LOG.debug("Unable to deliver resource due to:  " + e.getMessage() + ". Sending 404!");
        response.reset();
        response.sendError(404, e.getMessage());
    }
    out.flush();
}

From source file:com.aurel.track.admin.customize.category.report.execute.ReportExecuteBL.java

/**
 * Serializes the data source into the response's output stream using a
 * ReportExporter/*ww  w .jav a2  s.  c  o  m*/
 *
 * @param templateID
 * @param datasource
 * @return
 */
static String prepareReportResponse(HttpServletResponse response, Integer templateID,
        Map<String, Object> contextMap, Map<String, Object> description, Object datasource,
        Map<String, Object> parameters, ServletContext servletContext, TPersonBean personBean, Locale locale) {
    URL baseURL = null;
    String logoFolder = null;
    URL completeURL = null;
    String baseFileName = null;
    if (templateID == null) {
        final String baseFolder = "/design/silver/";
        // direct pdf/xls from report overview
        try {
            // set the baseURL to take some standard icons from
            // "/design/silver/icons"
            // which ale already used by the report overview anyway
            baseURL = servletContext.getResource(baseFolder + "16x16");
            LOGGER.debug("baseURL: " + baseURL.toString());
        } catch (final MalformedURLException e) {
            LOGGER.error("Getting the baseURL for " + baseFolder + "16x16 failed with " + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
        // set the baseURL to take some standard icons from
        // "/design/silver/icons"
        // which ale already used by the report overview anyway
        logoFolder = HandleHome.getTrackplus_Home() + File.separator + HandleHome.LOGOS_DIR + File.separator;
    } else {
        // template exists
        final File template = ReportBL.getDirTemplate(templateID);
        final ILabelBean templateBean = ReportFacade.getInstance().getByKey(templateID);
        if (templateBean != null) {
            baseFileName = templateBean.getLabel();
        }
        try {
            baseURL = template.toURL();
            LOGGER.debug("baseURL: " + baseURL.toString());
        } catch (final MalformedURLException e) {
            LOGGER.error("Wrong template URL for " + template.getName() + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
            return null;
        }
        try {
            completeURL = new URL(baseURL.toExternalForm() /*
                                                           * +
                                                           * "/"File.separator
                                                           */
                    + description.get(IDescriptionAttributes.MASTERFILE));
            completeURL.openStream();
            LOGGER.debug("completeURL: " + completeURL.toString());
        } catch (final Exception me) {
            LOGGER.error(LocalizeUtil.getParametrizedString(
                    "report.reportExportManager.err.masterFileTemplateNotFound",
                    new String[] { me.getMessage() }, locale) + me);
            return null;
        }
    }
    if (parameters == null) {
        parameters = new HashMap<String, Object>();
    }
    parameters.put(JasperReportExporter.REPORT_PARAMETERS.BASE_URL, baseURL);
    if (logoFolder != null) {
        parameters.put(JasperReportExporter.REPORT_PARAMETERS.LOGO_FOLDER_URL, logoFolder);
    }
    if (completeURL != null) {
        parameters.put(JasperReportExporter.REPORT_PARAMETERS.COMPLETE_URL, completeURL);
    }
    if (baseFileName == null) {
        baseFileName = "TrackReport";
    }
    baseFileName += DateTimeUtils.getInstance().formatISODateTime(new Date());
    response.reset();
    final String format = (String) description.get(IDescriptionAttributes.FORMAT);
    if (ReportExporter.FORMAT_PDF.equals(format)) {
        response.setHeader("Content-Type", "application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".pdf\"");
    } else if (ReportExporter.FORMAT_RTF.equals(format)) {
        response.setHeader("Content-Type", "application/rtf");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".rtf\"");
    } else if (ReportExporter.FORMAT_XML.equals(format)) {
        response.setHeader("Content-Type", "text/xml");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".xml\"");
    } else if (ReportExporter.FORMAT_HTML.equals(format)) {
        response.setHeader("Content-Type", "text/html");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".html\"");
    } else if (ReportExporter.FORMAT_ZIP.equals(format)) {
        response.setHeader("Content-Type", "application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".zip\"");
    } else if (ReportExporter.FORMAT_XLS.equals(format)) {
        response.setHeader("Content-Type", "application/xls");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".xls\"");
    } else if (ReportExporter.FORMAT_CSV.equals(format)) {
        final String csvEncoding = personBean.getCsvEncoding();
        LOGGER.debug("csvEncoding is " + csvEncoding);
        if (csvEncoding != null) {
            response.setContentType("text/plain; " + csvEncoding);
        } else {
            response.setContentType("text/plain; charset=UTF-8");
        }
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".csv\"");
    } else if (ReportExporter.FORMAT_DOCX.equals(format)) {
        response.setHeader("Content-Type",
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".docx\"");
    }
    DownloadUtil.prepareCacheControlHeader(ServletActionContext.getRequest(), response);
    OutputStream outputStream = null;
    try {
        outputStream = response.getOutputStream();
    } catch (final IOException e) {
        LOGGER.error("Getting the output stream failed with " + e.getMessage());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    }
    try {
        LOGGER.debug("Exporter type is " + description.get(IDescriptionAttributes.TYPE) + " exporter format is "
                + description.get(IDescriptionAttributes.FORMAT));
        final ReportExporter exporter = ReportExecuteBL
                .getExporter((String) description.get(IDescriptionAttributes.TYPE));
        exporter.exportReport((Document) datasource, personBean, locale, parameters, outputStream, contextMap,
                description);
        LOGGER.debug("Export done...");
    } catch (final ReportExportException e) {
        LOGGER.error("Exporting the report failed with " + e.getMessage());
        String actionMessage = "";
        if (e.getCause() != null) {
            actionMessage = LocalizeUtil.getParametrizedString(e.getMessage(),
                    new String[] { e.getCause().getMessage() }, locale);
        } else {
            actionMessage = LocalizeUtil.getLocalizedTextFromApplicationResources(e.getMessage(), locale);
        }
        LOGGER.error(actionMessage);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    } catch (final Exception e) {
        LOGGER.error("Exporting the report failed with throwable " + e.getMessage());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    }
    return null;
}

From source file:servlets.Samples_servlets.java

private void send_biocondition_template_document_handler(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    try {/* w w w .  ja  v a  2s  . c om*/

        ArrayList<String> BLOCKED_IDs = new ArrayList<String>();
        boolean ROLLBACK_NEEDED = false;
        DAO dao_instance = null;

        try {
            if (!ServletFileUpload.isMultipartContent(request)) {
                throw new Exception("Erroneus request.");
            }

            String user_id = "";
            String sessionToken = "";
            File xls_file = null;

            /**
             * *******************************************************
             * STEP 1 Get the request params: read the params and the XLS
             * file. IF ERROR --> throws SQL Exception, GO TO STEP ? ELSE
             * --> GO TO STEP 9
             * *******************************************************
             */
            response.reset();
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.setContentType("text/html");

            //Get the data as a JSON format string
            final String CACHE_PATH = "/tmp/";
            final int CACHE_SIZE = 100 * (int) Math.pow(10, 6);
            final int MAX_REQUEST_SIZE = 20 * (int) Math.pow(10, 6);
            final int MAX_FILE_SIZE = 20 * (int) Math.pow(10, 6);

            // Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // Set factory constraints
            factory.setRepository(new File(CACHE_PATH));
            factory.setSizeThreshold(CACHE_SIZE);

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // Set overall request size constraint
            upload.setSizeMax(MAX_REQUEST_SIZE);
            upload.setFileSizeMax(MAX_FILE_SIZE);

            // Parse the request
            List<FileItem> items = upload.parseRequest(request);

            for (FileItem item : items) {
                if (!item.isFormField()) {
                    if (!item.getName().equals("")) {
                        //First check if the file already exists -> error, probably a previous treatmente exists with the same treatment_id
                        xls_file = new File(CACHE_PATH + "tmp.xls");
                        item.write(xls_file);
                    }
                } else {
                    String name = item.getFieldName();
                    String value = item.getString();
                    if ("loggedUser".equals(name)) {
                        user_id = value;
                    } else if ("sessionToken".equals(name)) {
                        sessionToken = value;
                    }
                }
            }

            /**
             * *******************************************************
             * STEP 2 CHECK IF THE USER IS LOGGED CORRECTLY IN THE APP AND
             * IF FILE IS CORRECTLY UPDATED. IF ERROR --> throws exception
             * if not valid session, GO TO STEP 6b ELSE --> GO TO STEP 3
             * *******************************************************
             */
            if (!checkAccessPermissions(user_id, sessionToken)) {
                throw new AccessControlException("Your session is invalid. User or session token not allowed.");
            }
            if (xls_file == null) {
                throw new Exception("XLS file was not uploaded correctly.");
            }

            /**
             * *******************************************************
             * STEP 2 Parse the XLS file and get the information. IF ERROR
             * --> throws Exception, GO TO STEP ? ELSE --> GO TO STEP 3
             * *******************************************************
             */
            Object[] parsingResult = BioCondition_XLS_parser.parseXLSfile(xls_file, user_id);

            ArrayList<BioCondition> biocondition_list = (ArrayList<BioCondition>) parsingResult[0];
            HashMap<String, Batch> batchesTable = (HashMap<String, Batch>) parsingResult[1];
            HashMap<String, Protocol> protocolsTable = (HashMap<String, Protocol>) parsingResult[2];

            /**
             * *******************************************************
             * STEP 3 IF FILE WAS PARSED CORRECTLY ADD THE INFORMATION TO
             * DATABASE. IF ERROR --> throws SQLException, GO TO STEP ? ELSE
             * --> GO TO STEP 4
             * *******************************************************
             */
            dao_instance = DAOProvider.getDAOByName("Batch");
            dao_instance.disableAutocommit();
            ROLLBACK_NEEDED = true;

            //IF WE ARE HERE IT MEANS THAT APARENTLY EVERTHING WAS OK
            //therefore WE SHOULD START ADDING THE INFORMATION INTO THE DB
            for (Batch batch : batchesTable.values()) {
                String batch_id = dao_instance.getNextObjectID(null);
                BLOCKED_IDs.add(batch_id);
                batch.setBatchID(batch_id);
                //THE BATCH ID SHOULD BE UPDATED IN ALL THE BIOREPLICATES (BECAUSE IS THE SAME OBJECT)
                dao_instance.insert(batch);
            }

            dao_instance = DAOProvider.getDAOByName("Protocol");
            //IF WE ARE HERE IT MEANS THAT APARENTLY EVERTHING WAS OK
            //therefore WE SHOULD START ADDING THE INFORMATION INTO THE DB
            for (Protocol protocol : protocolsTable.values()) {
                String protocolID = dao_instance.getNextObjectID(null);
                BLOCKED_IDs.add(protocolID);
                protocol.setProtocolID(protocolID);
                //THE BATCH ID SHOULD BE UPDATED IN ALL THE BIOREPLICATES (BECAUSE IS THE SAME OBJECT)
                dao_instance.insert(protocol);
            }

            dao_instance = DAOProvider.getDAOByName("BioCondition");

            for (BioCondition biocondition : biocondition_list) {
                String newID = dao_instance.getNextObjectID(null);
                BLOCKED_IDs.add(newID);
                biocondition.setBioConditionID(newID);
                //THE biocondition ID SHOULD BE UPDATED IN ALL THE BIOREPLICATES
                dao_instance.insert(biocondition);
            }

            /**
             * *******************************************************
             * STEP 4 COMMIT CHANGES TO DATABASE. throws SQLException IF
             * ERROR --> throws SQL Exception, GO TO STEP 5b ELSE --> GO TO
             * STEP 5
             * *******************************************************
             */
            dao_instance.doCommit();

        } catch (Exception e) {
            ServerErrorManager.handleException(e, Samples_servlets.class.getName(),
                    "send_biocondition_template_document_handler", e.getMessage());
        } finally {
            /**
             * *******************************************************
             * STEP 5b CATCH ERROR, CLEAN CHANGES. throws SQLException
             * *******************************************************
             */
            if (ServerErrorManager.errorStatus()) {
                response.setStatus(400);
                response.getWriter().print(ServerErrorManager.getErrorResponse());

                if (ROLLBACK_NEEDED) {
                    dao_instance.doRollback();
                }
            } else {
                response.getWriter().print("{success: " + true + "}");
            }

            for (String blocked_id : BLOCKED_IDs) {
                BlockedElementsManager.getBlockedElementsManager().unlockID(blocked_id);
            }

            /**
             * *******************************************************
             * STEP 6 Close connection.
             * ********************************************************
             */
            if (dao_instance != null) {
                dao_instance.closeConnection();
            }
        }
        //CATCH IF THE ERROR OCCURRED IN ROLL BACK OR CONNECTION CLOSE 
    } catch (Exception e) {
        ServerErrorManager.handleException(e, Samples_servlets.class.getName(),
                "send_xls_creation_document_handler", e.getMessage());
        response.setStatus(400);
        response.getWriter().print(ServerErrorManager.getErrorResponse());
    }
}

From source file:org.dmb.trueprice.servlets.Download_servlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    /* Rcupration du chemin du fichier demand au sein de l'URL de la requte */
    String fichierRequis = request.getPathInfo();

    /* Vrifie qu'un fichier a bien t fourni */
    if (fichierRequis == null || "/".equals(fichierRequis)) {
        /* Si non, alors on envoie une erreur 404, qui signifie que la ressource demande n'existe pas */
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;/*  w w w.  j  a v  a2s.  c  o m*/
    }

    if (iconPathIsOK == false) {
        buildIconURL(request);
    }

    log.info("File asked [" + fichierRequis + "]");

    String parentFolder = xmlDataFolder;

    // Si c'est un fichier dans un dossier personnel d'un user
    if (fichierRequis.startsWith(xmlMemberDataPath)) {

        HttpSession session = request.getSession(false);

        Membre mb = (Membre) session.getAttribute(ATT_SESSION_USER);

        parentFolder = xmlMemberDataFolder + File.separator + mb.getMbMail();

    }
    // Si c'est un fichier dans le dossier XMl public
    else if (fichierRequis.startsWith(xmlPublicDataPath)) {
        parentFolder = xmlPublicDataFolder;
    }
    //        else if (fichierRequis.startsWith(iconDataPath)) { parentFolder = iconFolder ;}

    log.info("Parent folder : [" + parentFolder + "]");

    /* Dcode le nom de fichier rcupr, susceptible de contenir des espaces et autres caractres spciaux, et prpare l'objet File */
    fichierRequis = URLDecoder.decode(fichierRequis, "UTF-8");

    log.info("Decoded File asked : [" + fichierRequis + "]");

    /*  Ne retenir que le nom du fichier + extension */
    fichierRequis = FilenameUtils.getName(fichierRequis);

    log.info("Finally, file name is : [" + fichierRequis + "]");

    File fichier = new File(parentFolder, fichierRequis);

    /* Vrifie que le fichier existe bien */
    if (!fichier.exists()) {

        log.info("Can't find : [" + fichierRequis + "] in folder [" + parentFolder + "]");

        /* Si non, alors on envoie une erreur 404, qui signifie que la ressource demande n'existe pas */
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    /* Rcupre le type du fichier */
    String type = getServletContext().getMimeType(fichier.getName());

    /* Si le type de fichier est inconnu, alors on initialise un type par dfaut */
    if (type == null) {
        type = "application/octet-stream";
    } else {
        InitContextListener.getLogger(this.getClass())
                .info(" Found MimeType for asked ressource [" + type + "]");
    }

    /* Initialise la rponse HTTP */
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setContentType(type);
    response.setHeader("Content-Length", String.valueOf(fichier.length()));
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fichier.getName() + "\"");

    /* Prpare les flux */
    BufferedInputStream entree = null;
    BufferedOutputStream sortie = null;
    try {
        /* Ouvre les flux */
        entree = new BufferedInputStream(new FileInputStream(fichier), TAILLE_TAMPON);
        sortie = new BufferedOutputStream(response.getOutputStream(), TAILLE_TAMPON);

        /* ... */
        /* Lit le fichier et crit son contenu dans la rponse HTTP */
        byte[] tampon = new byte[TAILLE_TAMPON];
        int longueur;
        while ((longueur = entree.read(tampon)) > 0) {
            sortie.write(tampon, 0, longueur);
        }

    } finally {
        try {
            sortie.close();
        } catch (IOException ignore) {
        }
        try {
            entree.close();
        } catch (IOException ignore) {
        }
    }

    InitContextListener.getLogger(this.getClass()).info("File sent [" + fichierRequis + "]");

}