List of usage examples for javax.servlet.http HttpServletResponse flushBuffer
public void flushBuffer() throws IOException;
From source file:org.fusesource.fabric.maven.impl.MavenSecureHttpContext.java
public boolean authenticate(HttpServletRequest request, HttpServletResponse response) { // Return immediately if the header is missing String authHeader = request.getHeader(HEADER_AUTHORIZATION); if (authHeader != null && authHeader.length() > 0) { // Get the authType (Basic, Digest) and authInfo (user/password) // from the header authHeader = authHeader.trim();// w ww. j a v a 2 s. c o m int blank = authHeader.indexOf(' '); if (blank > 0) { String authType = authHeader.substring(0, blank); String authInfo = authHeader.substring(blank).trim(); // Check whether authorization type matches if (authType.equalsIgnoreCase(AUTHENTICATION_SCHEME_BASIC)) { try { String srcString = base64Decode(authInfo); int i = srcString.indexOf(':'); String username = srcString.substring(0, i); String password = srcString.substring(i + 1); // authenticate Subject subject = doAuthenticate(username, password); if (subject != null) { // as per the spec, set attributes request.setAttribute(HttpContext.AUTHENTICATION_TYPE, HttpServletRequest.BASIC_AUTH); request.setAttribute(HttpContext.REMOTE_USER, username); // succeed return true; } } catch (Exception e) { // Ignore } } } } // request authentication try { response.setHeader(HEADER_WWW_AUTHENTICATE, AUTHENTICATION_SCHEME_BASIC + " realm=\"" + this.realm + "\""); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.setContentLength(0); response.flushBuffer(); } catch (IOException ioe) { // failed sending the response ... cannot do anything about it } // inform HttpService that authentication failed return false; }
From source file:org.ms123.common.exporting.BaseExportingServiceImpl.java
protected String createReport(List rows, StoreDesc sdesc, String entity, String format, Map soptions, List fields, List aliases, String user, HttpServletResponse response) throws Exception { Map options = null;/*from w w w . ja v a 2 s. co m*/ if (soptions != null) { options = soptions; } else { options = new HashMap(); options.put("rowDelim", "UNIX"); options.put("columnDelim", ","); options.put("quote", "\""); options.put("alwaysQuote", false); } List aliasesArray = null; if (aliases != null && aliases.size() > 0) { aliasesArray = aliases; } else { aliasesArray = new ArrayList(); } List fieldsArray = null; if (fields != null && fields.size() > 0) { fieldsArray = fields; } else { throw new Exception("DataService.createDownloadFile:fieldsArray_is_empty"); } System.out.println("fields:" + fields); System.out.println("aliases:" + aliases); System.out.println("fieldsArray:" + fieldsArray); System.out.println("aliasesArray:" + aliasesArray); Map configForFieldsArray = getConfigForFieldsArray(sdesc, entity, fieldsArray); if (!format.equals("csv")) { String filename = (String) options.get("filename"); if (format.equals("pdf")) { response.setContentType("application/x-pdf"); response.addHeader("Content-Disposition", "inline;filename=" + filename); } else if (format.equals("xls")) { response.setContentType("application/msexcel"); response.addHeader("Content-Disposition", "inline;filename=" + filename); } else if (format.equals("html")) { response.setContentType("text/html"); response.addHeader("Content-Disposition", "inline;filename=" + filename); } String retx = m_reportingService.generateReport(rows, fieldsArray, aliasesArray, configForFieldsArray, format, options, response.getOutputStream()); response.flushBuffer(); return retx; } else { response.setContentType("text/csv;charset=UTF-8"); response.addHeader("Content-Disposition", "inline;filename=" + options.get("filename")); return m_reportingService.createCSV(rows, fieldsArray, aliasesArray, configForFieldsArray, options, response.getOutputStream()); } }
From source file:org.alfresco.repo.webdav.auth.BaseNTLMAuthenticationFilter.java
/** * Restart the NTLM logon process//w w w.j a v a 2 s . c om * * @param context ServletContext * @param req HttpServletRequest * @param res SessHttpServletResponse * @throws IOException */ public void restartLoginChallenge(ServletContext context, HttpServletRequest req, HttpServletResponse res) throws IOException { if (getLogger().isDebugEnabled()) getLogger().debug("restartLoginChallenge..."); // Remove any existing session and NTLM details from the session HttpSession session = req.getSession(false); if (session != null) { clearSession(session); } // check for "chrome" since Chrome user-agent contains a Safari version String userAgent = req.getHeader("user-agent"); if (userAgent != null && userAgent.indexOf("Safari") != -1 && userAgent.indexOf("Chrome") == -1) { final PrintWriter out = res.getWriter(); out.println("<html><head></head>"); out.println("<body><p>Login authentication failed. Please close and re-open Safari to try again.</p>"); out.println("</body></html>"); out.close(); } else { // Force the logon to start again res.setHeader(WWW_AUTHENTICATE, AUTH_NTLM); res.setStatus(HttpServletResponse.SC_UNAUTHORIZED); writeLoginPageLink(context, req, res); } if (isFallbackEnabled()) { includeFallbackAuth(context, req, res); } res.flushBuffer(); }
From source file:de.thorstenberger.examServer.webapp.action.PDFBulkExport.java
@Override public ActionForward execute(final ActionMapping mapping, final ActionForm form, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final ActionMessages errors = new ActionMessages(); // locate the taskdef to use long taskId;// www. j a v a2s . c o m try { taskId = Long.parseLong(request.getParameter("taskId")); } catch (final NumberFormatException e) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("invalid.parameter")); saveErrors(request, errors); return mapping.findForward("error"); } final TaskManager tm = (TaskManager) getBean("TaskManager"); final TaskDef td = tm.getTaskDef(taskId); final UserManager userManager = (UserManager) getBean("userManager"); if (request.getUserPrincipal() == null) { throw new RuntimeException("Not logged in."); } // we only know how to handle complextasks yet if (td.getType().equals(TaskContants.TYPE_COMPLEX)) { // initialize web crawler final PDFExporter pdfExporter = new PDFExporter(userManager, tm); // show an error message if tomcat isn't configured appropriately if (!pdfExporter.isAvailableWithoutCertificate()) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("invalid.serverconfig")); saveErrors(request, errors); return mapping.findForward("error"); } // set response headers to declare pdf content type response.setContentType("application/zip"); response.setHeader("Content-Disposition", "attachment; filename=" + getBulkFilename(td)); // locate the taskdef TaskDef_Complex ctd; try { ctd = (TaskDef_Complex) td; } catch (final ClassCastException e) { throw new RuntimeException("invalid type: \"" + td.getType() + "\", " + e.getMessage()); } // write headers, start streaming to the client response.flushBuffer(); // get all tasklets for the given taskdef final List<Tasklet> tasklets = tm.getTaskletContainer().getTasklets(taskId); log.info(String.format("Exporting %d pdfs for taskdef \"%s\"", tasklets.size(), ctd.getTitle())); renderAllPdfs(tasklets, response.getOutputStream(), pdfExporter); return null; } else { throw new RuntimeException("unsupported type: \"" + td.getType() + "\""); } }
From source file:org.alfresco.web.site.servlet.SSOAuthenticationFilter.java
/** * Restart the authentication process for NTLM or Kerberos - clear current security details *//* w w w . j a v a 2 s.com*/ private void restartAuthProcess(HttpSession session, HttpServletRequest req, HttpServletResponse res, String authHdr) throws IOException { if (logger.isDebugEnabled()) logger.debug("Restarting " + authHdr + " authentication."); // Clear any cached logon details from the sessiom clearSession(session); setRedirectUrl(req); // restart the authentication process for NTLM res.setHeader(HEADER_WWWAUTHENTICATE, authHdr); res.setStatus(HttpServletResponse.SC_UNAUTHORIZED); res.setContentType(MIME_HTML_TEXT); final PrintWriter out = res.getWriter(); out.println("<html><head>"); out.println( "<meta http-equiv=\"Refresh\" content=\"0; url=" + req.getContextPath() + "/page?pt=login" + "\">"); out.println("</head><body><p>Please <a href=\"" + req.getContextPath() + "/page?pt=login" + "\">log in</a>.</p>"); out.println("</body></html>"); out.close(); res.flushBuffer(); }
From source file:org.eclipse.orion.server.authentication.formopenid.FormOpenIdLoginServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String pathInfo = req.getPathInfo() == null ? "" : req.getPathInfo(); //$NON-NLS-1$ if (pathInfo.startsWith("/form")) { //$NON-NLS-1$ try {/*from w w w . j a v a 2 s .co m*/ LoginResult authResult = FormAuthHelper.performAuthentication(req, resp); if (authResult == LoginResult.OK) { // redirection from // FormAuthenticationService.setNotAuthenticated String versionString = req.getHeader("Orion-Version"); //$NON-NLS-1$ Version version = versionString == null ? null : new Version(versionString); // TODO: This is a workaround for calls // that does not include the WebEclipse version header String xRequestedWith = req.getHeader("X-Requested-With"); //$NON-NLS-1$ if (version == null && !"XMLHttpRequest".equals(xRequestedWith)) { //$NON-NLS-1$ if (req.getParameter(OpenIdHelper.REDIRECT) != null && !req.getParameter(OpenIdHelper.REDIRECT).equals("")) { //$NON-NLS-1$ resp.sendRedirect(req.getParameter(OpenIdHelper.REDIRECT)); } } else { resp.setStatus(HttpServletResponse.SC_OK); PrintWriter writer = resp.getWriter(); String uid = (String) req.getSession().getAttribute("user"); JSONObject userJson; try { userJson = FormAuthHelper.getUserJson(uid, req.getContextPath()); writer.print(userJson); resp.setContentType("application/json"); //$NON-NLS-1$ } catch (JSONException e) {/* ignore */ } } resp.flushBuffer(); } else if (authResult == LoginResult.BLOCKED) { displayError("Your account is not active. Please confirm your email before logging in.", req, resp); } else { displayError("Invalid user or password", req, resp); } } catch (UnsupportedUserStoreException e) { LogHelper.log(e); resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage()); } return; } if (pathInfo.startsWith("/openid")) { //$NON-NLS-1$ String openid = req.getParameter(OpenIdHelper.OPENID); if (openid != null) { try { consumer = OpenIdHelper.redirectToOpenIdProvider(req, resp, consumer); } catch (OpenIdException e) { LogHelper.log(new Status(IStatus.ERROR, Activator.PI_AUTHENTICATION_SERVLETS, "An error occurred redirecting to OpenId provider", e)); displayError(e.getMessage(), req, resp); } return; } String op_return = req.getParameter(OpenIdHelper.OP_RETURN); if (op_return != null) { try { OpenIdHelper.handleOpenIdReturnAndLogin(req, resp, consumer); } catch (OpenIdException e) { displayError(e.getMessage(), req, resp); } return; } } if (pathInfo.startsWith("/persona")) { //$NON-NLS-1$ String assertion = req.getParameter(PersonaConstants.PARAM_ASSERTION); if (assertion != null) { try { new PersonaHelper().handleCredentialsAndLogin(req, resp); } catch (PersonaException e) { displayError(e.getMessage(), req, resp); } } } if (pathInfo.startsWith("/canaddusers")) { JSONObject jsonResp = new JSONObject(); try { jsonResp.put("CanAddUsers", FormAuthHelper.canAddUsers()); jsonResp.put("ForceEmail", FormAuthHelper.forceEmail()); jsonResp.put("RegistrationURI", FormAuthHelper.registrationURI()); } catch (JSONException e) { } resp.getWriter().print(jsonResp); resp.setContentType("application/json"); return; } String user = req.getRemoteUser(); if (user == null) { user = authenticationService.getAuthenticatedUser(req, resp, authenticationService.getDefaultAuthenticationProperties()); } if (user != null) { resp.setStatus(HttpServletResponse.SC_OK); try { resp.getWriter().print(FormAuthHelper.getUserJson(user, req.getContextPath())); } catch (JSONException e) { handleException(resp, "An error occured when creating JSON object for logged in user", e); } return; } }
From source file:com.sun.faban.harness.webclient.CLIServlet.java
private void sendLogs(String[] reqC, HttpServletResponse response) throws ServletException, IOException { if (reqC.length < 2) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing RunId."); return;// w w w . j a v a2 s . c o m } RunId runId = new RunId(reqC[1]); boolean[] options = new boolean[2]; options[TAIL] = false; options[FOLLOW] = false; for (int i = 2; i < reqC.length; i++) { if ("tail".equals(reqC[i])) { options[TAIL] = true; } else if ("follow".equals(reqC[i])) { options[FOLLOW] = true; } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid option \"" + reqC[i] + "\"."); ; return; } } File logFile = new File(Config.OUT_DIR + runId, "log.xml"); String status = null; response.setContentType("text/plain"); PrintWriter out = response.getWriter(); while (!logFile.exists()) { String[] pending = RunQ.listPending(); if (pending == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND, "RunId " + runId + " not found"); return; } boolean queued = false; for (String run : pending) { if (run.equals(runId.toString())) { if (status == null) { status = "QUEUED"; out.println(status); response.flushBuffer(); } queued = true; try { Thread.sleep(1000); // Check back in one sec. } catch (InterruptedException e) { //Noop, just look it up again. } break; } } if (!queued) { // Either never queued or deleted from queue. // Check for 10x, 100ms each to allow for start time. for (int i = 0; i < 10; i++) { if (logFile.exists()) { status = "STARTED"; break; } try { Thread.sleep(100); } catch (InterruptedException e) { logger.log(Level.WARNING, "Interrupted checking existence of log file."); } } if (!"STARTED".equals(status)) { if ("QUEUED".equals(status)) { // was queued before status = "DELETED"; out.println(status); out.flush(); out.close(); return; } else { // Never queued or just removed. response.sendError(HttpServletResponse.SC_NOT_FOUND, "RunId " + runId + " not found"); return; } } } } LogOutputHandler handler = new LogOutputHandler(response, options); InputStream logInput; if (options[FOLLOW]) { // The XMLInputStream reads streaming XML and does not EOF. XMLInputStream input = new XMLInputStream(logFile); input.addEOFListener(handler); logInput = input; } else { logInput = new FileInputStream(logFile); } try { SAXParserFactory sFact = SAXParserFactory.newInstance(); sFact.setFeature("http://xml.org/sax/features/validation", false); sFact.setFeature("http://apache.org/xml/features/" + "allow-java-encodings", true); sFact.setFeature("http://apache.org/xml/features/nonvalidating/" + "load-dtd-grammar", false); sFact.setFeature("http://apache.org/xml/features/nonvalidating/" + "load-external-dtd", false); SAXParser parser = sFact.newSAXParser(); parser.parse(logInput, handler); handler.xmlComplete = true; // If we get here, the XML is good. } catch (ParserConfigurationException e) { throw new ServletException(e); } catch (SAXParseException e) { Throwable t = e.getCause(); // If it is caused by an IOException, we'll just throw it. if (t != null) { if (t instanceof IOException) throw (IOException) t; else if (options[FOLLOW]) throw new ServletException(t); } else if (options[FOLLOW]) { throw new ServletException(e); } } catch (SAXException e) { throw new ServletException(e); } finally { if (options[TAIL] && !options[FOLLOW]) // tail not yet printed handler.eof(); } }
From source file:org.ajax4jsf.webapp.BaseXMLFilter.java
/** * Perform filter chain with xml parsing and transformation. Subclasses must * implement concrete HTML to XML parsing, nesseasary transformations and * serialization./*from ww w . j a va 2s. co m*/ * * @param chain * @param httpServletRequest * @param httpServletResponse * @throws ServletException * @throws IOException */ protected void doXmlFilter(FilterChain chain, HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { if (log.isDebugEnabled()) { log.debug("XML filter service start processing request"); } FilterServletResponseWrapper servletResponseWrapper = getWrapper(response); // HACK - to avoid MyFaces <f:view> incompabilites and bypass // intermediaty filters // in chain, self-rendered region write directly to wrapper stored in // request-scope attribute. try { request.setAttribute(BaseFilter.RESPONSE_WRAPPER_ATTRIBUTE, servletResponseWrapper); chain.doFilter(request, servletResponseWrapper); } catch (ServletException e) { if (handleViewExpiredOnClient && (isViewExpired(e) || isViewExpired(e.getRootCause())) && isAjaxRequest(request)) { log.debug("ViewExpiredException in the filter chain - will be handled on the client", e); Writer output = resetResponse(response, servletResponseWrapper, "true"); String message = Messages.getMessage(Messages.AJAX_VIEW_EXPIRED); response.setHeader(AJAX_EXPIRED, message); output.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head>" + "<meta name=\"" + AjaxContainerRenderer.AJAX_FLAG_HEADER + "\" content=\"true\" />" + "<meta name=\"" + AJAX_EXPIRED + "\" content=\"" + message + "\" />" + "</head></html>"); output.flush(); response.flushBuffer(); return; } else { log.error("Exception in the filter chain", e); throw e; } } finally { request.removeAttribute(BaseFilter.RESPONSE_WRAPPER_ATTRIBUTE); } String viewId = (String) request.getAttribute(AjaxViewHandler.VIEW_ID_KEY); Node[] headEvents = (Node[]) request.getAttribute(AjaxContext.HEAD_EVENTS_PARAMETER); HtmlParser parser = null; // setup response // Redirect in AJAX request - convert to special response recognized by // client. String redirectLocation = servletResponseWrapper.getRedirectLocation(); String characterEncoding = servletResponseWrapper.getCharacterEncoding(); Writer output; if (null != redirectLocation) { if (isAjaxRequest(request)) { // Special handling of redirect - client-side script must // Check for response and perform redirect by window.location if (log.isDebugEnabled()) { log.debug("Create AJAX redirect response to url: " + redirectLocation); } output = resetResponse(response, servletResponseWrapper, "redirect"); response.setHeader(AjaxContainerRenderer.AJAX_LOCATION_HEADER, redirectLocation); // For buggy XmlHttpRequest realisations repeat headers in // <meta> output.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head>" + "<meta name=\"" + AjaxContainerRenderer.AJAX_FLAG_HEADER + "\" content=\"redirect\" />" + "<meta name=\"" + AjaxContainerRenderer.AJAX_LOCATION_HEADER + "\" content=\"" + redirectLocation + "\" />" + "</head></html>"); output.flush(); response.flushBuffer(); } else { response.sendRedirect(redirectLocation); } return; } else { if ("true".equals(servletResponseWrapper.getHeaders().get(AjaxContainerRenderer.AJAX_FLAG_HEADER))) { if (log.isDebugEnabled()) { log.debug("Process response to well-formed XML for AJAX XMLHttpRequest parser"); } // Not caching AJAX request response.setHeader("Cache-Control", "no-cache, must-revalidate, max_age=0, no-store"); response.setHeader("Expires", "0"); response.setHeader("Pragma", "no-cache"); // response.setCharacterEncoding(servletResponseWrapper // .getCharacterEncoding()); // // JSContentHandler.DEFAULT_ENCODING); // Set the content-type. For AJAX responses default encoding - // UTF8. // TODO - for null encoding, setup only Output encoding for // filter ? String outputEncoding = "UTF-8"; String contentType = getMimetype() + ";charset=" + outputEncoding; response.setContentType(contentType); parser = getParser(getMimetype(), true, viewId); if (null == parser) { throw new ServletException( Messages.getMessage(Messages.PARSER_NOT_INSTANTIATED_ERROR, contentType)); } output = createOutputWriter(response, outputEncoding); parser.setDoctype(getPublicid()); parser.setInputEncoding(characterEncoding); parser.setOutputEncoding(outputEncoding); parser.setViewState((String) request.getAttribute(AjaxViewHandler.SERIALIZED_STATE_KEY)); } else { // setup conversion reules for output contentType, send directly // if content not // supported by tidy. String contentType = servletResponseWrapper.getContentType(); String contentTypeCharset = contentType; if (log.isDebugEnabled()) { log.debug("create HTML/XML parser for content type: " + contentType); } // if(contentType == null){ // contentType = request.getContentType(); // } boolean forcenotrf = isForcenotrf(); if (forcenotrf || !servletResponseWrapper.isError()) { if (forcenotrf || (headEvents != null && headEvents.length != 0)) { if (contentTypeCharset != null) { if (contentTypeCharset.indexOf("charset") < 0 && null != characterEncoding) { contentTypeCharset += ";charset=" + characterEncoding; } parser = getParser(contentTypeCharset, false, viewId); if (null == parser) { if (log.isDebugEnabled()) { log.debug( "Parser not have support for the such content type, send response as-is"); } } } } else { if (log.isDebugEnabled()) { log.debug("No resource inclusions detected, send response as-is"); } } } else { if (log.isDebugEnabled()) { log.debug("Servlet error occured, send response as-is"); } } // null or unsupported content type if (null == parser) { try { if (servletResponseWrapper.isUseWriter()) { if (contentTypeCharset != null) { response.setContentType(contentTypeCharset); } output = createOutputWriter(response, characterEncoding); servletResponseWrapper.sendContent(output); } else if (servletResponseWrapper.isUseStream()) { if (contentType != null) { response.setContentType(contentType); } ServletOutputStream out = response.getOutputStream(); servletResponseWrapper.sendContent(out); } } finally { // reuseWrapper(servletResponseWrapper); } return; } if (contentTypeCharset != null) { response.setContentType(contentTypeCharset); } output = createOutputWriter(response, characterEncoding); parser.setInputEncoding(characterEncoding); parser.setOutputEncoding(characterEncoding); } } try { // Setup scripts and styles parser.setHeadNodes(headEvents); // Process parsing. long startTimeMills = System.currentTimeMillis(); servletResponseWrapper.parseContent(output, parser); if (log.isDebugEnabled()) { startTimeMills = System.currentTimeMillis() - startTimeMills; log.debug(Messages.getMessage(Messages.PARSING_TIME_INFO, "" + startTimeMills)); } } catch (Exception e) { throw new ServletException(Messages.getMessage(Messages.JTIDY_PARSING_ERROR), e); } finally { reuseParser(parser); } }