Java Code Examples for javax.faces.context.ExternalContext

The following examples show how to use javax.faces.context.ExternalContext. 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
Source Project: softwarecave   Source File: Headers.java    License: GNU General Public License v3.0 6 votes vote down vote up
@PostConstruct
public void init() {
    entries = new ArrayList<>();
    ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
    HttpServletRequest request = (HttpServletRequest) context.getRequest();
    
    Enumeration<String> namesIt = request.getHeaderNames();
    while (namesIt.hasMoreElements()) {
        String name = namesIt.nextElement();
        Enumeration<String> valueIt = request.getHeaders(name);
        while (valueIt.hasMoreElements()) {
            String value = valueIt.nextElement();
            entries.add(new HeaderEntry(name, value));
        }
    }
}
 
Example 2
Source Project: sailfish-core   Source File: StatisticsReportingBean.java    License: Apache License 2.0 6 votes vote down vote up
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
Source Project: sakai   Source File: StudentScoresBean.java    License: Educational Community License v2.0 6 votes vote down vote up
public String addAttachmentsRedirect() {
 // 1. redirect to add attachment
 try	{
  List filePickerList = new ArrayList();
  StudentScoresBean studentScoresBean = (StudentScoresBean) ContextUtil.lookupBean("studentScores");
  Long itemGradingId = studentScoresBean.getItemGradingIdForFilePicker();
  DeliveryBean deliveryBean = (DeliveryBean) ContextUtil.lookupBean("delivery");
  ItemContentsBean itemContentsBean = (ItemContentsBean) deliveryBean.getItemContentsMap().get(itemGradingId);
  if (itemContentsBean != null && itemContentsBean.getItemGradingAttachmentList() != null){
	  AttachmentUtil attachmentUtil = new AttachmentUtil();
	  filePickerList = attachmentUtil.prepareReferenceList(itemContentsBean.getItemGradingAttachmentList());
  }
  ToolSession currentToolSession = SessionManager.getCurrentToolSession();
  currentToolSession.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, filePickerList);
  
  currentToolSession.setAttribute("itemGradingId", itemGradingId);
  ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
  context.redirect("sakai.filepicker.helper/tool");
 }
 catch(Exception e){
  log.error("fail to redirect to attachment page: " + e.getMessage());
 }
 return "studentScores";
}
 
Example 4
Source Project: sakai   Source File: StudentScoresBean.java    License: Educational Community License v2.0 6 votes vote down vote up
public String addAttachmentsRedirect() {
 // 1. redirect to add attachment
 try	{
  List filePickerList = new ArrayList();
  StudentScoresBean studentScoresBean = (StudentScoresBean) ContextUtil.lookupBean("studentScores");
  Long itemGradingId = studentScoresBean.getItemGradingIdForFilePicker();
  DeliveryBean deliveryBean = (DeliveryBean) ContextUtil.lookupBean("delivery");
  ItemContentsBean itemContentsBean = (ItemContentsBean) deliveryBean.getItemContentsMap().get(itemGradingId);
  if (itemContentsBean != null && itemContentsBean.getItemGradingAttachmentList() != null){
	  AttachmentUtil attachmentUtil = new AttachmentUtil();
	  filePickerList = attachmentUtil.prepareReferenceList(itemContentsBean.getItemGradingAttachmentList());
  }
  ToolSession currentToolSession = SessionManager.getCurrentToolSession();
  currentToolSession.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, filePickerList);
  
  currentToolSession.setAttribute("itemGradingId", itemGradingId);
  ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
  context.redirect("sakai.filepicker.helper/tool");
 }
 catch(Exception e){
  log.error("fail to redirect to attachment page: " + e.getMessage());
 }
 return "studentScores";
}
 
Example 5
Source Project: sakai   Source File: AgentResults.java    License: Educational Community License v2.0 6 votes vote down vote up
public String addAssessmentAttachmentsRedirect() {
 // 1. redirect to add attachment
 try	{
  List<Reference> filePickerList = new ArrayList<>();
  if (assessmentGradingAttachmentList != null){
	  AttachmentUtil attachmentUtil = new AttachmentUtil();
	  filePickerList = attachmentUtil.prepareReferenceList(assessmentGradingAttachmentList);
  }
  ToolSession currentToolSession = SessionManager.getCurrentToolSession();
  currentToolSession.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, filePickerList);
  
  currentToolSession.setAttribute("assessmentGradingId", assessmentGradingId);
  ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
  context.redirect("sakai.filepicker.helper/tool");
 }
 catch(Exception e){
  log.error("fail to redirect to attachment page: " + e.getMessage());
 }
 return "sakai.filepicker.helper";
}
 
Example 6
Source Project: lams   Source File: FacesWebRequest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public String getDescription(boolean includeClientInfo) {
	ExternalContext externalContext = getExternalContext();
	StringBuilder sb = new StringBuilder();
	sb.append("context=").append(externalContext.getRequestContextPath());
	if (includeClientInfo) {
		Object session = externalContext.getSession(false);
		if (session != null) {
			sb.append(";session=").append(getSessionId());
		}
		String user = externalContext.getRemoteUser();
		if (StringUtils.hasLength(user)) {
			sb.append(";user=").append(user);
		}
	}
	return sb.toString();
}
 
Example 7
public static void registerFacesDependencies(ConfigurableListableBeanFactory beanFactory) {
	beanFactory.registerResolvableDependency(FacesContext.class, new ObjectFactory<FacesContext>() {
		@Override
		public FacesContext getObject() {
			return FacesContext.getCurrentInstance();
		}
		@Override
		public String toString() {
			return "Current JSF FacesContext";
		}
	});
	beanFactory.registerResolvableDependency(ExternalContext.class, new ObjectFactory<ExternalContext>() {
		@Override
		public ExternalContext getObject() {
			return FacesContext.getCurrentInstance().getExternalContext();
		}
		@Override
		public String toString() {
			return "Current JSF ExternalContext";
		}
	});
}
 
Example 8
Source Project: deltaspike   Source File: JsfUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static Set<RequestParameter> getViewConfigPageParameters()
{
    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();

    Set<RequestParameter> result = new HashSet<RequestParameter>();

    if (externalContext == null || //detection of early config for different mojarra versions
            externalContext.getRequestParameterValuesMap() == null || externalContext.getRequest() == null)
    {
        return result;
    }

    NavigationParameterContext navigationParameterContext =
            BeanProvider.getContextualReference(NavigationParameterContext.class);

    for (Map.Entry<String, String> entry : navigationParameterContext.getPageParameters().entrySet())
    {
        //TODO add multi-value support
        result.add(new RequestParameter(entry.getKey(), new String[]{entry.getValue()}));
    }

    return result;
}
 
Example 9
Source Project: ctsms   Source File: ValidatorUtil.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
public static boolean skipValidation(final FacesContext context) {
	final ExternalContext externalContext = context.getExternalContext();
	final Object validate = externalContext.getRequestMap().get(GetParamNames.VALIDATE.toString());
	if (validate != null) {
		return !(Boolean) validate;
	}
	Iterator<Entry<String, String[]>> parameterValuesIt = externalContext.getRequestParameterValuesMap()
			.entrySet().iterator();
	while (parameterValuesIt.hasNext()) {
		Entry<String, String[]> parameterValues = parameterValuesIt.next();
		final String key = parameterValues.getKey();
		Iterator<String> idPrefixIt = VALIDATION_REQUIRED_COMPONENT_ID_PREFIXES.iterator();
		while (idPrefixIt.hasNext()) {
			String idPrefix = idPrefixIt.next();
			if (key.contains(idPrefix)) {
				externalContext.getRequestMap().put(GetParamNames.VALIDATE.toString(), Boolean.TRUE);
				return false;
			}
		}
	}
	externalContext.getRequestMap().put(GetParamNames.VALIDATE.toString(), Boolean.FALSE);
	return true;
}
 
Example 10
Source Project: primefaces-blueprints   Source File: ProductsDAO.java    License: The Unlicense 6 votes vote down vote up
public List<Product> getAllProducts(int first, int pageSize,
		String sortField, String sortOrderValue, Map<String, Object> filters) {
	Session session = getSession();// sessionFactory.openSession();
	session.beginTransaction();

	ExternalContext externalContext = FacesContext.getCurrentInstance()
			.getExternalContext();
	Map<String, Object> sessionMap = externalContext.getSessionMap();
	productCategory = (String) sessionMap.get("productCategory");
	String query = null;
	
	Query queryResult=null;
	if (productCategory != "") {
		query = "from Product where prodcat = :productCategory ORDER BY "+sortField+" "+sortOrderValue;
		queryResult = session.createQuery(query);
		queryResult.setParameter("productCategory", productCategory);
	} else {
		query = "from Product ORDER BY "+sortField+" "+sortOrderValue;
	    queryResult = session.createQuery(query);
	}
	List<Product> allProducts = queryResult.list();
	session.getTransaction().commit();
	return allProducts;

}
 
Example 11
Source Project: sakai   Source File: SyllabusTool.java    License: Educational Community License v2.0 6 votes vote down vote up
public String processAddAttachRedirect()
{
  try
  {
    filePickerList = EntityManager.newReferenceList();
    ToolSession currentToolSession = SessionManager.getCurrentToolSession();
    currentToolSession.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, filePickerList);
    ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
    context.redirect("sakai.filepicker.helper/tool");
    if(context.getRequestParameterMap().get("itemId") != null){
  	  currentToolSession.setAttribute(SESSION_ATTACHMENT_DATA_ID, context.getRequestParameterMap().get("itemId"));
    }
    return null;
  }
  catch(Exception e)
  {
    log.error(this + ".processAddAttachRedirect - " + e);
    return null;
  }
}
 
Example 12
Source Project: sakai   Source File: SyllabusTool.java    License: Educational Community License v2.0 6 votes vote down vote up
public String processDeleteAttach() {
  ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
  String attachId = null;
  
  Map paramMap = context.getRequestParameterMap();
  Iterator itr = paramMap.keySet().iterator();
  while(itr.hasNext()) {
    Object key = itr.next();
    if( key instanceof String && "syllabus_current_attach".equals((String) key)) {
        attachId = (String) paramMap.get(key);
        break;
    }
  }

  removeAttachId = attachId;

  if (StringUtils.isNotBlank(removeAttachId)) {
    return "remove_attach_confirm";
  } else {
    return null;
  }

}
 
Example 13
Source Project: deltaspike   Source File: ClientWindowHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Handles the initial redirect for the LAZY mode, if no windowId is available in the current request URL.
 *
 * @param facesContext the {@link FacesContext}
 * @param newWindowId the new windowId
 */
public static void handleInitialRedirect(FacesContext facesContext, String newWindowId)
{        
    // store the new windowId as context attribute to prevent infinite loops
    // #sendRedirect will append the windowId (from ClientWindow#getWindowId again) to the redirectUrl
    facesContext.getAttributes().put(INITIAL_REDIRECT_WINDOW_ID, newWindowId);

    ExternalContext externalContext = facesContext.getExternalContext();

    String url = constructRequestUrl(externalContext);

    // remember the initial redirect windowId till the next request - see #729
    addRequestWindowIdCookie(facesContext, newWindowId, newWindowId);

    try
    {
        externalContext.redirect(url);
    }
    catch (IOException e)
    {
        throw new FacesException("Could not send initial redirect!", e);
    }
}
 
Example 14
Source Project: yawl   Source File: FormViewer.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/** takes necessary action after editing a custom form */
private String postCustomForm(WorkItemRecord wir) {
    String result = "<success/>";

    // reset session timeout if previously changed
    if (_sb.isSessionTimeoutValueChanged()) {
        _sb.resetSessionTimeout();
        _sb.setSessionTimeoutValueChanged(false);
    }

    // retrieve completion flag - if any
    ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
    HttpServletRequest request = (HttpServletRequest) context.getRequest();
    String complete = request.getParameter("complete");

    // complete wir if requested
    if ((complete != null) && complete.equalsIgnoreCase("true")) {
        result = completeWorkItem(wir);
    }
    return result;
}
 
Example 15
Source Project: joinfaces   Source File: WindowScopeTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeEach
public void setUp() throws MalformedURLException {
	FacesContext facesContext = FacesContextMocker.mockFacesContext();
	ExternalContext externalContext = mock(ExternalContext.class);
	when(facesContext.getExternalContext()).thenReturn(externalContext);
	when(externalContext.getResource("/WEB-INF/portlet.xml")).thenReturn(null);
	Application application = mock(Application.class);
	when(facesContext.getApplication()).thenReturn(application);

	this.scopeMap = new WindowScopeManager.ScopeMap(FacesContext.getCurrentInstance());

	this.windowScope = new WindowScope() {
		@Override
		@NonNull
		WindowScopeManager.ScopeMap getScopeMap() {
			return WindowScopeTest.this.scopeMap;
		}
	};
}
 
Example 16
Source Project: sakai   Source File: PostemTool.java    License: Educational Community License v2.0 6 votes vote down vote up
public String processAddAttachRedirect()
	  {
	    try
	    {
	      filePickerList = EntityManager.newReferenceList();
	      ToolSession currentToolSession = SessionManager.getCurrentToolSession();
	      currentToolSession.setAttribute("filepicker.attach_cardinality",FilePickerHelper.CARDINALITY_SINGLE);	      
	      currentToolSession.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, filePickerList);
	      ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
	      context.redirect("sakai.filepicker.helper/tool");
	      return null;
}
	    catch(Exception e)
	    {
	      log.error(this + ".processAddAttachRedirect - " + e);
	      return null;
	    }
	  }
 
Example 17
Source Project: development   Source File: ServiceDetailsCtrl.java    License: Apache License 2.0 6 votes vote down vote up
public String redirectToServiceDetails() {
    logger.logDebug("entering redirectToServiceDetails");
    FacesContext context = FacesContext.getCurrentInstance();
    ExternalContext extContext = context.getExternalContext();
    String viewId = Marketplace.MARKETPLACE_ROOT + "/serviceDetails.jsf";

    try {
        viewId = extContext.getRequestContextPath()
                + viewId
                + ui.getSelectedServiceKeyQueryPart(String.valueOf(model
                        .getSelectedServiceKey()))
                + ui.getMarketplaceIdQueryPart();
        String urlLink = context.getExternalContext().encodeActionURL(
                viewId);
        JSFUtils.redirect(extContext, urlLink);
    } catch (IOException e) {
        extContext.log(
                getClass().getName() + ".redirectToServiceDetails()", e);
    } finally {
        // reset requested key;
        model.setSelectedServiceKey(null);
    }
    return null;
}
 
Example 18
Source Project: development   Source File: CaptchaValidatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    validator = new CaptchaValidator();
    sessionMock = new HttpSessionStub(Locale.ENGLISH);
    context = new FacesContextStub(Locale.ENGLISH) {
        @Override
        public ExternalContext getExternalContext() {
            ExternalContext exContext = spy(new ExternalContextStub(
                    Locale.ENGLISH));
            doReturn(sessionMock).when(exContext).getSession(false);
            return exContext;
        }
    };

    inputField = new HtmlInputText() {
        @Override
        public String getClientId(FacesContext ctx) {
            return "";
        }
    };
}
 
Example 19
private boolean isMobilePage(FacesContext context) {
    ExternalContext o = context.getExternalContext();
    HttpServletRequest r = (javax.servlet.http.HttpServletRequest) o.getRequest();
    String path = r.getServletPath();
    ApplicationEx app = ApplicationEx.getInstance(context);
    String prefix = app.getApplicationProperty(MobileConstants.XSP_THEME_MOBILE_PAGEPREFIX, null);
    if (prefix == null) {
        return false;
    }
    else if (prefix.equals("*")) { // $NON-NLS-1$
        return true;
    }
    else {
        return path.startsWith("/" + prefix); // $NON-NLS-1$
    }
}
 
Example 20
Source Project: sakai   Source File: EmailBean.java    License: Educational Community License v2.0 6 votes vote down vote up
public String addAttachmentsRedirect() {
    try	{
      List filePickerList = new ArrayList();
      if (attachmentList != null){
        filePickerList = prepareReferenceList(attachmentList);
      }
      log.debug("**filePicker list="+filePickerList.size());
      ToolSession currentToolSession = SessionManager.getCurrentToolSession();
      currentToolSession.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, filePickerList);
      ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
      context.redirect("sakai.filepicker.helper/tool");
    }
    catch(Exception e){
      log.error("fail to redirect to attachment page: " + e.getMessage());
    }
    return "email";
}
 
Example 21
Source Project: primefaces-blueprints   Source File: TransactionSummaryDAO.java    License: The Unlicense 5 votes vote down vote up
public TransactionSummaryDAO() {
	super();
	// TODO Auto-generated constructor stub
	ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
	Map<String, Object> sessionMap = externalContext.getSessionMap();
	investmentNumber=(String) sessionMap.get("investmentNumber");
}
 
Example 22
Source Project: oxAuth   Source File: GlobalExceptionHandler.java    License: MIT License 5 votes vote down vote up
private void performRedirect(ExternalContext externalContext, String viewId) {
    try {
        externalContext.redirect(externalContext.getRequestContextPath() + viewId);
    } catch (Exception e) {
        log.error("Can't perform redirect to viewId: " + viewId, e);
    }
}
 
Example 23
Source Project: spring-analysis-note   Source File: FacesRequestAttributes.java    License: MIT License 5 votes vote down vote up
@Override
public Object getSessionMutex() {
	// Enforce presence of a session first to allow listeners to create the mutex attribute
	ExternalContext externalContext = getExternalContext();
	Object session = externalContext.getSession(true);
	Object mutex = externalContext.getSessionMap().get(WebUtils.SESSION_MUTEX_ATTRIBUTE);
	if (mutex == null) {
		mutex = (session != null ? session : externalContext);
	}
	return mutex;
}
 
Example 24
/**
 * Delegate the permission update job to sakai-permissions-helper tool
 */
private String doPermissions(String siteRef, String description) {
	try {
		ToolSession currentToolSession = SessionManager.getCurrentToolSession();
		currentToolSession.setAttribute(PermissionsHelper.PREFIX, "signup.");
		currentToolSession.setAttribute(PermissionsHelper.TARGET_REF, siteRef);
		currentToolSession.setAttribute(PermissionsHelper.DESCRIPTION, description);
		ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
		context.redirect("sakai.permissions.helper.helper/tool");
	} catch (Exception e) {
		log.error(this + ".processPermissionUpdateRedirect - " + e);
	}

	return null;
}
 
Example 25
/**
 * Handle the navigation
 * 
 * @param context
 *        The Faces context.
 * @param fromAction
 *        The action string that triggered the action.
 * @param outcome
 *        The logical outcome string, which is the new tool mode, or if null, the mode does not change.
 */
public void handleNavigation(FacesContext context, String fromAction, String outcome)
{
	m_chain.handleNavigation(context, fromAction, outcome);		
	
	ExternalContext exContext = context.getExternalContext();
   HttpSession session = (HttpSession) exContext.getSession(false);

   if (session == null){
     return;
   }
	
	// add previous navigationString (outcome) to session
	session.setAttribute("MC_PREVIOUS_NAV", outcome);
}
 
Example 26
Source Project: sakai   Source File: CalendarBean.java    License: Educational Community License v2.0 5 votes vote down vote up
public void selectEvent(ActionEvent e) {
	try{
		ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
		Map paramMap = context.getRequestParameterMap();
		selectedCalendarRef = (String) paramMap.get("calendarRef");
		selectedEventRef = (String) paramMap.get("eventRef");
		selectedEvent = null;
		updateEventList = false;
	}catch(Exception ex){
		log.error("Error getting selectedEventRef: {}", ex.toString());
	}
}
 
Example 27
Source Project: sakai   Source File: SiteListBean.java    License: Educational Community License v2.0 5 votes vote down vote up
public String processActionUserId() {
	try{
		ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
		Map paramMap = context.getRequestParameterMap();
		userId = (String) paramMap.get("userId");
		refreshQuery = true;
		return "sitelist";
	}catch(Exception e){
		log.error("Error getting userId var.");
		return "userlist";
	}
}
 
Example 28
Source Project: java-technology-stack   Source File: FacesRequestAttributes.java    License: MIT License 5 votes vote down vote up
@Override
public Object getSessionMutex() {
	// Enforce presence of a session first to allow listeners to create the mutex attribute
	ExternalContext externalContext = getExternalContext();
	Object session = externalContext.getSession(true);
	Object mutex = externalContext.getSessionMap().get(WebUtils.SESSION_MUTEX_ATTRIBUTE);
	if (mutex == null) {
		mutex = (session != null ? session : externalContext);
	}
	return mutex;
}
 
Example 29
Source Project: sakai   Source File: PrivateMessagesTool.java    License: Educational Community License v2.0 5 votes vote down vote up
public String processAddAttachmentRedirect()
{
  log.debug("processAddAttachmentRedirect()");
  try
  {
    ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
    context.redirect("sakai.filepicker.helper/tool");
    return null;
  }
  catch(Exception e)
  {
    log.debug("processAddAttachmentRedirect() - Exception");
    return null;
  }
}
 
Example 30
Source Project: oxTrust   Source File: GlobalExceptionHandler.java    License: MIT License 5 votes vote down vote up
private void performRedirect(ExternalContext externalContext, String viewId) {
    try {
        externalContext.redirect(externalContext.getRequestContextPath() + viewId);
    } catch (Exception e) {
        log.trace("Can't perform redirect to viewId: " + viewId, e);
    }
}