Example usage for javax.servlet ServletOutputStream write

List of usage examples for javax.servlet ServletOutputStream write

Introduction

In this page you can find the example usage for javax.servlet ServletOutputStream write.

Prototype

public abstract void write(int b) throws IOException;

Source Link

Document

Writes the specified byte to this output stream.

Usage

From source file:org.opencastproject.manager.system.workflow.WorkflowManager.java

/**
 * Handle workflow's files./* w  w  w. jav  a2  s.c  om*/
 *
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
public void handleWorkflowFiles(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String fileName = stringValidator((String) request.getParameter("workflow_file"));
    String empty = "";

    if (empty.equals(fileName) || fileName == null)
        throw new ServletException("Invalid or non-existent file parameter in SendXml servlet.");

    String xmlDir = PluginManagerConstants.WORKFLOWS_PATH;

    if (empty.equals(xmlDir) || xmlDir == null)
        throw new ServletException("Invalid or non-existent xmlDir context-param.");

    ServletOutputStream stream = null;
    BufferedInputStream buf = null;

    try {
        stream = response.getOutputStream();
        File xml = new File(xmlDir + fileName);

        response.setContentType("text/xml");
        response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
        response.setContentLength((int) xml.length());

        FileInputStream input = new FileInputStream(xml);

        buf = new BufferedInputStream(input);

        int readBytes = 0;

        //read from the file; write to the ServletOutputStream
        while ((readBytes = buf.read()) != -1) {
            stream.write(readBytes);
        }

    } catch (IOException ioe) {
        throw new ServletException(ioe.getMessage());
    } finally {

        if (stream != null)
            stream.close();

        if (buf != null)
            buf.close();
    }
}

From source file:UrlServlet.java

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

    //get the 'file' parameter
    String fileName = (String) request.getParameter("file");
    if (fileName == null || fileName.equals(""))
        throw new ServletException("Invalid or non-existent file parameter in UrlServlet servlet.");

    if (fileName.indexOf(".pdf") == -1)
        fileName = fileName + ".pdf";

    URL pdfDir = null;/*from w ww . j  a  v  a 2  s .c  om*/
    URLConnection urlConn = null;
    ServletOutputStream stream = null;
    BufferedInputStream buf = null;
    try {

        pdfDir = new URL(getServletContext().getInitParameter("remote-pdf-dir") + fileName);

    } catch (MalformedURLException mue) {

        throw new ServletException(mue.getMessage());
    }
    try {

        stream = response.getOutputStream();

        //set response headers
        response.setContentType("application/pdf");
        response.addHeader("Content-Disposition", "attachment; filename=" + fileName);

        urlConn = pdfDir.openConnection();
        response.setContentLength((int) urlConn.getContentLength());

        buf = new BufferedInputStream(urlConn.getInputStream());
        int readBytes = 0;

        //read from the file; write to the ServletOutputStream
        while ((readBytes = buf.read()) != -1)
            stream.write(readBytes);
    } catch (IOException ioe) {
        throw new ServletException(ioe.getMessage());
    } finally {
        if (stream != null)
            stream.close();
        if (buf != null)
            buf.close();
    }
}

From source file:org.red5.server.net.rtmpt.RTMPTServlet.java

/**
 * Return raw data to the client.//w  w  w .j  a  v  a2s . co m
 * 
 * @param conn
 *            RTMP connection
 * @param buffer
 *            Raw data as byte buffer
 * @param resp
 *            Servlet response
 * @throws IOException
 *             I/O exception
 */
protected void returnMessage(RTMPTConnection conn, IoBuffer buffer, HttpServletResponse resp)
        throws IOException {
    log.trace("returnMessage {}", buffer);
    if (conn != null) {
        resp.setStatus(HttpServletResponse.SC_OK);
    } else {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
    resp.setHeader("Connection", "Keep-Alive");
    resp.setHeader("Cache-Control", "no-cache");
    resp.setContentType(CONTENT_TYPE);
    int contentLength = buffer.limit() + 1;
    resp.setContentLength(contentLength);
    ServletOutputStream output = resp.getOutputStream();
    if (conn != null) {
        byte pollingDelay = conn.getPollingDelay();
        log.debug("Sending {} bytes; polling delay: {}", buffer.limit(), pollingDelay);
        output.write(pollingDelay);
    } else {
        output.write((byte) 0);
    }
    ServletUtils.copy(buffer.asInputStream(), output);
    if (conn != null) {
        conn.updateWrittenBytes(contentLength);
    }
    buffer.free();
    buffer = null;
}

From source file:org.wso2.carbon.service.mgt.ui.ServiceAdminClient.java

public void downloadServiceArchive(String serviceGroupName, String serviceType, HttpServletResponse response)
        throws AxisFault {
    try {//  ww w . j  a  va2 s  . c  om
        ServletOutputStream out = response.getOutputStream();
        ServiceDownloadData downloadData = stub.downloadServiceArchive(serviceGroupName);
        if (downloadData != null) {
            DataHandler handler = downloadData.getServiceFileData();
            response.setHeader("Content-Disposition", "fileName=" + downloadData.getFileName());
            response.setContentType(handler.getContentType());
            InputStream in = handler.getDataSource().getInputStream();
            int nextChar;
            while ((nextChar = in.read()) != -1) {
                out.write((char) nextChar);
            }
            out.flush();
            in.close();
        } else {
            out.write("The requested service archive was not found on the server".getBytes());
        }
    } catch (RemoteException e) {
        handleException("error.downloading.service", e);
    } catch (IOException e) {
        handleException("error.downloading.service", e);
    }
}

From source file:org.extensiblecatalog.ncip.v2.responder.implprof1.NCIPServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {

    long respTotalStartTime = System.currentTimeMillis();
    String serviceName = "Unknown";

    try {/*from  w w w . j  a  v  a 2  s.  com*/

        response.setContentType("application/xml; charset=\"utf-8\"");

        // Note: Statements that might throw exceptions are wrapped in individual try/catch blocks, allowing us
        // to provide very specific error messages.

        ServletInputStream inputStream = null;
        try {

            inputStream = request.getInputStream();

        } catch (IOException e) {

            returnException(response, "Exception getting ServletInputStream from the HttpServletRequest.", e);

        }

        ServiceContext serviceContext = null;
        try {

            serviceContext = serviceValidator.getInitialServiceContext();

        } catch (ToolkitException e) {

            returnException(response, "Exception creating initial service context.", e);

        }

        NCIPInitiationData initiationData = null;

        try {

            initiationData = translator.createInitiationData(serviceContext, inputStream);

        } catch (ServiceException e) {

            returnException(response,
                    "Exception creating the NCIPInitiationData object from the servlet's input stream.", e);

        } catch (ValidationException e) {

            returnValidationProblem(response, e);

        }

        long initPerfSvcStartTime = System.currentTimeMillis();

        NCIPResponseData responseData = messageHandler.performService(initiationData, serviceContext);

        long initPerfSvcEndTime = System.currentTimeMillis();

        serviceName = ServiceHelper.getServiceName(initiationData);

        statisticsBean.record(initPerfSvcStartTime, initPerfSvcEndTime,
                StatisticsBean.RESPONDER_PERFORM_SERVICE_LABELS, serviceName);

        InputStream responseMsgInputStream = null;
        try {

            responseMsgInputStream = translator.createResponseMessageStream(serviceContext, responseData);

        } catch (ServiceException e) {

            returnException(response, "Exception creating the InputStream from the NCIPResponseData object.",
                    e);

        } catch (ValidationException e) {

            returnException(response, "Exception creating the InputStream from the NCIPResponseData object.",
                    e);

        }

        int bytesAvailable = 0;
        if (responseMsgInputStream != null) {

            try {

                bytesAvailable = responseMsgInputStream.available();

            } catch (IOException e) {

                returnException(response,
                        "Exception getting the count of available bytes from the response message's InputStream.",
                        e);

            }

        }

        int bytesRead = 0;
        if (bytesAvailable != 0) {

            byte[] responseMsgBytes = new byte[bytesAvailable];

            try {

                bytesRead = responseMsgInputStream.read(responseMsgBytes, 0, bytesAvailable);

            } catch (IOException e) {

                returnException(response, "Exception reading bytes from the response message's InputStream.",
                        e);

            }

            if (bytesRead != bytesAvailable) {

                returnProblem(response, "Bytes read from the response message's InputStream (" + bytesRead
                        + ") are not the same as the number available (" + bytesAvailable + ").");

            } else {

                response.setContentLength(responseMsgBytes.length);

                // TODO: What about a try/finally that closes the output stream - is that needed?

                ServletOutputStream outputStream = null;
                try {

                    outputStream = response.getOutputStream();

                } catch (IOException e) {

                    returnException(response, "Exception getting the HttpServletResponse's OutputStream.", e);

                }

                try {

                    outputStream.write(responseMsgBytes);

                } catch (IOException e) {

                    returnException(response,
                            "Exception writing the NCIP response message to the HttpServletResponse's OutputStream.",
                            e);

                }

                try {

                    outputStream.flush();

                } catch (IOException e) {

                    returnException(response, "Exception flushing the HttpServletResponse's OutputStream.", e);

                }

            }

        }

    } catch (Exception e) {

        returnException(response, "Uncaught exception.", e);

    }

    long respTotalEndTime = System.currentTimeMillis();

    statisticsBean.record(respTotalStartTime, respTotalEndTime, StatisticsBean.RESPONDER_TOTAL_LABELS,
            serviceName);

}

From source file:com.baidu.upload.controller.ImageController.java

@RequestMapping("downloadImg")
public void downloadImg(Integer id, HttpServletRequest request, HttpServletResponse response) {
    Image image = imageService.get(id);
    String imgname = image.getName();
    ServletOutputStream out = null;
    try {//from  ww w  .  j a  va  2 s.  c o m
        response.reset();
        String userAgent = request.getHeader("User-Agent");
        byte[] bytes = userAgent.contains("MSIE") ? imgname.getBytes() : imgname.getBytes("UTF-8");
        // fileName.getBytes("UTF-8")?safari?
        String fileName = new String(bytes, "ISO-8859-1");
        System.out.println(fileName);
        // ?
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(imgname, "UTF-8"));
        //?blob
        byte[] contents = image.getImgblob();
        out = response.getOutputStream();
        //?
        out.write(contents);
        out.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.ewcms.content.vote.web.ResultServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletOutputStream out = null;
    StringBuffer output = new StringBuffer();
    try {//w  ww . j  av a 2 s  .  co  m
        String id = req.getParameter("id");

        if (!id.equals("") && StringUtils.isNumeric(id)) {
            Long questionnaireId = new Long(id);

            ServletContext application = getServletContext();
            WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(application);
            QuestionnaireService questionnaireService = (QuestionnaireService) wac
                    .getBean("questionnaireService");

            String ipAddr = req.getRemoteAddr();

            output = questionnaireService.getQuestionnaireResultClientToHtml(questionnaireId,
                    getServletContext().getContextPath(), ipAddr);
        }
        out = resp.getOutputStream();
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=UTF-8");
        out.write(output.toString().getBytes("UTF-8"));
        out.flush();
    } finally {
        if (out != null) {
            out.close();
            out = null;
        }
    }
}

From source file:org.mycore.common.content.util.MCRServletContentHelper.java

/**
 * Consumes the content and writes it to the ServletOutputStream.
 *
 * @param content  The source resource//  ww  w .  j a  v a  2s.com
 * @param out   The outputBufferSize stream to write to
 * @param range     Range the client wanted to retrieve
 */
private static void copy(final MCRContent content, final ServletOutputStream out, final Range range,
        // TODO: beautify this
        final int inputBufferSize, final int outputBufferSize) throws IOException {
    if (content.isReusable()) {
        try (ReadableByteChannel readableByteChannel = content.getReadableByteChannel()) {
            if (readableByteChannel instanceof SeekableByteChannel) {
                endCurrentTransaction();
                SeekableByteChannel seekableByteChannel = (SeekableByteChannel) readableByteChannel;
                seekableByteChannel.position(range.start);
                long bytesToCopy = range.end - range.start + 1;
                while (bytesToCopy > 0) {
                    ByteBuffer byteBuffer;
                    if (bytesToCopy > (long) MCRServletContentHelper.DEFAULT_BUFFER_SIZE) {
                        byteBuffer = ByteBuffer.allocate(MCRServletContentHelper.DEFAULT_BUFFER_SIZE);
                    } else {
                        byteBuffer = ByteBuffer.allocate((int) bytesToCopy);
                    }

                    int bytesRead = seekableByteChannel.read(byteBuffer);
                    bytesToCopy -= bytesRead;
                    out.write(byteBuffer.array());
                }
                return;
            }
        }
    }

    try (final InputStream resourceInputStream = content.getInputStream();
            final InputStream in = isInputStreamBuffered(resourceInputStream, content) ? resourceInputStream
                    : new BufferedInputStream(resourceInputStream, inputBufferSize)) {
        endCurrentTransaction();
        final IOException exception = copyRange(in, out, 0, range.start, range.end, outputBufferSize);
        if (exception != null) {
            throw exception;
        }
    }
}

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

@SuppressWarnings("unchecked")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    ObjectMapper mapper = new ObjectMapper();
    ServletOutputStream out = null;
    response.setContentType("application/json");
    out = response.getOutputStream();//w  w w  .  j ava2 s .  co  m
    String idSchemaField = request.getParameter("idSchemaField");
    ReadList readList = checksTypeDao.read(-1, -1);
    List<ChecksTypeEntity> checkTypeEntites = (List<ChecksTypeEntity>) readList.getResults();
    if (StringUtils.isNotEmpty(idSchemaField)) {
        String leftPane = request.getParameter("leftPane");
        ReadList assignedReadList = checksTypeDao.readCheckTypeBySchemaFieldId(Long.parseLong(idSchemaField));
        List<ChecksTypeEntity> assignedCheckTypeEntites = (List<ChecksTypeEntity>) assignedReadList
                .getResults();
        if ("true".equalsIgnoreCase(leftPane)) {
            if (CollectionUtils.isNotEmpty(assignedCheckTypeEntites)) {
                checkTypeEntites.removeAll(assignedCheckTypeEntites);
            }
        } else {
            readList.setResults(assignedCheckTypeEntites);
        }
    }
    out.write(mapper.writeValueAsBytes(readList));
    out.flush();
    out.close();
    return null;
}

From source file:com.mbv.web.rest.controller.DeliveryController.java

@RequestMapping(value = "/printPick", method = RequestMethod.GET)
public String printPick(HttpServletRequest request, HttpServletResponse response) throws MbvException {
    Long degId = Long.parseLong(request.getParameter("degId"));
    List<Long> degIds = new ArrayList<Long>();
    degIds.add(degId);//ww w.  j  av a2  s  .c  o  m

    List<GoodBean> goodList = deliveryService.queryGoodByParams(degId);

    String jasperPath = request.getSession().getServletContext().getRealPath("/reports/pick.jrxml");

    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("SUBREPORT_DIR", jasperPath);
    List<DeliveryDataSource> list = new ArrayList<DeliveryDataSource>();
    List<PickBean> goods = new ArrayList<PickBean>();
    int i = 0;
    for (GoodBean goodBean : goodList) {
        i++;
        PickBean good = new PickBean();
        good.setId(i);
        good.setCode(goodBean.getProdNum());
        good.setName(goodBean.getBrandName() + " " + goodBean.getProductName() + " " + goodBean.getColorName()
                + " " + goodBean.getSizeName());
        good.setNum(goodBean.getQty());
        goods.add(good);
    }

    DeliveryDataSource deliverySource = new DeliveryDataSource();
    deliverySource.setOrdercode(degId + "");
    deliverySource.setTable_datas(new JRBeanCollectionDataSource(goods));
    list.add(deliverySource);

    try {
        JRDataSource dataSource = new JRBeanCollectionDataSource(list);
        JasperReport jasperReport = JasperCompileManager.compileReport(jasperPath);
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource);
        request.getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint);

        byte[] bytes = JasperExportManager.exportReportToPdf(jasperPrint);

        response.setContentType("application/pdf");
        response.setContentLength(bytes.length);

        ServletOutputStream out = response.getOutputStream();
        out.write(bytes);
        out.flush();
        //end 

        //?
        deliveryService.updatePickPrintCount(degIds);

    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
        return null;
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }

    return null;
}