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:org.apache.struts2.views.jasperreports.JasperReportsResult.java

/**
 * Writes report bytes to response output stream.
 *
 * @param response Current response./*  w  w w  .j  a  v  a  2  s  . co m*/
 * @param output   Report bytes to write.
 * @throws ServletException on stream IOException.
 */
private void writeReport(HttpServletResponse response, byte[] output) throws ServletException {
    ServletOutputStream outputStream = null;
    try {
        outputStream = response.getOutputStream();
        outputStream.write(output);
        outputStream.flush();
    } catch (IOException e) {
        LOG.error("Error writing report output", e);
        throw new ServletException(e.getMessage(), e);
    } finally {
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException e) {
            LOG.error("Error closing report output stream", e);
            throw new ServletException(e.getMessage(), e);
        }
    }
}

From source file:com.octo.captcha.j2ee.servlet.ImageCaptchaFilter.java

/**
 * Generate a new ImageCaptcha, store it in the internal store and
 * render it as JPEG to the client.//from  w  w  w  .  j  ava2  s.  c  om
 * This method returns a 404 to the client instead of the image if
 * the request isn't correct (missing parameters, etc...).
 *
 * @param theRequest the request
 * @param theResponse the response
 * @throws IOException @TODO : DOCUMENT ME !
 * @throws ServletException @TODO : DOCUMENT ME  !
 */
private void generateAndRenderCaptcha(HttpServletRequest theRequest, HttpServletResponse theResponse)
        throws IOException, ServletException {
    // get captcha ID from the request
    String captchaID = theRequest.getParameter(captchaIDParameterName);

    // call the ImageCaptchaService methods
    byte[] captchaChallengeAsJpeg = null;
    try {
        captchaChallengeAsJpeg = this.captchaService.generateCaptchaAndRenderChallengeAsJpeg(captchaID);
    } catch (IllegalArgumentException e) {
        // log a security warning and return a 404...
        if (log.isWarnEnabled()) {
            log.warn("There was a try from " + theRequest.getRemoteAddr() + " to render an URL without ID"
                    + " or with a too long one");
            theResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
    } catch (ImageCaptchaServiceException 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);
        theResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // render the captcha challenge as a JPEG image in the response
    theResponse.setContentType("image/jpeg");
    ServletOutputStream responseOutputStream = theResponse.getOutputStream();
    responseOutputStream.write(captchaChallengeAsJpeg);
}

From source file:jetbrains.buildServer.torrent.TorrentTransportTest.java

@BeforeMethod
public void setUp() throws Exception {
    super.setUp();
    myServer = new Server(12345);
    WebAppContext handler = new WebAppContext();
    handler.setResourceBase("/");
    handler.setContextPath(CONTEXT_PATH);
    myDownloadMap = new HashMap<String, File>();
    myDownloadAttempts = new ArrayList<String>();
    myDownloadHonestly = true;/*from w ww  . j av a 2s .  c  om*/
    myDownloadHacks = new HashMap<String, byte[]>();
    myDownloadHackAttempts = new ArrayList<String>();
    handler.addServlet(new ServletHolder(new HttpServlet() {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            myDownloadAttempts.add(req.getPathInfo());
            final ServletOutputStream os = resp.getOutputStream();
            final File file = myDownloadMap.get(req.getPathInfo());
            final byte[] bytes = FileUtils.readFileToByteArray(file);
            os.write(bytes);
            os.close();
        }
    }), "/*");
    myServer.setHandler(handler);
    myServer.start();

    myAgentParametersMap = new HashMap<String, String>();

    Mockery m = new Mockery();
    myBuild = m.mock(AgentRunningBuild.class);
    final BuildProgressLogger myLogger = new BaseServerLoggerFacade() {
        @Override
        public void flush() {
        }

        @Override
        protected void log(final BuildMessage1 message) {

        }
    };

    m.checking(new Expectations() {
        {
            allowing(myBuild).getSharedConfigParameters();
            will(returnValue(myAgentParametersMap));
            allowing(myBuild).getBuildTypeId();
            will(returnValue("TC_Gaya80x_BuildDist"));
            allowing(myBuild).getBuildLogger();
            will(returnValue(myLogger));
        }
    });

    myDirectorySeeder = new TorrentsDirectorySeeder(createTempDir(), -1, 1);

    myTorrentTransport = new TorrentTransportFactory.TorrentTransport(myDirectorySeeder, new HttpClient(),
            myBuild.getBuildLogger()) {
        @Override
        protected byte[] download(@NotNull String urlString) throws IOException {
            if (myDownloadHonestly) {
                return super.download(urlString);
            } else {
                myDownloadHackAttempts.add(urlString);
                return myDownloadHacks.get(urlString);
            }
        }
    };

    myTempDir = createTempDir();
}

From source file:org.wso2.carbon.application.mgt.ui.ApplicationAdminClient.java

public void downloadCappArchive(String filename, HttpServletResponse response)
        throws IOException, ApplicationAdminExceptionException {

    ServletOutputStream out = response.getOutputStream();
    DataHandler dataHandler = stub.downloadCappArchive(filename);
    if (dataHandler != null) {
        response.setHeader("Content-Disposition", "fileName=" + filename + ".car");
        response.setContentType(dataHandler.getContentType());
        InputStream in = dataHandler.getDataSource().getInputStream();
        int nextChar;
        while ((nextChar = in.read()) != -1) {
            out.write((char) nextChar);
        }/*from   w  w w.j a  v a  2 s.c  o m*/
        out.flush();
        in.close();
        out.close();
    } else {
        out.write("The requested capp archive was not found on the server".getBytes());
    }

}

From source file:org.extensiblecatalog.ncip.v2.responder.implprof1.NCIPServlet.java

protected void returnValidationProblem(HttpServletResponse response, ValidationException validationException)
        throws ServletException {

    StringBuffer sb = new StringBuffer();
    sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
            // TODO: The version, namespace, etc. ought to come from ServiceContext
            .append("<ns1:NCIPMessage ns1:version=\"http://www.niso.org/ncip/v2_0/imp1/xsd/ncip_v2_0.xsd\"")
            .append(" xmlns:ns1=\"http://www.niso.org/2008/ncip\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"")
            .append(" xsi:schemaLocation=\"http://www.niso.org/2008/ncip ncip_v2_0.xsd\">\n");

    // This hand-marshaling may seem like a bad idea, but we may've entered this method because the marshaling is failing
    List<Problem> problemsList = validationException.getProblems();
    for (Problem p : problemsList) {

        sb.append("  <ns1:Problem>\n");
        ProblemType pt = p.getProblemType();
        if (pt != null) {

            sb.append("    <ns1:ProblemType");
            String scheme = p.getProblemType().getScheme();
            if (scheme != null && !scheme.isEmpty()) {
                sb.append(" ns1:Scheme=\"").append(scheme).append("\"");
            }/*from w w  w.  ja  va2  s.  c om*/
            sb.append(">").append(p.getProblemType().getValue()).append("</ns1:ProblemType>\n");

        }

        String pd = p.getProblemDetail();
        if (pd != null && !pd.isEmpty()) {

            sb.append("    <ns1:ProblemDetail>").append(StringEscapeUtils.escapeXml(pd))
                    .append("</ns1:ProblemDetail>\\n");

        }

        sb.append("  </ns1:Problem>\n");

    }

    sb.append("</ns1:NCIPMessage>");

    byte[] problemMsgBytes = sb.toString().getBytes();

    response.setContentLength(problemMsgBytes.length);

    try {

        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(problemMsgBytes);
        outputStream.flush();

    } catch (IOException e) {

        throw new ServletException("Exception writing Problem response.", e);

    }

}

From source file:org.wso2.carbon.mediation.library.ui.LibraryAdminClient.java

public void downloadCappArchive(String filename, HttpServletResponse response)
        throws IOException, MediationLibraryAdminServiceException {

    ServletOutputStream out = response.getOutputStream();
    DataHandler dataHandler = stub.downloadLibraryArchive(filename);
    if (dataHandler != null) {
        response.setHeader("Content-Disposition", "fileName=" + filename + ".zip");
        response.setContentType(dataHandler.getContentType());
        InputStream in = dataHandler.getDataSource().getInputStream();
        int nextChar;
        while ((nextChar = in.read()) != -1) {
            out.write((char) nextChar);
        }//from   ww w .ja va2s. co m
        out.flush();
        in.close();
        out.close();
    } else {
        out.write("The requested library archive was not found on the server".getBytes());
    }

}

From source file:org.openmrs.module.hl7output.web.controller.RHEApatientController.java

@RequestMapping(value = "/{ecID}/encounters", method = RequestMethod.GET)
@ResponseBody/*from  www.ja  v a  2 s  . c om*/
public Object getEncounters(@PathVariable("ecID") String enterpriseId,
        @RequestParam(value = "encounterUniqueId", required = false) String encounterUniqueId,
        @RequestParam(value = "dateStart", required = false) String dateStart,
        @RequestParam(value = "dateEnd", required = false) String dateEnd, HttpServletRequest request,
        HttpServletResponse response) throws ResponseException {

    LogEncounterService service = Context.getService(LogEncounterService.class);

    Date fromDate = null;
    Date toDate = null;
    Patient p = null;
    ORU_R01 r01 = null;

    log.info("RHEA Controller call detected...");
    log.info("Enterprise Patient Id is :" + enterpriseId);
    log.info("encounterUniqueId is :" + encounterUniqueId);
    log.info("dateStart is :" + dateStart);

    GetEncounterLog getEncounterLog = new GetEncounterLog();
    getEncounterLog.setEncounterUniqueId(encounterUniqueId);

    // first, we create from and to data objects out of the String
    // parameters

    if (enterpriseId == null) {
        log.info("Error : missing enterpriseId");
        getEncounterLog.setResult("Error, missing enterpriseId");
        service.saveGetEncounterLog(getEncounterLog);

        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }

    getEncounterLog.setEnterpriseId(enterpriseId);

    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
    try {
        if (dateStart != null)
            fromDate = format.parse(dateStart);
    } catch (ParseException e) {
        log.info("Error : failed to parse specidied start date : " + dateStart);
        getEncounterLog.setResult("Error, incorrectly parsed start date");
        service.saveGetEncounterLog(getEncounterLog);

        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }

    log.info("fromDate is :" + fromDate);

    try {
        if (dateEnd != null)
            toDate = format.parse(dateEnd);
    } catch (ParseException e) {
        log.info("Error : failed to parse specidied end date : " + dateEnd);
        getEncounterLog.setResult("Error, incorrectly parsed start date");
        service.saveGetEncounterLog(getEncounterLog);

        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }

    log.info("toDate is :" + toDate);

    getEncounterLog.setDateEnd(toDate);
    getEncounterLog.setDateStart(fromDate);

    // Next, we try to retrieve the matching patient object
    if (enterpriseId != null) {
        PatientIdentifierType patientIdentifierType = Context.getPatientService()
                .getPatientIdentifierTypeByName("ECID");
        List<PatientIdentifierType> identifierTypeList = new ArrayList<PatientIdentifierType>();
        identifierTypeList.add(patientIdentifierType);

        List<Patient> patients = Context.getPatientService().getPatients(null, enterpriseId, identifierTypeList,
                false);
        //I am not checking the identifier type here. Need to come back and add a check for this
        if (patients.size() == 1) {
            p = patients.get(0);
        }
    }

    // if the patient doesn't exist, we need to return 400-BAD REQUEST
    // because the parameters are malformed
    if (p == null) {
        log.info("Error : failed to retreive patient for the given uuid : " + enterpriseId);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

    } else {
        log.info("Patient id : " + p.getPatientId() + "was retreived...");

        if (p != null) {
            //get all the encounters for this patient
            List<Encounter> encounterList = Context.getEncounterService().getEncountersByPatient(p);
            //if the enconteruniqueId is not null, we can isolate the given encounter

            if (encounterUniqueId != null) {
                Iterator<Encounter> i = encounterList.iterator();
                while (i.hasNext()) {
                    if (!i.next().getUuid().equals(encounterUniqueId))
                        i.remove();
                }
            }

            //If the encounterUniqueId was not given, we will try to filter encounters based on from and to dates
            List<Encounter> filteredEncounterList = new ArrayList<Encounter>();

            if (fromDate != null || toDate != null) {
                for (Encounter encounter : encounterList) {
                    if (fromDate != null && toDate != null) {
                        if ((encounter.getEncounterDatetime().after(fromDate))
                                && (encounter.getEncounterDatetime().before(toDate))) {
                            filteredEncounterList.add(encounter);
                        }

                    } else if (fromDate == null) {
                        if (encounter.getEncounterDatetime().before(toDate)) {
                            filteredEncounterList.add(encounter);
                        }

                    } else {
                        if (encounter.getEncounterDatetime().after(fromDate)) {
                            filteredEncounterList.add(encounter);
                        }

                    }
                }

                log.info("The number of matching encounters are :" + filteredEncounterList.size());
                encounterList = filteredEncounterList;
            }
            log.info("Calling the ORU_R01 parser...");

            SortedSet<MatchingEncounters> encounterSet = new TreeSet<MatchingEncounters>();

            for (Encounter e : encounterList) {
                MatchingEncounters matchingEncounters = new MatchingEncounters();
                matchingEncounters.setGetEncounterLog(getEncounterLog);
                matchingEncounters.setEncounterId(e.getEncounterId());

                encounterSet.add(matchingEncounters);
            }

            getEncounterLog.setLogTime(new Date());
            if (encounterList.size() > 0)
                getEncounterLog.setResult("Results Retrived");
            if (encounterList.size() == 0)
                getEncounterLog.setResult("No Results Retrived");

            //Now we will generate the HL7 message

            GenerateORU_R01 R01Util = new GenerateORU_R01();
            try {
                r01 = R01Util.generateORU_R01Message(p, encounterList);
            } catch (Exception e) {
                getEncounterLog.setResult("Error : Processing hl7 message failed");
                service.saveGetEncounterLog(getEncounterLog);
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return null;
            }

            getEncounterLog.getMatchingEncounters().clear();
            getEncounterLog.setMatchingEncounters(encounterSet);

            service.saveGetEncounterLog(getEncounterLog);

        }

        try {
            // Convert the ORU_R01 object into a byte stream
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(r01);
            oos.flush();
            oos.close();
            bos.close();
            byte[] data = bos.toByteArray();

            // Write the bytestream into the HttpServletResponse
            ServletOutputStream stream = response.getOutputStream();
            stream.write(data);
            stream.flush();

            response.getWriter().flush();
            response.getWriter().close();

            //NOTE : Im returning the ORU_R01 object as a bytestream AND a session object. Why both ? remove one later !
            request.getSession().setAttribute("oru_r01", r01);

            response.setStatus(HttpServletResponse.SC_OK);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // Return null for now
    return null;
}

From source file:com.googlecode.noweco.calendar.CaldavServlet.java

@Override
public void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    MemoryFile locate = MemoryFileUtils.locate(ROOT, req.getRequestURI());
    if (locate == null) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;//  w w  w  .  ja  v a 2  s  . co m
    }
    Getcontenttype getcontenttype = locate.getProp().getGetcontenttype();
    if (getcontenttype != null) {
        resp.setContentType(getcontenttype.getContent().get(0));
    }
    ServletOutputStream outputStream = resp.getOutputStream();
    outputStream.write(locate.getContent());
    outputStream.close();
}

From source file:org.red5.stream.http.servlet.TransportSegmentFeeder.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)//from w  w  w .j a  v a  2s .  c  om
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.debug("Segment feed requested");
    // get red5 context and segmenter
    if (service == null) {
        ApplicationContext appCtx = (ApplicationContext) getServletContext()
                .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        service = (SegmenterService) appCtx.getBean("segmenter.service");
    }
    // get the requested stream / segment
    String servletPath = request.getServletPath();
    String streamName = servletPath.split("\\.")[0];
    log.debug("Stream name: {}", streamName);
    if (service.isAvailable(streamName)) {
        response.setContentType("video/MP2T");
        // data segment
        Segment segment = null;
        // setup buffers and output stream
        byte[] buf = new byte[188];
        ByteBuffer buffer = ByteBuffer.allocate(188);
        ServletOutputStream sos = response.getOutputStream();
        // loop segments
        while ((segment = service.getSegment(streamName)) != null) {
            do {
                buffer = segment.read(buffer);
                // log.trace("Limit - position: {}", (buffer.limit() - buffer.position()));
                if ((buffer.limit() - buffer.position()) == 188) {
                    buffer.get(buf);
                    // write down the output stream
                    sos.write(buf);
                } else {
                    log.info("Segment result has indicated a problem");
                    // verifies the currently requested stream segment
                    // number against the currently active segment
                    if (service.getSegment(streamName) == null) {
                        log.debug("Requested segment is no longer available");
                        break;
                    }
                }
                buffer.clear();
            } while (segment.hasMoreData());
            log.trace("Segment {} had no more data", segment.getIndex());
            // flush
            sos.flush();
            // segment had no more data
            segment.cleanupThreadLocal();
        }
        buffer.clear();
        buffer = null;
    } else {
        // let requester know that stream segment is not available
        response.sendError(404, "Requested segmented stream not found");
    }
}

From source file:eu.comvantage.dataintegration.QueryDistributionServiceImpl.java

private void print(HttpResponse in, HttpServletResponse out) throws IOException {
    //writing binary response stream
    for (Header h : in.getAllHeaders()) {
        out.addHeader(h.getName(), h.getValue());
    }//w  w  w.  j  av a  2 s  .c  om
    out.setStatus(in.getStatusLine().getStatusCode());
    out.setLocale(in.getLocale());
    out.setContentType("text/html");

    ServletOutputStream outstream = out.getOutputStream();
    int c;
    while ((c = in.getEntity().getContent().read()) != -1) {
        outstream.write(c);
    }
    outstream.flush();
}