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 void write(byte b[], int off, int len) throws IOException 

Source Link

Document

Writes len bytes from the specified byte array starting at offset off to this output stream.

Usage

From source file:edu.cornell.mannlib.vitro.webapp.filestorage.serving.FileServingServlet.java

@Override
protected void doGet(HttpServletRequest rawRequest, HttpServletResponse response)
        throws ServletException, IOException {
    VitroRequest request = new VitroRequest(rawRequest);

    // Use the alias URL to get the URI of the bytestream object.
    String path = request.getServletPath() + request.getPathInfo();
    log.debug("Path is '" + path + "'");

    /*//  w w w.  j av a 2s .  c  o  m
     * Get the mime type and an InputStream from the file. If we can't, use
     * the dummy image file instead.
     */
    InputStream in;
    String mimeType = null;
    try {
        FileInfo fileInfo = figureFileInfo(request.getWebappDaoFactory(), path);
        mimeType = fileInfo.getMimeType();

        String actualFilename = findAndValidateFilename(fileInfo, path);

        in = openImageInputStream(fileInfo, actualFilename);
    } catch (FileServingException e) {
        log.info("Failed to serve the file at '" + path + "' -- " + e);
        in = openMissingLinkImage(request);
        mimeType = "image/png";
    } catch (Exception e) {
        log.warn("Failed to serve the file at '" + path + "' -- " + e);
        in = openMissingLinkImage(request);
        mimeType = "image/png";
    }

    /*
     * Everything is ready. Set the status and the content type, and send
     * the image bytes.
     */
    response.setStatus(SC_OK);

    if (mimeType != null) {
        response.setContentType(mimeType);
    }

    ServletOutputStream out = null;
    try {
        out = response.getOutputStream();
        byte[] buffer = new byte[8192];
        int howMany;
        while (-1 != (howMany = in.read(buffer))) {
            out.write(buffer, 0, howMany);
        }
    } catch (IOException e) {
        log.warn("Failed to serve the file", e);
    } finally {
        try {
            in.close();
        } catch (Exception e) {
            log.warn("Serving " + request.getRequestURI() + ". Failed to close input stream.", e);
        }
        if (out != null) {
            try {
                out.close();
            } catch (Exception e) {
                log.warn("Serving " + request.getRequestURI() + ". Failed to close output stream.", e);
            }
        }
    }
}

From source file:nz.net.orcon.kanban.controllers.XmlFileController.java

private void generateXml(HttpServletResponse response, String boardId, Collection<Card> cardList)
        throws Exception {
    String xmlFileName = boardId + "-" + Calendar.getInstance().getTime() + ".xml";
    HashMap<String, String> aliases = new HashMap<String, String>();
    aliases.put("Card", "nz.net.orcon.kanban.model.Card");
    xstreamMarshaller.setAliases(aliases);
    XStream xStream = xstreamMarshaller.getXStream();
    xStream.registerConverter(new CardConverter());

    StringBuffer xmlCards = new StringBuffer();
    xmlCards.append("<Cards> \n");
    for (Card card : cardList) {
        xmlCards.append(xStream.toXML(card));
        xmlCards.append("\n");
    }//from ww  w  . j a  va2  s. c  o  m
    xmlCards.append("</Cards>");

    InputStream in = new ByteArrayInputStream(xmlCards.toString().getBytes("UTF-8"));
    ServletOutputStream out = response.getOutputStream();
    response.setContentLength(xmlCards.length());
    response.setHeader("Content-Disposition", "attachment; filename=\"" + xmlFileName + "\"");

    byte[] outputByte = new byte[4096];
    //copy binary content to output stream
    while (in.read(outputByte, 0, 4096) != -1) {
        out.write(outputByte, 0, 4096);
    }
    in.close();
    out.flush();
    out.close();
}

From source file:com.hp.security.jauth.admin.controller.BaseController.java

@RequestMapping("getResource")
public void getResource(String path, HttpServletRequest request, HttpServletResponse response)
        throws IOException, TemplateException {
    if (null != path) {
        if (path.endsWith(".js")) {
            response.setContentType("text/js");
        } else if (path.endsWith(".css")) {
            response.setContentType("text/css");
        } else if (path.endsWith(".gif")) {
            response.setContentType("image/gif");
        } else if (path.endsWith(".jpg") || path.endsWith(".jpeg")) {
            response.setContentType("image/jpeg");
        } else if (path.endsWith(".png")) {
            response.setContentType("image/png");
        } else {/*from   w  w  w  .j a  va 2  s  .  c  o m*/
            response.setContentType("text/html");
        }
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource resource = resolver.getResource("jauth/resources/" + path);
        ServletOutputStream out = response.getOutputStream();
        InputStream is = resource.getInputStream();
        int read = 0;
        byte[] buffer = new byte[8192];
        while ((read = is.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        out.flush();
        out.close();
    }
}

From source file:org.activiti.app.rest.idm.IdmProfileResource.java

@RequestMapping(value = "/profile-picture", method = RequestMethod.GET)
public void getProfilePicture(HttpServletResponse response) {
    try {/* www  .  ja  va2 s .c o m*/
        Picture picture = identityService.getUserPicture(SecurityUtils.getCurrentUserId());
        response.setContentType(picture.getMimeType());
        ServletOutputStream servletOutputStream = response.getOutputStream();
        BufferedInputStream in = new BufferedInputStream(new ByteArrayInputStream(picture.getBytes()));

        byte[] buffer = new byte[32384];
        while (true) {
            int count = in.read(buffer);
            if (count == -1)
                break;
            servletOutputStream.write(buffer, 0, count);
        }

        // Flush and close stream
        servletOutputStream.flush();
        servletOutputStream.close();
    } catch (Exception e) {
        throw new InternalServerErrorException("Could not get profile picture", e);
    }
}

From source file:com.google.appengine.tools.mapreduce.MapReduceServletTest.java

public void testStaticResources_status() throws Exception {
    HttpServletResponse resp = createMock(HttpServletResponse.class);
    resp.setContentType("text/html");
    resp.setHeader("Cache-Control", "public; max-age=300");
    ServletOutputStream sos = createMock(ServletOutputStream.class);
    expect(resp.getOutputStream()).andReturn(sos);
    sos.write((byte[]) EasyMock.anyObject(), EasyMock.eq(0), EasyMock.anyInt());
    EasyMock.expectLastCall().atLeastOnce();
    sos.flush();//  w  w  w  .jav  a  2 s.  c o m
    EasyMock.expectLastCall().anyTimes();
    replay(resp, sos);
    servlet.handleStaticResources("status", resp);
    verify(resp, sos);
}

From source file:com.google.appengine.tools.mapreduce.MapReduceServletTest.java

public void testStaticResources_jQuery() throws Exception {
    HttpServletResponse resp = createMock(HttpServletResponse.class);
    resp.setContentType("text/javascript");
    resp.setHeader("Cache-Control", "public; max-age=300");
    ServletOutputStream sos = createMock(ServletOutputStream.class);
    expect(resp.getOutputStream()).andReturn(sos);
    sos.write((byte[]) EasyMock.anyObject(), EasyMock.eq(0), EasyMock.anyInt());
    EasyMock.expectLastCall().atLeastOnce();
    sos.flush();/*from ww  w  .  j av  a2  s  .c  o m*/
    EasyMock.expectLastCall().anyTimes();
    replay(resp, sos);
    servlet.handleStaticResources("jquery.js", resp);
    verify(resp, sos);
}

From source file:com.rplt.studioMusik.controller.MemberController.java

@RequestMapping(value = "/cetakNota", method = RequestMethod.GET)
public String cetakNota(HttpServletResponse response) {
    //        Connection conn = DatabaseConnection.getmConnection();
    //            File reportFile = new File(application.getRealPath("Coba.jasper"));//your report_name.jasper file
    File reportFile = new File(
            servletConfig.getServletContext().getRealPath("/resources/report/nota_persewaan.jasper"));

    //        Map<String, Object> params = new HashMap<String, Object>();
    //        params.put("P_KODESEWA", request.getParameter("kodeSewa"));

    byte[] bytes = persewaanStudioMusik.cetakNota(request.getParameter("kodeSewa"), reportFile);
    //        //from w  ww . j  a  va 2  s  . c o m
    //        try {
    //            bytes = JasperRunManager.runReportToPdf(reportFile.getPath(), params, conn);
    //        } catch (JRException ex) {
    //            Logger.getLogger(MemberController.class.getName()).log(Level.SEVERE, null, ex);
    //        }

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

    try {
        ServletOutputStream outStream = response.getOutputStream();
        outStream.write(bytes, 0, bytes.length);
        outStream.flush();
        outStream.close();
    } catch (IOException ex) {
        Logger.getLogger(MemberController.class.getName()).log(Level.SEVERE, null, ex);
    }

    return "halaman-cetakNota-operator";
}

From source file:com.mkmeier.quickerbooks.ProcessUwcu.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request//from ww w. j ava  2s.  c o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    if (!ServletFileUpload.isMultipartContent(request)) {
        showForm(request, response);
    } else {

        ServletFileUploader up = new ServletFileUploader();
        up.parseRequest(request);

        File file = up.getFileMap().get("uwcuTxn");

        int depositAcctNum = Integer.parseInt(up.getFieldMap().get("depositAcct"));
        int creditCardAcctNum = Integer.parseInt(up.getFieldMap().get("ccAcct"));

        QbAccount depositAcct = getAccount(depositAcctNum);
        QbAccount creditCardAcct = getAccount(creditCardAcctNum);

        UwcuParser uwcuParser = new UwcuParser(file);
        List<UwcuTxn> txns;

        try {
            txns = uwcuParser.parse();
        } catch (UwcuException ex) {
            throw new ServletException(ex);
        }

        UwcuToIif uwcuToIif = new UwcuToIif(txns, depositAcct, creditCardAcct);
        File iifFile = uwcuToIif.getIifFile();

        response.setHeader("Content-Disposition", "attachement; filename=\"iifFile.iif\"");
        ServletOutputStream out = response.getOutputStream();
        FileInputStream in = new FileInputStream(iifFile);
        byte[] buffer = new byte[4096];
        int length;
        while ((length = in.read(buffer)) > 0) {
            out.write(buffer, 0, length);
        }
        in.close();
        out.flush();
    }
}

From source file:org.wise.vle.web.RApacheController.java

/**
 * Handle requests to the RApache server
 * @param request// w  ww .  ja v  a  2 s  .  co m
 * @param response
 * @throws IOException 
 * @throws ServletException 
 * @throws JSONException 
 */
private void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    HttpClient client = new HttpClient();

    String targetURL = null;
    String rtype = null;

    try {
        vleProperties = new Properties();
        vleProperties.load(getClass().getClassLoader().getResourceAsStream("vle.properties"));
        targetURL = vleProperties.getProperty("rApache_url");
        rtype = request.getParameter("type");
    } catch (Exception e) {
        System.err
                .println("RApacheController could not locate the rApache URL and/or identify the request type");
        e.printStackTrace();
    }

    if (targetURL != null && rtype != null) {
        // Create a method instance.
        if (rtype.equals("rstat")) {
            PostMethod method = new PostMethod(targetURL);

            String rdata = request.getParameter("rdata");

            // Map input = request.getParameterMap();

            // Provide custom retry handler is necessary
            method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                    new DefaultHttpMethodRetryHandler(3, false));

            method.addParameter(new NameValuePair("rtype", rtype));
            method.addParameter(new NameValuePair("rdata", rdata));

            byte[] responseBody = null;
            try {

                // Execute the method.
                int statusCode = client.executeMethod(method);

                if (statusCode != HttpStatus.SC_OK) {
                    System.err.println("Method failed: " + method.getStatusLine());
                }

                // Read the response body.
                responseBody = method.getResponseBody();

                // Deal with the response.
                // Use caution: ensure correct character encoding and is not binary data
            } catch (HttpException e) {
                System.err.println("Fatal protocol violation: " + e.getMessage());
                e.printStackTrace();
            } catch (IOException e) {
                System.err.println("Fatal transport error: " + e.getMessage());
                e.printStackTrace();
            } finally {
                // Release the connection.
                method.releaseConnection();
            }

            String responseString = "";

            if (responseBody != null) {
                responseString = new String(responseBody);
            }

            try {
                response.getWriter().print(responseString);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            PostMethod method = new PostMethod(targetURL);

            String rdata = request.getParameter("rdata");
            rdata = URLDecoder.decode(rdata, "UTF-8");
            // Map input = request.getParameterMap();

            // Provide custom retry handler is necessary
            method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                    new DefaultHttpMethodRetryHandler(3, false));

            method.addParameter(new NameValuePair("rtype", rtype));
            method.addParameter(new NameValuePair("rdata", rdata));

            byte[] responseBody = null;
            try {

                // Execute the method.
                int statusCode = client.executeMethod(method);

                if (statusCode != HttpStatus.SC_OK) {
                    System.err.println("Method failed: " + method.getStatusLine());
                }

                // Read the response body.
                responseBody = method.getResponseBody();

                // Deal with the response.
                // Use caution: ensure correct character encoding and is not binary data
            } catch (HttpException e) {
                System.err.println("Fatal protocol violation: " + e.getMessage());
                e.printStackTrace();
            } catch (IOException e) {
                System.err.println("Fatal transport error: " + e.getMessage());
                e.printStackTrace();
            } finally {
                // Release the connection.
                method.releaseConnection();
            }

            try {

                ServletOutputStream out = response.getOutputStream();
                response.setContentType("image/jpeg");
                response.setContentLength(responseBody.length);
                out.write(responseBody, 0, responseBody.length);

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

From source file:org.pentaho.platform.web.servlet.ProxyServlet.java

protected void doProxy(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException {
    if (proxyURL == null) { // Got nothing from web.xml
        return;//  www .  j av a2  s  . co  m
    }

    String servletPath = request.getServletPath();
    // System .out.println( ">>>>>>>> REQ: " + request.getRequestURL().toString() ); //$NON-NLS-1$//$NON-NLS-2$
    PentahoSystem.systemEntryPoint();
    try {
        String theUrl = proxyURL + servletPath;
        PostMethod method = new PostMethod(theUrl);

        // Copy the parameters from the request to the proxy
        // System .out.print( ">>>>>>>> PARAMS: " ); //$NON-NLS-1$
        Map paramMap = request.getParameterMap();
        Map.Entry entry;
        String[] array;
        for (Iterator it = paramMap.entrySet().iterator(); it.hasNext();) {
            entry = (Map.Entry) it.next();
            array = (String[]) entry.getValue();
            for (String element : array) {
                method.addParameter((String) entry.getKey(), element);
                // System.out.print( (String)entry.getKey() + "=" + array[i]
                // + "&" ); //$NON-NLS-1$ //$NON-NLS-2$
            }
        }
        // System.out.println( "" ); //$NON-NLS-1$

        // Just in case someone is trying to spoof the proxy
        method.removeParameter("_TRUST_USER_"); //$NON-NLS-1$

        // Get the user from the session
        IPentahoSession userSession = getPentahoSession(request);
        String name = userSession.getName();

        // Add the trusted user from the session
        if ((name != null) && (name.length() > 0)) {
            method.addParameter("_TRUST_USER_", name); //$NON-NLS-1$
            // System.out.println( ">>>>>>>> USR: " + name ); //$NON-NLS-1$
        } else if ((errorURL != null) && (errorURL.trim().length() > 0)) {
            response.sendRedirect(errorURL);
            // System.out.println( ">>>>>>>> REDIR: " + errorURL );
            // //$NON-NLS-1$
            return;
        }

        // System.out.println( ">>>>>>>> PROXY: " + theUrl ); //$NON-NLS-1$
        debug(Messages.getInstance().getString("ProxyServlet.DEBUG_0001_OUTPUT_URL", theUrl)); //$NON-NLS-1$

        // Now do the request
        HttpClient client = new HttpClient();

        try {
            // Execute the method.
            int statusCode = client.executeMethod(method);

            if (statusCode != HttpStatus.SC_OK) {
                error(Messages.getInstance().getErrorString("ProxyServlet.ERROR_0003_REMOTE_HTTP_CALL_FAILED", //$NON-NLS-1$
                        method.getStatusLine().toString()));
                return;
            }
            setHeader("Content-Type", method, response); //$NON-NLS-1$
            setHeader("Content-Length", method, response); //$NON-NLS-1$

            InputStream inStr = method.getResponseBodyAsStream();
            ServletOutputStream outStr = response.getOutputStream();

            int inCnt = 0;
            byte[] buf = new byte[2048];
            while (-1 != (inCnt = inStr.read(buf))) {
                outStr.write(buf, 0, inCnt);
            }
        } catch (HttpException e) {
            error(Messages.getInstance().getErrorString("ProxyServlet.ERROR_0004_PROTOCOL_FAILURE"), e); //$NON-NLS-1$
            e.printStackTrace();
        } catch (IOException e) {
            error(Messages.getInstance().getErrorString("ProxyServlet.ERROR_0005_TRANSPORT_FAILURE"), e); //$NON-NLS-1$
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }
    } finally {
        PentahoSystem.systemExitPoint();
    }
}