MIFOSX-97: some tidy up around users,roles and permissions in prep for command work.

This commit is contained in:
Keith Woodlock
2012-11-22 12:22:41 +00:00
parent baba0b809e
commit 85de5e92c2
28 changed files with 1467 additions and 1673 deletions
@@ -31,16 +31,17 @@ public class PermissionsApiResource {
@Autowired @Autowired
private PortfolioApiJsonSerializerService apiJsonSerializerService; private PortfolioApiJsonSerializerService apiJsonSerializerService;
private final String entityType = "PERMISSION";
@Autowired @Autowired
private PlatformSecurityContext context; private PlatformSecurityContext context;
private final String resourceNameForPermissions = "PERMISSION";
@GET @GET
@Consumes({MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public String retrieveAllPermissions(@Context final UriInfo uriInfo) { public String retrieveAllPermissions(@Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType); context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions);
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
@@ -53,16 +53,17 @@ public class RolesApiResource {
@Autowired @Autowired
private PortfolioApiJsonSerializerService apiJsonSerializerService; private PortfolioApiJsonSerializerService apiJsonSerializerService;
private final String entityType = "ROLE";
@Autowired @Autowired
private PlatformSecurityContext context; private PlatformSecurityContext context;
private final String resourceNameForPermissions = "ROLE";
@GET @GET
@Consumes({MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public String retrieveAllRoles(@Context final UriInfo uriInfo) { public String retrieveAllRoles(@Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType); context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions);
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
@@ -78,7 +79,7 @@ public class RolesApiResource {
@Produces({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public String retrieveNewRoleDetails(@Context final UriInfo uriInfo) { public String retrieveNewRoleDetails(@Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType); context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions);
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
@@ -116,7 +117,7 @@ public class RolesApiResource {
@Produces({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public String retrieveRole(@PathParam("roleId") final Long roleId, @Context final UriInfo uriInfo) { public String retrieveRole(@PathParam("roleId") final Long roleId, @Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType); context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions);
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
@@ -152,20 +153,19 @@ public class RolesApiResource {
@Produces({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public String retrieveRolePermissions(@PathParam("roleId") final Long roleId, @Context final UriInfo uriInfo) { public String retrieveRolePermissions(@PathParam("roleId") final Long roleId, @Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType); context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions);
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
RoleData role = this.roleReadPlatformService.retrieveRole(roleId); final RoleData role = this.roleReadPlatformService.retrieveRole(roleId);
Collection<PermissionUsageData> permissionUsageData = this.permissionReadPlatformService.retrieveAllRolePermissions(roleId); final Collection<PermissionUsageData> permissionUsageData = this.permissionReadPlatformService.retrieveAllRolePermissions(roleId);
RolePermissionsData permissionsData = new RolePermissionsData(role.getId(), role.getName(), role.getDescription(),
permissionUsageData); final RolePermissionsData permissionsData = role.toRolePermissionData(permissionUsageData);
return this.apiJsonSerializerService.serializeRolePermissionDataToJson(prettyPrint, responseParameters, permissionsData); return this.apiJsonSerializerService.serializeRolePermissionDataToJson(prettyPrint, responseParameters, permissionsData);
} }
@PUT @PUT
@Path("{roleId}/permissions") @Path("{roleId}/permissions")
@Consumes({MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_JSON})
@@ -1,9 +1,7 @@
package org.mifosng.platform.api; package org.mifosng.platform.api;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@@ -56,26 +54,22 @@ public class UsersApiResource {
@Autowired @Autowired
private PortfolioApiJsonSerializerService apiJsonSerializerService; private PortfolioApiJsonSerializerService apiJsonSerializerService;
private final String entityType = "USER";
@Autowired @Autowired
private PlatformSecurityContext context; private PlatformSecurityContext context;
private static final Set<String> typicalResponseParameters = new HashSet<String>(Arrays.asList("id", "officeId", "officeName", "username", "firstname", "lastname", "email", "selectedRoles")); private final String resourceNameForPermissions = "USER";
@GET @GET
@Consumes({MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public String retrieveUsers(@Context final UriInfo uriInfo) { public String retrieveUsers(@Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType); context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions);
Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
if (responseParameters.isEmpty()) { final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
responseParameters.addAll(typicalResponseParameters);
}
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
Collection<AppUserData> users = this.appUserReadPlatformService.retrieveAllUsers(); final Collection<AppUserData> users = this.appUserReadPlatformService.retrieveAllUsers();
return this.apiJsonSerializerService.serializeAppUserDataToJson(prettyPrint, responseParameters, users); return this.apiJsonSerializerService.serializeAppUserDataToJson(prettyPrint, responseParameters, users);
} }
@@ -86,47 +80,33 @@ public class UsersApiResource {
@Produces({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public String retrieveUser(@PathParam("userId") final Long userId, @Context final UriInfo uriInfo) { public String retrieveUser(@PathParam("userId") final Long userId, @Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType); context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions);
Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
if (responseParameters.isEmpty()) { final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
responseParameters.addAll(typicalResponseParameters); final boolean template = ApiParameterHelper.template(uriInfo.getQueryParameters());
}
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
boolean template = ApiParameterHelper.template(uriInfo.getQueryParameters());
AppUserData user = this.appUserReadPlatformService.retrieveUser(userId); AppUserData user = this.appUserReadPlatformService.retrieveUser(userId);
if (template) { if (template) {
List<OfficeLookup> offices = new ArrayList<OfficeLookup>(this.officeReadPlatformService.retrieveAllOfficesForLookup()); List<OfficeLookup> offices = new ArrayList<OfficeLookup>(this.officeReadPlatformService.retrieveAllOfficesForLookup());
user = new AppUserData(user, offices); user = new AppUserData(user, offices);
addTemplateRelatedParameters(responseParameters);
} }
return this.apiJsonSerializerService.serializeAppUserDataToJson(prettyPrint, responseParameters, user); return this.apiJsonSerializerService.serializeAppUserDataToJson(prettyPrint, responseParameters, user);
} }
private void addTemplateRelatedParameters(final Set<String> responseParameters) {
responseParameters.add("allowedOffices");
responseParameters.add("availableRoles");
}
@GET @GET
@Path("template") @Path("template")
@Consumes({MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public String newUserDetails(@Context final UriInfo uriInfo) { public String newUserDetails(@Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType); context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions);
Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
if (responseParameters.isEmpty()) { final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
responseParameters.addAll(typicalResponseParameters);
}
addTemplateRelatedParameters(responseParameters);
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); final AppUserData user = this.appUserReadPlatformService.retrieveNewUserDetails();
AppUserData user = this.appUserReadPlatformService.retrieveNewUserDetails();
return this.apiJsonSerializerService.serializeAppUserDataToJson(prettyPrint, responseParameters, user); return this.apiJsonSerializerService.serializeAppUserDataToJson(prettyPrint, responseParameters, user);
} }
@@ -136,9 +116,9 @@ public class UsersApiResource {
@Produces({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public Response createUser(final String jsonRequestBody) { public Response createUser(final String jsonRequestBody) {
UserCommand command = this.apiDataConversionService.convertJsonToUserCommand(null, jsonRequestBody); final UserCommand command = this.apiDataConversionService.convertJsonToUserCommand(null, jsonRequestBody);
Long userId = this.appUserWritePlatformService.createUser(command); final Long userId = this.appUserWritePlatformService.createUser(command);
return Response.ok().entity(new EntityIdentifier(userId)).build(); return Response.ok().entity(new EntityIdentifier(userId)).build();
} }
@@ -159,9 +139,9 @@ public class UsersApiResource {
@Produces({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public Response updateUser(@PathParam("userId") final Long userId, final String jsonRequestBody) { public Response updateUser(@PathParam("userId") final Long userId, final String jsonRequestBody) {
UserCommand command = this.apiDataConversionService.convertJsonToUserCommand(userId, jsonRequestBody); final UserCommand command = this.apiDataConversionService.convertJsonToUserCommand(userId, jsonRequestBody);
AppUser loggedInUser = context.authenticatedUser(); final AppUser loggedInUser = context.authenticatedUser();
if (loggedInUser.hasIdOf(userId)) { if (loggedInUser.hasIdOf(userId)) {
this.appUserWritePlatformService.updateUsersOwnAccountDetails(command); this.appUserWritePlatformService.updateUsersOwnAccountDetails(command);
@@ -13,7 +13,7 @@ public class RoleCommand {
private final Set<String> modifiedParameters; private final Set<String> modifiedParameters;
public RoleCommand(Set<String> modifiedParameters, final Long id, final String name, final String description, final String[] permissionIds) { public RoleCommand(Set<String> modifiedParameters, final Long id, final String name, final String description) {
this.modifiedParameters = modifiedParameters; this.modifiedParameters = modifiedParameters;
this.id = id; this.id = id;
this.name = name; this.name = name;
@@ -39,8 +39,4 @@ public class RoleCommand {
public boolean isDescriptionChanged() { public boolean isDescriptionChanged() {
return this.modifiedParameters.contains("description"); return this.modifiedParameters.contains("description");
} }
public boolean isPermissionsChanged() {
return this.modifiedParameters.contains("permissions");
}
} }
@@ -16,13 +16,13 @@ public class AppUserData {
private final String lastname; private final String lastname;
private final String email; private final String email;
@SuppressWarnings("unused")
private final List<OfficeLookup> allowedOffices; private final List<OfficeLookup> allowedOffices;
private final List<RoleData> availableRoles; private final List<RoleData> availableRoles;
private final List<RoleData> selectedRoles; private final List<RoleData> selectedRoles;
public AppUserData(final Long id, final String username, public AppUserData(final Long id, final String username, final String email, final Long officeId, final String officeName,
final String email, final Long officeId, final String firstname, final String lastname, final List<RoleData> availableRoles, final List<RoleData> selectedRoles) {
final String officeName, final String firstname, final String lastname, final List<RoleData> availableRoles, final List<RoleData> selectedRoles) {
this.id = id; this.id = id;
this.username = username; this.username = username;
this.officeId = officeId; this.officeId = officeId;
@@ -36,18 +36,18 @@ public class AppUserData {
this.selectedRoles = selectedRoles; this.selectedRoles = selectedRoles;
} }
public AppUserData(AppUserData user, List<OfficeLookup> allowedOffices) { public AppUserData(final AppUserData user, final List<OfficeLookup> allowedOffices) {
this.id = user.getId(); this.id = user.id;
this.username = user.getUsername(); this.username = user.username;
this.officeId = user.getOfficeId(); this.officeId = user.officeId;
this.officeName = user.getOfficeName(); this.officeName = user.officeName;
this.firstname = user.getFirstname(); this.firstname = user.firstname;
this.lastname = user.getLastname(); this.lastname = user.lastname;
this.email = user.getEmail(); this.email = user.email;
this.allowedOffices = allowedOffices; this.allowedOffices = allowedOffices;
this.availableRoles = user.getAvailableRoles(); this.availableRoles = user.availableRoles;
this.selectedRoles = user.getSelectedRoles(); this.selectedRoles = user.selectedRoles;
} }
public AppUserData(final List<OfficeLookup> allowedOffices, final List<RoleData> availableRoles) { public AppUserData(final List<OfficeLookup> allowedOffices, final List<RoleData> availableRoles) {
@@ -64,43 +64,11 @@ public class AppUserData {
this.selectedRoles = new ArrayList<RoleData>(); this.selectedRoles = new ArrayList<RoleData>();
} }
public Long getId() { public boolean hasIdentifyOf(final Long createdById) {
return id; return this.id.equals(createdById);
} }
public String getUsername() { public String username() {
return username; return this.username;
}
public Long getOfficeId() {
return officeId;
}
public String getOfficeName() {
return officeName;
}
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
public String getEmail() {
return email;
}
public List<OfficeLookup> getAllowedOffices() {
return allowedOffices;
}
public List<RoleData> getAvailableRoles() {
return availableRoles;
}
public List<RoleData> getSelectedRoles() {
return selectedRoles;
} }
} }
@@ -1,9 +1,14 @@
package org.mifosng.platform.api.data; package org.mifosng.platform.api.data;
/**
* Immutable data object used for office lookups (will remove eventually and just use {@link OfficeData}.
*/
public class OfficeLookup { public class OfficeLookup {
private Long id; private Long id;
@SuppressWarnings("unused")
private String name; private String name;
@SuppressWarnings("unused")
private String nameDecorated; private String nameDecorated;
public OfficeLookup(final Long id, final String name, final String nameDecorated) { public OfficeLookup(final Long id, final String name, final String nameDecorated) {
@@ -12,16 +17,7 @@ public class OfficeLookup {
this.nameDecorated = nameDecorated; this.nameDecorated = nameDecorated;
} }
public Long getId() { public boolean hasIdentifyOf(final Long officeId) {
return this.id; return this.id.equals(officeId);
} }
public String getName() {
return this.name;
}
public String getNameDecorated() {
return nameDecorated;
}
} }
@@ -1,11 +1,19 @@
package org.mifosng.platform.api.data; package org.mifosng.platform.api.data;
/**
* Immutable representation of permissions
*/
public class PermissionUsageData { public class PermissionUsageData {
@SuppressWarnings("unused")
private final String grouping; private final String grouping;
@SuppressWarnings("unused")
private final String code; private final String code;
@SuppressWarnings("unused")
private final String entityName; private final String entityName;
@SuppressWarnings("unused")
private final String actionName; private final String actionName;
@SuppressWarnings("unused")
private final Boolean selected; private final Boolean selected;
public PermissionUsageData(final String grouping, final String code, final String entityName, final String actionName, public PermissionUsageData(final String grouping, final String code, final String entityName, final String actionName,
@@ -16,25 +24,4 @@ public class PermissionUsageData {
this.actionName = actionName; this.actionName = actionName;
this.selected = selected; this.selected = selected;
} }
public String getGrouping() {
return grouping;
}
public String getCode() {
return code;
}
public String getEntityName() {
return entityName;
}
public String getActionName() {
return actionName;
}
public Boolean getSelected() {
return selected;
}
} }
@@ -31,6 +31,7 @@ public class RoleData {
this.availablePermissions = null; this.availablePermissions = null;
this.selectedPermissions = selectedPermissions; this.selectedPermissions = selectedPermissions;
} }
public RoleData(final Collection<PermissionData> availablePermissions, final Collection<PermissionData> selectedPermissions) { public RoleData(final Collection<PermissionData> availablePermissions, final Collection<PermissionData> selectedPermissions) {
this.id = null; this.id = null;
this.name = null; this.name = null;
@@ -62,16 +63,7 @@ public class RoleData {
return this.selectedPermissions; return this.selectedPermissions;
} }
public Long getId() { public RolePermissionsData toRolePermissionData(final Collection<PermissionUsageData> permissionUsageData) {
return id; return new RolePermissionsData(id, name, description, permissionUsageData);
} }
public String getName() {
return name;
}
public String getDescription() {
return description;
}
} }
@@ -2,12 +2,19 @@ package org.mifosng.platform.api.data;
import java.util.Collection; import java.util.Collection;
/**
* Immutable data object reprsenting a role with associated permissions.
*/
public class RolePermissionsData { public class RolePermissionsData {
@SuppressWarnings("unused")
private final Long id; private final Long id;
@SuppressWarnings("unused")
private final String name; private final String name;
@SuppressWarnings("unused")
private final String description; private final String description;
@SuppressWarnings("unused")
private final Collection<PermissionUsageData> permissionUsageData; private final Collection<PermissionUsageData> permissionUsageData;
public RolePermissionsData(final Long id, final String name, final String description, public RolePermissionsData(final Long id, final String name, final String description,
@@ -17,21 +24,4 @@ public class RolePermissionsData {
this.description = description; this.description = description;
this.permissionUsageData = permissionUsageData; this.permissionUsageData = permissionUsageData;
} }
public Long getId() {
return id;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public Collection<PermissionUsageData> getPermissionUsageData() {
return permissionUsageData;
}
} }
@@ -241,28 +241,10 @@ public class PortfolioApiDataConversionServiceImpl implements PortfolioApiDataCo
Set<String> modifiedParameters = new HashSet<String>(); Set<String> modifiedParameters = new HashSet<String>();
// check array
JsonParser parser = new JsonParser();
String[] permissionIds = null;
JsonElement element = parser.parse(json);
if (element.isJsonObject()) {
JsonObject object = element.getAsJsonObject();
if (object.has("permissions")) {
modifiedParameters.add("permissions");
JsonArray array = object.get("permissions").getAsJsonArray();
permissionIds = new String[array.size()];
for (int i = 0; i < array.size(); i++) {
permissionIds[i] = array.get(i).getAsString();
}
}
}
//
String name = extractStringParameter("name", requestMap, modifiedParameters); String name = extractStringParameter("name", requestMap, modifiedParameters);
String description = extractStringParameter("description", requestMap, modifiedParameters); String description = extractStringParameter("description", requestMap, modifiedParameters);
return new RoleCommand(modifiedParameters, resourceIdentifier, name, description, permissionIds); return new RoleCommand(modifiedParameters, resourceIdentifier, name, description);
} }
@Override @Override
@@ -43,10 +43,8 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
private final AppUserReadPlatformService appUserReadPlatformService; private final AppUserReadPlatformService appUserReadPlatformService;
@Autowired @Autowired
public ClientReadPlatformServiceImpl(final PlatformSecurityContext context, public ClientReadPlatformServiceImpl(final PlatformSecurityContext context, final TenantAwareRoutingDataSource dataSource,
final TenantAwareRoutingDataSource dataSource, final OfficeReadPlatformService officeReadPlatformService, final AppUserReadPlatformService appUserReadPlatformService) {
final OfficeReadPlatformService officeReadPlatformService,
final AppUserReadPlatformService appUserReadPlatformService) {
this.context = context; this.context = context;
this.officeReadPlatformService = officeReadPlatformService; this.officeReadPlatformService = officeReadPlatformService;
this.appUserReadPlatformService = appUserReadPlatformService; this.appUserReadPlatformService = appUserReadPlatformService;
@@ -64,8 +62,7 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
String sql = "select " + rm.clientSchema(); String sql = "select " + rm.clientSchema();
if (StringUtils.isNotBlank(extraCriteria)) if (StringUtils.isNotBlank(extraCriteria)) sql += " and (" + extraCriteria + ")";
sql += " and (" + extraCriteria + ")";
sql += " order by c.lastname ASC, c.firstname ASC"; sql += " order by c.lastname ASC, c.firstname ASC";
@@ -129,19 +126,16 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
return ClientData.template(officeId, new LocalDate(), offices); return ClientData.template(officeId, new LocalDate(), offices);
} }
private static final class ClientMapper implements RowMapper<ClientData> { private static final class ClientMapper implements RowMapper<ClientData> {
public String clientSchema() { public String clientSchema() {
return "c.office_id as officeId, o.name as officeName, c.id as id, c.firstname as firstname, c.lastname as lastname, c.display_name as displayName, " + return "c.office_id as officeId, o.name as officeName, c.id as id, c.firstname as firstname, c.lastname as lastname, c.display_name as displayName, "
"c.external_id as externalId, c.joining_date as joinedDate, c.image_key as imagekey from m_client c join m_office o on o.id = c.office_id " + + "c.external_id as externalId, c.joining_date as joinedDate, c.image_key as imagekey from m_client c join m_office o on o.id = c.office_id "
" where o.hierarchy like ? and c.is_deleted=0 "; + " where o.hierarchy like ? and c.is_deleted=0 ";
} }
@Override @Override
public ClientData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) public ClientData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
throws SQLException {
final Long officeId = JdbcSupport.getLong(rs, "officeId"); final Long officeId = JdbcSupport.getLong(rs, "officeId");
final Long id = JdbcSupport.getLong(rs, "id"); final Long id = JdbcSupport.getLong(rs, "id");
@@ -156,8 +150,8 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
final String imageKey = rs.getString("imageKey"); final String imageKey = rs.getString("imageKey");
final String officeName = rs.getString("officeName"); final String officeName = rs.getString("officeName");
return new ClientData(officeId, officeName, id, firstname, return new ClientData(officeId, officeName, id, firstname, lastname, displayName, externalId, joinedDate, imageKey, null, null,
lastname, displayName, externalId, joinedDate,imageKey, null, null, null); null);
} }
} }
@@ -165,9 +159,8 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
private static final class ClientLookupMapper implements RowMapper<ClientLookup> { private static final class ClientLookupMapper implements RowMapper<ClientLookup> {
public String clientLookupSchema() { public String clientLookupSchema() {
return "c.id as id, c.firstname as firstname, c.lastname as lastname, " + return "c.id as id, c.firstname as firstname, c.lastname as lastname, " + "c.office_id as officeId, o.name as officeName "
"c.office_id as officeId, o.name as officeName " + + "from m_client c join m_office o on o.id = c.office_id where c.is_deleted=0 ";
"from m_client c join m_office o on o.id = c.office_id where c.is_deleted=0 ";
} }
@Override @Override
@@ -233,7 +226,8 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
ClientDespoitAccountSummaryDataMapper depositAccountMapper = new ClientDespoitAccountSummaryDataMapper(); ClientDespoitAccountSummaryDataMapper depositAccountMapper = new ClientDespoitAccountSummaryDataMapper();
String depositAccountsSql = "select " + depositAccountMapper.schema() + " where da.client_id = ? and da.is_deleted=0"; String depositAccountsSql = "select " + depositAccountMapper.schema() + " where da.client_id = ? and da.is_deleted=0";
List<ClientAccountSummaryData> depositAccountResults = this.jdbcTemplate.query(depositAccountsSql, depositAccountMapper, new Object[] {clientId}); List<ClientAccountSummaryData> depositAccountResults = this.jdbcTemplate.query(depositAccountsSql, depositAccountMapper,
new Object[] { clientId });
if (depositAccountResults != null) { if (depositAccountResults != null) {
for (ClientAccountSummaryData row : depositAccountResults) { for (ClientAccountSummaryData row : depositAccountResults) {
@@ -256,8 +250,8 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
} }
return new ClientAccountSummaryCollectionData(pendingApprovalLoans, awaitingDisbursalLoans, openLoans, closedLoans, return new ClientAccountSummaryCollectionData(pendingApprovalLoans, awaitingDisbursalLoans, openLoans, closedLoans,
pendingApprovalDepositAccounts, approvedDepositAccounts, withdrawnByClientDespositAccounts, pendingApprovalDepositAccounts, approvedDepositAccounts, withdrawnByClientDespositAccounts, rejectedDepositAccounts,
rejectedDepositAccounts,closedDepositAccounts,preclosedDepositAccounts,maturedDepositAccounts); closedDepositAccounts, preclosedDepositAccounts, maturedDepositAccounts);
} catch (EmptyResultDataAccessException e) { } catch (EmptyResultDataAccessException e) {
throw new ClientNotFoundException(clientId); throw new ClientNotFoundException(clientId);
} }
@@ -280,24 +274,19 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
return loanAccounts; return loanAccounts;
} }
private static final class ClientLoanAccountSummaryDataMapper implements private static final class ClientLoanAccountSummaryDataMapper implements RowMapper<ClientAccountSummaryData> {
RowMapper<ClientAccountSummaryData> {
public String loanAccountSummarySchema() { public String loanAccountSummarySchema() {
StringBuilder accountsSummary = new StringBuilder("l.id as id, l.external_id as externalId,"); StringBuilder accountsSummary = new StringBuilder("l.id as id, l.external_id as externalId,");
accountsSummary accountsSummary.append("l.product_id as productId, lp.name as productName,").append("l.loan_status_id as statusId ")
.append("l.product_id as productId, lp.name as productName,") .append("from m_loan l ").append("LEFT JOIN m_product_loan AS lp ON lp.id = l.product_id ");
.append("l.loan_status_id as statusId ")
.append("from m_loan l ")
.append("LEFT JOIN m_product_loan AS lp ON lp.id = l.product_id ");
return accountsSummary.toString(); return accountsSummary.toString();
} }
@Override @Override
public ClientAccountSummaryData mapRow(final ResultSet rs, public ClientAccountSummaryData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
@SuppressWarnings("unused") final int rowNum) throws SQLException {
Long id = JdbcSupport.getLong(rs, "id"); Long id = JdbcSupport.getLong(rs, "id");
String externalId = rs.getString("externalId"); String externalId = rs.getString("externalId");
@@ -314,17 +303,14 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
public String schema() { public String schema() {
StringBuilder accountsSummary = new StringBuilder("da.id as id, da.external_id as externalId,"); StringBuilder accountsSummary = new StringBuilder("da.id as id, da.external_id as externalId,");
accountsSummary.append("da.product_id as productId, dp.name as productName,") accountsSummary.append("da.product_id as productId, dp.name as productName,").append("da.status_enum as statusId ")
.append("da.status_enum as statusId ") .append("from m_deposit_account da ").append("LEFT JOIN m_product_deposit AS dp ON dp.id = da.product_id ");
.append("from m_deposit_account da ")
.append("LEFT JOIN m_product_deposit AS dp ON dp.id = da.product_id ");
return accountsSummary.toString(); return accountsSummary.toString();
} }
@Override @Override
public ClientAccountSummaryData mapRow(final ResultSet rs, public ClientAccountSummaryData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
@SuppressWarnings("unused") final int rowNum) throws SQLException {
Long id = JdbcSupport.getLong(rs, "id"); Long id = JdbcSupport.getLong(rs, "id");
String externalId = rs.getString("externalId"); String externalId = rs.getString("externalId");
@@ -336,8 +322,6 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
} }
} }
@Override @Override
public NoteData retrieveClientNote(Long clientId, Long noteId) { public NoteData retrieveClientNote(Long clientId, Long noteId) {
@@ -349,13 +333,11 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
// FIXME - use join on sql query to fetch user information for note // FIXME - use join on sql query to fetch user information for note
// rather than fetching users? // rather than fetching users?
Collection<AppUserData> allUsers = this.appUserReadPlatformService Collection<AppUserData> allUsers = this.appUserReadPlatformService.retrieveAllUsers();
.retrieveAllUsers();
NoteMapper noteMapper = new NoteMapper(allUsers); NoteMapper noteMapper = new NoteMapper(allUsers);
String sql = "select " + noteMapper.schema() String sql = "select " + noteMapper.schema() + " where n.client_id = ? and n.id = ?";
+ " where n.client_id = ? and n.id = ?";
return this.jdbcTemplate.queryForObject(sql, noteMapper, new Object[] { clientId, noteId }); return this.jdbcTemplate.queryForObject(sql, noteMapper, new Object[] { clientId, noteId });
} catch (EmptyResultDataAccessException e) { } catch (EmptyResultDataAccessException e) {
@@ -373,14 +355,11 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
// FIXME - use join on sql query to fetch user information for note // FIXME - use join on sql query to fetch user information for note
// rather than fetching users? // rather than fetching users?
Collection<AppUserData> allUsers = this.appUserReadPlatformService Collection<AppUserData> allUsers = this.appUserReadPlatformService.retrieveAllUsers();
.retrieveAllUsers();
NoteMapper noteMapper = new NoteMapper(allUsers); NoteMapper noteMapper = new NoteMapper(allUsers);
String sql = "select " String sql = "select " + noteMapper.schema() + " where n.client_id = ? order by n.created_date DESC";
+ noteMapper.schema()
+ " where n.client_id = ? order by n.created_date DESC";
return this.jdbcTemplate.query(sql, noteMapper, new Object[] { clientId }); return this.jdbcTemplate.query(sql, noteMapper, new Object[] { clientId });
} }
@@ -400,8 +379,7 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
} }
@Override @Override
public NoteData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) public NoteData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
throws SQLException {
Long id = JdbcSupport.getLong(rs, "id"); Long id = JdbcSupport.getLong(rs, "id");
Long clientId = JdbcSupport.getLong(rs, "clientId"); Long clientId = JdbcSupport.getLong(rs, "clientId");
@@ -415,21 +393,19 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
Long createdById = JdbcSupport.getLong(rs, "createdById"); Long createdById = JdbcSupport.getLong(rs, "createdById");
String createdByUsername = findUserById(createdById, allUsers); String createdByUsername = findUserById(createdById, allUsers);
DateTime lastModifiedDate = JdbcSupport.getDateTime(rs, DateTime lastModifiedDate = JdbcSupport.getDateTime(rs, "lastModifiedDate");
"lastModifiedDate");
Long lastModifiedById = JdbcSupport.getLong(rs, "lastModifiedById"); Long lastModifiedById = JdbcSupport.getLong(rs, "lastModifiedById");
String updatedByUsername = findUserById(createdById, allUsers); String updatedByUsername = findUserById(createdById, allUsers);
return new NoteData(id, clientId, loanId, transactionId, noteType, return new NoteData(id, clientId, loanId, transactionId, noteType, note, createdDate, createdById, createdByUsername,
note, createdDate, createdById, createdByUsername,
lastModifiedDate, lastModifiedById, updatedByUsername); lastModifiedDate, lastModifiedById, updatedByUsername);
} }
private String findUserById(Long createdById, Collection<AppUserData> allUsers) { private String findUserById(final Long createdById, final Collection<AppUserData> allUsers) {
String username = ""; String username = "";
for (AppUserData appUserData : allUsers) { for (AppUserData appUserData : allUsers) {
if (appUserData.getId().equals(createdById)) { if (appUserData.hasIdentifyOf(createdById)) {
username = appUserData.getUsername(); username = appUserData.username();
break; break;
} }
} }
@@ -454,9 +430,7 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
} }
@Override @Override
public ClientIdentifierData retrieveClientIdentifier( public ClientIdentifierData retrieveClientIdentifier(final Long clientId, final Long clientIdentifierId) {
final Long clientId,
final Long clientIdentifierId) {
try { try {
AppUser currentUser = context.authenticatedUser(); AppUser currentUser = context.authenticatedUser();
String hierarchy = currentUser.getOffice().getHierarchy(); String hierarchy = currentUser.getOffice().getHierarchy();
@@ -468,8 +442,7 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
sql += " and ci.id = ?"; sql += " and ci.id = ?";
final ClientIdentifierData clientIdentifierData = this.jdbcTemplate final ClientIdentifierData clientIdentifierData = this.jdbcTemplate.queryForObject(sql, rm, new Object[] { clientId,
.queryForObject(sql, rm, new Object[] { clientId,
hierarchySearchString, clientIdentifierId }); hierarchySearchString, clientIdentifierId });
return clientIdentifierData; return clientIdentifierData;
@@ -481,22 +454,18 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
private static final class ClientIdentityMapper implements RowMapper<ClientIdentifierData> { private static final class ClientIdentityMapper implements RowMapper<ClientIdentifierData> {
public ClientIdentityMapper() { public ClientIdentityMapper() {}
}
public String schema() { public String schema() {
return "ci.id as id, ci.client_id as clientId, ci.document_type_id as documentTypeId, ci.document_key as documentKey," return "ci.id as id, ci.client_id as clientId, ci.document_type_id as documentTypeId, ci.document_key as documentKey,"
+ " ci.description as description, cv.code_value as documentType " + " ci.description as description, cv.code_value as documentType "
+ " from m_client_identifier ci, m_client c, m_office o, m_code_value cv" + " from m_client_identifier ci, m_client c, m_office o, m_code_value cv"
+ " where ci.client_id=c.id and c.office_id=o.id" + " where ci.client_id=c.id and c.office_id=o.id" + " and ci.document_type_id=cv.id"
+ " and ci.document_type_id=cv.id"
+ " and ci.client_id = ? and o.hierarchy like ? "; + " and ci.client_id = ? and o.hierarchy like ? ";
} }
@Override @Override
public ClientIdentifierData mapRow(final ResultSet rs, public ClientIdentifierData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
@SuppressWarnings("unused") final int rowNum)
throws SQLException {
final Long id = JdbcSupport.getLong(rs, "id"); final Long id = JdbcSupport.getLong(rs, "id");
final Long clientId = JdbcSupport.getLong(rs, "clientId"); final Long clientId = JdbcSupport.getLong(rs, "clientId");
@@ -511,9 +480,7 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
} }
@Override @Override
public ClientData retrieveClientByIdentifier( public ClientData retrieveClientByIdentifier(final Long identifierTypeId, final String identifierKey) {
final Long identifierTypeId,
final String identifierKey) {
try { try {
final ClientIdentifierMapper mapper = new ClientIdentifierMapper(); final ClientIdentifierMapper mapper = new ClientIdentifierMapper();
@@ -528,17 +495,13 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
private static final class ClientIdentifierMapper implements RowMapper<ClientData> { private static final class ClientIdentifierMapper implements RowMapper<ClientData> {
public String clientLookupByIdentifierSchema() { public String clientLookupByIdentifierSchema() {
return "c.id as id, c.firstname as firstname, c.lastname as lastname, " return "c.id as id, c.firstname as firstname, c.lastname as lastname, " + "c.office_id as officeId, o.name as officeName "
+ "c.office_id as officeId, o.name as officeName " + "from m_client c, m_office o, m_client_identifier ci " + "where o.id = c.office_id and c.id=ci.client_id "
+ "from m_client c, m_office o, m_client_identifier ci "
+ "where o.id = c.office_id and c.id=ci.client_id "
+ "and ci.document_type_id= ? and ci.document_key like ?"; + "and ci.document_type_id= ? and ci.document_key like ?";
} }
@Override @Override
public ClientData mapRow(final ResultSet rs, public ClientData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
@SuppressWarnings("unused") final int rowNum)
throws SQLException {
final Long id = rs.getLong("id"); final Long id = rs.getLong("id");
String firstname = rs.getString("firstname"); String firstname = rs.getString("firstname");
@@ -2,6 +2,6 @@ package org.mifosng.platform.makerchecker.service;
public interface ChangeDetectionService { public interface ChangeDetectionService {
String detectChanges(String operation, String resourceName, Long resourceId, String commandSerializedAsJson); String detectChangesOnUpdate(String resourceName, Long resourceId, String commandSerializedAsJson);
} }
@@ -24,11 +24,11 @@ public class ChangeDetectionServiceJdbc implements ChangeDetectionService {
} }
@Override @Override
public String detectChanges(final String operation, final String resourceName, final Long resourceId, public String detectChangesOnUpdate(final String resourceName, final Long resourceId, final String commandSerializedAsJson) {
final String commandSerializedAsJson) {
String changesOnlyJson = ""; String changesOnlyJson = "";
if ("clients".equalsIgnoreCase(resourceName)) {
// FIXME - KW/JW - this change detection code for update of clients // FIXME - KW/JW - this change detection code for update of clients
// using ClientCommand can re placed when more suitable sql version is // using ClientCommand can re placed when more suitable sql version is
// implemented. // implemented.
@@ -41,6 +41,9 @@ public class ChangeDetectionServiceJdbc implements ChangeDetectionService {
final ClientCommand changesOnly = this.apiDataConversionService.detectChanges(resourceId, baseJson, workingJson); final ClientCommand changesOnly = this.apiDataConversionService.detectChanges(resourceId, baseJson, workingJson);
changesOnlyJson = this.apiJsonSerializerService.serializeClientCommandToJson(changesOnly); changesOnlyJson = this.apiJsonSerializerService.serializeClientCommandToJson(changesOnly);
} else {
changesOnlyJson = commandSerializedAsJson;
}
return changesOnlyJson; return changesOnlyJson;
} }
@@ -57,8 +57,7 @@ public class ClientCommandHandler implements CommandSourceHandler {
} }
} else if (commandSource.isUpdate()) { } else if (commandSource.isUpdate()) {
try { try {
final String jsonOfChangesOnly = this.changeDetectionService.detectChanges(commandSource.operation(), final String jsonOfChangesOnly = this.changeDetectionService.detectChangesOnUpdate(commandSource.resourceName(), commandSource.resourceId(), commandSerializedAsJson);
commandSource.resourceName(), commandSource.resourceId(), commandSerializedAsJson);
commandSourceResult.updateJsonTo(jsonOfChangesOnly); commandSourceResult.updateJsonTo(jsonOfChangesOnly);
final ClientCommand changesOnly = this.apiDataConversionService.convertInternalJsonFormatToClientCommand( final ClientCommand changesOnly = this.apiDataConversionService.convertInternalJsonFormatToClientCommand(
@@ -34,8 +34,7 @@ public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService
@Autowired @Autowired
public OfficeReadPlatformServiceImpl(final PlatformSecurityContext context, public OfficeReadPlatformServiceImpl(final PlatformSecurityContext context,
final CurrencyReadPlatformService currencyReadPlatformService, final CurrencyReadPlatformService currencyReadPlatformService, final TenantAwareRoutingDataSource dataSource) {
final TenantAwareRoutingDataSource dataSource) {
this.context = context; this.context = context;
this.currencyReadPlatformService = currencyReadPlatformService; this.currencyReadPlatformService = currencyReadPlatformService;
this.jdbcTemplate = new JdbcTemplate(dataSource); this.jdbcTemplate = new JdbcTemplate(dataSource);
@@ -51,8 +50,7 @@ public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService
} }
@Override @Override
public OfficeData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) public OfficeData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
throws SQLException {
Long id = rs.getLong("id"); Long id = rs.getLong("id");
String name = rs.getString("name"); String name = rs.getString("name");
@@ -64,23 +62,18 @@ public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService
String parentName = rs.getString("parentName"); String parentName = rs.getString("parentName");
List<OfficeLookup> allowedParents = new ArrayList<OfficeLookup>(); List<OfficeLookup> allowedParents = new ArrayList<OfficeLookup>();
return new OfficeData(id, name, nameDecorated, externalId, return new OfficeData(id, name, nameDecorated, externalId, openingDate, hierarchy, parentId, parentName, allowedParents);
openingDate, hierarchy, parentId, parentName,
allowedParents);
} }
} }
private static final class OfficeLookupMapper implements private static final class OfficeLookupMapper implements RowMapper<OfficeLookup> {
RowMapper<OfficeLookup> {
public String officeLookupSchema() { public String officeLookupSchema() {
return " o.id as id, " + nameDecoratedBaseOnHierarchy return " o.id as id, " + nameDecoratedBaseOnHierarchy + " as nameDecorated, o.name as name from m_office o ";
+ " as nameDecorated, o.name as name from m_office o ";
} }
@Override @Override
public OfficeLookup mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) public OfficeLookup mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
throws SQLException {
Long id = rs.getLong("id"); Long id = rs.getLong("id");
String name = rs.getString("name"); String name = rs.getString("name");
@@ -90,8 +83,7 @@ public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService
} }
} }
private static final class OfficeTransactionMapper implements private static final class OfficeTransactionMapper implements RowMapper<OfficeTransactionData> {
RowMapper<OfficeTransactionData> {
public String officeTransactionSchema() { public String officeTransactionSchema() {
return " ot.id as id, ot.transaction_date as transactionDate, ot.from_office_id as fromOfficeId, fromoff.name as fromOfficeName, " return " ot.id as id, ot.transaction_date as transactionDate, ot.from_office_id as fromOfficeId, fromoff.name as fromOfficeName, "
@@ -101,17 +93,14 @@ public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService
+ " from m_office_transaction ot " + " from m_office_transaction ot "
+ " left join m_office fromoff on fromoff.id = ot.from_office_id " + " left join m_office fromoff on fromoff.id = ot.from_office_id "
+ " left join m_office tooff on tooff.id = ot.to_office_id " + " left join m_office tooff on tooff.id = ot.to_office_id " + " join m_currency rc on rc.`code` = ot.currency_code";
+ " join m_currency rc on rc.`code` = ot.currency_code";
} }
@Override @Override
public OfficeTransactionData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) public OfficeTransactionData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
throws SQLException {
Long id = rs.getLong("id"); Long id = rs.getLong("id");
LocalDate transactionDate = JdbcSupport.getLocalDate(rs, LocalDate transactionDate = JdbcSupport.getLocalDate(rs, "transactionDate");
"transactionDate");
Long fromOfficeId = JdbcSupport.getLong(rs, "fromOfficeId"); Long fromOfficeId = JdbcSupport.getLong(rs, "fromOfficeId");
String fromOfficeName = rs.getString("fromOfficeName"); String fromOfficeName = rs.getString("fromOfficeName");
Long toOfficeId = JdbcSupport.getLong(rs, "toOfficeId"); Long toOfficeId = JdbcSupport.getLong(rs, "toOfficeId");
@@ -120,21 +109,16 @@ public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService
String currencyCode = rs.getString("currencyCode"); String currencyCode = rs.getString("currencyCode");
String currencyName = rs.getString("currencyName"); String currencyName = rs.getString("currencyName");
String currencyNameCode = rs.getString("currencyNameCode"); String currencyNameCode = rs.getString("currencyNameCode");
String currencyDisplaySymbol = rs String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol");
.getString("currencyDisplaySymbol"); Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits");
Integer currencyDigits = JdbcSupport.getInteger(rs,
"currencyDigits");
CurrencyData currencyData = new CurrencyData(currencyCode, CurrencyData currencyData = new CurrencyData(currencyCode, currencyName, currencyDigits, currencyDisplaySymbol,
currencyName, currencyDigits, currencyDisplaySymbol,
currencyNameCode); currencyNameCode);
BigDecimal transactionAmount = rs BigDecimal transactionAmount = rs.getBigDecimal("transactionAmount");
.getBigDecimal("transactionAmount");
String description = rs.getString("description"); String description = rs.getString("description");
return new OfficeTransactionData(id, transactionDate, fromOfficeId, return new OfficeTransactionData(id, transactionDate, fromOfficeId, fromOfficeName, toOfficeId, toOfficeName, currencyData,
fromOfficeName, toOfficeId, toOfficeName, currencyData,
transactionAmount, description); transactionAmount, description);
} }
} }
@@ -148,11 +132,9 @@ public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService
String hierarchySearchString = hierarchy + "%"; String hierarchySearchString = hierarchy + "%";
OfficeMapper rm = new OfficeMapper(); OfficeMapper rm = new OfficeMapper();
String sql = "select " + rm.officeSchema() String sql = "select " + rm.officeSchema() + "where o.hierarchy like ? order by o.hierarchy";
+ "where o.hierarchy like ? order by o.hierarchy";
return this.jdbcTemplate.query(sql, rm, return this.jdbcTemplate.query(sql, rm, new Object[] { hierarchySearchString });
new Object[] { hierarchySearchString });
} }
@Override @Override
@@ -163,11 +145,9 @@ public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService
String hierarchySearchString = hierarchy + "%"; String hierarchySearchString = hierarchy + "%";
OfficeLookupMapper rm = new OfficeLookupMapper(); OfficeLookupMapper rm = new OfficeLookupMapper();
String sql = "select " + rm.officeLookupSchema() String sql = "select " + rm.officeLookupSchema() + "where o.hierarchy like ? order by o.hierarchy";
+ "where o.hierarchy like ? order by o.hierarchy";
return this.jdbcTemplate.query(sql, rm, return this.jdbcTemplate.query(sql, rm, new Object[] { hierarchySearchString });
new Object[] { hierarchySearchString });
} }
@Override @Override
@@ -179,8 +159,7 @@ public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService
OfficeMapper rm = new OfficeMapper(); OfficeMapper rm = new OfficeMapper();
String sql = "select " + rm.officeSchema() + " where o.id = ?"; String sql = "select " + rm.officeSchema() + " where o.id = ?";
OfficeData selectedOffice = this.jdbcTemplate.queryForObject(sql, OfficeData selectedOffice = this.jdbcTemplate.queryForObject(sql, rm, new Object[] { officeId });
rm, new Object[] { officeId });
return selectedOffice; return selectedOffice;
} catch (EmptyResultDataAccessException e) { } catch (EmptyResultDataAccessException e) {
@@ -205,12 +184,11 @@ public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService
List<OfficeLookup> filterParentLookups = new ArrayList<OfficeLookup>(); List<OfficeLookup> filterParentLookups = new ArrayList<OfficeLookup>();
if (isNotHeadOffice(officeId)) { if (isNotHeadOffice(officeId)) {
List<OfficeLookup> parentLookups = new ArrayList<OfficeLookup>( List<OfficeLookup> parentLookups = new ArrayList<OfficeLookup>(retrieveAllOfficesForLookup());
retrieveAllOfficesForLookup());
for (OfficeLookup office : parentLookups) { for (OfficeLookup office : parentLookups) {
if (!office.getId().equals(officeId)) { if (!office.hasIdentifyOf(officeId)) {
filterParentLookups.add(office); filterParentLookups.add(office);
} }
} }
@@ -233,25 +211,20 @@ public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService
String hierarchySearchString = hierarchy + "%"; String hierarchySearchString = hierarchy + "%";
OfficeTransactionMapper rm = new OfficeTransactionMapper(); OfficeTransactionMapper rm = new OfficeTransactionMapper();
String sql = "select " String sql = "select " + rm.officeTransactionSchema()
+ rm.officeTransactionSchema()
+ " where (fromoff.hierarchy like ? or tooff.hierarchy like ?) order by ot.transaction_date, ot.id"; + " where (fromoff.hierarchy like ? or tooff.hierarchy like ?) order by ot.transaction_date, ot.id";
return this.jdbcTemplate.query(sql, rm, new Object[] { return this.jdbcTemplate.query(sql, rm, new Object[] { hierarchySearchString, hierarchySearchString });
hierarchySearchString, hierarchySearchString });
} }
@Override @Override
public OfficeTransactionData retrieveNewOfficeTransactionDetails() { public OfficeTransactionData retrieveNewOfficeTransactionDetails() {
context.authenticatedUser(); context.authenticatedUser();
List<OfficeLookup> parentLookups = new ArrayList<OfficeLookup>( List<OfficeLookup> parentLookups = new ArrayList<OfficeLookup>(retrieveAllOfficesForLookup());
retrieveAllOfficesForLookup()); List<CurrencyData> currencyOptions = currencyReadPlatformService.retrieveAllowedCurrencies();
List<CurrencyData> currencyOptions = currencyReadPlatformService
.retrieveAllowedCurrencies();
return new OfficeTransactionData(new LocalDate(), parentLookups, return new OfficeTransactionData(new LocalDate(), parentLookups, currencyOptions);
currencyOptions);
} }
} }
@@ -5,5 +5,4 @@ import org.mifosng.platform.user.domain.AppUser;
public interface PlatformSecurityContext { public interface PlatformSecurityContext {
AppUser authenticatedUser(); AppUser authenticatedUser();
} }
@@ -8,7 +8,8 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
/** /**
* Wrapper around spring security's {@link SecurityContext} for extracted the current authenticated {@link AppUser}. * Wrapper around spring security's {@link SecurityContext} for extracted the
* current authenticated {@link AppUser}.
*/ */
@Service @Service
public class SpringSecurityPlatformSecurityContext implements PlatformSecurityContext { public class SpringSecurityPlatformSecurityContext implements PlatformSecurityContext {
@@ -24,9 +25,7 @@ public class SpringSecurityPlatformSecurityContext implements PlatformSecurityCo
} }
} }
if (currentUser == null) { if (currentUser == null) { throw new UnAuthenticatedUserException(); }
throw new UnAuthenticatedUserException();
}
return currentUser; return currentUser;
} }
@@ -27,8 +27,7 @@ import org.springframework.security.core.userdetails.User;
@Entity @Entity
@Table(name = "m_appuser", uniqueConstraints = @UniqueConstraint(columnNames = { "username" }, name = "username_org")) @Table(name = "m_appuser", uniqueConstraints = @UniqueConstraint(columnNames = { "username" }, name = "username_org"))
public class AppUser extends AbstractAuditableCustom<AppUser, Long> implements public class AppUser extends AbstractAuditableCustom<AppUser, Long> implements PlatformUser {
PlatformUser {
@Column(name = "email", nullable = false, length = 100) @Column(name = "email", nullable = false, length = 100)
private String email; private String email;
@@ -72,10 +71,8 @@ public class AppUser extends AbstractAuditableCustom<AppUser, Long> implements
@JoinTable(name = "m_appuser_role", joinColumns = @JoinColumn(name = "appuser_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) @JoinTable(name = "m_appuser_role", joinColumns = @JoinColumn(name = "appuser_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles; private Set<Role> roles;
public static AppUser createNew(final Office office, public static AppUser createNew(final Office office, final Set<Role> allRoles, final String username, final String email,
final Set<Role> allRoles, final String username, final String firstname, final String lastname, final String password) {
final String email, final String firstname, final String lastname,
final String password) {
boolean userEnabled = true; boolean userEnabled = true;
boolean userAccountNonExpired = true; boolean userAccountNonExpired = true;
@@ -83,12 +80,10 @@ public class AppUser extends AbstractAuditableCustom<AppUser, Long> implements
boolean userAccountNonLocked = true; boolean userAccountNonLocked = true;
Collection<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>(); Collection<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
authorities.add(new SimpleGrantedAuthority( authorities.add(new SimpleGrantedAuthority("DUMMY_ROLE_NOT_USED_OR_PERSISTED_TO_AVOID_EXCEPTION"));
"DUMMY_ROLE_NOT_USED_OR_PERSISTED_TO_AVOID_EXCEPTION"));
User user = new User(username, password, userEnabled, User user = new User(username, password, userEnabled, userAccountNonExpired, userCredentialsNonExpired, userAccountNonLocked,
userAccountNonExpired, userCredentialsNonExpired, authorities);
userAccountNonLocked, authorities);
return new AppUser(office, user, allRoles, email, firstname, lastname); return new AppUser(office, user, allRoles, email, firstname, lastname);
} }
@@ -105,8 +100,8 @@ public class AppUser extends AbstractAuditableCustom<AppUser, Long> implements
this.firstTimeLoginRemaining = true; this.firstTimeLoginRemaining = true;
} }
public AppUser(final Office office, final User user, final Set<Role> roles, public AppUser(final Office office, final User user, final Set<Role> roles, final String email, final String firstname,
final String email, final String firstname, final String lastname) { final String lastname) {
this.office = office; this.office = office;
this.email = email.trim(); this.email = email.trim();
this.username = user.getUsername().trim(); this.username = user.getUsername().trim();
@@ -126,8 +121,7 @@ public class AppUser extends AbstractAuditableCustom<AppUser, Long> implements
this.firstTimeLoginRemaining = false; this.firstTimeLoginRemaining = false;
} }
public void update(final Set<Role> allRoles, final Office office, public void update(final Set<Role> allRoles, final Office office, final UserCommand userCommand) {
final UserCommand userCommand) {
if (userCommand.isRolesChanged() && !allRoles.isEmpty()) { if (userCommand.isRolesChanged() && !allRoles.isEmpty()) {
this.roles.clear(); this.roles.clear();
@@ -178,8 +172,7 @@ public class AppUser extends AbstractAuditableCustom<AppUser, Long> implements
for (Role role : this.roles) { for (Role role : this.roles) {
Collection<Permission> permissions = role.getPermissions(); Collection<Permission> permissions = role.getPermissions();
for (Permission permission : permissions) { for (Permission permission : permissions) {
grantedAuthorities.add(new SimpleGrantedAuthority(permission grantedAuthorities.add(new SimpleGrantedAuthority(permission.code()));
.code()));
} }
} }
return grantedAuthorities; return grantedAuthorities;
@@ -236,75 +229,60 @@ public class AppUser extends AbstractAuditableCustom<AppUser, Long> implements
} }
public boolean canNotApproveLoanInPast() { public boolean canNotApproveLoanInPast() {
return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "APPROVEINPAST_LOAN", return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "APPROVEINPAST_LOAN", "PORTFOLIO_MANAGEMENT_SUPER_USER");
"PORTFOLIO_MANAGEMENT_SUPER_USER");
} }
public boolean canNotRejectLoanInPast() { public boolean canNotRejectLoanInPast() {
return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "REJECTINPAST_LOAN", return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "REJECTINPAST_LOAN", "PORTFOLIO_MANAGEMENT_SUPER_USER");
"PORTFOLIO_MANAGEMENT_SUPER_USER");
} }
public boolean canNotWithdrawByClientLoanInPast() { public boolean canNotWithdrawByClientLoanInPast() {
return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "WITHDRAWINPAST_LOAN", return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "WITHDRAWINPAST_LOAN", "PORTFOLIO_MANAGEMENT_SUPER_USER");
"PORTFOLIO_MANAGEMENT_SUPER_USER");
} }
public boolean canNotDisburseLoanInPast() { public boolean canNotDisburseLoanInPast() {
return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "DISBURSEINPAST_LOAN", return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "DISBURSEINPAST_LOAN", "PORTFOLIO_MANAGEMENT_SUPER_USER");
"PORTFOLIO_MANAGEMENT_SUPER_USER");
} }
public boolean canNotMakeRepaymentOnLoanInPast() { public boolean canNotMakeRepaymentOnLoanInPast() {
return hasNotPermissionForAnyOf("ALL_FUNCTIONS", return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "REPAYMENTINPAST_LOAN", "PORTFOLIO_MANAGEMENT_SUPER_USER");
"REPAYMENTINPAST_LOAN", "PORTFOLIO_MANAGEMENT_SUPER_USER");
} }
public boolean hasNotPermissionForReport(String reportName) { public boolean hasNotPermissionForReport(String reportName) {
if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ", "REPORTING_SUPER_USER", if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ", "REPORTING_SUPER_USER", "READ_" + reportName)) return true;
"READ_" + reportName))
return true;
return false; return false;
} }
public boolean hasNotPermissionForDatatable(String datatable, public boolean hasNotPermissionForDatatable(String datatable, String accessType) {
String accessType) {
String matchPermission = accessType + "_" + datatable; String matchPermission = accessType + "_" + datatable;
if (accessType.equalsIgnoreCase("READ")) { if (accessType.equalsIgnoreCase("READ")) {
if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ", if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ", matchPermission)) return true;
matchPermission))
return true;
return false; return false;
} }
if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", matchPermission)) if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", matchPermission)) return true;
return true;
return false; return false;
} }
public boolean hasNotPermissionForSet(String type, String set, public boolean hasNotPermissionForSet(String type, String set, String accessType) {
String accessType) {
String matchPermission = "CAN_" + accessType + "_" + type + "_x" + set; String matchPermission = "CAN_" + accessType + "_" + type + "_x" + set;
if (accessType.equalsIgnoreCase("READ")) { if (accessType.equalsIgnoreCase("READ")) {
if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ", if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ", matchPermission)) return true;
matchPermission))
return true;
return false; return false;
} }
if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", matchPermission)) if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", matchPermission)) return true;
return true;
return false; return false;
} }
@@ -323,13 +301,10 @@ public class AppUser extends AbstractAuditableCustom<AppUser, Long> implements
public void validateHasReadPermission(final String entityType) { public void validateHasReadPermission(final String entityType) {
String authorizationMessage = "User has no authority to view " String authorizationMessage = "User has no authority to view " + entityType.toLowerCase() + "s";
+ entityType.toLowerCase() + "s";
String matchPermission = "READ_" + entityType.toUpperCase(); String matchPermission = "READ_" + entityType.toUpperCase();
if (!(hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ", if (!(hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ", matchPermission))) return;
matchPermission)))
return;
String higherPermission = ""; String higherPermission = "";
if (entityType.equalsIgnoreCase("CHARGE")) { if (entityType.equalsIgnoreCase("CHARGE")) {
@@ -379,8 +354,7 @@ public class AppUser extends AbstractAuditableCustom<AppUser, Long> implements
} }
if (!(higherPermission.equals(""))) { if (!(higherPermission.equals(""))) {
if (hasNotPermissionForAnyOf(higherPermission)) if (hasNotPermissionForAnyOf(higherPermission)) throw new NoAuthorizationException(authorizationMessage);
throw new NoAuthorizationException(authorizationMessage);
} }
} }
@@ -14,6 +14,7 @@ public interface AppUserWritePlatformService {
@PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'USER_ADMINISTRATION_SUPER_USER', 'DELETE_USER')") @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'USER_ADMINISTRATION_SUPER_USER', 'DELETE_USER')")
void deleteUser(final Long userId); void deleteUser(final Long userId);
// we dont put any permissions on this e.g. a user with no admin rights can change their own details (email, username, password etc). // we dont put any permissions on this e.g. a user with no admin rights can
// change their own details (email, username, password etc).
void updateUsersOwnAccountDetails(UserCommand command); void updateUsersOwnAccountDetails(UserCommand command);
} }
@@ -46,8 +46,9 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit
private final RoleRepository roleRepository; private final RoleRepository roleRepository;
@Autowired @Autowired
public AppUserWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final AppUserRepository appUserRepository, final UserDomainService userDomainService, public AppUserWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final AppUserRepository appUserRepository,
final OfficeRepository officeRepository, final RoleRepository roleRepository, final PlatformPasswordEncoder platformPasswordEncoder) { final UserDomainService userDomainService, final OfficeRepository officeRepository, final RoleRepository roleRepository,
final PlatformPasswordEncoder platformPasswordEncoder) {
this.context = context; this.context = context;
this.appUserRepository = appUserRepository; this.appUserRepository = appUserRepository;
this.userDomainService = userDomainService; this.userDomainService = userDomainService;
@@ -69,19 +70,15 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit
final Set<Role> allRoles = assembleSetOfRoles(command); final Set<Role> allRoles = assembleSetOfRoles(command);
Office office = this.officeRepository.findOne(command.getOfficeId()); Office office = this.officeRepository.findOne(command.getOfficeId());
if (office == null) { if (office == null) { throw new OfficeNotFoundException(command.getOfficeId()); }
throw new OfficeNotFoundException(command.getOfficeId());
}
String password = command.getPassword(); String password = command.getPassword();
if (StringUtils.isBlank(password)) { if (StringUtils.isBlank(password)) {
password = "autogenerate"; password = "autogenerate";
} }
AppUser appUser = AppUser.createNew(office, AppUser appUser = AppUser.createNew(office, allRoles, command.getUsername(), command.getEmail(), command.getFirstname(),
allRoles, command.getUsername(), command.getEmail(), command.getLastname(), password);
command.getFirstname(), command.getLastname(),
password);
this.userDomainService.create(appUser); this.userDomainService.create(appUser);
@@ -91,10 +88,12 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit
return Long.valueOf(-1); return Long.valueOf(-1);
} catch (PlatformEmailSendException e) { } catch (PlatformEmailSendException e) {
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
ApiParameterError error = ApiParameterError.parameterError("error.msg.user.email.invalid", "The parameter email is invalid.", "email", command.getEmail()); ApiParameterError error = ApiParameterError.parameterError("error.msg.user.email.invalid", "The parameter email is invalid.",
"email", command.getEmail());
dataValidationErrors.add(error); dataValidationErrors.add(error);
throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.",
dataValidationErrors);
} }
} }
@@ -113,23 +112,18 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit
Office office = null; Office office = null;
if (command.isOfficeChanged()) { if (command.isOfficeChanged()) {
office = this.officeRepository.findOne(command.getOfficeId()); office = this.officeRepository.findOne(command.getOfficeId());
if (office == null) { if (office == null) { throw new OfficeNotFoundException(command.getOfficeId()); }
throw new OfficeNotFoundException(command.getOfficeId());
}
} }
AppUser userToUpdate = this.appUserRepository.findOne(command.getId()); AppUser userToUpdate = this.appUserRepository.findOne(command.getId());
if (userToUpdate == null) { if (userToUpdate == null) { throw new UserNotFoundException(command.getId()); }
throw new UserNotFoundException(command.getId());
}
userToUpdate.update(allRoles, office, command); userToUpdate.update(allRoles, office, command);
this.appUserRepository.saveAndFlush(userToUpdate); this.appUserRepository.saveAndFlush(userToUpdate);
if (command.isPasswordChanged()) { if (command.isPasswordChanged()) {
PlatformUser dummyPlatformUser = new BasicPasswordEncodablePlatformUser( PlatformUser dummyPlatformUser = new BasicPasswordEncodablePlatformUser(userToUpdate.getId(), userToUpdate.getUsername(),
userToUpdate.getId(), command.getPassword());
userToUpdate.getUsername(), command.getPassword());
String newPasswordEncoded = this.platformPasswordEncoder.encode(dummyPlatformUser); String newPasswordEncoded = this.platformPasswordEncoder.encode(dummyPlatformUser);
@@ -159,9 +153,7 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit
for (String roleId : rolesArray) { for (String roleId : rolesArray) {
Long id = Long.valueOf(roleId); Long id = Long.valueOf(roleId);
Role role = this.roleRepository.findOne(id); Role role = this.roleRepository.findOne(id);
if (role == null) { if (role == null) { throw new RoleNotFoundException(id); }
throw new RoleNotFoundException(id);
}
allRoles.add(role); allRoles.add(role);
} }
} }
@@ -174,23 +166,24 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit
public void deleteUser(final Long userId) { public void deleteUser(final Long userId) {
AppUser user = this.appUserRepository.findOne(userId); AppUser user = this.appUserRepository.findOne(userId);
if (user == null || user.isDeleted()) { if (user == null || user.isDeleted()) { throw new UserNotFoundException(userId); }
throw new UserNotFoundException(userId);
}
user.delete(); user.delete();
this.appUserRepository.save(user); this.appUserRepository.save(user);
} }
/* /*
* Guaranteed to throw an exception no matter what the data integrity issue is. * Guaranteed to throw an exception no matter what the data integrity issue
* is.
*/ */
private void handleDataIntegrityIssues(final UserCommand command, final DataIntegrityViolationException dve) { private void handleDataIntegrityIssues(final UserCommand command, final DataIntegrityViolationException dve) {
Throwable realCause = dve.getMostSpecificCause(); Throwable realCause = dve.getMostSpecificCause();
if (realCause.getMessage().contains("username_org")) { if (realCause.getMessage().contains("username_org")) {
StringBuilder defaultMessageBuilder = new StringBuilder("User with username ").append(command.getUsername()).append(" already exists."); StringBuilder defaultMessageBuilder = new StringBuilder("User with username ").append(command.getUsername()).append(
throw new PlatformDataIntegrityException("error.msg.user.duplicate.username", defaultMessageBuilder.toString(), "username", command.getUsername()); " already exists.");
throw new PlatformDataIntegrityException("error.msg.user.duplicate.username", defaultMessageBuilder.toString(), "username",
command.getUsername());
} }
logger.error(dve.getMessage(), dve); logger.error(dve.getMessage(), dve);
@@ -56,7 +56,7 @@ public class PermissionReadPlatformServiceImpl implements PermissionReadPlatform
} }
@Override @Override
public Collection<PermissionUsageData> retrieveAllRolePermissions(Long roleId) { public Collection<PermissionUsageData> retrieveAllRolePermissions(final Long roleId) {
final PermissionUsageDataMapper mapper = new PermissionUsageDataMapper(); final PermissionUsageDataMapper mapper = new PermissionUsageDataMapper();
final String sql = mapper.schema(); final String sql = mapper.schema();
@@ -64,7 +64,6 @@ public class PermissionReadPlatformServiceImpl implements PermissionReadPlatform
return this.jdbcTemplate.query(sql, mapper, new Object[] { roleId }); return this.jdbcTemplate.query(sql, mapper, new Object[] { roleId });
} }
private static final class PermissionUsageDataMapper implements RowMapper<PermissionUsageData> { private static final class PermissionUsageDataMapper implements RowMapper<PermissionUsageData> {
@Override @Override
@@ -80,10 +79,10 @@ public class PermissionReadPlatformServiceImpl implements PermissionReadPlatform
} }
public String schema() { public String schema() {
return "select p.grouping, p.code, p.entity_name as entityName, p.action_name as actionName, if(isnull(rp.role_id), false, true) as selected " + return "select p.grouping, p.code, p.entity_name as entityName, p.action_name as actionName, if(isnull(rp.role_id), false, true) as selected "
"from m_permission p " + + "from m_permission p "
"left join m_role_permission rp on rp.permission_id = p.id and rp.role_id = ? " + + "left join m_role_permission rp on rp.permission_id = p.id and rp.role_id = ? "
"order by p.grouping, ifnull(entity_name, ''), p.code"; + "order by p.grouping, ifnull(entity_name, ''), p.code";
} }
} }
@@ -24,7 +24,8 @@ public class RoleReadPlatformServiceImpl implements RoleReadPlatformService {
private final RoleRepository roleRepository; private final RoleRepository roleRepository;
@Autowired @Autowired
public RoleReadPlatformServiceImpl(final PlatformSecurityContext context, final TenantAwareRoutingDataSource dataSource, final RoleRepository roleRepository) { public RoleReadPlatformServiceImpl(final PlatformSecurityContext context, final TenantAwareRoutingDataSource dataSource,
final RoleRepository roleRepository) {
this.context = context; this.context = context;
this.roleRepository = roleRepository; this.roleRepository = roleRepository;
this.jdbcTemplate = new JdbcTemplate(dataSource); this.jdbcTemplate = new JdbcTemplate(dataSource);
@@ -45,17 +46,15 @@ public class RoleReadPlatformServiceImpl implements RoleReadPlatformService {
context.authenticatedUser(); context.authenticatedUser();
final Role role = this.roleRepository.findOne(id); final Role role = this.roleRepository.findOne(id);
if (role == null) { if (role == null) { throw new RoleNotFoundException(id); }
throw new RoleNotFoundException(id);
}
return role.toData(); return role.toData();
} }
protected static final class RoleMapper implements RowMapper<RoleData> { protected static final class RoleMapper implements RowMapper<RoleData> {
@Override @Override
public RoleData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) public RoleData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
throws SQLException {
final Long id = JdbcSupport.getLong(rs, "id"); final Long id = JdbcSupport.getLong(rs, "id");
final String name = rs.getString("name"); final String name = rs.getString("name");