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
private PortfolioApiJsonSerializerService apiJsonSerializerService;
private final String entityType = "PERMISSION";
@Autowired
private PlatformSecurityContext context;
private final String resourceNameForPermissions = "PERMISSION";
@GET
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public String retrieveAllPermissions(@Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType);
context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions);
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
@@ -53,16 +53,17 @@ public class RolesApiResource {
@Autowired
private PortfolioApiJsonSerializerService apiJsonSerializerService;
private final String entityType = "ROLE";
@Autowired
private PlatformSecurityContext context;
private final String resourceNameForPermissions = "ROLE";
@GET
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public String retrieveAllRoles(@Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType);
context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions);
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
@@ -74,11 +75,11 @@ public class RolesApiResource {
@GET
@Path("template")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public String retrieveNewRoleDetails(@Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType);
context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions);
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
@@ -91,8 +92,8 @@ public class RolesApiResource {
}
@POST
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public String createRole(final String jsonRequestBody) {
final RoleCommand command = this.apiDataConversionService.convertJsonToRoleCommand(null, jsonRequestBody);
@@ -112,11 +113,11 @@ public class RolesApiResource {
// into account the Object its looking at.
@GET
@Path("{roleId}")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
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 boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
@@ -135,8 +136,8 @@ public class RolesApiResource {
@PUT
@Path("{roleId}")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public String updateRole(@PathParam("roleId") final Long roleId, final String jsonRequestBody) {
final RoleCommand command = this.apiDataConversionService.convertJsonToRoleCommand(roleId, jsonRequestBody);
@@ -148,28 +149,27 @@ public class RolesApiResource {
@GET
@Path("{roleId}/permissions")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
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 boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
RoleData role = this.roleReadPlatformService.retrieveRole(roleId);
Collection<PermissionUsageData> permissionUsageData = this.permissionReadPlatformService.retrieveAllRolePermissions(roleId);
RolePermissionsData permissionsData = new RolePermissionsData(role.getId(), role.getName(), role.getDescription(),
permissionUsageData);
final RoleData role = this.roleReadPlatformService.retrieveRole(roleId);
final Collection<PermissionUsageData> permissionUsageData = this.permissionReadPlatformService.retrieveAllRolePermissions(roleId);
final RolePermissionsData permissionsData = role.toRolePermissionData(permissionUsageData);
return this.apiJsonSerializerService.serializeRolePermissionDataToJson(prettyPrint, responseParameters, permissionsData);
}
@PUT
@Path("{roleId}/permissions")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public String updateRolePermissions(@PathParam("roleId") final Long roleId, final String jsonRequestBody) {
final RolePermissionCommand command = this.apiDataConversionService.convertJsonToRolePermissionCommand(roleId, jsonRequestBody);
@@ -1,9 +1,7 @@
package org.mifosng.platform.api;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@@ -56,26 +54,22 @@ public class UsersApiResource {
@Autowired
private PortfolioApiJsonSerializerService apiJsonSerializerService;
private final String entityType = "USER";
@Autowired
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
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public String retrieveUsers(@Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType);
context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions);
Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
if (responseParameters.isEmpty()) {
responseParameters.addAll(typicalResponseParameters);
}
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final 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);
}
@@ -86,47 +80,33 @@ public class UsersApiResource {
@Produces({MediaType.APPLICATION_JSON})
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());
if (responseParameters.isEmpty()) {
responseParameters.addAll(typicalResponseParameters);
}
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
boolean template = ApiParameterHelper.template(uriInfo.getQueryParameters());
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
final boolean template = ApiParameterHelper.template(uriInfo.getQueryParameters());
AppUserData user = this.appUserReadPlatformService.retrieveUser(userId);
if (template) {
List<OfficeLookup> offices = new ArrayList<OfficeLookup>(this.officeReadPlatformService.retrieveAllOfficesForLookup());
user = new AppUserData(user, offices);
addTemplateRelatedParameters(responseParameters);
}
return this.apiJsonSerializerService.serializeAppUserDataToJson(prettyPrint, responseParameters, user);
}
private void addTemplateRelatedParameters(final Set<String> responseParameters) {
responseParameters.add("allowedOffices");
responseParameters.add("availableRoles");
}
@GET
@Path("template")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public String newUserDetails(@Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType);
context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions);
Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
if (responseParameters.isEmpty()) {
responseParameters.addAll(typicalResponseParameters);
}
addTemplateRelatedParameters(responseParameters);
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
AppUserData user = this.appUserReadPlatformService.retrieveNewUserDetails();
final AppUserData user = this.appUserReadPlatformService.retrieveNewUserDetails();
return this.apiJsonSerializerService.serializeAppUserDataToJson(prettyPrint, responseParameters, user);
}
@@ -136,9 +116,9 @@ public class UsersApiResource {
@Produces({MediaType.APPLICATION_JSON})
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();
}
@@ -159,9 +139,9 @@ public class UsersApiResource {
@Produces({MediaType.APPLICATION_JSON})
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)) {
this.appUserWritePlatformService.updateUsersOwnAccountDetails(command);
@@ -13,7 +13,7 @@ public class RoleCommand {
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.id = id;
this.name = name;
@@ -39,8 +39,4 @@ public class RoleCommand {
public boolean isDescriptionChanged() {
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 email;
@SuppressWarnings("unused")
private final List<OfficeLookup> allowedOffices;
private final List<RoleData> availableRoles;
private final List<RoleData> selectedRoles;
public AppUserData(final Long id, final String username,
final String email, final Long officeId,
final String officeName, final String firstname, final String lastname, final List<RoleData> availableRoles, final List<RoleData> selectedRoles) {
public AppUserData(final Long id, final String username, final String email, final Long officeId, final String officeName,
final String firstname, final String lastname, final List<RoleData> availableRoles, final List<RoleData> selectedRoles) {
this.id = id;
this.username = username;
this.officeId = officeId;
@@ -36,18 +36,18 @@ public class AppUserData {
this.selectedRoles = selectedRoles;
}
public AppUserData(AppUserData user, List<OfficeLookup> allowedOffices) {
this.id = user.getId();
this.username = user.getUsername();
this.officeId = user.getOfficeId();
this.officeName = user.getOfficeName();
this.firstname = user.getFirstname();
this.lastname = user.getLastname();
this.email = user.getEmail();
public AppUserData(final AppUserData user, final List<OfficeLookup> allowedOffices) {
this.id = user.id;
this.username = user.username;
this.officeId = user.officeId;
this.officeName = user.officeName;
this.firstname = user.firstname;
this.lastname = user.lastname;
this.email = user.email;
this.allowedOffices = allowedOffices;
this.availableRoles = user.getAvailableRoles();
this.selectedRoles = user.getSelectedRoles();
this.availableRoles = user.availableRoles;
this.selectedRoles = user.selectedRoles;
}
public AppUserData(final List<OfficeLookup> allowedOffices, final List<RoleData> availableRoles) {
@@ -64,43 +64,11 @@ public class AppUserData {
this.selectedRoles = new ArrayList<RoleData>();
}
public Long getId() {
return id;
public boolean hasIdentifyOf(final Long createdById) {
return this.id.equals(createdById);
}
public String getUsername() {
return 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;
public String username() {
return this.username;
}
}
@@ -1,9 +1,14 @@
package org.mifosng.platform.api.data;
/**
* Immutable data object used for office lookups (will remove eventually and just use {@link OfficeData}.
*/
public class OfficeLookup {
private Long id;
@SuppressWarnings("unused")
private String name;
@SuppressWarnings("unused")
private String nameDecorated;
public OfficeLookup(final Long id, final String name, final String nameDecorated) {
@@ -12,16 +17,7 @@ public class OfficeLookup {
this.nameDecorated = nameDecorated;
}
public Long getId() {
return this.id;
public boolean hasIdentifyOf(final Long officeId) {
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;
/**
* Immutable representation of permissions
*/
public class PermissionUsageData {
@SuppressWarnings("unused")
private final String grouping;
@SuppressWarnings("unused")
private final String code;
@SuppressWarnings("unused")
private final String entityName;
@SuppressWarnings("unused")
private final String actionName;
@SuppressWarnings("unused")
private final Boolean selected;
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.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.selectedPermissions = selectedPermissions;
}
public RoleData(final Collection<PermissionData> availablePermissions, final Collection<PermissionData> selectedPermissions) {
this.id = null;
this.name = null;
@@ -62,16 +63,7 @@ public class RoleData {
return this.selectedPermissions;
}
public Long getId() {
return id;
public RolePermissionsData toRolePermissionData(final Collection<PermissionUsageData> permissionUsageData) {
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;
/**
* Immutable data object reprsenting a role with associated permissions.
*/
public class RolePermissionsData {
@SuppressWarnings("unused")
private final Long id;
@SuppressWarnings("unused")
private final String name;
@SuppressWarnings("unused")
private final String description;
@SuppressWarnings("unused")
private final Collection<PermissionUsageData> permissionUsageData;
public RolePermissionsData(final Long id, final String name, final String description,
@@ -17,21 +24,4 @@ public class RolePermissionsData {
this.description = description;
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>();
// 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 description = extractStringParameter("description", requestMap, modifiedParameters);
return new RoleCommand(modifiedParameters, resourceIdentifier, name, description, permissionIds);
return new RoleCommand(modifiedParameters, resourceIdentifier, name, description);
}
@Override
@@ -43,10 +43,8 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
private final AppUserReadPlatformService appUserReadPlatformService;
@Autowired
public ClientReadPlatformServiceImpl(final PlatformSecurityContext context,
final TenantAwareRoutingDataSource dataSource,
final OfficeReadPlatformService officeReadPlatformService,
final AppUserReadPlatformService appUserReadPlatformService) {
public ClientReadPlatformServiceImpl(final PlatformSecurityContext context, final TenantAwareRoutingDataSource dataSource,
final OfficeReadPlatformService officeReadPlatformService, final AppUserReadPlatformService appUserReadPlatformService) {
this.context = context;
this.officeReadPlatformService = officeReadPlatformService;
this.appUserReadPlatformService = appUserReadPlatformService;
@@ -64,12 +62,11 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
String sql = "select " + rm.clientSchema();
if (StringUtils.isNotBlank(extraCriteria))
sql += " and (" + extraCriteria + ")";
if (StringUtils.isNotBlank(extraCriteria)) sql += " and (" + extraCriteria + ")";
sql += " order by c.lastname ASC, c.firstname ASC";
return this.jdbcTemplate.query(sql, rm, new Object[] {hierarchySearchString});
return this.jdbcTemplate.query(sql, rm, new Object[] { hierarchySearchString });
}
@Override
@@ -85,7 +82,7 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
String sql = "select " + rm.clientSchema() + " and c.id = " + clientId;
return this.jdbcTemplate.queryForObject(sql, rm, new Object[] {hierarchySearchString});
return this.jdbcTemplate.queryForObject(sql, rm, new Object[] { hierarchySearchString });
} catch (EmptyResultDataAccessException e) {
throw new ClientNotFoundException(clientId);
}
@@ -100,7 +97,7 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
String sql = "select " + rm.clientLookupSchema();
if (StringUtils.isNotBlank(extraCriteria)){
if (StringUtils.isNotBlank(extraCriteria)) {
sql += " and (" + extraCriteria + ")";
}
@@ -129,19 +126,16 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
return ClientData.template(officeId, new LocalDate(), offices);
}
private static final class ClientMapper implements RowMapper<ClientData> {
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, " +
"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 ";
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 "
+ " where o.hierarchy like ? and c.is_deleted=0 ";
}
@Override
public ClientData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum)
throws SQLException {
public ClientData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
final Long officeId = JdbcSupport.getLong(rs, "officeId");
final Long id = JdbcSupport.getLong(rs, "id");
@@ -156,18 +150,17 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
final String imageKey = rs.getString("imageKey");
final String officeName = rs.getString("officeName");
return new ClientData(officeId, officeName, id, firstname,
lastname, displayName, externalId, joinedDate,imageKey, null, null, null);
return new ClientData(officeId, officeName, id, firstname, lastname, displayName, externalId, joinedDate, imageKey, null, null,
null);
}
}
private static final class ClientLookupMapper implements RowMapper<ClientLookup>{
private static final class ClientLookupMapper implements RowMapper<ClientLookup> {
public String clientLookupSchema() {
return "c.id as id, c.firstname as firstname, c.lastname as lastname, " +
"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 ";
return "c.id as id, c.firstname as firstname, c.lastname as lastname, " + "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 ";
}
@Override
@@ -204,7 +197,7 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
String sql = "select " + rm.loanAccountSummarySchema() + " where l.client_id = ?";
List<ClientAccountSummaryData> results = this.jdbcTemplate.query(sql, rm, new Object[] {clientId});
List<ClientAccountSummaryData> results = this.jdbcTemplate.query(sql, rm, new Object[] { clientId });
if (results != null) {
for (ClientAccountSummaryData row : results) {
@@ -233,7 +226,8 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
ClientDespoitAccountSummaryDataMapper depositAccountMapper = new ClientDespoitAccountSummaryDataMapper();
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) {
for (ClientAccountSummaryData row : depositAccountResults) {
@@ -249,15 +243,15 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
closedDepositAccounts.add(row);
} else if (row.getAccountStatusId() == 700) {
maturedDepositAccounts.add(row);
}else if (row.getAccountStatusId() == 800) {
} else if (row.getAccountStatusId() == 800) {
preclosedDepositAccounts.add(row);
}
}
}
return new ClientAccountSummaryCollectionData(pendingApprovalLoans, awaitingDisbursalLoans, openLoans, closedLoans,
pendingApprovalDepositAccounts, approvedDepositAccounts, withdrawnByClientDespositAccounts,
rejectedDepositAccounts,closedDepositAccounts,preclosedDepositAccounts,maturedDepositAccounts);
pendingApprovalDepositAccounts, approvedDepositAccounts, withdrawnByClientDespositAccounts, rejectedDepositAccounts,
closedDepositAccounts, preclosedDepositAccounts, maturedDepositAccounts);
} catch (EmptyResultDataAccessException e) {
throw new ClientNotFoundException(clientId);
}
@@ -275,29 +269,24 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
String sql = "select " + rm.loanAccountSummarySchema() + " where l.client_id = ? and l.loan_officer_id = ?";
List<ClientAccountSummaryData> loanAccounts = this.jdbcTemplate.query(sql, rm, new Object[] {clientId, loanOfficerId});
List<ClientAccountSummaryData> loanAccounts = this.jdbcTemplate.query(sql, rm, new Object[] { clientId, loanOfficerId });
return loanAccounts;
}
private static final class ClientLoanAccountSummaryDataMapper implements
RowMapper<ClientAccountSummaryData> {
private static final class ClientLoanAccountSummaryDataMapper implements RowMapper<ClientAccountSummaryData> {
public String loanAccountSummarySchema() {
StringBuilder accountsSummary = new StringBuilder("l.id as id, l.external_id as externalId,");
accountsSummary
.append("l.product_id as productId, lp.name as productName,")
.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 ");
accountsSummary.append("l.product_id as productId, lp.name as productName,").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();
}
@Override
public ClientAccountSummaryData mapRow(final ResultSet rs,
@SuppressWarnings("unused") final int rowNum) throws SQLException {
public ClientAccountSummaryData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
Long id = JdbcSupport.getLong(rs, "id");
String externalId = rs.getString("externalId");
@@ -314,17 +303,14 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
public String schema() {
StringBuilder accountsSummary = new StringBuilder("da.id as id, da.external_id as externalId,");
accountsSummary.append("da.product_id as productId, dp.name as productName,")
.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 ");
accountsSummary.append("da.product_id as productId, dp.name as productName,").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 ");
return accountsSummary.toString();
}
@Override
public ClientAccountSummaryData mapRow(final ResultSet rs,
@SuppressWarnings("unused") final int rowNum) throws SQLException {
public ClientAccountSummaryData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
Long id = JdbcSupport.getLong(rs, "id");
String externalId = rs.getString("externalId");
@@ -336,8 +322,6 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
}
}
@Override
public NoteData retrieveClientNote(Long clientId, Long noteId) {
@@ -349,15 +333,13 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
// FIXME - use join on sql query to fetch user information for note
// rather than fetching users?
Collection<AppUserData> allUsers = this.appUserReadPlatformService
.retrieveAllUsers();
Collection<AppUserData> allUsers = this.appUserReadPlatformService.retrieveAllUsers();
NoteMapper noteMapper = new NoteMapper(allUsers);
String sql = "select " + noteMapper.schema()
+ " where n.client_id = ? and n.id = ?";
String sql = "select " + noteMapper.schema() + " 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) {
throw new NoteNotFoundException(clientId);
}
@@ -373,16 +355,13 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
// FIXME - use join on sql query to fetch user information for note
// rather than fetching users?
Collection<AppUserData> allUsers = this.appUserReadPlatformService
.retrieveAllUsers();
Collection<AppUserData> allUsers = this.appUserReadPlatformService.retrieveAllUsers();
NoteMapper noteMapper = new NoteMapper(allUsers);
String sql = "select "
+ noteMapper.schema()
+ " where n.client_id = ? order by n.created_date DESC";
String sql = "select " + 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 });
}
private static final class NoteMapper implements RowMapper<NoteData> {
@@ -400,8 +379,7 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
}
@Override
public NoteData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum)
throws SQLException {
public NoteData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
Long id = JdbcSupport.getLong(rs, "id");
Long clientId = JdbcSupport.getLong(rs, "clientId");
@@ -415,21 +393,19 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
Long createdById = JdbcSupport.getLong(rs, "createdById");
String createdByUsername = findUserById(createdById, allUsers);
DateTime lastModifiedDate = JdbcSupport.getDateTime(rs,
"lastModifiedDate");
DateTime lastModifiedDate = JdbcSupport.getDateTime(rs, "lastModifiedDate");
Long lastModifiedById = JdbcSupport.getLong(rs, "lastModifiedById");
String updatedByUsername = findUserById(createdById, allUsers);
return new NoteData(id, clientId, loanId, transactionId, noteType,
note, createdDate, createdById, createdByUsername,
return new NoteData(id, clientId, loanId, transactionId, noteType, note, createdDate, createdById, createdByUsername,
lastModifiedDate, lastModifiedById, updatedByUsername);
}
private String findUserById(Long createdById, Collection<AppUserData> allUsers) {
private String findUserById(final Long createdById, final Collection<AppUserData> allUsers) {
String username = "";
for (AppUserData appUserData : allUsers) {
if (appUserData.getId().equals(createdById)) {
username = appUserData.getUsername();
if (appUserData.hasIdentifyOf(createdById)) {
username = appUserData.username();
break;
}
}
@@ -454,9 +430,7 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
}
@Override
public ClientIdentifierData retrieveClientIdentifier(
final Long clientId,
final Long clientIdentifierId) {
public ClientIdentifierData retrieveClientIdentifier(final Long clientId, final Long clientIdentifierId) {
try {
AppUser currentUser = context.authenticatedUser();
String hierarchy = currentUser.getOffice().getHierarchy();
@@ -468,8 +442,7 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
sql += " and ci.id = ?";
final ClientIdentifierData clientIdentifierData = this.jdbcTemplate
.queryForObject(sql, rm, new Object[] { clientId,
final ClientIdentifierData clientIdentifierData = this.jdbcTemplate.queryForObject(sql, rm, new Object[] { clientId,
hierarchySearchString, clientIdentifierId });
return clientIdentifierData;
@@ -481,22 +454,18 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
private static final class ClientIdentityMapper implements RowMapper<ClientIdentifierData> {
public ClientIdentityMapper() {
}
public ClientIdentityMapper() {}
public String schema() {
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 "
+ " 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"
+ " and ci.document_type_id=cv.id"
+ " where ci.client_id=c.id and c.office_id=o.id" + " and ci.document_type_id=cv.id"
+ " and ci.client_id = ? and o.hierarchy like ? ";
}
@Override
public ClientIdentifierData mapRow(final ResultSet rs,
@SuppressWarnings("unused") final int rowNum)
throws SQLException {
public ClientIdentifierData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
final Long id = JdbcSupport.getLong(rs, "id");
final Long clientId = JdbcSupport.getLong(rs, "clientId");
@@ -505,15 +474,13 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
final String description = rs.getString("description");
final String documentTypeName = rs.getString("documentType");
return ClientIdentifierData.singleItem(id, clientId, documentTypeId,documentKey, description,documentTypeName);
return ClientIdentifierData.singleItem(id, clientId, documentTypeId, documentKey, description, documentTypeName);
}
}
@Override
public ClientData retrieveClientByIdentifier(
final Long identifierTypeId,
final String identifierKey) {
public ClientData retrieveClientByIdentifier(final Long identifierTypeId, final String identifierKey) {
try {
final ClientIdentifierMapper mapper = new ClientIdentifierMapper();
@@ -528,17 +495,13 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
private static final class ClientIdentifierMapper implements RowMapper<ClientData> {
public String clientLookupByIdentifierSchema() {
return "c.id as id, c.firstname as firstname, c.lastname as lastname, "
+ "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 "
return "c.id as id, c.firstname as firstname, c.lastname as lastname, " + "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 "
+ "and ci.document_type_id= ? and ci.document_key like ?";
}
@Override
public ClientData mapRow(final ResultSet rs,
@SuppressWarnings("unused") final int rowNum)
throws SQLException {
public ClientData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
final Long id = rs.getLong("id");
String firstname = rs.getString("firstname");
@@ -2,6 +2,6 @@ package org.mifosng.platform.makerchecker.service;
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
public String detectChanges(final String operation, final String resourceName, final Long resourceId,
final String commandSerializedAsJson) {
public String detectChangesOnUpdate(final String resourceName, final Long resourceId, final String commandSerializedAsJson) {
String changesOnlyJson = "";
if ("clients".equalsIgnoreCase(resourceName)) {
// FIXME - KW/JW - this change detection code for update of clients
// using ClientCommand can re placed when more suitable sql version is
// implemented.
@@ -41,6 +41,9 @@ public class ChangeDetectionServiceJdbc implements ChangeDetectionService {
final ClientCommand changesOnly = this.apiDataConversionService.detectChanges(resourceId, baseJson, workingJson);
changesOnlyJson = this.apiJsonSerializerService.serializeClientCommandToJson(changesOnly);
} else {
changesOnlyJson = commandSerializedAsJson;
}
return changesOnlyJson;
}
@@ -57,8 +57,7 @@ public class ClientCommandHandler implements CommandSourceHandler {
}
} else if (commandSource.isUpdate()) {
try {
final String jsonOfChangesOnly = this.changeDetectionService.detectChanges(commandSource.operation(),
commandSource.resourceName(), commandSource.resourceId(), commandSerializedAsJson);
final String jsonOfChangesOnly = this.changeDetectionService.detectChangesOnUpdate(commandSource.resourceName(), commandSource.resourceId(), commandSerializedAsJson);
commandSourceResult.updateJsonTo(jsonOfChangesOnly);
final ClientCommand changesOnly = this.apiDataConversionService.convertInternalJsonFormatToClientCommand(
@@ -34,8 +34,7 @@ public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService
@Autowired
public OfficeReadPlatformServiceImpl(final PlatformSecurityContext context,
final CurrencyReadPlatformService currencyReadPlatformService,
final TenantAwareRoutingDataSource dataSource) {
final CurrencyReadPlatformService currencyReadPlatformService, final TenantAwareRoutingDataSource dataSource) {
this.context = context;
this.currencyReadPlatformService = currencyReadPlatformService;
this.jdbcTemplate = new JdbcTemplate(dataSource);
@@ -51,8 +50,7 @@ public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService
}
@Override
public OfficeData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum)
throws SQLException {
public OfficeData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
Long id = rs.getLong("id");
String name = rs.getString("name");
@@ -64,23 +62,18 @@ public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService
String parentName = rs.getString("parentName");
List<OfficeLookup> allowedParents = new ArrayList<OfficeLookup>();
return new OfficeData(id, name, nameDecorated, externalId,
openingDate, hierarchy, parentId, parentName,
allowedParents);
return new OfficeData(id, name, nameDecorated, externalId, openingDate, hierarchy, parentId, parentName, allowedParents);
}
}
private static final class OfficeLookupMapper implements
RowMapper<OfficeLookup> {
private static final class OfficeLookupMapper implements RowMapper<OfficeLookup> {
public String officeLookupSchema() {
return " o.id as id, " + nameDecoratedBaseOnHierarchy
+ " as nameDecorated, o.name as name from m_office o ";
return " o.id as id, " + nameDecoratedBaseOnHierarchy + " as nameDecorated, o.name as name from m_office o ";
}
@Override
public OfficeLookup mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum)
throws SQLException {
public OfficeLookup mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
Long id = rs.getLong("id");
String name = rs.getString("name");
@@ -90,8 +83,7 @@ public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService
}
}
private static final class OfficeTransactionMapper implements
RowMapper<OfficeTransactionData> {
private static final class OfficeTransactionMapper implements RowMapper<OfficeTransactionData> {
public String officeTransactionSchema() {
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 "
+ " left join m_office fromoff on fromoff.id = ot.from_office_id "
+ " left join m_office tooff on tooff.id = ot.to_office_id "
+ " join m_currency rc on rc.`code` = ot.currency_code";
+ " left join m_office tooff on tooff.id = ot.to_office_id " + " join m_currency rc on rc.`code` = ot.currency_code";
}
@Override
public OfficeTransactionData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum)
throws SQLException {
public OfficeTransactionData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
Long id = rs.getLong("id");
LocalDate transactionDate = JdbcSupport.getLocalDate(rs,
"transactionDate");
LocalDate transactionDate = JdbcSupport.getLocalDate(rs, "transactionDate");
Long fromOfficeId = JdbcSupport.getLong(rs, "fromOfficeId");
String fromOfficeName = rs.getString("fromOfficeName");
Long toOfficeId = JdbcSupport.getLong(rs, "toOfficeId");
@@ -120,21 +109,16 @@ public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService
String currencyCode = rs.getString("currencyCode");
String currencyName = rs.getString("currencyName");
String currencyNameCode = rs.getString("currencyNameCode");
String currencyDisplaySymbol = rs
.getString("currencyDisplaySymbol");
Integer currencyDigits = JdbcSupport.getInteger(rs,
"currencyDigits");
String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol");
Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits");
CurrencyData currencyData = new CurrencyData(currencyCode,
currencyName, currencyDigits, currencyDisplaySymbol,
CurrencyData currencyData = new CurrencyData(currencyCode, currencyName, currencyDigits, currencyDisplaySymbol,
currencyNameCode);
BigDecimal transactionAmount = rs
.getBigDecimal("transactionAmount");
BigDecimal transactionAmount = rs.getBigDecimal("transactionAmount");
String description = rs.getString("description");
return new OfficeTransactionData(id, transactionDate, fromOfficeId,
fromOfficeName, toOfficeId, toOfficeName, currencyData,
return new OfficeTransactionData(id, transactionDate, fromOfficeId, fromOfficeName, toOfficeId, toOfficeName, currencyData,
transactionAmount, description);
}
}
@@ -148,11 +132,9 @@ public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService
String hierarchySearchString = hierarchy + "%";
OfficeMapper rm = new OfficeMapper();
String sql = "select " + rm.officeSchema()
+ "where o.hierarchy like ? order by o.hierarchy";
String sql = "select " + rm.officeSchema() + "where o.hierarchy like ? order by o.hierarchy";
return this.jdbcTemplate.query(sql, rm,
new Object[] { hierarchySearchString });
return this.jdbcTemplate.query(sql, rm, new Object[] { hierarchySearchString });
}
@Override
@@ -163,11 +145,9 @@ public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService
String hierarchySearchString = hierarchy + "%";
OfficeLookupMapper rm = new OfficeLookupMapper();
String sql = "select " + rm.officeLookupSchema()
+ "where o.hierarchy like ? order by o.hierarchy";
String sql = "select " + rm.officeLookupSchema() + "where o.hierarchy like ? order by o.hierarchy";
return this.jdbcTemplate.query(sql, rm,
new Object[] { hierarchySearchString });
return this.jdbcTemplate.query(sql, rm, new Object[] { hierarchySearchString });
}
@Override
@@ -179,8 +159,7 @@ public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService
OfficeMapper rm = new OfficeMapper();
String sql = "select " + rm.officeSchema() + " where o.id = ?";
OfficeData selectedOffice = this.jdbcTemplate.queryForObject(sql,
rm, new Object[] { officeId });
OfficeData selectedOffice = this.jdbcTemplate.queryForObject(sql, rm, new Object[] { officeId });
return selectedOffice;
} catch (EmptyResultDataAccessException e) {
@@ -205,12 +184,11 @@ public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService
List<OfficeLookup> filterParentLookups = new ArrayList<OfficeLookup>();
if (isNotHeadOffice(officeId)) {
List<OfficeLookup> parentLookups = new ArrayList<OfficeLookup>(
retrieveAllOfficesForLookup());
List<OfficeLookup> parentLookups = new ArrayList<OfficeLookup>(retrieveAllOfficesForLookup());
for (OfficeLookup office : parentLookups) {
if (!office.getId().equals(officeId)) {
if (!office.hasIdentifyOf(officeId)) {
filterParentLookups.add(office);
}
}
@@ -233,25 +211,20 @@ public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService
String hierarchySearchString = hierarchy + "%";
OfficeTransactionMapper rm = new OfficeTransactionMapper();
String sql = "select "
+ rm.officeTransactionSchema()
String sql = "select " + rm.officeTransactionSchema()
+ " where (fromoff.hierarchy like ? or tooff.hierarchy like ?) order by ot.transaction_date, ot.id";
return this.jdbcTemplate.query(sql, rm, new Object[] {
hierarchySearchString, hierarchySearchString });
return this.jdbcTemplate.query(sql, rm, new Object[] { hierarchySearchString, hierarchySearchString });
}
@Override
public OfficeTransactionData retrieveNewOfficeTransactionDetails() {
context.authenticatedUser();
List<OfficeLookup> parentLookups = new ArrayList<OfficeLookup>(
retrieveAllOfficesForLookup());
List<CurrencyData> currencyOptions = currencyReadPlatformService
.retrieveAllowedCurrencies();
List<OfficeLookup> parentLookups = new ArrayList<OfficeLookup>(retrieveAllOfficesForLookup());
List<CurrencyData> currencyOptions = currencyReadPlatformService.retrieveAllowedCurrencies();
return new OfficeTransactionData(new LocalDate(), parentLookups,
currencyOptions);
return new OfficeTransactionData(new LocalDate(), parentLookups, currencyOptions);
}
}
@@ -5,5 +5,4 @@ import org.mifosng.platform.user.domain.AppUser;
public interface PlatformSecurityContext {
AppUser authenticatedUser();
}
@@ -8,7 +8,8 @@ import org.springframework.security.core.context.SecurityContextHolder;
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
public class SpringSecurityPlatformSecurityContext implements PlatformSecurityContext {
@@ -24,9 +25,7 @@ public class SpringSecurityPlatformSecurityContext implements PlatformSecurityCo
}
}
if (currentUser == null) {
throw new UnAuthenticatedUserException();
}
if (currentUser == null) { throw new UnAuthenticatedUserException(); }
return currentUser;
}
@@ -27,8 +27,7 @@ import org.springframework.security.core.userdetails.User;
@Entity
@Table(name = "m_appuser", uniqueConstraints = @UniqueConstraint(columnNames = { "username" }, name = "username_org"))
public class AppUser extends AbstractAuditableCustom<AppUser, Long> implements
PlatformUser {
public class AppUser extends AbstractAuditableCustom<AppUser, Long> implements PlatformUser {
@Column(name = "email", nullable = false, length = 100)
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"))
private Set<Role> roles;
public static AppUser createNew(final Office office,
final Set<Role> allRoles, final String username,
final String email, final String firstname, final String lastname,
final String password) {
public static AppUser createNew(final Office office, final Set<Role> allRoles, final String username, final String email,
final String firstname, final String lastname, final String password) {
boolean userEnabled = true;
boolean userAccountNonExpired = true;
@@ -83,12 +80,10 @@ public class AppUser extends AbstractAuditableCustom<AppUser, Long> implements
boolean userAccountNonLocked = true;
Collection<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
authorities.add(new SimpleGrantedAuthority(
"DUMMY_ROLE_NOT_USED_OR_PERSISTED_TO_AVOID_EXCEPTION"));
authorities.add(new SimpleGrantedAuthority("DUMMY_ROLE_NOT_USED_OR_PERSISTED_TO_AVOID_EXCEPTION"));
User user = new User(username, password, userEnabled,
userAccountNonExpired, userCredentialsNonExpired,
userAccountNonLocked, authorities);
User user = new User(username, password, userEnabled, userAccountNonExpired, userCredentialsNonExpired, userAccountNonLocked,
authorities);
return new AppUser(office, user, allRoles, email, firstname, lastname);
}
@@ -105,8 +100,8 @@ public class AppUser extends AbstractAuditableCustom<AppUser, Long> implements
this.firstTimeLoginRemaining = true;
}
public AppUser(final Office office, final User user, final Set<Role> roles,
final String email, final String firstname, final String lastname) {
public AppUser(final Office office, final User user, final Set<Role> roles, final String email, final String firstname,
final String lastname) {
this.office = office;
this.email = email.trim();
this.username = user.getUsername().trim();
@@ -126,8 +121,7 @@ public class AppUser extends AbstractAuditableCustom<AppUser, Long> implements
this.firstTimeLoginRemaining = false;
}
public void update(final Set<Role> allRoles, final Office office,
final UserCommand userCommand) {
public void update(final Set<Role> allRoles, final Office office, final UserCommand userCommand) {
if (userCommand.isRolesChanged() && !allRoles.isEmpty()) {
this.roles.clear();
@@ -178,8 +172,7 @@ public class AppUser extends AbstractAuditableCustom<AppUser, Long> implements
for (Role role : this.roles) {
Collection<Permission> permissions = role.getPermissions();
for (Permission permission : permissions) {
grantedAuthorities.add(new SimpleGrantedAuthority(permission
.code()));
grantedAuthorities.add(new SimpleGrantedAuthority(permission.code()));
}
}
return grantedAuthorities;
@@ -236,75 +229,60 @@ public class AppUser extends AbstractAuditableCustom<AppUser, Long> implements
}
public boolean canNotApproveLoanInPast() {
return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "APPROVEINPAST_LOAN",
"PORTFOLIO_MANAGEMENT_SUPER_USER");
return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "APPROVEINPAST_LOAN", "PORTFOLIO_MANAGEMENT_SUPER_USER");
}
public boolean canNotRejectLoanInPast() {
return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "REJECTINPAST_LOAN",
"PORTFOLIO_MANAGEMENT_SUPER_USER");
return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "REJECTINPAST_LOAN", "PORTFOLIO_MANAGEMENT_SUPER_USER");
}
public boolean canNotWithdrawByClientLoanInPast() {
return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "WITHDRAWINPAST_LOAN",
"PORTFOLIO_MANAGEMENT_SUPER_USER");
return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "WITHDRAWINPAST_LOAN", "PORTFOLIO_MANAGEMENT_SUPER_USER");
}
public boolean canNotDisburseLoanInPast() {
return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "DISBURSEINPAST_LOAN",
"PORTFOLIO_MANAGEMENT_SUPER_USER");
return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "DISBURSEINPAST_LOAN", "PORTFOLIO_MANAGEMENT_SUPER_USER");
}
public boolean canNotMakeRepaymentOnLoanInPast() {
return hasNotPermissionForAnyOf("ALL_FUNCTIONS",
"REPAYMENTINPAST_LOAN", "PORTFOLIO_MANAGEMENT_SUPER_USER");
return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "REPAYMENTINPAST_LOAN", "PORTFOLIO_MANAGEMENT_SUPER_USER");
}
public boolean hasNotPermissionForReport(String reportName) {
if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ", "REPORTING_SUPER_USER",
"READ_" + reportName))
return true;
if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ", "REPORTING_SUPER_USER", "READ_" + reportName)) return true;
return false;
}
public boolean hasNotPermissionForDatatable(String datatable,
String accessType) {
public boolean hasNotPermissionForDatatable(String datatable, String accessType) {
String matchPermission = accessType + "_" + datatable;
if (accessType.equalsIgnoreCase("READ")) {
if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ",
matchPermission))
return true;
if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ", matchPermission)) return true;
return false;
}
if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", matchPermission))
return true;
if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", matchPermission)) return true;
return false;
}
public boolean hasNotPermissionForSet(String type, String set,
String accessType) {
public boolean hasNotPermissionForSet(String type, String set, String accessType) {
String matchPermission = "CAN_" + accessType + "_" + type + "_x" + set;
if (accessType.equalsIgnoreCase("READ")) {
if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ",
matchPermission))
return true;
if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ", matchPermission)) return true;
return false;
}
if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", matchPermission))
return true;
if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", matchPermission)) return true;
return false;
}
@@ -323,13 +301,10 @@ public class AppUser extends AbstractAuditableCustom<AppUser, Long> implements
public void validateHasReadPermission(final String entityType) {
String authorizationMessage = "User has no authority to view "
+ entityType.toLowerCase() + "s";
String authorizationMessage = "User has no authority to view " + entityType.toLowerCase() + "s";
String matchPermission = "READ_" + entityType.toUpperCase();
if (!(hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ",
matchPermission)))
return;
if (!(hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ", matchPermission))) return;
String higherPermission = "";
if (entityType.equalsIgnoreCase("CHARGE")) {
@@ -379,8 +354,7 @@ public class AppUser extends AbstractAuditableCustom<AppUser, Long> implements
}
if (!(higherPermission.equals(""))) {
if (hasNotPermissionForAnyOf(higherPermission))
throw new NoAuthorizationException(authorizationMessage);
if (hasNotPermissionForAnyOf(higherPermission)) throw new NoAuthorizationException(authorizationMessage);
}
}
@@ -22,10 +22,10 @@ import org.mifosng.platform.infrastructure.AbstractAuditableCustom;
@Table(name = "m_role")
public class Role extends AbstractAuditableCustom<AppUser, Long> {
@Column(name="name", nullable=false, length=100)
@Column(name = "name", nullable = false, length = 100)
private String name;
@Column(name="description", nullable=false, length=500)
@Column(name = "description", nullable = false, length = 500)
private String description;
@ManyToMany(fetch = FetchType.EAGER)
@@ -14,6 +14,7 @@ public interface AppUserWritePlatformService {
@PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'USER_ADMINISTRATION_SUPER_USER', 'DELETE_USER')")
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);
}
@@ -46,8 +46,9 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit
private final RoleRepository roleRepository;
@Autowired
public AppUserWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final AppUserRepository appUserRepository, final UserDomainService userDomainService,
final OfficeRepository officeRepository, final RoleRepository roleRepository, final PlatformPasswordEncoder platformPasswordEncoder) {
public AppUserWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final AppUserRepository appUserRepository,
final UserDomainService userDomainService, final OfficeRepository officeRepository, final RoleRepository roleRepository,
final PlatformPasswordEncoder platformPasswordEncoder) {
this.context = context;
this.appUserRepository = appUserRepository;
this.userDomainService = userDomainService;
@@ -69,19 +70,15 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit
final Set<Role> allRoles = assembleSetOfRoles(command);
Office office = this.officeRepository.findOne(command.getOfficeId());
if (office == null) {
throw new OfficeNotFoundException(command.getOfficeId());
}
if (office == null) { throw new OfficeNotFoundException(command.getOfficeId()); }
String password = command.getPassword();
if (StringUtils.isBlank(password)) {
password = "autogenerate";
}
AppUser appUser = AppUser.createNew(office,
allRoles, command.getUsername(), command.getEmail(),
command.getFirstname(), command.getLastname(),
password);
AppUser appUser = AppUser.createNew(office, allRoles, command.getUsername(), command.getEmail(), command.getFirstname(),
command.getLastname(), password);
this.userDomainService.create(appUser);
@@ -91,10 +88,12 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit
return Long.valueOf(-1);
} catch (PlatformEmailSendException e) {
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);
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;
if (command.isOfficeChanged()) {
office = this.officeRepository.findOne(command.getOfficeId());
if (office == null) {
throw new OfficeNotFoundException(command.getOfficeId());
}
if (office == null) { throw new OfficeNotFoundException(command.getOfficeId()); }
}
AppUser userToUpdate = this.appUserRepository.findOne(command.getId());
if (userToUpdate == null) {
throw new UserNotFoundException(command.getId());
}
if (userToUpdate == null) { throw new UserNotFoundException(command.getId()); }
userToUpdate.update(allRoles, office, command);
this.appUserRepository.saveAndFlush(userToUpdate);
if (command.isPasswordChanged()) {
PlatformUser dummyPlatformUser = new BasicPasswordEncodablePlatformUser(
userToUpdate.getId(),
userToUpdate.getUsername(), command.getPassword());
PlatformUser dummyPlatformUser = new BasicPasswordEncodablePlatformUser(userToUpdate.getId(), userToUpdate.getUsername(),
command.getPassword());
String newPasswordEncoded = this.platformPasswordEncoder.encode(dummyPlatformUser);
@@ -159,9 +153,7 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit
for (String roleId : rolesArray) {
Long id = Long.valueOf(roleId);
Role role = this.roleRepository.findOne(id);
if (role == null) {
throw new RoleNotFoundException(id);
}
if (role == null) { throw new RoleNotFoundException(id); }
allRoles.add(role);
}
}
@@ -174,23 +166,24 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit
public void deleteUser(final Long userId) {
AppUser user = this.appUserRepository.findOne(userId);
if (user == null || user.isDeleted()) {
throw new UserNotFoundException(userId);
}
if (user == null || user.isDeleted()) { throw new UserNotFoundException(userId); }
user.delete();
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) {
Throwable realCause = dve.getMostSpecificCause();
if (realCause.getMessage().contains("username_org")) {
StringBuilder defaultMessageBuilder = new StringBuilder("User with username ").append(command.getUsername()).append(" already exists.");
throw new PlatformDataIntegrityException("error.msg.user.duplicate.username", defaultMessageBuilder.toString(), "username", command.getUsername());
StringBuilder defaultMessageBuilder = new StringBuilder("User with username ").append(command.getUsername()).append(
" already exists.");
throw new PlatformDataIntegrityException("error.msg.user.duplicate.username", defaultMessageBuilder.toString(), "username",
command.getUsername());
}
logger.error(dve.getMessage(), dve);
@@ -56,15 +56,14 @@ public class PermissionReadPlatformServiceImpl implements PermissionReadPlatform
}
@Override
public Collection<PermissionUsageData> retrieveAllRolePermissions(Long roleId) {
public Collection<PermissionUsageData> retrieveAllRolePermissions(final Long roleId) {
final PermissionUsageDataMapper mapper = new PermissionUsageDataMapper();
final String sql = mapper.schema();
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> {
@Override
@@ -80,10 +79,10 @@ public class PermissionReadPlatformServiceImpl implements PermissionReadPlatform
}
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 " +
"from m_permission p " +
"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";
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 "
+ "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";
}
}
@@ -24,7 +24,8 @@ public class RoleReadPlatformServiceImpl implements RoleReadPlatformService {
private final RoleRepository roleRepository;
@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.roleRepository = roleRepository;
this.jdbcTemplate = new JdbcTemplate(dataSource);
@@ -45,17 +46,15 @@ public class RoleReadPlatformServiceImpl implements RoleReadPlatformService {
context.authenticatedUser();
final Role role = this.roleRepository.findOne(id);
if (role == null) {
throw new RoleNotFoundException(id);
}
if (role == null) { throw new RoleNotFoundException(id); }
return role.toData();
}
protected static final class RoleMapper implements RowMapper<RoleData> {
@Override
public RoleData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum)
throws SQLException {
public RoleData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
final Long id = JdbcSupport.getLong(rs, "id");
final String name = rs.getString("name");