Skip to main content
1-Visitor
January 22, 2018
Solved

Cannot Create User

  • January 22, 2018
  • 2 replies
  • 3571 views

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?

Best answer by bknight-2

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

2 replies

1-Visitor
January 22, 2018

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

bknight-21-VisitorAuthor
1-Visitor
January 22, 2018

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

1-Visitor
January 23, 2018

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-21-VisitorAuthorAnswer
1-Visitor
January 24, 2018

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