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:de.berlios.jedi.presentation.editor.DownloadPackageAction.java

/**
 * Handle server requests./* w  ww.j a  va  2  s. c  o m*/
 * 
 * @param mapping
 *            The ActionMapping used to select this instance.
 * @param form
 *            The optional ActionForm bean for this request (if any).
 * @param request
 *            The HTTP request we are processing.
 * @param response
 *            The HTTP response we are creating.
 */
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {

    JispPackagesList jispPackagesList = (JispPackagesList) request.getSession()
            .getAttribute(EditorKeys.JISP_PACKAGES_LIST_KEY);
    JispPackage jispPackage = (JispPackage) request.getSession().getAttribute(EditorKeys.JISP_PACKAGE);

    setJispMetadata(jispPackage, jispPackagesList);

    JispFile jispFile = null;
    try {
        jispFile = new EditorLogicService().getJispFileFromJispPackage(jispPackage);
    } catch (UnsupportedOperationException e) {
        LogFactory.getLog(DownloadPackageAction.class).fatal("UTF-8 encoding not supported!!!", e);

        return errorForward(mapping, request, new ActionMessage("utf8NotSupported"), "utf8NotSupported",
                Keys.ADD_STATUS_FORWARD_NAME);
    } catch (JispIncompletePackageException e) {
        LogFactory.getLog(DownloadPackageAction.class).error("Incomplete JispPackage", e);

        return errorForward(mapping, request, new ActionMessage("incompleteJispPackage", e.getMessage()),
                "incompleteJispPackage", Keys.ADD_STATUS_FORWARD_NAME);
    }

    response.setContentType("application/vnd.jisp");
    // Filename should be equal to the name of the root directory of the
    // jisp file
    response.setHeader("Content-disposition",
            "attachment; filename=\"" + JispUtil.getDefaultRootDirectoryName(jispPackage) + ".jisp\"");

    ServletOutputStream out = null;
    try {
        out = response.getOutputStream();
        out.write(jispFile.getData());
    } catch (IOException e) {
        LogFactory.getLog(DownloadPackageAction.class)
                .error("IOException when writing the JispFile to the " + "ServlerOutputStream", e);

        return errorForward(mapping, request, new ActionMessage("failedJispFileWriteToOutputStream"),
                "failedJispFileWriteToOutputStream", Keys.ADD_STATUS_FORWARD_NAME);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
    }

    return null;
}

From source file:com.github.safrain.remotegsh.server.RgshFilter.java

private void performJar(HttpServletResponse response) throws IOException {
    ServletOutputStream os = response.getOutputStream();
    os.write(toBytes(RgshFilter.class.getClassLoader().getResourceAsStream(RESOURCE_PATH + JAR_NAME)));
    response.setStatus(200);/*from  w  w w  .  ja  va  2  s. c o  m*/
}

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

/**
 * Return raw data to the client./*  w w w. j a v a 2  s  .c o m*/
 *
 * @param client
 * @param buffer
 * @param resp
 * @throws IOException
 */
protected void returnMessage(RTMPTConnection client, ByteBuffer buffer, HttpServletResponse resp)
        throws IOException {
    resp.setStatus(HttpServletResponse.SC_OK);
    resp.setHeader("Connection", "Keep-Alive");
    resp.setHeader("Cache-Control", "no-cache");
    resp.setContentType(CONTENT_TYPE);
    //this will prevent stringbuffers from being created when not in debug mode
    if (log.isDebugEnabled()) {
        log.debug("Sending " + buffer.limit() + " bytes.");
    }
    resp.setContentLength(buffer.limit() + 1);
    ServletOutputStream output = resp.getOutputStream();
    output.write(client.getPollingDelay());
    ServletUtils.copy(buffer.asInputStream(), output);
    buffer = null;
}

From source file:gov.utah.dts.sdc.actions.StudentSearchAction.java

private void pdfOut(byte[] contents, String fileName) throws Exception {

    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
    ServletOutputStream out = response.getOutputStream();

    out.write(contents);

    out.flush();//from   w w  w  .j a va2  s  .c o  m
    out.close();

}

From source file:com.yanbang.portal.controller.PortalController.java

/**
 * ???//from   w  ww .  j av  a2s .c  o  m
 * 
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping(params = "action=handleRnd")
public void handleRnd(HttpServletRequest request, HttpServletResponse response) throws Exception {
    response.setHeader("Cache-Control", "no-store");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0L);
    response.setContentType("image/jpeg");
    BufferedImage image = new BufferedImage(65, 25, BufferedImage.TYPE_INT_RGB);
    Graphics g = image.getGraphics();
    g.setColor(Color.GRAY);
    g.fillRect(0, 0, 65, 25);
    g.setColor(Color.yellow);
    Font font = new Font("", Font.BOLD, 20);
    g.setFont(font);
    Random r = new Random();
    String rnd = "";
    int ir = r.nextInt(10);
    rnd = rnd + "" + ir;
    g.drawString("" + ir, 5, 18);
    g.setColor(Color.red);
    ir = r.nextInt(10);
    rnd = rnd + "" + ir;
    g.drawString("" + ir, 20, 18);
    g.setColor(Color.blue);
    ir = r.nextInt(10);
    rnd = rnd + "" + ir;
    g.drawString("" + ir, 35, 18);
    g.setColor(Color.green);
    ir = r.nextInt(10);
    rnd = rnd + "" + ir;
    g.drawString("" + ir, 50, 18);
    request.getSession().setAttribute("RND", rnd);
    ServletOutputStream out = response.getOutputStream();
    out.write(ImageUtil.imageToBytes(image, "gif"));
    out.flush();
    out.close();
}

From source file:ch.ralscha.extdirectspring.controller.ApiController.java

/**
 * Method that handles api.js and api-debug.js calls. Generates a javascript with the
 * necessary code for Ext Direct./*from   w  w  w.  j  a v a  2  s . c  o  m*/
 *
 * @param apiNs name of the namespace the variable remotingApiVar will live in.
 * Defaults to Ext.app
 * @param actionNs name of the namespace the action will live in.
 * @param remotingApiVar name of the remoting api variable. Defaults to REMOTING_API
 * @param pollingUrlsVar name of the polling urls object. Defaults to POLLING_URLS
 * @param group name of the api group. Multiple groups delimited with comma
 * @param fullRouterUrl if true the router property contains the full request URL with
 * method, server and port. Defaults to false returns only the URL without method,
 * server and port
 * @param format only valid value is "json2. Ext Designer sends this parameter and the
 * response is a JSON. Defaults to null and response is Javascript.
 * @param baseRouterUrl Sets the path to the router and poll controllers. If set
 * overrides default behavior that uses request.getRequestURI
 * @param request the HTTP servlet request
 * @param response the HTTP servlet response
 * @throws IOException
 */
@SuppressWarnings({ "resource" })
@RequestMapping(value = { "/api.js", "/api-debug.js", "/api-debug-doc.js" }, method = RequestMethod.GET)
public void api(@RequestParam(value = "apiNs", required = false) String apiNs,
        @RequestParam(value = "actionNs", required = false) String actionNs,
        @RequestParam(value = "remotingApiVar", required = false) String remotingApiVar,
        @RequestParam(value = "pollingUrlsVar", required = false) String pollingUrlsVar,
        @RequestParam(value = "group", required = false) String group,
        @RequestParam(value = "fullRouterUrl", required = false) Boolean fullRouterUrl,
        @RequestParam(value = "format", required = false) String format,
        @RequestParam(value = "baseRouterUrl", required = false) String baseRouterUrl,
        HttpServletRequest request, HttpServletResponse response) throws IOException {

    if (format == null) {
        response.setContentType(this.configurationService.getConfiguration().getJsContentType());
        response.setCharacterEncoding(ExtDirectSpringUtil.UTF8_CHARSET.name());

        String apiString = buildAndCacheApiString(apiNs, actionNs, remotingApiVar, pollingUrlsVar, group,
                fullRouterUrl, baseRouterUrl, request);

        byte[] outputBytes = apiString.getBytes(ExtDirectSpringUtil.UTF8_CHARSET);
        response.setContentLength(outputBytes.length);

        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(outputBytes);
        outputStream.flush();
    } else {
        response.setContentType(RouterController.APPLICATION_JSON.toString());
        response.setCharacterEncoding(RouterController.APPLICATION_JSON.getCharset().name());

        String requestUrlString = request.getRequestURL().toString();

        boolean debug = requestUrlString.contains("api-debug.js");
        String routerUrl = requestUrlString.replaceFirst("api[^/]*?\\.js", "router");

        String apiString = buildApiJson(apiNs, actionNs, remotingApiVar, routerUrl, group, debug);
        byte[] outputBytes = apiString.getBytes(ExtDirectSpringUtil.UTF8_CHARSET);
        response.setContentLength(outputBytes.length);

        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(outputBytes);
        outputStream.flush();
    }
}

From source file:jp.xet.uncommons.web.HtmlCompressionFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    OutputStreamResponseWrapper wrappedResponse = new OutputStreamResponseWrapper(response);

    filterChain.doFilter(request, wrappedResponse);

    ByteArrayOutputStream baos = wrappedResponse.getRealOutputStream();

    if (enabled && Strings.nullToEmpty(response.getContentType()).startsWith("text/html")) {
        HtmlCompressor compressor = new HtmlCompressor();
        compressor.setEnabled(enabled);//from   ww w .  j  a va2  s.  c  o  m
        compressor.setRemoveComments(removeComments);
        compressor.setRemoveMultiSpaces(removeMultiSpaces);
        compressor.setRemoveIntertagSpaces(removeIntertagSpaces);
        compressor.setRemoveQuotes(removeQuotes);
        compressor.setCompressJavaScript(compressJavaScript);
        compressor.setCompressCss(compressCss);
        compressor.setYuiJsNoMunge(yuiJsNoMunge);
        compressor.setYuiJsPreserveAllSemiColons(yuiJsPreserveAllSemiColons);
        compressor.setYuiJsDisableOptimizations(yuiJsDisableOptimizations);
        compressor.setYuiJsLineBreak(yuiJsLineBreak);
        compressor.setYuiCssLineBreak(yuiCssLineBreak);

        PrintWriter writer = null;
        try {
            String compressed = compressor.compress(baos.toString());
            response.setContentLength(compressed.length());
            writer = response.getWriter();
            writer.write(compressed);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    } else if (baos != null) {
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            outputStream.write(baos.toByteArray());
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }
}

From source file:com.jd.survey.web.reports.ReportController.java

@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/{id}", params = "spss", produces = "text/html")
public void surveySPSSExport(@PathVariable("id") Long surveyDefinitionId, Principal principal,
        HttpServletRequest httpServletRequest, HttpServletResponse response) {
    try {/*from ww  w .  j av  a  2  s . c o  m*/
        User user = userService.user_findByLogin(principal.getName());
        if (!securityService.userIsAuthorizedToManageSurvey(surveyDefinitionId, user)) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            response.sendRedirect("../accessDenied");
            //throw new AccessDeniedException("Unauthorized access attempt");
        }

        String metadataFileName = "survey" + surveyDefinitionId + ".sps";
        String dataFileName = "survey" + surveyDefinitionId + ".dat";

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zipfile = new ZipOutputStream(baos);

        //metadata    
        zipfile.putNextEntry(new ZipEntry(metadataFileName));
        zipfile.write(sPSSHelperService.getSurveyDefinitionSPSSMetadata(surveyDefinitionId, dataFileName));
        //data
        zipfile.putNextEntry(new ZipEntry(dataFileName));
        zipfile.write(sPSSHelperService.getSurveyDefinitionSPSSData(surveyDefinitionId));
        zipfile.close();

        //response.setContentType("text/html; charset=utf-8");
        response.setContentType("application/octet-stream");
        // 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=survey" + surveyDefinitionId + "_spss.zip");
        ServletOutputStream servletOutputStream = response.getOutputStream();
        //servletOutputStream.write(stringBuilder.toString().getBytes("UTF-8"));
        servletOutputStream.write(baos.toByteArray());
        servletOutputStream.flush();

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}

From source file:com.jd.survey.web.settings.InvitationController.java

/**
 *  exports a sample invitations comma delimited file
 * @param dataSetId//from   w  w  w  .jav  a2  s. c  om
 * @param principal
 * @param response
 */
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/example", produces = "text/html")
public void getExampleCsvFile(Principal principal, HttpServletResponse response) {
    try {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(messageSource.getMessage(FIRST_NAME_MESSAGE, null, LocaleContextHolder.getLocale())
                .replace(",", ""));
        stringBuilder.append(",");
        stringBuilder.append(messageSource
                .getMessage(MIDDLE_NAME_MESSAGE, null, LocaleContextHolder.getLocale()).replace(",", ""));
        stringBuilder.append(",");
        stringBuilder.append(messageSource.getMessage(LAST_NAME_MESSAGE, null, LocaleContextHolder.getLocale())
                .replace(",", ""));
        stringBuilder.append(",");
        stringBuilder.append(messageSource.getMessage(EMAIL_MESSAGE, null, LocaleContextHolder.getLocale())
                .replace(",", ""));
        stringBuilder.append("\n");
        stringBuilder.append("a,b,c,abc@jdsoft.com\n");
        //response.setContentType("text/html; charset=utf-8");
        response.setContentType("application/octet-stream");
        // 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=Invitationsexample.csv");
        ServletOutputStream servletOutputStream = response.getOutputStream();
        servletOutputStream.write(stringBuilder.toString().getBytes("UTF-8"));
        servletOutputStream.flush();

    }

    catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:org.ikasan.console.web.controller.WiretapEventsSearchFormController.java

/**
 * Download the payload content as a file
 * //from  w  w w . j  a  v a  2s .  c  o  m
 * TODO Improve Error handling?
 * 
 * @param wiretapEventId - The Event id of the wiretapped event to download
 * @param response - The HttpServletResponse object, content is streamed to
 *            this
 */
@RequestMapping("downloadPayloadContent.htm")
public void outputFile(@RequestParam("wiretapEventId") long wiretapEventId,
        final HttpServletResponse response) {
    this.logger.debug("inside downloadPayloadContent, wiretapEventId=[" + wiretapEventId + "]");
    WiretapEvent wiretapEvent = this.wiretapService.getWiretapEvent(new Long(wiretapEventId));
    String outgoingFileName = String.valueOf(wiretapEvent.getIdentifier());
    response.setContentType("application/download");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + outgoingFileName + "\"");
    try {
        ServletOutputStream op = response.getOutputStream();
        op.write(wiretapEvent.getEvent().toString().getBytes());
        op.flush();
    } catch (IOException e) {
        this.logger.error("Could not download payload content.", e);
    }
}