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.red5.stream.http.servlet.TransportSegment.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *//* w w  w.j  av  a2  s. co  m*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.errorf("Segment requested");

    // http://localhost:5080/httplivestreamingstreaming/test1.ts

    String servletPath = request.getServletPath();

    int segmentDuration = availabilityService.getSegmentTimeLimit() / 1000;
    int numMaxSegments = availabilityService.getNumMaxSegments();
    int numExpiredSegmentsOnCDN = availabilityService.getNumExpiredSegmentsOnCDN();
    /*
     * CDN Segment Age:
     *       For a Origin-Pull CDN, a MPEG-TS segment should expire
     *       once it is not longer available on the server for a cycle.
     *       Calcuate by taking the duration of the segment, and multiplying
     *       it by the number of max segments, and adding twice the segment
     *       duration to that value. For example, a if a segment is 6
     *       seconds long, and there can only be 10 segments available
     *       on the server at a given time, the first segment is no longer
     *       available 66 seconds after it was first created.
     */
    int cdnSegmentAge = (segmentDuration * numMaxSegments) + (numExpiredSegmentsOnCDN * segmentDuration);

    String[] path = servletPath.split("/");

    /*
     * @param we are expecting the following servlet path: /Application/Stream/MobileProfileName/stream00000000000.ts
     */

    String streamName = null;
    String mobileProfileName = null;
    String requestedSegment = null;
    String[] parts = servletPath.split("/");
    log.tracef("Parts: %s", parts.length);
    if (!(parts.length == 4)) {
        log.errorf(
                "Servlet Request was not formatted as expected. Expected /streamName/stream.m3u8 or /streamName/mobileProfileName/stream.m3u8 , but got: %s",
                servletPath);
        response.sendError(404, "Segment not found");
        return;
    } else {
        streamName = parts[1];
        log.errorf("Stream Name: %s", streamName);
        mobileProfileName = parts[2];
        log.errorf("Mobile Profile Name: %s", mobileProfileName);
        log.tracef("Requested Profile Name: %s", mobileProfileName);
        requestedSegment = path[3];
        log.tracef("Requested Segment: %s", requestedSegment);
    }

    /*   TODO: Define if this is appropriate for Origin-Pull CDNs.
     *       If the same CDN requests the file again, its probably necessary.
     *       Until proven otherwise, I am removing this code.
     *       Maybe when I reFOSS the app I will make this tunable;
     *    
     *   //fail if they request the same segment
     *  // if(tunableSessionBehavior){
     *    HttpSession session = ((HttpServletRequest) request).getSession(false);
     *   if (session != null) {
     *      String sN = (String) session.getAttribute("streamName");
     *      String mPN = (String) session.getAttribute("mobileProfileName");
     *      if (streamName.equals(sN)||mobileProfileName.equals(mPN)) {
     *         log.info("Segment %s was already played by this requester", sN+mPN);
     *         return;
     *      }
     *      session.setAttribute("stream", streamName);
     *      session.setAttribute("mobileProfileName", mobileProfileName);
     *   }
     *      
     */

    String fileNameSansExtension = requestedSegment.replace(".ts", "");
    String sequenceNumberStr = fileNameSansExtension.replace("stream", "");
    int sequenceNumber = Integer.valueOf(sequenceNumberStr);
    log.tracef("Segment sequence: %s", sequenceNumber);

    if (availabilityService.isAvailable(streamName, mobileProfileName)) {
        response.setContentType("video/MP2T");
        byte[] segment = availabilityService.getSegment(streamName, mobileProfileName, sequenceNumber);
        if (segment != null) {
            InputStream iS = new ByteArrayInputStream(segment);
            ServletOutputStream oS = response.getOutputStream();
            response.setHeader("Cache-Control", "max-age=" + cdnSegmentAge);
            response.setContentType("video/MP2T");
            response.setContentLength(segment.length);
            if (IOUtils.copy(iS, oS) < 0) {
                log.errorf("Error serving TS: %s", servletPath);
                response.sendError(500, "Unable to serve segment");
            }
            oS.flush();
            oS.close();
        } else {
            log.infof("Segment for %s was not found", streamName);
        }
    } else {
        //T0D0 <== done? let requester know that stream segment is not available
        response.sendError(404, "Segment not found");
    }

}

From source file:de.berlios.jedi.presentation.editor.GetJispObjectAction.java

/**
 * Handle server requests./*from   w w  w  .  j  av  a  2  s . c  om*/
 * 
 * @param mapping
 *            The ActionMapping used to select this instance.
 * @param form
 *            The optional ActionForm bean for this request (if any).
 * @param request
 *            The HTTP request we are processing.
 * @param response
 *            The HTTP response we are creating.
 */
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {

    JispIdManager jispIdManager = (JispIdManager) request.getSession()
            .getAttribute(EditorKeys.JISP_ID_MANAGER_KEY);

    String jispObjectId = request.getParameter("jispObjectId");

    if (jispObjectId == null) {
        return errorForward(mapping, request, new ActionMessage("missedId", "jispObjectId"), "missedId",
                Keys.ADD_STATUS_FORWARD_NAME);
    }

    JispObject jispObject = jispIdManager.getJispObject(jispObjectId);

    if (jispObject == null) {
        return errorForward(mapping, request, new ActionMessage("invalidId", "jispObjectId"), "invalidId",
                Keys.ADD_STATUS_FORWARD_NAME);
    }

    response.setContentType(jispObject.getMimeType());

    ServletOutputStream out = null;
    try {
        out = response.getOutputStream();
        out.write(jispObject.getData());
    } catch (IOException e) {
        LogFactory.getLog(GetJispObjectAction.class)
                .error("IOException when writing the JispObject to the" + " ServlerOutputStream", e);

        return errorForward(mapping, request, new ActionMessage("failedJispObjectWriteToOutputStream"),
                "failedJispObjectWriteToOutputStream", Keys.ADD_STATUS_FORWARD_NAME);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
    }

    return null;
}

From source file:org.exist.webstart.JnlpWriter.java

void sendImage(JnlpHelper jh, JnlpJarFiles jf, String filename, HttpServletResponse response)
        throws IOException {
    logger.debug("Send image " + filename);

    String type = null;/*from  w ww  .  jav a  2 s .  co m*/
    if (filename.endsWith(".gif")) {
        type = "image/gif";
    } else if (filename.endsWith(".png")) {
        type = "image/png";
    } else {
        type = "image/jpeg";
    }

    final InputStream is = this.getClass().getResourceAsStream("resources/" + filename);
    if (is == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "Image file '" + filename + "' not found.");
        return;
    }

    // Copy data
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    IOUtils.copy(is, baos);
    IOUtils.closeQuietly(is);

    // It is very improbable that a 64 bit jar is needed, but
    // it is better to be ready
    response.setContentType(type);
    response.setContentLength(baos.size());
    //response.setHeader("Content-Length", ""+baos.size());

    final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    final ServletOutputStream os = response.getOutputStream();

    try {
        IOUtils.copy(bais, os);
    } catch (final IllegalStateException ex) {
        logger.debug(ex.getMessage());
    } catch (final IOException ex) {
        logger.debug("Ignored IOException for '" + filename + "' " + ex.getMessage());
    }

    // Release resources
    os.flush();
    os.close();
    bais.close();
}

From source file:org.wso2.carbon.mediation.library.ui.LibraryAdminClient.java

public void downloadCappArchive(String filename, HttpServletResponse response)
        throws IOException, MediationLibraryAdminServiceException {

    ServletOutputStream out = response.getOutputStream();
    DataHandler dataHandler = stub.downloadLibraryArchive(filename);
    if (dataHandler != null) {
        response.setHeader("Content-Disposition", "fileName=" + filename + ".zip");
        response.setContentType(dataHandler.getContentType());
        InputStream in = dataHandler.getDataSource().getInputStream();
        int nextChar;
        while ((nextChar = in.read()) != -1) {
            out.write((char) nextChar);
        }//from  ww  w. j a v a2  s.co m
        out.flush();
        in.close();
        out.close();
    } else {
        out.write("The requested library archive was not found on the server".getBytes());
    }

}

From source file:com.denimgroup.threadfix.webapp.controller.VulnerabilitySearchController.java

private boolean sendFileContentToClient(String content, HttpServletResponse response) throws IOException {
    if (content == null) {
        return false;
    }/*  w  w w  .ja v  a 2  s  .  c o m*/
    InputStream in = new ByteArrayInputStream(content.getBytes("UTF-8"));

    if (in != null) {
        ServletOutputStream out = response.getOutputStream();

        byte[] outputByteBuffer = new byte[65535];

        int remainingSize = in.read(outputByteBuffer, 0, 65535);

        // copy binary content to output stream
        while (remainingSize != -1) {
            out.write(outputByteBuffer, 0, remainingSize);
            remainingSize = in.read(outputByteBuffer, 0, 65535);
        }
        in.close();
        out.flush();
        out.close();
        return true;
    } else {
        return false;
    }
}

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

@RequestMapping(value = "/createtable", method = RequestMethod.POST)
public String createTableAction(@ModelAttribute("tableAttribute") NewTable tableAttribute, 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 ava 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;
            }
        }

    }

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

    String tabName = tableAttribute.getTableName();

    String[] columnNames = request.getParameterValues("column_name[]");
    String[] columnTypes = request.getParameterValues("column_type[]");
    String[] columnPrecision = request.getParameterValues("column_precision[]");
    String[] columnDefaultValues = request.getParameterValues("column_default_value[]");
    String[] columnSelectedNulls = request.getParameterValues("column_selected_null[]");
    String[] columnSelectedPrimaryKeys = request.getParameterValues("column_selected_primary_key[]");
    String[] columnSelectedAutoIncrements = request.getParameterValues("column_selected_auto_increment[]");

    logger.debug("New Table Name = " + tabName);
    logger.debug("columnNames = " + Arrays.toString(columnNames));
    logger.debug("columnTypes = " + Arrays.toString(columnTypes));
    logger.debug("columnPrecision = " + Arrays.toString(columnPrecision));
    logger.debug("columnDefaultValues = " + Arrays.toString(columnDefaultValues));
    logger.debug("columnSelectedNulls = " + Arrays.toString(columnSelectedNulls));
    logger.debug("columnSelectedPrimaryKeys = " + Arrays.toString(columnSelectedPrimaryKeys));
    logger.debug("columnSelectedAutoIncrements = " + Arrays.toString(columnSelectedAutoIncrements));

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

    DiskStoreDAO dsDAO = GemFireXDWebDAOFactory.getDiskStoreDAO();
    HdfsStoreDAO hdfsDAO = GemFireXDWebDAOFactory.getHdfsStoreDAO();

    List<DiskStore> dsks = dsDAO.retrieveDiskStoreForCreateList((String) session.getAttribute("user_key"));

    List<HdfsStore> hdfs = hdfsDAO.retrieveHdfsStoreForCreateList((String) session.getAttribute("user_key"));

    model.addAttribute("diskstores", dsks);
    model.addAttribute("hdfsstores", hdfs);

    if (submit != null) {

        if (submit.equalsIgnoreCase("Column(s)")) {
            TypeDAO typeDAO = GemFireXDWebDAOFactory.getTypeDAO();
            List<Type> types = typeDAO.retrieveTypeList((String) session.getAttribute("schema"), null,
                    (String) session.getAttribute("user_key"));

            model.addAttribute("types", types);

            int cols = Integer.parseInt(request.getParameter("numColumns"));
            int numColumns = Integer.parseInt((String) session.getAttribute("numColumns"));

            numColumns = numColumns + cols;

            session.setAttribute("numColumns", "" + numColumns);
            session.setAttribute("tabName", tableAttribute.getTableName());

            model.addAttribute("numColumns", numColumns);
            model.addAttribute("tabName", tableAttribute.getTableName());
            model.addAttribute("hdfsStore", tableAttribute.getHdfsStore());
            model.addAttribute("diskStore", tableAttribute.getDiskStore());
        } else {
            // build create table SQL 
            StringBuffer createTable = new StringBuffer();
            String schema = tableAttribute.getSchemaName();
            if (schema.length() == 0) {
                schema = (String) session.getAttribute("schema");
            }

            createTable.append("create table " + schema + "." + tabName + " \n");
            createTable.append("(");

            int i = 0;
            String val = null;

            if (columnNames != null) {
                int size = columnNames.length;
                for (String columnName : columnNames) {
                    createTable.append(columnName + " ");
                    createTable.append(columnTypes[i]);

                    // doing precision / size
                    val = checkIfEntryExists(columnPrecision, i);
                    if (val != null) {
                        createTable.append("(" + columnPrecision[i] + ")");
                    }
                    val = null;

                    // doing auto increment check here
                    val = checkIfEntryExists(columnSelectedAutoIncrements, i);
                    if (val != null) {
                        // should check for column type here
                        if (val.equalsIgnoreCase("Y")) {
                            createTable.append(" generated always as identity");
                        }
                    }
                    val = null;

                    // doing default value
                    val = checkIfEntryExists(columnDefaultValues, i);
                    if (val != null) {
                        // should check for column type here
                        createTable.append(" default " + columnDefaultValues[i]);
                    }
                    val = null;

                    // doing not null check here
                    val = checkIfEntryExists(columnSelectedNulls, i);
                    if (val != null) {
                        if (val.equalsIgnoreCase("Y")) {
                            createTable.append(" NOT NULL");
                        }
                    }
                    val = null;

                    // doing primary key check here
                    val = checkIfEntryExists(columnSelectedPrimaryKeys, i);
                    if (val != null) {
                        if (val.equalsIgnoreCase("Y")) {
                            createTable.append(" CONSTRAINT " + tabName + "_PK Primary Key");
                        }
                    }
                    val = null;

                    int j = size - 1;
                    if (i < j) {
                        createTable.append(",\n");
                    }

                    i++;
                }

            }

            createTable.append(")\n");

            if (request.getParameter("dataPolicy").equalsIgnoreCase("REPLICATE")) {
                createTable.append("REPLICATE\n");
            }

            if (!checkIfParameterEmpty(request, "serverGroups")) {
                createTable.append("SERVER GROUPS (" + tableAttribute.getServerGroups() + ")\n");
            }

            if (!checkIfParameterEmpty(request, "persistant")) {
                if (tableAttribute.getPersistant().equalsIgnoreCase("Y")) {
                    createTable.append("PERSISTENT ");
                    if (!checkIfParameterEmpty(request, "diskStore")) {
                        createTable.append("'" + tableAttribute.getDiskStore() + "' ");
                        if (!checkIfParameterEmpty(request, "persistenceType")) {
                            createTable.append(tableAttribute.getPersistenceType() + "\n");
                        } else {
                            createTable.append("\n");
                        }

                    }
                }
            }

            if (request.getParameter("dataPolicy").equalsIgnoreCase("PARTITION")) {
                if (!checkIfParameterEmpty(request, "partitionBy")) {
                    createTable.append("PARTITION BY " + tableAttribute.getPartitionBy() + "\n");
                }

                if (!checkIfParameterEmpty(request, "colocateWith")) {
                    createTable.append("COLOCATE WITH (" + tableAttribute.getColocateWith() + ")\n");
                }

                if (!checkIfParameterEmpty(request, "redundancy")) {
                    createTable.append("REDUNDANCY " + tableAttribute.getRedundancy() + "\n");
                }
            }

            if (!checkIfParameterEmpty(request, "hdfsStore")) {
                createTable.append("HDFSSTORE (" + tableAttribute.getHdfsStore() + ") ");
                if (request.getParameter("writeonly").equalsIgnoreCase("Y")) {
                    createTable.append("WRITEONLY\n");
                } else {
                    // need to ad eviction properties here
                    if (!checkIfParameterEmpty(request, "evictionbycriteria")) {
                        createTable.append(
                                "EVICTION BY CRITERIA (" + tableAttribute.getEvictionbycriteria() + ")\n");
                    }

                    if (!checkIfParameterEmpty(request, "evictionfrequency")) {
                        createTable
                                .append("EVICTION FREQUENCY " + tableAttribute.getEvictionfrequency() + "\n");
                    } else {
                        if (request.getParameter("evictincoming").equalsIgnoreCase("Y")) {
                            createTable.append("EVICT INCOMING\n");
                        }
                    }
                }

            }

            if (!checkIfParameterEmpty(request, "gatewaysender")) {
                createTable.append("GATEWAYSENDER (" + tableAttribute.getGatewaysender() + ")\n");
            }

            if (!checkIfParameterEmpty(request, "asynceventlistener")) {
                createTable.append("ASYNCEVENTLISTENER (" + tableAttribute.getAsynceventlistener() + ")\n");
            }

            if (!checkIfParameterEmpty(request, "offheap")) {
                if (request.getParameter("offheap").equalsIgnoreCase("Y")) {
                    createTable.append("OFFHEAP\n");
                }
            }

            if (!checkIfParameterEmpty(request, "other")) {
                createTable.append(tableAttribute.getOther() + "\n");
            }

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

                logger.debug("Creating table as -> " + createTable.toString());

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

                model.addAttribute("result", result);
                model.addAttribute("hdfsStore", tableAttribute.getHdfsStore());
                model.addAttribute("diskStore", tableAttribute.getDiskStore());

            } else if (submit.equalsIgnoreCase("Show SQL")) {
                logger.debug("Table SQL as follows as -> " + createTable.toString());
                model.addAttribute("sql", createTable.toString());
                model.addAttribute("hdfsStore", tableAttribute.getHdfsStore());
                model.addAttribute("diskStore", tableAttribute.getDiskStore());
            } else if (submit.equalsIgnoreCase("Save to File")) {
                response.setContentType(SAVE_CONTENT_TYPE);
                response.setHeader("Content-Disposition",
                        "attachment; filename=" + String.format(FILENAME, tabName));

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

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

From source file:gov.nih.nci.calims2.ui.common.document.DocumentController.java

/**
 * // ww w  .ja v  a2s.co m
 * @param response The servlet response.
 * @param id The id of the filledreport to view.
 */
@RequestMapping("/download.do")
public void download(HttpServletResponse response, @RequestParam("id") Long id) {
    try {
        Document document = getMainService().findById(Document.class, id);
        ServletOutputStream servletOutputStream = response.getOutputStream();
        File downloadedFile = storageService.get(document, new File(tempfiledir));
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + document.getName());
        FileInputStream fileInputStream = new FileInputStream(downloadedFile);
        IOUtils.copyLarge(fileInputStream, servletOutputStream);
        IOUtils.closeQuietly(fileInputStream);
        servletOutputStream.flush();
        servletOutputStream.close();
        downloadedFile.delete();
    } catch (IOException e1) {
        throw new RuntimeException("IOException in download", e1);
    } catch (StorageServiceException e) {
        throw new RuntimeException("StorageServiceException in download", e);
    }
}

From source file:sys.core.manager.RecursosManager.java

public void viewArchivo(String archivo) {
    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
    response.setContentType("application/force-download");
    response.addHeader("Content-Disposition", "attachment; filename=\"" + archivo + "\"");
    ApplicationMBean applicationMBean = (ApplicationMBean) WebServletContextListener.getApplicationContext()
            .getBean("applicationMBean");
    byte[] buf = new byte[1024];
    try {/*w ww. ja  v a  2  s . co  m*/
        File file = new File(applicationMBean.getRutaArchivos() + archivo);
        long length = file.length();
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
        ServletOutputStream out = response.getOutputStream();
        response.setContentLength((int) length);
        while ((in != null) && ((length = in.read(buf)) != -1)) {
            out.write(buf, 0, (int) length);
        }
        in.close();
        out.close();
    } catch (Exception exc) {
        logger.error(exc);
    }
}

From source file:com.denimgroup.threadfix.webapp.controller.ToolsDownloadController.java

private String doDownload(HttpServletRequest request, HttpServletResponse response, String jarName) {

    String jarResource = JAR_DOWNLOAD_DIR + jarName;

    InputStream in = request.getServletContext().getResourceAsStream(jarResource);
    if (in == null) {
        exceptionLogService.storeExceptionLog(
                new ExceptionLog(new FileNotFoundException("File not found for download: " + jarResource)));
        return index();
    }//from  w  w w . j  a  v  a2s .  c  om

    try {
        ServletOutputStream out = response.getOutputStream();
        int jarSize = request.getServletContext().getResource(jarResource).openConnection().getContentLength();

        if (jarName.endsWith(".jar"))
            response.setContentType("application/java-archive");
        else
            response.setContentType("application/octet-stream");
        ;
        response.setContentLength(jarSize);
        response.addHeader("Content-Disposition", "attachment; filename=\"" + jarName + "\"");

        IOUtils.copy(in, out);
        in.close();
        out.flush();
        out.close();
    } catch (IOException ioe) {
        exceptionLogService.storeExceptionLog(new ExceptionLog(ioe));
        return index();
    }
    return null;
}

From source file:util.RelatorioUtil.java

public void criaRelatorio(List listas, String caminhorelatorio, String nomerelatorio, Map parameters)
        throws IOException, JRException {

    FacesContext fcontext = FacesContext.getCurrentInstance();
    ServletContext scontext = (ServletContext) fcontext.getExternalContext().getContext();

    String relJasper = scontext.getRealPath(caminhorelatorio);
    //InputStream inputStream = getClass().getResourceAsStream(relJasper);
    HttpServletResponse response = (HttpServletResponse) fcontext.getExternalContext().getResponse();
    ServletOutputStream responseStream = response.getOutputStream();
    JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(listas);

    response.setHeader("Content-Disposition", "inline; filename=" + nomerelatorio);
    response.setHeader("Cache-Control", "no-cache");
    response.setContentType("application/pdf");

    JasperPrint jasperPrint = JasperFillManager.fillReport(relJasper, parameters, ds);
    JasperExportManager.exportReportToPdfStream(jasperPrint, responseStream);
    byte x1[] = JasperExportManager.exportReportToPdf(jasperPrint);
    response.getOutputStream().write(x1);
    responseStream.flush();//  w  w  w .j  av a 2s  .co m
    responseStream.close();
    fcontext.renderResponse();
    fcontext.responseComplete();

}