Search in sources :

Example 96 with ServletOutputStream

use of javax.servlet.ServletOutputStream in project async-http-client by AsyncHttpClient.

the class NonAsciiContentLengthTest method setUpGlobal.

@BeforeClass(alwaysRun = true)
public void setUpGlobal() throws Exception {
    server = new Server();
    ServerConnector connector = addHttpConnector(server);
    server.setHandler(new AbstractHandler() {

        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException {
            // Can only handle bodies of up to 1024 bytes.
            int MAX_BODY_SIZE = 1024;
            byte[] b = new byte[MAX_BODY_SIZE];
            int offset = 0;
            int numBytesRead;
            try (ServletInputStream is = request.getInputStream()) {
                while ((numBytesRead = is.read(b, offset, MAX_BODY_SIZE - offset)) != -1) {
                    offset += numBytesRead;
                }
            }
            assertEquals(request.getContentLength(), offset);
            response.setStatus(200);
            response.setCharacterEncoding(request.getCharacterEncoding());
            response.setContentLength(request.getContentLength());
            try (ServletOutputStream os = response.getOutputStream()) {
                os.write(b, 0, offset);
            }
        }
    });
    server.start();
    port1 = connector.getLocalPort();
}
Also used : ServerConnector(org.eclipse.jetty.server.ServerConnector) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletInputStream(javax.servlet.ServletInputStream) Server(org.eclipse.jetty.server.Server) ServletOutputStream(javax.servlet.ServletOutputStream) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) BeforeClass(org.testng.annotations.BeforeClass)

Example 97 with ServletOutputStream

use of javax.servlet.ServletOutputStream in project bamboobsc by billchen198318.

the class JReportUtils method fillReportToResponse.

public static void fillReportToResponse(String reportId, Map<String, Object> paramMap, HttpServletResponse response) throws ServiceException, Exception {
    if (StringUtils.isBlank(reportId)) {
        throw new java.lang.IllegalArgumentException("error, reportId is blank");
    }
    TbSysJreport sysJreport = new TbSysJreport();
    sysJreport.setReportId(reportId);
    DefaultResult<TbSysJreport> result = sysJreportService.findEntityByUK(sysJreport);
    if (result.getValue() == null) {
        throw new ServiceException(result.getSystemMessage().getValue());
    }
    sysJreport = result.getValue();
    String jasperFileFullPath = Constants.getDeployJasperReportDir() + "/" + sysJreport.getReportId() + "/" + sysJreport.getReportId() + ".jasper";
    File jasperFile = new File(jasperFileFullPath);
    if (!jasperFile.exists()) {
        jasperFile = null;
        throw new Exception("error, Files are missing : " + jasperFileFullPath);
    }
    InputStream reportSource = new FileInputStream(jasperFile);
    Connection conn = null;
    try {
        conn = DataUtils.getConnection();
        ServletOutputStream ouputStream = response.getOutputStream();
        JasperPrint jasperPrint = JasperFillManager.fillReport(reportSource, paramMap, conn);
        response.setContentType("application/pdf");
        response.setHeader("Content-disposition", "inline; filename=" + sysJreport.getReportId() + ".pdf");
        JRPdfExporter jrPdfExporter = new JRPdfExporter();
        jrPdfExporter.setExporterInput(new SimpleExporterInput(jasperPrint));
        jrPdfExporter.setExporterOutput(new SimpleOutputStreamExporterOutput(ouputStream));
        SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
        jrPdfExporter.setConfiguration(configuration);
        configuration.setOwnerPassword(Constants.getEncryptorKey1());
        jrPdfExporter.exportReport();
        ouputStream.flush();
        ouputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        DataUtils.doReleaseConnection(conn);
        if (null != reportSource) {
            try {
                reportSource.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        reportSource = null;
        jasperFile = null;
    }
}
Also used : TbSysJreport(com.netsteadfast.greenstep.po.hbm.TbSysJreport) ServletOutputStream(javax.servlet.ServletOutputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) SimpleOutputStreamExporterOutput(net.sf.jasperreports.export.SimpleOutputStreamExporterOutput) JasperPrint(net.sf.jasperreports.engine.JasperPrint) Connection(java.sql.Connection) SimpleExporterInput(net.sf.jasperreports.export.SimpleExporterInput) JRPdfExporter(net.sf.jasperreports.engine.export.JRPdfExporter) IOException(java.io.IOException) JRException(net.sf.jasperreports.engine.JRException) IOException(java.io.IOException) ServiceException(com.netsteadfast.greenstep.base.exception.ServiceException) FileInputStream(java.io.FileInputStream) ServiceException(com.netsteadfast.greenstep.base.exception.ServiceException) SimplePdfExporterConfiguration(net.sf.jasperreports.export.SimplePdfExporterConfiguration) ZipFile(net.lingala.zip4j.core.ZipFile) File(java.io.File)

Example 98 with ServletOutputStream

use of javax.servlet.ServletOutputStream in project opennms by OpenNMS.

the class MonkeyServlet method doGet.

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // super.doGet(req, resp);
    String responseText = "You are reading this from a servlet!\n";
    ServletOutputStream os = resp.getOutputStream();
    os.print(responseText);
    os.close();
    resp.setContentType("text/plain");
    resp.setContentLength(responseText.length());
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream)

Example 99 with ServletOutputStream

use of javax.servlet.ServletOutputStream in project Lucee by lucee.

the class CFMLWriterImpl method getOutputStream.

private OutputStream getOutputStream(boolean allowCompression) throws IOException {
    if (allowCompression) {
        String encodings = ReqRspUtil.getHeader(request, "Accept-Encoding", "");
        if (encodings.indexOf("gzip") != -1) {
            boolean inline = HttpServletResponseWrap.get();
            if (!inline) {
                ServletOutputStream os = response.getOutputStream();
                response.setHeader("Content-Encoding", "gzip");
                return new GZIPOutputStream(os);
            }
        }
    }
    return response.getOutputStream();
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) GZIPOutputStream(java.util.zip.GZIPOutputStream)

Example 100 with ServletOutputStream

use of javax.servlet.ServletOutputStream in project alf.io by alfio-event.

the class EventApiController method downloadSponsorScanExport.

@RequestMapping("/events/{eventName}/sponsor-scan/export.csv")
public void downloadSponsorScanExport(@PathVariable("eventName") String eventName, HttpServletResponse response, Principal principal) throws IOException {
    Event event = loadEvent(eventName, principal);
    List<TicketFieldConfiguration> fields = ticketFieldRepository.findAdditionalFieldsForEvent(event.getId());
    response.setContentType("text/csv;charset=UTF-8");
    response.setHeader("Content-Disposition", "attachment; filename=" + eventName + "-sponsor-scan.csv");
    try (ServletOutputStream out = response.getOutputStream();
        CSVWriter writer = new CSVWriter(new OutputStreamWriter(out))) {
        for (int marker : BOM_MARKERS) {
            out.write(marker);
        }
        List<String> header = new ArrayList<>();
        header.add("Username");
        header.add("Timestamp");
        header.add("Full name");
        header.add("Email");
        header.addAll(fields.stream().map(TicketFieldConfiguration::getName).collect(toList()));
        writer.writeNext(header.toArray(new String[header.size()]));
        userManager.findAllEnabledUsers(principal.getName()).stream().map(u -> Pair.of(u, userManager.getUserRole(u))).filter(p -> p.getRight() == Role.SPONSOR).flatMap(p -> sponsorScanRepository.loadSponsorData(event.getId(), p.getKey().getId(), SponsorScanRepository.DEFAULT_TIMESTAMP).stream().map(v -> Pair.of(v, ticketFieldRepository.findAllValuesForTicketId(v.getTicket().getId())))).map(p -> {
            DetailedScanData data = p.getLeft();
            Map<String, String> descriptions = p.getRight();
            return Pair.of(data, fields.stream().map(x -> descriptions.getOrDefault(x.getName(), "")).collect(toList()));
        }).map(p -> {
            List<String> line = new ArrayList<>();
            Ticket ticket = p.getLeft().getTicket();
            SponsorScan sponsorScan = p.getLeft().getSponsorScan();
            line.add(userManager.findUser(sponsorScan.getUserId()).getUsername());
            line.add(sponsorScan.getTimestamp().toString());
            line.add(ticket.getFullName());
            line.add(ticket.getEmail());
            line.addAll(p.getRight());
            return line.toArray(new String[line.size()]);
        }).forEachOrdered(writer::writeNext);
        writer.flush();
        out.flush();
    }
}
Also used : alfio.manager(alfio.manager) TemplateProcessor(alfio.controller.support.TemplateProcessor) StringUtils(org.apache.commons.lang3.StringUtils) BigDecimal(java.math.BigDecimal) Json(alfio.util.Json) Model(org.springframework.ui.Model) Pair(org.apache.commons.lang3.tuple.Pair) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SponsorScanRepository(alfio.repository.SponsorScanRepository) ParseException(java.text.ParseException) Triple(org.apache.commons.lang3.tuple.Triple) ZipEntry(java.util.zip.ZipEntry) DateFormat(java.text.DateFormat) PageAndContent(alfio.controller.api.support.PageAndContent) TicketCategoryDescriptionRepository(alfio.repository.TicketCategoryDescriptionRepository) Organization(alfio.model.user.Organization) Predicate(java.util.function.Predicate) TemplateManager(alfio.util.TemplateManager) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) Collectors(java.util.stream.Collectors) ZoneId(java.time.ZoneId) DynamicFieldTemplateRepository(alfio.repository.DynamicFieldTemplateRepository) Role(alfio.model.user.Role) Principal(java.security.Principal) alfio.model(alfio.model) org.springframework.web.bind.annotation(org.springframework.web.bind.annotation) alfio.model.modification(alfio.model.modification) OptionalWrapper.optionally(alfio.util.OptionalWrapper.optionally) ValidationResult(alfio.model.result.ValidationResult) ZipOutputStream(java.util.zip.ZipOutputStream) DataAccessException(org.springframework.dao.DataAccessException) Errors(org.springframework.validation.Errors) java.util(java.util) TicketHelper(alfio.controller.api.support.TicketHelper) Getter(lombok.Getter) EventListItem(alfio.controller.api.support.EventListItem) CSVReader(com.opencsv.CSVReader) SimpleDateFormat(java.text.SimpleDateFormat) Function(java.util.function.Function) TicketFieldRepository(alfio.repository.TicketFieldRepository) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletOutputStream(javax.servlet.ServletOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) StreamUtils(org.springframework.util.StreamUtils) OutputStream(java.io.OutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) CSVWriter(com.opencsv.CSVWriter) IOException(java.io.IOException) Validator(alfio.util.Validator) InputStreamReader(java.io.InputStreamReader) DateUtils(org.apache.commons.lang3.time.DateUtils) HttpStatus(org.springframework.http.HttpStatus) Collectors.toList(java.util.stream.Collectors.toList) Validate(org.apache.commons.lang3.Validate) MonetaryUtil(alfio.util.MonetaryUtil) UserManager(alfio.manager.user.UserManager) Log4j2(lombok.extern.log4j.Log4j2) ResponseEntity(org.springframework.http.ResponseEntity) I18nManager(alfio.manager.i18n.I18nManager) DescriptionsLoader(alfio.controller.api.support.DescriptionsLoader) AllArgsConstructor(lombok.AllArgsConstructor) ServletOutputStream(javax.servlet.ServletOutputStream) CSVWriter(com.opencsv.CSVWriter) OutputStreamWriter(java.io.OutputStreamWriter) Collectors.toList(java.util.stream.Collectors.toList)

Aggregations

ServletOutputStream (javax.servlet.ServletOutputStream)509 IOException (java.io.IOException)212 HttpServletResponse (javax.servlet.http.HttpServletResponse)147 Test (org.junit.Test)112 HttpServletRequest (javax.servlet.http.HttpServletRequest)109 ServletException (javax.servlet.ServletException)91 InputStream (java.io.InputStream)62 File (java.io.File)57 ByteArrayOutputStream (java.io.ByteArrayOutputStream)40 FileInputStream (java.io.FileInputStream)40 CountDownLatch (java.util.concurrent.CountDownLatch)27 WriteListener (javax.servlet.WriteListener)27 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)27 PrintWriter (java.io.PrintWriter)26 HttpServlet (javax.servlet.http.HttpServlet)25 AsyncContext (javax.servlet.AsyncContext)23 ServletInputStream (javax.servlet.ServletInputStream)22 ArrayList (java.util.ArrayList)21 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)20 Date (java.util.Date)18