Example usage for javax.servlet.http HttpServletResponse getOutputStream

List of usage examples for javax.servlet.http HttpServletResponse getOutputStream

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse getOutputStream.

Prototype

public ServletOutputStream getOutputStream() throws IOException;

Source Link

Document

Returns a ServletOutputStream suitable for writing binary data in the response.

Usage

From source file:cn.com.report.HtmlServlet3.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    InputStream is = HtmlServlet3.class.getResourceAsStream("templatedesign1.jrxml");
    resp.setContentType("application/pdf");

    OutputStream out = resp.getOutputStream();
    JasperPdfExporterBuilder pdfExporter = export.pdfExporter(out);
    try {/*from w ww . j  av  a2s . c  om*/
        JasperReportBuilder report = report();
        report.setTemplate(Templates.reportTemplate).setParameters(createParameters()).setTemplateDesign(is)
                .columns(col.column("Item", "item", type.stringType()),
                        col.column("?", "quantity", type.integerType()),
                        col.column("Unit price", "unitprice", type.integerType()))
                //.title(Templates.createTitleComponent("JasperTemplateDesign1"))
                .setDataSource(createDataSource())
        //           .show(false)
        ;
        ;
        File tempFile = File.createTempFile("web", ".pdf");
        report.toPdf(new FileOutputStream(tempFile));
        out.write(FileUtils.readFileToByteArray(tempFile));
        System.out.println("%%%%%%%%%%" + tempFile.getCanonicalPath());
        //         report.toPdf(pdfExporter);//?pdf?  
    } catch (DRException e) {
        e.printStackTrace();
    }
    out.close();
}

From source file:com.impala.paga.all.QueryMobileOperators.java

/**
 * /*w w w .j  a v  a2s  .c  om*/
 * @param request
 * @param response
 * @throws ServletException
 *             , IOException
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    OutputStream out = response.getOutputStream();

    response.setContentType("text/plain;charset=UTF-8");
    response.setDateHeader("Expires", new Date().getTime()); // Expiration
    // date
    response.setDateHeader("Date", new Date().getTime()); // Date and time
    try {
        // that the
        // message was
        // sent
        out.write(moneytransfer(request).getBytes());
    } catch (JSONException ex) {
        Logger.getLogger(QueryMobileOperators.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(QueryMobileOperators.class.getName()).log(Level.SEVERE, null, ex);
    }
    out.flush();
    out.close();
}

From source file:net.scran24.staff.server.services.UploadUserInfoService.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("text/html");
    ServletOutputStream outputStream = resp.getOutputStream();
    PrintWriter writer = new PrintWriter(outputStream);

    if (!ServletFileUpload.isMultipartContent(req)) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
    } else {/* ww  w .j a va2s . co  m*/
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletContext servletContext = this.getServletConfig().getServletContext();
        File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repository);

        ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            List<FileItem> items = upload.parseRequest(req);

            InputStream file = null;
            String role = null;
            Set<String> permissions = new HashSet<String>();
            String surveyId = req.getParameter("surveyId");

            for (FileItem i : items) {
                if (i.getFieldName().equals("file"))
                    file = i.getInputStream();
                else if (i.getFieldName().equals("role"))
                    role = i.getString();
                else if (i.getFieldName().equals("permission"))
                    permissions.add(i.getString());
            }

            if (file == null)
                throw new ServletException("file field not specified");
            if (role == null)
                throw new ServletException("role field not specified");
            if (surveyId == null)
                throw new ServletException("surveyId field not specified");

            List<UserRecord> userRecords = UserRecordCSV.fromCSV(file);

            try {
                Set<String> roles = new HashSet<String>();
                roles.add(role);

                dataStore.saveUsers(surveyId, mapToSecureUserRecords(userRecords, roles, permissions));
                writer.print("OK");
            } catch (DataStoreException e) {
                writer.print("ERR:" + e.getMessage());
            } catch (DuplicateKeyException e) {
                writer.print("ERR:" + e.getMessage());
            }

        } catch (FileUploadException e) {
            writer.print("ERR:" + e.getMessage());
        } catch (IOException e) {
            writer.print("ERR:" + e.getMessage());
        }
    }

    writer.close();
}

From source file:com.controlj.green.istat.web.StatServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    resp.setHeader("Expires", "Wed, 01 Jan 2003 12:00:00 GMT");
    resp.setHeader("Cache-Control", "no-cache");
    ServletOutputStream out = resp.getOutputStream();

    try {//  w  w  w  .java 2s.  co  m
        writeStats(out, req.getParameter("loc"), req);
    } catch (Exception e) {
        resp.sendError(500, e.getMessage());
        //throw new ServletException(e);
    }

    /*
    out.println("[{ hsp:67,");
    out.println("csp: 74,");
    out.println("off: 1.5,");
    out.println("lim: 3.0,");
    out.println("current:71,");
    out.println("loc:'"+req.getParameter("loc")+"',");
    out.println("time:'"+new Date().getSeconds()+"'");
    out.println("}]");
    */
}

From source file:edu.unc.lib.dl.ui.controller.DjatokaContentController.java

/**
 * Handles requests for jp2 metadata/*from   ww w .j a  v a  2  s  .  com*/
 * 
 * @param model
 * @param request
 * @param response
 */
@RequestMapping("/jp2Metadata/{id}/{datastream}")
public void getMetadata(@PathVariable("id") String id, @PathVariable("datastream") String datastream,
        HttpServletResponse response) {
    // Check if the user is allowed to view this object
    if (this.hasAccess(id, datastream)) {
        try {
            djatokaContentService.getMetadata(id, datastream, response.getOutputStream(), response);
        } catch (IOException e) {
            LOG.error("Error retrieving JP2 metadata content for " + id, e);
        }
    } else {
        LOG.debug("Access was forbidden to " + id + " for user " + GroupsThreadStore.getUsername());
        response.setStatus(HttpStatus.SC_FORBIDDEN);
    }
}

From source file:controllers.CarOptionValueController.java

@RequestMapping("/getXls")
public void getXls(Map<String, Object> model, HttpServletResponse response) throws Exception {
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=options.xls");
    carOptionValueService.getXls().write(response.getOutputStream());
}

From source file:ee.ria.xroad.proxy.testsuite.testcases.ServerProxyConnectionAborted2.java

@Override
public AbstractHandler getServerProxyHandler() {
    return new AbstractHandler() {
        @Override//from w ww  .java2s .com
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException {
            // Read all of the request.
            IOUtils.readLines(request.getInputStream());

            response.setContentType("text/xml");
            response.setContentLength(1000);
            response.getOutputStream().close();
            response.flushBuffer();
            baseRequest.setHandled(true);
        }
    };
}

From source file:com.stratelia.webactiv.servlets.RestOnlineFileServer.java

private void displayWarningHtmlCode(HttpServletResponse res) throws IOException {
    StringReader sr = null;/*from w w  w.j  a  v a 2 s .  co m*/
    OutputStream out2 = res.getOutputStream();
    int read;
    ResourceLocator resourceLocator = new ResourceLocator(
            "com.stratelia.webactiv.util.peasUtil.multiLang.fileServerBundle", "");
    sr = new StringReader(resourceLocator.getString("warning"));
    try {
        read = sr.read();
        while (read != -1) {
            SilverTrace.info("peasUtil", "RestOnlineFileServer.displayHtmlCode()", "root.MSG_GEN_ENTER_METHOD",
                    " StringReader read " + read);
            out2.write(read); // writes bytes into the response
            read = sr.read();
        }
    } catch (Exception e) {
        SilverTrace.warn("peasUtil", "RestOnlineFileServer.displayWarningHtmlCode", "root.EX_CANT_READ_FILE",
                "warning properties");
    } finally {
        try {
            if (sr != null) {
                sr.close();
            }
            out2.close();
        } catch (Exception e) {
            SilverTrace.warn("peasUtil", "RestOnlineFileServer.displayHtmlCode", "root.EX_CANT_READ_FILE",
                    "close failed");
        }
    }
}

From source file:com.vigglet.oei.service.GetServicePdfServlet.java

@Override
protected void downloadPdf(HttpServletRequest req, HttpServletResponse resp, User user, int modelId)
        throws Exception {
    File file = new ServicePdf(ServiceUtil.getInstance().findById(modelId), user).createServiceReport();
    resp.setContentLength((int) file.length());

    FileInputStream fis = new FileInputStream(file);
    IOUtils.copy(fis, resp.getOutputStream());
    IOUtils.closeQuietly(fis);//from w  ww  . j  av  a  2  s.  c o m
}

From source file:cn.com.report.HtmlServlet2.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    InputStream is = HtmlServlet2.class.getResourceAsStream("Blank_A4.jrxml");
    resp.setContentType("application/pdf");

    OutputStream out = resp.getOutputStream();
    JasperPdfExporterBuilder pdfExporter = export.pdfExporter(out);
    try {// w  w  w.  ja v  a2s.c  o  m
        JasperReportBuilder report = report();

        report.setTemplate(Templates.reportTemplate).setTemplateDesign(is).setParameters(createParameters())
                /*.columns(
                   col.column("Item",       "item",      type.stringType()),
                   col.column("?",   "quantity",  type.integerType()),
                   col.column("Unit price", "unitprice", type.integerType()))*/
                //           .title(Templates.createTitleComponent("TestDRByDiyDesigner"))
                .setDataSource(createDataSource()).show(false);
        File tempFile = File.createTempFile("xjjjxxxxxxxxx", ".pdf");
        report.toPdf(new FileOutputStream(tempFile));
        out.write(FileUtils.readFileToByteArray(tempFile));
        System.out.println("%%%%%%%%%%" + tempFile.getCanonicalPath());
        //         report.toPdf(pdfExporter);//?pdf?  
    } catch (DRException e) {
        e.printStackTrace();
    }
    out.close();
}