Search in sources :

Example 66 with Role

use of com.serotonin.m2m2.vo.role.Role in project ma-core-public by infiniteautomation.

the class AssertionUtils method assertRoles.

default void assertRoles(Set<Role> expected, Set<Role> actual) {
    assertEquals(expected.size(), actual.size());
    Set<Role> missing = new HashSet<>();
    for (Role expectedRole : expected) {
        boolean found = false;
        for (Role actualRole : actual) {
            if (StringUtils.equals(expectedRole.getXid(), actualRole.getXid())) {
                found = true;
                break;
            }
        }
        if (!found) {
            missing.add(expectedRole);
        }
    }
    if (missing.size() > 0) {
        StringBuilder missingRoles = new StringBuilder();
        for (Role missingRole : missing) {
            missingRoles.append("< ").append(missingRole.getId()).append(" - ").append(missingRole.getXid()).append("> ");
        }
        fail("Not all roles matched, missing: " + missingRoles);
    }
}
Also used : Role(com.serotonin.m2m2.vo.role.Role) HashSet(java.util.HashSet)

Example 67 with Role

use of com.serotonin.m2m2.vo.role.Role in project ma-core-public by infiniteautomation.

the class DataSourceDaoDeadlockDetection method detectDeadlockWithEventHandlerRoleMappingandDataSourceTablesExplicit.

@Test
public void detectDeadlockWithEventHandlerRoleMappingandDataSourceTablesExplicit() {
    // This will create 2x threads for each operating as one of the desired problem scenarios
    int numThreads = 5;
    int numDataSources = 10;
    AtomicInteger running = new AtomicInteger(numThreads * 2);
    PermissionService permissionService = Common.getBean(PermissionService.class);
    // Insert some roles
    int roleCount = 0;
    RoleService roleService = Common.getBean(RoleService.class);
    List<RoleVO> roleVOs = new ArrayList<>();
    Set<Role> roles = new HashSet<>();
    for (int i = 0; i < roleCount; i++) {
        RoleVO role = new RoleVO(Common.NEW_ID, Common.generateXid("ROLE_"), "Role " + i);
        roleVOs.add(role);
        roleService.insert(role);
        roles.add(role.getRole());
    }
    DataSource dataSource = Common.getBean(DatabaseProxy.class).getDataSource();
    JdbcConnectionPool pool = (JdbcConnectionPool) dataSource;
    pool.setMaxConnections(numThreads * 2);
    PlatformTransactionManager transactionManager = Common.getBean(DatabaseProxy.class).getTransactionManager();
    AtomicInteger successes = new AtomicInteger();
    AtomicInteger failures = new AtomicInteger();
    MutableObject<Exception> failure = new MutableObject<>(null);
    for (int i = 0; i < numThreads; i++) {
        // #5 lock eventHandlerMappings and roleMappings and then try to lock dataSources
        // Basically delete a data source
        new Thread() {

            @Override
            public void run() {
                try {
                    for (int i = 0; i < numDataSources; i++) {
                        // Insert an event handler
                        EventHandlerService eventHandlerService = Common.getBean(EventHandlerService.class);
                        ProcessEventHandlerVO eh = new ProcessEventHandlerVO();
                        eh.setDefinition(new ProcessEventHandlerDefinition());
                        eh.setName(Common.generateXid("Handler "));
                        eh.setActiveProcessCommand("ls");
                        eventHandlerService.insert(eh);
                        ExtendedJdbcTemplate ejt = new ExtendedJdbcTemplate(dataSource);
                        // Get event handler
                        AbstractEventHandlerVO myEventHandler = eventHandlerService.get(eh.getXid());
                        // Create data source
                        MockDataSourceVO ds = new MockDataSourceVO();
                        ds.setName(Common.generateXid("Mock "));
                        DataSourceService dataSourceService = Common.getBean(DataSourceService.class);
                        dataSourceService.insert(ds);
                        // Insert a mapping
                        myEventHandler.setEventTypes(Collections.singletonList(new EventTypeMatcher(new DataSourceEventType(ds.getId(), ds.getPollAbortedExceptionEventId()))));
                        eventHandlerService.update(eh.getXid(), myEventHandler);
                        new TransactionTemplate(transactionManager).execute((status) -> {
                            // The order of these statements matters for deadlock, we must always lock groups of tables in the same order
                            ejt.update("DELETE FROM dataSources WHERE id=?", new Object[] { ds.getId() });
                            ejt.update("DELETE FROM eventHandlersMapping WHERE eventTypeName=? AND eventTypeRef1=?", new Object[] { EventTypeNames.DATA_SOURCE, ds.getId() });
                            return null;
                        });
                        successes.getAndIncrement();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    failure.setValue(e);
                    failures.getAndIncrement();
                } finally {
                    running.decrementAndGet();
                }
            }
        }.start();
        // #8 lock dataSources and try to lock roleMappings
        // Basically update a data source
        new Thread() {

            @Override
            public void run() {
                try {
                    for (int i = 0; i < numDataSources; i++) {
                        ExtendedJdbcTemplate ejt = new ExtendedJdbcTemplate(dataSource);
                        // Insert an event handler
                        EventHandlerService eventHandlerService = Common.getBean(EventHandlerService.class);
                        ProcessEventHandlerVO eh = new ProcessEventHandlerVO();
                        eh.setDefinition(new ProcessEventHandlerDefinition());
                        eh.setName(Common.generateXid("Handler "));
                        eh.setActiveProcessCommand("ls");
                        eventHandlerService.insert(eh);
                        // Get event handler
                        AbstractEventHandlerVO myEventHandler = eventHandlerService.get(eh.getXid());
                        // Create data source
                        MockDataSourceVO ds = new MockDataSourceVO();
                        ds.setName(Common.generateXid("Mock "));
                        DataSourceService dataSourceService = Common.getBean(DataSourceService.class);
                        dataSourceService.insert(ds);
                        // Insert a mapping
                        myEventHandler.setEventTypes(Collections.singletonList(new EventTypeMatcher(new DataSourceEventType(ds.getId(), ds.getPollAbortedExceptionEventId()))));
                        eventHandlerService.update(eh.getXid(), myEventHandler);
                        new TransactionTemplate(transactionManager).execute((status) -> {
                            ejt.update("UPDATE dataSources SET xid=? WHERE id=?", new Object[] { ds.getXid() + "1", ds.getId() });
                            return null;
                        });
                        successes.getAndIncrement();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    failure.setValue(e);
                    failures.getAndIncrement();
                } finally {
                    running.decrementAndGet();
                }
            }
        }.start();
    }
    while (running.get() > 0) {
        try {
            Thread.sleep(100);
        } catch (Exception e) {
        }
    }
    if (failures.get() > 0) {
        fail("Ran " + successes.get() + " queries: " + failure.getValue().getMessage());
    }
}
Also used : DataSourceService(com.infiniteautomation.mango.spring.service.DataSourceService) Role(com.serotonin.m2m2.vo.role.Role) BeforeClass(org.junit.BeforeClass) EventHandlerService(com.infiniteautomation.mango.spring.service.EventHandlerService) ProcessEventHandlerDefinition(com.serotonin.m2m2.module.definitions.event.handlers.ProcessEventHandlerDefinition) EventTypeNames(com.serotonin.m2m2.rt.event.type.EventType.EventTypeNames) MockDataSourceVO(com.serotonin.m2m2.vo.dataSource.mock.MockDataSourceVO) ProcessEventHandlerVO(com.serotonin.m2m2.vo.event.ProcessEventHandlerVO) LoggerFactory(org.slf4j.LoggerFactory) DataSourceEventType(com.serotonin.m2m2.rt.event.type.DataSourceEventType) DataPointVO(com.serotonin.m2m2.vo.DataPointVO) ArrayList(java.util.ArrayList) ExtendedJdbcTemplate(com.serotonin.db.spring.ExtendedJdbcTemplate) HashSet(java.util.HashSet) EventTypeMatcher(com.serotonin.m2m2.rt.event.type.EventTypeMatcher) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RoleVO(com.serotonin.m2m2.vo.role.RoleVO) DataSource(javax.sql.DataSource) MangoTestBase(com.serotonin.m2m2.MangoTestBase) DataPointService(com.infiniteautomation.mango.spring.service.DataPointService) Assert.fail(org.junit.Assert.fail) MutableObject(org.apache.commons.lang3.mutable.MutableObject) MockPointLocatorVO(com.serotonin.m2m2.vo.dataPoint.MockPointLocatorVO) Logger(org.slf4j.Logger) Common(com.serotonin.m2m2.Common) DatabaseProxy(com.serotonin.m2m2.db.DatabaseProxy) Set(java.util.Set) Test(org.junit.Test) UUID(java.util.UUID) AbstractEventHandlerVO(com.serotonin.m2m2.vo.event.AbstractEventHandlerVO) List(java.util.List) PlatformTransactionManager(org.springframework.transaction.PlatformTransactionManager) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) Collections(java.util.Collections) PermissionService(com.infiniteautomation.mango.spring.service.PermissionService) RoleService(com.infiniteautomation.mango.spring.service.RoleService) JdbcConnectionPool(org.h2.jdbcx.JdbcConnectionPool) ArrayList(java.util.ArrayList) ExtendedJdbcTemplate(com.serotonin.db.spring.ExtendedJdbcTemplate) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) AbstractEventHandlerVO(com.serotonin.m2m2.vo.event.AbstractEventHandlerVO) PermissionService(com.infiniteautomation.mango.spring.service.PermissionService) EventHandlerService(com.infiniteautomation.mango.spring.service.EventHandlerService) HashSet(java.util.HashSet) MutableObject(org.apache.commons.lang3.mutable.MutableObject) ProcessEventHandlerVO(com.serotonin.m2m2.vo.event.ProcessEventHandlerVO) MockDataSourceVO(com.serotonin.m2m2.vo.dataSource.mock.MockDataSourceVO) EventTypeMatcher(com.serotonin.m2m2.rt.event.type.EventTypeMatcher) DataSourceEventType(com.serotonin.m2m2.rt.event.type.DataSourceEventType) JdbcConnectionPool(org.h2.jdbcx.JdbcConnectionPool) DatabaseProxy(com.serotonin.m2m2.db.DatabaseProxy) PlatformTransactionManager(org.springframework.transaction.PlatformTransactionManager) DataSource(javax.sql.DataSource) DataSourceService(com.infiniteautomation.mango.spring.service.DataSourceService) Role(com.serotonin.m2m2.vo.role.Role) ProcessEventHandlerDefinition(com.serotonin.m2m2.module.definitions.event.handlers.ProcessEventHandlerDefinition) RoleVO(com.serotonin.m2m2.vo.role.RoleVO) RoleService(com.infiniteautomation.mango.spring.service.RoleService) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MutableObject(org.apache.commons.lang3.mutable.MutableObject) Test(org.junit.Test)

Example 68 with Role

use of com.serotonin.m2m2.vo.role.Role in project ma-modules-public by infiniteautomation.

the class UserModel method fromVO.

@Override
public void fromVO(User vo) {
    super.fromVO(vo);
    this.username = vo.getUsername();
    this.password = vo.getPassword();
    this.email = vo.getEmail();
    this.phone = vo.getPhone();
    this.disabled = vo.isDisabled();
    this.homeUrl = vo.getHomeUrl();
    this.lastLogin = vo.getLastLogin() == 0 ? null : new Date(vo.getLastLogin());
    this.lastPasswordChange = new Date(vo.getPasswordChangeTimestamp());
    this.receiveAlarmEmails = vo.getReceiveAlarmEmails();
    this.timezone = StringUtils.isBlank(vo.getTimezone()) ? null : vo.getTimezone();
    this.muted = vo.isMuted();
    this.receiveOwnAuditEvents = vo.isReceiveOwnAuditEvents();
    this.roles = new HashSet<>();
    for (Role role : vo.getRoles()) {
        roles.add(role.getXid());
    }
    // TODO move this into the model mapper and use map/unmap anywhere
    // a user model is needed
    PermissionService permissionService = Common.getBean(PermissionService.class);
    this.inheritedRoles = new HashSet<>();
    Set<Role> getAllInheritedRoles = permissionService.getAllInheritedRoles(vo);
    for (Role role : getAllInheritedRoles) {
        this.inheritedRoles.add(role.getXid());
    }
    this.systemPermissions = permissionService.getSystemPermissions(vo);
    this.locale = StringUtils.isBlank(vo.getLocale()) ? null : vo.getLocale();
    this.passwordLocked = vo.isPasswordLocked();
    this.sessionExpirationOverride = vo.isSessionExpirationOverride();
    if (sessionExpirationOverride)
        this.sessionExpirationPeriod = new TimePeriod(vo.getSessionExpirationPeriods(), TimePeriodType.valueOf(vo.getSessionExpirationPeriodType()));
    this.organization = vo.getOrganization();
    this.organizationalRole = vo.getOrganizationalRole();
    this.created = vo.getCreated();
    this.emailVerified = vo.getEmailVerifiedDate();
    this.data = vo.getData();
    this.editPermission = new MangoPermissionModel(vo.getEditPermission());
    this.readPermission = new MangoPermissionModel(vo.getReadPermission());
}
Also used : Role(com.serotonin.m2m2.vo.role.Role) PermissionService(com.infiniteautomation.mango.spring.service.PermissionService) TimePeriod(com.infiniteautomation.mango.rest.latest.model.time.TimePeriod) MangoPermissionModel(com.infiniteautomation.mango.rest.latest.model.permissions.MangoPermissionModel) Date(java.util.Date)

Example 69 with Role

use of com.serotonin.m2m2.vo.role.Role in project ma-modules-public by infiniteautomation.

the class RoleModelMapping method unmap.

@Override
public RoleVO unmap(Object from, PermissionHolder user, RestModelMapper mapper) throws ValidationException {
    RoleModel model = (RoleModel) from;
    RoleVO vo = model.toVO();
    Set<Role> roles = new HashSet<>();
    if (model.getInherited() != null) {
        for (String xid : model.getInherited()) {
            Role role = service.getRole(xid);
            if (role != null) {
                roles.add(role);
            } else {
                roles.add(new Role(Common.NEW_ID, xid));
            }
        }
    }
    vo.setInherited(roles);
    return vo;
}
Also used : Role(com.serotonin.m2m2.vo.role.Role) RoleVO(com.serotonin.m2m2.vo.role.RoleVO) HashSet(java.util.HashSet)

Example 70 with Role

use of com.serotonin.m2m2.vo.role.Role in project ma-modules-public by infiniteautomation.

the class WatchListVO method jsonRead.

@Override
public void jsonRead(JsonReader reader, JsonObject jsonObject) throws JsonException {
    super.jsonRead(reader, jsonObject);
    String type = jsonObject.getString("type");
    try {
        this.type = WatchListType.valueOf(type.toUpperCase(Locale.ROOT));
    } catch (IllegalArgumentException e) {
        this.type = null;
    }
    JsonValue read = jsonObject.get("readPermission");
    if (read != null) {
        this.readPermission = reader.read(MangoPermission.class, read);
    }
    JsonValue edit = jsonObject.get("editPermission");
    if (edit != null) {
        this.editPermission = reader.read(MangoPermission.class, edit);
    }
    if (jsonObject.containsKey("user")) {
        String username = jsonObject.getString("user");
        if (StringUtils.isBlank(username))
            throw new TranslatableJsonException("emport.error.missingValue", "user");
        User user = UserDao.getInstance().getByXid(username);
        if (user == null) {
            throw new TranslatableJsonException("emport.error.missingUser", username);
        } else if (!Common.getBean(PermissionService.class).hasAdminRole(user)) {
            RoleDao dao = Common.getBean(RoleDao.class);
            String name = jsonObject.getString("name", new TranslatableMessage("header.watchlist").translate(user.getTranslations()));
            // Create a role for this user to be able to edit this item
            String editName = new TranslatableMessage("watchList.watchListEditRolePrefix", name).translate(user.getTranslations());
            RoleVO editRole = new RoleVO(Common.NEW_ID, UUID.randomUUID().toString(), editName);
            dao.insert(editRole);
            Set<Set<Role>> editRoles = new HashSet<>(this.editPermission.getRoles());
            editRoles.add(Collections.singleton(editRole.getRole()));
            this.editPermission = new MangoPermission(editRoles);
            // Create a role for this user to be able to read this item
            String readName = new TranslatableMessage("watchList.watchListReadRolePrefix", name).translate(user.getTranslations());
            RoleVO readRole = new RoleVO(Common.NEW_ID, UUID.randomUUID().toString(), readName);
            dao.insert(readRole);
            Set<Set<Role>> readRoles = new HashSet<>(this.readPermission.getRoles());
            readRoles.add(Collections.singleton(readRole.getRole()));
            this.readPermission = new MangoPermission(readRoles);
            // Update the user to have this role
            UserDao userDao = Common.getBean(UserDao.class);
            Set<Role> newUserRoles = new HashSet<>(user.getRoles());
            newUserRoles.add(editRole.getRole());
            newUserRoles.add(readRole.getRole());
            user.setRoles(newUserRoles);
            userDao.update(user.getId(), user);
        }
    }
    JsonArray jsonDataPoints = jsonObject.getJsonArray("dataPoints");
    if (jsonDataPoints != null) {
        List<IDataPoint> points = new ArrayList<>();
        DataPointDao dataPointDao = DataPointDao.getInstance();
        for (JsonValue jv : jsonDataPoints) {
            String xid = jv.toString();
            DataPointSummary dpVO = dataPointDao.getSummary(xid);
            if (dpVO == null)
                throw new TranslatableJsonException("emport.error.missingPoint", xid);
            points.add(dpVO);
        }
        pointList.set(points);
    }
    JsonObject o = jsonObject.getJsonObject("data");
    if (o != null)
        this.data = o.toMap();
}
Also used : DataPointSummary(com.serotonin.m2m2.vo.DataPointSummary) User(com.serotonin.m2m2.vo.User) HashSet(java.util.HashSet) Set(java.util.Set) DataPointDao(com.serotonin.m2m2.db.dao.DataPointDao) JsonValue(com.serotonin.json.type.JsonValue) ArrayList(java.util.ArrayList) TranslatableJsonException(com.serotonin.m2m2.i18n.TranslatableJsonException) JsonObject(com.serotonin.json.type.JsonObject) PermissionService(com.infiniteautomation.mango.spring.service.PermissionService) Role(com.serotonin.m2m2.vo.role.Role) JsonArray(com.serotonin.json.type.JsonArray) RoleVO(com.serotonin.m2m2.vo.role.RoleVO) UserDao(com.serotonin.m2m2.db.dao.UserDao) RoleDao(com.serotonin.m2m2.db.dao.RoleDao) IDataPoint(com.serotonin.m2m2.vo.IDataPoint) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) MangoPermission(com.infiniteautomation.mango.permission.MangoPermission)

Aggregations

Role (com.serotonin.m2m2.vo.role.Role)102 Test (org.junit.Test)59 HashSet (java.util.HashSet)40 Set (java.util.Set)38 User (com.serotonin.m2m2.vo.User)33 MangoPermission (com.infiniteautomation.mango.permission.MangoPermission)23 RoleVO (com.serotonin.m2m2.vo.role.RoleVO)22 Collectors (java.util.stream.Collectors)18 Common (com.serotonin.m2m2.Common)17 MangoTestBase (com.serotonin.m2m2.MangoTestBase)15 RoleDao (com.serotonin.m2m2.db.dao.RoleDao)15 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)15 List (java.util.List)15 PermissionService (com.infiniteautomation.mango.spring.service.PermissionService)14 Assert.assertEquals (org.junit.Assert.assertEquals)14 Assert.assertTrue (org.junit.Assert.assertTrue)14 DataPointService (com.infiniteautomation.mango.spring.service.DataPointService)12 PermissionHolder (com.serotonin.m2m2.vo.permission.PermissionHolder)12 IDataPoint (com.serotonin.m2m2.vo.IDataPoint)11 DSLContext (org.jooq.DSLContext)11