Example usage for javax.servlet ServletOutputStream flush

List of usage examples for javax.servlet ServletOutputStream flush

Introduction

In this page you can find the example usage for javax.servlet ServletOutputStream flush.

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:com.aaasec.sigserv.csspserver.SpServlet.java

/**
 * Processes requests for both HTTP//w  w  w.ja  v  a2 s .  co  m
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");

    SpSession session = getSession(request, response);

    RequestModel req = reqFactory.getRequestModel(request, session);
    AuthData authdata = req.getAuthData();

    // Supporting devmode login
    if (SpModel.isDevmode()) {
        authdata = TestIdentities.getTestID(request, req);
        req.setAuthData(authdata);
        if (authdata.getAuthType().length() == 0) {
            authdata.setAuthType("devlogin");
        }
        session.setIdpEntityId(authdata.getIdpEntityID());
        session.setSignerAttribute(RequestModelFactory.getAttrOidString(authdata.getIdAttribute()));
        session.setSignerId(authdata.getId());
    }

    //Terminate if no valid request data
    if (req == null) {
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        response.getWriter().write("");
        return;
    }

    // Handle form post from web page
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        response.getWriter().write(SpServerLogic.processFileUpload(request, response, req));
        return;
    }

    // Handle auth data request 
    if (req.getAction().equals("authdata")) {
        response.setContentType("application/json");
        response.setHeader("Cache-Control", "no-cache");
        response.getWriter().write(gson.toJson(authdata));
        return;
    }

    // Get list of serverstored xml documents
    if (req.getAction().equals("doclist")) {
        response.setContentType("application/json");
        response.getWriter().write(SpServerLogic.getDocList());
        return;
    }

    // Provide info about the session for logout handling
    if (req.getAction().equals("logout")) {
        response.setContentType("application/json");
        Logout lo = new Logout();
        lo.authType = (request.getAuthType() == null) ? "" : request.getAuthType();
        lo.devmode = String.valueOf(SpModel.isDevmode());
        response.getWriter().write(gson.toJson(lo));
        return;
    }

    // Respons to a client alive check to test if the server session is alive
    if (req.getAction().equals("alive")) {
        response.setContentType("application/json");
        response.getWriter().write("[]");
        return;
    }

    // Handle sign request and return Xhtml form with post data to the signature server
    if (req.getAction().equals("sign")) {
        boolean addSignMessage = (req.getParameter().equals("message"));
        String xhtml = SpServerLogic.prepareSignRedirect(req, addSignMessage);
        response.getWriter().write(xhtml);
        return;
    }

    // Get status data about the current session
    if (req.getAction().equals("status")) {
        response.setContentType("application/json");
        response.getWriter().write(gson.toJson(session.getStatus()));
        return;
    }

    // Handle a declined sign request
    if (req.getAction().equals("declined")) {
        if (SpModel.isDevmode()) {
            response.sendRedirect("index.jsp?declined=true");
            return;
        }
        response.sendRedirect("https://eid2cssp.3xasecurity.com/sign/index.jsp?declined=true");
        return;
    }

    // Return Request and response data as a file.
    if (req.getAction().equalsIgnoreCase("getReqRes")) {
        response.setContentType("text/xml;charset=UTF-8");
        byte[] data = TestCases.getRawData(req);
        BufferedInputStream fis = new BufferedInputStream(new ByteArrayInputStream(data));
        ServletOutputStream output = response.getOutputStream();
        if (req.getParameter().equalsIgnoreCase("download")) {
            response.setHeader("Content-Disposition", "attachment; filename=" + req.getId() + ".xml");
        }

        int readBytes = 0;
        byte[] buffer = new byte[10000];
        while ((readBytes = fis.read(buffer, 0, 10000)) != -1) {
            output.write(buffer, 0, readBytes);
        }
        output.flush();
        output.close();
        fis.close();
        return;
    }

    // Return the signed document
    if (req.getAction().equalsIgnoreCase("getSignedDoc")
            || req.getAction().equalsIgnoreCase("getUnsignedDoc")) {
        // If the request if for a plaintext document, or only if the document has a valid signature
        if (session.getStatus().signedDocValid || req.getAction().equalsIgnoreCase("getUnsignedDoc")) {
            response.setContentType(session.getDocumentType().getMimeType());
            switch (session.getDocumentType()) {
            case XML:
                response.getWriter().write(new String(session.getSignedDoc(), Charset.forName("UTF-8")));
                return;
            case PDF:
                File docFile = session.getDocumentFile();
                if (req.getAction().equalsIgnoreCase("getSignedDoc") && session.getStatus().signedDocValid) {
                    docFile = session.getSigFile();
                }
                FileInputStream fis = new FileInputStream(docFile);
                ServletOutputStream output = response.getOutputStream();
                if (req.getParameter().equalsIgnoreCase("download")) {
                    response.setHeader("Content-Disposition", "attachment; filename=" + "signedPdf.pdf");
                }

                int readBytes = 0;
                byte[] buffer = new byte[10000];
                while ((readBytes = fis.read(buffer, 0, 10000)) != -1) {
                    output.write(buffer, 0, readBytes);
                }
                output.flush();
                output.close();
                fis.close();
                return;
            }
            return;
        } else {
            if (SpModel.isDevmode()) {
                response.sendRedirect("index.jsp");
                return;
            }
            response.sendRedirect("https://eid2cssp.3xasecurity.com/sign/index.jsp");
            return;
        }
    }

    // Process a sign response from the signature server
    if (req.getSigResponse().length() > 0) {
        try {
            byte[] sigResponse = Base64Coder.decode(req.getSigResponse().trim());

            // Handle response
            SpServerLogic.completeSignedDoc(sigResponse, req);

        } catch (Exception ex) {
        }
        if (SpModel.isDevmode()) {
            response.sendRedirect("index.jsp");
            return;
        }
        response.sendRedirect("https://eid2cssp.3xasecurity.com/sign/index.jsp");
        return;
    }

    // Handle testcases
    if (req.getAction().equals("test")) {
        boolean addSignMessage = (req.getParameter().equals("message"));
        String xhtml = TestCases.prepareTestRedirect(request, response, req, addSignMessage);
        respond(response, xhtml);
        return;
    }

    // Get test data for display such as request data, response data, certificates etc.
    if (req.getAction().equals("info")) {
        switch (session.getDocumentType()) {
        case PDF:
            File returnFile = null;
            if (req.getId().equalsIgnoreCase("document")) {
                respond(response, getDocIframe("getUnsignedDoc", needPdfDownloadButton(request)));
            }
            if (req.getId().equalsIgnoreCase("formSigDoc")) {
                respond(response, getDocIframe("getSignedDoc", needPdfDownloadButton(request)));
            }
            respond(response, TestCases.getTestData(req));
            return;
        default:
            respond(response, TestCases.getTestData(req));
            return;
        }
    }

    if (req.getAction().equals("verify")) {
        response.setContentType("text/xml;charset=UTF-8");
        String sigVerifyReport = TestCases.getTestData(req);
        if (sigVerifyReport != null) {
            respond(response, sigVerifyReport);
            return;
        }
    }

    nullResponse(response);
}

From source file:com.ewcms.content.vote.web.ResultServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletOutputStream out = null;
    StringBuffer output = new StringBuffer();
    try {//from w  w w .  j a  va 2  s .  c o m
        String id = req.getParameter("id");

        if (!id.equals("") && StringUtils.isNumeric(id)) {
            Long questionnaireId = new Long(id);

            ServletContext application = getServletContext();
            WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(application);
            QuestionnaireService questionnaireService = (QuestionnaireService) wac
                    .getBean("questionnaireService");

            String ipAddr = req.getRemoteAddr();

            output = questionnaireService.getQuestionnaireResultClientToHtml(questionnaireId,
                    getServletContext().getContextPath(), ipAddr);
        }
        out = resp.getOutputStream();
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=UTF-8");
        out.write(output.toString().getBytes("UTF-8"));
        out.flush();
    } finally {
        if (out != null) {
            out.close();
            out = null;
        }
    }
}

From source file:com.ephesoft.gxt.admin.server.ExportBatchClassDownloadServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    BatchClassService batchClassService = this.getSingleBeanOfType(BatchClassService.class);
    BatchSchemaService batchSchemaService = this.getSingleBeanOfType(BatchSchemaService.class);
    BatchClass batchClass = batchClassService.getLoadedBatchClassByIdentifier(req.getParameter(IDENTIFIER));
    String exportLearning = req.getParameter(EXPORT_LEARNING);
    if (batchClass == null) {
        log.error("Incorrect batch class identifier specified.");
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Incorrect batch class identifier specified.");
    } else {//  ww w  .j a v  a2  s  . c  o  m
        // Marking exported batch class as 'Advance' as this batch has some advance feature like new FPR.rsp file.
        batchClass.setAdvancedBatchClass(Boolean.TRUE);
        Calendar cal = Calendar.getInstance();
        String exportSerailizationFolderPath = batchSchemaService.getBatchExportFolderLocation();

        SimpleDateFormat formatter = new SimpleDateFormat("MMddyy");
        String formattedDate = formatter.format(new Date());
        String zipFileName = batchClass.getIdentifier() + "_" + formattedDate + "_"
                + cal.get(Calendar.HOUR_OF_DAY) + cal.get(Calendar.SECOND);

        String tempFolderLocation = exportSerailizationFolderPath + File.separator + zipFileName;
        File copiedFolder = new File(tempFolderLocation);

        if (copiedFolder.exists()) {
            copiedFolder.delete();
        }

        copiedFolder.mkdirs();

        BatchClassUtil.copyModules(batchClass);
        BatchClassUtil.copyDocumentTypes(batchClass);
        BatchClassUtil.copyConnections(batchClass);
        BatchClassUtil.copyScannerConfig(batchClass);
        BatchClassUtil.exportEmailConfiguration(batchClass);
        BatchClassUtil.exportUserGroups(batchClass);
        BatchClassUtil.exportBatchClassField(batchClass);
        BatchClassUtil.exportCMISConfiguration(batchClass);
        // BatchClassUtil.decryptAllPasswords(batchClass);

        File serializedExportFile = new File(
                tempFolderLocation + File.separator + batchClass.getIdentifier() + SERIALIZATION_EXT);
        try {
            SerializationUtils.serialize(batchClass, new FileOutputStream(serializedExportFile));

            File originalFolder = new File(
                    batchSchemaService.getBaseSampleFDLock() + File.separator + batchClass.getIdentifier());

            if (originalFolder.isDirectory()) {

                String[] folderList = originalFolder.list();
                Arrays.sort(folderList);

                for (int i = 0; i < folderList.length; i++) {
                    if (folderList[i].endsWith(SERIALIZATION_EXT)) {
                        // skip previous ser file since new is created.
                    } else if (FilenameUtils.getName(folderList[i])
                            .equalsIgnoreCase(batchSchemaService.getTestKVExtractionFolderName())
                            || FilenameUtils.getName(folderList[i])
                                    .equalsIgnoreCase(batchSchemaService.getTestTableFolderName())
                            || FilenameUtils.getName(folderList[i]).equalsIgnoreCase(
                                    batchSchemaService.getFileboundPluginMappingFolderName())) {
                        // Skip this folder
                        continue;
                    } else if (FilenameUtils.getName(folderList[i])
                            .equalsIgnoreCase(batchSchemaService.getImagemagickBaseFolderName())
                            && Boolean.parseBoolean(exportLearning)) {
                        FileUtils.copyDirectoryWithContents(new File(originalFolder, folderList[i]),
                                new File(copiedFolder, folderList[i]));
                    } else if (FilenameUtils.getName(folderList[i]).equalsIgnoreCase(
                            batchSchemaService.getSearchSampleName()) && Boolean.parseBoolean(exportLearning)) {
                        FileUtils.copyDirectoryWithContents(new File(originalFolder, folderList[i]),
                                new File(copiedFolder, folderList[i]));
                    } else if (!(FilenameUtils.getName(folderList[i])
                            .equalsIgnoreCase(batchSchemaService.getImagemagickBaseFolderName())
                            || FilenameUtils.getName(folderList[i])
                                    .equalsIgnoreCase(batchSchemaService.getSearchSampleName()))) {
                        FileUtils.copyDirectoryWithContents(new File(originalFolder, folderList[i]),
                                new File(copiedFolder, folderList[i]));
                    }
                }
            }

        } catch (FileNotFoundException e) {
            // Unable to read serializable file
            log.error("Error occurred while creating the serializable file." + e, e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Error occurred while creating the serializable file.");

        } catch (IOException e) {
            // Unable to create the temporary export file(s)/folder(s)
            log.error("Error occurred while creating the serializable file." + e, e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Error occurred while creating the serializable file.Please try again");
        }
        resp.setContentType("application/x-zip\r\n");
        resp.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName + ZIP_EXT + "\"\r\n");
        ServletOutputStream out = null;
        ZipOutputStream zout = null;
        try {
            out = resp.getOutputStream();
            zout = new ZipOutputStream(out);
            FileUtils.zipDirectory(tempFolderLocation, zout, zipFileName);
            resp.setStatus(HttpServletResponse.SC_OK);
        } catch (IOException e) {
            // Unable to create the temporary export file(s)/folder(s)
            log.error("Error occurred while creating the zip file." + e, e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to export.Please try again.");
        } finally {
            // clean up code
            if (zout != null) {
                zout.close();
            }
            if (out != null) {
                out.flush();
            }
            FileUtils.deleteDirectoryAndContentsRecursive(copiedFolder);
        }
    }
}

From source file:com.sample.JavaHTTPResource.java

public void execute(HttpHost host, HttpUriRequest req, HttpServletResponse resultResponse)
        throws IOException, IllegalStateException, SAXException {
    HttpResponse RSSResponse = client.execute(host, req);
    ServletOutputStream os = resultResponse.getOutputStream();
    if (RSSResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        resultResponse.addHeader("Content-Type", "application/json");
        //String json = IOUtils.toString(RSSResponse.getEntity().getContent());
        InputStream in = RSSResponse.getEntity().getContent();
        StringBuilder sb = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String read;//from w  ww  .j  a va 2 s  .c  o m

        while ((read = br.readLine()) != null) {
            //System.out.println(read);
            sb.append(read);
        }

        br.close();
        os.write(sb.toString().getBytes(Charset.forName("UTF-8")));

    } else {
        resultResponse.setStatus(RSSResponse.getStatusLine().getStatusCode());
        RSSResponse.getEntity().getContent().close();
        os.write(RSSResponse.getStatusLine().getReasonPhrase().getBytes());
    }
    os.flush();
    os.close();
}

From source file:org.flowable.ui.modeler.service.FlowableDecisionTableService.java

protected void exportDecisionTable(HttpServletResponse response, AbstractModel decisionTableModel) {
    DecisionTableRepresentation decisionTableRepresentation = getDecisionTableRepresentation(
            decisionTableModel);//from ww  w .  j a va2s .co m

    try {

        JsonNode editorJsonNode = objectMapper.readTree(decisionTableModel.getModelEditorJson());

        // URLEncoder.encode will replace spaces with '+', to keep the actual name replacing '+' to '%20'
        String fileName = URLEncoder.encode(decisionTableRepresentation.getName(), "UTF-8").replaceAll("\\+",
                "%20") + ".dmn";
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName);

        ServletOutputStream servletOutputStream = response.getOutputStream();
        response.setContentType("application/xml");

        DmnDefinition dmnDefinition = dmnJsonConverter.convertToDmn(editorJsonNode, decisionTableModel.getId(),
                decisionTableModel.getVersion(), decisionTableModel.getLastUpdated());
        byte[] xmlBytes = dmnXmlConverter.convertToXML(dmnDefinition);

        BufferedInputStream in = new BufferedInputStream(new ByteArrayInputStream(xmlBytes));

        byte[] buffer = new byte[8096];
        while (true) {
            int count = in.read(buffer);
            if (count == -1)
                break;
            servletOutputStream.write(buffer, 0, count);
        }

        // Flush and close stream
        servletOutputStream.flush();
        servletOutputStream.close();

    } catch (Exception e) {
        LOGGER.error("Could not export decision table model", e);
        throw new InternalServerErrorException("Could not export decision table model");
    }
}

From source file:com.ephesoft.dcma.gwt.admin.bm.server.ExportBatchClassDownloadServlet.java

/**
 * Overriden doGet method.//from www . j a v  a  2s .c  o m
 * 
 * @param request HttpServletRequest
 * @param response HttpServletResponse
 * @throws IOException
 */
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    BatchClassService batchClassService = this.getSingleBeanOfType(BatchClassService.class);
    BatchSchemaService batchSchemaService = this.getSingleBeanOfType(BatchSchemaService.class);
    BatchClass batchClass = batchClassService.getLoadedBatchClassByIdentifier(req.getParameter("identifier"));
    if (batchClass == null) {
        LOG.error("Incorrect batch class identifier specified.");
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Incorrect batch class identifier specified.");
    } else {
        Calendar cal = Calendar.getInstance();
        String exportSerailizationFolderPath = batchSchemaService.getBatchExportFolderLocation();

        SimpleDateFormat formatter = new SimpleDateFormat("MMddyy", Locale.getDefault());
        String formattedDate = formatter.format(new Date());
        String zipFileName = batchClass.getIdentifier() + BatchClassManagementConstants.UNDERSCORE
                + formattedDate + BatchClassManagementConstants.UNDERSCORE + cal.get(Calendar.HOUR_OF_DAY)
                + cal.get(Calendar.SECOND);

        String tempFolderLocation = exportSerailizationFolderPath + File.separator + zipFileName;
        File copiedFolder = new File(tempFolderLocation);

        if (copiedFolder.exists()) {
            copiedFolder.delete();
        }

        copiedFolder.mkdirs();

        BatchClassUtil.copyModules(batchClass);
        BatchClassUtil.copyDocumentTypes(batchClass);
        BatchClassUtil.copyScannerConfig(batchClass);
        BatchClassUtil.exportEmailConfiguration(batchClass);
        BatchClassUtil.exportUserGroups(batchClass);
        BatchClassUtil.exportBatchClassField(batchClass);

        File serializedExportFile = new File(
                tempFolderLocation + File.separator + batchClass.getIdentifier() + SERIALIZATION_EXT);

        try {
            SerializationUtils.serialize(batchClass, new FileOutputStream(serializedExportFile));
            boolean isImagemagickBaseFolder = false;
            String imageMagickBaseFolderParam = req
                    .getParameter(batchSchemaService.getImagemagickBaseFolderName());
            if (imageMagickBaseFolderParam != null && (imageMagickBaseFolderParam
                    .equalsIgnoreCase(batchSchemaService.getImagemagickBaseFolderName())
                    || Boolean.parseBoolean(imageMagickBaseFolderParam))) {
                isImagemagickBaseFolder = true;
            }

            boolean isSearchSampleName = false;
            String isSearchSampleNameParam = req.getParameter(batchSchemaService.getSearchSampleName());
            if (isSearchSampleNameParam != null
                    && (isSearchSampleNameParam.equalsIgnoreCase(batchSchemaService.getSearchSampleName())
                            || Boolean.parseBoolean(isSearchSampleNameParam))) {
                isSearchSampleName = true;
            }

            File originalFolder = new File(
                    batchSchemaService.getBaseSampleFDLock() + File.separator + batchClass.getIdentifier());

            if (originalFolder.isDirectory()) {

                validateFolderAndFile(batchSchemaService, copiedFolder, isImagemagickBaseFolder,
                        isSearchSampleName, originalFolder);
            }

        } catch (FileNotFoundException e) {
            // Unable to read serializable file
            LOG.error("Error occurred while creating the serializable file." + e, e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Error occurred while creating the serializable file.");

        } catch (IOException e) {
            // Unable to create the temporary export file(s)/folder(s)
            LOG.error("Error occurred while creating the serializable file." + e, e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Error occurred while creating the serializable file.Please try again");
        }
        resp.setContentType("application/x-zip\r\n");
        resp.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName + ZIP_EXT + "\"\r\n");
        ServletOutputStream out = null;
        ZipOutputStream zout = null;
        try {
            out = resp.getOutputStream();
            zout = new ZipOutputStream(out);
            FileUtils.zipDirectory(tempFolderLocation, zout, zipFileName);
            resp.setStatus(HttpServletResponse.SC_OK);
        } catch (IOException e) {
            // Unable to create the temporary export file(s)/folder(s)
            LOG.error("Error occurred while creating the zip file." + e, e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to export.Please try again.");
        } finally {
            // clean up code
            if (zout != null) {
                zout.close();
            }
            if (out != null) {
                out.flush();
            }
            FileUtils.deleteDirectoryAndContentsRecursive(copiedFolder);
        }
    }
}

From source file:jp.co.opentone.bsol.framework.web.view.util.ViewHelper.java

protected void doDownload(HttpServletResponse response, InputStream in) throws IOException {
    ServletOutputStream o = getServletOutputStream(response);
    try {//w  ww .  j av a2 s  . co  m
        final int bufLength = 4096;
        byte[] buf = new byte[bufLength];
        int i = 0;
        while ((i = in.read(buf, 0, buf.length)) != -1) {
            o.write(buf, 0, i);
        }

        o.flush();
        o.close();
    } catch (IOException e) {
        if (isDownloadCanceled(e)) {
            log.warn("Download canceled.");
        } else {
            throw e;
        }
    }
}

From source file:com.portfolio.data.attachment.FileServlet.java

void RetrieveAnswer(HttpURLConnection connection, HttpServletResponse response, String referer)
        throws MalformedURLException, IOException {
    /// Receive answer
    InputStream in;/*from   w ww.ja  v  a2  s  .c  om*/
    try {
        in = connection.getInputStream();
    } catch (Exception e) {
        System.out.println(e.toString());
        in = connection.getErrorStream();
    }

    InitAnswer(connection, response, referer);

    /// Write back data
    DataInputStream stream = new DataInputStream(in);
    byte[] buffer = new byte[1024];
    int size;
    ServletOutputStream out = null;
    try {
        out = response.getOutputStream();
        while ((size = stream.read(buffer, 0, buffer.length)) != -1)
            out.write(buffer, 0, size);

    } catch (Exception e) {
        System.out.println(e.toString());
        System.out.println("Writing messed up!");
    } finally {
        in.close();
        out.flush(); // close() should flush already, but Tomcat 5.5 doesn't
        out.close();
    }
}

From source file:fr.insalyon.creatis.vip.query.server.rpc.FileDownload.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    User user = (User) req.getSession().getAttribute(CoreConstants.SESSION_USER);
    String queryId = req.getParameter("queryid");
    String path = req.getParameter("path");
    String queryName = req.getParameter("name");
    String tab[] = path.split("/");

    if (user != null && queryId != null && !queryId.isEmpty()) {

        try {/*w w  w  .  j a va2 s .c  om*/

            String k = new String();

            int l = tab.length;
            for (int i = 0; i < l - 1; i++) {
                k += "//" + tab[i];
            }
            File file = new File(k);
            logger.info("that" + k);
            if (file.isDirectory()) {

                file = new File(k + "/" + tab[l - 1]);

            }
            int length = 0;
            ServletOutputStream op = resp.getOutputStream();
            ServletContext context = getServletConfig().getServletContext();
            String mimetype = context.getMimeType(file.getName());

            logger.info("(" + user.getEmail() + ") Downloading '" + file.getAbsolutePath() + "'.");

            resp.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
            resp.setContentLength((int) file.length());
            //name of the file in servlet download
            resp.setHeader("Content-Disposition", "attachment; filename=\"" + queryName + "_"
                    + getCurrentTimeStamp().toString().replaceAll(" ", "_") + ".txt" + "\"");

            byte[] bbuf = new byte[4096];
            DataInputStream in = new DataInputStream(new FileInputStream(file));

            while ((in != null) && ((length = in.read(bbuf)) != -1)) {
                op.write(bbuf, 0, length);
            }

            in.close();
            op.flush();
            op.close();
        } catch (Exception ex) {
            logger.error(ex);
        }

    }
}

From source file:org.kuali.student.core.document.ui.server.upload.UploadServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    DocumentInfo info = null;//  ww  w.j av  a  2 s  . c om
    try {
        info = documentService.getDocument(request.getParameter("docId"), ContextUtils.getContextInfo());
    } catch (Exception e) {
        LOG.error("Exception occurred", e);
    }

    if (info != null && info.getDocumentBinary() != null && info.getDocumentBinary().getBinary() != null
            && !(info.getDocumentBinary().getBinary().isEmpty())) {

        ServletOutputStream op = response.getOutputStream();
        try {
            byte[] fileBytes = Base64.decodeBase64(info.getDocumentBinary().getBinary().getBytes());
            int length = fileBytes.length;

            ServletContext context = getServletConfig().getServletContext();
            String mimetype = context.getMimeType(info.getFileName());

            response.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
            response.setContentLength(length);
            response.setHeader("Content-Disposition", "attachment; filename=\"" + info.getFileName() + "\"");

            //
            //  Stream to the requester.
            //
            op.write(fileBytes, 0, length);
        } catch (Exception e) {
            LOG.error("Exception occurred", e);
        } finally {
            op.flush();
            op.close();
        }

    } else {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println(
                "Sorry, the file could not be retrieved.  It may not exist, or the server could not be contacted.");
    }

}