Java Code Examples for javax.faces.context.FacesContext#responseComplete()

The following examples show how to use javax.faces.context.FacesContext#responseComplete() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
private void downloadExcelSpreadsheet(List<SignupMeetingWrapper> smWrappers,
		String downloadType, String fileName) {

	FacesContext fc = FacesContext.getCurrentInstance();
	ServletOutputStream out = null;
	try {
		HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
		responseSettings(fileName, XLS_MIME_TYPE, response);
		out = response.getOutputStream();

		excelSpreadsheet(out, smWrappers, downloadType);

		out.flush();
	} catch (Exception ex) {
		log.warn("Error generating XLS spreadsheet for download event:" + ex.getMessage());
	} finally {
		if (out != null)
			closeStream(out);
	}
	fc.responseComplete();
}
 
Example 2
public void getResultsInCSV() {
    logger.info("getResultsInCSV invoked {}", System.getProperty("user.name"));
    try {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ExternalContext externalContext = facesContext.getExternalContext();
        externalContext.responseReset();
        String reportName = getExportFileName();
        externalContext.setResponseHeader("Content-Disposition", "attachment; filename=\"" + reportName + "\"");
        OutputStream output = externalContext.getResponseOutputStream();
        statisticsReportHandler.writeReport(output);
        facesContext.responseComplete();
    } catch (Exception e) {
        logger.error("Could not export report", e);
        BeanUtil.addErrorMessage("Could not export report", e.getMessage());
    }
}
 
Example 3
public void getExported() {

		try {
            FacesContext facesContext = FacesContext.getCurrentInstance();
            ExternalContext externalContext = facesContext.getExternalContext();
            externalContext.responseReset();
            externalContext.setResponseContentType("text/csv");
            String reportName = StatisticsUtils.createStatsPerTagsName();
            externalContext.setResponseHeader("Content-Disposition", "attachment; filename=\"" + reportName + "\"");

            OutputStream output = externalContext.getResponseOutputStream();
            StatisticsUtils.writeTagGroupReportToCsv(output, results);
            facesContext.responseComplete();
		} catch (IOException e) {

			logger.error("Could not export data to csv file", e);
			
			BeanUtil.addErrorMessage("Could not export statistics to csv file", "");
		}
		
	}
 
Example 4
public void getExported() {

		try {

            FacesContext facesContext = FacesContext.getCurrentInstance();
            ExternalContext externalContext = facesContext.getExternalContext();
            externalContext.responseReset();
            externalContext.setResponseContentType("text/csv");
            String reportName = StatisticsUtils.createScriptRunsHistoryName();
            externalContext.setResponseHeader("Content-Disposition", "attachment; filename=\"" + reportName + "\"");
            OutputStream output = externalContext.getResponseOutputStream();
            StatisticsUtils.writeScriptRunsHistory(BeanUtil.getSfContext(), output,
                                                   new ArrayList<>(Arrays.asList(selectedColumns)), lastResult,
                                                   exportWithTCs, exportWithActions, matrixInfo);
            facesContext.responseComplete();

		} catch (IOException e) {

			logger.error("Could not export data to csv file", e);

			BeanUtil.addErrorMessage("Could not export statistics to csv file", "");

		}
	}
 
Example 5
public void login() {

        FacesContext context = FacesContext.getCurrentInstance();
        Credential credential = new UsernamePasswordCredential(username, new Password(password));

        AuthenticationStatus status = securityContext.authenticate(
                getRequest(context),
                getResponse(context),
                withParams()
                        .credential(credential)
                        .newAuthentication(!continued)
                        .rememberMe(rememberMe)
        );

        LOG.info("authentication result:" + status);

        if (status.equals(SEND_CONTINUE)) {
            // Authentication mechanism has send a redirect, should not
            // send anything to response from JSF now.
            context.responseComplete();
        } else if (status.equals(SEND_FAILURE)) {
            addError(context, "Authentication failed");
        }

    }
 
Example 6
Source Project: ee8-sandbox   File: LoginBean.java    License: Apache License 2.0 6 votes vote down vote up
public void login() {

        FacesContext context = FacesContext.getCurrentInstance();
        Credential credential = new UsernamePasswordCredential(username, new Password(password));

        AuthenticationStatus status = securityContext.authenticate(
                getRequest(context),
                getResponse(context),
                withParams()
                        .credential(credential));

        LOG.info("authentication result:" + status);

        if (status.equals(SEND_CONTINUE)) {
            // Authentication mechanism has send a redirect, should not
            // send anything to response from JSF now.
            context.responseComplete();
        } else if (status.equals(SEND_FAILURE)) {
            addError(context, "Authentication failed");
        }

    }
 
Example 7
Source Project: ee8-sandbox   File: LoginBean.java    License: Apache License 2.0 6 votes vote down vote up
public void login() {

        FacesContext context = FacesContext.getCurrentInstance();
        Credential credential = new UsernamePasswordCredential(username, new Password(password));

        AuthenticationStatus status = securityContext.authenticate(
                getRequest(context),
                getResponse(context),
                withParams()
                        .credential(credential));

        LOG.log(Level.INFO, "authentication result:{0}", status);

        if (status.equals(SEND_CONTINUE)) {
            // Authentication mechanism has send a redirect, should not
            // send anything to response from JSF now.
            context.responseComplete();
        } else if (status.equals(SEND_FAILURE)) {
            addError(context, "Authentication failed");
        }

    }
 
Example 8
private void downloadExcelSpreadsheet(List<SignupMeetingWrapper> smWrappers,
		String downloadType, String fileName) {

	FacesContext fc = FacesContext.getCurrentInstance();
	ServletOutputStream out = null;
	try {
		HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
		responseSettings(fileName, XLS_MIME_TYPE, response);
		out = response.getOutputStream();

		excelSpreadsheet(out, smWrappers, downloadType);

		out.flush();
	} catch (Exception ex) {
		log.warn("Error generating XLS spreadsheet for download event:" + ex.getMessage());
	} finally {
		if (out != null)
			closeStream(out);
	}
	fc.responseComplete();
}
 
Example 9
Source Project: java2word   File: ReportCaller.java    License: MIT License 6 votes vote down vote up
public void runReport() throws IOException {
	log.info("Running Word Report...");

	FacesContext fc = FacesContext.getCurrentInstance();

	HttpServletResponse servletResponse = (HttpServletResponse) fc
			.getExternalContext().getResponse();

	servletResponse.setContentType("application/msword");
	servletResponse.setHeader("Content-disposition", "inline; filename="
			+ "myWordDocFromSeam.doc");

	PrintWriter writer = servletResponse.getWriter();

	//Create the word document
       IDocument myDoc = new Document2004();
       myDoc.getBody().addEle(new Heading1("Heading01"));
       myDoc.getBody().addEle(new BreakLine(2)); //two break lines
       myDoc.getBody().addEle(new Paragraph("This document is an example of paragraph"));

       String myWord = myDoc.getContent();

	writer.println(myWord);
	fc.responseComplete();

}
 
Example 10
Source Project: development   File: ExceptionHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 
 */
private static void handleOrganizationAuthoritiesException() {
    FacesContext fc = FacesContext.getCurrentInstance();
    // distinguish old/new portal by means of relative marketplace url
    HttpServletRequest request = JSFUtils.getRequest();
    if (request.getServletPath().startsWith(Marketplace.MARKETPLACE_ROOT)) {
        fc.getApplication()
                .getNavigationHandler()
                .handleNavigation(fc, "bean.actionName",
                        "InsufficientOrganizationAuthoritiesMPL");
    } else {
        fc.getApplication()
                .getNavigationHandler()
                .handleNavigation(fc, "bean.actionName",
                        "InsufficientOrganizationAuthorities");
    }
    fc.responseComplete();
}
 
Example 11
Source Project: development   File: ExceptionHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 
 */
public static void handleInvalidSession() {
    FacesContext fc = FacesContext.getCurrentInstance();
    // distinguish old/new portal by means of relative marketplace url
    HttpServletRequest request = JSFUtils.getRequest();
    if (request.getServletPath().startsWith(Marketplace.MARKETPLACE_ROOT)) {
        fc.getApplication()
                .getNavigationHandler()
                .handleNavigation(fc, "bean.actionName",
                        "marketplace/login");
    } else {
        fc.getApplication().getNavigationHandler()
                .handleNavigation(fc, "bean.actionName", "login");
    }
    fc.responseComplete();
}
 
Example 12
private void downloadCsvSpreadsheet(List<SignupMeetingWrapper> smWrappers, String fileName) {

		FacesContext fc = FacesContext.getCurrentInstance();
		ServletOutputStream out = null;
		try {
			HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
			responseSettings(fileName, CSV_MIME_TYPE, response);
			out = response.getOutputStream();

			csvSpreadsheet(out, smWrappers);

			out.flush();
		} catch (IOException ex) {
			log.warn("Error generating CSV spreadsheet for download event:" + ex.getMessage());
		} finally {
			if (out != null)
				closeStream(out);
		}
		fc.responseComplete();
	}
 
Example 13
/**
 * Send a warning message to user about failed ICS file generation
 * @param fileName
 * @param warningMsg
 */
protected void sendDownloadWarning(String fileName, String warningMsg) {

	FacesContext fc = FacesContext.getCurrentInstance();
	ServletOutputStream out = null;
	
	
	try {
		HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
		
		response.reset();
		response.setHeader("Pragma", "public");
		response.setHeader("Cache-Control","public, must-revalidate, post-check=0, pre-check=0, max-age=0"); 
		response.setContentType("text/plain");
		response.setHeader("Content-disposition", "attachment; filename=" + fileName);
		
		out = response.getOutputStream();
		warningMsg= warningMsg!=null? warningMsg:"Missing Scheduler tool on site";
		out.print(warningMsg);

		out.flush();
	} catch (IOException ex) {
		log.warn("Error generating file for download:" + ex.getMessage());
	} finally {
		try{
			if(out != null) {
				out.close();
			}
		}catch (Exception e){
			//do nothing;
		}
	}
	fc.responseComplete();
	
}
 
Example 14
public void exportExcel(ActionEvent event){
    log.debug("exporting as Excel: assessment id =  " + getAssessmentId());
    // allow local customization of spreadsheet output
    FacesContext faces = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse)faces.getExternalContext().getResponse();
    response.reset();	// Eliminate the added-on stuff
    response.setHeader("Pragma", "public");	// Override old-style cache control
    response.setHeader("Cache-Control", "public, must-revalidate, post-check=0, pre-check=0, max-age=0");	// New-style
   	writeDataToResponse(getSpreadsheetData(), getDownloadFileName(), response);
   	faces.responseComplete();
}
 
Example 15
public void downloadData(String key) {
    log.log(Level.INFO, "downloadData:: enter  key: " + key);
    byte[] res = modelTemplate.getData(key);
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    externalContext.setResponseHeader("Content-Length", String.valueOf(res.length));
    externalContext.setResponseHeader("Content-Disposition", "attachment;filename=\"" + key + "\"");
    try {
        externalContext.getResponseOutputStream().write(res);
    } catch (IOException e) {
        log.log(Level.WARNING,    "IOException during downloadData ");
        e.printStackTrace();
    }
    facesContext.responseComplete();
}
 
Example 16
/**
 * Send a file for download. 
 * 
 * @param filePath
 * 
 */
protected void sendDownload(String filePath, String mimeType) {

	FacesContext fc = FacesContext.getCurrentInstance();
	ServletOutputStream out = null;
	FileInputStream in = null;
	
	String filename = StringUtils.substringAfterLast(filePath, File.separator);
	
	try {
		HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
		
		response.reset();
		response.setHeader("Pragma", "public");
		response.setHeader("Cache-Control","public, must-revalidate, post-check=0, pre-check=0, max-age=0"); 
		response.setContentType(mimeType);
		response.setHeader("Content-disposition", "attachment; filename=" + filename);
		
		in = FileUtils.openInputStream(new File(filePath));
		out = response.getOutputStream();

		IOUtils.copy(in, out);

		out.flush();
	} catch (IOException ex) {
		log.warn("Error generating file for download:" + ex.getMessage());
	} finally {
		IOUtils.closeQuietly(in);
		IOUtils.closeQuietly(out);
	}
	fc.responseComplete();
	
}
 
Example 17
Source Project: development   File: OrganizationBean.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * execute navigation rule: go to destination specified for concurrent
 * modification situation
 */
void concurrentModification() {
    FacesContext ctx = FacesContext.getCurrentInstance();
    ctx.getApplication().getNavigationHandler()
            .handleNavigation(ctx, "", CONCURRENT_MODIFICATION_ERROR);
    ctx.responseComplete();
}
 
Example 18
public void exportExcel(ActionEvent event){
    log.debug("exporting as Excel: assessment id =  " + getAssessmentId());
    // allow local customization of spreadsheet output
    FacesContext faces = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse)faces.getExternalContext().getResponse();
    response.reset();	// Eliminate the added-on stuff
    response.setHeader("Pragma", "public");	// Override old-style cache control
    response.setHeader("Cache-Control", "public, must-revalidate, post-check=0, pre-check=0, max-age=0");	// New-style
   	writeDataToResponse(getSpreadsheetData(), getDownloadFileName(), response);
   	faces.responseComplete();
}
 
Example 19
public void afterPhase(PhaseEvent event) {
	FacesContext context = FacesContext.getCurrentInstance();
	Application app = context.getApplication();
	ValueBinding binding = app.createValueBinding("#{ForumTool}");
	DiscussionForumTool forumTool = (DiscussionForumTool) binding
			.getValue(context);
	Map requestParams = context.getExternalContext()
			.getRequestParameterMap();

	String action = (String) requestParams.get("action");
	String messageId = (String) requestParams.get("messageId");
	String topicId = (String) requestParams.get("topicId");
	String ajax = (String) requestParams.get("ajax");

	HttpServletResponse response = (HttpServletResponse)context.getExternalContext().getResponse();
	if ("true".equals(ajax)) {
		try {
			ServletOutputStream out = response.getOutputStream();
			response.setHeader("Pragma", "No-Cache");
			response.setHeader("Cache-Control",
					"no-cache,no-store,max-age=0");
			response.setDateHeader("Expires", 1);
			if (action == null) {
				out.println("FAIL");
			} else if ("markMessageAsRead".equals(action)) {
				// Ajax call to mark messages as read for user
				if (messageId != null && topicId != null) {
					if (!forumTool.isMessageReadForUser(Long.valueOf(topicId),
							Long.valueOf(messageId))) {
						forumTool.markMessageReadForUser(Long.valueOf(topicId),
								Long.valueOf(messageId), true);
						out.println("SUCCESS");
					} else {
						// also output success in case message is read, but
						// page rendered mail icon (old state)
						out.println("SUCCESS");
					}
				}
			}
			out.flush();
		} catch (Exception ee) {
			log.error(ee.getMessage(), ee);
		}
		context.responseComplete();
	}
	;
}
 
Example 20
Source Project: development   File: JSFUtils.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Writes the given content to the response as attachment of the given type
 * with the given filename.
 * 
 * @param content
 *            the data
 * @param filename
 *            the wanted filename
 * @param contentType
 *            the wanted content type
 * @throws IOException
 */
public static void writeContentToResponse(byte[] content, String filename,
        String contentType) throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    writeContentToResponse(content, filename, contentType, fc);
    fc.responseComplete();
}