Throw Exception in ModelListener Liferay












0















Hello Liferay Experts,



I have a requirement where I need to stop an Admin from assigning a role, I am trying to implement this with a ModelListener.



Here is the code..



@Component(immediate = true, service = ModelListener.class)
public class TestUserModelListener extends BaseModelListener<User> {

@Override
public void onBeforeAddAssociation(Object classPK, String associationClassName, Objext accociationClassPK) throws ModelListenerException {
// ...
throw new ModelListenerException("User creation not allowed");
}
}


When this code executes, the exception is thrown but the UI doesnt handle it correctly, the control panel Menus are not displayed and the exception message is not displayed to the user.



How to throw an exception and handle it correctly in UI and display error message to the user.



Thanks



M










share|improve this question

























  • Did you try to set your error messages via SessionErrors.add operation. I don't know, if you have a request object access (maybe threadlocal).

    – Andre Albert
    Nov 14 '18 at 9:25






  • 1





    Also, You can try to wrap/extends the MVC ActionCommand. I guess that you could use mvc.command.name=/users_admin/update_user_roles (not tested) - see here

    – Andre Albert
    Nov 14 '18 at 9:31


















0















Hello Liferay Experts,



I have a requirement where I need to stop an Admin from assigning a role, I am trying to implement this with a ModelListener.



Here is the code..



@Component(immediate = true, service = ModelListener.class)
public class TestUserModelListener extends BaseModelListener<User> {

@Override
public void onBeforeAddAssociation(Object classPK, String associationClassName, Objext accociationClassPK) throws ModelListenerException {
// ...
throw new ModelListenerException("User creation not allowed");
}
}


When this code executes, the exception is thrown but the UI doesnt handle it correctly, the control panel Menus are not displayed and the exception message is not displayed to the user.



How to throw an exception and handle it correctly in UI and display error message to the user.



Thanks



M










share|improve this question

























  • Did you try to set your error messages via SessionErrors.add operation. I don't know, if you have a request object access (maybe threadlocal).

    – Andre Albert
    Nov 14 '18 at 9:25






  • 1





    Also, You can try to wrap/extends the MVC ActionCommand. I guess that you could use mvc.command.name=/users_admin/update_user_roles (not tested) - see here

    – Andre Albert
    Nov 14 '18 at 9:31
















0












0








0








Hello Liferay Experts,



I have a requirement where I need to stop an Admin from assigning a role, I am trying to implement this with a ModelListener.



Here is the code..



@Component(immediate = true, service = ModelListener.class)
public class TestUserModelListener extends BaseModelListener<User> {

@Override
public void onBeforeAddAssociation(Object classPK, String associationClassName, Objext accociationClassPK) throws ModelListenerException {
// ...
throw new ModelListenerException("User creation not allowed");
}
}


When this code executes, the exception is thrown but the UI doesnt handle it correctly, the control panel Menus are not displayed and the exception message is not displayed to the user.



How to throw an exception and handle it correctly in UI and display error message to the user.



Thanks



M










share|improve this question
















Hello Liferay Experts,



I have a requirement where I need to stop an Admin from assigning a role, I am trying to implement this with a ModelListener.



Here is the code..



@Component(immediate = true, service = ModelListener.class)
public class TestUserModelListener extends BaseModelListener<User> {

@Override
public void onBeforeAddAssociation(Object classPK, String associationClassName, Objext accociationClassPK) throws ModelListenerException {
// ...
throw new ModelListenerException("User creation not allowed");
}
}


When this code executes, the exception is thrown but the UI doesnt handle it correctly, the control panel Menus are not displayed and the exception message is not displayed to the user.



How to throw an exception and handle it correctly in UI and display error message to the user.



Thanks



M







liferay hook






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 18 '18 at 19:58









quatax

1135




1135










asked Nov 12 '18 at 20:40









SamSam

63




63













  • Did you try to set your error messages via SessionErrors.add operation. I don't know, if you have a request object access (maybe threadlocal).

    – Andre Albert
    Nov 14 '18 at 9:25






  • 1





    Also, You can try to wrap/extends the MVC ActionCommand. I guess that you could use mvc.command.name=/users_admin/update_user_roles (not tested) - see here

    – Andre Albert
    Nov 14 '18 at 9:31





















  • Did you try to set your error messages via SessionErrors.add operation. I don't know, if you have a request object access (maybe threadlocal).

    – Andre Albert
    Nov 14 '18 at 9:25






  • 1





    Also, You can try to wrap/extends the MVC ActionCommand. I guess that you could use mvc.command.name=/users_admin/update_user_roles (not tested) - see here

    – Andre Albert
    Nov 14 '18 at 9:31



















Did you try to set your error messages via SessionErrors.add operation. I don't know, if you have a request object access (maybe threadlocal).

– Andre Albert
Nov 14 '18 at 9:25





Did you try to set your error messages via SessionErrors.add operation. I don't know, if you have a request object access (maybe threadlocal).

– Andre Albert
Nov 14 '18 at 9:25




1




1





Also, You can try to wrap/extends the MVC ActionCommand. I guess that you could use mvc.command.name=/users_admin/update_user_roles (not tested) - see here

– Andre Albert
Nov 14 '18 at 9:31







Also, You can try to wrap/extends the MVC ActionCommand. I guess that you could use mvc.command.name=/users_admin/update_user_roles (not tested) - see here

– Andre Albert
Nov 14 '18 at 9:31














1 Answer
1






active

oldest

votes


















1














Andre Albert already gave you the correct hints in the comments.
You should keep the ModelListener and override the ActionCommand additionally.



First, read the tutorial about Overriding MVC Comands. When implementing your custom Command, use Liferay's implemenation as basis (don't forget to add the higher service.ranking) and replace the catch block with something like this:



// I took the freedom and refactored Liferay's catch block a little bit
catch (NoSuchUserException | PrincipalException e) {
SessionErrors.add(actionRequest, e.getClass());
actionResponse.setRenderParameter("mvcPath", "/error.jsp");
} catch (MembershipPolicyException e) {
SessionErrors.add(actionRequest, e.getClass(), e);
actionResponse.setRenderParameter("mvcPath", "/edit_user.jsp");
actionResponse.setRenderParameter("screenNavigationCategoryKey", UserFormConstants.CATEGORY_KEY_GENERAL);
actionResponse.setRenderParameter("screenNavigationEntryKey", UserFormConstants.ENTRY_KEY_ROLES);
} catch (ForbiddenRoleAssociationException e) {
// Here you can add a SessionError
// and set some render parameters
} catch (Exception e) {
throw e;
}


The ForbiddenRoleAssociationException does not exist yet. It's purpose is to distinguish this special case of a ModelListenerException from others which might not interest you. You'll have to implement it yourself. Just extend the ModelListenerException:



public class ForbiddenRoleAssociationException extends ModelListenerException {
// here might be some constructors
}


Now adjust your ModelListener so that it throws your new ForbiddenRoeAssociationException:



@Component(immediate = true, service = ModelListener.class)
public class TestUserModelListener extends BaseModelListener<User> {

@Override
public void onBeforeAddAssociation(Object classPK, String associationClassName, Objext accociationClassPK) throws ModelListenerException {
// ...
throw new ForbiddenRoleAssociationException(); // or any other constructor
}
}


This way you should be able to display error messages to admins (depending on your code in the catch block of the ForbiddenRoleAssociationException) and circumvent any other (programmatic) attempt to assign the Role as well.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53269773%2fthrow-exception-in-modellistener-liferay%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Andre Albert already gave you the correct hints in the comments.
    You should keep the ModelListener and override the ActionCommand additionally.



    First, read the tutorial about Overriding MVC Comands. When implementing your custom Command, use Liferay's implemenation as basis (don't forget to add the higher service.ranking) and replace the catch block with something like this:



    // I took the freedom and refactored Liferay's catch block a little bit
    catch (NoSuchUserException | PrincipalException e) {
    SessionErrors.add(actionRequest, e.getClass());
    actionResponse.setRenderParameter("mvcPath", "/error.jsp");
    } catch (MembershipPolicyException e) {
    SessionErrors.add(actionRequest, e.getClass(), e);
    actionResponse.setRenderParameter("mvcPath", "/edit_user.jsp");
    actionResponse.setRenderParameter("screenNavigationCategoryKey", UserFormConstants.CATEGORY_KEY_GENERAL);
    actionResponse.setRenderParameter("screenNavigationEntryKey", UserFormConstants.ENTRY_KEY_ROLES);
    } catch (ForbiddenRoleAssociationException e) {
    // Here you can add a SessionError
    // and set some render parameters
    } catch (Exception e) {
    throw e;
    }


    The ForbiddenRoleAssociationException does not exist yet. It's purpose is to distinguish this special case of a ModelListenerException from others which might not interest you. You'll have to implement it yourself. Just extend the ModelListenerException:



    public class ForbiddenRoleAssociationException extends ModelListenerException {
    // here might be some constructors
    }


    Now adjust your ModelListener so that it throws your new ForbiddenRoeAssociationException:



    @Component(immediate = true, service = ModelListener.class)
    public class TestUserModelListener extends BaseModelListener<User> {

    @Override
    public void onBeforeAddAssociation(Object classPK, String associationClassName, Objext accociationClassPK) throws ModelListenerException {
    // ...
    throw new ForbiddenRoleAssociationException(); // or any other constructor
    }
    }


    This way you should be able to display error messages to admins (depending on your code in the catch block of the ForbiddenRoleAssociationException) and circumvent any other (programmatic) attempt to assign the Role as well.






    share|improve this answer




























      1














      Andre Albert already gave you the correct hints in the comments.
      You should keep the ModelListener and override the ActionCommand additionally.



      First, read the tutorial about Overriding MVC Comands. When implementing your custom Command, use Liferay's implemenation as basis (don't forget to add the higher service.ranking) and replace the catch block with something like this:



      // I took the freedom and refactored Liferay's catch block a little bit
      catch (NoSuchUserException | PrincipalException e) {
      SessionErrors.add(actionRequest, e.getClass());
      actionResponse.setRenderParameter("mvcPath", "/error.jsp");
      } catch (MembershipPolicyException e) {
      SessionErrors.add(actionRequest, e.getClass(), e);
      actionResponse.setRenderParameter("mvcPath", "/edit_user.jsp");
      actionResponse.setRenderParameter("screenNavigationCategoryKey", UserFormConstants.CATEGORY_KEY_GENERAL);
      actionResponse.setRenderParameter("screenNavigationEntryKey", UserFormConstants.ENTRY_KEY_ROLES);
      } catch (ForbiddenRoleAssociationException e) {
      // Here you can add a SessionError
      // and set some render parameters
      } catch (Exception e) {
      throw e;
      }


      The ForbiddenRoleAssociationException does not exist yet. It's purpose is to distinguish this special case of a ModelListenerException from others which might not interest you. You'll have to implement it yourself. Just extend the ModelListenerException:



      public class ForbiddenRoleAssociationException extends ModelListenerException {
      // here might be some constructors
      }


      Now adjust your ModelListener so that it throws your new ForbiddenRoeAssociationException:



      @Component(immediate = true, service = ModelListener.class)
      public class TestUserModelListener extends BaseModelListener<User> {

      @Override
      public void onBeforeAddAssociation(Object classPK, String associationClassName, Objext accociationClassPK) throws ModelListenerException {
      // ...
      throw new ForbiddenRoleAssociationException(); // or any other constructor
      }
      }


      This way you should be able to display error messages to admins (depending on your code in the catch block of the ForbiddenRoleAssociationException) and circumvent any other (programmatic) attempt to assign the Role as well.






      share|improve this answer


























        1












        1








        1







        Andre Albert already gave you the correct hints in the comments.
        You should keep the ModelListener and override the ActionCommand additionally.



        First, read the tutorial about Overriding MVC Comands. When implementing your custom Command, use Liferay's implemenation as basis (don't forget to add the higher service.ranking) and replace the catch block with something like this:



        // I took the freedom and refactored Liferay's catch block a little bit
        catch (NoSuchUserException | PrincipalException e) {
        SessionErrors.add(actionRequest, e.getClass());
        actionResponse.setRenderParameter("mvcPath", "/error.jsp");
        } catch (MembershipPolicyException e) {
        SessionErrors.add(actionRequest, e.getClass(), e);
        actionResponse.setRenderParameter("mvcPath", "/edit_user.jsp");
        actionResponse.setRenderParameter("screenNavigationCategoryKey", UserFormConstants.CATEGORY_KEY_GENERAL);
        actionResponse.setRenderParameter("screenNavigationEntryKey", UserFormConstants.ENTRY_KEY_ROLES);
        } catch (ForbiddenRoleAssociationException e) {
        // Here you can add a SessionError
        // and set some render parameters
        } catch (Exception e) {
        throw e;
        }


        The ForbiddenRoleAssociationException does not exist yet. It's purpose is to distinguish this special case of a ModelListenerException from others which might not interest you. You'll have to implement it yourself. Just extend the ModelListenerException:



        public class ForbiddenRoleAssociationException extends ModelListenerException {
        // here might be some constructors
        }


        Now adjust your ModelListener so that it throws your new ForbiddenRoeAssociationException:



        @Component(immediate = true, service = ModelListener.class)
        public class TestUserModelListener extends BaseModelListener<User> {

        @Override
        public void onBeforeAddAssociation(Object classPK, String associationClassName, Objext accociationClassPK) throws ModelListenerException {
        // ...
        throw new ForbiddenRoleAssociationException(); // or any other constructor
        }
        }


        This way you should be able to display error messages to admins (depending on your code in the catch block of the ForbiddenRoleAssociationException) and circumvent any other (programmatic) attempt to assign the Role as well.






        share|improve this answer













        Andre Albert already gave you the correct hints in the comments.
        You should keep the ModelListener and override the ActionCommand additionally.



        First, read the tutorial about Overriding MVC Comands. When implementing your custom Command, use Liferay's implemenation as basis (don't forget to add the higher service.ranking) and replace the catch block with something like this:



        // I took the freedom and refactored Liferay's catch block a little bit
        catch (NoSuchUserException | PrincipalException e) {
        SessionErrors.add(actionRequest, e.getClass());
        actionResponse.setRenderParameter("mvcPath", "/error.jsp");
        } catch (MembershipPolicyException e) {
        SessionErrors.add(actionRequest, e.getClass(), e);
        actionResponse.setRenderParameter("mvcPath", "/edit_user.jsp");
        actionResponse.setRenderParameter("screenNavigationCategoryKey", UserFormConstants.CATEGORY_KEY_GENERAL);
        actionResponse.setRenderParameter("screenNavigationEntryKey", UserFormConstants.ENTRY_KEY_ROLES);
        } catch (ForbiddenRoleAssociationException e) {
        // Here you can add a SessionError
        // and set some render parameters
        } catch (Exception e) {
        throw e;
        }


        The ForbiddenRoleAssociationException does not exist yet. It's purpose is to distinguish this special case of a ModelListenerException from others which might not interest you. You'll have to implement it yourself. Just extend the ModelListenerException:



        public class ForbiddenRoleAssociationException extends ModelListenerException {
        // here might be some constructors
        }


        Now adjust your ModelListener so that it throws your new ForbiddenRoeAssociationException:



        @Component(immediate = true, service = ModelListener.class)
        public class TestUserModelListener extends BaseModelListener<User> {

        @Override
        public void onBeforeAddAssociation(Object classPK, String associationClassName, Objext accociationClassPK) throws ModelListenerException {
        // ...
        throw new ForbiddenRoleAssociationException(); // or any other constructor
        }
        }


        This way you should be able to display error messages to admins (depending on your code in the catch block of the ForbiddenRoleAssociationException) and circumvent any other (programmatic) attempt to assign the Role as well.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 18 '18 at 20:56









        quataxquatax

        1135




        1135






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53269773%2fthrow-exception-in-modellistener-liferay%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Full-time equivalent

            Bicuculline

            さくらももこ