I am attempting to create a user using Entity Services in the SDK.
I'm using the following code and it keeps throwing a NullPointerException:
String user = "jpublic";
EntityServices es = new EntityServices();
try {
// Create Tag and Add to Collection
TagLink tag = TagLink.fromString("Users:Mashup");
TagCollection tc = new TagCollection();
tc.add(tag);
// Create User
es.CreateUser(user, "John Q Public", tc, "ABC123");
} catch (Exception e) {
// Log Errors
_logger.error(DateTime.now() + " -- Error: " + e.toString());
_logger.error(DateTime.now() + " -- Failed to Create User: " + user);
}
Any ideas on what I'm doing wrong?
Solved! Go to Solution.
I entered a ticket with PTC and received the following code snippet which solves my issue.
String username = user;
String groupName = group;
TransactionFactory.beginTransactionRequired();
ThreadLocalContext.setSecurityContext(SecurityContext.createSuperUserContext());
EntityServices es = (EntityServices) EntityUtilities.findEntity("EntityServices", ThingworxRelationshipTypes.Resource);
es.CreateUser(username, null, null, username);
User user = (User) EntityUtilities.findEntity(username, ThingworxRelationshipTypes.User);
Group grp = (Group) EntityUtilities.findEntity(groupName, ThingworxRelationshipTypes.Group);
if (grp != null) {
user.addGroup(grp);
}
TransactionFactory.endTransactionRequired();
I hope this helps others who have this issue. !
Does whatever/whoever is creating the user have Create permissions in the design time permissions (CRUD) ?
I am doing this process inside a Custom Authenticator. I gave the Authenticator permissions for Read, Update, Delete.
Can you give the Authenticator permission for Create as well?
In the past I've run into problems trying to create things, only to find that the user calling my create service didn't have permission to create users.
I entered a ticket with PTC and received the following code snippet which solves my issue.
String username = user;
String groupName = group;
TransactionFactory.beginTransactionRequired();
ThreadLocalContext.setSecurityContext(SecurityContext.createSuperUserContext());
EntityServices es = (EntityServices) EntityUtilities.findEntity("EntityServices", ThingworxRelationshipTypes.Resource);
es.CreateUser(username, null, null, username);
User user = (User) EntityUtilities.findEntity(username, ThingworxRelationshipTypes.User);
Group grp = (Group) EntityUtilities.findEntity(groupName, ThingworxRelationshipTypes.Group);
if (grp != null) {
user.addGroup(grp);
}
TransactionFactory.endTransactionRequired();
I hope this helps others who have this issue. !