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:com.mmj.app.web.controller.user.UserController.java

@RequestMapping(value = "/gozapIdentifyCode")
public ModelAndView gozapIdentifyCode(String t, HttpServletRequest request, HttpServletResponse response) {

    response.setContentType("image/png; charset=utf-8");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control",
            "private, must-revalidate,no-store, no-cache, must-revalidate,post-check=0, pre-check=0");
    response.addHeader("Content-Disposition", "attachment; filename=\"" + "gozapIdentifyCode" + "\"");
    response.setCharacterEncoding("UTF-8");

    final byte[] bytes = WebsiteCheckCodeManager.INSTANCE.create(CookieManagerLocator.get(request, response),
            response);//from  w ww .ja  v  a  2s  .c  o  m

    OutputStream os;
    try {
        os = response.getOutputStream();
        IOUtils.write(bytes, os);
        response.flushBuffer();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.dataconservancy.dcs.access.server.BagUploadServlet.java

public void getSIPfile(String bagitEp, String filename, HttpServletResponse resp)
        throws IOException, InvalidXmlException {
    Client client = Client.create();/*from  ww w  .j  ava 2  s .  co m*/
    System.out.println(bagitEp);
    WebResource webResource = client.resource(bagitEp);

    File file = new File(filename);
    FileDataBodyPart fdp = new FileDataBodyPart("file", file, MediaType.APPLICATION_OCTET_STREAM_TYPE);

    FormDataMultiPart formDataMultiPart = new FormDataMultiPart();

    formDataMultiPart.bodyPart(fdp);

    ClientResponse response = webResource.path("sip").type(MediaType.MULTIPART_FORM_DATA)
            .post(ClientResponse.class, formDataMultiPart);

    if (response.getStatus() == 500) {
        StringWriter writer = new StringWriter();
        IOUtils.copy(response.getEntityInputStream(), writer);
        resp.getWriter().write(writer.toString());
        resp.setStatus(500);
        resp.flushBuffer();
        return;
    }
    String sipPath = System.getProperty("java.io.tmpdir") + "/" + UUID.randomUUID().toString() + "_sip_0.xml";// significance of 0 is limiting

    IOUtils.copy(response.getEntityInputStream(), new FileOutputStream(sipPath));
    ResearchObject sip = new SeadXstreamStaxModelBuilder().buildSip(new FileInputStream(sipPath));

    StringWriter tempWriter = new StringWriter();
    siptoJsonConverter().toXML(toQueryResult(sip), tempWriter);
    tempWriter.append(";" + sipPath);
    resp.getWriter().write(tempWriter.toString());
    //  resp.setHeader("localSipPath", sipPath);
    resp.setStatus(200);
    resp.setContentType("application/json");
    resp.flushBuffer();
}

From source file:com.almende.eve.transport.http.AgentServlet.java

/**
 * Send a JSON-RPC message to an agent Usage: POST /servlet/{agentId} With a
 * JSON-RPC request as body. Response will be a JSON-RPC response.
 * /*from w  ww.  java  2 s  .  c  om*/
 * @param req
 *            the req
 * @param resp
 *            the resp
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws ServletException
 *             the servlet exception
 */
@Override
public void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws IOException, ServletException {

    // retrieve the agent url and the request body
    final String body = StringUtil.streamToString(req.getInputStream());

    final String agentUrl = req.getRequestURI();
    String agentId;
    try {
        agentId = httpTransport.getAgentId(new URI(agentUrl));
    } catch (URISyntaxException e) {
        throw new ServletException(AGENTURLWARNING, e);
    }
    if (agentId == null || agentId.equals("")) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "No agentId found in url.");
        resp.flushBuffer();
        return;
    }

    if (host.hasPrivate(agentId) && !handleSession(req, resp)) {
        if (!resp.isCommitted()) {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
        resp.flushBuffer();
        return;
    }

    // Attach the claimed senderId, or null if not given.
    String senderUrl = req.getHeader("X-Eve-SenderUrl");
    if (senderUrl == null || senderUrl.equals("")) {
        senderUrl = "web://" + req.getRemoteUser() + "@" + req.getRemoteAddr();
    }
    final String tag = new UUID().toString();

    final SyncCallback<String> callback = new SyncCallback<String>();

    final AsyncCallbackQueue<String> callbacks = host.getCallbackQueue("HttpTransport", String.class);
    callbacks.push(tag, "", callback);
    //TODO: check if it's base64 encoded data, decode to byte[] and call receive byte[].
    host.receive(agentId, body, URI.create(senderUrl), tag);

    try {
        final Object message = callback.get();
        // return response
        resp.addHeader("Content-Type", "application/json");
        resp.getWriter().println(message.toString());
        resp.getWriter().close();
    } catch (final Exception e) {
        LOG.log(Level.WARNING, "Http Sync receive raised exception.", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Receiver raised exception:" + e.getMessage());
    }
    resp.flushBuffer();
}

From source file:org.fenixedu.academic.ui.struts.action.internationalRelatOffice.candidacy.erasmus.ErasmusIndividualCandidacyProcessDA.java

public ActionForward retrieveLearningAgreement(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    MobilityIndividualApplicationProcess process = getProcess(request);

    final LearningAgreementDocument document = new LearningAgreementDocument(process);
    byte[] data = ReportsUtils.generateReport(document).getData();

    response.setContentLength(data.length);
    response.setContentType("application/pdf");
    response.addHeader("Content-Disposition", "attachment; filename=" + document.getReportFileName() + ".pdf");

    final ServletOutputStream writer = response.getOutputStream();
    writer.write(data);//ww  w  .j  av a2s  .c om
    writer.flush();
    writer.close();

    response.flushBuffer();
    return mapping.findForward("");
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.internationalRelatOffice.candidacy.erasmus.ErasmusIndividualCandidacyProcessDA.java

public ActionForward retrieveLearningAgreement(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    MobilityIndividualApplicationProcess process = getProcess(request);

    final LearningAgreementDocument document = new LearningAgreementDocument(process);
    byte[] data = ReportsUtils.exportMultipleToPdfAsByteArray(document);

    response.setContentLength(data.length);
    response.setContentType("application/pdf");
    response.addHeader("Content-Disposition", "attachment; filename=" + document.getReportFileName() + ".pdf");

    final ServletOutputStream writer = response.getOutputStream();
    writer.write(data);/*from  w w w.  j av a  2 s. c o m*/
    writer.flush();
    writer.close();

    response.flushBuffer();
    return mapping.findForward("");
}

From source file:org.epics.archiverappliance.utils.ui.GetUrlContent.java

/**
 * Get the contents of a redirect URL and use as reponse for the provided HttpServletResponse.
 * If possible, pass in error responses as well.
 * @param redirectURIStr  &emsp;  /*from ww  w  .j a va2  s  .c  om*/
 * @param resp  HttpServletResponse 
 * @throws IOException  &emsp; 
 */
public static void proxyURL(String redirectURIStr, HttpServletResponse resp) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet getMethod = new HttpGet(redirectURIStr);
    getMethod.addHeader("Connection", "close"); // https://www.nuxeo.com/blog/using-httpclient-properly-avoid-closewait-tcp-connections/
    try (CloseableHttpResponse response = httpclient.execute(getMethod)) {
        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();

            HashSet<String> proxiedHeaders = new HashSet<String>();
            proxiedHeaders.addAll(Arrays.asList(MimeResponse.PROXIED_HEADERS));
            Header[] headers = response.getAllHeaders();
            for (Header header : headers) {
                if (proxiedHeaders.contains(header.getName())) {
                    logger.debug("Adding headerName " + header.getName() + " and value " + header.getValue()
                            + " when proxying request");
                    resp.addHeader(header.getName(), header.getValue());
                }
            }

            if (entity != null) {
                logger.debug("Obtained a HTTP entity of length " + entity.getContentLength());
                try (OutputStream os = resp.getOutputStream();
                        InputStream is = new BufferedInputStream(entity.getContent())) {
                    byte buf[] = new byte[10 * 1024];
                    int bytesRead = is.read(buf);
                    while (bytesRead > 0) {
                        os.write(buf, 0, bytesRead);
                        resp.flushBuffer();
                        bytesRead = is.read(buf);
                    }
                }
            } else {
                throw new IOException("HTTP response did not have an entity associated with it");
            }
        } else {
            logger.error("Invalid status code " + response.getStatusLine().getStatusCode()
                    + " when connecting to URL " + redirectURIStr + ". Sending the errorstream across");
            try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
                try (InputStream is = new BufferedInputStream(response.getEntity().getContent())) {
                    byte buf[] = new byte[10 * 1024];
                    int bytesRead = is.read(buf);
                    while (bytesRead > 0) {
                        os.write(buf, 0, bytesRead);
                        bytesRead = is.read(buf);
                    }
                }
                resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
                resp.sendError(response.getStatusLine().getStatusCode(), new String(os.toByteArray()));
            }
        }
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.commons.delegates.DelegatesManagementDispatchAction.java

public ActionForward exportToXLS(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws FenixServiceException {

    ExecutionYear currentExecutionYear = ExecutionYear.readCurrentExecutionYear();
    try {/*from ww w .ja  v a2  s  .c o m*/
        String filename = getResourceMessage("delegates.section") + "_" + currentExecutionYear.getYear();

        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment; filename=" + filename + ".xls");
        ServletOutputStream writer = response.getOutputStream();

        exportDelegatesToXLS(currentExecutionYear, writer);
        writer.flush();
        response.flushBuffer();
        return null;

    } catch (IOException e) {
        throw new FenixServiceException();
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.resourceAllocationManager.ShiftDistributionFirstYearDA.java

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

    ShiftDistributionFileBean fileBean = getRenderedObject();
    Spreadsheet spreadsheet = getStatisticsFromShiftDistribution(fileBean.getDistribution(),
            fileBean.getAbstractStudentNumbers());

    response.setHeader("Content-Disposition",
            "attachment; filename=estatisticas_distribuicao" + new DateTime() + ".csv");
    final ServletOutputStream writer = response.getOutputStream();
    spreadsheet.exportToCSV(writer, COLUMN_SEPARATOR, LINE_SEPARATOR);
    writer.flush();/*from  w w w. j  a va2s  .c  o m*/
    response.flushBuffer();
    return null;
}

From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.Default.java

public void handlePut(HttpServletRequest request, HttpServletResponse response, String pathInContext,
        Resource resource) throws ServletException, IOException {
    boolean exists = resource != null && resource.exists();
    if (exists && !passConditionalHeaders(request, response, resource))
        return;/*  w ww .j  av  a2 s.  c  om*/

    if (pathInContext.endsWith("/")) {
        if (!exists) {
            if (!resource.getFile().mkdirs())
                response.sendError(HttpResponse.__403_Forbidden, "Directories could not be created");
            else {
                response.setStatus(HttpResponse.__201_Created);
                response.flushBuffer();
            }
        } else {
            response.setStatus(HttpResponse.__200_OK);
            response.flushBuffer();
        }
    } else {
        try {
            int toRead = request.getContentLength();
            InputStream in = request.getInputStream();
            OutputStream out = resource.getOutputStream();
            if (toRead >= 0)
                IO.copy(in, out, toRead);
            else
                IO.copy(in, out);
            out.close();

            response.setStatus(exists ? HttpResponse.__200_OK : HttpResponse.__201_Created);
            response.flushBuffer();
        } catch (Exception ex) {
            log.warn(LogSupport.EXCEPTION, ex);
            response.sendError(HttpResponse.__403_Forbidden, ex.getMessage());
        }
    }
}

From source file:org.apache.sentry.provider.db.service.thrift.LogLevelServlet.java

/**
 * Parse the class name and log level in the http servlet request.
 * If the request contains only class name, return the log level in the response message.
 * If the request contains both class name and level, set the log level to the requested level
 * and return the setting result in the response message.
 *///  w  w  w. j ava  2s .  c om
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String logName = getParameter(request, "log");
    String level = getParameter(request, "level");
    response.setContentType("text/html;charset=utf-8");
    response.setStatus(HttpServletResponse.SC_OK);
    PrintWriter out = response.getWriter();

    if (logName != null) {
        Logger logInstance = LogManager.getLogger(logName);
        if (level == null) {
            out.write(
                    String.format(FORMS_GET, escapeHtml(logName), logInstance.getEffectiveLevel().toString()));
        } else if (isLogLevelValid(level)) {
            logInstance.setLevel(Level.toLevel(level));
            out.write(String.format(FORMS_SET, escapeHtml(logName), level, level,
                    logInstance.getEffectiveLevel().toString()));
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid log level: " + level);
            return;
        }
    }
    out.write(FORMS_END);
    out.close();
    response.flushBuffer();
}