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.kolich.spring.views.mappers.KolichMappingHTMLView.java

@Override
public void myRenderMergedOutputModel(final KolichViewSerializable payload, final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    final ServletOutputStream os = response.getOutputStream();
    // Convert the payload into a JSON response.
    os.write(payload.getEntity().getBytes());
    // Quietly close the output stream.
    IOUtils.closeQuietly(os);/*from  w ww  . j  av a2s .  c om*/
}

From source file:no.feide.moria.servlet.PictureServlet.java

/**
 * Implements the HttpServlet.doGet method.
 * @param request//from www .  j  a va 2 s. c  o  m
 *            The HTTP request.
 * @param response
 *            The HTTP response.
 * @throws IOException
 * @throws ServletException
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    try {

        int idx = 0;
        String index = request.getParameter("index");
        if (index != null) {
            idx = Integer.parseInt(index);
        }

        // login.feide.no/Picture can be entered as an URL without any further arguments.
        // That will lead to a null pointer exception, caught by the catch-clause below, but 
        // we really should avoid creating such errors. For one, they end up in the log file looking
        // horribly serious, when there is little reason to worry.

        response.setContentType("image/jpeg");
        String[] picture = (String[]) request.getSession().getAttribute(PICTURE_ATTRIBUTE);

        if (picture == null) {
            log.logWarn("PictureServlet called without picture context. Nothing to display");
        } else {
            byte[] decoded = Base64.decodeBase64(picture[idx].getBytes("ISO-8859-1"));

            ServletOutputStream writer = response.getOutputStream();
            writer.write(decoded);
            writer.close();
        }

    } catch (Throwable t) {
        log.logWarn("Picture display failed", t);
    }

}

From source file:net.sourceforge.fenixedu.presentationTier.Action.externalServices.ISTConnectDA.java

private void writeJSONObject(HttpServletResponse response, final JSONArray jsonObject) throws IOException {
    final ServletOutputStream outputStream = response.getOutputStream();
    outputStream.write(jsonObject.toJSONString().getBytes());
    outputStream.close();/*ww  w.ja  v a 2  s. co m*/
}

From source file:org.codelibs.fess.helper.OpenSearchHelper.java

public void write(final HttpServletResponse response) {
    if (osddFile == null) {
        throw new FessSystemException("Unsupported OpenSearch response.");
    }//  ww w . j  a v  a 2  s.c o  m

    response.setContentType(contentType + "; charset=" + encoding);
    ServletOutputStream os = null;
    try {
        os = response.getOutputStream();
        os.write(FileUtil.getBytes(osddFile));
    } catch (final IOException e) {
        throw new FessSystemException("Failed to write OpenSearch response.", e);
    } finally {
        IOUtils.closeQuietly(os);
    }

}

From source file:com.geminimobile.web.DownloadCSVController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    String msisdn = (String) request.getParameter("msisdn");
    String startTime = (String) request.getParameter("starttime");
    String endTime = (String) request.getParameter("endtime");
    String market = (String) request.getParameter("market");
    String type = (String) request.getParameter("type");

    Date toDate = SearchCommand.m_sdf.parse(endTime);
    //String maxTimestamp = Long.toString(toDate.getTime());

    Date fromDate = SearchCommand.m_sdf.parse(startTime);
    //String minTimestamp = Long.toString(fromDate.getTime());

    CDRDataAccess cdrAccess = new CDRDataAccess();
    Vector<CDREntry> cdrs = cdrAccess.getCDRsByMSISDN(msisdn, fromDate.getTime(), toDate.getTime(), market,
            type, 100000); // 100,000 entries max

    //Vector<CDREntry> cdrs = (Vector<CDREntry>) request.getSession().getAttribute("cdrResults");

    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");
    }/*from  www  . ja  va2  s  .  com*/

    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;
}

From source file:com.dreamwork.web.FrontJsonController.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html; charset=UTF-8");
    ServletOutputStream out = response.getOutputStream();

    String message = "Not supported";

    out.write(message.getBytes("UTF-8"));
    out.flush();//from w w  w  . j a v  a 2  s  . com

}

From source file:ostepu.cconfig.help.java

/**
 * der Aufruf des help-Befehls//from   ww  w  .  j  ava  2 s  .  c o m
 *
 * @param context  der Kontext des Servlet
 * @param request  die eingehende Anfrage
 * @param response das Antwortobjekt
 */
public static void request(ServletContext context, HttpServletRequest request, HttpServletResponse response) {
    String pathInfo = request.getPathInfo();

    if (pathInfo == null) {
        try {
            response.sendError(404);
        } catch (IOException ex) {
            Logger.getLogger(help.class.getName()).log(Level.SEVERE, null, ex);
            response.setStatus(500);
        }
        return;
    }

    if (!"GET".equals(request.getMethod())) {
        try {
            response.sendError(404);
        } catch (IOException ex) {
            Logger.getLogger(help.class.getName()).log(Level.SEVERE, null, ex);
            response.setStatus(500);
        }
        return;
    }

    ServletOutputStream out;
    try {
        out = response.getOutputStream();
    } catch (IOException ex) {
        Logger.getLogger(help.class.getName()).log(Level.SEVERE, null, ex);
        response.setStatus(500);
        return;
    }

    String[] helpPath = pathInfo.split("/");
    String extension = FilenameUtils.getExtension(pathInfo);
    String language = helpPath[1];
    helpPath[helpPath.length - 1] = helpPath[helpPath.length - 1].substring(0,
            helpPath[helpPath.length - 1].length() - extension.length() - 1);
    helpPath = Arrays.copyOfRange(helpPath, 2, helpPath.length);

    Path helpFile = Paths.get(
            context.getRealPath("/data/help/" + String.join("_", helpPath) + "_" + language + "." + extension));

    try {
        if (Files.exists(helpFile)) {
            InputStream inp = new FileInputStream(helpFile.toFile());
            byte[] res = IOUtils.toByteArray(inp);
            inp.close();
            out.write(res);
            response.setStatus(200);
            response.setHeader("Content-Type", "charset=utf-8");
        } else {
            response.sendError(404);
        }
    } catch (IOException ex) {
        Logger.getLogger(help.class.getName()).log(Level.SEVERE, null, ex);
        response.setStatus(500);
    } finally {
        try {
            out.close();
        } catch (IOException ex) {
            Logger.getLogger(help.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:com.octo.captcha.module.struts.image.RenderImageCaptchaAction.java

public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm,
        HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

    ImageCaptchaService service = (ImageCaptchaService) CaptchaServicePlugin.getInstance().getService();
    String captchaID = CaptchaModuleConfigHelper.getId(httpServletRequest);
    //(String) theRequest.getParameter(captchaIDParameterName);

    // call the ManageableImageCaptchaService methods
    byte[] captchaChallengeAsJpeg = null;
    ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
    try {//w w  w  .ja  va2 s.co m
        BufferedImage challenge = service.getImageChallengeForID(captchaID, httpServletRequest.getLocale());
        // the output stream to render the captcha image as jpeg into

        // a jpeg encoder
        JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream);
        jpegEncoder.encode(challenge);
    } catch (IllegalArgumentException e) {
        // log a security warning and return a 404...
        if (log.isWarnEnabled()) {
            log.warn("There was a try from " + httpServletRequest.getRemoteAddr()
                    + " to render an URL without ID" + " or with a too long one");
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            log.error("should never pass here!");
            return actionMapping.findForward("error");
        }
    } catch (CaptchaServiceException e) {
        // log and return a 404 instead of an image...
        log.warn("Error trying to generate a captcha and " + "render its challenge as JPEG", e);
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        // log.error("should never pass here!");
        return actionMapping.findForward("error");
    }

    captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

    // render the captcha challenge as a JPEG image in the response
    httpServletResponse.setHeader("Cache-Control", "no-store");
    httpServletResponse.setHeader("Pragma", "no-cache");
    httpServletResponse.setDateHeader("Expires", 0);
    httpServletResponse.setContentType("image/jpeg");
    ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
    responseOutputStream.write(captchaChallengeAsJpeg);
    responseOutputStream.flush();
    responseOutputStream.close();
    // log.error("should never pass here!");
    return null;
}

From source file:mx.com.quadrum.contratos.controller.busquedas.MuestraPdf.java

@RequestMapping(value = "muestraPdf/{idContrato}", method = RequestMethod.GET)
public void muestraPdf(@PathVariable("idContrato") Integer idContrato, HttpSession session,
        HttpServletRequest request, HttpServletResponse response) {
    if (session.getAttribute(USUARIO) == null && session.getAttribute(CLIENTE) == null) {
        return;//from  w ww.  j av a  2 s  .co m
    }
    Contrato contrato = contratoService.buscarPorId(idContrato);

    Usuario usuario = (Usuario) session.getAttribute(USUARIO);
    response.setContentType("application/pdf");

    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    File pdf = new File(
            USUARIOS + usuario.getMail() + "\\" + contrato.getNombre() + "\\" + contrato.getNombre() + ".pdf");
    try {
        InputStream in = new FileInputStream(pdf);
        byte[] data = new byte[in.available()];
        in.read(data);
        javax.servlet.ServletOutputStream servletoutputstream = response.getOutputStream();

        servletoutputstream.write(data);
        servletoutputstream.flush();
        servletoutputstream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:unUtils.WikittyPublicationServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    Object result;//  w  ww .  jav  a 2 s  . c  om
    WikittyPublicationContext context = new WikittyPublicationContext(appConfig);
    try {
        context.parse(req, resp);

        if ("true".equals(context.getArguments().get("debug"))) {
            // debug asked, not do action, but show context
            result = context.toString();
            context.setContentType("text/plain");
        } else {
            WikittyPublicationAction action = context.getAction();
            result = action.doAction(context);
        }
    } catch (Throwable eee) {
        WikittyPublicationAction action = new ActionError(eee);
        result = action.doAction(context);
    }

    String contentType = context.getContentType();
    if (contentType != null && contentType.startsWith("forward")) {
        req.getRequestDispatcher(String.valueOf(result)).forward(req, resp);
    } else {
        if (contentType != null) {
            resp.setContentType(contentType);
        }
        if (result instanceof byte[]) {
            ServletOutputStream out = resp.getOutputStream();
            out.write((byte[]) result);
            out.flush();
        } else {
            PrintWriter out = resp.getWriter();
            out.write(String.valueOf(result));
            out.flush();
        }
    }
}