Example usage for javax.servlet ServletOutputStream close

List of usage examples for javax.servlet ServletOutputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with this stream.

Usage

From source file:org.wso2.carbon.bpel.ui.bpel2svg.PNGGenarateServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request  servlet request//from  ww w  .  jav a2 s. c om
 * @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 {

    Log log = LogFactory.getLog(PNGGenarateServlet.class);
    HttpSession session = request.getSession(true);
    String pid = CharacterEncoder.getSafeText(request.getParameter("pid"));
    ServletConfig config = getServletConfig();
    String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session);
    ConfigurationContext configContext = (ConfigurationContext) config.getServletContext()
            .getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
    String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
    String processDef;
    ProcessManagementServiceClient client;
    SVGInterface svg;
    String svgStr;
    try {
        client = new ProcessManagementServiceClient(cookie, backendServerURL, configContext,
                request.getLocale());
        //Gets the bpel process definition needed to create the SVG from the processId
        processDef = client.getProcessInfo(QName.valueOf(pid)).getDefinitionInfo().getDefinition()
                .getExtraElement().toString();

        BPELInterface bpel = new BPELImpl();
        //Converts the bpel process definition to an omElement which is how the AXIS2 Object Model (AXIOM)
        // represents an XML document
        OMElement bpelStr = bpel.load(processDef);
        /**
         * Process the OmElement containing the bpel process definition
         * Process the subactivites of the bpel process by iterating through the omElement
         * */
        bpel.processBpelString(bpelStr);

        //Create a new instance of the LayoutManager for the bpel process
        LayoutManager layoutManager = BPEL2SVGFactory.getInstance().getLayoutManager();
        //Set the layout of the SVG to vertical
        layoutManager.setVerticalLayout(true);
        //Get the root activity i.e. the Process Activity
        layoutManager.layoutSVG(bpel.getRootActivity());

        svg = new SVGImpl();
        //Set the root activity of the SVG i.e. the Process Activity
        svg.setRootActivity(bpel.getRootActivity());
        //Set the content type of the HTTP response as "image/png"
        response.setContentType("image/png");
        //Create an instance of ServletOutputStream to write the output
        ServletOutputStream sos = response.getOutputStream();
        //Convert the image as a byte array of a PNG
        byte[] pngBytes = svg.toPNGBytes();
        // stream to write binary data into the response
        sos.write(pngBytes);
        sos.flush();
        sos.close();

    } catch (ProcessManagementException e) {
        log.error("PNG Generation Error", e);
    }

}

From source file:pivotal.au.se.gemfirexdweb.controller.CreateProcedureController.java

@RequestMapping(value = "/createprocedure", method = RequestMethod.POST)
public String createProcedureAction(@ModelAttribute("procedureAttribute") NewProcedure procedureAttribute,
        Model model, HttpServletResponse response, HttpServletRequest request, HttpSession session)
        throws Exception {
    if (session.getAttribute("user_key") == null) {
        logger.debug("user_key is null new Login required");
        response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
        return null;
    } else {//from   www . j  a  v  a  2s. c o  m
        Connection conn = AdminUtil.getConnection((String) session.getAttribute("user_key"));
        if (conn == null) {
            response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
            return null;
        } else {
            if (conn.isClosed()) {
                response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
                return null;
            }
        }

    }

    logger.debug("Received request to action an event for create Procedure");

    String schema = procedureAttribute.getSchemaName().trim();

    if (schema.length() == 0) {
        schema = (String) session.getAttribute("schema");
    }

    logger.debug("New Procedure schema name = " + schema);
    logger.debug("New Procedure name = " + procedureAttribute.getProcedureName());

    // perform some action here with what we have
    String submit = request.getParameter("pSubmit");

    if (submit != null) {
        if (submit.equalsIgnoreCase("Parameter(s)")) {
            int cols = Integer.parseInt(request.getParameter("numParams"));
            int numParams = Integer.parseInt((String) session.getAttribute("numParams"));

            numParams = numParams + cols;

            session.setAttribute("numParams", "" + numParams);
            model.addAttribute("numParams", numParams);
        } else {
            // build create HDFS Store SQL
            StringBuffer createProcedure = new StringBuffer();

            createProcedure
                    .append("CREATE PROCEDURE " + schema + "." + procedureAttribute.getProcedureName() + " \n");

            String[] parameterTypes = request.getParameterValues("parameter_type[]");
            String[] parameterNames = request.getParameterValues("parameter_name[]");
            String[] dataTypes = request.getParameterValues("data_type[]");
            String[] columnPrecision = request.getParameterValues("column_precision[]");

            logger.debug("parameterTypes = " + Arrays.toString(parameterTypes));
            logger.debug("parameterNames = " + Arrays.toString(parameterNames));
            logger.debug("dataTypes = " + Arrays.toString(dataTypes));
            logger.debug("columnPrecision = " + Arrays.toString(columnPrecision));

            int i = 0;

            int size = 0;

            if (parameterNames != null) {
                size = parameterNames.length;

                for (String parameterName : parameterNames) {
                    if (i == 0) {
                        createProcedure.append("(");
                    }

                    createProcedure.append(parameterTypes[i] + " " + parameterName + " " + dataTypes[i]);
                    if (columnPrecision[i].length() != 0) {
                        createProcedure.append("(" + columnPrecision[i] + ")");
                    }

                    i++;
                    if (i < size) {
                        createProcedure.append(", \n");
                    }
                }

                if (i >= 1) {
                    createProcedure.append(") \n");
                }
            }

            if (!checkIfParameterEmpty(request, "language")) {
                createProcedure.append("LANGUAGE " + procedureAttribute.getLanguage() + " \n");
            }

            if (!checkIfParameterEmpty(request, "parameterStyle")) {
                createProcedure.append("PARAMETER STYLE " + procedureAttribute.getParameterStyle() + " \n");
            }

            if (!checkIfParameterEmpty(request, "sqlAccess")) {
                createProcedure.append(procedureAttribute.getSqlAccess() + " \n");
            }

            if (!checkIfParameterEmpty(request, "dynamicResultsets")) {
                createProcedure
                        .append("DYNAMIC RESULT SETS " + procedureAttribute.getDynamicResultsets() + " \n");
            }

            createProcedure.append("EXTERNAL NAME '" + procedureAttribute.getExternalName() + "'\n");

            if (submit.equalsIgnoreCase("create")) {
                Result result = new Result();

                logger.debug("Creating Procedure as -> " + createProcedure.toString());

                result = GemFireXDWebDAOUtil.runCommand(createProcedure.toString(),
                        (String) session.getAttribute("user_key"));

                model.addAttribute("result", result);

            } else if (submit.equalsIgnoreCase("Show SQL")) {
                logger.debug("Create Procedure SQL as follows as -> " + createProcedure.toString());
                model.addAttribute("sql", createProcedure.toString());
            } else if (submit.equalsIgnoreCase("Save to File")) {
                response.setContentType(SAVE_CONTENT_TYPE);
                response.setHeader("Content-Disposition", "attachment; filename="
                        + String.format(FILENAME, procedureAttribute.getProcedureName()));

                ServletOutputStream out = response.getOutputStream();
                out.println(createProcedure.toString());
                out.close();
                return null;
            }
        }

    }

    // This will resolve to /WEB-INF/jsp/create-procedure.jsp
    return "create-procedure";
}

From source file:org.wso2.carbon.reporting.ui.servlet.BeanCollectionReportServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request  servlet request/* w w  w .j a v  a 2s.  c  o m*/
 * @param response servlet response
 * @throws ReportingException if failed to handle report request
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ReportingException {

    String component = request.getParameter("component");
    String template = request.getParameter("template");
    String type = request.getParameter("type");
    String reportData = request.getParameter("reportDataSession");
    String downloadFileName = null;

    if (component == null || template == null || type == null || reportData == null) {
        throw new ReportingException(
                "required one or more parameters missing (component ,template , reportType, reportData)");
    }

    if (type.equals("pdf")) {
        response.setContentType("application/pdf");
        downloadFileName = template + ".pdf";
    } else if (type.equals("excel")) {
        response.setContentType("application/vnd.ms-excel");
        downloadFileName = template + ".xls";
    } else if (type.equals("html")) {
        response.setContentType("text/html");

    } else {
        throw new ReportingException("requested report type can not be support");
    }
    if (downloadFileName != null) {
        response.setHeader("Content-Disposition", "attachment; filename=\"" + downloadFileName + "\"");
    }
    Object reportDataObject = request.getSession().getAttribute(reportData);
    if (reportDataObject == null) {
        throw new ReportingException("can't generate report , data unavailable in session ");
    }

    try {
        String serverURL = CarbonUIUtil.getServerURL(request.getSession().getServletContext(),
                request.getSession());
        ConfigurationContext configurationContext = (ConfigurationContext) request.getSession()
                .getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
        String cookie = (String) request.getSession().getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);

        ReportResourceSupplierClient resourceSupplierClient = new ReportResourceSupplierClient(cookie,
                serverURL, configurationContext);

        String reportResource = resourceSupplierClient.getReportResources(component, template);
        JRDataSource jrDataSource = new BeanCollectionReportData().getReportDataSource(reportDataObject);
        JasperPrintProvider jasperPrintProvider = new JasperPrintProvider();
        JasperPrint jasperPrint = jasperPrintProvider.createJasperPrint(jrDataSource, reportResource,
                new ReportParamMap[0]);
        request.getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint);
        ReportStream reportStream = new ReportStream();
        ByteArrayOutputStream outputStream = reportStream.getReportStream(jasperPrint, type);
        ServletOutputStream servletOutputStream = response.getOutputStream();
        try {
            outputStream.writeTo(servletOutputStream);
            outputStream.flush();
        } finally {
            outputStream.close();
            servletOutputStream.close();
        }

    } catch (Exception e) {
        String msg = "Error occurred handling " + template + "report request from " + component;
        log(msg);
        throw new ReportingException(msg, e);
    }
}

From source file:com.arcadian.loginservlet.LecturesServlet.java

/**
 * Handles the HTTP//from  w  w w . j  av a  2s .c  om
 * <code>GET</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (request.getParameter("filename") != null) {
        String fileName = request.getParameter("filename");
        File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileName);
        System.out.println("File location on server::" + file.getAbsolutePath());
        ServletContext ctx = getServletContext();
        InputStream fis = new FileInputStream(file);
        String mimeType = ctx.getMimeType(file.getAbsolutePath());
        System.out.println("mime type=" + mimeType);
        response.setContentType(mimeType != null ? mimeType : "application/octet-stream");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

        ServletOutputStream os = response.getOutputStream();
        byte[] bufferData = new byte[102400];
        int read = 0;
        while ((read = fis.read(bufferData)) != -1) {
            os.write(bufferData, 0, read);
        }
        os.flush();
        os.close();
        fis.close();
        System.out.println("File downloaded at client successfully");
    }

    processRequest(request, response);
}

From source file:pivotal.au.se.gemfirexdweb.controller.CreateFunctionController.java

@RequestMapping(value = "/createfunction", method = RequestMethod.POST)
public String createFunctionAction(@ModelAttribute("functionAttribute") NewFunction functionAttribute,
        Model model, HttpServletResponse response, HttpServletRequest request, HttpSession session)
        throws Exception {
    if (session.getAttribute("user_key") == null) {
        logger.debug("user_key is null new Login required");
        response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
        return null;
    } else {//from  ww w  .  j  a va  2s  .c  o m
        Connection conn = AdminUtil.getConnection((String) session.getAttribute("user_key"));
        if (conn == null) {
            response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
            return null;
        } else {
            if (conn.isClosed()) {
                response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
                return null;
            }
        }

    }

    logger.debug("Received request to action an event for create Procedure");

    String schema = functionAttribute.getSchemaName().trim();

    if (schema.length() == 0) {
        schema = (String) session.getAttribute("schema");
    }

    logger.debug("New Function schema name = " + schema);
    logger.debug("New Function name = " + functionAttribute.getFunctionName());

    // perform some action here with what we have
    String submit = request.getParameter("pSubmit");

    if (submit != null) {
        if (submit.equalsIgnoreCase("Parameter(s)")) {
            int cols = Integer.parseInt(request.getParameter("numParams"));
            int numParams = Integer.parseInt((String) session.getAttribute("numParams"));

            numParams = numParams + cols;

            session.setAttribute("numParams", "" + numParams);
            model.addAttribute("numParams", numParams);
        } else {
            // build create HDFS Store SQL
            StringBuffer createFunction = new StringBuffer();

            createFunction
                    .append("CREATE FUNCTION " + schema + "." + functionAttribute.getFunctionName() + " \n");

            String[] parameterTypes = request.getParameterValues("parameter_type[]");
            String[] parameterNames = request.getParameterValues("parameter_name[]");
            String[] dataTypes = request.getParameterValues("data_type[]");
            String[] columnPrecision = request.getParameterValues("column_precision[]");

            logger.debug("parameterTypes = " + Arrays.toString(parameterTypes));
            logger.debug("parameterNames = " + Arrays.toString(parameterNames));
            logger.debug("dataTypes = " + Arrays.toString(dataTypes));
            logger.debug("columnPrecision = " + Arrays.toString(columnPrecision));

            int i = 0;
            int size = 0;

            if (parameterNames != null) {
                size = parameterNames.length;

                for (String parameterName : parameterNames) {
                    if (i == 0) {
                        createFunction.append("(");
                    }

                    createFunction.append(parameterName + " " + dataTypes[i]);
                    if (columnPrecision[i].length() != 0) {
                        createFunction.append("(" + columnPrecision[i] + ")");
                    }

                    i++;
                    if (i < size) {
                        createFunction.append(", \n");
                    }
                }

                if (i >= 1) {
                    createFunction.append(") \n");
                }
            }

            createFunction.append("RETURNS " + functionAttribute.getReturnType());
            if (functionAttribute.getReturnPrecision().trim().length() != 0) {
                createFunction.append("(" + functionAttribute.getReturnPrecision() + ") \n");
            } else {
                createFunction.append(" \n");
            }

            if (!checkIfParameterEmpty(request, "language")) {
                createFunction.append("LANGUAGE " + functionAttribute.getLanguage() + " \n");
            }

            createFunction.append("EXTERNAL NAME '" + functionAttribute.getExternalName() + "' \n");

            if (!checkIfParameterEmpty(request, "parameterStyle")) {
                createFunction.append("PARAMETER STYLE " + functionAttribute.getParameterStyle() + " \n");
            }

            if (!checkIfParameterEmpty(request, "sqlAccess")) {
                createFunction.append(functionAttribute.getSqlAccess() + " \n");
            }

            if (!checkIfParameterEmpty(request, "ifNull")) {
                createFunction.append(functionAttribute.getIfNull() + " \n");
            }

            if (submit.equalsIgnoreCase("create")) {
                Result result = new Result();

                logger.debug("Creating Function as -> " + createFunction.toString());

                result = GemFireXDWebDAOUtil.runCommand(createFunction.toString(),
                        (String) session.getAttribute("user_key"));

                model.addAttribute("result", result);
                model.addAttribute("returnType", functionAttribute.getReturnType());
            } else if (submit.equalsIgnoreCase("Show SQL")) {
                logger.debug("Create Function SQL as follows as -> " + createFunction.toString());
                model.addAttribute("sql", createFunction.toString());
                model.addAttribute("returnType", functionAttribute.getReturnType());
            } else if (submit.equalsIgnoreCase("Save to File")) {
                response.setContentType(SAVE_CONTENT_TYPE);
                response.setHeader("Content-Disposition",
                        "attachment; filename=" + String.format(FILENAME, functionAttribute.getFunctionName()));

                ServletOutputStream out = response.getOutputStream();
                out.println(createFunction.toString());
                out.close();
                return null;
            }
        }

    }

    // This will resolve to /WEB-INF/jsp/create-function.jsp
    return "create-function";
}

From source file:org.codelibs.fess.web.admin.DataAction.java

@Execute(validator = false)
public String download() {
    final DateFormat df = new SimpleDateFormat(CoreLibConstants.DATE_FORMAT_DIGIT_ONLY);
    final StringBuilder buf = new StringBuilder();
    buf.append("backup-");
    buf.append(df.format(new Date()));
    buf.append(".xml");

    final HttpServletResponse response = ResponseUtil.getResponse();
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + buf.toString() + "\"");

    try {//w w w.  ja v a2 s  . c  o  m
        final ServletOutputStream sos = response.getOutputStream();
        try {
            databaseService.exportData(sos);
            sos.flush();
        } finally {
            sos.close();
        }
        return null;
    } catch (final Exception e) {
        logger.error("Failed to export data.", e);
        throw new SSCActionMessagesException(e, "errors.failed_to_export_data");
    }
}

From source file:springapp.web.controller.theme.DownloadController.java

public ModelAndView handleRequest(HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws Exception {

    String templateIdString = httpServletRequest.getParameter(ApplicationConstants.TEMPLATE_ID);

    byte templateId = null != templateIdString ? Byte.parseByte(templateIdString) : 0;
    String templateName = templateId == 0 ? "blue" : "gray";

    String shemaNameParam = httpServletRequest.getParameter(ApplicationConstants.NEW_SCHEMA_NAME);
    String newSchemaName = (null != shemaNameParam) && (!"".equals(shemaNameParam)) ? shemaNameParam
            : "default";

    String versionString = httpServletRequest.getParameter("version");
    String version = (null == versionString) ? "3.2" : versionString;

    HttpSession session = httpServletRequest.getSession();

    ServletContext servletContext = session.getServletContext();
    WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    //String resourcesPath = (String)context.getBean("resourcesPath");

    ResourcesHolder currentSchema = (ResourcesHolder) session
            .getAttribute(ApplicationConstants.CURRENT_SCHEMA_ATTRIBUTE_NAME/*+version*/);
    String resourcesPath = currentSchema.getResourcesPath();
    ResourcesLoader loader = loaderFactory.getResourcesLoader(currentSchema, context);

    httpServletResponse.setContentType("application/zip");

    httpServletResponse.setHeader("Pragma", "no-cache");
    httpServletResponse.setHeader("Cache-Control", "no-cache");
    httpServletResponse.setHeader("Expires", "-1");
    httpServletResponse.setHeader("Content-Disposition",
            "attachment; filename=\"xtheme-" + newSchemaName + ".zip\";");
    //httpServletResponse.setContentLength(zipOS.size());
    ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
    ZipOutputStream zipOS = new ZipOutputStream(servletOutputStream);

    zipOS = loader.outForZip(currentSchema, resourcesPath, zipOS, context, newSchemaName, templateName,
            version);// ww  w  .  j a  v a 2s.c o m

    zipOS.flush();
    zipOS.close();
    servletOutputStream.flush();
    servletOutputStream.close();

    logger.info("DownloadController processed! ");

    return null;
}

From source file:com.seer.datacruncher.spring.ForgetPasswordController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isEmailSent = false;
    String userName = request.getParameter("userName");
    String email = request.getParameter("email");
    ServletOutputStream out = null;
    response.setContentType("application/json");
    out = response.getOutputStream();/*from  w w w  . ja v  a2 s  .co m*/
    if (userName == null || "".equalsIgnoreCase(userName.trim())) {
        out.write("userNameRequired".getBytes());
        out.flush();
        out.close();
        return null;
    }
    if (email == null || "".equalsIgnoreCase(email.trim())) {
        out.write("emailRequired".getBytes());
        out.flush();
        out.close();
        return null;
    }

    UserEntity userEntity = new UserEntity();
    userEntity = usersDao.findUserByNameNMailId(userName, email);

    ObjectMapper mapper = new ObjectMapper();
    mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
    Update updateResult = new Update();
    if (userEntity != null) {
        String tempPassword = RandomStringUtils.randomAlphanumeric(4);
        userEntity.setPassword(tempPassword);
        updateResult = usersDao.update(userEntity);
        if (updateResult.isSuccess()) {
            MailConfig mailConfig = new MailConfig();
            mailConfig.setMailTo(userEntity.getEmail());
            mailConfig.setMailFrom(mailFrom);
            mailConfig.setSubject(mailSubject);
            Map<String, String> model = new HashMap<String, String>();
            model.put("name", userEntity.getUserName());
            model.put("tempPassword", tempPassword);
            String mailContent = CommonUtils.mergeVelocityTemplateForEmail(velocityEngine, mailTemplate, model);
            mailConfig.setText(mailContent);
            try {
                Mail.getJavaMailService().sendMail(mailConfig);
                isEmailSent = true;
            } catch (Exception e) {
                isEmailSent = false;
                log.error("Failed to dispatch mail:", e);

            }
        }
        if (!isEmailSent) {
            updateResult.setMessage(I18n.getMessage("error.emailConfigError"));
            updateResult.setSuccess(false);
        } else {
            updateResult.setMessage(I18n.getMessage("success.emailConfigSuccess"));
        }

    } else {
        updateResult.setMessage(I18n.getMessage("error.emailError"));
        updateResult.setSuccess(false);

    }
    out.write(mapper.writeValueAsBytes(updateResult));
    out.flush();
    out.close();
    return null;
}

From source file:pivotal.au.se.gemfirexdweb.controller.GatewayReceiverController.java

@RequestMapping(value = "/gatewayreceivers", method = RequestMethod.POST)
public String performGatewayReceiversAction(Model model, HttpServletResponse response,
        HttpServletRequest request, HttpSession session) throws Exception {
    if (session.getAttribute("user_key") == null) {
        logger.debug("user_key is null new Login required");
        response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
        return null;
    } else {/*w w w .j  a v  a 2 s .co m*/
        Connection conn = AdminUtil.getConnection((String) session.getAttribute("user_key"));
        if (conn == null) {
            response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
            return null;
        } else {
            if (conn.isClosed()) {
                response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
                return null;
            }
        }

    }

    int startAtIndex = 0, endAtIndex = 0;
    Result result = new Result();
    List<GatewayReceiver> gatewayreceivers = null;
    String ddlString = null;

    logger.debug("Received request to perform an action on the gateway recievers");

    GatewayReceiverDAO grDAO = GemFireXDWebDAOFactory.getGatewayRecieverDAO();

    if (request.getParameter("search") != null) {
        gatewayreceivers = grDAO.retrieveGatewayReceiverList((String) session.getAttribute("schema"),
                (String) request.getParameter("search"), (String) session.getAttribute("user_key"));

        model.addAttribute("search", (String) request.getParameter("search"));
    } else {
        String[] tableList = request.getParameterValues("selected_gatewayreceivers[]");
        String commandStr = request.getParameter("submit_mult");

        logger.debug("tableList = " + Arrays.toString(tableList));
        logger.debug("command = " + commandStr);

        // start actions now if tableList is not null

        if (tableList != null) {
            List al = new ArrayList<Result>();
            List<String> al2 = new ArrayList<String>();

            for (String id : tableList) {
                if (commandStr.equalsIgnoreCase("DDL") || commandStr.equalsIgnoreCase("DDL_FILE")) {
                    ddlString = grDAO.generateDDL(id, (String) session.getAttribute("user_key"));
                    al2.add(ddlString);
                } else {
                    result = null;
                    result = grDAO.simplegatewayReceiverCommand(id, commandStr,
                            (String) session.getAttribute("user_key"));
                    al.add(result);
                }
            }

            if (commandStr.equalsIgnoreCase("DDL")) {
                request.setAttribute("arrayresultddl", al2);
            } else if (commandStr.equalsIgnoreCase("DDL_FILE")) {
                response.setContentType(SAVE_CONTENT_TYPE);
                response.setHeader("Content-Disposition",
                        "attachment; filename=" + String.format(FILENAME, "GatewayReceiverDDL"));

                ServletOutputStream out = response.getOutputStream();
                for (String ddl : al2) {
                    out.println(ddl);
                }

                out.close();
                return null;
            } else {
                model.addAttribute("arrayresult", al);
            }
        }

        gatewayreceivers = grDAO.retrieveGatewayReceiverList((String) session.getAttribute("schema"), null,
                (String) session.getAttribute("user_key"));
    }

    model.addAttribute("records", gatewayreceivers.size());
    model.addAttribute("estimatedrecords", gatewayreceivers.size());

    UserPref userPref = (UserPref) session.getAttribute("prefs");

    if (gatewayreceivers.size() <= userPref.getRecordsToDisplay()) {
        model.addAttribute("gatewayreceivers", gatewayreceivers);
    } else {
        if (request.getParameter("startAtIndex") != null) {
            startAtIndex = Integer.parseInt(request.getParameter("startAtIndex"));
        }

        if (request.getParameter("endAtIndex") != null) {
            endAtIndex = Integer.parseInt(request.getParameter("endAtIndex"));
            if (endAtIndex > gatewayreceivers.size()) {
                endAtIndex = gatewayreceivers.size();
            }
        } else {
            endAtIndex = userPref.getRecordsToDisplay();
        }

        List subList = gatewayreceivers.subList(startAtIndex, endAtIndex);
        model.addAttribute("gatewayreceivers", subList);
    }

    model.addAttribute("startAtIndex", startAtIndex);
    model.addAttribute("endAtIndex", endAtIndex);

    // This will resolve to /WEB-INF/jsp/gatewayreceivers.jsp
    return "gatewayreceivers";

}

From source file:org.inbio.ait.web.ajax.controller.TaxonomyAutoCompleteController.java

/**
 * Writes the response in the output!.//from ww  w . jav  a  2 s. c om
 * @param request
 * @param response
 * @param acnList
 * @return
 * @throws Exception
 */
private ModelAndView writeReponse(HttpServletRequest request, HttpServletResponse response,
        List<AutocompleteNode> acnList) throws Exception {

    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");
    // Binary output
    ServletOutputStream out = response.getOutputStream();

    if (acnList != null) {

        for (AutocompleteNode sp : acnList) {
            out.println(sp.getItemName() + "\t" + sp.getItemId());
        }
    }

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

    return null;
}