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:info.magnolia.imaging.ImagingServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final String generatorName = getImageGeneratorName(request);
    final ImageGenerator generator = getGenerator(generatorName);
    if (generator == null) {
        throw new IllegalArgumentException("No ImageGenerator with name " + generatorName);
    }/*from w  w w.  j  a va 2 s . com*/

    final ParameterProviderFactory parameterProviderFactory = generator.getParameterProviderFactory();
    final ParameterProvider p = parameterProviderFactory.newParameterProviderFor(request);

    if (validateFileExtension) {
        String outputFormat = generator.getOutputFormat(p).getFormatName();
        String requestedPath = StringUtils.substringAfterLast(request.getPathInfo(), "/"); // don't take part of node name as extension, we support dots in node names!
        String requestedFormat = StringUtils.substringAfterLast(requestedPath, ".");
        if (!StringUtils.equals(outputFormat, requestedFormat)) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
    }

    try {
        // TODO -- mimetype etc.
        final ImageStreamer streamer = getStreamer(parameterProviderFactory);
        streamer.serveImage(generator, p, response.getOutputStream());

        response.flushBuffer();
        // IOUtils.closeQuietly(response.getOutputStream());
    } catch (ImagingException e) {
        throw new ServletException(e); // TODO
    }
}

From source file:net.siegmar.japtproxy.JaptProxyServlet.java

/**
 * Check the requested data and forward the request to internal sender.
 *
 * @param req the HttpServletRequest object
 * @param res the HttpServletResponse object
 * @throws ServletException {@inheritDoc}
 * @throws IOException      {@inheritDoc}
 *//* w w  w. j  a  v a2  s.c o  m*/
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse res)
        throws ServletException, IOException {
    res.setBufferSize(Util.DEFAULT_BUFFER_SIZE);

    MDC.put("REQUEST_ID", DigestUtils.md5Hex(Long.toString(System.currentTimeMillis())));

    LOG.debug("Incoming request from IP '{}', " + "User-Agent '{}'", req.getRemoteAddr(),
            req.getHeader(HttpHeaderConstants.USER_AGENT));

    if (LOG.isDebugEnabled()) {
        logHeader(req);
    }

    try {
        japtProxy.handleRequest(req, res);
    } catch (final InvalidRequestException e) {
        LOG.warn(e.getMessage());
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid request");
        return;
    } catch (final UnknownBackendException e) {
        LOG.info(e.getMessage());
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unknown backend");
        return;
    } catch (final ResourceUnavailableException e) {
        LOG.debug(e.getMessage(), e);
        res.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    } catch (final HandlingException e) {
        LOG.error("HandlingException", e);
        res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    } finally {
        MDC.clear();
    }

    res.flushBuffer();
}

From source file:org.surfnet.oaaas.auth.AuthorizationServerFilter.java

protected boolean handledCorsPreflightRequest(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    if (!this.allowCorsRequests || StringUtils.isBlank(request.getHeader("Origin"))) {
        return false;
    }//  ww  w  . j  ava2  s  . com
    /*
     * We must do this anyway, this being (probably) a CORS request
     */
    response.setHeader("Access-Control-Allow-Origin", "*");
    if (StringUtils.isNotBlank(request.getHeader("Access-Control-Request-Method"))
            && request.getMethod().equalsIgnoreCase("OPTIONS")) {
        /*
         * We don't want to propogate the request any further
         */
        response.setHeader("Access-Control-Allow-Methods", getAccessControlAllowedMethods());
        String requestHeaders = request.getHeader("Access-Control-Request-Headers");
        if (StringUtils.isNotBlank(requestHeaders)) {
            response.setHeader("Access-Control-Allow-Headers", getAllowedHeaders(requestHeaders));
        }
        response.setHeader("Access-Control-Max-Age", getAccessControlMaxAge());
        response.setStatus(HttpServletResponse.SC_OK);
        response.flushBuffer();
        return true;
    }
    return false;
}

From source file:cz.zcu.kiv.eegdatabase.logic.controller.scenario.ScenarioXMLDownloadController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    //   ModelAndView mav = new ModelAndView("scenarioXMLDownloadView");
    // There should always be set integer value in this field - it is generated by view, not by user
    log.debug("Processing download scenario.");
    int scenarioId = Integer.parseInt(request.getParameter("scenarioId"));
    Scenario scenario = scenarioDao.read(scenarioId);
    //TODO set Blob or XMLType
    //Document xmlType = (Document) scenario.getScenarioType().getScenarioXml();
    //Blob c = (Blob) scenario.getScenarioType().getScenarioXml();

    Person user = personDao.getPerson(ControllerUtils.getLoggedUserName());
    Timestamp currentTimestamp = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime());
    History history = new History();
    log.debug("Setting downloading scenario");
    history.setScenario(scenario);// w  ww. j  ava  2 s .c o m
    log.debug("Setting user");
    history.setPerson(user);
    log.debug("Setting time of download");
    history.setDateOfDownload(currentTimestamp);
    log.debug("Saving download history");
    historyDao.create(history);
    response.setHeader("Content-Type", scenario.getMimetype());
    response.setHeader("Content-Disposition", "attachment;filename=" + scenario.getScenarioName());
    response.flushBuffer();
    // mav.addObject("dataObject", scenarioDao.read(scenarioId));

    return null;
}

From source file:com.autoupdater.server.controllers.FrontEndAPIController.java

/**
 * Send file to client.//from   w w w . ja  v  a 2  s . c  o  m
 * 
 * Runs on GET /server/api/download/{updateID} request.
 * 
 * @param updateID
 *            update's ID
 * @param response
 *            response to be sent
 * @param request
 *            received by servlet
 */
@SuppressWarnings("resource")
@RequestMapping(value = "/download/{updateID}", method = GET)
public @ResponseBody void getFile(@PathVariable("updateID") int updateID, HttpServletResponse response,
        HttpServletRequest request) {
    InputStream is = null;
    try {
        logger.debug("Received request: GET /api/download/" + updateID);

        Update update = updateService.findById(updateID);
        if (update == null) {
            logger.debug("Response 404, Update not found for: GET /api/list_updates/" + updateID);
            sendError(response, SC_NOT_FOUND, "Update id=" + updateID + " not found");
            return;
        }

        is = fileService.loadFile(update.getFileData());

        String range = request.getHeader("Range");
        long skip = 0;
        if (range != null) {
            logger.debug("Values of range header : " + range);
            range = range.substring("bytes=".length());
            skip = parseLong(range);

            is.skip(skip);
        }
        response.setContentType(update.getFileType());
        response.setContentLength((int) (update.getFileSize() - skip));

        logger.debug("Sending file on request: GET /api/download/" + updateID);
        copy(is, response.getOutputStream());
        response.flushBuffer();
    } catch (NumberFormatException | IOException e) {
        logger.error("Error sending file updateID=" + updateID + ": " + e);
        sendError(response, SC_INTERNAL_SERVER_ERROR, "Couldn't prepare file to send");
    } finally {
        if (is != null)
            try {
                is.close();
            } catch (IOException e) {
                logger.debug(e);
            }
    }
}

From source file:gov.redhawk.rap.internal.PluginProviderServlet.java

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    final Path path = new Path(req.getRequestURI());
    String pluginId = path.lastSegment();
    if (pluginId.endsWith(".jar")) {
        pluginId = pluginId.substring(0, pluginId.length() - 4);
    }//  w w  w .j av a  2s.  com
    final Bundle b = Platform.getBundle(pluginId);
    if (b == null) {
        final String protocol = req.getProtocol();
        final String msg = "Plugin does not exist: " + pluginId;
        if (protocol.endsWith("1.1")) {
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
        } else {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        }
        return;
    }
    final File file = FileLocator.getBundleFile(b);
    resp.setContentType("application/octet-stream");

    if (file.isFile()) {
        final String contentDisposition = "attachment; filename=\"" + file.getName() + "\"";
        resp.setHeader("Content-Disposition", contentDisposition);
        resp.setContentLength((int) file.length());
        final FileInputStream istream = new FileInputStream(file);
        try {
            IOUtils.copy(istream, resp.getOutputStream());
        } finally {
            istream.close();
        }
        resp.flushBuffer();
    } else {
        final String contentDisposition = "attachment; filename=\"" + file.getName() + ".jar\"";
        resp.setHeader("Content-Disposition", contentDisposition);
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        final Manifest man = new Manifest(new FileInputStream(new File(file, "META-INF/MANIFEST.MF")));
        final JarOutputStream out = new JarOutputStream(outputStream, man);
        final File binDir = new File(file, "bin");

        if (binDir.exists()) {
            addFiles(out, Path.ROOT, binDir.listFiles());
            for (final File f : file.listFiles()) {
                if (!f.getName().equals("bin")) {
                    addFiles(out, Path.ROOT, f);
                }
            }
        } else {
            addFiles(out, Path.ROOT, file.listFiles());
        }
        out.close();
        outputStream.close();
        final ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        resp.setContentLength(outputStream.size());
        try {
            IOUtils.copy(inputStream, resp.getOutputStream());
        } finally {
            inputStream.close();
        }
        resp.flushBuffer();
    }

}

From source file:it.geosolutions.geofence.gui.server.UploadServlet.java

@SuppressWarnings("unchecked")
@Override//from w w  w.  j  av a  2s .  c o  m
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {

        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        File uploadedFile = null;
        // Parse the request
        try {
            List<FileItem> items = upload.parseRequest(req);

            for (FileItem item : items) {
                // process only file upload - discard other form item types
                if (item.isFormField()) {
                    continue;
                }

                String fileName = item.getName();
                // get only the file name not whole path
                if (fileName != null) {
                    fileName = FilenameUtils.getName(fileName);
                }

                uploadedFile = File.createTempFile(fileName, "");
                // if (uploadedFile.createNewFile()) {
                item.write(uploadedFile);
                resp.setStatus(HttpServletResponse.SC_CREATED);
                resp.flushBuffer();

                // uploadedFile.delete();
                // } else
                // throw new IOException(
                // "The file already exists in repository.");
            }
        } catch (Exception e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while creating the file : " + e.getMessage());
        }

        try {
            String wkt = calculateWKT(uploadedFile);
            resp.getWriter().print(wkt);
        } catch (Exception exc) {
            resp.getWriter().print("Error : " + exc.getMessage());
            logger.error("ERROR ********** " + exc);
        }

        uploadedFile.delete();

    } else {
        resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}

From source file:org.commoncrawl.service.listcrawler.ProxyServlet2.java

public void handleConnect(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String uri = request.getRequestURI();

    context.log("CONNECT: " + uri);

    // InetAddrPort addrPort=new InetAddrPort(uri);
    URL url = new URL(uri);

    InetAddress address = InetAddress.getByName(url.getHost());
    int port = (url.getPort() != -1) ? url.getPort() : 80;

    //if (isForbidden(HttpMessage.__SSL_SCHEME,addrPort.getHost(),addrPort.getPort(),false))
    //{//from  ww  w . java 2 s.c o  m
    //    sendForbid(request,response,uri);
    //}
    //else
    {
        InputStream in = request.getInputStream();
        OutputStream out = response.getOutputStream();

        Socket socket = new Socket(address, port);
        context.log("Socket: " + socket);

        response.setStatus(200);
        response.setHeader("Connection", "close");
        response.flushBuffer();

        System.err.println(response);

        context.log("out<-in");
        IO.copyThread(socket.getInputStream(), out);
        context.log("in->out");
        IO.copy(in, socket.getOutputStream());
    }
}

From source file:com.groupon.odo.controllers.ServerMappingController.java

/**
 * Returns a X509 binary certificate for a given domain name if a certificate has been generated for it
 *
 * @param locale//w  w w  .ja v a2 s.c om
 * @param model
 * @param response
 * @param hostname
 * @throws Exception
 */
@RequestMapping(value = "/cert/{hostname:.+}", method = { RequestMethod.GET, RequestMethod.HEAD })
public @ResponseBody void getCert(Locale locale, Model model, HttpServletResponse response,
        @PathVariable String hostname) throws Exception {
    // Set the appropriate headers so the browser thinks this is a file
    response.reset();
    response.setContentType("application/x-x509-ca-cert");
    response.setHeader("Content-Disposition", "attachment;filename=" + hostname + ".cer");

    // special handling for hostname=="root"
    // return the CyberVillians Root Cert in this case
    if (hostname.equals("root")) {
        hostname = "cybervillainsCA";
        response.setContentType("application/pkix-cert ");
    }

    // get the cert for the hostname
    KeyStoreManager keyStoreManager = com.groupon.odo.bmp.Utils.getKeyStoreManager(hostname);

    if (hostname.equals("cybervillainsCA")) {
        // get the cybervillians cert from resources
        File root = new File("seleniumSslSupport" + File.separator + hostname);

        // return the root cert
        Files.copy(new File(root.getAbsolutePath() + File.separator + hostname + ".cer").toPath(),
                response.getOutputStream());
        response.flushBuffer();
    } else {
        // return the cert for the appropriate alias
        response.getOutputStream().write(keyStoreManager.getCertificateByAlias(hostname).getEncoded());
        response.flushBuffer();
    }

}

From source file:architecture.ee.web.spring.controller.DownloadController.java

@RequestMapping(value = "/image/{fileName}", method = RequestMethod.GET)
@ResponseBody/*from w  w  w  .ja v a  2 s .c om*/
public void handleImageByLink(@PathVariable("fileName") String fileName,
        @RequestParam(value = "width", defaultValue = "0", required = false) Integer width,
        @RequestParam(value = "height", defaultValue = "0", required = false) Integer height,
        HttpServletResponse response) throws IOException {

    log.debug(" ------------------------------------------");
    log.debug("fileName:" + fileName);
    log.debug("width:" + width);
    log.debug("height:" + height);
    log.debug("------------------------------------------");

    try {
        Image image = imageManager.getImageByImageLink(fileName);

        InputStream input;
        String contentType;
        int contentLength;

        if (width > 0 && width > 0) {
            input = imageManager.getImageThumbnailInputStream(image, width, height);
            contentType = image.getThumbnailContentType();
            contentLength = image.getThumbnailSize();
        } else {
            input = imageManager.getImageInputStream(image);
            contentType = image.getContentType();
            contentLength = image.getSize();

        }

        response.setContentType(contentType);
        response.setContentLength(contentLength);
        IOUtils.copy(input, response.getOutputStream());
        response.flushBuffer();

    } catch (NotFoundException e) {
        response.sendError(404);
    }
}