Learn how to access services in the backend.

Introduction

When implementing domain logic you have to access certain services of the censhare-Server, e.g. PermissionService to check if the user is allowed to execute the operation or QueryService to search for assets. Since no dependency injection is used for Command Handlers, services must be explicitly requested using Platform.getCCService(class) or commandContext.getService(class).

Example: Accessing the permission service in the execution method:

public ResultData execute(CommandContext context, InputData input) {

    PermissionService permService = Platform.getCCService(PermissionService.class);
    if (!permService.hasPermission(PermissionKeydef.KEY_APP_ADMIN_ALL))
        throw new SecurityException("No permission");
    ...
}

Some service references are only valid within a transactional context (e.g. Repository and QueryService). Hence, you should request services when they are needed and never request services in advance and store the service references. In particular: You must not store service references in private fields of the Command Handler and share those references between public method calls (e.g. different execution methods). It's not guaranteed that those references are still valid when the next execution method is invoked.

So don't do this (anti pattern):

@CommandHandler(command = "com.acme.CustomCommand", scope=ScopeType.REQUEST)
public class CustomCommandHandler {

    private PermissionService permService;
    private QueryService queryService;
    private Repository repo;

    @Init
    public void init(CommandContext context) {
        permService = Platform.getCCService(PermissionService.class);
        queryService = Platform.getCCService(QueryService.class);
        repo = Platform.getCCService(Repository.class);
    }

    ...
}

Here ist the list of most commonly used services:

  • Repository - Querying assets by ID.
  • UpdatingRepository - Modifying, creating and deleting assets (check in new, check out, check in, update, delete).
  • QueryService - Querying assets by condition (using query builder).
  • PermissionService - Checking user permissions.
  • AssetPermissions - Checking the current user's permissions in the context of an asset.
  • CacheService - Lookup of master data.