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:com.indeed.imhotep.web.QueryServlet.java

static void handleError(HttpServletResponse resp, boolean json, Throwable e, boolean status500,
        boolean isEventStream) throws IOException {
    if (!(e instanceof Exception || e instanceof OutOfMemoryError)) {
        throw Throwables.propagate(e);
    }/* ww w.j a  v a  2s.  c  o  m*/
    // output parse/execute error
    if (!json) {
        final ServletOutputStream outputStream = resp.getOutputStream();
        final PrintStream printStream = new PrintStream(outputStream);
        if (isEventStream) {
            resp.setContentType("text/event-stream");
            final String[] stackTrace = Throwables.getStackTraceAsString(e).split("\\n");
            printStream.println("event: servererror");
            for (String s : stackTrace) {
                printStream.println("data: " + s);
            }
            printStream.println();
        } else {
            resp.setStatus(500);
            e.printStackTrace(printStream);
            printStream.close();
        }
    } else {
        if (status500) {
            resp.setStatus(500);
        }
        // construct a parsed error object to be JSON serialized
        String clause = "";
        int offset = -1;
        if (e instanceof IQLParseException) {
            final IQLParseException IQLParseException = (IQLParseException) e;
            clause = IQLParseException.getClause();
            offset = IQLParseException.getOffsetInClause();
        }
        final String stackTrace = Throwables.getStackTraceAsString(Throwables.getRootCause(e));
        final ErrorResult error = new ErrorResult(e.getClass().getSimpleName(), e.getMessage(), stackTrace,
                clause, offset);
        resp.setContentType("application/json");
        final ObjectMapper jsonMapper = new ObjectMapper();
        final ServletOutputStream outputStream = resp.getOutputStream();
        jsonMapper.defaultPrettyPrintingWriter().writeValue(outputStream, error);
        outputStream.close();
    }
}

From source file:jahspotify.web.api.HistoryController.java

public void serializeHistoryCursor(Collection<TrackHistory> historyCursor,
        HttpServletResponse httpServletResponse) {
    try {//ww  w . jav  a  2  s .c  o m
        final ServletOutputStream httpOutputStream = httpServletResponse.getOutputStream();
        final BufferedWriter outputStream = new BufferedWriter(new OutputStreamWriter(httpOutputStream));
        outputStream.write("{");
        outputStream.write("\"count\":");
        outputStream.write("" + historyCursor.size());

        if (historyCursor.size() > 0) {
            Gson gson = new Gson();

            outputStream.write(",");
            outputStream.write("\"tracks\":[");

            for (Iterator<TrackHistory> iterator = historyCursor.iterator(); iterator.hasNext();) {
                TrackHistory next = iterator.next();
                outputStream.write(gson.toJson(toWebTrack(next)));
                if (iterator.hasNext()) {
                    outputStream.write(",");
                }
                outputStream.flush();
            }

            /*
                            while (historyCursor.hasNext())
                            {
            outputStream.write(gson.toJson(toWebTrack(historyCursor.next())));
            if (historyCursor.hasNext())
            {
                outputStream.write(",");
            }
            outputStream.flush();
                            }
            */
            outputStream.write("]");
        }
        outputStream.write("}");
        outputStream.flush();
        outputStream.close();
        httpOutputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.etudes.tool.melete.BookmarkPage.java

/**
 * writes the text file to browser//from w w  w  . j av  a2 s . c o m
 *
 * @param file -
 *            text file to download
 * @throws Exception
 */
private void download(File file) throws Exception {
    FileInputStream fis = null;
    ServletOutputStream out = null;
    try {
        String disposition = "attachment; filename=\"" + file.getName() + "\"";
        fis = new FileInputStream(file);

        FacesContext cxt = FacesContext.getCurrentInstance();
        ExternalContext context = cxt.getExternalContext();
        HttpServletResponse response = (HttpServletResponse) context.getResponse();
        response.setContentType("application/text"); // application/text
        response.addHeader("Content-Disposition", disposition);
        // Contributed by Diego for ME-233
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "public, post-check=0, must-revalidate, pre-check=0");

        out = response.getOutputStream();

        int len;
        byte buf[] = new byte[102400];
        while ((len = fis.read(buf)) > 0) {
            out.write(buf, 0, len);
        }

        out.flush();
    } catch (IOException e) {
        throw e;
    } finally {
        try {
            if (out != null)
                out.close();
        } catch (IOException e1) {
        }

        try {
            if (fis != null)
                fis.close();
        } catch (IOException e2) {
        }
    }
}

From source file:es.juntadeandalucia.panelGestion.presentacion.controlador.impl.GIController.java

public void getRAFile(Service service) {
    String errorMessage = null;//  w w w  .ja v  a  2 s . c  o m

    ServletOutputStream os = null;

    try {
        // configures the response
        String fileNameWithExtension = racontroller.getFileNameWithExtension(service);
        HttpServletResponse response = (HttpServletResponse) externalCtx.getResponse();
        response.setContentType("text/xml");
        response.addHeader("Content-disposition",
                "attachment; filename=\"".concat(fileNameWithExtension).concat("\""));

        // gets the configuration file
        InputStream is = racontroller.getConfigurationFile(service);

        os = response.getOutputStream();

        IOUtils.copy(is, os);

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

        is.close();

        facesContext.responseComplete();
    } catch (IOException e) {
        errorMessage = "Error al comprimir los archivos de configuracin: " + e.getLocalizedMessage();
    } catch (Exception e) {
        errorMessage = "Error en la descarga de la configuracin: " + e.getLocalizedMessage();
    } finally {
        try {
            if (os != null) {
                os.flush();
                os.close();
            }
        } catch (IOException e) {
            errorMessage = "Error al comprimir los archivos de configuracin: " + e.getLocalizedMessage();
        }
    }

    if (errorMessage != null) {
        StatusMessages.instance().add(Severity.ERROR, errorMessage);
        log.error(errorMessage);
    }
}

From source file:org.agnitas.web.ShowComponent.java

/**
  * Gets mailing components/*  ww  w . ja  v a 2s.c  o m*/
  * TYPE_IMAGE: if component not empty, write it into response
  * <br><br>
  * TYPE_HOSTED_IMAGE: if component not empty, write it into response
  * <br><br>
  * TYPE_THUMBMAIL_IMAGE: if component not empty, write it into response
  * <br><br>
  * TYPE_ATTACHMENT: create preview <br>
  *          write component into response
  * <br><br>
  * TYPE_PERSONALIZED_ATTACHMENT: create preview <br>
  *          write component into response
  * <br><br>
  */
@Override
public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {

    ServletOutputStream out = null;
    long len = 0;
    int compId = 0;

    if (!AgnUtils.isUserLoggedIn(req)) {
        return;
    }

    try {
        compId = Integer.parseInt(req.getParameter("compID"));
    } catch (Exception e) {
        logger.warn("Error converting "
                + (req.getParameter("compID") != null ? "'" + req.getParameter("compID") + "'"
                        : req.getParameter("compID"))
                + " to integer", e);
        return;
    }

    if (compId == 0) {
        return;
    }

    int customerID = 0;

    String customerIDStr = req.getParameter("customerID");
    if (StringUtils.isNumeric(customerIDStr)) {
        customerID = Integer.parseInt(customerIDStr);
    }

    MailingComponentDao mDao = (MailingComponentDao) WebApplicationContextUtils
            .getWebApplicationContext(this.getServletContext()).getBean("MailingComponentDao");

    MailingComponent comp = mDao.getMailingComponent(compId, AgnUtils.getCompanyID(req));

    if (comp != null) {

        switch (comp.getType()) {
        case MailingComponent.TYPE_IMAGE:
        case MailingComponent.TYPE_HOSTED_IMAGE:
            if (comp.getBinaryBlock() != null) {
                res.setContentType(comp.getMimeType());
                out = res.getOutputStream();
                out.write(comp.getBinaryBlock());
                out.flush();
                out.close();
            }
            break;
        case MailingComponent.TYPE_THUMBMAIL_IMAGE:
            if (comp.getBinaryBlock() != null) {
                res.setContentType(comp.getMimeType());
                out = res.getOutputStream();
                out.write(comp.getBinaryBlock());
                out.flush();
                out.close();
            }
            break;
        case MailingComponent.TYPE_ATTACHMENT:
        case MailingComponent.TYPE_PERSONALIZED_ATTACHMENT:
            res.setHeader("Content-Disposition", "attachment; filename=" + comp.getComponentName() + ";");
            out = res.getOutputStream();
            ApplicationContext applicationContext = WebApplicationContextUtils
                    .getWebApplicationContext(getServletContext());
            Preview preview = ((PreviewFactory) applicationContext.getBean("PreviewFactory")).createPreview();

            byte[] attachment = null;
            int mailingID = comp.getMailingID();

            if (comp.getType() == MailingComponent.TYPE_PERSONALIZED_ATTACHMENT) {
                Page page = null;
                if (customerID == 0) { // no customerID is available, take the 1st available test recipient
                    RecipientDao recipientDao = (RecipientDao) applicationContext.getBean("RecipientDao");
                    Map<Integer, String> recipientList = recipientDao
                            .getAdminAndTestRecipientsDescription(comp.getCompanyID(), mailingID);
                    customerID = recipientList.keySet().iterator().next();
                }
                page = preview.makePreview(mailingID, customerID, false);
                attachment = page.getAttachment(comp.getComponentName());

            } else {
                attachment = comp.getBinaryBlock();
            }

            len = attachment.length;
            res.setContentLength((int) len);
            out.write(attachment);
            out.flush();
            out.close();
            break;
        }
    }
}

From source file:org.exist.http.SOAPServer.java

/**
 * HTTP GET/*  www.java2  s .c o  m*/
 * Processes requests for description documents - WSDL, Human Readable and Human Readable for a specific function
 * 
 * TODO: I think simple webservices can also be called using GET, so we may need to cater for that as well
 * but first it would be best to write the doPost() method, split the code out into functions and also use it for this.
 */
public void doGet(DBBroker broker, HttpServletRequest request, HttpServletResponse response, String path)
        throws BadRequestException, PermissionDeniedException, NotFoundException, IOException {
    //set the encoding
    if (request.getCharacterEncoding() == null) {
        request.setCharacterEncoding(formEncoding);
    }

    /* Process the request */
    try {
        //Get a Description of the XQWS
        final XQWSDescription description = getXQWSDescription(broker, path, request);

        //Get the approriate description for the user
        byte[] result = null;
        if (request.getParameter("WSDL") != null || request.getParameter("wsdl") != null) {
            //WSDL document literal
            result = description.getWSDL();

            //set output content type for wsdl
            response.setContentType(MimeType.XML_TYPE.getName());
        } else if (request.getParameter("WSDLRPC") != null || request.getParameter("wsdlrpc") != null) {
            //WSDL RPC
            result = description.getWSDL(false);

            //set output content type for wsdl
            response.setContentType(MimeType.XML_TYPE.getName());
        } else if (request.getParameter("function") != null) {
            //Specific Function Description
            result = description.getFunctionDescription(request.getParameter("function"));
        } else {
            //Human Readable Description
            result = description.getHumanDescription();
        }

        //send the description to the http servlet response
        final ServletOutputStream os = response.getOutputStream();
        final BufferedOutputStream bos = new BufferedOutputStream(os);
        bos.write(result);
        bos.close();
        os.close();
    } catch (final XPathException xpe) {
        LOG.debug(xpe.getMessage());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        writeResponse(response, formatXPathException(null, path, xpe), "text/html", ENCODING);
    } catch (final SAXException saxe) {
        LOG.debug(saxe.getMessage());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        writeResponse(response,
                formatXPathException(null, path, new XPathException(
                        "SAX exception while transforming node: " + saxe.getMessage(), saxe)),
                "text/html", ENCODING);
    } catch (final TransformerConfigurationException tce) {
        LOG.debug(tce.getMessage());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        writeResponse(response,
                formatXPathException(null, path,
                        new XPathException("SAX exception while transforming node: " + tce.getMessage(), tce)),
                "text/html", ENCODING);
    }
}

From source file:com.gae.ImageServlet.java

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    MemoryFileItemFactory factory = new MemoryFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    //resp.setContentType("image/png");
    ServletOutputStream out = resp.getOutputStream();
    try {//  w w w.  j  a va2 s .c  om
        List<FileItem> list = upload.parseRequest(req);
        for (FileItem item : list) {
            if (!(item.isFormField())) {
                String fileName = item.getName();

                //Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
                //BlobKey blobKey = blobs.get("myFile");                 

                if (fileName != null && !"".equals(fileName)) {
                    int size = (int) item.getSize();
                    byte[] data = new byte[size];
                    InputStream in = item.getInputStream();
                    in.read(data);
                    //ImagesService imagesService = ImagesServiceFactory.getImagesService(); 

                    /*
                    Image oldImage = ImagesServiceFactory.makeImage(data); 
                    Transform resize = ImagesServiceFactory.makeResize(180, 150); 
                    Image newImage = imagesService.applyTransform(resize, oldImage, OutputEncoding.PNG); 
                    byte[] newImageData = newImage.getImageData();
                    out.write(newImageData);
                    */
                    /*
                    Image image = ImagesServiceFactory.makeImage(data); 
                    byte[] ImageData = image.getImageData();
                    */
                    out.flush();
                }
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:com.carfinance.module.common.controller.DocumentDownloadController.java

/**
 * ????Excel/* ww  w. j  a v a2  s  .c o m*/
 * @param model
 * @param request
 * @param response
 */
@RequestMapping(value = "/cashierstatement", method = RequestMethod.GET)
public void cashierStatement(Model model, HttpServletRequest request, HttpServletResponse response) {
    String contrace_id_str = request.getParameter("contrace_id");

    String contrace_no = "";
    String customer_name = "";
    String customer_no = "";
    String daily_available_km = "";
    String contrace_type = "";

    VehicleContraceInfo vehicleContraceInfo = this.vehicleServiceManageService
            .getVehicleContraceInfoById(Long.valueOf(contrace_id_str));
    if (vehicleContraceInfo != null) {
        contrace_no = vehicleContraceInfo.getContrace_no();
        customer_name = vehicleContraceInfo.getCustomer_name();
        daily_available_km = vehicleContraceInfo.getDaily_available_km() + "";
    } else {
        PropertyContraceInfo propertyContraceInfo = this.vehicleServiceManageService
                .getPropertyContraceInfoById(Long.valueOf(contrace_id_str));
        if (propertyContraceInfo != null) {
            contrace_no = propertyContraceInfo.getContrace_no();
            customer_name = propertyContraceInfo.getCustomer_name();
            contrace_type = "?";
        }
    }

    List<VehicleContraceVehsInfo> vehicleContraceVehsInfoList = this.vehicleServiceManageService
            .getVehicleContraceVehsListByContraceId(Long.valueOf(contrace_id_str));

    //1.ContentType
    response.setContentType("multipart/form-data");
    //2.????(??a.pdf)
    response.setHeader("Content-Disposition", "attachment;fileName=" + contrace_no + ".xls");

    // webbookExcel
    HSSFWorkbook wb = new HSSFWorkbook();

    for (VehicleContraceVehsInfo v : vehicleContraceVehsInfoList) {
        // webbooksheet,Excelsheet
        HSSFSheet sheet = wb.createSheet(v.getLicense_plate());
        // sheet0,??poiExcel?short
        HSSFRow row = sheet.createRow((int) 0);
        // ? 
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // ?

        HSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("??");
        cell.setCellStyle(style);
        cell = row.createCell((short) 1);
        cell.setCellValue("?");
        cell.setCellStyle(style);
        cell = row.createCell((short) 2);
        cell.setCellValue("");
        cell.setCellStyle(style);
        cell = row.createCell((short) 3);
        cell.setCellValue("?");
        cell.setCellStyle(style);
        cell = row.createCell((short) 4);
        cell.setCellValue("");
        cell.setCellStyle(style);

        row = sheet.createRow(1);
        row.createCell((short) 0).setCellValue(customer_name);
        row.createCell((short) 1).setCellValue(customer_no);
        row.createCell((short) 2).setCellValue(contrace_type);
        row.createCell((short) 3).setCellValue("");
        row.createCell((short) 4).setCellValue("");

        row = sheet.createRow(2);
        HSSFCell cell2 = row.createCell((short) 0);
        cell2.setCellValue("?");
        cell2.setCellStyle(style);
        cell2 = row.createCell((short) 1);
        cell2.setCellValue("??");
        cell2.setCellStyle(style);
        cell2 = row.createCell((short) 2);
        cell2.setCellValue("");
        cell2.setCellStyle(style);
        cell2 = row.createCell((short) 3);
        cell2.setCellValue("");
        cell2.setCellStyle(style);
        cell2 = row.createCell((short) 4);
        cell2.setCellValue("??");
        cell2.setCellStyle(style);

        row = sheet.createRow(3);
        row.createCell((short) 0).setCellValue(v.getKm());
        row.createCell((short) 1).setCellValue(v.getOil_percent());
        long over_km = (v.getReturn_km() - v.getKm()) > 0 ? (v.getReturn_km() - v.getKm()) : 0;
        row.createCell((short) 2).setCellValue(over_km);
        row.createCell((short) 3).setCellValue("");
        row.createCell((short) 4).setCellValue("");

        row = sheet.createRow(4);
        HSSFCell cell4 = row.createCell((short) 0);
        cell4.setCellValue("");
        cell4.setCellStyle(style);
        cell4 = row.createCell((short) 1);
        cell4.setCellValue("?");
        cell4.setCellStyle(style);
        cell4 = row.createCell((short) 2);
        cell4.setCellValue("");
        cell4.setCellStyle(style);
        cell4 = row.createCell((short) 3);
        cell4.setCellValue("");
        cell4.setCellStyle(style);
        cell4 = row.createCell((short) 4);
        cell4.setCellValue("");
        cell4.setCellStyle(style);

        row = sheet.createRow(5);
        row.createCell((short) 0).setCellValue(v.getReturn_km());
        row.createCell((short) 1).setCellValue(v.getRevert_oil_percent());
        long over_oil = (v.getOil_percent() - v.getRevert_oil_percent()) > 0
                ? (v.getOil_percent() - v.getRevert_oil_percent())
                : 0;
        row.createCell((short) 2).setCellValue(over_oil);
        row.createCell((short) 3).setCellValue("");
        row.createCell((short) 4).setCellValue(v.getActually_price());
    }

    // ?
    try {

        String path = appProps.get("contrace.over.download.path") + contrace_no + ".xls";
        FileOutputStream fout = new FileOutputStream(path);
        wb.write(fout);
        fout.close();

        ServletOutputStream out;
        //File(?download.pdf)
        File file = new File(path);

        try {
            FileInputStream inputStream = new FileInputStream(file);
            //3.response?ServletOutputStream(out)
            out = response.getOutputStream();
            int b = 0;
            byte[] buffer = new byte[512];
            while (b != -1) {
                b = inputStream.read(buffer);
                //4.?(out)
                out.write(buffer, 0, b);
            }
            inputStream.close();
            out.close();
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

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

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession();
    UserEntity user = (UserEntity) session.getAttribute("user");
    if (user == null) {
        return null;
    }//from  w w w  . j av a2  s. c  om
    String start = request.getParameter("start");
    String limit = request.getParameter("limit");

    if (start == null || limit == null) {
        start = "-1";
        limit = "-1";
    }
    ObjectMapper mapper = new ObjectMapper();
    long appId = -1;
    String appIds = request.getParameter("appIds");
    String paramIdSchemaType = null;
    List<String> idSchemaTypeList = null;
    int idSchemaType = -1;

    if (appIds != null && (appIds.trim().length() == 0 || appIds.equals("-1"))) {
        appIds = null;
    }

    if (request.getParameter("idSchemaType") != null) {
        idSchemaType = -1;
        paramIdSchemaType = request.getParameter("idSchemaType");
        if ((paramIdSchemaType.indexOf(",", 0)) < 0) {
            // 1 condition
            idSchemaType = Integer.parseInt(request.getParameter("idSchemaType"));
        } else {
            //more condition
            idSchemaTypeList = Arrays.asList(StringUtils.splitPreserveAllTokens(paramIdSchemaType, ","));
        }
    }
    String strAppId = request.getParameter("appId");
    if (strAppId != null && !strAppId.trim().isEmpty()) {
        appId = Integer.valueOf(strAppId);
        if (appId == 0)
            appId = -1;
    }
    mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
    ServletOutputStream out = null;
    response.setContentType("application/json");
    out = response.getOutputStream();
    ReadList readList = null;

    if (user.getIdRole() == Roles.ADMINISTRATOR.getDbCode()) {
        if (idSchemaTypeList != null) {
            readList = schemasDao.readBySchemaTypeId(Integer.parseInt(start), Integer.parseInt(limit),
                    idSchemaTypeList, appIds);
        } else {
            readList = schemasDao.readBySchemaTypeId(Integer.parseInt(start), Integer.parseInt(limit),
                    idSchemaType, appIds);
        }
    } else {
        readList = schemasDao.read(Integer.parseInt(start), Integer.parseInt(limit), user.getIdUser());
    }

    //FIXME: Check with Mario

    @SuppressWarnings("unchecked")
    List<SchemaEntity> SchemaEntities = (List<SchemaEntity>) readList.getResults();
    if (SchemaEntities != null && SchemaEntities.size() > 0) {
        for (SchemaEntity schemaEntity : SchemaEntities) {
            ReadList readTriggersList = schemaTriggerStatusDao.findByIdSchema(schemaEntity.getIdSchema());
            if (CollectionUtils.isNotEmpty(readTriggersList.getResults())) {
                SchemaTriggerStatusEntity schemaTriggerStatusEntity = (SchemaTriggerStatusEntity) readTriggersList
                        .getResults().get(0);
                schemaEntity.setSchemaEvents(schemaTriggerStatusEntity);
            }
        }
    }

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