ServiceContext: What is this for?

Lately I was trying to insert some content into liferay programmatically and I saw in many API calls that there was a parameter object of type ServiceContext. I didn’t realize at the beginning what it’s for, but after having a problem creating a vocabulary, it got more clear:

There is a method

1
2
3
4
5
6
AssetVocabularyLocalServiceUtil.addVocabulary(
        long userId, java.lang.String title,
        java.util.Map<java.util.Locale, java.lang.String> titleMap,
        java.util.Map<java.util.Locale, java.lang.String> descriptionMap,
        java.lang.String settings,
        com.liferay.portal.service.ServiceContext serviceContext)

which creates a vocabulary with the given title. I used it in my code, but if a vocabulary with the same name was already there a DuplicateVocabularyException was thrown. So in the exception handling I decided to get this vocabulary using the following method:

1
2
AssetVocabularyLocalServiceUtil.getGroupVocabulary(
        long groupId, java.lang.String name)

If you look closely you will notice that the get- method requires a groupId. No such parameter was required in the add- method. I think this is a little declaration bug in the API, because it seems that the groupId is required for the existence of a vocabulary.

After having a look at the source code of the portal, I saw in the add- method that the groupId has been used in the insertion from the ServiceContext. So, the ServiceContext is a simple bean that carries all the necessary (or not) information needed for the API service calls. More details here.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>