Create user using java class

Hi!

I have just started using Camunda platform and wanted to create new user using service task which implements java class.

I don’t know why the code is not working. Any suggestions?
Here is the code:

import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
import org.camunda.bpm.engine.identity.User;
import org.camunda.bpm.engine.impl.IdentityServiceImpl;

public abstract class CreateUser implements JavaDelegate{

   public void execute(DelegateExecution execution, ProcessEngine engine) throws Exception {
	
  final IdentityServiceImpl identityService = (IdentityServiceImpl) engine.getIdentityService();

  User user = identityService.newUser("demo");
  user.setFirstName("Demo");
  user.setLastName("Demo");
  user.setPassword("demo");
  user.setEmail("demo@camunda.org");
  identityService.saveUser(user);

}
}

@pauline Every time when CreateUser delegate is called in service task, new instance of CreateUser will be created. In your case you marked the class with modifier as “abstract”. In Java, instances will not be created for abstract classes. So please remove the keyword abstract and give a try.

Without abstract, it gives error:

I think I’m doing something wrong with the structure.

@pauline you are calling nested functions. it wont work like that except anonymous function.

Inside the execute function you are providing implementation of create() function. its wrong implementation. Move all the code which is inside create() function to execute() function.

If you’re not able to do, please upload your java file, i will modify and resend to you.

1 Like

CreateUser.txt (1.0 KB)

I get an error and don’t know how to fix it…
I am truly grateful for your time and help :slight_smile:

Hi @pauline,
which camunda version are you using? The execute method from JavaDelegate has only 1 parameter, so you only needs to remove the ProcessEngine paramater from execute method
and get it from delegateExecution variable and finally get the IdentityService this way

public void execute(DelegateExecution execution) throws Exception {

      IdentityService identityService = execution.getProcessEngine().getIdentityService();

      if(identityService.isReadOnly()) {
        return;
      }

      User singleResult = identityService.createUserQuery().userId("demo").singleResult();
      if (singleResult != null) {
        return;
      }

      User user = identityService.newUser("demo");
      user.setFirstName("Demo");
      user.setLastName("Demo");
      user.setPassword("demo");
      user.setEmail("demo@camunda.org");
      identityService.saveUser(user);

}
2 Likes

Hi, @kyle,
Thank you so much! It works now. :blush: