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:com.sccl.attech.modules.sys.web.LoginController.java

@SuppressWarnings("resource")
@RequestMapping("${adminPath}/download")
public String download(@RequestParam String filePath, HttpServletRequest request,
        HttpServletResponse response) {
    String fp = filePath.replaceAll("\\"", "");
    String fpe = EncodedUtil.encodeValue(fp);
    System.out.println(fpe);/*from   ww w.  j  a  v a2 s.c o m*/
    File file = new File(fpe);
    InputStream inputStream;
    try {
        inputStream = new FileInputStream(fpe);
        response.reset();
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        byte data[] = new byte[1024];
        while (inputStream.read(data, 0, 1024) >= 0) {
            outputStream.write(data);
        }
        outputStream.flush();
        outputStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.candidate.degree.DegreeCandidacyManagementDispatchAction.java

public ActionForward showSummaryFile(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) {
    CandidacySummaryFile file = getCandidacy(request).getSummaryFile();

    response.reset();
    try {//from   w ww  .  j a va2 s. co  m
        response.getOutputStream().write(file.getContents());
        response.setContentLength(file.getContents().length);
        response.setContentType("application/pdf");
        response.flushBuffer();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }

    return null;
}

From source file:org.apache.hama.manager.LogView.java

/**
 * download log file./*from  w ww . ja  v  a 2  s .  co m*/
 * 
 * @param filPath log file path.
 * @throws Exception
 */
public static void downloadFile(HttpServletResponse response, String filePath)
        throws ServletException, IOException {

    File file = new File(filePath);

    if (!file.exists()) {
        throw new ServletException("File doesn't exists.");
    }

    String headerKey = "Content-Disposition";
    String headerValue = "attachment; filename=\"" + file.getName() + "\"";

    BufferedInputStream in = null;
    BufferedOutputStream out = null;

    try {

        response.setContentType("application/octet-stream");
        response.setContentLength((int) file.length());
        response.setHeader(headerKey, headerValue);

        in = new BufferedInputStream(new FileInputStream(file));
        out = new BufferedOutputStream(response.getOutputStream());

        byte[] buffer = new byte[4 * 1024];
        int read = -1;

        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }

    } catch (SocketException e) {
        // download cancel..
    } catch (Exception e) {
        response.reset();
        response.sendError(HttpURLConnection.HTTP_INTERNAL_ERROR, e.toString());
    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.flush();
            out.close();
        }
    }
}

From source file:uws.service.error.DefaultUWSErrorWriter.java

/**
 * <p>Formats and writes the given error in the HTTP servlet response.</p>
 * <p>A JSON response is printed with: the HTTP error code, the error type, the name of the exception, the message and the list of all causes' message.</p>
 * /*from w w w  . jav a 2s  .c  o m*/
 * @param message         Error message to write.
 * @param type            Type of the error: FATAL or TRANSIENT.
 * @param httpErrorCode      HTTP error code (i.e. 404, 500).
 * @param reqID            ID of the request at the origin of the specified error.
 * @param action         Action which generates the error <i><u>note:</u> displayed only if not NULL and not empty.
 * @param user            User which is at the origin of the request/action which generates the error.
 * @param response         Response in which the error must be written.
 * 
 * @throws IOException      If there is an error while writing the given exception.
 */
protected void formatJSONError(final String message, final ErrorType type, final int httpErrorCode,
        final String reqID, final String action, final JobOwner user, final HttpServletResponse response)
        throws IOException {
    try {
        // Erase anything written previously in the HTTP response:
        response.reset();

        // Set the HTTP status:
        response.setStatus(httpErrorCode);

        // Set the MIME type of the answer (JSON):
        response.setContentType(UWSSerializer.MIME_TYPE_JSON);

        // Set the character encoding:
        response.setCharacterEncoding(UWSToolBox.DEFAULT_CHAR_ENCODING);

    } catch (IllegalStateException ise) {
        /*   If it is not possible any more to reset the response header and body,
         * the error is anyway written in order to corrupt the HTTP response.
         *   Thus, it will be obvious that an error occurred and the result is
         * incomplete and/or wrong.*/
    }

    PrintWriter out;
    try {
        out = response.getWriter();
    } catch (IllegalStateException ise) {
        /*   This exception may occur just because either the writer or
         * the output-stream can be used (because already got before).
         *   So, we just have to get the output-stream if getting the writer
         * throws an error.*/
        out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(response.getOutputStream())));
    }

    try {
        JSONWriter json = new JSONWriter(out);

        json.object();
        json.key("errorcode").value(httpErrorCode);
        json.key("errortype").value(type.toString());
        if (reqID != null)
            json.key("requestid").value(reqID);
        if (action != null)
            json.key("action").value(action);
        json.key("message").value(message);

        json.endObject();

        out.flush();

    } catch (JSONException je) {
        logger.logUWS(LogLevel.ERROR, null, "FORMAT_ERROR", "Impossible to format/write an error in JSON!", je);
        throw new IOException("Error while formatting the error in JSON!", je);
    }
}

From source file:org.sakaiproject.tool.assessment.ui.bean.evaluation.ExportResponsesBean.java

public void exportExcel(ActionEvent event) {
    log.debug("exporting as Excel: assessment id =  " + getAssessmentId());
    // allow local customization of spreadsheet output
    FacesContext faces = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) faces.getExternalContext().getResponse();
    response.reset(); // Eliminate the added-on stuff
    response.setHeader("Pragma", "public"); // Override old-style cache control
    response.setHeader("Cache-Control", "public, must-revalidate, post-check=0, pre-check=0, max-age=0"); // New-style
    writeDataToResponse(getSpreadsheetData(), getDownloadFileName(), response);
    faces.responseComplete();/*w w  w  .j av a2  s . co m*/
}

From source file:uws.service.error.DefaultUWSErrorWriter.java

/**
 * <p>Formats and writes the given error in the HTTP servlet response.</p>
 * <p>A full HTML response is printed with: the HTTP error code, the error type, the name of the exception, the message and the full stack trace.</p>
 * /*from w ww.  j  a va  2 s  . c om*/
 * @param message         Error message to write.
 * @param type            Type of the error: FATAL or TRANSIENT.
 * @param httpErrorCode      HTTP error code (i.e. 404, 500).
 * @param reqID            ID of the request at the origin of the specified error.
 * @param action         Action which generates the error <i><u>note:</u> displayed only if not NULL and not empty.
 * @param user            User which is at the origin of the request/action which generates the error.
 * @param response         Response in which the error must be written.
 * 
 * @throws IOException      If there is an error while writing the given exception.
 */
protected void formatHTMLError(final String message, final ErrorType type, final int httpErrorCode,
        final String reqID, final String action, final JobOwner user, final HttpServletResponse response)
        throws IOException {
    try {
        // Erase anything written previously in the HTTP response:
        response.reset();

        // Set the HTTP status:
        response.setStatus(httpErrorCode);

        // Set the MIME type of the answer (XML for a VOTable document):
        response.setContentType(UWSSerializer.MIME_TYPE_HTML);

        // Set the character encoding:
        response.setCharacterEncoding(UWSToolBox.DEFAULT_CHAR_ENCODING);

    } catch (IllegalStateException ise) {
        /*   If it is not possible any more to reset the response header and body,
         * the error is anyway written in order to corrupt the HTTP response.
         *   Thus, it will be obvious that an error occurred and the result is
         * incomplete and/or wrong.*/
    }

    PrintWriter out;
    try {
        out = response.getWriter();
    } catch (IllegalStateException ise) {
        /*   This exception may occur just because either the writer or
         * the output-stream can be used (because already got before).
         *   So, we just have to get the output-stream if getting the writer
         * throws an error.*/
        out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(response.getOutputStream())));
    }

    // Header:
    out.println("<html>\n\t<head>");
    out.println("\t\t<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />");
    out.println("\t\t<style type=\"text/css\">");
    out.println("\t\t\tbody { background-color: white; color: black; }");
    out.println(
            "\t\t\th2 { font-weight: bold; font-variant: small-caps; text-decoration: underline; font-size: 1.5em; color: #4A4A4A; }");
    out.println("\t\t\tul, ol { margin-left: 2em; margin-top: 0.2em; text-align: justify; }");
    out.println("\t\t\tli { margin-bottom: 0.2em; margin-top: 0; }");
    out.println("\t\t\tp, p.listheader { text-align: justify; text-indent: 2%; margin-top: 0; }");
    out.println("\t\t\ttable { border-collapse: collapse; }");
    out.println("\t\t\ttable, th, td { border: 1px solid #FC8813; }");
    out.println("\t\t\tth { background-color: #F29842; color: white; font-size: 1.1em; }");
    out.println("\t\t\ttr.alt { background-color: #FFDAB6; }");
    out.println("\t\t</style>");
    out.println("\t\t<title>SERVICE ERROR</title>");
    out.println("\t</head>\n\t<body>");

    // Title:
    String errorColor = (type == ErrorType.FATAL) ? "red" : "orange";
    out.println("\t\t<h1 style=\"text-align: center; background-color:" + errorColor
            + "; color: white; font-weight: bold;\">SERVICE ERROR - " + httpErrorCode + "</h1>");

    // Description part:
    out.println("\t\t<h2>Description</h2>");
    out.println("\t\t<ul>");
    out.println("\t\t\t<li><b>Type: </b>" + type + "</li>");
    if (reqID != null)
        out.println("\t\t\t<li><b>Request ID: </b>" + reqID + "</li>");
    if (action != null)
        out.println("\t\t\t<li><b>Action: </b>" + action + "</li>");
    out.println("\t\t\t<li><b>Message:</b><p>" + message + "</p></li>");
    out.println("\t\t</ul>");

    out.println("\t</body>\n</html>");

    out.flush();
}

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

public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception {
    File f = new File(filePath);
    if (!f.exists()) {
        response.sendError(404, "File not found!");
        return;// www.ja  va 2  s  .  c om
    }
    BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
    byte[] buf = new byte[1024];
    int len = 0;

    response.reset(); // ???
    if (isOnLine) { // ?
        URL u = new URL("file:///" + filePath);
        response.setContentType(u.openConnection().getContentType());
        response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
        // ????UTF-8
    } else { // ?
        response.setContentType("application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
    }
    OutputStream out = response.getOutputStream();
    while ((len = br.read(buf)) > 0)
        out.write(buf, 0, len);
    br.close();
    out.close();
}

From source file:de.iteratec.iteraplan.presentation.dialog.Templates.TemplatesController.java

@RequestMapping(method = RequestMethod.POST)
public String onSubmit(@ModelAttribute("dialogMemory") TemplatesDialogMemory dialogMem, ModelMap model,
        HttpSession session, MultipartHttpServletRequest req, HttpServletResponse response) {

    UserContext userContext = UserContext.getCurrentUserContext();
    userContext.getPerms().assureFunctionalPermission(TypeOfFunctionalPermission.TEMPLATES);
    response.reset();

    dialogMem.clearErrors();//from  w  w w .  j ava 2s. c o  m

    String action = dialogMem.getAction();
    if ("upload".equals(action)) {
        dialogMem.setUploadSuccessful(false);
        MultipartFile uploadedFile = uploadTemplate(dialogMem, req);
        if (uploadedFile == null) {
            return INIT_VIEW;
        }
        save(TemplateType.getTypeFromKey(dialogMem.getTargetTemplateType()), uploadedFile);
    } else if ("remove".equals(action)) {
        removeTemplate(dialogMem);
    } else if ("download".equals(action)) {
        downloadTemplate(dialogMem, response);
    }

    /*  Custom dashboard things */
    else if ("createDashboardTemplate".equals(action)) {
        // create a new dashboard template
        if (dialogMem.getSelectedBBTypeId() != null) { // it is necessary that a bbt has been selected

            CustomDashboardTemplatesDialogMemory cdtDialogMem = dialogMem.getCustomDashboardDialogMemory();

            // load the selected building Block Type
            BuildingBlockType bbt = bbTypeService.loadObjectById(dialogMem.getSelectedBBTypeId());

            // create a new empty dashboard template with the building Block Type
            cdtDialogMem.setCustomDashboardTemplate(new CustomDashboardTemplate(bbt, "", "", ""));

            // load the saved querys for the dashboard template editor
            cdtDialogMem.setSavedQueries(savedQueryService.getAllSavedQueryForDashboards(bbt));
        }
    } else if ("setDashboardTemplateToEdit".equals(action)) {
        // load the custom dashboard template
        CustomDashboardTemplate customDashboardTemplate = customDashboardTemplateService
                .findById(dialogMem.getCustomDashboardId());
        dialogMem.getCustomDashboardDialogMemory().setCustomDashboardTemplate(customDashboardTemplate);

        // load the saved queries for the dashboard template editor
        BuildingBlockType bbt = dialogMem.getCustomDashboardDialogMemory().getCustomDashboardSelectedBBType();
        dialogMem.getCustomDashboardDialogMemory()
                .setSavedQueries(savedQueryService.getAllSavedQueryForDashboards(bbt));
    } else if ("rollbackDashboardTemplate".equals(action)) {
        initCustomDashboardDialogMemory(dialogMem);
    } else if ("saveDashboardTemplate".equals(action)) {
        // save Dashboard Template
        customDashboardTemplateService.saveCustomDashboardTemplate(
                dialogMem.getCustomDashboardDialogMemory().getCustomDashboardTemplate());
        initCustomDashboardDialogMemory(dialogMem);
    } else if ("deleteDashboardTemplate".equals(action)) {

        CustomDashboardTemplate customDashboardTemplate = customDashboardTemplateService
                .findById(dialogMem.getCustomDashboardId());

        List<CustomDashboardInstance> templates = customDashboardInstanceService
                .getCustomDashboardByDashboardTemplate(customDashboardTemplate);
        if (!templates.isEmpty()) {
            dialogMem.addError(MessageAccess.getString("customDashboard.deleteTemplate.warning"));
        } else {

            if (customDashboardTemplate
                    .equals(dialogMem.getCustomDashboardDialogMemory().getCustomDashboardTemplate())) {
                dialogMem.getCustomDashboardDialogMemory().setCustomDashboardTemplate(null);
                dialogMem.getCustomDashboardDialogMemory().setCustomDashboardSelectedBBType(null);
            }
            customDashboardTemplateService.deleteCustomDashboardTemplate(customDashboardTemplate);
            initCustomDashboardDialogMemory(dialogMem);
        }
    } else if ("edit".equals(action)) {
        dialogMem.getCustomDashboardDialogMemory()
                .setSelectedTab(CustomDashboardTemplatesDialogMemory.MODE_EDIT);
    } else if ("preview".equals(action)) {
        dialogMem.getCustomDashboardDialogMemory()
                .setSelectedTab(CustomDashboardTemplatesDialogMemory.MODE_PREVIEW);
    } else if ("metadata".equals(action)) {
        dialogMem.getCustomDashboardDialogMemory()
                .setSelectedTab(CustomDashboardTemplatesDialogMemory.MODE_METADATA);
    }

    refillDialogMem(dialogMem);

    updateGuiContext(dialogMem);

    return INIT_VIEW;
}

From source file:fll.web.report.PerformanceScoreDump.java

protected void processRequest(final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext application, final HttpSession session) throws IOException, ServletException {
    CSVWriter csv = null;/*from   w  w w .ja v  a 2 s.co m*/
    Connection connection = null;
    try {
        final DataSource datasource = ApplicationAttributes.getDataSource(application);
        connection = datasource.getConnection();

        final int tournamentID = Queries.getCurrentTournament(connection);

        response.reset();
        response.setContentType("text/csv");
        response.setHeader("Content-Disposition", "filename=performance_scores.csv");

        csv = new CSVWriter(response.getWriter());

        writeHeader(csv);
        writeData(connection, tournamentID, csv);

    } catch (final SQLException e) {
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(csv);
        SQLFunctions.close(connection);
    }
}

From source file:com.groupon.odo.controllers.ServerMappingController.java

/**
 * Returns a X509 binary certificate for a given domain name if a certificate has been generated for it
 *
 * @param locale//  www . j  a v  a 2s  .  c  o m
 * @param model
 * @param response
 * @param hostname
 * @throws Exception
 */
@RequestMapping(value = "/cert/{hostname:.+}", method = { RequestMethod.GET, RequestMethod.HEAD })
public @ResponseBody void getCert(Locale locale, Model model, HttpServletResponse response,
        @PathVariable String hostname) throws Exception {
    // Set the appropriate headers so the browser thinks this is a file
    response.reset();
    response.setContentType("application/x-x509-ca-cert");
    response.setHeader("Content-Disposition", "attachment;filename=" + hostname + ".cer");

    // special handling for hostname=="root"
    // return the CyberVillians Root Cert in this case
    if (hostname.equals("root")) {
        hostname = "cybervillainsCA";
        response.setContentType("application/pkix-cert ");
    }

    // get the cert for the hostname
    KeyStoreManager keyStoreManager = com.groupon.odo.bmp.Utils.getKeyStoreManager(hostname);

    if (hostname.equals("cybervillainsCA")) {
        // get the cybervillians cert from resources
        File root = new File("seleniumSslSupport" + File.separator + hostname);

        // return the root cert
        Files.copy(new File(root.getAbsolutePath() + File.separator + hostname + ".cer").toPath(),
                response.getOutputStream());
        response.flushBuffer();
    } else {
        // return the cert for the appropriate alias
        response.getOutputStream().write(keyStoreManager.getCertificateByAlias(hostname).getEncoded());
        response.flushBuffer();
    }

}