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:it.attocchi.web.auth.AuthenticationFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    logger.debug("Filtro Autenticazione");

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    HttpSession session = httpRequest.getSession();

    String requestPath = httpRequest.getServletPath();
    logger.debug("requestPath " + requestPath);

    String user_agent = null;/*w ww. j a v  a 2  s.  com*/
    String auth = null;

    String workstation = null;
    String domain = null;
    String username = null;

    try {

        if (requestPath != null
                && (requestPath.endsWith("index.xhtml") || requestPath.endsWith("login.xhtml"))) {
            logger.debug("Richiesta una pagina fra quelle speciali, esco dal filtro");
            chain.doFilter(request, response);
            return;
        } else {

            user_agent = httpRequest.getHeader("user-agent");
            if ((user_agent != null) && (user_agent.indexOf("MSIE") > -1)) {
                logger.debug("USER-AGENT: " + user_agent);

                auth = httpRequest.getHeader("Authorization");
                if (auth == null) {
                    logger.debug("STEP1: SC_UNAUTHORIZED");

                    httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    httpResponse.setHeader("WWW-Authenticate", "NTLM");
                    httpResponse.flushBuffer();
                    return;
                }

                if (auth.startsWith("NTLM ")) {
                    logger.debug("STEP2: NTLM");

                    byte[] msg = org.apache.commons.codec.binary.Base64.decodeBase64(auth.substring(5));
                    // byte[] msg = new
                    // sun.misc.BASE64Decoder().decodeBuffer(auth.substring(5));
                    int off = 0, length, offset;
                    if (msg[8] == 1) {
                        logger.debug("STEP2a: NTLM");

                        byte z = 0;
                        byte[] msg1 = { (byte) 'N', (byte) 'T', (byte) 'L', (byte) 'M', (byte) 'S', (byte) 'S',
                                (byte) 'P', z, (byte) 2, z, z, z, z, z, z, z, (byte) 40, z, z, z, (byte) 1,
                                (byte) 130, z, z, z, (byte) 2, (byte) 2, (byte) 2, z, z, z, z, z, z, z, z, z, z,
                                z, z };
                        // httpResponse.setHeader("WWW-Authenticate",
                        // "NTLM " + new
                        // sun.misc.BASE64Encoder().encodeBuffer(msg1));
                        httpResponse.setHeader("WWW-Authenticate",
                                "NTLM " + org.apache.commons.codec.binary.Base64.encodeBase64String(msg1));
                        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                        return;
                    } else if (msg[8] == 3) {
                        logger.debug("STEP2b: read data");

                        off = 30;
                        length = msg[off + 17] * 256 + msg[off + 16];
                        offset = msg[off + 19] * 256 + msg[off + 18];
                        workstation = new String(msg, offset, length);

                        length = msg[off + 1] * 256 + msg[off];
                        offset = msg[off + 3] * 256 + msg[off + 2];
                        domain = new String(msg, offset, length);

                        length = msg[off + 9] * 256 + msg[off + 8];
                        offset = msg[off + 11] * 256 + msg[off + 10];
                        username = new String(msg, offset, length);

                        char a = 0;
                        char b = 32;
                        // logger.debug("Username:" +
                        // username.trim().replace(a, b).replaceAll("",
                        // ""));
                        username = username.trim().replace(a, b).replaceAll(" ", "");
                        workstation = workstation.trim().replace(a, b).replaceAll(" ", "");
                        domain = domain.trim().replace(a, b).replaceAll(" ", "");

                        logger.debug("Username: " + username);
                        logger.debug("RemoteHost: " + workstation);
                        logger.debug("Domain: " + domain);

                    }
                }
            } // if IE
            else {
                chain.doFilter(request, response);
            }

            String winUser = username; // domain + "\\" + username;

        }
    } catch (RuntimeException e) {
        logger.error("Errore nel Filtro Autenticazione");
        logger.error(e);

        chain.doFilter(request, response);
        httpResponse.sendError(httpResponse.SC_UNAUTHORIZED);

        httpResponse.sendRedirect(httpRequest.getContextPath() + "/index.jsp");
    }

    logger.debug("Fine Filtro Autenticazione");
}

From source file:org.kuali.ole.web.DocumentServlet.java

/**
 * Method sends the response generated for the given request
 *
 * @param res/*from   w w  w.j ava2 s. c  om*/
 * @param file
 * @throws IOException
 */
private void sendResponseAsFile(HttpServletResponse res, File file) throws IOException {
    ServletOutputStream stream = res.getOutputStream();
    FileInputStream fos = new FileInputStream(file.getAbsolutePath());
    BufferedInputStream buf = new BufferedInputStream(fos);
    int readBytes = 0;
    while ((readBytes = buf.read()) != -1) {
        stream.write(readBytes);
    }
    if (stream != null) {
        stream.close();
    }
    if (buf != null) {
        buf.close();
    }
    res.flushBuffer();
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.administrativeOffice.lists.StudentsListByCurricularCourseDA.java

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

    final CurricularCourse curricularCourse = getDomainObject(request, "curricularCourseCode");
    final Integer semester = getIntegerFromRequest(request, "semester");
    final ExecutionYear executionYear = ExecutionYear
            .readExecutionYearByName((String) getFromRequest(request, "curricularYear"));
    final String year = (String) getFromRequest(request, "year");

    try {//from   ww  w.ja v  a  2  s.  c om
        String filename = getResourceMessage("label.students") + "_" + curricularCourse.getName() + "_("
                + curricularCourse.getDegreeCurricularPlan().getName() + ")_" + executionYear.getYear();

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

        exportToXls(searchStudentByCriteria(executionYear, curricularCourse, semester), writer, executionYear,
                curricularCourse, year, semester.toString(), detailed);
        writer.flush();
        response.flushBuffer();

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

    return null;

}

From source file:org.intermine.webservice.server.WebService.java

/**
 * Starting method of web service. The web service should be run like
 *
 * <pre>//from  w ww  .  jav  a2 s .co  m
 * new ListsService().service(request, response);
 * </pre>
 *
 * Ensures initialisation of web service and makes steps common for all web
 * services and after that executes the <tt>execute</tt> method, for which
 * each subclass must provide an implementation.
 *
 * @param request
 *            The request, as received by the servlet.
 * @param response
 *            The response, as handled by the servlet.
 */
public void service(HttpServletRequest request, HttpServletResponse response) {
    this.request = request;
    this.response = response;

    try {
        if (agentIsRobot()) {
            response.sendError(Output.SC_FORBIDDEN);
        } else {
            setHeaders();
            initState();
            initOutput();
            checkEnabled();
            authenticate();
            initialised = true;
            postInit();
            validateState();
            execute();
        }
    } catch (Throwable t) {
        sendError(t, response);
    }

    try {
        if (output == null) {
            response.flushBuffer();
        } else {
            output.flush();
        }
    } catch (Throwable t) {
        logError(t, "Error flushing", 500);
    }

    try {
        cleanUp();
    } catch (Throwable t) {
        LOG.error("Error cleaning up", t);
    }

}

From source file:fr.treeptik.cloudunit.controller.FileController.java

/**
 * Download a file into a container//  w  w  w .j a  v a 2 s .c om
 *
 * @param containerId
 * @param applicationName
 * @param path
 * @param fileName
 * @param request
 * @param response
 * @throws ServiceException
 * @throws CheckException
 * @throws IOException
 * @returnoriginalName
 */
@RequestMapping(value = "/container/{containerId}/application/{applicationName}/path/{path}/fileName/{fileName:.*}", method = RequestMethod.GET)
public void downloadFileFromContainer(@PathVariable final String containerId,
        @PathVariable final String applicationName, @PathVariable String path,
        @PathVariable final String fileName, HttpServletRequest request, HttpServletResponse response)
        throws ServiceException, CheckException, IOException {

    if (logger.isDebugEnabled()) {
        logger.debug("containerId:" + containerId);
        logger.debug("applicationName:" + applicationName);
        logger.debug("fileName:" + fileName);
    }

    User user = authentificationUtils.getAuthentificatedUser();
    Application application = applicationService.findByNameAndUser(user, applicationName);

    // We must be sure there is no running action before starting new one
    this.authentificationUtils.canStartNewAction(user, application, locale);

    File file = File.createTempFile("previousDownload", FilesUtils.setSuffix(fileName));

    path = convertPathFromUI(path);
    Optional<File> fileFromContainer = fileService.getFileFromContainer(applicationName, containerId, file,
            fileName, path);

    // File can be empty but we need to return one
    if (fileFromContainer.filter(x -> x.length() == 0).isPresent()) {
        file = File.createTempFile(fileName, "");
        // put an empty space for empty file
        FileUtils.write(file, " ");
    }

    InputStream inputStream = new FileInputStream(file); //load the file
    IOUtils.copy(inputStream, response.getOutputStream());
    response.flushBuffer();

}

From source file:net.sourceforge.fenixedu.presentationTier.Action.scientificCouncil.credits.ViewTeacherCreditsReportDispatchAction.java

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

    User userView = Authenticate.getUser();

    String fromExecutionYearID = request.getParameter("fromExecutionYearID");
    String untilExecutionYearID = request.getParameter("untilExecutionYearID");
    String departmentID = request.getParameter("departmentID");

    Map<Department, Map<Unit, List>> teachersCreditsByDepartment = getDetailedTeachersCreditsMap(request,
            userView, fromExecutionYearID, untilExecutionYearID, departmentID);

    try {/*from   ww w.java  2s .c  o m*/
        String filename = "RelatorioCreditos:" + getFileName(Calendar.getInstance().getTime());
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment; filename=" + filename + ".xls");

        ServletOutputStream writer = response.getOutputStream();
        exportToXls(teachersCreditsByDepartment, writer);

        writer.flush();
        response.flushBuffer();

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

From source file:net.solarnetwork.node.setup.test.DefaultSetupServiceTest.java

@Test
public void renewNetworkCertificate() throws Exception {
    SetupIdentityInfo info = new SetupIdentityInfo(1L, TEST_CONF_VALUE, TEST_SOLARIN_HOST, getHttpServerPort(),
            false, TEST_PW_VALUE);/* ww  w . j  a va  2s .c om*/
    expect(setupIdentityDao.getSetupIdentityInfo()).andReturn(info).atLeastOnce();
    replayAll();
    keystoreService.saveCACertificate(CA_CERT);
    keystoreService.generateNodeSelfSignedCertificate(TEST_DN);
    String csr = keystoreService.generateNodePKCS10CertificateRequestString();

    X509Certificate originalCert;

    PemReader pemReader = new PemReader(new StringReader(csr));
    try {
        PemObject pem = pemReader.readPemObject();
        PKCS10CertificationRequest req = new PKCS10CertificationRequest(pem.getContent());
        originalCert = PKITestUtils.sign(req, CA_CERT, CA_KEY_PAIR.getPrivate());
        String signedPem = PKITestUtils.getPKCS7Encoding(new X509Certificate[] { originalCert });
        keystoreService.saveNodeSignedCertificate(signedPem);

        log.debug("Saved signed node certificate {}:\n{}", originalCert.getSerialNumber(), signedPem);

        assertThat("Generated CSR", csr, notNullValue());
    } finally {
        pemReader.close();
    }

    // now let's renew!
    AbstractTestHandler handler = new AbstractTestHandler() {

        @Override
        protected boolean handleInternal(String target, HttpServletRequest request,
                HttpServletResponse response, int dispatch) throws Exception {
            assertEquals("POST", request.getMethod());
            assertEquals("/solarin/api/v1/sec/cert/renew", target);
            String password = request.getParameter("password");
            assertEquals("foobar", password);

            String keystoreData = request.getParameter("keystore");
            assertNotNull(keystoreData);
            byte[] data = Base64.decodeBase64(keystoreData);
            KeyStore keyStore = KeyStore.getInstance("pkcs12");
            keyStore.load(new ByteArrayInputStream(data), password.toCharArray());
            Certificate cert = keyStore.getCertificate("node");
            assertNotNull(cert);
            assertTrue(cert instanceof X509Certificate);
            X509Certificate nodeCert = (X509Certificate) cert;
            assertEquals(new X500Principal(TEST_DN), nodeCert.getSubjectX500Principal());
            assertEquals(CA_CERT.getSubjectX500Principal(), nodeCert.getIssuerX500Principal());

            response.setContentType("application/json");
            PrintWriter out = response.getWriter();
            out.write("{\"success\":true}");
            out.flush();
            response.flushBuffer();
            return true;
        }

    };
    httpServer.addHandler(handler);

    service.renewNetworkCertificate("foobar");
}

From source file:org.codice.ddf.security.idp.client.IdpHandler.java

private void doHttpRedirectBinding(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {

    String redirectUrl;/*  ww  w  . ja va 2 s .  c om*/
    String idpRequest = null;
    String relayState = createRelayState(request);
    try {
        String queryParams = String.format("SAMLRequest=%s&RelayState=%s", createAuthnRequest(false),
                URLEncoder.encode(relayState, "UTF-8"));
        idpRequest = idpMetadata.getSingleSignOnLocation() + "?" + queryParams;
        UriBuilder idpUri = new UriBuilderImpl(new URI(idpRequest));

        simpleSign.signUriString(queryParams, idpUri);

        redirectUrl = idpUri.build().toString();
    } catch (UnsupportedEncodingException e) {
        LOGGER.warn("Unable to encode relay state: " + relayState, e);
        throw new ServletException("Unable to create return location");
    } catch (SimpleSign.SignatureException e) {
        String msg = "Unable to sign request";
        LOGGER.warn(msg, e);
        throw new ServletException(msg);
    } catch (URISyntaxException e) {
        LOGGER.warn("Unable to parse IDP request location: " + idpRequest, e);
        throw new ServletException("Unable to determine IDP location.");
    }

    try {
        response.sendRedirect(redirectUrl);
        response.flushBuffer();
    } catch (IOException e) {
        LOGGER.warn("Unable to redirect AuthnRequest to " + redirectUrl, e);
        throw new ServletException("Unable to redirect to IdP");
    }
}

From source file:org.fao.unredd.portal.ApplicationController.java

@RequestMapping("/static/**")
public void getCustomStaticFile(HttpServletRequest request, HttpServletResponse response) throws IOException {

    // Get path to file
    String fileName = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);

    // Verify file exists
    File file = new File(config.getDir() + "/static/" + fileName);
    if (!file.isFile()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;//from   ww w. j av a2 s  . c  om
    }

    // Manage cache headers: Last-Modified and If-Modified-Since
    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    long lastModified = file.lastModified();
    if (ifModifiedSince >= (lastModified / 1000 * 1000)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }
    response.setDateHeader("Last-Modified", lastModified);

    // Set content type
    FileNameMap fileNameMap = URLConnection.getFileNameMap();
    String type = fileNameMap.getContentTypeFor(fileName);
    response.setContentType(type);

    // Send contents
    try {
        InputStream is = new FileInputStream(file);
        IOUtils.copy(is, response.getOutputStream());
        response.flushBuffer();
    } catch (IOException e) {
        logger.error("Error reading file", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:org.apache.sentry.api.service.thrift.PubSubServlet.java

/**
 * Parse the topic and message values and submit them via PubSub.submit() API.
 * Reject request for unknown topic, i.e. topic no one is subscribed to.
 *//*from  ww  w  .j av  a 2  s  . c om*/
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String topic = getParameter(request, "topic");
    String message = getParameter(request, "message");
    response.setContentType("text/html;charset=utf-8");
    response.setStatus(HttpServletResponse.SC_OK);
    PrintWriter out = response.getWriter();

    String msg = "Topic is required, Message is optional.\nValid topics: " + PubSub.getInstance().getTopics();
    if (topic != null) {
        LOGGER.info("Submitting topic " + topic + ", message " + message);
        try {
            PubSub.getInstance().publish(PubSub.Topic.fromString(topic), message);
            msg = "Submitted topic " + topic + ", message " + message;
        } catch (Exception e) {
            msg = "Failed to submit topic " + topic + ", message " + message + " - " + e.getMessage();
            LOGGER.error(msg);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
            return;
        }
    }

    StringBuilder topics = new StringBuilder();
    for (PubSub.Topic t : PubSub.getInstance().getTopics()) {
        topics.append("<option>").append(t.getName()).append("</option>");
    }

    String output = String.format(FORM_GET, topics.toString(), escapeHtml(msg));
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("HTML Page: " + output);
    }
    out.write(output);
    out.close();
    response.flushBuffer();
}