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:module.siadap.presentationTier.actions.SiadapPersonnelManagement.java

private ActionForward streamSpreadsheet(final HttpServletResponse response, final String fileName,
        final HSSFWorkbook resultSheet) throws IOException {

    response.setContentType("application/xls ");
    response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");

    ServletOutputStream outputStream = response.getOutputStream();

    resultSheet.write(outputStream);//from   w  w  w .j  av a2s . c  o  m
    outputStream.flush();
    outputStream.close();

    return null;
}

From source file:it.cnr.icar.eric.server.interfaces.rest.QueryManagerURLHandler.java

/** Write the result set as a RegistryObjectList */
private void writeRegistryObjectList(List<? extends IdentifiableType> ebRegistryObjectTypeList)
        throws IOException, RegistryException {
    ServletOutputStream sout = null;
    try {/* w  w  w  .j  a v  a  2s  . c  o m*/
        sout = response.getOutputStream();

        @SuppressWarnings("unchecked")
        RegistryObjectListType ebRegistryObjectListType = bu
                .getRegistryObjectListType((List<RegistryObjectType>) ebRegistryObjectTypeList);

        //            javax.xml.bind.Marshaller marshaller = bu.rimFac.createMarshaller();
        javax.xml.bind.Marshaller marshaller = bu.getJAXBContext().createMarshaller();
        marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(ebRegistryObjectListType, sout);

    } catch (JAXBException e) {
        throw new RegistryException(e);
    } finally {
        if (sout != null) {
            sout.close();
        }
    }
}

From source file:module.siadap.presentationTier.actions.SiadapPersonnelManagement.java

private ActionForward streamSpreadsheet(final HttpServletResponse response, final String fileName,
        final Spreadsheet resultSheet) throws IOException {
    response.setContentType("application/xls ");
    response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");

    ServletOutputStream outputStream = response.getOutputStream();
    resultSheet.exportToXLSSheet(outputStream);
    outputStream.flush();//from w ww.j ava2s .  co m
    outputStream.close();

    return null;
}

From source file:org.jspresso.framework.util.resources.server.ResourceProviderServlet.java

/**
 * {@inheritDoc}/*from   ww  w . java  2 s .  c o m*/
 */
@SuppressWarnings("unchecked")
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) {

    try {
        HttpRequestHolder.setServletRequest(request);
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        List<FileItem> items = upload.parseRequest(request);
        response.setContentType("text/xml");
        ServletOutputStream out = response.getOutputStream();
        for (FileItem item : items) {
            if (!item.isFormField()) {
                out.print("<resource");
                IResourceBase uploadResource = new UploadResourceAdapter("application/octet-stream", item);
                String resourceId = ResourceManager.getInstance().register(uploadResource);
                out.print(" id=\"" + resourceId);
                // Sometimes prevents the browser to parse back the result
                // out.print("\" name=\"" + HtmlHelper.escapeForHTML(item.getName()));
                out.println("\" />");
            }
        }
        out.flush();
        out.close();
    } catch (Exception ex) {
        LOG.error("An unexpected error occurred while uploading the content.", ex);
    } finally {
        HttpRequestHolder.setServletRequest(null);
    }
}

From source file:com.francelabs.datafari.servlets.URL.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *      response)//from w  w  w.java2  s  .  com
 */
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    request.setCharacterEncoding("UTF-8");

    final String protocol = request.getScheme() + ":";

    final Map<String, String[]> requestMap = new HashMap<>();
    requestMap.putAll(request.getParameterMap());
    final IndexerQuery query = IndexerServerManager.createQuery();
    query.addParams(requestMap);
    // get the AD domain
    String domain = "";
    HashMap<String, String> h;
    try {
        h = RealmLdapConfiguration.getConfig(request);

        if (h.get(RealmLdapConfiguration.ATTR_CONNECTION_NAME) != null) {
            final String userBase = h.get(RealmLdapConfiguration.ATTR_DOMAIN_NAME).toLowerCase();
            final String[] parts = userBase.split(",");
            domain = "";
            for (int i = 0; i < parts.length; i++) {
                if (parts[i].indexOf("dc=") != -1) { // Check if the current
                    // part is a domain
                    // component
                    if (!domain.isEmpty()) {
                        domain += ".";
                    }
                    domain += parts[i].substring(parts[i].indexOf('=') + 1);
                }
            }
        }

        // Add authentication
        if (request.getUserPrincipal() != null) {
            String AuthenticatedUserName = request.getUserPrincipal().getName().replaceAll("[^\\\\]*\\\\", "");
            if (AuthenticatedUserName.contains("@")) {
                AuthenticatedUserName = AuthenticatedUserName.substring(0, AuthenticatedUserName.indexOf("@"));
            }
            if (!domain.equals("")) {
                AuthenticatedUserName += "@" + domain;
            }
            query.setParam("AuthenticatedUserName", AuthenticatedUserName);
        }
    } catch (final Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    StatsPusher.pushDocument(query, protocol);

    // String surl = URLDecoder.decode(request.getParameter("url"),
    // "ISO-8859-1");
    final String surl = request.getParameter("url");

    if (ScriptConfiguration.getProperty("ALLOWLOCALFILEREADING").equals("true")
            && !surl.startsWith("file://///")) {

        final int BUFSIZE = 4096;
        String fileName = null;

        /**
         * File Display/Download --> <!-- Written by Rick Garcia -->
         */
        if (SystemUtils.IS_OS_LINUX) {
            // try to open the file locally
            final String fileNameA[] = surl.split(":");
            fileName = URLDecoder.decode(fileNameA[1], "UTF-8");

        } else if (SystemUtils.IS_OS_WINDOWS) {
            fileName = URLDecoder.decode(surl, "UTF-8").replaceFirst("file:/", "");
        }

        final File file = new File(fileName);
        int length = 0;
        final ServletOutputStream outStream = response.getOutputStream();
        final ServletContext context = getServletConfig().getServletContext();
        String mimetype = context.getMimeType(fileName);

        // sets response content type
        if (mimetype == null) {
            mimetype = "application/octet-stream";

        }
        response.setContentType(mimetype);
        response.setContentLength((int) file.length());

        // sets HTTP header
        response.setHeader("Content-Disposition", "inline; fileName=\"" + fileName + "\"");

        final byte[] byteBuffer = new byte[BUFSIZE];
        final DataInputStream in = new DataInputStream(new FileInputStream(file));

        // reads the file's bytes and writes them to the response stream
        while (in != null && (length = in.read(byteBuffer)) != -1) {
            outStream.write(byteBuffer, 0, length);
        }

        in.close();
        outStream.close();
    } else {

        final RequestDispatcher rd = request.getRequestDispatcher(redirectUrl);
        rd.forward(request, response);
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.harvester.FileHarvestController.java

private void doDownloadTemplatePost(HttpServletRequest request, HttpServletResponse response) {

    VitroRequest vreq = new VitroRequest(request);
    FileHarvestJob job = getJob(vreq, vreq.getParameter(PARAMETER_JOB));
    File fileToSend = new File(job.getTemplateFilePath());

    response.setContentType("application/octet-stream");
    response.setContentLength((int) (fileToSend.length()));
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileToSend.getName() + "\"");

    try {/*  w  ww.ja  v a 2s  .  c  om*/
        byte[] byteBuffer = new byte[(int) (fileToSend.length())];
        DataInputStream inStream = new DataInputStream(new FileInputStream(fileToSend));

        ServletOutputStream outputStream = response.getOutputStream();
        for (int length = inStream.read(byteBuffer); length != -1; length = inStream.read(byteBuffer)) {
            outputStream.write(byteBuffer, 0, length);
        }

        inStream.close();
        outputStream.flush();
        outputStream.close();
    } catch (IOException e) {
        log.error(e, e);
    }
}

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

/**
 * Write the XML to be parsed on the analysis view
 * Case: three parameters (1)//from   www .  j  a  va2s  .  com
 * @param request
 * @param response
 * @param totalMatch
 * @param matchesByPolygon
 * @return
 * @throws java.lang.Exception
 */
private ModelAndView writeReponse1(HttpServletRequest request, HttpServletResponse response,
        List<Node> matchesByPolygon, List<Node> matchesByIndicator, Long totalMatches, Long totalPercentage)
        throws Exception {

    response.setCharacterEncoding("ISO-8859-1");
    response.setContentType("text/xml");
    ServletOutputStream out = response.getOutputStream();

    StringBuilder result = new StringBuilder();
    result.append("<?xml version='1.0' encoding='ISO-8859-1'?><response>");
    result.append("<type>1</type>");
    result.append("<total>" + totalMatches + "</total>");
    result.append("<totalp>" + totalPercentage + "</totalp>");
    for (Node mp : matchesByPolygon) {
        result.append("<bypolygon>");
        result.append("<abs>" + mp.getValue1() + "</abs>");
        result.append("<per>" + mp.getValue2() + "</per>");
        result.append("</bypolygon>");
    }
    for (Node mi : matchesByIndicator) {
        result.append("<byindicator>");
        result.append("<abs>" + mi.getValue1() + "</abs>");
        result.append("<per>" + mi.getValue2() + "</per>");
        result.append("</byindicator>");
    }
    result.append("</response>");

    out.println(result.toString());
    out.flush();
    out.close();

    return null;
}

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

void RetrieveAnswer(HttpURLConnection connection, HttpServletResponse response, String referer)
        throws MalformedURLException, IOException {
    /// Receive answer
    InputStream in;//  w  w w.j  av a2  s  .  com
    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:org.opensubsystems.core.util.servlet.WebUtils.java

/**
 * Serve files to the Internet.// ww  w.j a  v  a2s  .c o m
 *
 * @param hsrpResponse - the servlet response.
 * @param strRealPath - real path to the file to server
 * @throws IOException - an error has occurred while accessing the file or writing response
 */
public static void serveFile(HttpServletResponse hsrpResponse, String strRealPath) throws IOException {
    // TODO: Improve: Figure out, how we don't have to serve the file, 
    // but the webserver will!!! (cos.jar has a method for it, but the license
    // is to prohibitive to use it. Maybe Jetty has one too) 
    Properties prpSettings;
    int iWebFileBufferSize;

    prpSettings = Config.getInstance().getProperties();

    // Load default size of buffer to serve files 
    iWebFileBufferSize = PropertyUtils.getIntPropertyInRange(prpSettings, WEBUTILS_WEBFILE_BUFFER_SIZE,
            WEBFILE_BUFFER_DEFAULT_SIZE, "Size of a buffer to serve files ",
            // Use some reasonable lower limit
            4096,
            // This should be really limited 
            // by size of available memory
            100000000);

    ServletOutputStream sosOut = hsrpResponse.getOutputStream();
    byte[] arBuffer = new byte[iWebFileBufferSize];
    File flImage = new File(strRealPath);
    FileInputStream fisReader = new FileInputStream(flImage);

    // get extension of the file
    String strExt = strRealPath.substring(strRealPath.lastIndexOf(".") + 1, strRealPath.length());
    // set content type for particular extension
    hsrpResponse.setContentType(MimeTypeConstants.getMimeType(strExt));
    hsrpResponse.setBufferSize(WEBFILE_BUFFER_DEFAULT_SIZE);
    hsrpResponse.setContentLength((int) flImage.length());

    // TODO: Performance: BufferedInputStream allocate additional internal 
    // buffer so we have two buffers for each file of given size, evaluate 
    // if this is faster than non buffered read and if it is not, then get 
    // rid of it. But the preference is to get rid of this method all together,
    BufferedInputStream bisReader = new BufferedInputStream(fisReader, iWebFileBufferSize);
    int iRead;

    try {
        while (true) {
            iRead = bisReader.read(arBuffer);
            if (iRead != -1) {
                sosOut.write(arBuffer, 0, iRead);
            } else {
                break;
            }
        }
    } finally {
        try {
            fisReader.close();
        } finally {
            sosOut.close();
        }
    }
}

From source file:org.freeeed.search.web.controller.CaseFileDownloadController.java

@Override
public ModelAndView execute() {
    HttpSession session = this.request.getSession(true);
    SolrSessionObject solrSession = (SolrSessionObject) session
            .getAttribute(WebConstants.WEB_SESSION_SOLR_OBJECT);

    if (solrSession == null || solrSession.getSelectedCase() == null) {
        return new ModelAndView(WebConstants.CASE_FILE_DOWNLOAD);
    }/*from   w  w w .j a v  a 2 s .co m*/

    Case selectedCase = solrSession.getSelectedCase();

    String action = (String) valueStack.get("action");

    log.debug("Action called: " + action);

    File toDownload = null;
    boolean htmlMode = false;

    String docPath = (String) valueStack.get("docPath");
    String uniqueId = (String) valueStack.get("uniqueId");

    try {
        if ("exportNative".equals(action)) {
            toDownload = caseFileService.getNativeFile(selectedCase.getName(), docPath, uniqueId);

        } else if ("exportImage".equals(action)) {
            toDownload = caseFileService.getImageFile(selectedCase.getName(), docPath, uniqueId);
        } else if ("exportHtml".equals(action)) {
            toDownload = caseFileService.getHtmlFile(selectedCase.getName(), docPath, uniqueId);
            htmlMode = true;
        } else if ("exportHtmlImage".equals(action)) {
            toDownload = caseFileService.getHtmlImageFile(selectedCase.getName(), docPath);
            htmlMode = true;
        } else if ("exportNativeAll".equals(action)) {
            String query = solrSession.buildSearchQuery();
            int rows = solrSession.getTotalDocuments();

            List<SolrDocument> docs = getDocumentPaths(query, 0, rows);

            toDownload = caseFileService.getNativeFiles(selectedCase.getName(), docs);

        } else if ("exportNativeAllFromSource".equals(action)) {
            String query = solrSession.buildSearchQuery();
            int rows = solrSession.getTotalDocuments();

            List<SolrDocument> docs = getDocumentPaths(query, 0, rows);

            String source = (String) valueStack.get("source");
            try {
                source = URLDecoder.decode(source, "UTF-8");
            } catch (UnsupportedEncodingException e) {
            }

            toDownload = caseFileService.getNativeFilesFromSource(source, docs);
        } else if ("exportImageAll".equals(action)) {
            String query = solrSession.buildSearchQuery();
            int rows = solrSession.getTotalDocuments();

            List<SolrDocument> docs = getDocumentPaths(query, 0, rows);
            toDownload = caseFileService.getImageFiles(selectedCase.getName(), docs);
        }
    } catch (Exception e) {
        log.error("Problem sending cotent", e);
        valueStack.put("error", true);
    }

    if (toDownload != null) {
        try {
            int length = 0;
            ServletOutputStream outStream = response.getOutputStream();
            String mimetype = "application/octet-stream";
            if (htmlMode) {
                mimetype = "text/html";
            }

            response.setContentType(mimetype);
            response.setContentLength((int) toDownload.length());
            String fileName = toDownload.getName();

            if (!htmlMode) {
                // sets HTTP header
                response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            }

            byte[] byteBuffer = new byte[1024];
            DataInputStream in = new DataInputStream(new FileInputStream(toDownload));

            // reads the file's bytes and writes them to the response stream
            while ((in != null) && ((length = in.read(byteBuffer)) != -1)) {
                outStream.write(byteBuffer, 0, length);
            }

            in.close();
            outStream.close();
        } catch (Exception e) {
            log.error("Problem sending cotent", e);
            valueStack.put("error", true);
        }
    } else {
        valueStack.put("error", true);
    }

    return new ModelAndView(WebConstants.CASE_FILE_DOWNLOAD);
}