Example usage for javax.servlet.http HttpServletResponse flushBuffer

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

Introduction

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

Prototype

public void flushBuffer() throws IOException;

Source Link

Document

Forces any content in the buffer to be written to the client.

Usage

From source file:org.fenixedu.parking.ui.Action.ParkingManagerDispatchAction.java

public ActionForward exportToPDFParkingCard(ActionMapping mapping, ActionForm actionForm,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

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

    final ParkingParty parkingParty = FenixFramework.getDomainObject(parkingPartyID);
    String parkingGroupID = request.getParameter("groupID");

    if (parkingGroupID != null) {
        String parkingRequestID = request.getParameter("code");
        if (request.getParameter("groupID") == null) {
            saveErrorMessage(request, "group", "error.invalidGroup");
            request.setAttribute("externalId", parkingRequestID);
            return showRequest(mapping, actionForm, request, response);
        }/* ww  w.  j ava2  s. c o  m*/

        if (!isValidGroup(parkingGroupID)) {
            saveErrorMessage(request, "group", "error.invalidGroup");
            request.setAttribute("externalId", parkingRequestID);
            return showRequest(mapping, actionForm, request, response);
        }
    }

    ParkingGroup parkingGroup = null;
    if (parkingGroupID != null) {
        parkingGroup = FenixFramework.getDomainObject(parkingGroupID);
    } else {
        parkingGroup = parkingParty.getParkingGroup();
    }

    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("imageUrl", "images/Logo_IST_color.tiff");

    Person person = (Person) parkingParty.getParty();
    parameters.put("number", getMostSignificantNumberString(person, parkingGroup));

    List<Person> persons = new ArrayList<Person>();
    persons.add(person);

    ReportResult report = ReportsUtils.generateReport("parkingManager.parkingCard", parameters, persons);
    byte[] data = report.getData();
    response.setContentType(report.getContentType());
    response.addHeader("Content-Disposition", "attachment; filename=cartao." + report.getFileExtension());
    response.setContentLength(data.length);
    ServletOutputStream writer = response.getOutputStream();
    writer.write(data);
    writer.flush();
    writer.close();
    response.flushBuffer();

    return mapping.findForward("");
}

From source file:org.apache.lucene.replicator.http.ReplicationService.java

/** Executes the replication task. */
public void perform(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String[] pathElements = getPathElements(req);

    if (pathElements.length != 2) {
        throw new ServletException("invalid path, must contain shard ID and action, e.g. */s1/update");
    }/*  w  w w  .j  a va2  s  .c  o  m*/

    final ReplicationAction action;
    try {
        action = ReplicationAction.valueOf(pathElements[ACTION_IDX].toUpperCase(Locale.ENGLISH));
    } catch (IllegalArgumentException e) {
        throw new ServletException("Unsupported action provided: " + pathElements[ACTION_IDX]);
    }

    final Replicator replicator = replicators.get(pathElements[SHARD_IDX]);
    if (replicator == null) {
        throw new ServletException("unrecognized shard ID " + pathElements[SHARD_IDX]);
    }

    // SOLR-8933 Don't close this stream.
    ServletOutputStream resOut = resp.getOutputStream();
    try {
        switch (action) {
        case OBTAIN:
            final String sessionID = extractRequestParam(req, REPLICATE_SESSION_ID_PARAM);
            final String fileName = extractRequestParam(req, REPLICATE_FILENAME_PARAM);
            final String source = extractRequestParam(req, REPLICATE_SOURCE_PARAM);
            InputStream in = replicator.obtainFile(sessionID, source, fileName);
            try {
                copy(in, resOut);
            } finally {
                in.close();
            }
            break;
        case RELEASE:
            replicator.release(extractRequestParam(req, REPLICATE_SESSION_ID_PARAM));
            break;
        case UPDATE:
            String currVersion = req.getParameter(REPLICATE_VERSION_PARAM);
            SessionToken token = replicator.checkForUpdate(currVersion);
            if (token == null) {
                resOut.write(0); // marker for null token
            } else {
                resOut.write(1);
                token.serialize(new DataOutputStream(resOut));
            }
            break;
        }
    } catch (Exception e) {
        resp.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); // propagate the failure
        try {
            /*
             * Note: it is assumed that "identified exceptions" are thrown before
             * anything was written to the stream.
             */
            ObjectOutputStream oos = new ObjectOutputStream(resOut);
            oos.writeObject(e);
            oos.flush();
        } catch (Exception e2) {
            throw new IOException("Could not serialize", e2);
        }
    } finally {
        resp.flushBuffer();
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.student.onlineTests.StudentTestsAction.java

public ActionForward showImage(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws FenixActionException {
    final String testCode = request.getParameter("testCode");
    final String exerciseId = request.getParameter("exerciseCode");
    final Integer imgCode = getRequestParameterAsInteger(request, "imgCode");
    final String imgTypeString = request.getParameter("imgType");
    final Integer feedbackId = getRequestParameterAsInteger(request, "feedbackCode");
    final Integer itemIndex = getRequestParameterAsInteger(request, "item");

    final DistributedTest distributedTest = FenixFramework.getDomainObject(testCode);
    if (distributedTest == null) {
        request.setAttribute("invalidTest", new Boolean(true));
        return mapping.findForward("testError");
    }//  w ww.  ja  v a 2 s . co  m
    final Registration registration = getRegistration(request);
    if (registration == null) {
        request.setAttribute("invalidTest", new Boolean(true));
        return mapping.findForward("testError");
    }
    String img = null;
    try {
        img = ReadStudentTestQuestionImage.run(registration.getExternalId(), distributedTest.getExternalId(),
                exerciseId, imgCode, feedbackId, itemIndex);
    } catch (FenixServiceException e) {
        throw new FenixActionException(e);
    }
    byte[] imageData = BaseEncoding.base64().decode(img);
    try {
        response.reset();
        response.setContentType(imgTypeString);
        response.setContentLength(imageData.length);
        response.setBufferSize(imageData.length);
        StringBuilder imageName = new StringBuilder();
        imageName.append("image").append(exerciseId).append(imgCode);
        if (feedbackId != null) {
            imageName.append("_").append(feedbackId);
        }
        imageName.append(".")
                .append(imgTypeString.substring(imgTypeString.lastIndexOf("/") + 1, imgTypeString.length()));
        response.setHeader("Content-disposition", "attachment; filename=" + imageName.toString());
        OutputStream os = response.getOutputStream();
        os.write(imageData, 0, imageData.length);
        response.flushBuffer();
    } catch (java.io.IOException e) {
        throw new FenixActionException(e);
    }
    return null;
}

From source file:edu.mayo.cts2.framework.plugin.service.lexevs.bulk.codesystemversion.controller.CodeSystemVersionBulkDownloadController.java

/**
 * Download.//  ww  w  .j  a v a2 s  .c  o m
 *
 * @param response the response
 * @param codingschemes the codingschemes
 * @param fields the fields
 * @param separator the separator
 * @throws LBException the lB exception
 */
@RequestMapping(value = "/exporter/codingscheme")
public void download(HttpServletResponse response,
        @RequestParam(value = "meddratoken", defaultValue = "") String meddraToken,
        @RequestParam(value = "codingschemes", defaultValue = "") String codingschemes,
        @RequestParam(value = "fields", defaultValue = "") String fields,
        @RequestParam(value = "separator", defaultValue = DEFAULT_SEPARATOR) char separator,
        @RequestParam(value = "filename", defaultValue = DEFAULT_FILE_NAME) String filename)
        throws LBException {

    if (StringUtils.isBlank(codingschemes)) {
        throw new UserInputException("'codingschemes' parameter is required.");
    }

    boolean isValidMeddraToken = false;
    if (StringUtils.isNotBlank(meddraToken)) {
        boolean validates = this.mssoUserValidator.isValid(meddraToken);
        if (!validates) {
            try {
                response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid MedDRA token.");
                return;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            isValidMeddraToken = true;
        }
    }

    List<String> fieldsList;
    if (StringUtils.isBlank(fields)) {
        fieldsList = DEFAULT_FIELDS;
    } else {
        fieldsList = Arrays.asList(StringUtils.split(fields, ','));
    }

    this.setHeaders(response, filename);

    Set<CodingSchemeReference> references = new HashSet<CodingSchemeReference>();

    for (String codingScheme : StringUtils.split(codingschemes, ',')) {
        if (codingScheme.equals(CodeSystemVersionBulkDownloader.ALL_CODINGSCHEMES)) {
            continue;
        }
        String[] parts = StringUtils.split(codingScheme, ':');

        CodingSchemeReference reference = new CodingSchemeReference();
        reference.setCodingScheme(parts[0]);

        if (parts.length == 2) {
            reference.setVersionOrTag(Constructors.createCodingSchemeVersionOrTagFromVersion(parts[1]));
        }

        references.add(reference);
    }

    Set<CodingSchemeReference> exclusions = new HashSet<CodingSchemeReference>();
    exclusions.addAll(this.nciMetaExclusions);
    if (!isValidMeddraToken) {
        exclusions.addAll(this.meddraExclusions);
    }

    try {
        this.codeSystemVersionBulkDownloader.download(response.getOutputStream(), references, exclusions,
                fieldsList, separator);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    try {
        response.flushBuffer();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.nutch.tools.proxy.SegmentHandler.java

@Override
public void handle(Request req, HttpServletResponse res, String target, int dispatch)
        throws IOException, ServletException {
    try {/*from  w  ww .j  a  v  a2 s  . co m*/
        String uri = req.getUri().toString();
        LOG.info("URI: " + uri);
        addMyHeader(res, "URI", uri);
        Text url = new Text(uri.toString());
        CrawlDatum cd = seg.getCrawlDatum(url);
        if (cd != null) {
            addMyHeader(res, "Res", "found");
            LOG.info("-got " + cd.toString());
            ProtocolStatus ps = (ProtocolStatus) cd.getMetaData().get(Nutch.WRITABLE_PROTO_STATUS_KEY);
            if (ps != null) {
                Integer TrCode = protoCodes.get(ps.getCode());
                if (TrCode != null) {
                    res.setStatus(TrCode.intValue());
                } else {
                    res.setStatus(HttpServletResponse.SC_OK);
                }
                addMyHeader(res, "ProtocolStatus", ps.toString());
            } else {
                res.setStatus(HttpServletResponse.SC_OK);
            }
            Content c = seg.getContent(url);
            if (c == null) { // missing content
                req.setHandled(true);
                res.addHeader("X-Handled-By", getClass().getSimpleName());
                return;
            }
            byte[] data = c.getContent();
            LOG.debug("-data len=" + data.length);
            Metadata meta = c.getMetadata();
            String[] names = meta.names();
            LOG.debug("- " + names.length + " meta");
            for (int i = 0; i < names.length; i++) {
                boolean my = true;
                char ch = names[i].charAt(0);
                if (Character.isLetter(ch) && Character.isUpperCase(ch)) {
                    // pretty good chance it's a standard header
                    my = false;
                }
                String[] values = meta.getValues(names[i]);
                for (int k = 0; k < values.length; k++) {
                    if (my) {
                        addMyHeader(res, names[i], values[k]);
                    } else {
                        res.addHeader(names[i], values[k]);
                    }
                }
            }
            req.setHandled(true);
            res.addHeader("X-Handled-By", getClass().getSimpleName());
            res.setContentType(meta.get(Metadata.CONTENT_TYPE));
            res.setContentLength(data.length);
            OutputStream os = res.getOutputStream();
            os.write(data, 0, data.length);
            res.flushBuffer();
        } else {
            addMyHeader(res, "Res", "not found");
            LOG.info(" -not found " + url);
        }
    } catch (Exception e) {
        e.printStackTrace();
        LOG.warn(StringUtils.stringifyException(e));
        addMyHeader(res, "Res", "Exception: " + StringUtils.stringifyException(e));
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.BolonhaManager.ManageCompetenceCourseInformationVersions.java

public ActionForward exportCompetenceCourseExecutionToExcel(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws FenixServiceException {
    final List<CompetenceCourse> competenceCourses = getDepartmentCompetenceCourses();

    try {/* w w  w. j av  a 2  s.  c  o  m*/
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment; filename=list.xls");

        final ServletOutputStream outputStream = response.getOutputStream();

        final Spreadsheet spreadsheet = new Spreadsheet("list");
        spreadsheet.setHeader(BundleUtil.getString(Bundle.BOLONHA, "competenceCourse"));
        spreadsheet.setHeader(BundleUtil.getString(Bundle.BOLONHA, "curricularPlan"));
        spreadsheet.setHeader(BundleUtil.getString(Bundle.BOLONHA, "curricularYear"));
        spreadsheet.setHeader(BundleUtil.getString(Bundle.BOLONHA, "label.semester"));

        for (final CompetenceCourse competenceCourse : competenceCourses) {
            if (competenceCourse.getCurricularStage() == CurricularStage.APPROVED) {
                for (final CurricularCourse curricularCourse : competenceCourse
                        .getAssociatedCurricularCoursesSet()) {
                    for (final ExecutionCourse executionCourse : curricularCourse
                            .getAssociatedExecutionCoursesSet()) {
                        final ExecutionSemester executionSemester = executionCourse.getExecutionPeriod();
                        for (final DegreeModuleScope degreeModuleScope : curricularCourse
                                .getDegreeModuleScopes()) {
                            if (degreeModuleScope.isActiveForExecutionPeriod(executionSemester)) {
                                final DegreeCurricularPlan degreeCurricularPlan = curricularCourse
                                        .getDegreeCurricularPlan();
                                final Row row = spreadsheet.addRow();

                                row.setCell(competenceCourse.getName(executionSemester));
                                row.setCell(degreeCurricularPlan.getName());
                                row.setCell(degreeModuleScope.getCurricularYear());
                                row.setCell(degreeModuleScope.getCurricularSemester());
                            }
                        }
                    }
                }
            }
        }

        spreadsheet.exportToXLSSheet(outputStream);
        outputStream.flush();
        response.flushBuffer();
    } catch (final IOException e) {
        throw new FenixServiceException(e);
    }
    return null;
}

From source file:com.Voxce.Controllers.TrialsController.java

public ModelAndView DownloadDocumentMedical(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    List<ApprovalStatusType> approvalstatustypelist;

    List<Users> userslist;//from w  ww.java2  s  .c  om

    List<Sites> siteslist;

    List<MedicalLicense> medicallist;

    userslist = userdao.listusers(CurrentUser);
    approvalstatustypelist = approvalstatustypedao.listapprovals(currentstudy.getStudy_id());

    siteslist = sitedao.SitesList(CurrentUser);

    MedicalLicense doc = new MedicalLicense();

    int docid = Integer.parseInt(request.getParameter("docid"));
    doc = medicaldao.find(docid);

    response.setContentType(doc.getType());
    response.setContentLength(doc.getData().length);
    response.setHeader("Content-Disposition", "attachment; filename=\"" + doc.getFilename() + "\"");
    FileCopyUtils.copy(doc.getData(), response.getOutputStream());

    medicallist = medicaldao.listmedical(currentstudy.getStudy_id());
    for (int i = 0; i < medicallist.size(); i++)
        medicallist.get(i).setData(null);
    response.flushBuffer();
    ModelMap modelMap = new ModelMap();
    modelMap.addAttribute("currentstudy", currentstudy);
    modelMap.addAttribute("CurrentFormMedical", "View_Medical_License_div");
    modelMap.addAttribute("approvalstatustypelist", approvalstatustypelist);
    modelMap.addAttribute("userslist", userslist);
    modelMap.addAttribute("siteslist", siteslist);
    modelMap.addAttribute("medicallist", medicallist);
    return new ModelAndView("medical_license", modelMap);
}

From source file:com.cloud.bridge.service.controller.s3.S3BucketAction.java

public void executePutBucket(HttpServletRequest request, HttpServletResponse response) throws IOException {
    int contentLength = request.getContentLength();
    Object objectInContent = null;

    if (contentLength > 0) {
        InputStream is = null;//from  w w  w. j  a  v  a  2 s  .  c  om
        try {
            is = request.getInputStream();
            String xml = StringHelper.stringFromStream(is);
            Class.forName("com.cloud.bridge.service.core.s3.S3CreateBucketConfiguration");
            XSerializer serializer = new XSerializer(new XSerializerXmlAdapter());
            objectInContent = serializer.serializeFrom(xml);
            if (objectInContent != null && !(objectInContent instanceof S3CreateBucketConfiguration)) {
                throw new InvalidRequestContentException("Invalid request content in create-bucket: " + xml);
            }
            is.close();

        } catch (IOException e) {
            logger.error("Unable to read request data due to " + e.getMessage(), e);
            throw new NetworkIOException(e);

        } catch (ClassNotFoundException e) {
            logger.error("In a normal world this should never never happen:" + e.getMessage(), e);
            throw new RuntimeException("A required class was not found in the classpath:" + e.getMessage());
        } finally {
            if (is != null)
                is.close();
        }
    }

    S3CreateBucketRequest engineRequest = new S3CreateBucketRequest();
    engineRequest.setBucketName((String) request.getAttribute(S3Constants.BUCKET_ATTR_KEY));
    engineRequest.setConfig((S3CreateBucketConfiguration) objectInContent);
    try {
        S3CreateBucketResponse engineResponse = ServiceProvider.getInstance().getS3Engine()
                .handleRequest(engineRequest);
        response.addHeader("Location", "/" + engineResponse.getBucketName());
        response.setContentLength(0);
        response.setStatus(200);
        response.flushBuffer();
    } catch (ObjectAlreadyExistsException oaee) {
        response.setStatus(409);
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <Error><Code>OperationAborted</Code><Message>A conflicting conditional operation is currently in progress against this resource. Please try again..</Message>";
        response.setContentType("text/xml; charset=UTF-8");
        S3RestServlet.endResponse(response, xml.toString());
    }
}

From source file:com.groupon.odo.Proxy.java

/**
 * @param httpServletResponse//from w w  w .j a  v a2  s.c  o  m
 * @param outStream
 * @param jsonpCallback
 * @throws IOException
 */
private void writeResponseOutput(HttpServletResponse httpServletResponse, OutputStream outStream,
        String jsonpCallback) throws IOException {
    RequestInformation requestInfo = requestInformation.get();

    // check to see if this is chunked
    boolean chunked = false;
    if (httpServletResponse.containsHeader(HttpUtilities.STRING_TRANSFER_ENCODING) && httpServletResponse
            .getHeader(HttpUtilities.STRING_TRANSFER_ENCODING).compareTo("chunked") == 0) {
        httpServletResponse.setHeader(HttpUtilities.STRING_CONNECTION, HttpUtilities.STRING_CHUNKED);
        chunked = true;
    }

    // reattach JSONP if needed
    if (requestInfo.outputString != null && jsonpCallback != null) {
        requestInfo.outputString = jsonpCallback + "(" + requestInfo.outputString + ");";
    }

    // don't do this if we got a HTTP 304 since there is no data to send back
    if (httpServletResponse.getStatus() != HttpServletResponse.SC_NOT_MODIFIED) {
        logger.info("Chunked: {}, {}", chunked, httpServletResponse.getBufferSize());
        if (!chunked) {
            // change the content length header to the new length
            if (requestInfo.outputString != null) {
                httpServletResponse.setContentLength(requestInfo.outputString.getBytes().length);
            } else {
                httpServletResponse.setContentLength(((ByteArrayOutputStream) outStream).toByteArray().length);
            }
        }

        OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();

        if (requestInfo.outputString != null) {
            outputStreamClientResponse.write(requestInfo.outputString.getBytes());
        } else {
            outputStreamClientResponse.write(((ByteArrayOutputStream) outStream).toByteArray());
        }
        httpServletResponse.flushBuffer();

        logger.info("Done writing");
    }

    // outstr might still be null.. let's try to set it from outStream
    if (requestInfo.outputString == null) {
        try {
            requestInfo.outputString = outStream.toString();
        } catch (Exception e) {
            // can ignore any issues.. worst case outstr is still null
        }
    }
}

From source file:org.ned.server.nedadminconsole.server.NedFileUploadServlet.java

private void processUploadNewLanguage(List<?> items, HttpServletResponse resp) throws IOException {
    Iterator<?> iter = items.iterator();
    String languageName = null;/*from w ww.j ava 2 s. c o m*/
    String languageLocale = null;
    String fileName;
    String finalFileName;
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (item.getFieldName().equals("languageName")) {
            languageName = item.getString();
        } else if (item.getFieldName().equals("languageLocale")) {
            languageLocale = item.getString();
        } else if (!item.isFormField()) {
            fileName = item.getName();
            int slashindex = fileName.lastIndexOf('\\');
            if (slashindex > -1) {
                finalFileName = fileName.substring(slashindex + 1, fileName.length());
            } else {
                finalFileName = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
            }

            // FILE PATH CONSISTS OF
            // ROOT - TOMCAT_PATH\webapps\ROOT
            // BASEROOT - Languages
            // FILENAME - GET FROM CHOSEN FILE

            String directory = createLanguageDir();

            File fDir = new File(directory);
            fDir.getAbsolutePath();
            if (!fDir.exists()) {
                fDir.mkdirs();
            }

            finalFileName = createFilePath(directory, finalFileName);
            String uf = directory + finalFileName;
            File uploadedFile = new File(uf);

            // //////////////////////////////////////////////
            InputStream uploadedStream = item.getInputStream();
            FileOutputStream fos = new FileOutputStream(uploadedFile);
            byte[] myarray = new byte[1024];
            int i = 0;
            while ((i = uploadedStream.read(myarray)) != -1) {
                fos.write(myarray, 0, i);
            }
            fos.flush();
            fos.close();
            uploadedStream.close();

            // update database
            try {
                if (languageName != null && languageLocale != null) {
                    getPosgresConnection().uploadNewLanguage(finalFileName, languageName, languageLocale);
                }
            } catch (Exception ex) {
                // TODO delete file
                Logger.getLogger(NedFileUploadServlet.class.getSimpleName()).log(Level.SEVERE,
                        ex.getLocalizedMessage(), ex);
                resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                resp.getWriter().print(NedServerResponses.ERROR_DATABASE_UPDATE);
                resp.flushBuffer();
                disconnectPostgres();
                return;
            }
        }
    }

}