public class ApacheIsisApplibMixinsRoleAndPermissions extends AbstractRoleAndPermissionsFixtureScript {

    public static final String ROLE_NAME = "applib-mixins-user";

    public ApacheIsisApplibMixinsRoleAndPermissions() {
        super(ROLE_NAME, "User access to applib (metadata) mixins");
    }

    @Override
    protected void execute(final ExecutionContext executionContext) {
        newPackagePermissions(
                ApplicationPermissionRule.ALLOW,
                ApplicationPermissionMode.CHANGING,
                "org.apache.isis.applib");
    }

} public class AuditModuleRoleAndPermissions extends AbstractRoleAndPermissionsFixtureScript {

    public static final String ROLE_NAME = "todoapp-auditing-admin";

    public AuditModuleRoleAndPermissions() {
        super(ROLE_NAME, "Admin access to audit module");
    }

    @Override
    protected void execute(final FixtureScript.ExecutionContext executionContext) {
        newPackagePermissions(
                ApplicationPermissionRule.ALLOW,
                ApplicationPermissionMode.CHANGING,
                "org.isisaddons.module.audit");
    }

} public class CommandModuleRoleAndPermissions extends AbstractRoleAndPermissionsFixtureScript {

    public static final String ROLE_NAME = "todoapp-command-admin";

    public CommandModuleRoleAndPermissions() {
        super(ROLE_NAME, "Admin access to command module");
    }

    @Override
    protected void execute(final ExecutionContext executionContext) {
        newPackagePermissions(
                ApplicationPermissionRule.ALLOW,
                ApplicationPermissionMode.CHANGING,
                "org.isisaddons.module.command");
    }

} public class ApacheIsisPersistableMixinsRoleAndPermissions extends AbstractRoleAndPermissionsFixtureScript {

    public static final String ROLE_NAME = "persistable-mixins-user";

    public ApacheIsisPersistableMixinsRoleAndPermissions() {
        super(ROLE_NAME, "User access to persistable (metadata) mixins");
    }

    @Override
    protected void execute(final ExecutionContext executionContext) {
        newPackagePermissions(
                ApplicationPermissionRule.ALLOW,
                ApplicationPermissionMode.CHANGING,
                Persistable_datanucleusIdLong.class.getPackage().getName());
    }

} public class SessionLoggerModuleRoleAndPermissions extends AbstractRoleAndPermissionsFixtureScript {

    public static final String ROLE_NAME = "todoapp-sessionlogger-admin";

    public SessionLoggerModuleRoleAndPermissions() {
        super(ROLE_NAME, "Admin access to sessionlogger module");
    }

    @Override
    protected void execute(final ExecutionContext executionContext) {
        newPackagePermissions(
                ApplicationPermissionRule.ALLOW,
                ApplicationPermissionMode.CHANGING,
                "org.isisaddons.module.sessionlogger");
    }

} public class SettingsModuleRoleAndPermissions extends AbstractRoleAndPermissionsFixtureScript {

    public static final String ROLE_NAME = "todoapp-settings-admin";

    public SettingsModuleRoleAndPermissions() {
        super(ROLE_NAME, "Admin access to settings module");
    }

    @Override
    protected void execute(final ExecutionContext executionContext) {
        newPackagePermissions(
                ApplicationPermissionRule.ALLOW,
                ApplicationPermissionMode.CHANGING,
                "org.isisaddons.module.settings");
    }

} public class ToDoAppFixtureServiceRoleAndPermissions extends AbstractRoleAndPermissionsFixtureScript {

    public static final String ROLE_NAME = "todoapp-fixture-scripts";

    public ToDoAppFixtureServiceRoleAndPermissions() {
        super(ROLE_NAME, "Execute the ToDoApp fixture scripts");
    }

    @Override
    protected void execute(FixtureScript.ExecutionContext executionContext) {
        newPackagePermissions(
                ApplicationPermissionRule.ALLOW,
                ApplicationPermissionMode.CHANGING,
                FixtureScriptsDefault.class.getPackage().getName(),
                "todoapp.fixture");
    }

} public class ToDoAppRegularRoleAndPermissions extends AbstractRoleAndPermissionsFixtureScript {

    public static final String ROLE_NAME = "todoapp-regular-role";

    public ToDoAppRegularRoleAndPermissions() {
        super(ROLE_NAME, "Read/write access to todoapp dom");
    }

    @Override
    protected void execute(final FixtureScript.ExecutionContext executionContext) {
        newPackagePermissions(
                ApplicationPermissionRule.ALLOW,
                ApplicationPermissionMode.CHANGING,
                "todoapp.app",
                ToDoAppDomainModule.class.getPackage().getName()
                );
    }

} public class DeleteUserAndUserRolesAndToDoItems extends FixtureScript {

    //region > username
    private String username;

    /**
     * The user to delete; required.
     */
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
    //endregion

    @Override
    protected void execute(final ExecutionContext ec) {

        // defaults
        final String username = Util.coalesce(ec.getParameter("username"), getUsername());
        if (username == null) {
            throw new IllegalArgumentException("username is required");
        }

        // validate user
        final ApplicationUser applicationUser = applicationUserRepository.findByUsername(username);
        if(applicationUser == null) {
            // nothing to do...
            return;
        }

        final String atPath = UsersTenancy.TENANCY_PATH + username;

        // delete
        isisJdoSupport.executeUpdate(
                "DELETE FROM \"todo\".\"ToDoItemDependencies\" WHERE \"dependingId\" IN (SELECT \"id\" FROM \"todo\".\"ToDoItem\" WHERE \"atPath\" = '" + atPath + "')");
        isisJdoSupport.executeUpdate(
                "DELETE FROM \"todo\".\"ToDoItem\" WHERE \"atPath\" = '" + atPath + "'");
        isisJdoSupport.executeUpdate(
                "DELETE FROM \"isissecurity\".\"ApplicationUserRoles\" WHERE \"userId\" IN (SELECT \"id\" FROM \"isissecurity\".\"ApplicationUser\" WHERE \"username\" = '" + username + "')");
        isisJdoSupport.executeUpdate(
                "DELETE FROM \"isissecurity\".\"ApplicationUser\" WHERE \"username\" = '" + username + "'");
        isisJdoSupport.executeUpdate(
                "DELETE FROM \"isissecurity\".\"ApplicationTenancy\" WHERE \"path\" = '" + UsersTenancy.TENANCY_PATH + username + "'");
    }

    @Inject
    private IsisJdoSupport isisJdoSupport;

    @javax.inject.Inject
    private ApplicationUserRepository applicationUserRepository;

} public class CreateUserFixtureScript extends FixtureScript {

    //region > username (required)
    /**
     * The user to setup (required).
     */
    private String username;

    public String getUsername() {
        return username;
    }

    public void setUsername(final String username) {
        this.username = username;
    }
    //endregion

    //region > emailAddress (optional)
    private String emailAddress;

    /**
     * Optional.
     */
    public String getEmailAddress() {
        return emailAddress;
    }

    public void setEmailAddress(final String emailAddress) {
        this.emailAddress = emailAddress;
    }
    //endregion

    //region > accountType (optional)
    private AccountType accountType;

    /**
     * The account type to create; optional, defaults to {@link org.isisaddons.module.security.dom.user.AccountType#LOCAL}.
     */
    public AccountType getAccountType() {
        return accountType;
    }

    public void setAccountType(final AccountType accountType) {
        this.accountType = accountType;
    }
    //endregion



    //region > initialRole (optional)
    private ApplicationRole initialRole;

    /**
     * The initial role for the user to have (optional).
     *
     * <p>
     *     Defaults to <code>null</code>, meaning none.   Takes precedence over {@link #getInitialRoleName()}.
     * </p>
     */
    public ApplicationRole getInitialRole() {
        return initialRole;
    }
    public void setInitialRole(ApplicationRole initialRole) {
        this.initialRole = initialRole;
    }
    //endregion

    //region > initialRoleName (optional)
    private String initialRoleName;

    /**
     * The (name of) the initial role for the user to have (optional).
     *
     * <p>
     *     Defaults to <code>null</code>, meaning none.
     * </p>
     *
     */
    public String getInitialRoleName() {
        return initialRoleName;
    }

    public void setInitialRoleName(final String initialRoleName) {
        this.initialRoleName = initialRoleName;
    }
    //endregion

    //region > enabled (optional)
    private Boolean enabled;

    /**
     * Whether the user should be enabled or not (optional).
     *
     * <p>
     *     Defaults to <code>null</code>, which is interpreted as disabled.
     * </p>
     */
    public Boolean getEnabled() {
        return enabled;
    }
    public void setEnabled(Boolean enabled) {
        this.enabled = enabled;
    }
    //endregion

    //region > password (optional)
    private String password;

    /**
     * The password to set up for a {@link org.isisaddons.module.security.dom.user.AccountType#LOCAL local} user only
     * (optional).
     *
     * <p>
     *     Defaults to 'pass'.  Is ignored if setting up a delegate user.
     * </p>
     */
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
    //endregion

    //region > applicationUser (output)
    private ApplicationUser applicationUser;

    /**
     * The application user created by the fixture (output property)
     */
    public ApplicationUser getApplicationUser() {
        return applicationUser;
    }
    private void setApplicationUser(final ApplicationUser applicationUser) {
        this.applicationUser = applicationUser;
    }
    //endregion

    @Override
    protected void execute(FixtureScript.ExecutionContext ec) {

        // required
        final String username = todoapp.fixture.util.Util.coalesce(ec.getParameter("username"), getUsername());
        if (username == null) {
            throw new IllegalArgumentException("username is required");
        }

        // optional
        final String emailAddress = todoapp.fixture.util.Util.coalesce(ec.getParameter("emailAddress"), getEmailAddress());
        final AccountType accountType = todoapp.fixture.util.Util.coalesce(ec.getParameterAsEnum("accountType", AccountType.class), getAccountType(), AccountType.LOCAL);
//        final String tenancyPath = todoapp.fixture.util.Util.coalesce(ec.getParameter("atPath"), getAtPath(), GlobalTenancy.TENANCY_PATH + username);
        final String password = todoapp.fixture.util.Util.coalesce(ec.getParameter("password"), getPassword(), "pass");
        final ApplicationRole initialRole = todoapp.fixture.util.Util.coalesce(findRoleByName(ec.getParameter("initialRole")), getInitialRole(), findRoleByName(getInitialRoleName()));
        boolean enabled = todoapp.fixture.util.Util.coalesce(ec.getParameterAsBoolean("enabled"), getEnabled(), Boolean.TRUE);

        //
        // execute
        //
        final ApplicationUser applicationUser;
        if (accountType == AccountType.DELEGATED) {
            applicationUser = wrap(applicationUserMenu).newDelegateUser(username, initialRole, enabled);
        } else {
            final Password passwordValue = new Password(password);
            applicationUser = wrap(applicationUserMenu).newLocalUser(username, passwordValue, passwordValue, initialRole, enabled, emailAddress);
        }

        // no longer required, performed automatically by subscriber...
//        final ApplicationTenancy applicationTenancy = applicationTenancyRepository.findTenancyByPath(tenancyPath);
//        if (applicationTenancy == null) {
//            final ApplicationTenancy rootTenancy = applicationTenancyRepository.findTenancyByPath(GlobalTenancy.TENANCY_PATH);
//            applicationTenancyRepository.newTenancy(username, tenancyPath, rootTenancy);
//        }
//        applicationUser.setTenancy(applicationTenancy);

        ec.addResult(this, username, applicationUser);

        setApplicationUser(applicationUser);
    }

    private ApplicationRole findRoleByName(final String initialRole1) {
        return applicationRoleRepository.findByName(initialRole1);
    }

    @javax.inject.Inject
    private ApplicationUserMenu applicationUserMenu;

    @javax.inject.Inject
    private ApplicationRoleRepository applicationRoleRepository;

    @javax.inject.Inject
    private ApplicationTenancyRepository applicationTenancyRepository;


} public class UserRolesFixtureScript extends FixtureScript {

    //region > userName
    private String username;

    /**
     * Required.
     */
    public String getUsername() {
        return username;
    }

    public void setUsername(final String username) {
        this.username = username;
    }
    //endregion

    //region > roleNames
    private List<String> roleNames;
    public List<String> getRoleNames() {
        return roleNames;
    }

    public void setRoleNames(final List<String> roleNames) {
        this.roleNames = roleNames;
    }
    //endregion


    //region > applicationUser (output property)
    private ApplicationUser applicationUser;

    /**
     * The application user updated by the script.
     */
    public ApplicationUser getApplicationUser() {
        return applicationUser;
    }

    private void setApplicationUser(final ApplicationUser applicationUser) {
        this.applicationUser = applicationUser;
    }
    //endregion

    //region > applicationRoles (output property)
    private List<ApplicationRole> applicationRoles;

    /**
     * The application roles corresponding to {@link #getRoleNames()}.
     */
    public List<ApplicationRole> getApplicationRoles() {
        return applicationRoles;
    }

    public void setApplicationRoles(final List<ApplicationRole> applicationRoles) {
        this.applicationRoles = applicationRoles;
    }
    //endregion

    @Override
    protected void execute(ExecutionContext ec) {

        // required
        final String username = Util.coalesce(ec.getParameter("username"), getUsername());
        if (username == null) {
            throw new IllegalArgumentException("username is required");
        }

        // validate user
        this.applicationUser = applicationUserRepository.findByUsername(username);
        if(this.applicationUser == null) {
            throw new IllegalArgumentException(String.format("No user with username: '%s'", username));
        }

        // no defaults for roles

        // validate all roleNames
        this.applicationRoles =
                Lists.newArrayList(
                    Iterables.filter(
                        Iterables.transform(getRoleNames(), roleNameToRole()),
                        Predicates.notNull()));

        List<ApplicationRole> applicationRoleList = this.applicationRoles;
        List<String> roleNames = getRoleNames();
        if(applicationRoleList.size() != roleNames.size()) {
            throw new IllegalArgumentException("One or more roles not found");
        }

        // execute
        ec.addResult(this, applicationUser.getName(), this.applicationUser);

        for (ApplicationRole applicationRole : this.applicationRoles) {
            if (applicationRole != null) {
                this.applicationUser.addRole(applicationRole);
                ec.addResult(this, applicationRole.getName(), applicationRole);
            }
        }
    }

    private Function<String, ApplicationRole> roleNameToRole() {
        return new Function<String, ApplicationRole>() {
            @Nullable
            @Override
            public ApplicationRole apply(final String input) {
                return applicationRoleRepository.findByNameCached(input);
            }
        };
    }


    @javax.inject.Inject
    private ApplicationUserRepository applicationUserRepository;
    @javax.inject.Inject
    private ApplicationRoleRepository applicationRoleRepository;

}
import todoapp.fixture.module.security.UserRolesFixtureScript;
import java.util.Arrays;
import org.isisaddons.module.security.seed.scripts.IsisModuleSecurityAdminRoleAndPermissions;
import todoapp.dom.seed.roles.ApacheIsisApplibMixinsRoleAndPermissions;
import todoapp.dom.seed.roles.AuditModuleRoleAndPermissions;
import todoapp.dom.seed.roles.CommandModuleRoleAndPermissions;
import todoapp.dom.seed.roles.ApacheIsisPersistableMixinsRoleAndPermissions;
import todoapp.dom.seed.roles.SessionLoggerModuleRoleAndPermissions;
import todoapp.dom.seed.roles.SettingsModuleRoleAndPermissions;
import todoapp.dom.seed.roles.ToDoAppFixtureServiceRoleAndPermissions;
import todoapp.dom.seed.roles.ToDoAppRegularRoleAndPermissions;
import todoapp.fixture.module.DeleteUserAndUserRolesAndToDoItems;
import todoapp.fixture.module.security.CreateUserFixtureScript;
/*
 *  Copyright 2014 Dan Haywood
 *
 *  Licensed under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 */
package todoapp.fixture.scenarios;




public class RecreateSvenUserAndRolesAndToDoItems extends CreateUserFixtureScript {

    public static final String USER_NAME = "sven";
    public static final String EMAIL_ADDRESS = "sven@example.com";

    public RecreateSvenUserAndRolesAndToDoItems() {
        withDiscoverability(Discoverability.DISCOVERABLE);
    }

    @Override
    protected void execute(ExecutionContext ec) {

        ec.setParameter("username", USER_NAME);

        // teardown
        ec.executeChild(this, new DeleteUserAndUserRolesAndToDoItems());

        // create user
        ec.executeChild(this, new CreateUserFixtureScript() {{ setEmailAddress(EMAIL_ADDRESS); }});

        // setup roles
        ec.executeChild(this, new UserRolesFixtureScript() {{
            setRoleNames(Arrays.asList(
                    IsisModuleSecurityAdminRoleAndPermissions.ROLE_NAME,
                    ToDoAppRegularRoleAndPermissions.ROLE_NAME,
                    ToDoAppFixtureServiceRoleAndPermissions.ROLE_NAME,
                    AuditModuleRoleAndPermissions.ROLE_NAME,
                    CommandModuleRoleAndPermissions.ROLE_NAME,
                    SessionLoggerModuleRoleAndPermissions.ROLE_NAME,
                    SettingsModuleRoleAndPermissions.ROLE_NAME,
                    ApacheIsisPersistableMixinsRoleAndPermissions.ROLE_NAME,