Java Code Examples for javax.faces.context.FacesContext

The following examples show how to use javax.faces.context.FacesContext. 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: sailfish-core   Source File: TestScriptsBean.java    License: Apache License 2.0 6 votes vote down vote up
public void goEditMatrix() {

		long id = Long.parseLong(BeanUtil.getRequestParam("id"));
		logger.info("goEditMatrix invoked {} id[{}]", BeanUtil.getUser(), id);

		MatrixAdapter matrixAdapter = getMatrixAdapterById(id);

		if (matrixAdapter == null) {
			BeanUtil.showMessage(FacesMessage.SEVERITY_ERROR, "Matrix not found", "");
			return;
		}
		try {
			onChange(matrixAdapter);
			setMatrixToEdit(matrixAdapter);
			FacesContext.getCurrentInstance().getExternalContext().redirect(EXCEL_EDITOR);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			BeanUtil.showMessage(FacesMessage.SEVERITY_ERROR, "Error", e.getMessage());
		}

	}
 
Example 2
Source Project: sakai   Source File: TocTreeTag.java    License: Educational Community License v2.0 6 votes vote down vote up
/** 
 * @see javax.faces.webapp.UIComponentTag#setProperties(javax.faces.component.UIComponent)
 */
protected void setProperties(UIComponent component)
{
  super.setProperties(component);
  FacesContext context = getFacesContext();
  if (value != null)
  {
    ValueBinding vb = context.getApplication().createValueBinding(value);
    component.setValueBinding("value", vb);
  }
  if (var != null)
  {
    ((UIData) component).setVar(var);
  }

}
 
Example 3
Source Project: BootsFaces-OSP   Source File: DateTimeConverter.java    License: Apache License 2.0 6 votes vote down vote up
private String getAsStringValue(FacesContext facesContext, UIComponent uiComponent, Object value) {
	if (facesContext == null) {
		throw new NullPointerException("facesContext");
	}
	if (uiComponent == null) {
		throw new NullPointerException("uiComponent");
	}

	if (value == null) {
		return "";
	}
	if (value instanceof String) {
		return (String) value;
	}

	DateTimeFormatter format = getDateFormat(uiComponent);

	try {
		return format.print((ReadableInstant) value);
	}
	catch (Exception e) {
		throw new ConverterException("Cannot convert value '" + value + "'");
	}
}
 
Example 4
Source Project: deltaspike   Source File: JsfMessageResolver.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected List<String> getMessageSources(MessageContext messageContext)
{
    List<String> result = new ArrayList<String>(super.getMessageSources(messageContext) /*unmodifiable-list*/);

    FacesContext facesContext = FacesContext.getCurrentInstance();

    if (facesContext == null || facesContext.getCurrentPhaseId() == null)
    {
        return result;
    }

    String bundleName = facesContext.getApplication().getMessageBundle();

    if (bundleName != null)
    {
        result.add(bundleName);
    }
    result.add(FacesMessage.FACES_MESSAGES); //default messages from jsf

    return result;
}
 
Example 5
Source Project: BootsFaces-OSP   Source File: InputTextRenderer.java    License: Apache License 2.0 6 votes vote down vote up
/**
  * Add script to enable the input mask. If the mask attribute starts with {@code {}} the value is expected to be a
  * JSON object (and can for example be used to set a regular expression: {@code {regex:'[0-9\u0600-\u06FF]*'}}).
  * 
  * See https://github.com/RobinHerbots/Inputmask.
  * 
  * @param context
  * @param inputText
  * @param fieldId
  * @param rw
  * 
  * @throws IOException
  */
 protected void encodeMask(FacesContext context,
                           InputText inputText,
                           String fieldId,
                           ResponseWriter rw) throws IOException {
   if (inputText.getMask() != null && !inputText.getMask().isEmpty()) {
     rw.startElement("script", inputText);
     rw.writeText("Inputmask(", null);
     if (inputText.getMask().trim().startsWith("{")) {
rw.writeText(inputText.getMask().trim(), null);
     }
     else {
rw.writeText(String.format("\"%s\"", inputText.getMask().replace("\"", "\\\"")), null);
     }
     rw.writeText(").mask(document.getElementById(\"", null);
     rw.writeText(fieldId, null);
     rw.writeText("\"));", null);
     rw.endElement("script");
   }
 }
 
Example 6
Source Project: admin-template   Source File: CustomExceptionHandler.java    License: MIT License 6 votes vote down vote up
/**
 * @param context
 * @throws Throwable
 */
private void handleException(FacesContext context) {
    Iterator<ExceptionQueuedEvent> unhandledExceptionQueuedEvents = getUnhandledExceptionQueuedEvents().iterator();

    if (unhandledExceptionQueuedEvents.hasNext()) {
        Throwable exception = unhandledExceptionQueuedEvents.next().getContext().getException();
        unhandledExceptionQueuedEvents.remove();

        Throwable rootCause = Exceptions.unwrap(exception);

        if (rootCause instanceof BusinessException) {
            handleBusinessException(context, (BusinessException) rootCause);
            return;
        }

        //send user to error page when unexpected exceptions are raised
        goToErrorPage(context, rootCause);
    }

}
 
Example 7
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 8
private void encodeTooltip(FacesContext context, String targetId, String tooltipText) throws IOException {
	if (Settings.getBoolean(SettingCodes.ENABLE_TOOLTIPS, Bundle.SETTINGS, DefaultSettings.ENABLE_TOOLTIPS)) {
		String tooltipId = targetId + "_tooltip";
		ResponseWriter writer = context.getResponseWriter();
		writer.startElement("div", null);
		writer.writeAttribute("id", tooltipId, null);
		writer.writeAttribute("class", Tooltip.CONTAINER_CLASS, null);
		writer.writeText(tooltipText, null);
		writer.endElement("div");
		startScript(writer, tooltipId + "_script");
		writer.write("$(function() {");
		writer.write("PrimeFaces.cw('Tooltip','" + "widget_" + tooltipId + "',{");
		writer.write("id:'" + tooltipId + "'");
		writer.write(",target:'" + targetId + "'");
		writer.write(",showEffect:'fade'");
		writer.write(",hideEffect:'fade'");
		writer.write("});});");
		endScript(writer);
	}
}
 
Example 9
@Override
protected void writeHeaderPagerArea(FacesContext context, ResponseWriter w, AbstractDataView c, ViewDefinition viewDef, UIComponent pagerTop, UIComponent pagerTopLeft, UIComponent pagerTopRight) throws IOException {
        String tag = (String)getProperty(PROP_HEADER_PAGER_AREA_TAG);
        if(StringUtil.isNotEmpty(tag)) {
            startElement(w, tag, PROP_HEADERSTYLE, PROP_HEADERCLASS, PROP_HEADERDOJOTYPE);
            w.writeAttribute("role","navigation", null); // $NON-NLS-1$ $NON-NLS-2$
            w.writeAttribute("aria-label", "Paging", null); // $NON-NLS-1$ $NLS-OneUIv302ForumViewRenderer.Paging-2$
        }
        writeHeaderLeft(context, w, c, viewDef, pagerTopLeft);
        writeHeaderMiddle(context, w, c, viewDef, pagerTop);
        writeHeaderRight(context, w, c, viewDef, pagerTopRight);
        if(StringUtil.isNotEmpty(tag)) {
            w.endElement(tag);
        }
        newLine(w);
    }
 
Example 10
Source Project: sakai   Source File: ItemAuthorBean.java    License: Educational Community License v2.0 6 votes vote down vote up
public String doit() {
	if ("searchQuestionBank".equals(outcome)) {
		try {
			ExternalContext context = FacesContext.getCurrentInstance()
					.getExternalContext();
			context
					.redirect("sakai.questionbank.client.helper/authorIndex");
		} catch (Exception e) {
			log.error("fail to redirect to question bank: "
					+ e.getMessage());
		}
	}

	// navigation for ItemModifyListener
	return outcome;
}
 
Example 11
Source Project: sakai   Source File: AgentResults.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();
			if (itemGradingAttachmentList != null) {
				AttachmentUtil attachmentUtil = new AttachmentUtil();
				filePickerList = attachmentUtil.prepareReferenceList(itemGradingAttachmentList);
			}
			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 "sakai.filepicker.helper";
	}
 
Example 12
Source Project: XPagesExtensionLibrary   Source File: AbstractDataView.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object saveState(FacesContext context) {
    Object[] values = new Object[12];
    values[0] = super.saveState(context);
    values[1] = showItemsFlat;
    values[2] = StateHolderUtil.saveObjectState(context, summaryColumn);
    values[3] = collapsibleDetail;
    values[4] = detailsOnClient;
    values[5] = disableHideRow;
    values[6] = pageName;
    values[7] = openDocAsReadonly;
    values[8] = style;
    values[9] = styleClass;
    values[10] = rowStyle;
    values[11] = rowStyleClass;
   
    return values;
}
 
Example 13
Source Project: XPagesExtensionLibrary   Source File: TestProject.java    License: Apache License 2.0 6 votes vote down vote up
public static FacesContext createFacesContext(AbstractXspTest test,
        HttpServletRequest request) throws Exception {
    FacesController controller = (FacesController) test.getTestLocalVars().get("controller");
    if( null == controller ){
        bootstrap(test);
        controller = (FacesController) test.getTestLocalVars().get("controller");
    }
    LocalServletContext servletContext = (LocalServletContext) test.getTestLocalVars().get("servletContext");
    
    HttpServletResponse response = new LocalHttpServletResponse(servletContext, null);
    FacesContextFactory factory1 = (FacesContextFactory)FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
    
    FacesContext context = factory1.getFacesContext(servletContext, request, response, controller.getLifecycle());
    String sessionId = request.getSession().getId();
    SessionUtil.setSessionId(context, sessionId);
    
    test.getTestLocalVars().put("facesContext", context);
    return context;
}
 
Example 14
Source Project: sakai   Source File: TagUtil.java    License: Educational Community License v2.0 6 votes vote down vote up
/**
 * Set a MethodBinding on a component - used by tags setProperties() method.
 */
public static void setMethodBinding(UIComponent component, String name, String value,
        Class[] paramTypes)
{
    if (value == null)
    {
        return;
    }
    if (UIComponentTag.isValueReference(value))
    {
        FacesContext context = FacesContext.getCurrentInstance();
        Application app = context.getApplication();
        MethodBinding mb = app.createMethodBinding(value, paramTypes);
        component.getAttributes().put(name, mb);
    }
}
 
Example 15
public void keepAliveCallback() {
	FacesContext context = FacesContext.getCurrentInstance();
	Map map = context.getExternalContext().getRequestParameterMap();
	String ajaxKeepAliveJsCallback = (String) map.get(JSValues.AJAX_KEEP_ALIVE_JS_CALLBACK.toString());
	String ajaxKeepAliveJsCallbackArgs = (String) map.get(JSValues.AJAX_KEEP_ALIVE_JS_CALLBACK_ARGS.toString());
	RequestContext requestContext = RequestContext.getCurrentInstance();
	if (requestContext != null) {
		requestContext.addCallbackParam(JSValues.AJAX_OPERATION_SUCCESS.toString(), true);
		requestContext.addCallbackParam(JSValues.AJAX_KEEP_ALIVE_JS_CALLBACK.toString(), ajaxKeepAliveJsCallback);
		if (ajaxKeepAliveJsCallbackArgs != null) {
			requestContext.addCallbackParam(JSValues.AJAX_KEEP_ALIVE_JS_CALLBACK_ARGS.toString(), ajaxKeepAliveJsCallbackArgs);
		}
	}
}
 
Example 16
Source Project: XPagesExtensionLibrary   Source File: ObjectDataSource.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void refresh() {
    // instead of delegate to superclass, copy template in
    // com.ibm.xsp.extlib.model.DataAccessorSource.refresh()
    // to do a reduced refresh, that clears
    // the current value but doesn't re-load.
    FacesContext context = getFacesContext();
    if (context == null)
        return;

    // clear the current value
    putDataContainer(context, null);
}
 
Example 17
Source Project: sakai   Source File: QuestionPoolBean.java    License: Educational Community License v2.0 5 votes vote down vote up
public void setOutComeParams(String outcome){
	if(outcome==null){
		setOutcome((String) FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("outCome"));
	}else{
		setOutcome(outcome);
	}
	setOutcomePool((getCurrentPool()!=null)?getCurrentPool().getId():0);
}
 
Example 18
Source Project: oxTrust   Source File: MetadataFilterConverter.java    License: MIT License 5 votes vote down vote up
public Object getAsObject(FacesContext arg0, UIComponent arg1, String metadataFilterName) {
	List<MetadataFilter> filters = filterService.getAvailableMetadataFilters();
	for (MetadataFilter filter : filters) {
		if (filter.getName().equals(metadataFilterName)) {
			return filter;
		}
	}
	return null;
}
 
Example 19
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
	if (Money.class.isInstance(value)) {
		return Money.class.cast(value).getNumber().toString();
	}
	return null;
}
 
Example 20
Source Project: BootsFaces-OSP   Source File: GenContainerDiv.java    License: Apache License 2.0 5 votes vote down vote up
@Override
  public void encodeEnd(FacesContext context) throws IOException {
      if (!isRendered()) {
          return;
      }
      context.getResponseWriter()
             .endElement("div");
Tooltip.activateTooltips(context, this);

  }
 
Example 21
Source Project: XPagesExtensionLibrary   Source File: BeanNamePickerData.java    License: Apache License 2.0 5 votes vote down vote up
protected INamePickerData getBeanInstance() {
    if(bean==null) {
        String beanName = getDataBean();
        Object b = ManagedBeanUtil.getBean(FacesContext.getCurrentInstance(), beanName);
        if(b!=null) {
            if(!(b instanceof INamePickerData)) {
                throw new FacesExceptionEx(null,"Bean {0}({1}) is not a INamePickerData",beanName,b.getClass()); // $NLX-BeanNamePickerData.Bean01isnotaINamePickerData-1$
            }
            bean = (INamePickerData)b;
        } else {
            throw new FacesExceptionEx(null,"Bean {0} does not exist",beanName); // $NLX-BeanNamePickerData.Bean0doesnotexist-1$
        }
    }
    return bean;
}
 
Example 22
Source Project: XPagesExtensionLibrary   Source File: UITagCloud.java    License: Apache License 2.0 5 votes vote down vote up
public boolean isSliderVisible() {
	if (null != this.sliderVisible) {
		return this.sliderVisible;
	}
	ValueBinding _vb = getValueBinding("sliderVisible"); //$NON-NLS-1$
	if (_vb != null) {
		Boolean val = (java.lang.Boolean) _vb.getValue(FacesContext.getCurrentInstance());
		if(val!=null) {
			return val;
		}
	} 
	return false;
}
 
Example 23
Source Project: XPagesExtensionLibrary   Source File: AnimationProps.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object saveState(FacesContext context) {
       Object[] state = new Object[5];
       state[0] = super.saveState(context);
       state[1] = name;
       state[2] = start;
       state[3] = end;
       state[4] = unit;
       return state;
   }
 
Example 24
Source Project: joinfaces   Source File: ViewScopeTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRegisterDestructionCallback() {
	UIViewRoot viewRoot = FacesContext.getCurrentInstance().getViewRoot();
	doCallRealMethod().when(viewRoot).subscribeToViewEvent(any(), any());
	doCallRealMethod().when(viewRoot).unsubscribeFromViewEvent(any(), any());
	when(viewRoot.getViewListenersForEventClass(any())).thenCallRealMethod();

	this.viewScope.registerDestructionCallback(KEY, () -> {
	});

	this.viewScope.remove(KEY);
}
 
Example 25
Source Project: sakai   Source File: SyllabusIfNotRender.java    License: Educational Community License v2.0 5 votes vote down vote up
public void encodeBegin(FacesContext context, UIComponent component)
throws IOException
{
  ResponseWriter writer = context.getResponseWriter();
  
  String test = (String) component.getAttributes().get("test");
  if(test!=null)
    test = test.trim();
  
  if((test!=null) && (!test.equals("")))
  {
    writer.write("<div>");
  }
}
 
Example 26
Source Project: sakai   Source File: RendererUtil.java    License: Educational Community License v2.0 5 votes vote down vote up
/**
 * Write default HTML passthrough attributes
 */
public static void writePassthroughs(FacesContext context, UIComponent component)
        throws IOException
{
    String[] passthrus = { "ondblclick", "onclick", "onkeydown", "onkeypress", "onkeyup",
            "onmousedown", "onmousemove", "onmouseout", "onmouseover", "onmouseup" };
    writePassthroughAttributes(passthrus, true, context, component);
}
 
Example 27
public boolean isAutoCommit() {
    if (null != this.autoCommit) {
        return this.autoCommit;
    }
    ValueBinding _vb = getValueBinding("autoCommit"); //$NON-NLS-1$
    if (_vb != null) {
        Boolean val = (java.lang.Boolean) _vb.getValue(FacesContext.getCurrentInstance());
        if(val!=null) {
            return val;
        }
    } 
    return false;
}
 
Example 28
Source Project: BootsFaces-OSP   Source File: Datepicker.java    License: Apache License 2.0 5 votes vote down vote up
public void processEvent(ComponentSystemEvent event) throws AbortProcessingException {
	if (isAutoUpdate()) {
		if (FacesContext.getCurrentInstance().isPostback()) {
			FacesContext.getCurrentInstance().getPartialViewContext().getRenderIds().add(getClientId());
		}
		super.processEvent(event);
	}
}
 
Example 29
Source Project: XPagesExtensionLibrary   Source File: UIApplication.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void restoreState(FacesContext _context, Object _state) {
	Object _values[] = (Object[]) _state;
	super.restoreState(_context, _values[0]);
	this.selectedPageName = (String)_values[1];
       this.onOrientationChange = (String) _values[2];
       this.onResize = (String) _values[3];
}
 
Example 30
public String getOnKeyUp() {
	if (null != this.onKeyUp) {
		return this.onKeyUp;
	}
	ValueBinding _vb = getValueBinding("onKeyUp"); //$NON-NLS-1$
	if (_vb != null) {
		return (java.lang.String) _vb.getValue(FacesContext.getCurrentInstance());
	} else {
		return null;
	}
}