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.activiti.app.rest.idm.IdmProfileResource.java

@RequestMapping(value = "/profile-picture", method = RequestMethod.GET)
public void getProfilePicture(HttpServletResponse response) {
    try {//  w w  w .j  a va 2s  .c om
        Picture picture = identityService.getUserPicture(SecurityUtils.getCurrentUserId());
        response.setContentType(picture.getMimeType());
        ServletOutputStream servletOutputStream = response.getOutputStream();
        BufferedInputStream in = new BufferedInputStream(new ByteArrayInputStream(picture.getBytes()));

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

        // Flush and close stream
        servletOutputStream.flush();
        servletOutputStream.close();
    } catch (Exception e) {
        throw new InternalServerErrorException("Could not get profile picture", e);
    }
}

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

private ModelAndView writeReponse(HttpServletRequest request, HttpServletResponse response,
        List<AutocompleteNode> acnList) throws Exception {

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

    if (acnList != null) {
        StringBuilder result = new StringBuilder();
        result.append("<?xml version='1.0' encoding='ISO-8859-1'?><response>");
        for (AutocompleteNode sp : acnList) {
            result.append("<node><id>" + sp.getItemId() + "</id>");
            result.append("<name>" + sp.getItemName() + "</name></node>");
        }/*from   ww  w.  j a  v a 2 s .com*/
        result.append("</response>");
        out.println(result.toString());
    }

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

    return null;
}

From source file:jetbrains.buildServer.torrent.TorrentTransportTest.java

@BeforeMethod
public void setUp() throws Exception {
    super.setUp();
    myServer = new Server(12345);
    WebAppContext handler = new WebAppContext();
    handler.setResourceBase("/");
    handler.setContextPath(CONTEXT_PATH);
    myDownloadMap = new HashMap<String, File>();
    myDownloadAttempts = new ArrayList<String>();
    myDownloadHonestly = true;// ww  w . j  a  va2 s  .c o  m
    myDownloadHacks = new HashMap<String, byte[]>();
    myDownloadHackAttempts = new ArrayList<String>();
    handler.addServlet(new ServletHolder(new HttpServlet() {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            myDownloadAttempts.add(req.getPathInfo());
            final ServletOutputStream os = resp.getOutputStream();
            final File file = myDownloadMap.get(req.getPathInfo());
            final byte[] bytes = FileUtils.readFileToByteArray(file);
            os.write(bytes);
            os.close();
        }
    }), "/*");
    myServer.setHandler(handler);
    myServer.start();

    myAgentParametersMap = new HashMap<String, String>();

    Mockery m = new Mockery();
    myBuild = m.mock(AgentRunningBuild.class);
    final BuildProgressLogger myLogger = new BaseServerLoggerFacade() {
        @Override
        public void flush() {
        }

        @Override
        protected void log(final BuildMessage1 message) {

        }
    };

    m.checking(new Expectations() {
        {
            allowing(myBuild).getSharedConfigParameters();
            will(returnValue(myAgentParametersMap));
            allowing(myBuild).getBuildTypeId();
            will(returnValue("TC_Gaya80x_BuildDist"));
            allowing(myBuild).getBuildLogger();
            will(returnValue(myLogger));
        }
    });

    myDirectorySeeder = new TorrentsDirectorySeeder(createTempDir(), -1, 1);

    myTorrentTransport = new TorrentTransportFactory.TorrentTransport(myDirectorySeeder, new HttpClient(),
            myBuild.getBuildLogger()) {
        @Override
        protected byte[] download(@NotNull String urlString) throws IOException {
            if (myDownloadHonestly) {
                return super.download(urlString);
            } else {
                myDownloadHackAttempts.add(urlString);
                return myDownloadHacks.get(urlString);
            }
        }
    };

    myTempDir = createTempDir();
}

From source file:com.maogousoft.wuliu.controller.DriverController.java

public void exportExcel() throws IOException {
    StringBuffer from = new StringBuffer();
    from.append("from logistics_driver where status = 1 ");
    from.append(createOrder());// www.  j a va  2s  .c o  m
    Page<Record> page = Db.paginate(getPageIndex(), 100000, "select * ", from.toString());
    List<Record> list = page.getList();
    Dict.fillDictToRecords(page.getList());

    String headers = "?|?|??|??|?|??|||?|??||?|??|?|??|?";
    String attributes = "id|phone|name|recommender|plate_number|id_card|car_type_str|car_length|car_weight|gold|regist_time|car_phone|start_province_str|start_city_str|end_province_str|end_city_str";

    Workbook wb = new HSSFWorkbook();
    Sheet sheet = wb.createSheet();
    Row headerRow = sheet.createRow(0);
    List<String> headerList = WuliuStringUtils.parseVertical(headers);
    for (int j = 0; j < headerList.size(); j++) {
        String attr = headerList.get(j);
        Cell cell = headerRow.createCell(j);
        cell.setCellValue(attr);
    }

    for (int i = 0; i < list.size(); i++) {
        Record record = list.get(i);
        Row row = sheet.createRow(i + 1);

        List<String> attrList = WuliuStringUtils.parseVertical(attributes);
        for (int j = 0; j < attrList.size(); j++) {
            String attr = attrList.get(j);
            Cell cell = row.createCell(j);
            Object value = getValue(record, attr);
            cell.setCellValue(value + "");
        }
    }

    HttpServletResponse resp = getResponse();
    String filename = TimeUtil.format(new Date(), "'?'yyyyMMdd_HHmmss'.xls'");
    resp.addHeader("Content-Disposition",
            "attachment;filename=" + new String(filename.getBytes("GBK"), "ISO-8859-1"));
    ServletOutputStream out = resp.getOutputStream();
    wb.write(out);
    out.close();
    renderNull();
}

From source file:com.maogousoft.wuliu.controller.DriverController.java

/**
 * /*  www .  j  a v a  2  s.c  o m*/
 * @description ? 
 * @author shevliu
 * @email shevliu@gmail.com
 * 201386 ?11:47:19
 * @throws IOException
 */
public void exportPendingAudit() throws IOException {
    StringBuffer from = new StringBuffer();
    from.append("from logistics_driver where status = 0 ");
    from.append(createOrder());
    Page<Record> page = Db.paginate(getPageIndex(), 100000, "select * ", from.toString());
    List<Record> list = page.getList();
    Dict.fillDictToRecords(page.getList());

    String headers = "?|?|??|??|?|??|||?|??||?|??|?|??|?";
    String attributes = "id|phone|name|recommender|plate_number|id_card|car_type_str|car_length|car_weight|gold|regist_time|car_phone|start_province_str|start_city_str|end_province_str|end_city_str";

    Workbook wb = new HSSFWorkbook();
    Sheet sheet = wb.createSheet();
    Row headerRow = sheet.createRow(0);
    List<String> headerList = WuliuStringUtils.parseVertical(headers);
    for (int j = 0; j < headerList.size(); j++) {
        String attr = headerList.get(j);
        Cell cell = headerRow.createCell(j);
        cell.setCellValue(attr);
    }

    for (int i = 0; i < list.size(); i++) {
        Record record = list.get(i);
        Row row = sheet.createRow(i + 1);
        List<String> attrList = WuliuStringUtils.parseVertical(attributes);
        for (int j = 0; j < attrList.size(); j++) {
            String attr = attrList.get(j);
            Cell cell = row.createCell(j);
            Object value = getValue(record, attr);
            cell.setCellValue(value + "");
        }
    }

    HttpServletResponse resp = getResponse();
    String filename = TimeUtil.format(new Date(), "'?'yyyyMMdd_HHmmss'.xls'");
    resp.addHeader("Content-Disposition",
            "attachment;filename=" + new String(filename.getBytes("GBK"), "ISO-8859-1"));
    ServletOutputStream out = resp.getOutputStream();
    wb.write(out);
    out.close();
    renderNull();
}

From source file:org.springside.modules.security.jcaptcha.JCaptchaFilter.java

/**
 * ???./*  w  ww  . jav a 2s.  c om*/
 */
protected void genernateCaptchaImage(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException {

    ServletUtils.setDisableCacheHeader(response);
    response.setContentType("image/jpeg");

    ServletOutputStream out = response.getOutputStream();
    try {
        String captchaId = request.getSession(true).getId();
        BufferedImage challenge = (BufferedImage) captchaService.getChallengeForID(captchaId,
                request.getLocale());
        ImageIO.write(challenge, "jpg", out);
        out.flush();
    } catch (CaptchaServiceException e) {
        logger.error(e.getMessage(), e);
    } finally {
        out.close();
    }
}

From source file:com.concursive.connect.web.modules.documents.beans.FileDownload.java

/**
 * Description of the Method//w  w w . j a v a 2  s . co  m
 *
 * @param context Description of the Parameter
 * @param text    Description of the Parameter
 * @throws Exception Description of the Exception
 */
public void sendTextAsFile(ActionContext context, String text) throws Exception {
    context.getResponse().setContentType("application/octet-stream");
    context.getResponse().setHeader("Content-Disposition", "attachment;filename=" + displayName + ";");
    context.getResponse().setContentLength((int) text.length());

    ServletOutputStream outputStream = context.getResponse().getOutputStream();
    StringReader strReader = new StringReader(text);
    int data;
    while ((data = strReader.read()) != -1) {
        outputStream.write(data);
    }
    strReader.close();
    outputStream.close();
}

From source file:com.tasktop.c2c.server.internal.wiki.server.WikiServiceController.java

@Section(value = "Attachments")
@Title("Retrieve Image")
@Documentation("Retrieve an Image from a Page")
@RequestMapping(value = "{pageId}/attachment/{name:.*}", method = RequestMethod.GET)
public void getImage(@PathVariable(value = "pageId") Integer pageId,
        @PathVariable(value = "name") String imageName, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    String etag = request.getHeader("If-None-Match");
    if (etag != null && etag.length() > 1 && etag.charAt(0) == '"' && etag.charAt(etag.length() - 1) == '"') {
        etag = etag.substring(1, etag.length() - 1);
    }//from  w ww.  j av a  2s.c om
    Attachment attachment;
    try {
        attachment = service.retrieveAttachmentByNameWithETag(pageId, imageName, etag);
    } catch (EntityNotFoundException e) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    if (attachment.getContent() == null) {
        // ETag match
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }
    String modified = formatRFC2822(attachment.getModificationDate());
    if (modified.equals(request.getHeader("If-Modified-Since"))) {
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }
    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentLength(attachment.getSize());
    response.setContentType(attachment.getMimeType());
    response.setHeader("ETag", "\"" + attachment.getEtag() + "\"");
    response.setHeader("Modified", modified);

    ServletOutputStream outputStream = response.getOutputStream();
    try {
        outputStream.write(attachment.getContent());
    } finally {
        outputStream.close();
    }
}

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

/**
 * Write the XML to be parsed on the analysis view
 * Case 0: If there is just one criteria category or especifically these categories
 * (geographical-taxonomical or or taxonomical-indicator). It means type 0 on xml
 * @param request//from w w  w .  j  a v  a  2  s .c o m
 * @param response
 * @param totalMatch
 * @param matchesByPolygon
 * @return
 * @throws java.lang.Exception
 */
private ModelAndView writeReponse0(HttpServletRequest request, HttpServletResponse response, Long totalMatch,
        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>0</type>");
    result.append("<total>" + totalMatch + "</total>");
    result.append("<totalp>" + totalPercentage + "</totalp></response>");

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

    return null;
}

From source file:cn.newgxu.lab.core.config.MappingJacksonJsonpView.java

@Override
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    if (request.getMethod().toUpperCase().equals("GET")) {
        if (request.getParameterMap().containsKey("callback")) {
            ServletOutputStream ostream = response.getOutputStream();
            //            try
            ostream.write(new String("try{" + request.getParameter("callback") + "(").getBytes());
            super.render(model, request, response);
            ostream.write(new String(");}catch(e){}").getBytes());
            //            ????closeflushspring?
            //            ?
            ostream.flush();//from   w w w .j ava  2  s .  c  o  m
            ostream.close();
        } else {
            super.render(model, request, response);
        }
    } else {
        super.render(model, request, response);
    }
}