Skip to main content
Jan 22, 2018 2:28 PM UTC
Solved

Cannot Create User

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?

bknight-2Answer
Jan 24, 2018 2:02 PM UTC

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. !

4 replies

Jan 22, 2018 2:39 PM UTC

Does whatever/whoever is creating the user have Create permissions in the design time permissions (CRUD) ?

bknight-2Author
Jan 22, 2018 2:58 PM UTC

I am doing this process inside a Custom Authenticator.  I gave the Authenticator permissions for Read, Update, Delete.

Jan 23, 2018 12:57 AM UTC

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.

bknight-2AuthorAnswer
Jan 24, 2018 2:02 PM UTC

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. !