Java Code Examples for javax.faces.FacesException

The following are top voted examples for showing how to use javax.faces.FacesException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: sakai   File: SakaiViewHandler.java   Source Code and License 7 votes vote down vote up
public void renderView(FacesContext context, UIViewRoot root) throws IOException, FacesException {
	// SAK-20286 start
	// Get the request
	HttpServletRequest req = (HttpServletRequest) context.getExternalContext().getRequest();
	String requestURI = req.getRequestURI();
	// Make the attribute name unique to the request 
	String attrName = "sakai.jsf.tool.URL.loopDetect.viewId-" + requestURI;
	// Try to fetch the attribute
	Object attribute = req.getAttribute(attrName);
	// If the attribute is null, this is the first request for this view
	if (attribute == null) {
		req.setAttribute(attrName, "true");
	} else if ("true".equals(attribute)) { // A looping request is detected.
		HttpServletResponse res = (HttpServletResponse) context.getExternalContext().getResponse();
		// Send a 404
		res.sendError(404, "File not found: " + requestURI);
	}
	// SAK-20286 end
	m_wrapped.renderView(context, root);
}
 
Example 2
Project: BootsFaces-OSP   File: FindIdRecursiveExpressionResolver.java   Source Code and License 7 votes vote down vote up
public List<UIComponent> resolve(UIComponent component, List<UIComponent> parentComponents, String currentId,
		String originalExpression, String[] parameters) {

	List<UIComponent> result = new ArrayList<UIComponent>();
	for (UIComponent parent : parentComponents) {
		UIComponent searchRoot = parent;
		while ((!(searchRoot instanceof UIViewRoot)) && (!(searchRoot instanceof NamingContainer))) {
			searchRoot = searchRoot.getParent();
		}
			
		List<UIComponent> c = findIdsRecursively(searchRoot, parameters[0]);
		if (null != c) {
			result.addAll(c);
		}
	}
	if (result.size() > 0) {
		return result;
	}

	throw new FacesException("Invalid search expression - couldn't find id " + currentId + ". Complete search expression: " + originalExpression);
}
 
Example 3
Project: Mastering-Java-EE-Development-with-WildFly   File: ACLRenderingController.java   Source Code and License 6 votes vote down vote up
public boolean aclCheck(String fragment, Object contextData) {
	boolean isAccessAllowed;
	try {
		Object[] runtime = new Object[1];
		if (contextData != null) {
			runtime[0] = contextData;
		}

		UIContext securityContext = new UIContext(getUser(userModule));
		securityContext.setFragment(fragment);
		securityContext.setContextData(runtime);
		isAccessAllowed = forumsACLProvider.hasAccess(securityContext);
	} catch (NoSuchMethodException nsme) {
		throw new FacesException(nsme);
	} catch (Exception e) {
		throw new FacesException(e);
	}

	return isAccessAllowed;
}
 
Example 4
Project: Mastering-Java-EE-Development-with-WildFly   File: AuthorizationListener.java   Source Code and License 6 votes vote down vote up
@AroundInvoke
public Object accessAllowed(InvocationContext ctx) throws Exception {
	Method businessAction = ctx.getMethod();
	Object managedBean = ctx.getTarget();
	boolean isAccessAllowed = false;

	try {

		ActionContext securityContext = new ActionContext(getUser(userModule));
		securityContext.setBusinessAction(businessAction);
		securityContext.setManagedBean(managedBean);

		isAccessAllowed = forumsACLProvider.hasAccess(securityContext);
		if (!isAccessAllowed)
			return null;
	} catch (NoSuchMethodException nsme) {
		throw new FacesException("Error calling action method of component with id " + nsme, nsme);
	} catch (Exception e) {
		throw new FacesException("Error calling action method of component with id " + e, e);
	}
	return ctx.proceed();
}
 
Example 5
Project: oscm   File: ExceptionHandler.java   Source Code and License 6 votes vote down vote up
/**
 * Convert a EJBException into FacesMessage which is presented to the user.
 * 
 * @param ex
 *            the EJBException to be analyzed
 */
public static void execute(EJBException ex) {
    if (ex != null && ex.getCause() instanceof Exception
            && ex.getCausedByException() instanceof AccessException) {
        handleOrganizationAuthoritiesException();
    } else if (ex != null && isInvalidUserSession(ex)) {
        HttpServletRequest request = JSFUtils.getRequest();
        request.getSession().removeAttribute(Constants.SESS_ATTR_USER);
        request.getSession().invalidate();
        handleInvalidSession();
    } else if (ex != null && isConnectionException(ex)) {
        handleMissingConnect(BaseBean.ERROR_DATABASE_NOT_AVAILABLE);
    } else {
        throw new FacesException(ex);
    }
}
 
Example 6
Project: myfaces-trinidad   File: ReturnActionListenerTag.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("deprecation")
public void apply(FaceletContext faceletContext,
        UIComponent parent) throws IOException, FacesException, FaceletException, ELException
{
  if(ComponentHandler.isNew(parent))
  {
    ActionSource actionSource = (ActionSource)parent;
    ReturnActionListener listener = new ReturnActionListener();
    if (_value != null)
    {
      ValueExpression valueExp = _value.getValueExpression(faceletContext, Object.class);
      listener.setValueExpression(ReturnActionListener.VALUE_KEY,valueExp);
    }

    actionSource.addActionListener(listener);
  }
}
 
Example 7
Project: myfaces-trinidad   File: GenericEntry.java   Source Code and License 6 votes vote down vote up
@Override
public void renderView(
  FacesContext context,
  UIViewRoot   viewToRender) throws IOException, FacesException
{
  String entryKey = (String) context.getExternalContext().getRequestParameterMap().get(__ENTRY_KEY_PARAM);
  if (entryKey == null)
  {
    RequestContext requestContext = RequestContext.getCurrentInstance();
    if (requestContext != null)
    {
      Object o = requestContext.getPageFlowScope().get(__ENTRY_KEY_PARAM);
      if (o != null)
        entryKey = o.toString();
    }
  }

  service(context,entryKey);
}
 
Example 8
Project: myfaces-trinidad   File: PanelPartialRootRenderer.java   Source Code and License 6 votes vote down vote up
public VisitResult visit(
  VisitContext context,
  UIComponent  target)
{
  try
  {
    // we have the subtree we want, render it
    target.encodeAll(context.getFacesContext());
  }
  catch (IOException ioe)
  {
    // launder the IOException as a FacesException, we'll unwrap this later
    throw new FacesException(ioe);
  }

  PartialPageContext pprContext = RenderingContext.getCurrentInstance().getPartialPageContext();

  // if we finished rendering all of the destired targets, return that we are
  // done.  Otherwise, reject this subtree so that we don't traverse into it, since
  // we have already rendered all of the targets in it
  if (pprContext.areAllTargetsProcessed())
    return VisitResult.COMPLETE;
  else
    return VisitResult.REJECT;
}
 
Example 9
Project: myfaces-trinidad   File: SkinPregenerationService.java   Source Code and License 6 votes vote down vote up
@Override
public void renderView(FacesContext context, UIViewRoot viewToRender)
  throws IOException, FacesException
{
  if (!isEnabled())
  {
    _sendPregenerationDisabledError(context);
    return;
  }
  
  long duration = _pregenerateSkin(context);    
  
  if (!context.getResponseComplete())
  {
    _renderResponse(context, duration);
  }
}
 
Example 10
Project: myfaces-trinidad   File: ClassLoaderUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Dynamically accesses the current context class loader. 
 * Includes a check for priviledges against java2 security 
 * to ensure no security related exceptions are encountered. 
 * Returns null if there is no per-thread context class loader.
 */
public static ClassLoader getContextClassLoader()
{
    if (System.getSecurityManager() != null) 
    {
        try 
        {
            ClassLoader cl = AccessController.doPrivileged(new PrivilegedExceptionAction<ClassLoader>()
                    {
                        public ClassLoader run() throws PrivilegedActionException
                        {
                            return Thread.currentThread().getContextClassLoader();
                        }
                    });
            return cl;
        }
        catch (PrivilegedActionException pae)
        {
            throw new FacesException(pae);
        }
    }
    else
    {
        return Thread.currentThread().getContextClassLoader();
    }
}
 
Example 11
Project: myfaces-trinidad   File: ClassUtils.java   Source Code and License 6 votes vote down vote up
/**
 * @param resource       Name of resource(s) to find in classpath
 * @param defaultObject  The default object to use to determine the class loader 
 *                       (if none associated with current thread.)
 * @return Iterator over URL Objects
 */
public static Iterator getResources(String resource, Object defaultObject)
{
    try
    {
        Enumeration resources = getCurrentLoader(defaultObject).getResources(resource);
        List lst = new ArrayList();
        while (resources.hasMoreElements())
        {
            lst.add(resources.nextElement());
        }
        return lst.iterator();
    }
    catch (IOException e)
    {
        log.log(Level.SEVERE, e.getMessage(), e);
        throw new FacesException(e);
    }
}
 
Example 12
Project: myfaces-trinidad   File: ClassUtils.java   Source Code and License 6 votes vote down vote up
public static Object newInstance(String type, Class[] expectedTypes)
{
    if (type == null)
    {
        return null;
    }
    
    Class clazzForName = simpleClassForName(type);
    
    if(expectedTypes != null)
    {
        for (int i = 0, size = expectedTypes.length; i < size; i++)
        {
            if (!expectedTypes[i].isAssignableFrom(clazzForName))
            {
                throw new FacesException("'" + type + "' does not implement expected type '" + expectedTypes[i]
                        + "'");
            }
        }
    }
    
    return newInstance(clazzForName);
}
 
Example 13
Project: myfaces-trinidad   File: ClassUtils.java   Source Code and License 6 votes vote down vote up
public static <T> T newInstance(Class<T> clazz,
                                Class<?>[] constructorArgClasses,
                                Object... constructorArgs) throws NoSuchMethodException
{
    if (constructorArgs.length == 0)
    {
        // no args given - use normal newInstance()
        return newInstance(clazz);
    }

    // try to get a fitting constructor (throws NoSuchMethodException)
    Constructor constructor = clazz.getConstructor(constructorArgClasses);

    try
    {
        // actually create instance
        return (T) constructor.newInstance(constructorArgs);
    }
    catch (Exception e)
    {
        throw new FacesException(e);
    }
}
 
Example 14
Project: myfaces-trinidad   File: ClassUtils.java   Source Code and License 6 votes vote down vote up
public static Object convertToType(Object value, Class desiredClass)
{
    if (value == null)
    {
        return null;
    }

    try
    {
        ExpressionFactory expFactory = FacesContext.getCurrentInstance().getApplication().getExpressionFactory();
        return expFactory.coerceToType(value, desiredClass);
    }
    catch (Exception e)
    {
        String message = "Cannot coerce " + value.getClass().getName()
                         + " to " + desiredClass.getName();
        log.log(Level.SEVERE, message, e);
        throw new FacesException(message, e);
    }
}
 
Example 15
Project: myfaces-trinidad   File: StateUtils.java   Source Code and License 6 votes vote down vote up
/**
 * This fires during the Render Response phase, saving state.
 */

public static final String construct(Object object, ExternalContext ctx)
{
    byte[] bytes = getAsByteArray(object, ctx);
    if( enableCompression(ctx) )
    {
        bytes = compress(bytes);
    }
    if(isSecure(ctx))
    {
        bytes = encrypt(bytes, ctx);
    }
    bytes = encode(bytes);
    try
    {
        return new String(bytes, ZIP_CHARSET);
    }
    catch (UnsupportedEncodingException e)
    {
        throw new FacesException(e);
    }
}
 
Example 16
Project: myfaces-trinidad   File: StateUtils.java   Source Code and License 6 votes vote down vote up
public static final byte[] compress(byte[] bytes)
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try
    {
        GZIPOutputStream gzip = new GZIPOutputStream(baos);
        gzip.write(bytes, 0, bytes.length);
        gzip.finish();
        byte[] fewerBytes = baos.toByteArray();
        gzip.close();
        baos.close();
        gzip = null;
        baos = null;
        return fewerBytes;
    }
    catch (IOException e)
    {
        throw new FacesException(e);
    }
}
 
Example 17
Project: myfaces-trinidad   File: MApplication.java   Source Code and License 6 votes vote down vote up
@Override
public UIComponent createComponent(String type) throws FacesException
{
  String s = _components.get(type);
  if (s == null)
    throw new IllegalArgumentException("No component for type " + type);
  try
  {
    Class<?> c = Class.forName(s);
    return (UIComponent) c.newInstance();
  }
  catch (Exception e)
  {
    throw (FacesException)
      (new FacesException("Could not create component of type " +
                          type + " with class " + s).initCause(e));
  }
}
 
Example 18
Project: HSECU   File: FindDMBean.java   Source Code and License 6 votes vote down vote up
public void getAllDossier(){
     String request = "SELECT * FROM dossierMedicale";

    try {
        connexion = DBConnect.getConnection();
        statement = connexion.createStatement();
        resultSet = statement.executeQuery(request);
                   
        while (resultSet.next()) {
            //TODO Recuperer les informations
        }

    } catch (Exception e) {
        System.err.println("Error getAllDossier " + request);
        throw new FacesException(e);
    }
}
 
Example 19
Project: HSECU   File: AddDMBean.java   Source Code and License 6 votes vote down vote up
public void initHopital(){
    //String request = "SELECT O.id_org,O.nom,O.description FROM organisation as O,hopital as H WHERE O.id_org=H.id_org";
    String request = "SELECT * from hopital";
    try {
        connexion = DBConnect.getConnection();
        statement = connexion.createStatement();
        resultSet = statement.executeQuery(request);
                   
        while (resultSet.next()) {
            if(!mapHospital.containsKey(resultSet.getInt(1)))
            {
                mapHospital.put(resultSet.getInt(1), new Hospital(resultSet.getInt(1),resultSet.getString(2)));
            }
        }

    } catch (Exception e) {
        System.err.println("Error getAllHopital " + request);
        throw new FacesException(e);
    }
}
 
Example 20
Project: HSECU   File: AddDMBean.java   Source Code and License 6 votes vote down vote up
public void initPole(){
    String request = "SELECT * from pole";
    try {
        connexion = DBConnect.getConnection();
        statement = connexion.createStatement();
        resultSet = statement.executeQuery(request);
                   
        while (resultSet.next()) {
            if((!mapPole.containsKey(resultSet.getInt(1)))&&(mapHospital.containsKey(resultSet.getInt(3))))
            {
                Pole poleee = new Pole(resultSet.getInt(1),resultSet.getString(2),resultSet.getInt(3));
                mapPole.put(resultSet.getInt(1),poleee);
                Hospital hosppp = mapHospital.get(resultSet.getInt(3));
                hosppp.getListPole().add(poleee);
            }
        }

    } catch (Exception e) {
        System.err.println("Error getAllHopital " + request);
        throw new FacesException(e); 
   }
}
 
Example 21
Project: HSECU   File: AddDMBean.java   Source Code and License 6 votes vote down vote up
public void initService(){
    String request = "SELECT * from service";
    try {
        connexion = DBConnect.getConnection();
        statement = connexion.createStatement();
        resultSet = statement.executeQuery(request);
                   
        while (resultSet.next()) {
            if  ((!mapService.containsKey(resultSet.getInt(1))) && (mapPole.containsKey(resultSet.getInt(3))))
            {
                Pole polee = mapPole.get(resultSet.getInt(3));
                Service serviceee = new Service(resultSet.getInt(1),resultSet.getString(2),resultSet.getInt(3));
                polee.getListService().add(serviceee);
                mapService.put(resultSet.getInt(1),serviceee);
            }
        }

    } catch (Exception e) {
        System.err.println("Error getAllHopital " + request);
        throw new FacesException(e);
    }
}
 
Example 22
Project: HSECU   File: AddDMBean.java   Source Code and License 6 votes vote down vote up
public void initServiceList(){
    String request = "SELECT * from service";
    try {
        connexion = DBConnect.getConnection();
        statement = connexion.createStatement();
        resultSet = statement.executeQuery(request);
                   
        while (resultSet.next()) {
                Service serviceee = new Service(resultSet.getInt(1),resultSet.getString(2),resultSet.getInt(3));
                getListString().add(serviceee.getName());
        }

    } catch (Exception e) {
        System.err.println("Error getAllHopital " + request);
        throw new FacesException(e);
    }
}
 
Example 23
Project: genopro-tools   File: ViewExpiredExceptionExceptionHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void handle() throws FacesException {
    
    for (Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator(); i.hasNext();) {
        ExceptionQueuedEvent event = i.next();
        ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();
        Throwable t = context.getException();
        if (t instanceof ViewExpiredException) {
            FacesContext fc = FacesContext.getCurrentInstance();
            NavigationHandler nav = fc.getApplication().getNavigationHandler();
            try {
                nav.handleNavigation(fc, null, "expired?faces-redirect=true&amp;includeViewParams=true");
                fc.renderResponse();
            } finally {
                i.remove();
            }
        }
    }
    // At this point, the queue will not contain any ViewExpiredEvents.
    // Therefore, let the parent handle them.
    getWrapped().handle();

}
 
Example 24
Project: gvnix1   File: ViewExpiredExceptionExceptionHandler-template.java   Source Code and License 6 votes vote down vote up
@Override
public void handle() throws FacesException {
    for (Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator(); i.hasNext();) {
        ExceptionQueuedEvent event = i.next();
        ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();

        Throwable t = context.getException();
        if (t instanceof ViewExpiredException) {
            ViewExpiredException vee = (ViewExpiredException) t;
            FacesContext facesContext = FacesContext.getCurrentInstance();
            Map<String, Object> requestMap = facesContext.getExternalContext().getRequestMap();
            NavigationHandler navigationHandler = facesContext.getApplication().getNavigationHandler();
            try {
                // Push some useful stuff to the request scope for use in the page
                requestMap.put("currentViewId", vee.getViewId());
                navigationHandler.handleNavigation(facesContext, null, "/viewExpired");
                facesContext.renderResponse();
            } finally {
                i.remove();
            }
        }
    }

    // At this point, the queue will not contain any ViewExpiredEvents. Therefore, let the parent handle them.
    getWrapped().handle();
}
 
Example 25
Project: gluu   File: ExternalResourceHandler.java   Source Code and License 6 votes vote down vote up
@Override
public URL resolveUrl(String path) {
	if (!useExternalResourceBase) {
		return this.parent.resolveUrl(path);
	}

	// First try external resource folder
	final File externalResource = new File(this.externalResourceBaseFolder, path);
	if (externalResource.exists()) {
		try {
			log.debug("Found overriden resource: " + path);
			URL resource = externalResource.toURI().toURL();

			return resource;
		} catch (MalformedURLException ex) {
			throw new FacesException(ex);
		}
	}

	// Return default resource
	return this.parent.resolveUrl(path);
}
 
Example 26
Project: development   File: ExceptionHandler.java   Source Code and License 6 votes vote down vote up
/**
 * Convert a EJBException into FacesMessage which is presented to the user.
 * 
 * @param ex
 *            the EJBException to be analyzed
 */
public static void execute(EJBException ex) {
    if (ex != null && ex.getCause() instanceof Exception
            && ex.getCausedByException() instanceof AccessException) {
        handleOrganizationAuthoritiesException();
    } else if (ex != null && isInvalidUserSession(ex)) {
        HttpServletRequest request = JSFUtils.getRequest();
        request.getSession().removeAttribute(Constants.SESS_ATTR_USER);
        request.getSession().invalidate();
        handleInvalidSession();
    } else if (ex != null && isConnectionException(ex)) {
        handleMissingConnect(BaseBean.ERROR_DATABASE_NOT_AVAILABLE);
    } else {
        throw new FacesException(ex);
    }
}
 
Example 27
Project: web-ifad   File: JsfExceptionHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void handle() throws FacesException {
	Iterator<ExceptionQueuedEvent> events = getUnhandledExceptionQueuedEvents().iterator();

	while (events.hasNext()) {
		ExceptionQueuedEvent event = events.next();
		ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();

		Throwable exception = context.getException();

		try {
			if (exception instanceof ViewExpiredException) {
                                   HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
                                   FacesContext.getCurrentInstance().getExternalContext().redirect(request.getRequestURI()+"?viewExpired=true");
			}
		} catch (IOException ex) {
                       Logger.getLogger(JsfExceptionHandler.class.getName()).log(Level.SEVERE, null, ex);
                   } finally {
			events.remove();
		}
	}

	getWrapped().handle();
}
 
Example 28
Project: exemplos   File: CustomExceptionHandler.java   Source Code and License 6 votes vote down vote up
/**
 *
 * @throws FacesException
 */
@Override
public void handle() throws FacesException {

    final Iterator<ExceptionQueuedEvent> unhandledExceptionQueuedEvents
            = getUnhandledExceptionQueuedEvents().iterator();

    if (unhandledExceptionQueuedEvents.hasNext()) {

        final Throwable exception = unhandledExceptionQueuedEvents
                .next()
                .getContext()
                .getException();

        unhandledExceptionQueuedEvents.remove();

        final Throwable rootCause = this.unwrap(exception);

        this.showError(rootCause.getMessage());
        
        return;
    }
    this.wrapped.handle();
}
 
Example 29
Project: exemplos   File: CustomExceptionHandler.java   Source Code and License 6 votes vote down vote up
/**
 *
 * @throws FacesException
 */
@Override
public void handle() throws FacesException {

    final Iterator<ExceptionQueuedEvent> unhandledExceptionQueuedEvents
            = getUnhandledExceptionQueuedEvents().iterator();

    if (unhandledExceptionQueuedEvents.hasNext()) {

        final Throwable exception = unhandledExceptionQueuedEvents
                .next()
                .getContext()
                .getException();

        unhandledExceptionQueuedEvents.remove();

        final Throwable rootCause = this.unwrap(exception);

        this.showError(rootCause.getMessage());
        
        return;
    }
    this.wrapped.handle();
}
 
Example 30
Project: ButterFaces   File: UIDataAdaptor.java   Source Code and License 6 votes vote down vote up
private void walkThroughChildren(FacesContext faces, ChildrenComponentVisitor visitor) {
    if (!this.isRendered()) {
        return;
    }

    final String var = getVar();
    if (var != null) {
        Map<String, Object> attrs = getVariablesMap(faces);

        this.originalVarValues.push(attrs.get(var));
    }
    this.setRowKey(faces, null);

    try {
        walk(faces, visitor);
    } catch (Exception e) {
        throw new FacesException(e);
    } finally {
        this.setRowKey(faces, null);
        this.restoreOrigValue(faces);
    }
}
 
Example 31
Project: iclos   File: PostRedirectGetListener.java   Source Code and License 6 votes vote down vote up
/**
 * Invoke a redirect to the same URL as the current action URL.
 * 
 * @param facesContext
 *            The involved facescontext.
 */
private static void redirect(final FacesContext facesContext) {

    // Obtain the action URL of the current view.
    String url = facesContext
            .getApplication()
            .getViewHandler()
            .getActionURL(facesContext,
                    facesContext.getViewRoot().getViewId());

    try {
        // Invoke a redirect to the action URL.
        facesContext.getExternalContext().redirect(url);
    } catch (IOException e) {
        // Uhh, something went seriously wrong.
        throw new FacesException("Cannot redirect to " + url
                + " due to IO exception.", e);
    }
}
 
Example 32
Project: iclos   File: DataCenterController.java   Source Code and License 6 votes vote down vote up
public void runVmPlacementTest() {
//      this.dataCenterVirtualMachinePlacementSimulator.setDataCenter(this.dataCenter);        
      this.placementSimulatorTestRunner.setRefreshTime(1);
      Thread simulatorVirtualMachinePlacement;
      simulatorVirtualMachinePlacement = new Thread(placementSimulatorTestRunner,
              "placementSimulatorTestRunner");
      simulatorVirtualMachinePlacement.start();
      this.setPlacementSimulatorTestRunnerStarted(true);
      
      FacesContext context = FacesContext.getCurrentInstance();
      String url = context
              .getApplication()
              .getViewHandler()
              .getActionURL(context,
                      context.getViewRoot().getViewId());

      try {
          // Invoke a redirect to the action URL.
          context.getExternalContext().redirect(url);
      } catch (IOException e) {
          // Uhh, something went seriously wrong.
          throw new FacesException("Cannot redirect to " + url
                  + " due to IO exception.", e);
      }
  }
 
Example 33
Project: sakai   File: SakaiViewHandlerWrapper.java   Source Code and License 6 votes vote down vote up
public void renderView(FacesContext context, UIViewRoot root) throws IOException, FacesException {
	// SAK-20286 start
	// Get the request
	HttpServletRequest req = (HttpServletRequest) context.getExternalContext().getRequest();
	String requestURI = req.getRequestURI();
	// Make the attribute name unique to the request 
	String attrName = "sakai.jsf.tool.URL.loopDetect.viewId-" + requestURI;
	// Try to fetch the attribute
	Object attribute = req.getAttribute(attrName);
	// If the attribute is null, this is the first request for this view
	if (attribute == null) {
		req.setAttribute(attrName, "true");
	} else if ("true".equals(attribute)) { // A looping request is detected.
		HttpServletResponse res = (HttpServletResponse) context.getExternalContext().getResponse();
		// Send a 404
		res.sendError(404, "File not found: " + requestURI);
	}
	// SAK-20286 end
	getWrapped().renderView(context, root);
}
 
Example 34
Project: yawl   File: RequestBean.java   Source Code and License 6 votes vote down vote up
/**
 * <p>This method is called when this bean is initially added to
 * request scope.  Typically, this occurs as a result of evaluating
 * a value binding or method binding expression, which utilizes the
 * managed bean facility to instantiate this bean and store it into
 * request scope.</p>
 * 
 * <p>You may customize this method to allocate resources that are required
 * for the lifetime of the current request.</p>
 */
public void init() {
    // Perform initializations inherited from our superclass
    super.init();
    // Perform application initialization that must complete
    // *before* managed components are initialized
    // TODO - add your own initialiation code here

    // <editor-fold defaultstate="collapsed" desc="Creator-managed Component Initialization">
    // Initialize automatically managed components
    // *Note* - this logic should NOT be modified
    try {
        _init();
    } catch (Exception e) {
        log("RequestBean1 Initialization Failure", e);
        throw e instanceof FacesException ? (FacesException) e: new FacesException(e);
    }
    // </editor-fold>
    // Perform application initialization that must complete
    // *after* managed components are initialized
    // TODO - add your own initialization code here

}
 
Example 35
Project: community-edition-old   File: BaseComponentGenerator.java   Source Code and License 6 votes vote down vote up
/**
 * Creates the converter with the given id and adds it to the component.
 * 
 * @param context FacesContext
 * @param converterId The name of the converter to create
 * @param component The component to add the converter to
 */
protected void createAndSetConverter(FacesContext context, String converterId, 
      UIComponent component)
{
   if (converterId != null && component instanceof UIOutput)
   {
      try
      {
         Converter conv = context.getApplication().createConverter(converterId);
         ((UIOutput)component).setConverter(conv);
      }
      catch (NullPointerException npe)
      {
         // workaround a NPE bug in MyFaces
         logger.warn("Converter " + converterId + " could not be applied");
      }
      catch (FacesException fe)
      {
         logger.warn("Converter " + converterId + " could not be applied");
      }
   }
}
 
Example 36
Project: karaku   File: ControllerHelper.java   Source Code and License 6 votes vote down vote up
/**
 * Retorna una EL expression correspondiente a un metodo.
 * 
 * @param valueExpression
 *            cadena que representa la expresion.
 * @param expectedReturnType
 *            clase del tipo que se espera que retorna la expresion
 * @param expectedParamTypes
 *            clase de los parametros esperados que reciba el metodo
 * 
 * @return {@link MethodExpression} correspondiente
 */
public MethodExpression createMethodExpression(
		final String valueExpression, final Class<?> expectedReturnType,
		final Class<?> ... expectedParamTypes) {

	MethodExpression methodExpression = null;
	try {
		FacesContext fc = getContext();
		ExpressionFactory factory = fc.getApplication()
				.getExpressionFactory();
		methodExpression = factory.createMethodExpression(
				fc.getELContext(), valueExpression, expectedReturnType,
				expectedParamTypes);
	} catch (Exception e) {
		throw new FacesException("Method expression '" + valueExpression
				+ "' could not be created.", e);
	}

	return methodExpression;
}
 
Example 37
Project: BootsFaces-OSP   File: StyleClassExpressionResolver.java   Source Code and License 6 votes vote down vote up
public List<UIComponent> resolve(UIComponent component, List<UIComponent> parentComponents, String currentId,
		String originalExpression, String[] parameters) {
	if (null==parameters || parameters.length!=1) {
		throw new FacesException("The @styleClass search expression requires a parameter! " + originalExpression);
	}
	List<UIComponent> result = null;
	for (UIComponent p:parentComponents) {
		List<UIComponent> r = findStyleClassRecursively(p, parameters[0]);
		if (result==null) {
			result=r;
		} else if (r!=null) {
			result.addAll(r);
		}
		
	}
	return result;
}
 
Example 38
Project: XPagesExtensionLibrary   File: UIDojoTabPane.java   Source Code and License 6 votes vote down vote up
@Override
public boolean invokeOnComponent(FacesContext context, String clientId, ContextCallback callback) throws FacesException {
    UIComponent subTree = getSubTreeComponent();
    if(subTree!=null) {
        // Handle partial refresh here
        FacesContextEx ctx = (FacesContextEx)context;
        if(ctx.isRenderingPhase()) {
            this.oldSubTree = ctx.getSubTreeComponent();
            ctx.setSubTreeComponent(subTree);
            try {
                return super.invokeOnComponent(context, clientId, callback);
            } finally {
                ctx.setSubTreeComponent(oldSubTree instanceof UIComponent?(UIComponent)oldSubTree:null);
                oldSubTree = null;
            }
        }
    }
    return super.invokeOnComponent(context, clientId, callback);
}
 
Example 39
Project: BootsFaces-OSP   File: AfterExpressionResolver.java   Source Code and License 6 votes vote down vote up
/**
 * Collects every JSF node following the current JSF node within the same branch of the tree.
 * It's like "@next @next:@next @next:@next:@next ...".
 */
public List<UIComponent> resolve(UIComponent component, List<UIComponent> parentComponents, String currentId,
		String originalExpression, String[] parameters) {
	List<UIComponent> result = new ArrayList<UIComponent>();
	for (UIComponent parent : parentComponents) {
	UIComponent grandparent = component.getParent();
	for (int i = 0; i < grandparent.getChildCount(); i++) {
		if (grandparent.getChildren().get(i) == parent) {
			i++;
			while (i<grandparent.getChildCount()) {
				result.add(grandparent.getChildren().get(i));
				i++;
			}
		}
	}
	}
	if (result.size() > 0) {
		return result;
	}
	throw new FacesException("Invalid search expression - there's no successor to the component " + originalExpression);
}
 
Example 40
Project: BootsFaces-OSP   File: FindPartialIdRecursiveExpressionResolver.java   Source Code and License 6 votes vote down vote up
public List<UIComponent> resolve(UIComponent component, List<UIComponent> parentComponents, String currentId,
		String originalExpression, String[] parameters) {

	List<UIComponent> result = new ArrayList<UIComponent>();
	for (UIComponent parent : parentComponents) {
		UIComponent searchRoot = parent;
		while ((!(searchRoot instanceof UIViewRoot)) && (!(searchRoot instanceof NamingContainer))) {
			searchRoot = searchRoot.getParent();
		}
			
		List<UIComponent> c = findIdRecursively(searchRoot, parameters[0]);
		if (null != c) {
			result.addAll(c);
		}
	}
	if (result.size() > 0) {
		return result;
	}

	throw new FacesException("Invalid search expression - couldn't find id " + currentId + ". Complete search expression: " + originalExpression);
}