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:pivotal.au.se.gemfirexdweb.controller.CreateTriggerController.java

@RequestMapping(value = "/createtrigger", method = RequestMethod.POST)
public String createTriggerAction(@ModelAttribute("triggerAttribute") NewTrigger triggerAttribute, 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 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 Trigger");

    TableDAO tableDAO = GemFireXDWebDAOFactory.getTableDAO();

    List<Table> tables = tableDAO.retrieveTableList((String) session.getAttribute("schema"), null,
            (String) session.getAttribute("user_key"), "tables");

    model.addAttribute("tables", tables);

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

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

    logger.debug("New Trigger schema name = " + schema);
    logger.debug("New Trigger name = " + triggerAttribute.getTriggerName());

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

    if (submit != null) {
        // build create HDFS Store SQL
        StringBuffer createTrigger = new StringBuffer();

        createTrigger.append("CREATE TRIGGER " + schema + "." + triggerAttribute.getTriggerName() + " \n");
        createTrigger.append(triggerAttribute.getBeforeOrAfter() + " \n");
        createTrigger.append(triggerAttribute.getType() + " \n");

        if (!checkIfParameterEmpty(request, "columnList")) {
            createTrigger.append("OF " + triggerAttribute.getColumnList() + " \n");
        }

        createTrigger.append("ON " + triggerAttribute.getTableName() + " \n");

        if (!checkIfParameterEmpty(request, "referencingOldClause")) {
            createTrigger.append("REFERENCING OLD AS " + triggerAttribute.getReferencingOldClause() + " \n");
        }

        if (!checkIfParameterEmpty(request, "referencingNewClause")) {
            createTrigger.append("REFERENCING NEW AS " + triggerAttribute.getReferencingNewClause() + " \n");
        }

        createTrigger.append(triggerAttribute.getForEachRow() + " \n");

        if (!checkIfParameterEmpty(request, "triggerDefinition")) {
            createTrigger.append(triggerAttribute.getTriggerDefinition() + " \n");
        }

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

            logger.debug("Creating Trigger as -> " + createTrigger.toString());

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

            model.addAttribute("result", result);
            model.addAttribute("tableName", triggerAttribute.getTableName());

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

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

    }

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

From source file:com.ibm.watson.ta.retail.DemoServlet.java

/**
 * Create and POST a request to the Watson service
 *
 * @param req/*from w w w. j a  v  a2 s .c om*/
 *            the Http Servlet request
 * @param resp
 *            the Http Servlet response
 * @throws ServletException
 *             the servlet exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

    req.setCharacterEncoding("UTF-8");
    try {
        String queryStr = req.getQueryString();
        String url = baseURL + "/v1/dilemmas";
        if (queryStr != null) {
            url += "?" + queryStr;
        }
        URI uri = new URI(url).normalize();
        logger.info("posting to " + url);

        Request newReq = Request.Post(uri);
        newReq.addHeader("Accept", "application/json");
        InputStreamEntity entity = new InputStreamEntity(req.getInputStream());
        newReq.bodyString(EntityUtils.toString(entity, "UTF-8"), ContentType.APPLICATION_JSON);

        Executor executor = this.buildExecutor(uri);
        Response response = executor.execute(newReq);
        HttpResponse httpResponse = response.returnResponse();
        resp.setStatus(httpResponse.getStatusLine().getStatusCode());

        ServletOutputStream servletOutputStream = resp.getOutputStream();
        httpResponse.getEntity().writeTo(servletOutputStream);
        servletOutputStream.flush();
        servletOutputStream.close();

        logger.info("post done");
    } catch (Exception e) {
        // Log something and return an error message
        logger.log(Level.SEVERE, "got error: " + e.getMessage(), e);
        resp.setStatus(HttpStatus.SC_BAD_GATEWAY);
    }
}

From source file:cpabe.controladores.UploadDecriptacaoServlet.java

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

    String fileName = request.getParameter("fileName");
    if (fileName == null || fileName.equals("")) {
        throw new ServletException("O nome do arquivo no pode ser null ou vazio.");
    }//from  ww  w . j  a va  2 s .c  o  m
    File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileName);
    if (!file.exists()) {
        throw new ServletException("O arquivo desejado no existe no Servidor.");
    }
    System.out.println("File location on server::" + file.getAbsolutePath());
    ServletContext ctx = getServletContext();
    InputStream fis = new FileInputStream(file);
    String mimeType = ctx.getMimeType(file.getAbsolutePath());
    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[1024];
    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");
}

From source file:com.geminimobile.web.SearchController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException arg3) throws Exception {
    SearchCommand cmd = (SearchCommand) command;
    ModelAndView mav = new ModelAndView(getSuccessView());

    CDRDataAccess cdrAccess = new CDRDataAccess();

    Date toDate = SearchCommand.m_sdf.parse(cmd.getToDate());
    long maxTimestamp = toDate.getTime();

    Date fromDate = SearchCommand.m_sdf.parse(cmd.getFromDate());
    long minTimestamp = fromDate.getTime();

    String msisdn = cmd.getMsisdn();
    String action = cmd.getAction();
    Vector<CDREntry> cdrs;//from  www.jav a  2s .  co  m

    if (action.compareToIgnoreCase("downloadcsv") == 0) {

        if (msisdn != null && msisdn.length() > 0) {
            cdrs = cdrAccess.getCDRsByMSISDN(cmd.getMsisdn(), minTimestamp, maxTimestamp, cmd.getMarket(),
                    cmd.getMessageType(), 100000); // 100,000 entries max
        } else {
            cdrs = cdrAccess.getCDRsByHour(minTimestamp, maxTimestamp, cmd.getMarket(), cmd.getMessageType(),
                    MAX_ENTRIES_PER_PAGE);
        }
        StringBuffer sb = new StringBuffer();

        // Write column headers 
        sb.append("Date/Time,Market,Type,MSISDN,MO IP address,MT IP Address,Sender Domain,Recipient Domain\n");

        for (CDREntry entry : cdrs) {
            sb.append(entry.getDisplayTimestamp() + "," + entry.getMarket() + "," + entry.getType() + ","
                    + entry.getMsisdn() + "," + entry.getMoIPAddress() + "," + entry.getMtIPAddress() + ","
                    + entry.getSenderDomain() + "," + entry.getRecipientDomain() + "\n");
        }

        String csvString = sb.toString();

        response.setBufferSize(sb.length());
        response.setContentLength(sb.length());
        response.setContentType("text/plain; charset=UTF-8");
        //response.setContentType( "text/csv" );
        //response.setContentType("application/ms-excel");
        //response.setHeader("Content-disposition", "attachment;filename=cdrResults.csv");
        response.setHeader("Content-Disposition", "attachment; filename=" + "cdrResults.csv" + ";");
        ServletOutputStream os = response.getOutputStream();

        os.write(csvString.getBytes());

        os.flush();
        os.close();

        return null;

    } else if (action.compareToIgnoreCase("graph") == 0) {
        cmd.setGraph(true);
        List<ChartSeries> chartData;
        if (msisdn != null && msisdn.length() > 0) {
            chartData = cdrAccess.getChartDataByMSISDN(cmd.getMsisdn(), minTimestamp, maxTimestamp,
                    cmd.getMarket(), cmd.getMessageType(), 100000);
        } else {
            chartData = cdrAccess.getChartDataByHour(minTimestamp, maxTimestamp, cmd.getMarket(),
                    cmd.getMessageType(), 100000);
        }

        request.getSession().setAttribute("chartData", chartData);

    } else if (action.compareToIgnoreCase("getmore") == 0) {
        cdrs = (Vector<CDREntry>) request.getSession().getAttribute("currentcdrs");
        int numCDRs = cdrs.size();
        CDREntry lastCDR = cdrs.get(numCDRs - 1);
        long lastCDRTime = Long.parseLong(lastCDR.getTimestamp());

        if (msisdn != null && msisdn.length() > 0) {
            Vector<CDREntry> moreCDRs = cdrAccess.getCDRsByMSISDN(cmd.getMsisdn(), lastCDRTime, maxTimestamp,
                    cmd.getMarket(), cmd.getMessageType(), MAX_ENTRIES_PER_PAGE);
            cdrs.addAll(moreCDRs);
        } else {
            Vector<CDREntry> moreCDRs = cdrAccess.getCDRsByHour(lastCDRTime, maxTimestamp, cmd.getMarket(),
                    cmd.getMessageType(), MAX_ENTRIES_PER_PAGE);
            cdrs.addAll(moreCDRs);
        }

        request.getSession().setAttribute("currentcdrs", cdrs);
        mav.addObject("cdrs", cdrs);
    } else {
        // Normal search            
        if (msisdn != null && msisdn.length() > 0) {
            cdrs = cdrAccess.getCDRsByMSISDN(cmd.getMsisdn(), minTimestamp, maxTimestamp, cmd.getMarket(),
                    cmd.getMessageType(), MAX_ENTRIES_PER_PAGE);
        } else {
            cdrs = cdrAccess.getCDRsByHour(minTimestamp, maxTimestamp, cmd.getMarket(), cmd.getMessageType(),
                    MAX_ENTRIES_PER_PAGE);
        }

        request.getSession().setAttribute("currentcdrs", cdrs);
        mav.addObject("cdrs", cdrs);
    }

    mav.addObject("searchCmd", cmd);

    List<Option> msgOptions = getMessageOptions();
    mav.addObject("msgTypes", msgOptions);
    List<Option> marketOptions = getMarketOptions();
    mav.addObject("marketTypes", marketOptions);

    return mav;
}

From source file:com.Uploader.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//w  w  w.  ja va2  s .co  m
 * @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 {
    //  processRequest(request, response);
    String fileName = request.getParameter("fileName");
    if (fileName == null || fileName.equals("")) {
        throw new ServletException("File Name can't be null or empty");
    }
    File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileName);
    if (!file.exists()) {
        throw new ServletException("File doesn't exists on server.");
    }
    System.out.println("File location on server::" + file.getAbsolutePath());
    ServletContext ctx = getServletContext();
    InputStream fis = new FileInputStream(file);
    String mimeType = ctx.getMimeType(file.getAbsolutePath());
    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[1024];
    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");
}

From source file:dijalmasilva.controllers.ControladorIdolo.java

@RequestMapping("/image/{id}")
public void carregaImagem(@PathVariable Long id, HttpServletResponse resp) {
    ServletOutputStream out = null;
    try {// w  ww. java  2  s  . co  m
        Idolo idolo = serviceIdolo.buscar(id);
        out = resp.getOutputStream();
        out.write(idolo.getFoto());
        out.flush();
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        try {
            out.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:com.ace.erp.filter.jcaptcha.JCaptchaFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

    response.setDateHeader("Expires", 0L);
    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    response.setHeader("Pragma", "no-cache");
    response.setContentType("image/jpeg");

    ServletOutputStream out = response.getOutputStream();

    try {//  w w  w  .  ja v  a 2 s .c  o m
        String id = request.getSession(true).getId();
        //String id = request.getRequestedSessionId();
        BufferedImage bi = JCaptcha.captchaService.getImageChallengeForID(id);

        ImageIO.write(bi, "jpg", out);
        out.flush();
    } finally {
        out.close();
    }
}

From source file:com.horstmann.violet.web.UMLEditorWebApplication.java

private void createDefaultWorkspace() throws IOException {
    setTheme(new WBootstrapTheme());
    useStyleSheet(new WLink(new WResource() {
        @Override//from www  .  j  av a2  s  .  co m
        protected void handleRequest(WebRequest request, WebResponse response) throws IOException {
            ClassLoader classLoader = this.getClass().getClassLoader();
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("text/css");
            InputStream inputStream = classLoader.getResourceAsStream("/violet.css");
            IOUtils.copy(inputStream, outputStream);
            inputStream.close();
            outputStream.close();
        }

    }));
    //URL resource = getClass().getResource("test.class.violet.html");
    //IFile aFile = new LocalFile(new File(resource.getFile()));
    GraphFile graphFile = new GraphFile(ClassDiagramGraph.class);
    IWorkspace workspace = new Workspace(graphFile);
    workspace.getAWTComponent().setSize(800, 600);
    workspace.getAWTComponent().prepareLayout();
    WorkspaceWidget workspaceWidget = new WorkspaceWidget(workspace);
    WContainerWidget root = getRoot();
    root.setWidth(new WLength(100, Unit.Percentage));
    root.setWidth(new WLength(100, Unit.Percentage));
    root.setStyleClass("root");
    root.addWidget(workspaceWidget);
    root.mouseMoved().setBlocked(true);

}

From source file:edu.umd.cs.submitServer.servlets.RobotDownloadPassingSubmissions.java

/**
 * The doGet method of the servlet. <br>
 *
 *
 * @param request/*w  w  w  .ja va 2 s  . co  m*/
 *            the request send by the client to the server
 * @param response
 *            the response send by the server to the client
 * @throws ServletException
 *             if an error occurred
 * @throws IOException
 *             if an error occurred
 */
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Connection conn = null;
    File tempfile = null;
    FileOutputStream fileOutputStream = null;
    FileInputStream fis = null;
    ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
    PrintWriter names = new PrintWriter(byteOutputStream);
    try {
        conn = getConnection();

        // get the project and all the student registrations
        Map<Integer, Submission> lastSubmissionMap = (Map<Integer, Submission>) request
                .getAttribute("lastSubmission");
        Map<Integer, Submission> bestSubmissionMap = (Map<Integer, Submission>) request
                .getAttribute("bestSubmissionMap");

        Project project = (Project) request.getAttribute("project");
        Set<StudentRegistration> registrationSet = (Set<StudentRegistration>) request
                .getAttribute("studentRegistrationSet");

        // write everything to a tempfile, then send the tempfile
        tempfile = File.createTempFile("temp", "zipfile");
        fileOutputStream = new FileOutputStream(tempfile);

        // zip aggregator
        ZipFileAggregator zipAggregator = new ZipFileAggregator(fileOutputStream);

        for (StudentRegistration registration : registrationSet) {
            @StudentRegistration.PK
            Integer studentRegistrationPK = registration.getStudentRegistrationPK();
            Submission submission = (Submission) lastSubmissionMap.get(studentRegistrationPK);
            if (!isOK(submission, conn)) {
                submission = (Submission) bestSubmissionMap.get(studentRegistrationPK);
                if (!isOK(submission, conn))
                    continue;
            }

            String status = "";
            if (registration.getInstructorLevel() != StudentRegistration.STUDENT_CAPABILITY_LEVEL)
                status = "*";
            String timestamp = submission.getFormattedSubmissionTimestamp();
            names.printf("%s,%s,%s,%s %s%n", registration.getClassAccount(), timestamp, status,
                    registration.getFirstname(), registration.getLastname());
            try {
                byte[] bytes = submission.downloadArchive(conn);
                zipAggregator.addFileFromBytes(registration.getClassAccount(),
                        submission.getSubmissionTimestamp().getTime(), bytes);
            } catch (ZipFileAggregator.BadInputZipFileException ignore) {
                // ignore, since students could submit things that aren't
                // zipfiles
                getSubmitServerServletLog().warn(ignore.getMessage(), ignore);
            }

        }
        names.close();
        try {
            zipAggregator.addPlainFileFromBytes("names.txt", byteOutputStream.toByteArray());
        } catch (BadInputZipFileException e) {
            throw new ServletException(e);
        }
        zipAggregator.close();

        // write the zipfile to the client
        response.setContentType("application/zip");
        response.setContentLength((int) tempfile.length());

        // take into account the inability of certain browsers to download
        // zipfiles
        String filename = "p" + project.getProjectNumber() + ".zip";
        Util.setAttachmentHeaders(response, filename);

        ServletOutputStream out = response.getOutputStream();
        fis = new FileInputStream(tempfile);

        IO.copyStream(fis, out);

        out.flush();
        out.close();
    } catch (SQLException e) {
        handleSQLException(e);
        throw new ServletException(e);
    } finally {
        releaseConnection(conn);
        if (tempfile != null && !tempfile.delete())
            getSubmitServerServletLog().warn("Unable to delete temporary file " + tempfile.getAbsolutePath());
        IOUtils.closeQuietly(fileOutputStream);
        IOUtils.closeQuietly(fis);
    }
}

From source file:com.ibm.watson.ta.retail.TAProxyServlet.java

/**
 * Create and POST a request to the Watson service
 *
 * @param req//w ww . j av a 2 s.c o  m
 *            the Http Servlet request
 * @param resp
 *            the Http Servlet response
 * @throws ServletException
 *             the servlet exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

    req.setCharacterEncoding("UTF-8");
    try {
        String reqURI = req.getRequestURI();
        String endpoint = reqURI.substring(reqURI.lastIndexOf('/') + 1);
        String url = baseURL + "/v1/" + endpoint;
        // concatenate query params
        String queryStr = req.getQueryString();
        if (queryStr != null) {
            url += "?" + queryStr;
        }
        URI uri = new URI(url).normalize();
        logger.info("posting to " + url);

        Request newReq = Request.Post(uri);
        newReq.addHeader("Accept", "application/json");

        String metadata = req.getHeader("x-watson-metadata");
        if (metadata != null) {
            metadata += "client-ip:" + req.getRemoteAddr();
            newReq.addHeader("x-watson-metadata", metadata);
        }

        InputStreamEntity entity = new InputStreamEntity(req.getInputStream());
        newReq.bodyString(EntityUtils.toString(entity, "UTF-8"), ContentType.APPLICATION_JSON);

        Executor executor = this.buildExecutor(uri);
        Response response = executor.execute(newReq);
        HttpResponse httpResponse = response.returnResponse();
        resp.setStatus(httpResponse.getStatusLine().getStatusCode());

        ServletOutputStream servletOutputStream = resp.getOutputStream();
        httpResponse.getEntity().writeTo(servletOutputStream);
        servletOutputStream.flush();
        servletOutputStream.close();

        logger.info("post done");
    } catch (Exception e) {
        // Log something and return an error message
        logger.log(Level.SEVERE, "got error: " + e.getMessage(), e);
        resp.setStatus(HttpStatus.SC_BAD_GATEWAY);
    }
}