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.kaaproject.kaa.server.admin.controller.KaaAdminController.java

/**
 * Get log record schema with header and log schema inside by record key.
 *
 * @param key// w w  w  .java 2  s.c om
 *            the key
 * @param request
 *            the request
 * @param response
 *            the response
 * @throws KaaAdminServiceException
 *             the kaa admin service exception
 */
@RequestMapping(value = "logRecordSchema", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void getRecordSchema(@RequestBody RecordKey key, HttpServletRequest request,
        HttpServletResponse response) throws KaaAdminServiceException {
    try {
        FileData file = cacheService.getRecordSchema(key);
        response.setContentType("text/plain");
        ServletUtils.prepareDisposition(request, response, file.getFileName());
        response.setContentLength(file.getFileData().length);
        response.setBufferSize(BUFFER);
        response.getOutputStream().write(file.getFileData());
        response.flushBuffer();
    } catch (Exception e) {
        throw Utils.handleException(e);
    }
}

From source file:org.kaaproject.kaa.server.admin.controller.KaaAdminController.java

/**
 * Generate log library by record key.//from w w w.j a  va 2 s  .com
 *
 * @param key
 *            the key
 * @param request
 *            the request
 * @param response
 *            the response
 * @throws KaaAdminServiceException
 *             the kaa admin service exception
 */
@RequestMapping(value = "logLibrary", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void getRecordLibrary(@RequestBody RecordKey key, HttpServletRequest request,
        HttpServletResponse response) throws KaaAdminServiceException {
    try {
        FileData file = cacheService.getRecordLibrary(key);
        response.setContentType("application/java-archive");
        ServletUtils.prepareDisposition(request, response, file.getFileName());
        response.setContentLength(file.getFileData().length);
        response.setBufferSize(BUFFER);
        response.getOutputStream().write(file.getFileData());
        response.flushBuffer();
    } catch (Exception e) {
        throw Utils.handleException(e);
    }
}

From source file:nl.surfnet.spring.security.opensaml.controller.AuthnRequestController.java

@RequestMapping(value = { "/OpenSAML.sso/Metadata" }, method = RequestMethod.GET)
public void metaData(HttpServletResponse response) throws IOException {
    /*//from ww  w  .  j  av  a  2s. com
     * see https://rnd.feide.no/2010/01/05/
     * metadata_aggregation_requirements_specification/#section_5_5_3
     */
    response.setHeader("Content-Type", "application/xml");
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

    String result = IOUtils.toString(new ClassPathResource("metadata-template-sp.xml").getInputStream());

    result = result.replace("%VALID_UNTIL%",
            df.format(new DateTime().toDateMidnight().toDateTime().plusDays(1).toDate()));
    result = result.replace("%ENTITY_ID%", entityID);
    result = result.replace("%ASSERTION_CONSUMER_SERVICE_URL%", assertionConsumerServiceURL);

    Properties props = new Properties();
    props.load(new ClassPathResource("metadata.defaults.properties").getInputStream());

    if (StringUtils.hasText(metaDataProperties)) {
        ClassPathResource classPathResource = new ClassPathResource(metaDataProperties);
        if (classPathResource.exists()) {
            props.load(classPathResource.getInputStream());
        }
    }

    result = result.replace("%NAMEID_FORMAT%", props.getProperty("nameid-format"));

    result = result.replace("%SERVICE_NAME_EN%", props.getProperty("service-name-en"));
    result = result.replace("%SERVICE_NAME_NL%", props.getProperty("service-name-nl"));
    result = result.replace("%SERVICE_DESCRIPTION_EN%", props.getProperty("service-description-en"));
    result = result.replace("%SERVICE_DESCRIPTION_NL%", props.getProperty("service-description-nl"));

    result = result.replace("%CONTACT_PERSON_ADMINISTRATIVE_GIVEN_NAME%",
            props.getProperty("contact-person-administrative-given-name"));
    result = result.replace("%CONTACT_PERSON_ADMINISTRATIVE_SUR_NAME%",
            props.getProperty("contact-person-administrative-sur-name"));
    result = result.replace("%CONTACT_PERSON_ADMINISTRATIVE_EMAIL%",
            props.getProperty("contact-person-administrative-email"));

    result = result.replace("%CONTACT_PERSON_TECHNICAL_GIVEN_NAME%",
            props.getProperty("contact-person-technical-given-name"));
    result = result.replace("%CONTACT_PERSON_TECHNICAL_SUR_NAME%",
            props.getProperty("contact-person-technical-sur-name"));
    result = result.replace("%CONTACT_PERSON_TECHNICAL_EMAIL%",
            props.getProperty("contact-person-technical-email"));

    result = result.replace("%CONTACT_PERSON_SUPPORT_GIVEN_NAME%",
            props.getProperty("contact-person-support-given-name"));
    result = result.replace("%CONTACT_PERSON_SUPPORT_SUR_NAME%",
            props.getProperty("contact-person-support-sur-name"));
    result = result.replace("%CONTACT_PERSON_SUPPORT_EMAIL%",
            props.getProperty("contact-person-support-email"));

    response.getOutputStream().write(result.getBytes());
    response.flushBuffer();

}

From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java

public void test_ErrorPage10() throws Exception {
    Servlet servlet = new HttpServlet() {
        private static final long serialVersionUID = 1L;

        @Override//ww w  .  j a va 2  s. c om
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {

            resp.getWriter().write("some output");
            resp.flushBuffer();

            throw new IOException();
        }
    };

    Dictionary<String, Object> props = new Hashtable<String, Object>();
    props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_NAME, "E10");
    props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, "/TestErrorPage10/*");
    registrations.add(getBundleContext().registerService(Servlet.class, servlet, props));

    try {
        requestAdvisor.request("TestErrorPage10/a");
    } catch (Exception e) {
        Assert.assertTrue(e instanceof IOException);

        return;
    }

    Assert.fail("Expecting java.io.IOException: Premature EOF");
}

From source file:org.kaaproject.kaa.server.admin.controller.KaaAdminController.java

/**
 * Exports a CTL schema and, depending on the export method specified, all
 * of its dependencies.//from  w  w w . j a v a  2  s  .  c o  m
 * 
 * @param fqn
 *            - the schema fqn
 * @param version
 *            - the schema version
 * @param method
 *            - the schema export method
 * @param applicationId
 *            id of the application
 * @param request
 *            - the http request
 * @param response
 *            - the http response
 * 
 * @see CTLSchemaExportMethod
 * 
 * @throws KaaAdminServiceException
 *             the kaa admin service exception
 * @deprecated  As of release 0.9.0, replaced by {@link #exportCTLSchemaByAppToken(String, int, String, String, HttpServletRequest, HttpServletResponse)}
 */
@Deprecated
@RequestMapping(value = "CTL/exportSchema", params = { "fqn", "version",
        "method" }, method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void exportCTLSchema(@RequestParam String fqn, @RequestParam int version, @RequestParam String method,
        @RequestParam(required = false) String applicationId, HttpServletRequest request,
        HttpServletResponse response) throws KaaAdminServiceException {
    try {
        FileData output = kaaAdminService.exportCTLSchema(fqn, version, applicationId,
                CTLSchemaExportMethod.valueOf(method.toUpperCase()));
        ServletUtils.prepareDisposition(request, response, output.getFileName());
        response.setContentType(output.getContentType());
        response.setContentLength(output.getFileData().length);
        response.setBufferSize(BUFFER);
        response.getOutputStream().write(output.getFileData());
        response.flushBuffer();
    } catch (Exception cause) {
        throw Utils.handleException(cause);
    }
}

From source file:org.openmrs.module.pharmacy.web.controller.DrugDispenseStore.java

@RequestMapping(method = RequestMethod.GET, value = "module/pharmacy/drugDispenseStore")
public synchronized void pageLoad(HttpServletRequest request, HttpServletResponse response) {
    String locationVal = null;// w ww .  j av  a 2 s .c o m

    service = Context.getService(PharmacyService.class);
    pharmacyLocationUsersByUserName = service
            .getPharmacyLocationUsersByUserName(Context.getAuthenticatedUser().getUsername());
    size1 = pharmacyLocationUsersByUserName.size();

    if (size1 > 1) {
        locationVal = request.getSession().getAttribute("location").toString();

    } else if (size1 == 1) {
        locationVal = pharmacyLocationUsersByUserName.get(0).getLocation();

    }
    userService = Context.getUserContext();
    dialogShow = request.getParameter("drugID");
    dialog = request.getParameter("uuid");

    serviceLocation = Context.getLocationService();
    datadFrm = new JSONArray();

    drugDispenseSettings = service.getDrugDispenseSettings();

    size = drugDispenseSettings.size();
    currentDate = Calendar.getInstance();
    readDate = Calendar.getInstance();

    dateC = new Date();

    currentDate.setTime(dateC);

    one = new GregorianCalendar();
    two = new GregorianCalendar();

    one.set(currentDate.get(currentDate.YEAR), currentDate.get(currentDate.MONTH),
            currentDate.get(currentDate.DAY_OF_MONTH));

    try {

        if (dialog != null) {
            json = new JSONObject();
            pharmacyStoreList = service.getPharmacyInventory();
            size2 = pharmacyStoreList.size();

            for (int i = 0; i < size2; i++) {
                if (service.getPharmacyLocationsByUuid(pharmacyStoreList.get(i).getLocation()).getName()
                        .equalsIgnoreCase(locationVal)) {

                    datadFrm = new JSONArray();

                    datadFrm = getArray(pharmacyStoreList, i, dialog, locationVal);
                    if (datadFrm != null)
                        json.accumulate("aaData", datadFrm);
                }

            }

            if (!json.has("aaData")) {
                datad2 = new JSONArray();

                datad2.put("None");
                datad2.put("None");
                datad2.put("None");

                datad2.put("None");
                datad2.put("None");
                datad2.put("None");

                json.accumulate("aaData", datad2);
            }
            dialog = null;
        }

        json.accumulate("iTotalRecords", json.getJSONArray("aaData").length());
        json.accumulate("iTotalDisplayRecords", json.getJSONArray("aaData").length());
        json.accumulate("iDisplayStart", 0);
        json.accumulate("iDisplayLength", 10);

        response.getWriter().print(json);

        response.flushBuffer();

    } catch (Exception e) {
        // TODO Auto-generated catch block
        log.error("Error generated", e);
    }

}

From source file:org.kaaproject.kaa.server.admin.controller.KaaAdminController.java

/**
 * Exports a CTL schema and, depending on the export method specified, all
 * of its dependencies.//from   w  w w .  ja  va 2s  .  co m
 *
 * @param fqn
 *            - the schema fqn
 * @param version
 *            - the schema version
 * @param method
 *            - the schema export method
 * @param applicationToken
 *            the application token
 * @param request
 *            - the http request
 * @param response
 *            - the http response
 *
 * @see CTLSchemaExportMethod
 *
 * @throws KaaAdminServiceException
 *             the kaa admin service exception
 */
@RequestMapping(value = "CTL/appToken/exportSchema", params = { "fqn", "version",
        "method" }, method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void exportCTLSchemaByAppToken(@RequestParam String fqn, @RequestParam int version,
        @RequestParam String method, @RequestParam(required = false) String applicationToken,
        HttpServletRequest request, HttpServletResponse response) throws KaaAdminServiceException {
    try {
        FileData output = kaaAdminService.exportCTLSchemaByAppToken(fqn, version, applicationToken,
                CTLSchemaExportMethod.valueOf(method.toUpperCase()));
        ServletUtils.prepareDisposition(request, response, output.getFileName());
        response.setContentType(output.getContentType());
        response.setContentLength(output.getFileData().length);
        response.setBufferSize(BUFFER);
        response.getOutputStream().write(output.getFileData());
        response.flushBuffer();
    } catch (Exception cause) {
        throw Utils.handleException(cause);
    }
}

From source file:org.kaaproject.kaa.server.admin.controller.KaaAdminController.java

/**
 * Generates an SDK for the specified target platform from an SDK profile .
 *
 * @param sdkProfileId/*from   w w w  .  j a  v a2s .c om*/
 *            the sdk profile id
 * @param targetPlatform
 *            the target platform
 * @param request
 *            the request
 * @param response
 *            the response
 * @throws KaaAdminServiceException
 *             the kaa admin service exception
 */
@RequestMapping(value = "sdk", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void getSdk(@RequestParam(value = "sdkProfileId") String sdkProfileId,
        @RequestParam(value = "targetPlatform") String targetPlatform, HttpServletRequest request,
        HttpServletResponse response) throws KaaAdminServiceException {
    try {
        SdkProfileDto sdkProfile = kaaAdminService.getSdkProfile(sdkProfileId);
        FileData sdkData = kaaAdminService.getSdk(sdkProfile,
                SdkPlatform.valueOf(targetPlatform.toUpperCase()));
        response.setContentType(sdkData.getContentType());
        ServletUtils.prepareDisposition(request, response, sdkData.getFileName());
        response.setContentLength(sdkData.getFileData().length);
        response.setBufferSize(BUFFER);
        response.getOutputStream().write(sdkData.getFileData());
        response.flushBuffer();
    } catch (Exception e) {
        throw Utils.handleException(e);
    }
}

From source file:org.apache.cocoon.servlet.CocoonServlet.java

protected void manageException(HttpServletRequest req, HttpServletResponse res, Environment env, String uri,
        int errorStatus, String title, String message, String description, Exception e) throws IOException {
    if (this.manageExceptions) {
        if (env != null) {
            env.tryResetResponse();//from w w w  . j av a  2 s . co  m
        } else {
            res.reset();
        }

        String type = Notifying.FATAL_NOTIFICATION;
        HashMap extraDescriptions = null;

        if (errorStatus == HttpServletResponse.SC_NOT_FOUND) {
            type = "resource-not-found";
            // Do not show the exception stacktrace for such common errors.
            e = null;
        } else {
            extraDescriptions = new HashMap(2);
            extraDescriptions.put(Notifying.EXTRA_REQUESTURI, req.getRequestURI());
            if (uri != null) {
                extraDescriptions.put("Request URI", uri);
            }

            // Do not show exception stack trace when log level is WARN or above. Show only message.
            if (!getLogger().isInfoEnabled()) {
                Throwable t = DefaultNotifyingBuilder.getRootCause(e);
                if (t != null)
                    extraDescriptions.put(Notifying.EXTRA_CAUSE, t.getMessage());
                e = null;
            }
        }

        Notifying n = new DefaultNotifyingBuilder().build(this, e, type, title, "Cocoon Servlet", message,
                description, extraDescriptions);

        res.setContentType("text/html");
        res.setStatus(errorStatus);
        Notifier.notify(n, res.getOutputStream(), "text/html");
    } else {
        res.sendError(errorStatus, title);
        res.flushBuffer();
    }
}

From source file:org.ngrinder.script.controller.DavSvnController.java

/**
 * Request Handler./*from   w  ww .  ja v  a2s  .  c o m*/
 * 
 * @param request
 *            request
 * @param response
 *            response
 * @throws ServletException
 *             occurs when servlet has a problem.
 * @throws IOException
 *             occurs when file system has a problem.
 */
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (LOGGER.isTraceEnabled()) {
        logRequest(request);
    }
    try {
        final String head = DAVPathUtil.head(request.getPathInfo());
        final User currentUser = userContext.getCurrentUser();
        // check the security. If the other user tries to the other user's
        // repo, deny it.
        if (!StringUtils.equals(currentUser.getUserId(), head)) {
            SecurityContextHolder.getContext().setAuthentication(null);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                    head + " is not accessible by " + currentUser.getUserId());
            return;
        }
        // To make it understand Asian Language..
        request = new MyHttpServletRequestWrapper(request);
        DAVRepositoryManager repositoryManager = new DAVRepositoryManager(getDAVConfig(), request);
        ServletDAVHandler handler = DAVHandlerExFactory.createHandler(repositoryManager, request, response);
        handler.execute();
    } catch (DAVException de) {
        response.setContentType(XML_CONTENT_TYPE);
        handleError(de, response);
    } catch (SVNException svne) {
        StringWriter sw = new StringWriter();
        svne.printStackTrace(new PrintWriter(sw));

        /**
         * truncate status line if it is to long
         */
        String msg = sw.getBuffer().toString();
        if (msg.length() > 128) {
            msg = msg.substring(0, 128);
        }
        SVNErrorCode errorCode = svne.getErrorMessage().getErrorCode();
        if (errorCode == SVNErrorCode.FS_NOT_DIRECTORY || errorCode == SVNErrorCode.FS_NOT_FOUND
                || errorCode == SVNErrorCode.RA_DAV_PATH_NOT_FOUND) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
        } else if (errorCode == SVNErrorCode.NO_AUTH_FILE_PATH) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, msg);
        } else if (errorCode == SVNErrorCode.RA_NOT_AUTHORIZED) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, msg);
        } else {
            String errorBody = generateStandardizedErrorBody(errorCode.getCode(), null, null,
                    svne.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentType(XML_CONTENT_TYPE);
            response.getWriter().print(errorBody);
        }
    } catch (Throwable th) {
        StringWriter sw = new StringWriter();
        th.printStackTrace(new PrintWriter(sw));
        String msg = sw.getBuffer().toString();
        LOGGER.debug("Error in DavSVN Controller", th);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
    } finally {
        response.flushBuffer();
    }
}