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);
}
}
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());
}
}
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());
}
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;
}
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();
}
Aggregations