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:com.geminimobile.web.SearchController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException arg3) throws Exception {
    SearchCommand cmd = (SearchCommand) command;
    ModelAndView mav = new ModelAndView(getSuccessView());

    CDRDataAccess cdrAccess = new CDRDataAccess();

    Date toDate = SearchCommand.m_sdf.parse(cmd.getToDate());
    long maxTimestamp = toDate.getTime();

    Date fromDate = SearchCommand.m_sdf.parse(cmd.getFromDate());
    long minTimestamp = fromDate.getTime();

    String msisdn = cmd.getMsisdn();
    String action = cmd.getAction();
    Vector<CDREntry> cdrs;//from  w w  w.j  a v a2s.  com

    if (action.compareToIgnoreCase("downloadcsv") == 0) {

        if (msisdn != null && msisdn.length() > 0) {
            cdrs = cdrAccess.getCDRsByMSISDN(cmd.getMsisdn(), minTimestamp, maxTimestamp, cmd.getMarket(),
                    cmd.getMessageType(), 100000); // 100,000 entries max
        } else {
            cdrs = cdrAccess.getCDRsByHour(minTimestamp, maxTimestamp, cmd.getMarket(), cmd.getMessageType(),
                    MAX_ENTRIES_PER_PAGE);
        }
        StringBuffer sb = new StringBuffer();

        // Write column headers 
        sb.append("Date/Time,Market,Type,MSISDN,MO IP address,MT IP Address,Sender Domain,Recipient Domain\n");

        for (CDREntry entry : cdrs) {
            sb.append(entry.getDisplayTimestamp() + "," + entry.getMarket() + "," + entry.getType() + ","
                    + entry.getMsisdn() + "," + entry.getMoIPAddress() + "," + entry.getMtIPAddress() + ","
                    + entry.getSenderDomain() + "," + entry.getRecipientDomain() + "\n");
        }

        String csvString = sb.toString();

        response.setBufferSize(sb.length());
        response.setContentLength(sb.length());
        response.setContentType("text/plain; charset=UTF-8");
        //response.setContentType( "text/csv" );
        //response.setContentType("application/ms-excel");
        //response.setHeader("Content-disposition", "attachment;filename=cdrResults.csv");
        response.setHeader("Content-Disposition", "attachment; filename=" + "cdrResults.csv" + ";");
        ServletOutputStream os = response.getOutputStream();

        os.write(csvString.getBytes());

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

        return null;

    } else if (action.compareToIgnoreCase("graph") == 0) {
        cmd.setGraph(true);
        List<ChartSeries> chartData;
        if (msisdn != null && msisdn.length() > 0) {
            chartData = cdrAccess.getChartDataByMSISDN(cmd.getMsisdn(), minTimestamp, maxTimestamp,
                    cmd.getMarket(), cmd.getMessageType(), 100000);
        } else {
            chartData = cdrAccess.getChartDataByHour(minTimestamp, maxTimestamp, cmd.getMarket(),
                    cmd.getMessageType(), 100000);
        }

        request.getSession().setAttribute("chartData", chartData);

    } else if (action.compareToIgnoreCase("getmore") == 0) {
        cdrs = (Vector<CDREntry>) request.getSession().getAttribute("currentcdrs");
        int numCDRs = cdrs.size();
        CDREntry lastCDR = cdrs.get(numCDRs - 1);
        long lastCDRTime = Long.parseLong(lastCDR.getTimestamp());

        if (msisdn != null && msisdn.length() > 0) {
            Vector<CDREntry> moreCDRs = cdrAccess.getCDRsByMSISDN(cmd.getMsisdn(), lastCDRTime, maxTimestamp,
                    cmd.getMarket(), cmd.getMessageType(), MAX_ENTRIES_PER_PAGE);
            cdrs.addAll(moreCDRs);
        } else {
            Vector<CDREntry> moreCDRs = cdrAccess.getCDRsByHour(lastCDRTime, maxTimestamp, cmd.getMarket(),
                    cmd.getMessageType(), MAX_ENTRIES_PER_PAGE);
            cdrs.addAll(moreCDRs);
        }

        request.getSession().setAttribute("currentcdrs", cdrs);
        mav.addObject("cdrs", cdrs);
    } else {
        // Normal search            
        if (msisdn != null && msisdn.length() > 0) {
            cdrs = cdrAccess.getCDRsByMSISDN(cmd.getMsisdn(), minTimestamp, maxTimestamp, cmd.getMarket(),
                    cmd.getMessageType(), MAX_ENTRIES_PER_PAGE);
        } else {
            cdrs = cdrAccess.getCDRsByHour(minTimestamp, maxTimestamp, cmd.getMarket(), cmd.getMessageType(),
                    MAX_ENTRIES_PER_PAGE);
        }

        request.getSession().setAttribute("currentcdrs", cdrs);
        mav.addObject("cdrs", cdrs);
    }

    mav.addObject("searchCmd", cmd);

    List<Option> msgOptions = getMessageOptions();
    mav.addObject("msgTypes", msgOptions);
    List<Option> marketOptions = getMarketOptions();
    mav.addObject("marketTypes", marketOptions);

    return mav;
}

From source file:com.liferay.portal.servlet.ImageServlet.java

public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {

    String path = req.getPathInfo();

    // The image id may be passed in as image_id, img_id, or i_id

    String imageId = ParamUtil.getString(req, "image_id");

    if (Validator.isNull(imageId)) {
        imageId = ParamUtil.getString(req, "img_id");

        if (Validator.isNull(imageId)) {
            imageId = ParamUtil.getString(req, "i_id");
        }/*from   ww w  .  ja  va 2s.c o  m*/
    }

    // Company Logo

    if (path.startsWith("/company_logo")) {
        if (ParamUtil.get(req, "png", false)) {
            imageId += ".png";

            res.setContentType("image/png");
        } else if (ParamUtil.get(req, "wbmp", false)) {
            imageId += ".wbmp";

            res.setContentType("image/vnd.wap.wbmp");
        }
    }

    // Image Gallery

    if (path.startsWith("/image_gallery")) {
        if (!imageId.equals(StringPool.BLANK) && !imageId.startsWith(_companyId + ".image_gallery.")) {

            imageId = _companyId + ".image_gallery." + imageId;

            if (ParamUtil.get(req, "small", false)) {
                imageId += ".small";
            } else {
                imageId += ".large";
            }
        }
    }

    // Journal Article

    if (path.startsWith("/journal/article")) {
        if (!imageId.equals(StringPool.BLANK) && !imageId.startsWith(_companyId + ".journal.article.")) {

            imageId = _companyId + ".journal.article." + imageId;

            String version = req.getParameter("version");

            if (Validator.isNotNull(version)) {
                imageId += "." + version;
            }
        }
    }

    // Journal Template

    if (path.startsWith("/journal/template")) {
        if (!imageId.equals(StringPool.BLANK) && !imageId.startsWith(_companyId + ".journal.template.")) {

            imageId = _companyId + ".journal.template." + imageId;
            imageId += ".small";
        }
    }

    // Shopping Item

    else if (path.startsWith("/shopping/item")) {
        if (!imageId.equals(StringPool.BLANK) && !imageId.startsWith(_companyId + ".shopping.item.")) {

            imageId = _companyId + ".shopping.item." + imageId;

            if (ParamUtil.get(req, "small", false)) {
                imageId += ".small";
            } else if (ParamUtil.get(req, "medium", false)) {
                imageId += ".medium";
            } else {
                imageId += ".large";
            }
        }
    }

    Image image = ImageLocalUtil.get(imageId);

    if (Validator.isNull(imageId)) {
        _log.error("Image id should never be null or empty, path is " + req.getPathInfo());
    }

    if (image == null) {
        _log.error("Image should never be null");
    } else {
        if (Validator.isNotNull(image.getType())) {
            res.setContentType("image/" + image.getType());
        }

        /*res.setHeader(
           "Cache-control", "max-age=" + Long.toString(Time.WEEK));*/

        try {
            if (!res.isCommitted()) {
                ServletOutputStream out = res.getOutputStream();

                out.write(image.getTextObj());
                out.flush();
            }
        } catch (Exception e) {
            Logger.error(this, e.getMessage(), e);
        }
    }
}

From source file:org.sakaiproject.evaluation.tool.settings.ExportConfigurationHook.java

public boolean handle() throws ParseException {
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=\"evalSettings.properties\"");
    ArrayList<String> propertyFieldNames = getSortedEvalSettingsPropertyFieldNames();
    ServletOutputStream out;
    try {/*  w  w w  . j  av  a  2s  .  c o m*/
        out = response.getOutputStream();
        for (String propertyFieldName : propertyFieldNames) {
            String constValue = getEvalSettingConstValueByFieldName(propertyFieldName);
            out.write(constValue.getBytes());
            out.write("=".getBytes());
            Object settingVal = evalSettings.get(constValue);
            // When there is no value, we need to output something or the properties file will not work
            out.write(null == settingVal ? "null".getBytes() : settingVal.toString().getBytes());
            out.write("\n".getBytes());
        }
    } catch (IOException e) {
        LOG.error("Error producing output stream for evalSettings.properties", e);
        return false;
    }
    return true;
}

From source file:com.jd.survey.web.surveys.SurveyController.java

@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/doc/{Id}", produces = "text/html")
public void getQuestionDocument(@PathVariable("Id") Long surveyDocumentId, Principal principal,
        HttpServletResponse response) {//from w  w  w.  j ava  2s . co  m
    try {
        SurveyDocument surveyDocument = surveyService.surveyDocumentDAO_findById(surveyDocumentId);

        response.setContentType(surveyDocument.getContentType());
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache,must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Content-Disposition", "inline;filename=" + surveyDocument.getFileName());
        ServletOutputStream servletOutputStream = response.getOutputStream();
        servletOutputStream.write(surveyDocument.getContent());
        servletOutputStream.flush();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:org.springframework.reactive.web.servlet.ResponseBodySubscriber.java

@Override
public void onWritePossible() throws IOException {
    ServletOutputStream output = this.synchronizer.getOutputStream();

    boolean ready = output.isReady();
    logger.debug("Output: " + ready + " buffer: " + (buffer == null));

    if (ready) {/*from   w w w .ja v  a2  s .c  om*/
        if (this.buffer != null) {
            output.write(this.buffer);
            this.buffer = null;

            if (!subscriberComplete) {
                this.subscription.request(1);
            } else {
                this.synchronizer.writeComplete();
            }
        } else {
            this.subscription.request(1);
        }
    }
}

From source file:dijalmasilva.controllers.ControladorUser.java

@RequestMapping("/image/{id}")
public void carregaImagem(@PathVariable Long id, HttpServletResponse resp) {
    ServletOutputStream out = null;
    try {//from   w  w  w . j ava  2 s.c om
        Usuario usuario = serviceUser.findById(id);
        out = resp.getOutputStream();
        out.write(usuario.getFoto());
        out.flush();
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        try {
            out.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:org.zalando.logbook.servlet.example.ExampleController.java

@RequestMapping(value = "/read-bytes", produces = MediaType.TEXT_PLAIN_VALUE)
public void readBytes(final HttpServletRequest request, final HttpServletResponse response) throws IOException {

    final ServletInputStream input = request.getInputStream();
    final ServletOutputStream output = response.getOutputStream();

    final byte[] buffer = new byte[1];

    while (true) {
        final int read = input.read(buffer);
        if (read == -1) {
            break;
        }//from  w w  w. j  a  v a2s . co  m
        output.write(buffer);
    }
}

From source file:com.sample.RSSAdapterResource.java

public void execute(HttpUriRequest req, HttpServletResponse resultResponse)
        throws ClientProtocolException, IOException, IllegalStateException, SAXException {
    HttpResponse RSSResponse = client.execute(host, req);
    ServletOutputStream os = resultResponse.getOutputStream();
    if (RSSResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        resultResponse.addHeader("Content-Type", "application/json");
        String json = XML.toJson(RSSResponse.getEntity().getContent());
        os.write(json.getBytes(Charset.forName("UTF-8")));

    } else {/* ww  w  .  j  a  v  a 2  s.c  o m*/
        resultResponse.setStatus(RSSResponse.getStatusLine().getStatusCode());
        RSSResponse.getEntity().getContent().close();
        os.write(RSSResponse.getStatusLine().getReasonPhrase().getBytes());
    }
    os.flush();
    os.close();
}

From source file:org.cloudfoundry.practical.demo.web.controller.TimeoutController.java

@RequestMapping("/timeout/ajaxdrip")
public void ajax(HttpServletResponse response) throws IOException {
    ServletOutputStream outputStream = response.getOutputStream();
    this.logger.info("Long running task...");
    try {/*from  w  w  w  .  j  ava 2  s.  co m*/
        for (int i = 1; i <= TOTAL_SECONDS_DELAY; i++) {
            Thread.sleep(ONE_SECOND);
            this.logger.info(" Thinking..." + i);
            outputStream.write('.');
            response.flushBuffer();
        }
    } catch (InterruptedException e) {
    }
    outputStream.write("Hello from the server".getBytes());
}

From source file:de.mpg.escidoc.pubman.statistic_charts.StatisticChartServlet.java

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

    String numberOfMonthsString = request.getParameter(numberOfMonthsParameterName);
    if (numberOfMonthsString == null) {
        numberOfMonths = 12;/*from w w w . j a va 2 s  .  c  o  m*/
    } else {
        numberOfMonths = Integer.parseInt(numberOfMonthsString);
    }

    String lang = request.getParameter(languageParameterName);
    if (lang == null) {
        this.language = "en";
    } else {
        this.language = lang;
    }

    id = request.getParameter(idParameterName);
    type = request.getParameter(typeParameterName);

    try {

        CategoryDataset dataset = createDataset();
        JFreeChart chart = createChart(dataset);
        BufferedImage img = chart.createBufferedImage(630, 250);
        byte[] image = new KeypointPNGEncoderAdapter().encode(img);

        response.setContentType(CONTENT_TYPE);
        ServletOutputStream out = response.getOutputStream();
        out.write(image);
        out.flush();
        out.close();

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

}