First way for user creation
public static User addUser(Organization org,String tenantAdminName,
String tenantAdminEmailId) throws SystemException{
ServiceContext serviceContext = ServiceContextThreadLocal
.getServiceContext();
//long userId =
CounterLocalServiceUtil.increment();
User user=null;
Locale locale=null;
long[] emptyLong = {};
try{ user=UserLocalServiceUtil.addUser(CounterLocalServiceUtil.increment(),user.getCompanyId(), false,
null, null, false, tenantAdminName,
tenantAdminEmailId, 0, null, locale, tenantAdminName,
null, null, 0, 0, false, 1,
2, 2015, null, emptyLong, emptyLong,
emptyLong, emptyLong, false, serviceContext);
UserLocalServiceUtil.addOrganizationUser(org.getOrganizationId(),user);
UserLocalServiceUtil.updateUser(user);
}catch (Exception e) {
try {
throw new Exception(e);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
return user;}
Second way
public static User addUser(Organization org,String tenantAdminName,
String tenantAdminEmailId) throws SystemException{
System.out.println("inside user======");
ServiceContext serviceContext = ServiceContextThreadLocal
.getServiceContext();
long userId = CounterLocalServiceUtil.increment();
User userToCreate = UserUtil.create(userId);
userToCreate.setCompanyId(org.getCompanyId());
userToCreate.setFirstName(tenantAdminName);
System.out.println("admin
name========"+tenantAdminName);
userToCreate.setEmailAddress(tenantAdminEmailId);
System.out.println("admin
email========"+tenantAdminEmailId);
userToCreate.setScreenName(tenantAdminName);
User createdUser = UserLocalServiceUtil.addUser(userToCreate);
UserLocalServiceUtil.addOrganizationUser(org.getOrganizationId(),userToCreate);
UserLocalServiceUtil.updateUser(userToCreate);
return userToCreate;}
Third way for user creation
/*private void
addOrgUser(Organization org, String tenantAdminName,String
tenantAdminEmailId)
throws PortalException,
SystemException {
long userId =
CounterLocalServiceUtil.increment();
try
{;
User newUser =
UserLocalServiceUtil.createUser(CounterLocalServiceUtil.increment());
System.out.println("userrrrrrrrrr=============="+newUser);
newUser.setFirstName(tenantAdminName);
System.out.println("use
tenantAdminName=============="+newUser);
newUser.setEmailAddress(tenantAdminEmailId);
System.out.println("tenantAdminEmailId=============="+newUser);
newUser.setCompanyId(org.getCompanyId());
newUser.setScreenName("screenName");
System.out.println("tenantAdminEmailId2=============="+newUser);
UserLocalServiceUtil.addOrganizationUser(org.getOrganizationId(),newUser);
UserLocalServiceUtil.updateUser(newUser);
} catch (SystemException e) {
e.printStackTrace();
}
}*/
public static User addUser(String
firstName, String lastName, String email, String password, String screenName)
throws CantAddUserException {
try {
long[] emptyLong = {};
User user = UserLocalServiceUtil.addUser(
new Long(Constants.ADMIN_ID) /*long creatorUserId*/,
Constants.COMP_ID /*long companyId*/,
false /*boolean autoPassword*/,
password /*String password1*/,
password /*String password2*/,
false /*boolean autoScreenName*/,
screenName /* String screenName*/,
email /*String emailAddress*/,
new Locale("fr") /*Locale locale*/,
firstName /*String firstName*/,
null /*String middleName*/,
lastName /*String lastName*/,
0/*int prefixId*/,
0 /*int suffixId*/,
false /*boolean male*/,
1 /*int birthdayMonth*/,
1 /*int birthdayDay*/,
2000 /*int birthdayYear*/,
null /*String jobTitle*/,
emptyLong /*long[] organizationIds*/,
false /*boolean sendEmail*/);
return user;
} catch (Exception e) {
throw new CantAddUserException(e);
try {
long[] emptyLong = {};
User user = UserLocalServiceUtil.addUser(
new Long(Constants.ADMIN_ID) /*long creatorUserId*/,
Constants.COMP_ID /*long companyId*/,
false /*boolean autoPassword*/,
password /*String password1*/,
password /*String password2*/,
false /*boolean autoScreenName*/,
screenName /* String screenName*/,
email /*String emailAddress*/,
new Locale("fr") /*Locale locale*/,
firstName /*String firstName*/,
null /*String middleName*/,
lastName /*String lastName*/,
0/*int prefixId*/,
0 /*int suffixId*/,
false /*boolean male*/,
1 /*int birthdayMonth*/,
1 /*int birthdayDay*/,
2000 /*int birthdayYear*/,
null /*String jobTitle*/,
emptyLong /*long[] organizationIds*/,
false /*boolean sendEmail*/);
return user;
} catch (Exception e) {
throw new CantAddUserException(e);
long userId =
CounterLocalServiceUtil.increment();
User userToCreate = UserUtil.create(userId);
userToCreate.setFirstName(firstName);
userToCreate.setLastName(lastName);
userToCreate.setEmailAddress(email);
userToCreate.setPassword(password);
userToCreate.setScreenName(screenName);
userToCreate.setActive(true);
userToCreate.setCreateDate(new Date());
userToCreate.setGreeting("Hi " + screenName);
userToCreate.setJobTitle(job_title);
userToCreate.setLanguageId(languageId);
userToCreate.setMiddleName(middleName);
User createdUser = UserLocalServiceUtil.addUser(userToCreate);
User userToCreate = UserUtil.create(userId);
userToCreate.setFirstName(firstName);
userToCreate.setLastName(lastName);
userToCreate.setEmailAddress(email);
userToCreate.setPassword(password);
userToCreate.setScreenName(screenName);
userToCreate.setActive(true);
userToCreate.setCreateDate(new Date());
userToCreate.setGreeting("Hi " + screenName);
userToCreate.setJobTitle(job_title);
userToCreate.setLanguageId(languageId);
userToCreate.setMiddleName(middleName);
User createdUser = UserLocalServiceUtil.addUser(userToCreate);
long userId =
CounterLocalServiceUtil.increment();
User userToCreate = UserUtil.create(userId);
userToCreate.setFirstName("Test Name");
userToCreate.setLastName("Test Last Name");
userToCreate.setEmailAddress("test@liferay.com");
userToCreate.setPassword("password");
userToCreate.setScreenName("Test Name");
userToCreate.setActive(true);
userToCreate.setCreateDate(new Date());
userToCreate.setGreeting("Hi Test Name");
userToCreate.setJobTitle("Job Test");
userToCreate.setLanguageId("en_US");
userToCreate.setMiddleName("Test");
User createdUser = UserLocalServiceUtil.addUser(userToCreate);
try {
UserIndexer.updateUser(createdUser);
}
catch (SearchException se) {
_log.error("Indexing " + userId, se);
}
User userToCreate = UserUtil.create(userId);
userToCreate.setFirstName("Test Name");
userToCreate.setLastName("Test Last Name");
userToCreate.setEmailAddress("test@liferay.com");
userToCreate.setPassword("password");
userToCreate.setScreenName("Test Name");
userToCreate.setActive(true);
userToCreate.setCreateDate(new Date());
userToCreate.setGreeting("Hi Test Name");
userToCreate.setJobTitle("Job Test");
userToCreate.setLanguageId("en_US");
userToCreate.setMiddleName("Test");
User createdUser = UserLocalServiceUtil.addUser(userToCreate);
try {
UserIndexer.updateUser(createdUser);
}
catch (SearchException se) {
_log.error("Indexing " + userId, se);
}
Rank: Regular Member
Posts:
103
Join
Date: August 18, 2011
I
have a scenarion similar to yours but with a difference .I create users when I
am creating organisation .we have a use case where some default users be
created with certain set of roles when we are trying to create organisation .
As you might be aware that certain entities like orgaisation , user ,etc have model listeners attached to them so that when we create a successful insert in one of these ,simultaneous entries go in associated model listeners.And this is the way liferay behaves.For your custom insert into a liferay db you may be able to insert a user in user_ table but you will not be able to use that user or at least refer to that user unless simulatneos insert sre being made in associated model listeners for user.
I am attaching a create user method that I used in my use case.Hope this answers your query to a certain extent:
private User insertOrgPublisher(ActionRequest actionRequest,Organization organization,ServiceContext serviceContext) throws PortalException, SystemException {
ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
long companyId = themeDisplay.getCompanyId();
long groupId= themeDisplay.getLayout().getGroupId();
String password1= "orgpub";//organization.getName().toLowerCase();
String domainName = null;
long facebookId=0;
String openId=null;
String firstName=organization.getName();
String lastName=organization.getName();
int prefixId=123;
int suffixId=234;
String jobTitle="Organization Publisher";
domainName = organization.getName();
domainName= domainName.trim();
if(domainName.contains(" ")) {
domainName = domainName.replaceAll("\\s+", "-");
}
String emailAddress="publisher@"+domainName+".com";
Role role = RoleLocalServiceUtil.getRole(companyId, "Organization Publisher");
User user = null;
if(role != null){
String greeting="Welcome "+role.getName();
long id = CounterLocalServiceUtil.increment(User.class.getName());
user = UserLocalServiceUtil.createUser(id);
user.setCompanyId(companyId);
user.setPassword(password1);
String screenName=organization.getName().toLowerCase()+id;
user.setScreenName(screenName);
user.setGreeting(greeting);
user.setEmailAddress(emailAddress);
user.setFacebookId(facebookId);
user.setOpenId(openId);
user.setFirstName(firstName);
user.setLastName(lastName);
user.setJobTitle(jobTitle);
user.setCreateDate(new Date ());
user.setContactId(id+1);
user.setPasswordReset(true);
user.setPasswordModifiedDate(new Date());
user.setCreateDate(new Date());
user.setModifiedDate(new Date());
user.setLanguageId(themeDisplay.getLanguageId());
user.setTimeZoneId(themeDisplay.getTimeZone().getDisplayName());
UserLocalServiceUtil.addUser(user);
//Associate a role with user
long userid[] = {user.getUserId()};
//UserLocalServiceUtil.addRoleUsers(role.getRoleId(), userid);
long roleids[]={role.getRoleId()};
UserGroupRoleLocalServiceUtil.addUserGroupRoles(user.getUserId(), groupId, roleids);
ClassName clsNameUser = ClassNameLocalServiceUtil.getClassName("com.liferay.portal.model.User");
long classNameId=clsNameUser.getClassNameId();
//Insert Group for a user
long gpId = CounterLocalServiceUtil.increment(Group.class.getName());
Group userGrp = GroupLocalServiceUtil.createGroup(gpId);
userGrp.setClassNameId(classNameId);
userGrp.setClassPK(userid[0]);
userGrp.setCompanyId(companyId);
userGrp.setName("group"+String.valueOf(userid[0]));
userGrp.setFriendlyURL("/group"+gpId);
userGrp.setCreatorUserId(PortalUtil.getUserId(actionRequest));
userGrp.setActive(true);
GroupLocalServiceUtil.addGroup(userGrp);
//Insert Contact for a user
long idContact = user.getUserId() + 1;//CounterLocalServiceUtil.increment(Contact.class.getName());
Contact contact = ContactLocalServiceUtil.createContact(idContact);
contact.setCompanyId(companyId);
contact.setCreateDate(new Date());
contact.setUserName(screenName);
contact.setUserId(user.getUserId());
contact.setModifiedDate(new Date());
contact.setFirstName("contact-"+contact.getContactId());
contact.setLastName("contact-"+contact.getContactId());
contact.setMiddleName("contact-"+contact.getContactId());
contact.setPrefixId(prefixId);
contact.setBirthday(new Date());
contact.setSuffixId(suffixId);
contact.setJobTitle(jobTitle+contact.getContactId());
ContactLocalServiceUtil.addContact(contact);
//Create AssetEntry
long assetEntryId = user.getUserId()+5;//CounterLocalServiceUtil.increment(AssetEntry.class.getName());
AssetEntry ae = AssetEntryLocalServiceUtil.createAssetEntry(assetEntryId);
ae.setCompanyId(companyId);
ae.setClassPK(user.getUserId());
ae.setGroupId(userGrp.getGroupId());
ae.setClassNameId(classNameId);
AssetEntryLocalServiceUtil.addAssetEntry(ae);
//Insert ResourcePermission for a User
long resPermId = CounterLocalServiceUtil.increment(ResourcePermission.class.getName());
ResourcePermission rpEntry = ResourcePermissionLocalServiceUtil.createResourcePermission(resPermId);
rpEntry.setCompanyId(organization.getCompanyId());
rpEntry.setName("com.liferay.portal.model.User");
rpEntry.setRoleId(role.getRoleId());
rpEntry.setScope(4);
ResourcePermissionLocalServiceUtil.addResourcePermission(rpEntry);
//Insert Layoutset for public and private
long layoutSetIdPub = CounterLocalServiceUtil.increment(LayoutSet.class.getName());
LayoutSet layoutSetPub=LayoutSetLocalServiceUtil.createLayoutSet(layoutSetIdPub);
layoutSetPub.setCompanyId(companyId);
layoutSetPub.setPrivateLayout(false);
layoutSetPub.setGroupId(userGrp.getGroupId());
layoutSetPub.setThemeId("classic");
try{
LayoutSetLocalServiceUtil.addLayoutSet(layoutSetPub);
}catch(SystemException se){
}
long layoutSetIdPriv= CounterLocalServiceUtil.increment(LayoutSet.class.getName());
LayoutSet layoutSetPriv=LayoutSetLocalServiceUtil.createLayoutSet(layoutSetIdPriv);
layoutSetPriv.setCompanyId(companyId);
layoutSetPriv.setPrivateLayout(true);
layoutSetPriv.setThemeId("classic");
layoutSetPriv.setGroupId(userGrp.getGroupId());
try{
LayoutSetLocalServiceUtil.addLayoutSet(layoutSetPriv);
}catch(SystemException se){
}
}else{
return null;
}
return user;
}
As you might be aware that certain entities like orgaisation , user ,etc have model listeners attached to them so that when we create a successful insert in one of these ,simultaneous entries go in associated model listeners.And this is the way liferay behaves.For your custom insert into a liferay db you may be able to insert a user in user_ table but you will not be able to use that user or at least refer to that user unless simulatneos insert sre being made in associated model listeners for user.
I am attaching a create user method that I used in my use case.Hope this answers your query to a certain extent:
private User insertOrgPublisher(ActionRequest actionRequest,Organization organization,ServiceContext serviceContext) throws PortalException, SystemException {
ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
long companyId = themeDisplay.getCompanyId();
long groupId= themeDisplay.getLayout().getGroupId();
String password1= "orgpub";//organization.getName().toLowerCase();
String domainName = null;
long facebookId=0;
String openId=null;
String firstName=organization.getName();
String lastName=organization.getName();
int prefixId=123;
int suffixId=234;
String jobTitle="Organization Publisher";
domainName = organization.getName();
domainName= domainName.trim();
if(domainName.contains(" ")) {
domainName = domainName.replaceAll("\\s+", "-");
}
String emailAddress="publisher@"+domainName+".com";
Role role = RoleLocalServiceUtil.getRole(companyId, "Organization Publisher");
User user = null;
if(role != null){
String greeting="Welcome "+role.getName();
long id = CounterLocalServiceUtil.increment(User.class.getName());
user = UserLocalServiceUtil.createUser(id);
user.setCompanyId(companyId);
user.setPassword(password1);
String screenName=organization.getName().toLowerCase()+id;
user.setScreenName(screenName);
user.setGreeting(greeting);
user.setEmailAddress(emailAddress);
user.setFacebookId(facebookId);
user.setOpenId(openId);
user.setFirstName(firstName);
user.setLastName(lastName);
user.setJobTitle(jobTitle);
user.setCreateDate(new Date ());
user.setContactId(id+1);
user.setPasswordReset(true);
user.setPasswordModifiedDate(new Date());
user.setCreateDate(new Date());
user.setModifiedDate(new Date());
user.setLanguageId(themeDisplay.getLanguageId());
user.setTimeZoneId(themeDisplay.getTimeZone().getDisplayName());
UserLocalServiceUtil.addUser(user);
//Associate a role with user
long userid[] = {user.getUserId()};
//UserLocalServiceUtil.addRoleUsers(role.getRoleId(), userid);
long roleids[]={role.getRoleId()};
UserGroupRoleLocalServiceUtil.addUserGroupRoles(user.getUserId(), groupId, roleids);
ClassName clsNameUser = ClassNameLocalServiceUtil.getClassName("com.liferay.portal.model.User");
long classNameId=clsNameUser.getClassNameId();
//Insert Group for a user
long gpId = CounterLocalServiceUtil.increment(Group.class.getName());
Group userGrp = GroupLocalServiceUtil.createGroup(gpId);
userGrp.setClassNameId(classNameId);
userGrp.setClassPK(userid[0]);
userGrp.setCompanyId(companyId);
userGrp.setName("group"+String.valueOf(userid[0]));
userGrp.setFriendlyURL("/group"+gpId);
userGrp.setCreatorUserId(PortalUtil.getUserId(actionRequest));
userGrp.setActive(true);
GroupLocalServiceUtil.addGroup(userGrp);
//Insert Contact for a user
long idContact = user.getUserId() + 1;//CounterLocalServiceUtil.increment(Contact.class.getName());
Contact contact = ContactLocalServiceUtil.createContact(idContact);
contact.setCompanyId(companyId);
contact.setCreateDate(new Date());
contact.setUserName(screenName);
contact.setUserId(user.getUserId());
contact.setModifiedDate(new Date());
contact.setFirstName("contact-"+contact.getContactId());
contact.setLastName("contact-"+contact.getContactId());
contact.setMiddleName("contact-"+contact.getContactId());
contact.setPrefixId(prefixId);
contact.setBirthday(new Date());
contact.setSuffixId(suffixId);
contact.setJobTitle(jobTitle+contact.getContactId());
ContactLocalServiceUtil.addContact(contact);
//Create AssetEntry
long assetEntryId = user.getUserId()+5;//CounterLocalServiceUtil.increment(AssetEntry.class.getName());
AssetEntry ae = AssetEntryLocalServiceUtil.createAssetEntry(assetEntryId);
ae.setCompanyId(companyId);
ae.setClassPK(user.getUserId());
ae.setGroupId(userGrp.getGroupId());
ae.setClassNameId(classNameId);
AssetEntryLocalServiceUtil.addAssetEntry(ae);
//Insert ResourcePermission for a User
long resPermId = CounterLocalServiceUtil.increment(ResourcePermission.class.getName());
ResourcePermission rpEntry = ResourcePermissionLocalServiceUtil.createResourcePermission(resPermId);
rpEntry.setCompanyId(organization.getCompanyId());
rpEntry.setName("com.liferay.portal.model.User");
rpEntry.setRoleId(role.getRoleId());
rpEntry.setScope(4);
ResourcePermissionLocalServiceUtil.addResourcePermission(rpEntry);
//Insert Layoutset for public and private
long layoutSetIdPub = CounterLocalServiceUtil.increment(LayoutSet.class.getName());
LayoutSet layoutSetPub=LayoutSetLocalServiceUtil.createLayoutSet(layoutSetIdPub);
layoutSetPub.setCompanyId(companyId);
layoutSetPub.setPrivateLayout(false);
layoutSetPub.setGroupId(userGrp.getGroupId());
layoutSetPub.setThemeId("classic");
try{
LayoutSetLocalServiceUtil.addLayoutSet(layoutSetPub);
}catch(SystemException se){
}
long layoutSetIdPriv= CounterLocalServiceUtil.increment(LayoutSet.class.getName());
LayoutSet layoutSetPriv=LayoutSetLocalServiceUtil.createLayoutSet(layoutSetIdPriv);
layoutSetPriv.setCompanyId(companyId);
layoutSetPriv.setPrivateLayout(true);
layoutSetPriv.setThemeId("classic");
layoutSetPriv.setGroupId(userGrp.getGroupId());
try{
LayoutSetLocalServiceUtil.addLayoutSet(layoutSetPriv);
}catch(SystemException se){
}
}else{
return null;
}
return user;
}
Hello everybody,
I am trying to create a new user via liferay API. The only way how I could create a user who was able to log in into the portal, was to repeat the steps form the create.sql script.
1) creating a new user: User user = UserLocalServiceUtil.createUser(userId);
2) setting properties for this user (password, companyId, screenName, active,.... )
3) creating corresponding contact: Contact contact = ContactLocalServiceUtil.createContact(contactId);
4) setting contact's properties (userId, accountId,...)
5) adding user: UserLocalServiceUtil.addUser(user);
6) adding contact: ContactLocalServiceUtil.addContact(contact);
7) adding user to the group: UserUtil.addGroups(userId, grpIds);
8) adding user to the organization: UserUtil.addOrganizations(userId, orgIds);
9) adding user roles: UserUtil.addRoles(id, roleIds);
10)creating group: GroupLocalServiceUtil.createGroup(groupId);
11)setting properties for the group
12)creating layout sets: LayoutSetLocalServiceUtil.createLayoutSet(layoutId);
13)setting propeties for the sets
14)adding group : GroupLocalServiceUtil.addGroup(group);
15)adding layout sets: LayoutSetLocalServiceUtil.addLayoutSet(ls1);
Isnt there a simpler solution which creates a liferay user with all (default) required dependecies/roles/groups?
I am trying to create a new user via liferay API. The only way how I could create a user who was able to log in into the portal, was to repeat the steps form the create.sql script.
1) creating a new user: User user = UserLocalServiceUtil.createUser(userId);
2) setting properties for this user (password, companyId, screenName, active,.... )
3) creating corresponding contact: Contact contact = ContactLocalServiceUtil.createContact(contactId);
4) setting contact's properties (userId, accountId,...)
5) adding user: UserLocalServiceUtil.addUser(user);
6) adding contact: ContactLocalServiceUtil.addContact(contact);
7) adding user to the group: UserUtil.addGroups(userId, grpIds);
8) adding user to the organization: UserUtil.addOrganizations(userId, orgIds);
9) adding user roles: UserUtil.addRoles(id, roleIds);
10)creating group: GroupLocalServiceUtil.createGroup(groupId);
11)setting properties for the group
12)creating layout sets: LayoutSetLocalServiceUtil.createLayoutSet(layoutId);
13)setting propeties for the sets
14)adding group : GroupLocalServiceUtil.addGroup(group);
15)adding layout sets: LayoutSetLocalServiceUtil.addLayoutSet(ls1);
Isnt there a simpler solution which creates a liferay user with all (default) required dependecies/roles/groups?
No comments:
Post a Comment