FacesContext instance est nulle dans un webscript

cancel
Showing results for 
Search instead for 
Did you mean: 
jnjp28
Member II

FacesContext instance est nulle dans un webscript

Bonjour,

J'ai un problème avec l'utilisation de FacesContext dans un webscript qui étend de  DeclarativeWebScript
Lorsque je tente d'obtenir une instance de FacesConext j'ai cette erreur: "FacesContext must not be null"

Il s'agit du code:

FacesContext context = FacesContext.getCurrentInstance();
Config config = Application.getConfigService(context).getConfig(node);
ActionsConfigElement actionConfig = (ActionsConfigElement)config.getConfigElement(ActionsConfigElement.CONFIG_ELEMENT_ID);
ActionGroup actionGroup = actionConfig.getActionGroup("template");

Merci pour vos réponse.
7 Replies
cleseach
Active Member II

Re: FacesContext instance est nulle dans un webscript

Bonjour,

FacesContext s'utilise dans "l'univers JSF" qui est disjoint de "l'univers des WebScripts"; il n'est donc pas étonnant qu'il soit null dans votre webscript.

Votre besoin semble être de récupérer le ConfigService, pourquoi ne pas l'injecter avec Spring dans votre WebScript ?

Cordialement,
Charles Le Seac'h
jnjp28
Member II

Re: FacesContext instance est nulle dans un webscript

Merci pour la réponse, c'est bien la solution que je pensais mais passant après un developpeur je voulais tout de même confirmer cette solution.

Un problème reste cependant : le configService est une interface, quelle implémentation dois-je injecter?

Merci
jnjp28
Member II

Re: FacesContext instance est nulle dans un webscript

Je vais essayer le "webClientConfigService"
jnjp28
Member II

Re: FacesContext instance est nulle dans un webscript

Bonjour

le soucis c'est que l'ancien développeur utilise un webscript pour creer un action group dans l'interface. Pour ce faire je dois absolument récupérer un FacesContext.

Voici la méthode utilisée dans le webscript :

protected List<Map<String, String>> buildActionGroup(FacesContext context, ActionsConfigElement config, ActionGroup actionGroup, Node node) throws UnsupportedEncodingException {
      
      
      javax.faces.application.Application facesApp = context.getApplication();
      ResourceBundle messages = Application.getBundle(context);

      List<Map<String, String>> actions = new ArrayList<Map<String, String>>();
      for (String actionId : actionGroup)
       {
          if (logger.isDebugEnabled())
             logger.debug("—processing ActionDefinition: " + actionId);
         
          ActionDefinition actionDef = config.getActionDefinition(actionId);
          if (actionDef == null)
          {
             throw new AlfrescoRuntimeException("Unable to find configured ActionDefinition Id: " + actionId);
          }
         
          // build a permissions evaluator component to wrap the actionlink
          PermissionEvaluator permEval = null;
          List<String> allow = actionDef.getAllowPermissions();
          if (allow != null && allow.size() != 0)
          {
             // found some permissions to test
             permEval = (PermissionEvaluator)facesApp.createComponent(UIActions.COMPONENT_PERMISSIONEVAL);
             String condition = allow.get(0);
             if (allow.size() != 1)
             {
                for (int i=1; i<allow.size(); i++)
                {
                   condition += "," + allow.get(i);
                }
             }
             permEval.setAllow(condition);
          }
          List<String> deny = actionDef.getDenyPermissions();
          if (deny != null && deny.size() != 0)
          {
             if (permEval == null)
             {
                permEval = (PermissionEvaluator)facesApp.createComponent(UIActions.COMPONENT_PERMISSIONEVAL);
             }
             String condition = deny.get(0);
             if (deny.size() != 1)
             {
                for (int i=1; i<deny.size(); i++)
                {
                   condition += "," + deny.get(i);
                }
             }
             permEval.setDeny(condition);
          }

          // Evaluate permissions
          if (permEval != null) {
             // Set context node
             permEval.setValue(node);
             if (! permEval.evaluate()) {
                // Skip this action
                continue;
             }
          }

          // now prepare any code based evaluators that may be present
          if (actionDef.Evaluator != null)
          {
             ActionInstanceEvaluator evaluator = (ActionInstanceEvaluator)facesApp.createComponent(UIActions.COMPONENT_ACTIONEVAL);
             evaluator.setEvaluator(actionDef.Evaluator);
             // Set context node
            evaluator.setValue(node);
            
             if (! evaluator.evaluate()) {
                // Skip this action
                continue;
             }
          }
         
          Map<String, String> action = new HashMap<String, String>();

          // Build href
          StringBuilder scriptHref = new StringBuilder(100);
          scriptHref.append("/command/script/execute");
          if (actionDef.Script.charAt(0) == '/') {
             // found a Path - encode it as a URL argument
             scriptHref.append("?scriptPath=");
             scriptHref.append(Utils.replace(URLEncoder.encode(actionDef.Script, "UTF-8"), "+", "%20"));
          }
          action.put("href", scriptHref.toString());
          action.put("target", actionDef.Target);
          action.put("image", actionDef.Image);
          if (actionDef.TooltipMsg != null) {
             action.put("tooltip", Application.getMessage(context, actionDef.TooltipMsg));
          } else if (actionDef.Tooltip != null) {
             action.put("tooltip", actionDef.Tooltip);
          }
          if (actionDef.LabelMsg != null) {
             action.put("label", Application.getMessage(context, actionDef.LabelMsg));
          } else if (actionDef.Label != null) {
             action.put("label", actionDef.Label);
          }
         
          actions.add(action);
       }
      
      return actions;
   }

Quels sont les bestPractices pour faire ce genre de chose ?

Merci
cleseach
Active Member II

Re: FacesContext instance est nulle dans un webscript

Alors là, il va nous falloir un peu plus d'information pour pouvoir vous aider.
Par exemple (liste non exhaustive) :
  • Quelle est l'interface utilisée ? (j'imagine Explorer)

  • Comment est appelé le webscript ? (j'imagine dans une JSP)
Dans tous les cas, ce mix technologique me paraît plutôt surprenant.

Cordialement,
Charles Le Seac'h
jnjp28
Member II

Re: FacesContext instance est nulle dans un webscript

En effet:

j'ai découpé les appels étapes par étapes :

  • Le développeur a déclaré un actionGroup dans le web-client-config.xml. Cet id de l'actionGroup est "template"

  • Lors du clique sur une flèche présente sur ligne d'action d'un noeud, un webscript est appelé

    templateActionsMenu =
                         "<a title=\"S�lectionneur de Mod�les\" onclick=\"javascript:toggleTemplateActions(event, '"+nodeRef.getId()+"', '"+dbid+"');return false;\">" +
                            "<img src=\"/alfresco/images/icons/more.gif\" style=\"border-width: 0px;\" alt=\"\" title=\"\"/>" +
                         "</a>" +
                         "<br/>" +
                         "<div id=\"template-actions-menu_"+dbid+"\" style=\"position: absolute; right: 15; overflow: visible; display: none; padding-left: 2px; *width:0px\">" +
                            "<table class=\"moreActionsMenu\" cellspacing=\"1\" cellpadding=\"0\" border=\"0\">" +
                               "<tr><td><img src=\"/alfresco/images/icons/ajax_anim.gif\"></td><td> <i>Chargement…</i></td>" +
                            "</table>" +
                         "</div>";
                      actions += templateActionsMenu;


  • Une fonction javascript est appelée

    function toggleTemplateActions(event, id, dbid) {
                parent.YAHOO.util.Connect.asyncRequest(
                   "GET",
                   '/alfresco/wcservice/****/templateactions?id='+id,
                   {
                      success: displayTemplateActions,
                      failure: parent.handleErrorYahoo,    // global error handler
                  argument: { dbid:dbid } 
                   });
             _toggleMenu(event, "template-actions-menu_"+dbid);
          }

  • Ce qui appelle le webscript de l'action suivante

    @Override
       protected Map<String, Object> executeImpl(WebScriptRequest req, WebScriptStatus status) {
          Map<String, Object> model = new HashMap<String, Object>();

          // Extract parameters
          String id = req.getParameter("id");
          logger.debug("id: "+id);
          model.put("id", id);

          // Build node
          NodeRef nodeRef = new NodeRef(Repository.getStoreRef(), id);
          Node node = new Node(nodeRef);
          
          // Get parent for forwarding after action execution
          NodeRef parentNodeRef = nodeService.getPrimaryParent(nodeRef).getParentRef();
          logger.debug("parentId: "+parentNodeRef.getId());
          model.put("parentId", parentNodeRef.getId());
          
          // Read actions config
          FacesContext context = FacesContext.getCurrentInstance();
          Config config = Application.getConfigService(context).getConfig(node);
            ActionsConfigElement actionConfig = (ActionsConfigElement)config.getConfigElement(ActionsConfigElement.CONFIG_ELEMENT_ID);
            ActionGroup actionGroup = actionConfig.getActionGroup("template");

            // Get list of actions
            List<Map<String, String>> actions;
          try {
             actions = buildActionGroup(context, actionConfig, actionGroup, node);
          } catch (UnsupportedEncodingException e) {
             throw new RuntimeException(e);
          }
           
            model.put("actions", actions);
            return model;
       }

       /**
        * Build action list after evaluation of each of them.
        * Code inspired by UIActions.buildActionGroup.
        *
        * @see UIActions#buildActionGroup
        * @return List of actions, each action being transfered as a Map<String, String>.
        * @throws UnsupportedEncodingException
        */
       protected List<Map<String, String>> buildActionGroup(FacesContext context, ActionsConfigElement config, ActionGroup actionGroup, Node node) throws UnsupportedEncodingException {
          javax.faces.application.Application facesApp = context.getApplication();
          ResourceBundle messages = Application.getBundle(context);

          List<Map<String, String>> actions = new ArrayList<Map<String, String>>();
          for (String actionId : actionGroup)
           {
              if (logger.isDebugEnabled())
                 logger.debug("—processing ActionDefinition: " + actionId);
             
              ActionDefinition actionDef = config.getActionDefinition(actionId);
              if (actionDef == null)
              {
                 throw new AlfrescoRuntimeException("Unable to find configured ActionDefinition Id: " + actionId);
              }
             
              // build a permissions evaluator component to wrap the actionlink
              PermissionEvaluator permEval = null;
              List<String> allow = actionDef.getAllowPermissions();
              if (allow != null && allow.size() != 0)
              {
                 // found some permissions to test
                 permEval = (PermissionEvaluator)facesApp.createComponent(UIActions.COMPONENT_PERMISSIONEVAL);
                 String condition = allow.get(0);
                 if (allow.size() != 1)
                 {
                    for (int i=1; i<allow.size(); i++)
                    {
                       condition += "," + allow.get(i);
                    }
                 }
                 permEval.setAllow(condition);
              }
              List<String> deny = actionDef.getDenyPermissions();
              if (deny != null && deny.size() != 0)
              {
                 if (permEval == null)
                 {
                    permEval = (PermissionEvaluator)facesApp.createComponent(UIActions.COMPONENT_PERMISSIONEVAL);
                 }
                 String condition = deny.get(0);
                 if (deny.size() != 1)
                 {
                    for (int i=1; i<deny.size(); i++)
                    {
                       condition += "," + deny.get(i);
                    }
                 }
                 permEval.setDeny(condition);
              }

              // Evaluate permissions
              if (permEval != null) {
                 // Set context node
                 permEval.setValue(node);
                 if (! permEval.evaluate()) {
                    // Skip this action
                    continue;
                 }
              }

              // now prepare any code based evaluators that may be present
              if (actionDef.Evaluator != null)
              {
                 ActionInstanceEvaluator evaluator = (ActionInstanceEvaluator)facesApp.createComponent(UIActions.COMPONENT_ACTIONEVAL);
                 evaluator.setEvaluator(actionDef.Evaluator);
                 // Set context node
                evaluator.setValue(node);
                
                 if (! evaluator.evaluate()) {
                    // Skip this action
                    continue;
                 }
              }
             
              Map<String, String> action = new HashMap<String, String>();

              // Build href
              StringBuilder scriptHref = new StringBuilder(100);
              scriptHref.append("/command/script/execute");
              if (actionDef.Script.charAt(0) == '/') {
                 // found a Path - encode it as a URL argument
                 scriptHref.append("?scriptPath=");
                 scriptHref.append(Utils.replace(URLEncoder.encode(actionDef.Script, "UTF-8"), "+", "%20"));
              }
              action.put("href", scriptHref.toString());
              action.put("target", actionDef.Target);
              action.put("image", actionDef.Image);
              if (actionDef.TooltipMsg != null) {
                 action.put("tooltip", Application.getMessage(context, actionDef.TooltipMsg));
              } else if (actionDef.Tooltip != null) {
                 action.put("tooltip", actionDef.Tooltip);
              }
              if (actionDef.LabelMsg != null) {
                 action.put("label", Application.getMessage(context, actionDef.LabelMsg));
              } else if (actionDef.Label != null) {
                 action.put("label", actionDef.Label);
              }
             
              actions.add(action);
           }
          
          return actions;
       }
cleseach
Active Member II

Re: FacesContext instance est nulle dans un webscript

Bonjour,

De mon point de vue, vous devriez repenser le code de votre webscript pour vous passer de l'usage de FacesContext.
Si vous jugez indispensable l'utilisation de FacesContext, il faudra vous passer d'un webscript et plutôt vous orienter vers un appel Ajax (cf. AjaxServlet).

Cordialement,
Charles Le Seac'h