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.backBeans.departmentMember.teacherService.ViewTeacherService.java

public void exportTeacherServiceByCourseToXLS() throws FenixServiceException, IOException {
    if (this.executionCourseServiceDTO == null) {
        loadDistributionServiceDataByCourse();
    }//from w  w w  .  java2 s.c o m

    final StyledExcelSpreadsheet spreadsheet = new StyledExcelSpreadsheet("teacher distribution");
    fillSpreadSheetHeaders(spreadsheet);
    fillSpreadSheedResults(spreadsheet);

    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

    String fileName = "file.xls";
    String contentType = "application/vnd.ms-excel";

    response.reset();
    response.setContentType(contentType);
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

    OutputStream output = response.getOutputStream();
    spreadsheet.getWorkbook().write(output);

    fc.responseComplete();
}

From source file:fedora.server.security.servletfilters.FilterEnforceAuthn.java

@Override
public boolean doThisSubclass(ExtendedHttpServletRequest request, HttpServletResponse response)
        throws Throwable {
    String method = "doThisSubclass() ";
    if (log.isDebugEnabled()) {
        log.debug(enter(method));/*from   ww w .  ja  v  a 2s .c om*/
    }
    super.doThisSubclass(request, response);
    request.lockWrapper();

    boolean terminateServletFilterChain = request.getUserPrincipal() == null;
    if (terminateServletFilterChain) {
        if (log.isDebugEnabled()) {
            log.debug(format(method, "no principal found, sending 401"));
        }
        String realm = "fedora";
        String value = "BASIC realm=\"" + realm + "\"";
        String name = "WWW-Authenticate";
        int sc = HttpServletResponse.SC_UNAUTHORIZED;
        response.reset();
        //httpServletResponse.sendError(sc, "supply credentials"); //same as after
        if (response.containsHeader(name)) {
            response.setHeader(name, value);
        } else {
            response.addHeader(name, value);
        }
        try {
            response.sendError(sc, "supply credentials");
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } //here, no bad auth msg at wget
        response.setContentType("text/plain");
        try {
            response.flushBuffer();
        } catch (IOException e) {
            showThrowable(e, log, "response flush error");
        }
    }
    return terminateServletFilterChain;
}

From source file:org.springframework.boot.context.web.ErrorPageFilter.java

private void forwardToErrorPage(String path, HttpServletRequest request, HttpServletResponse response,
        Throwable ex) throws ServletException, IOException {
    if (logger.isErrorEnabled()) {
        String message = "Forwarding to error page from request " + getDescription(request)
                + " due to exception [" + ex.getMessage() + "]";
        logger.error(message, ex);/*from  w  ww.  j ava  2 s .c o  m*/
    }
    setErrorAttributes(request, 500, ex.getMessage());
    request.setAttribute(ERROR_EXCEPTION, ex);
    request.setAttribute(ERROR_EXCEPTION_TYPE, ex.getClass().getName());
    response.reset();
    response.sendError(500, ex.getMessage());
    request.getRequestDispatcher(path).forward(request, response);
}

From source file:com.feilong.controller.DownloadController.java

public HttpServletResponse download(String path, HttpServletResponse response) {
    try {/* w w  w .jav  a 2  s  . c  om*/
        // path
        File file = new File(path);
        // ???
        String filename = file.getName();
        // ????
        String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

        // ??
        InputStream fis = new BufferedInputStream(new FileInputStream(path));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // response
        response.reset();
        // responseHeader
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return response;
}

From source file:de.digitalcollections.streaming.euphoria.controller.StreamingController.java

/**
 * Create response for the request.//from w w w.  j  a v a 2s. c  o m
 *
 * @param id The id of requested content.
 * @param extension The (target) file extension/format of requested content.
 * @param request The request to be responded to.
 * @param response The response to the request.
 * @param head "true" if response body should be written (GET) or "false" if not (HEAD).
 * @throws IOException If something fails at I/O level.
 */
private void respond(String id, String extension, HttpServletRequest request, HttpServletResponse response,
        boolean head) throws IOException {
    logRequestHeaders(request);

    response.reset();

    // try to get access to resource
    Resource resource;
    try {
        resource = getResource(id, extension);
    } catch (ResourceIOException ex) {
        LOGGER.warn("*** Response {}: Error referencing streaming resource with id {} and extension {}",
                HttpServletResponse.SC_NOT_FOUND, id, extension);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // get resource metadata
    ResourceInfo resourceInfo = new ResourceInfo(id, resource);
    if (resourceInfo.length <= 0) {
        LOGGER.warn("*** Response {}: Error streaming resource with id {} and extension {}: not found/no size",
                HttpServletResponse.SC_NOT_FOUND, id, extension);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    if (preconditionFailed(request, resourceInfo)) {
        LOGGER.warn(
                "*** Response {}: Precondition If-Match/If-Unmodified-Since failed for resource with id {} and extension {}.",
                HttpServletResponse.SC_PRECONDITION_FAILED, id, extension);
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    setCacheHeaders(response, resourceInfo);

    if (notModified(request, resourceInfo)) {
        LOGGER.debug("*** Response {}: 'Not modified'-response for resource with id {} and extension {}.",
                HttpServletResponse.SC_NOT_MODIFIED, id, extension);
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    List<Range> ranges = getRanges(request, resourceInfo);

    if (ranges == null) {
        response.setHeader("Content-Range", "bytes */" + resourceInfo.length);
        LOGGER.warn("Response {}: Header Range for resource with id {} and extension {} not satisfiable",
                HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE, id, extension);
        response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
        return;
    }

    if (!ranges.isEmpty()) {
        response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
    } else {
        ranges.add(new Range(0, resourceInfo.length - 1)); // Full content.
    }

    String contentType = setContentHeaders(request, response, resourceInfo, ranges);
    boolean acceptsGzip = false;
    // If content type is text, then determine whether GZIP content encoding is supported by
    // the browser and expand content type with the one and right character encoding.
    if (contentType.startsWith("text")) {
        String acceptEncoding = request.getHeader("Accept-Encoding");
        acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip");
        contentType += ";charset=UTF-8";
    }

    if (head) {
        return;
    }

    writeContent(response, resource, resourceInfo, ranges, contentType, acceptsGzip);
    LOGGER.debug("*** RESPONSE FINISHED ***");
}

From source file:de.unirostock.sems.caroweb.Converter.java

private void checkout(HttpServletRequest request, HttpServletResponse response, Path storage, String req)
        throws ServletException, IOException {
    Path target = storage.resolve(req).toAbsolutePath().normalize();
    if (!target.startsWith(storage) || !Files.exists(target)) {
        error(request, response, "you're not allowed to download that file.");
        return;/*  www  .java  2 s  . c om*/
    }

    try {
        String mime = target.toString().endsWith("omex") ? "application/zip"
                : "application/vnd.wf4ever.robundle+zip";

        response.reset();
        response.setBufferSize(CaRoWebutils.DEFAULT_BUFFER_SIZE);
        response.setContentType(mime);
        response.setHeader("Content-Length", String.valueOf(target.toFile().length()));
        response.setHeader("Content-Disposition", "attachment; filename=\"" + req + "\"");
        response.setHeader("Expires", CaRoWebutils.downloadDateFormater
                .format(new Date(System.currentTimeMillis() + CaRoWebutils.CACHE_TIME * 1000)));
        response.setHeader("Cache-Control", "max-age=" + CaRoWebutils.CACHE_TIME);
        response.setHeader("Last-Modified", CaRoWebutils.downloadDateFormater
                .format(new Date(Files.getLastModifiedTime(target).toMillis())));
        response.setHeader("ETag", GeneralTools.hash(target + "-" + Files.getLastModifiedTime(target)));

        BufferedInputStream input = new BufferedInputStream(new FileInputStream(target.toFile()),
                CaRoWebutils.DEFAULT_BUFFER_SIZE);
        BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream(),
                CaRoWebutils.DEFAULT_BUFFER_SIZE);

        // pass the stream to client
        byte[] buffer = new byte[CaRoWebutils.DEFAULT_BUFFER_SIZE];
        int length;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }

        input.close();
        output.close();

        return;
    } catch (IOException e) {
        // whoops, that's our fault. shouldn't happen. hopefully.
        LOGGER.error("unable to dump file " + target + " (at least not in an expected form)");
    }
    error(request, response, "couldn't dump file");
}

From source file:com.iyonger.apm.web.controller.FileEntryController.java

/**
 * Download file entry of given path.//from  w  ww .j a va 2  s. com
 *
 * @param user     current user
 * @param path     user
 * @param response response
 */
@RequestMapping("/download/**")
public void download(User user, String path, HttpServletResponse response) {
    FileEntry fileEntry = fileEntryService.getOne(user, path);
    if (fileEntry == null) {
        LOG.error("{} requested to download not existing file entity {}", user.getUserId(), path);
        return;
    }
    response.reset();
    try {
        response.addHeader("Content-Disposition", "attachment;filename="
                + java.net.URLEncoder.encode(FilenameUtils.getName(fileEntry.getPath()), "utf8"));
    } catch (UnsupportedEncodingException e1) {
        LOG.error(e1.getMessage(), e1);
    }
    response.setContentType("application/octet-stream; charset=UTF-8");
    response.addHeader("Content-Length", "" + fileEntry.getFileSize());
    byte[] buffer = new byte[4096];
    ByteArrayInputStream fis = null;
    OutputStream toClient = null;
    try {
        fis = new ByteArrayInputStream(fileEntry.getContentBytes());
        toClient = new BufferedOutputStream(response.getOutputStream());
        int readLength;
        while (((readLength = fis.read(buffer)) != -1)) {
            toClient.write(buffer, 0, readLength);
        }
    } catch (IOException e) {
        throw processException("error while download file", e);
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(toClient);
    }
}

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

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

    log.debug("Entering");

    // set content type
    response.setContentType("text/html; charset=utf-8");

    // initialize model
    HashMap model = new HashMap();
    try {
        // populate the rendering model
        Map initData = new HashMap();

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

    } catch (PlanetException ex) {
        log.error("ERROR loading model", 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");

        // what template are we going to render?
        Template template = new StaticTemplate("home.vm", null, "velocity");

        // get the Renderer
        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
    try {
        log.debug("Doing rendering");
        renderer.render(model, response.getWriter());
    } catch (Exception e) {
        // bummer, error during rendering
        log.error("Error during rendering", 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:org.springframework.boot.web.servlet.support.ErrorPageFilter.java

private void forwardToErrorPage(String path, HttpServletRequest request, HttpServletResponse response,
        Throwable ex) throws ServletException, IOException {
    if (logger.isErrorEnabled()) {
        String message = "Forwarding to error page from request " + getDescription(request)
                + " due to exception [" + ex.getMessage() + "]";
        logger.error(message, ex);/*  w w w.  jav  a2  s .  c  o m*/
    }
    setErrorAttributes(request, 500, ex.getMessage());
    request.setAttribute(ERROR_EXCEPTION, ex);
    request.setAttribute(ERROR_EXCEPTION_TYPE, ex.getClass());
    response.reset();
    response.setStatus(500);
    request.getRequestDispatcher(path).forward(request, response);
    request.removeAttribute(ERROR_EXCEPTION);
    request.removeAttribute(ERROR_EXCEPTION_TYPE);
}

From source file:de.itsvs.cwtrpc.controller.RemoteServiceControllerServlet.java

protected void processUnexpectedFailure(HttpServletRequest request, HttpServletResponse response,
        Throwable exception) throws ServletException, IOException {
    log.error("Unexpected error while processing service request", exception);

    if (CwtRpcUtils.getRpcSessionInvalidationPolicy(request).isInvalidateOnUnexpectedException()) {
        invalidateSession(request);//from w  w w  .j a v  a2 s . c o  m
    }
    if (!response.isCommitted()) {
        response.reset();
        addNoCacheResponseHeaders(request, response);
        RPCServletUtils.writeResponseForUnexpectedFailure(getServletContext(), response, exception);
        /*
         * Flush all remaining output to the client (client can continue
         * immediately). Also response will be marked as being committed
         * (status may be required later by a filter).
         */
        response.flushBuffer();
    }
}