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

The following examples show how to use javax.faces.context.FacesContext#getCurrentInstance() . 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 check out the related API usage on the sidebar.
Example 1
Source File: MultiResourceBundle.java    From web-budget with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Load the bundles by the name
 *
 * @param bundles the bundles to load
 */
private void load(String[] bundles) {

    final FacesContext facesContext = FacesContext.getCurrentInstance();

    for (String bundle : bundles) {

        final Locale locale;

        if (facesContext != null) {
            locale = facesContext.getApplication().getDefaultLocale();
        } else {
            locale = Locale.getDefault();
        }

        final ResourceBundle resourceBundle = ResourceBundle.getBundle(bundle, locale);

        resourceBundle.getKeys()
                .asIterator()
                .forEachRemaining(key -> this.combined.put(key, resourceBundle.getString(key)));
    }
}
 
Example 2
Source File: QuoteDataJSF.java    From jboss-daytrader with Apache License 2.0 6 votes vote down vote up
public String getQuotesBySymbols() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
    session.setAttribute("symbols", symbols);
    
    ArrayList quotes = new ArrayList();
    java.util.StringTokenizer st = new java.util.StringTokenizer(symbols, " ,");
    QuoteData[] quoteDatas = new QuoteData[6];
    int count = 0;
    while (st.hasMoreElements()) {
        String symbol = st.nextToken();
        TradeAction tAction = new TradeAction();            
        try {
            QuoteDataBean quoteData = tAction.getQuote(symbol);
            quoteDatas[count] =  new QuoteData(quoteData.getOpen(), quoteData.getPrice(), quoteData.getSymbol(), quoteData.getHigh(), quoteData.getLow(), quoteData.getCompanyName(),quoteData.getVolume(), quoteData.getChange());
            count ++;
        } catch (Exception e) {
            Log.error(e.toString());
        }
    }
    setQuotes(quoteDatas);
    return "quotes";
}
 
Example 3
Source File: TagUtil.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public static Boolean evalBoolean(String expression)
{
    if (expression == null)
    {
        return null;
    }
    if (UIComponentTag.isValueReference(expression))
    {
        FacesContext context = FacesContext.getCurrentInstance();
        Application app = context.getApplication();
        Object r = app.createValueBinding(expression).getValue(context);
        if (r == null)
        {
            return null;
        } else if (r instanceof Boolean)
        {
            return (Boolean) r;
        } else
        {
            return Boolean.valueOf(r.toString());
        }
    } else
    {
        return Boolean.valueOf(expression);
    }
}
 
Example 4
Source File: CustomExceptionHandler.java    From microprofile-starter with Apache License 2.0 5 votes vote down vote up
@Override
public void handle() throws FacesException {
    final Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator();
    while (i.hasNext()) {
        ExceptionQueuedEvent event = i.next();
        ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();

        // get the exception from context
        Throwable t = context.getException();

        FacesContext facesContext = FacesContext.getCurrentInstance();

        if (t instanceof ViewExpiredException) {
            try {

                String homeLocation = "/index.xhtml";
                facesContext.setViewRoot(facesContext.getApplication().getViewHandler().createView(facesContext, homeLocation));
                facesContext.getPartialViewContext().setRenderAll(true);
                String messageText = "Your session is expired and data is resetted.";
                FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, messageText, messageText);
                facesContext.addMessage(null, message);
                facesContext.renderResponse();

            } finally {
                //remove it from queue
                i.remove();
            }
        }
    }
    //parent handle
    getWrapped().handle();
}
 
Example 5
Source File: DeleteTemplateListener.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void processAction(ActionEvent ae) throws AbortProcessingException
{
  FacesContext context = FacesContext.getCurrentInstance();

  String deleteId = this.lookupTemplateBean(context).getIdString();
  if(!deleteTemplate(deleteId))
  {
    // todo: define package specific RuntimeException
    throw new RuntimeException("Cannot delete template.");
  }
  // reset template list
  TemplateListener lis = new TemplateListener();
  lis.processAction(null); 
}
 
Example 6
Source File: TagUtil.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public static Integer evalInteger(String expression)
{
  if (expression == null)
  {
    return null;
  }
  if (UIComponentTag.isValueReference(expression))
  {
    FacesContext context = FacesContext.getCurrentInstance();
    Application app = context.getApplication();
    Object r = app.createValueBinding(expression).getValue(context);
    if (r == null)
    {
      return null;
    }
    else if (r instanceof Integer)
    {
      return (Integer) r;
    }
    else
    {
      return new Integer(r.toString());
    }
  }
  else
  {
    return new Integer(expression);
  }
}
 
Example 7
Source File: EventBackingBean.java    From pragmatic-microservices-lab with MIT License 5 votes vote down vote up
public String handleEventSubmission() {

        VoyageNumber selectedVoyage = null;
        
        //Date completionTime = new SimpleDateFormat(ISO_8601_FORMAT).parse(completionDate);                                
        Date registrationTime = new Date();
        TrackingId trackingId = new TrackingId(trackId);
        UnLocode unLocode = new UnLocode(this.location);
        HandlingEvent.Type type = HandlingEvent.Type.valueOf(eventType);

        if (voyageNumber!= null) {  // Only Load & Unload could have a Voyage set
            selectedVoyage = new VoyageNumber(voyageNumber);
        }
        
        HandlingEventRegistrationAttempt attempt
                = new HandlingEventRegistrationAttempt(registrationTime, completionDate, trackingId, selectedVoyage, type, unLocode);
        
        applicationEvents.receivedHandlingEventRegistrationAttempt(attempt);

        voyageNumber = null;
        completionDate = null;
        unLocode = null;
        eventType = null;
        location = null;
        trackId = null;
        eventSubmitable = loadEventCondition = voyageSelectable = inputsOk = false; 

        FacesContext context = FacesContext.getCurrentInstance();
        context.addMessage(null, new FacesMessage("Event submitted", ""));

        return null;
    }
 
Example 8
Source File: AddResourcesListener.java    From BootsFaces-OSP with Apache License 2.0 5 votes vote down vote up
/**
 * Add the default datatables.net resource if and only if the user doesn't bring
 * their own copy, and if they didn't disallow it in the web.xml by setting the
 * context paramter net.bootsfaces.get_datatable_from_cdn to true.
 *
 * @param defaultFilename The URL of the file to be loaded
 * @param type            either "js" or "css"
 */
public static void addDatatablesResourceIfNecessary(String defaultFilename, String type) {
	boolean loadDatatables = shouldLibraryBeLoaded(P_GET_DATATABLE_FROM_CDN, true);
	// Do we have to add datatables.min.{css|js}, or are the resources already
	// there?
	FacesContext context = FacesContext.getCurrentInstance();
	UIViewRoot root = context.getViewRoot();

	String[] positions = { "head", "body", "form" };
	for (String position : positions) {
		if (loadDatatables) {
			List<UIComponent> availableResources = root.getComponentResources(context, position);
			for (UIComponent ava : availableResources) {
				if (ava.isRendered()) {
					String name = (String) ava.getAttributes().get("name");
					if (null != name) {
						name = name.toLowerCase();
						if (name.contains("datatables") && name.endsWith("." + type)) {
							loadDatatables = false;
							break;
						}
					}
				}
			}
		}
	}
	if (loadDatatables) {
		addResourceIfNecessary(defaultFilename);
	}
}
 
Example 9
Source File: SyllabusShowAreaTag.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public static void setValueBinding(UIComponent component,
    String attributeName, String attributeValue)
{
  FacesContext context = FacesContext.getCurrentInstance();
  Application app = context.getApplication();
  ValueBinding vb = app.createValueBinding(attributeValue);
  component.setValueBinding(attributeName, vb);
}
 
Example 10
Source File: Settings.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static ResourceBundle getBundle(Bundle bundle) {
	ResourceBundle result = null;
	try {
		result = CommonUtil.getBundle(WEB_ROOT_PACKAGE_NAME + "." + bundle.getVar(), Locale.ROOT);
	} catch (MissingResourceException e) {
	}
	if (result == null) {
		FacesContext context = FacesContext.getCurrentInstance();
		if (context != null) {
			result = context.getApplication().getResourceBundle(context, bundle.getVar());
		}
	}
	return result;
}
 
Example 11
Source File: ExtLibUtil.java    From XPagesExtensionLibrary with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked") // $NON-NLS-1$
public static Map<String,Object> getRequestScope() {
    FacesContext ctx = FacesContext.getCurrentInstance();
    if(ctx!=null) {
        return ctx.getExternalContext().getRequestMap();
    }
    return null;
}
 
Example 12
Source File: BookingBackingBean.java    From pragmatic-microservices-lab with MIT License 5 votes vote down vote up
public String register() {

        String trackingId = null;
        try {
            if (!originUnlocode.equals(destinationUnlocode)) {
                trackingId = bookingServiceFacade.bookNewCargo(
                        originUnlocode,
                        destinationUnlocode,
                        //new SimpleDateFormat(FORMAT).parse(arrivalDeadline));
                        //new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").parse(arrivalDeadline)); // davidd
                        arrivalDeadline);

            } else {
                // TODO See if this can be injected.
                FacesContext context = FacesContext.getCurrentInstance();
                // UI now prevents from selecting same origin/destination
                FacesMessage message = new FacesMessage("Origin and destination cannot be the same.");
                message.setSeverity(FacesMessage.SEVERITY_ERROR);
                context.addMessage(null, message);
                return null;
            }
        } catch (Exception e) {
            throw new RuntimeException("Error parsing date", e); // todo, not parsing anymore
        }
        //return "show_original.xhtml?faces-redirect=true&trackingId=" + trackingId;
        return "/admin/dashboard.xhtml";
    }
 
Example 13
Source File: BaseBean.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * Reset all resource bundles
 */
public void resetBundles() {
    FacesContext fc = FacesContext.getCurrentInstance();
    Iterator<Locale> it = fc.getApplication().getSupportedLocales();
    while (it.hasNext()) {
        Locale locale = it.next();
        ResourceBundle bundle = getResourceBundle(locale);
        if (bundle instanceof DbMessages) {
            ((DbMessages) bundle).resetProperties();
        }
    }
}
 
Example 14
Source File: SessionBean.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * @return true if the browser of the current user is an internet explorer
 */
public boolean isIe() {
    if (ie != null) {
        return ie.booleanValue();
    }
    FacesContext context = FacesContext.getCurrentInstance();
    if (context == null) {
        return false;
    }
    Object obj = context.getExternalContext().getRequest();
    if (!(obj instanceof HttpServletRequest)) {
        return false;
    }
    HttpServletRequest request = (HttpServletRequest) obj;

    // The user-agent string contains information about which
    // browser is used to view the pages
    String useragent = request.getHeader(USER_AGENT_HEADER);
    if (useragent == null) {
        ie = Boolean.FALSE;
        return ie.booleanValue();
    }
    if (useragent.toLowerCase().contains("msie")) {
        ie = Boolean.TRUE;
        return ie.booleanValue();
    }
    // Check if browser is IE11
    if (useragent.toLowerCase().contains("trident")
            && useragent.toLowerCase().contains("rv:11")) {
        ie = Boolean.TRUE;
    } else {
        ie = Boolean.FALSE;
    }
    return ie.booleanValue();
}
 
Example 15
Source File: JSFUtils.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that the view locale is equal to the user's locale
 * 
 */
public static void verifyViewLocale() {
    FacesContext fc = FacesContext.getCurrentInstance();

    HttpServletRequest request = (HttpServletRequest) fc
            .getExternalContext().getRequest();
    HttpSession session = request.getSession();
    String localeString = null;
    if (session != null) {
        localeString = (String) session.getAttribute("loggedInUserLocale");
    }

    // if the view locale differs from the users locale change the view
    // locale
    Locale locale = fc.getViewRoot().getLocale();
    if (localeString != null && !locale.toString().equals(localeString)) {
        Iterator<Locale> it = fc.getApplication().getSupportedLocales();
        while (it.hasNext()) {
            locale = it.next();
            if (locale.toString().equals(localeString)) {
                fc.getViewRoot().setLocale(locale);
                return;
            }
        }
        // we use the default locale if the requested locale was not
        // found
        if (!fc.getViewRoot().getLocale()
                .equals(fc.getApplication().getDefaultLocale())) {
            fc.getViewRoot().setLocale(
                    fc.getApplication().getDefaultLocale());
        }
    }
}
 
Example 16
Source File: TagUtil.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public static void setValueBinding(UIComponent component,
  String attributeName,
  String attributeValue)
{
  FacesContext context = FacesContext.getCurrentInstance();
  Application app = context.getApplication();
  ValueBinding vb = app.createValueBinding(attributeValue);
  component.setValueBinding(attributeName, vb);
}
 
Example 17
Source File: Captcha.java    From ctsms with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
protected FacesContext getFacesContext() {
	return FacesContext.getCurrentInstance();
}
 
Example 18
Source File: SimpleValuePickerData.java    From XPagesExtensionLibrary with Apache License 2.0 4 votes vote down vote up
public List<IPickerEntry> loadEntries(Object[] ids, String[] attributeNames) {
    FacesContext context = FacesContext.getCurrentInstance();
    List<IPickerEntry> entries = new ArrayList<IPickerEntry>(ids.length);
    for(int i=0; i<ids.length; i++) {
        entries.add(null);
    }
    String labelSep = getLabelSeparator();
    if(StringUtil.isEmpty(labelSep)) {
        labelSep = null;
    }
    final boolean searchLabel = labelSep!=null; 
    int start = 0;
    int count = Integer.MAX_VALUE;
    String startKey = null;
    for(int i=0; i<ids.length; i++) {
        Object key = ids[i];
        List<ShadowedObject> _shadowedData = pushVar(context, start, count, key, startKey);
        try {
            Object values = getValueList();
            if(values!=null) {
                boolean caseInsensitive = isCaseInsensitive();
                for(Iterator<Object> it=getIterator(values); it.hasNext(); ) {
                    Object o = it.next();
                    if(o!=null) {
                        IPickerEntry e = getEntry(o,labelSep);
                        if(e!=null) {
                            //String value = toString(searchLabel?e.getLabel():e.getValue());
                            String value = toString(e.getValue());
                            if(caseInsensitive) {
                                if(StringUtil.equalsIgnoreCase(value,ids[i].toString())) {
                                    entries.set(i,e);
                                    break;
                                }
                            } else {
                                if(StringUtil.equals(value,ids[i])) {
                                    entries.set(i,e);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        } finally {
            popVar(context,_shadowedData);
        }
    }
    // Sort the entries
    (new QuickSort.JavaList(entries) {
        @Override
        public int compare(Object o1, Object o2) {
            if(o1==null) {
                if(o2==null) return 0;
                return -1;
            }
            if(o2==null) {
                return 1;
            }
            String s1 = SimpleValuePickerData.toString(searchLabel ? ((IPickerEntry)o1).getLabel() : ((IPickerEntry)o1).getValue());
            String s2 = SimpleValuePickerData.toString(searchLabel ? ((IPickerEntry)o2).getLabel() : ((IPickerEntry)o2).getValue());
            return StringUtil.compareToIgnoreCase(s1, s2);
        }
    }).sort();
    return entries;
}
 
Example 19
Source File: TargetLocationBean.java    From development with Apache License 2.0 4 votes vote down vote up
protected FacesContext getFacesContext() {
    return FacesContext.getCurrentInstance();
}
 
Example 20
Source File: FacesContextProducer.java    From packt-java-ee-7-code-samples with GNU General Public License v2.0 4 votes vote down vote up
@Produces
@RequestScoped
public FacesContext produceFacesContext() {
    return FacesContext.getCurrentInstance();
}