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

The following examples show how to use javax.faces.context.FacesContext#getCurrentInstance() . 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
/**
 * 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 Project: sakai   File: TagUtil.java    License: 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 3
Source Project: jboss-daytrader   File: QuoteDataJSF.java    License: 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 4
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 5
Source Project: sakai   File: TagUtil.java    License: 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 6
Source Project: development   File: JSFUtils.java    License: 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 7
Source Project: development   File: SessionBean.java    License: 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 8
Source Project: development   File: BaseBean.java    License: 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 9
@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 10
@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 11
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 12
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 13
/**
 * 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 14
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 15
Source Project: sakai   File: TagUtil.java    License: 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 16
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 17
@Produces
@RequestScoped
public FacesContext produceFacesContext() {
    return FacesContext.getCurrentInstance();
}
 
Example 18
Source Project: development   File: TargetLocationBean.java    License: Apache License 2.0 4 votes vote down vote up
protected FacesContext getFacesContext() {
    return FacesContext.getCurrentInstance();
}
 
Example 19
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 20
@Override
protected FacesContext getFacesContext() {
	return FacesContext.getCurrentInstance();
}