RE: Initialize serviceContext without request

thumbnail
ali yeganeh, modified 6 Years ago. Regular Member Posts: 148 Join Date: 5/1/19 Recent Posts
hi
I create Service Context object and used it in the addFolder method in the DLAppServiceUtil class and I get the Principal is null exception
my code is :

long companyId = CompanyLocalServiceUtil.getCompanyByMx( PropsUtil.get( PropsKeys.COMPANY_DEFAULT_WEB_ID ) ).getCompanyId();
Group group = GroupLocalServiceUtil.fetchGroup( companyId, GroupConstants.GUEST );
long groupId = group.getGroupId();
ServiceContext serviceContext = new ServiceContext();
serviceContext.setScopeGroupId( groupId );
serviceContext.setCompanyId( companyId );
DLAppServiceUtil.addFolder( groupId, DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, "ALI", "---", serviceContext ); 
thumbnail
Mohammed Yasin, modified 6 Years ago. Liferay Master Posts: 593 Join Date: 8/8/14 Recent Posts
Hi, 
​​​​​​​This may be because the user from which you are doing this might not have permission to add folder to the repository.
Try once setting userid also  in serviceContext.setuserId( userId); and check
thumbnail
ali yeganeh, modified 6 Years ago. Regular Member Posts: 148 Join Date: 5/1/19 Recent Posts
hi
I add admin  user to my service context object ,But I still have this problem
User userByEmailAddress = UserLocalServiceUtil.getUserByEmailAddress( companyId, " " );
thumbnail
Amos Fong, modified 6 Years ago. Liferay Legend Posts: 2047 Join Date: 10/7/08 Recent Posts
If this code isn't initiated from a request (eg startupAction, or scheduled job), then it rightly throws a principal is null exception which means there's no user doing the action. Usually if this is the case, it probably means you don't want to check permissions anyway because you're controlling the execution of the code. So you should call the DLAppLocalService method which does not check permissions.
thumbnail
Mohammed Yasin, modified 6 Years ago. Liferay Master Posts: 593 Join Date: 8/8/14 Recent Posts
Hi,
 You can set the permission checker  and see
PermissionChecker permissionChecker  = PermissionCheckerFactoryUtil.create(adminUser);
PermissionThreadLocal.setPermissionChecker(permissionChecker);
thumbnail
ali yeganeh, modified 6 Years ago. Regular Member Posts: 148 Join Date: 5/1/19 Recent Posts
Amos Fong:

If this code isn't initiated from a request (eg startupAction, or scheduled job), then it rightly throws a principal is null exception which means there's no user doing the action. Usually if this is the case, it probably means you don't want to check permissions anyway because you're controlling the execution of the code. So you should call the DLAppLocalService method which does not check permissions.

Thank you very much
I answered your solution