MIFOSX-97: enable maker checker flow for update of role permissions.

This commit is contained in:
Keith Woodlock
2012-11-23 13:02:28 +00:00
parent e8676832ee
commit f7c7bfdd5f
25 changed files with 562 additions and 461 deletions
@@ -0,0 +1 @@
ALTER TABLE `m_portfolio_command_source` CHANGE COLUMN `command_as_json` `command_as_json` VARCHAR(5000) NOT NULL;
@@ -2,14 +2,20 @@ package org.mifosng.platform.accounting.api.commands;
import java.util.Map; import java.util.Map;
/**
* Immutable command for updating permissions against a role.
*/
public class RolePermissionCommand { public class RolePermissionCommand {
private final Long roleId; private final transient Long roleId;
private final Map<String, Boolean> permissions; private final Map<String, Boolean> permissions;
public RolePermissionCommand(final Long roleId, final Map<String, Boolean> permissionsMap) { private final transient boolean makerCheckerApproval;
public RolePermissionCommand(final Long roleId, final Map<String, Boolean> permissionsMap, final boolean makerCheckerApproval) {
this.roleId = roleId; this.roleId = roleId;
this.permissions = permissionsMap; this.permissions = permissionsMap;
this.makerCheckerApproval = makerCheckerApproval;
} }
public Map<String, Boolean> getPermissions() { public Map<String, Boolean> getPermissions() {
@@ -19,4 +25,8 @@ public class RolePermissionCommand {
public Long getRoleId() { public Long getRoleId() {
return this.roleId; return this.roleId;
} }
public boolean isApprovedByChecker() {
return this.makerCheckerApproval;
}
} }
@@ -87,8 +87,8 @@ public class ClientsApiResource {
private PlatformSecurityContext context; private PlatformSecurityContext context;
@GET @GET
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({MediaType.APPLICATION_JSON})
@Produces({ MediaType.APPLICATION_JSON }) @Produces({MediaType.APPLICATION_JSON})
public String retrieveAllIndividualClients(@Context final UriInfo uriInfo, @QueryParam("sqlSearch") final String sqlSearch, public String retrieveAllIndividualClients(@Context final UriInfo uriInfo, @QueryParam("sqlSearch") final String sqlSearch,
@QueryParam("officeId") final Integer officeId, @QueryParam("externalId") final String externalId, @QueryParam("officeId") final Integer officeId, @QueryParam("externalId") final String externalId,
@QueryParam("displayName") final String displayName, @QueryParam("firstName") final String firstName, @QueryParam("displayName") final String displayName, @QueryParam("firstName") final String firstName,
@@ -151,8 +151,8 @@ public class ClientsApiResource {
@GET @GET
@Path("{clientId}") @Path("{clientId}")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({MediaType.APPLICATION_JSON})
@Produces({ MediaType.APPLICATION_JSON }) @Produces({MediaType.APPLICATION_JSON})
public String retrieveClient(@PathParam("clientId") final Long clientId, @Context final UriInfo uriInfo) { public String retrieveClient(@PathParam("clientId") final Long clientId, @Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission("CLIENT"); context.authenticatedUser().validateHasReadPermission("CLIENT");
@@ -160,47 +160,41 @@ public class ClientsApiResource {
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());
final boolean template = ApiParameterHelper.template(uriInfo.getQueryParameters()); final boolean template = ApiParameterHelper.template(uriInfo.getQueryParameters());
final Long makerCheckerId = ApiParameterHelper.makerCheckerId(uriInfo.getQueryParameters()); final Long commandId = ApiParameterHelper.commandId(uriInfo.getQueryParameters());
ClientData clientData = this.clientReadPlatformService.retrieveIndividualClient(clientId); ClientData clientData = this.clientReadPlatformService.retrieveIndividualClient(clientId);
if (template) { if (template) {
final List<OfficeLookup> allowedOffices = new ArrayList<OfficeLookup>(officeReadPlatformService.retrieveAllOfficesForLookup()); final List<OfficeLookup> allowedOffices = new ArrayList<OfficeLookup>(officeReadPlatformService.retrieveAllOfficesForLookup());
clientData = ClientData.templateOnTop(clientData, allowedOffices); clientData = ClientData.templateOnTop(clientData, allowedOffices);
} }
if (makerCheckerId != null) { if (commandId != null) {
clientData = handleMakerCheckerRequest(clientId, makerCheckerId, clientData); clientData = handleRequestToIntegrateProposedChangesFromCommand(clientId, commandId, clientData);
} }
boolean retrieveChanges = true; // pick up possibility of changes by default - might push down a layer into the retrieve client method
if (retrieveChanges) { final Collection<ClientData> dataChanges = retrieveAllUnprocessedDataChanges(clientId);
final Collection<ClientData> dataChanges = retrieveAllUnprocessedDataChanges(clientId); clientData = ClientData.integrateChanges(clientData, clientData.currentChange(), dataChanges);
clientData = ClientData.integrateChanges(clientData, clientData.currentChange(), dataChanges);
}
return this.apiJsonSerializerService.serializeClientDataToJson(prettyPrint, responseParameters, clientData); return this.apiJsonSerializerService.serializeClientDataToJson(prettyPrint, responseParameters, clientData);
} }
private ClientData handleMakerCheckerRequest(final Long clientId, final Long makerCheckerId, ClientData clientData) { private ClientData handleRequestToIntegrateProposedChangesFromCommand(final Long clientId, final Long commandId, final ClientData clientData) {
final CommandSourceData entry = this.commandSourceReadPlatformService.retrieveById(makerCheckerId); final CommandSourceData entry = this.commandSourceReadPlatformService.retrieveById(commandId);
final ClientData currentChange = this.apiDataConversionService.convertInternalJsonFormatToClientDataChange(clientId, entry.json()); final ClientData currentChange = this.apiDataConversionService.convertInternalJsonFormatToClientDataChange(clientId, entry.json());
final Collection<ClientData> dataChanges = retrieveAllUnprocessedDataChanges(clientId); final Collection<ClientData> dataChanges = null; // retrieveAllUnprocessedDataChanges(clientId);
clientData = ClientData.integrateChanges(clientData, currentChange, dataChanges); return ClientData.integrateChanges(clientData, currentChange, dataChanges);
return clientData;
} }
private Collection<ClientData> retrieveAllUnprocessedDataChanges(final Long clientId) { private Collection<ClientData> retrieveAllUnprocessedDataChanges(final Long clientId) {
Collection<ClientData> dataChanges = new ArrayList<ClientData>(); Collection<ClientData> dataChanges = new ArrayList<ClientData>();
boolean retrieveChanges = true; Collection<CommandSourceData> unprocessedChanges = this.commandSourceReadPlatformService.retrieveUnprocessChangesByResourceId(
if (retrieveChanges) { "clients", clientId);
Collection<CommandSourceData> unprocessedChanges = this.commandSourceReadPlatformService.retrieveUnprocessChangesByResourceId( for (CommandSourceData commandSourceData : unprocessedChanges) {
"clients", clientId); ClientData change = this.apiDataConversionService.convertInternalJsonFormatToClientDataChange(clientId,
for (CommandSourceData commandSourceData : unprocessedChanges) { commandSourceData.json());
ClientData change = this.apiDataConversionService.convertInternalJsonFormatToClientDataChange(clientId, dataChanges.add(change);
commandSourceData.json());
dataChanges.add(change);
}
} }
if (dataChanges.isEmpty()) { if (dataChanges.isEmpty()) {
@@ -212,27 +206,27 @@ public class ClientsApiResource {
@GET @GET
@Path("template") @Path("template")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({MediaType.APPLICATION_JSON})
@Produces({ MediaType.APPLICATION_JSON }) @Produces({MediaType.APPLICATION_JSON})
public String newClientDetails(@Context final UriInfo uriInfo) { public String newClientDetails(@Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission("CLIENT"); context.authenticatedUser().validateHasReadPermission("CLIENT");
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());
final Long makerCheckerId = ApiParameterHelper.makerCheckerId(uriInfo.getQueryParameters()); final Long makerCheckerId = ApiParameterHelper.commandId(uriInfo.getQueryParameters());
ClientData clientData = this.clientReadPlatformService.retrieveNewClientDetails(); ClientData clientData = this.clientReadPlatformService.retrieveNewClientDetails();
if (makerCheckerId != null) { if (makerCheckerId != null) {
clientData = handleMakerCheckerRequest(null, makerCheckerId, clientData); clientData = handleRequestToIntegrateProposedChangesFromCommand(null, makerCheckerId, clientData);
} }
return this.apiJsonSerializerService.serializeClientDataToJson(prettyPrint, responseParameters, clientData); return this.apiJsonSerializerService.serializeClientDataToJson(prettyPrint, responseParameters, clientData);
} }
@POST @POST
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({MediaType.APPLICATION_JSON})
@Produces({ MediaType.APPLICATION_JSON }) @Produces({MediaType.APPLICATION_JSON})
public String createClient(final String jsonRequestBody) { public String createClient(final String jsonRequestBody) {
final EntityIdentifier result = this.commandsSourceWritePlatformService final EntityIdentifier result = this.commandsSourceWritePlatformService
@@ -243,8 +237,8 @@ public class ClientsApiResource {
@PUT @PUT
@Path("{clientId}") @Path("{clientId}")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({MediaType.APPLICATION_JSON})
@Produces({ MediaType.APPLICATION_JSON }) @Produces({MediaType.APPLICATION_JSON})
public String updateClient(@PathParam("clientId") final Long clientId, final String jsonRequestBody) { public String updateClient(@PathParam("clientId") final Long clientId, final String jsonRequestBody) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("UPDATE", "clients", clientId, final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("UPDATE", "clients", clientId,
@@ -255,8 +249,8 @@ public class ClientsApiResource {
@DELETE @DELETE
@Path("{clientId}") @Path("{clientId}")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({MediaType.APPLICATION_JSON})
@Produces({ MediaType.APPLICATION_JSON }) @Produces({MediaType.APPLICATION_JSON})
public String deleteClient(@PathParam("clientId") final Long clientId) { public String deleteClient(@PathParam("clientId") final Long clientId) {
final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("DELETE", "clients", clientId, "{}"); final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("DELETE", "clients", clientId, "{}");
@@ -266,8 +260,8 @@ public class ClientsApiResource {
@GET @GET
@Path("{clientId}/loans") @Path("{clientId}/loans")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({MediaType.APPLICATION_JSON})
@Produces({ MediaType.APPLICATION_JSON }) @Produces({MediaType.APPLICATION_JSON})
public String retrieveClientAccount(@PathParam("clientId") final Long clientId, @Context final UriInfo uriInfo) { public String retrieveClientAccount(@PathParam("clientId") final Long clientId, @Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission("CLIENT"); context.authenticatedUser().validateHasReadPermission("CLIENT");
@@ -293,8 +287,8 @@ public class ClientsApiResource {
@GET @GET
@Path("{clientId}/notes") @Path("{clientId}/notes")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({MediaType.APPLICATION_JSON})
@Produces({ MediaType.APPLICATION_JSON }) @Produces({MediaType.APPLICATION_JSON})
public String retrieveAllClientNotes(@PathParam("clientId") final Long clientId, @Context final UriInfo uriInfo) { public String retrieveAllClientNotes(@PathParam("clientId") final Long clientId, @Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission("CLIENTNOTE"); context.authenticatedUser().validateHasReadPermission("CLIENTNOTE");
@@ -315,8 +309,8 @@ public class ClientsApiResource {
@POST @POST
@Path("{clientId}/notes") @Path("{clientId}/notes")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({MediaType.APPLICATION_JSON})
@Produces({ MediaType.APPLICATION_JSON }) @Produces({MediaType.APPLICATION_JSON})
public Response addNewClientNote(@PathParam("clientId") final Long clientId, final String jsonRequestBody) { public Response addNewClientNote(@PathParam("clientId") final Long clientId, final String jsonRequestBody) {
NoteCommand command = this.apiDataConversionService.convertJsonToNoteCommand(null, clientId, jsonRequestBody); NoteCommand command = this.apiDataConversionService.convertJsonToNoteCommand(null, clientId, jsonRequestBody);
@@ -328,8 +322,8 @@ public class ClientsApiResource {
@GET @GET
@Path("{clientId}/notes/{noteId}") @Path("{clientId}/notes/{noteId}")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({MediaType.APPLICATION_JSON})
@Produces({ MediaType.APPLICATION_JSON }) @Produces({MediaType.APPLICATION_JSON})
public String retrieveClientNote(@PathParam("clientId") final Long clientId, @PathParam("noteId") final Long noteId, public String retrieveClientNote(@PathParam("clientId") final Long clientId, @PathParam("noteId") final Long noteId,
@Context final UriInfo uriInfo) { @Context final UriInfo uriInfo) {
@@ -351,8 +345,8 @@ public class ClientsApiResource {
@PUT @PUT
@Path("{clientId}/notes/{noteId}") @Path("{clientId}/notes/{noteId}")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({MediaType.APPLICATION_JSON})
@Produces({ MediaType.APPLICATION_JSON }) @Produces({MediaType.APPLICATION_JSON})
public Response updateClientNote(@PathParam("clientId") final Long clientId, @PathParam("noteId") final Long noteId, public Response updateClientNote(@PathParam("clientId") final Long clientId, @PathParam("noteId") final Long noteId,
final String jsonRequestBody) { final String jsonRequestBody) {
@@ -368,8 +362,8 @@ public class ClientsApiResource {
*/ */
@POST @POST
@Path("{clientId}/image") @Path("{clientId}/image")
@Consumes({ MediaType.MULTIPART_FORM_DATA }) @Consumes({MediaType.MULTIPART_FORM_DATA})
@Produces({ MediaType.APPLICATION_JSON }) @Produces({MediaType.APPLICATION_JSON})
public Response addNewClientImage(@PathParam("clientId") final Long clientId, @HeaderParam("Content-Length") Long fileSize, public Response addNewClientImage(@PathParam("clientId") final Long clientId, @HeaderParam("Content-Length") Long fileSize,
@FormDataParam("file") InputStream inputStream, @FormDataParam("file") FormDataContentDisposition fileDetails, @FormDataParam("file") InputStream inputStream, @FormDataParam("file") FormDataContentDisposition fileDetails,
@FormDataParam("file") FormDataBodyPart bodyPart) { @FormDataParam("file") FormDataBodyPart bodyPart) {
@@ -394,8 +388,8 @@ public class ClientsApiResource {
*/ */
@POST @POST
@Path("{clientId}/image") @Path("{clientId}/image")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({MediaType.APPLICATION_JSON})
@Produces({ MediaType.APPLICATION_JSON }) @Produces({MediaType.APPLICATION_JSON})
public Response addNewClientImage(@PathParam("clientId") final Long clientId, final String jsonRequestBody) { public Response addNewClientImage(@PathParam("clientId") final Long clientId, final String jsonRequestBody) {
Base64EncodedImage base64EncodedImage = FileUtils.extractImageFromDataURL(jsonRequestBody); Base64EncodedImage base64EncodedImage = FileUtils.extractImageFromDataURL(jsonRequestBody);
@@ -410,8 +404,8 @@ public class ClientsApiResource {
*/ */
@GET @GET
@Path("{clientId}/image") @Path("{clientId}/image")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({MediaType.APPLICATION_JSON})
@Produces({ MediaType.APPLICATION_JSON }) @Produces({MediaType.APPLICATION_JSON})
public Response retrieveClientImage(@PathParam("clientId") final Long clientId) { public Response retrieveClientImage(@PathParam("clientId") final Long clientId) {
context.authenticatedUser().validateHasReadPermission("CLIENTIMAGE"); context.authenticatedUser().validateHasReadPermission("CLIENTIMAGE");
@@ -428,8 +422,8 @@ public class ClientsApiResource {
*/ */
@PUT @PUT
@Path("{clientId}/image") @Path("{clientId}/image")
@Consumes({ MediaType.MULTIPART_FORM_DATA }) @Consumes({MediaType.MULTIPART_FORM_DATA})
@Produces({ MediaType.APPLICATION_JSON }) @Produces({MediaType.APPLICATION_JSON})
public Response updateClientImage(@PathParam("clientId") final Long clientId, @HeaderParam("Content-Length") Long fileSize, public Response updateClientImage(@PathParam("clientId") final Long clientId, @HeaderParam("Content-Length") Long fileSize,
@FormDataParam("file") InputStream inputStream, @FormDataParam("file") FormDataContentDisposition fileDetails, @FormDataParam("file") InputStream inputStream, @FormDataParam("file") FormDataContentDisposition fileDetails,
@FormDataParam("file") FormDataBodyPart bodyPart) { @FormDataParam("file") FormDataBodyPart bodyPart) {
@@ -438,8 +432,8 @@ public class ClientsApiResource {
@DELETE @DELETE
@Path("{clientId}/image") @Path("{clientId}/image")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({MediaType.APPLICATION_JSON})
@Produces({ MediaType.APPLICATION_JSON }) @Produces({MediaType.APPLICATION_JSON})
public Response deleteClientImage(@PathParam("clientId") final Long clientId) { public Response deleteClientImage(@PathParam("clientId") final Long clientId) {
this.clientWritePlatformService.deleteClientImage(clientId); this.clientWritePlatformService.deleteClientImage(clientId);
return Response.ok(new EntityIdentifier(clientId)).build(); return Response.ok(new EntityIdentifier(clientId)).build();
@@ -453,8 +447,8 @@ public class ClientsApiResource {
*/ */
@PUT @PUT
@Path("{clientId}/image") @Path("{clientId}/image")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({MediaType.APPLICATION_JSON})
@Produces({ MediaType.APPLICATION_JSON }) @Produces({MediaType.APPLICATION_JSON})
public Response updateClientImage(@PathParam("clientId") final Long clientId, final String jsonRequestBody) { public Response updateClientImage(@PathParam("clientId") final Long clientId, final String jsonRequestBody) {
return addNewClientImage(clientId, jsonRequestBody); return addNewClientImage(clientId, jsonRequestBody);
} }
@@ -16,20 +16,20 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.UriInfo;
import org.mifosng.platform.accounting.api.commands.RolePermissionCommand; import org.mifosng.platform.accounting.api.commands.RolePermissionCommand;
import org.mifosng.platform.api.commands.RoleCommand; import org.mifosng.platform.api.data.CommandSourceData;
import org.mifosng.platform.api.data.EntityIdentifier; import org.mifosng.platform.api.data.EntityIdentifier;
import org.mifosng.platform.api.data.PermissionData; import org.mifosng.platform.api.data.PermissionData;
import org.mifosng.platform.api.data.PermissionUsageData; import org.mifosng.platform.api.data.PermissionUsageData;
import org.mifosng.platform.api.data.RoleData; import org.mifosng.platform.api.data.RoleData;
import org.mifosng.platform.api.data.RolePermissionsData; import org.mifosng.platform.api.data.RolePermissionsData;
import org.mifosng.platform.api.infrastructure.PortfolioApiDataConversionService;
import org.mifosng.platform.api.infrastructure.PortfolioApiJsonSerializerService; import org.mifosng.platform.api.infrastructure.PortfolioApiJsonSerializerService;
import org.mifosng.platform.api.infrastructure.PortfolioCommandDeserializerService;
import org.mifosng.platform.infrastructure.api.ApiParameterHelper; import org.mifosng.platform.infrastructure.api.ApiParameterHelper;
import org.mifosng.platform.makerchecker.service.PortfolioCommandSourceWritePlatformService; import org.mifosng.platform.makerchecker.service.PortfolioCommandSourceWritePlatformService;
import org.mifosng.platform.makerchecker.service.PortfolioCommandsReadPlatformService;
import org.mifosng.platform.security.PlatformSecurityContext; import org.mifosng.platform.security.PlatformSecurityContext;
import org.mifosng.platform.user.service.PermissionReadPlatformService; import org.mifosng.platform.user.service.PermissionReadPlatformService;
import org.mifosng.platform.user.service.RoleReadPlatformService; import org.mifosng.platform.user.service.RoleReadPlatformService;
import org.mifosng.platform.user.service.RoleWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@@ -45,18 +45,18 @@ public class RolesApiResource {
@Autowired @Autowired
private PermissionReadPlatformService permissionReadPlatformService; private PermissionReadPlatformService permissionReadPlatformService;
@Autowired
private RoleWritePlatformService roleWritePlatformService;
@Autowired
private PortfolioApiDataConversionService apiDataConversionService;
@Autowired @Autowired
private PortfolioApiJsonSerializerService apiJsonSerializerService; private PortfolioApiJsonSerializerService apiJsonSerializerService;
@Autowired @Autowired
private PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; private PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
@Autowired
private PortfolioCommandsReadPlatformService commandSourceReadPlatformService;
@Autowired
private PortfolioCommandDeserializerService commandDeserializerService;
@Autowired @Autowired
private PlatformSecurityContext context; private PlatformSecurityContext context;
@@ -124,15 +124,19 @@ public class RolesApiResource {
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());
final boolean template = ApiParameterHelper.template(uriInfo.getQueryParameters()); final boolean template = ApiParameterHelper.template(uriInfo.getQueryParameters());
final Long commandId = ApiParameterHelper.commandId(uriInfo.getQueryParameters());
RoleData role = this.roleReadPlatformService.retrieveRole(roleId); RoleData role = this.roleReadPlatformService.retrieveRole(roleId);
if (template) { if (template) {
final Collection<PermissionData> availablePermissions = this.permissionReadPlatformService.retrieveAllPermissions(); final Collection<PermissionData> availablePermissions = this.permissionReadPlatformService.retrieveAllPermissions();
availablePermissions.removeAll(role.selectedPermissions()); availablePermissions.removeAll(role.selectedPermissions());
role = new RoleData(role, availablePermissions); role = new RoleData(role, availablePermissions);
} }
if (commandId != null) {
// currentChanges = handleRequestToIntegrateProposedChangesFromCommand(roleId, commandId);
}
return this.apiJsonSerializerService.serializeRoleDataToJson(prettyPrint, responseParameters, role); return this.apiJsonSerializerService.serializeRoleDataToJson(prettyPrint, responseParameters, role);
} }
@@ -140,13 +144,11 @@ public class RolesApiResource {
@Path("{roleId}") @Path("{roleId}")
@Consumes({MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public String updateRole(@PathParam("roleId") final Long roleId, final String jsonRequestBody) { public String updateRole(@PathParam("roleId") final Long roleId, final String apiRequestBodyAsJson) {
final RoleCommand command = this.apiDataConversionService.convertApiRequestJsonToRoleCommand(roleId, jsonRequestBody); final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("UPDATE", "roles", roleId, apiRequestBodyAsJson);
this.roleWritePlatformService.updateRole(command); return this.apiJsonSerializerService.serializeEntityIdentifier(result);
return this.apiJsonSerializerService.serializeEntityIdentifier(new EntityIdentifier(roleId));
} }
@GET @GET
@@ -159,25 +161,70 @@ public class RolesApiResource {
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());
final Long commandId = ApiParameterHelper.commandId(uriInfo.getQueryParameters());
final RoleData role = this.roleReadPlatformService.retrieveRole(roleId); final RoleData role = this.roleReadPlatformService.retrieveRole(roleId);
final Collection<PermissionUsageData> permissionUsageData = this.permissionReadPlatformService.retrieveAllRolePermissions(roleId); final Collection<PermissionUsageData> permissionUsageData = this.permissionReadPlatformService.retrieveAllRolePermissions(roleId);
Collection<PermissionUsageData> currentChanges = null;
if (commandId != null) {
currentChanges = handleRequestToIntegrateProposedChangesFromCommand(roleId, commandId);
}
final RolePermissionsData permissionsData = role.toRolePermissionData(permissionUsageData); Collection<Collection<PermissionUsageData>> allChanges = retrieveAllUnprocessedDataChanges(roleId);
final RolePermissionsData permissionsData = role.toRolePermissionData(permissionUsageData, currentChanges, allChanges);
return this.apiJsonSerializerService.serializeRolePermissionDataToJson(prettyPrint, responseParameters, permissionsData); return this.apiJsonSerializerService.serializeRolePermissionDataToJson(prettyPrint, responseParameters, permissionsData);
} }
private Collection<PermissionUsageData> handleRequestToIntegrateProposedChangesFromCommand(final Long roleId, final Long commandId) {
final CommandSourceData entry = this.commandSourceReadPlatformService.retrieveById(commandId);
return assemblePermissionChanges(roleId, entry);
}
private Collection<PermissionUsageData> assemblePermissionChanges(final Long roleId, final CommandSourceData entry) {
final RolePermissionCommand changesOnly = this.commandDeserializerService.deserializeRolePermissionCommand(roleId, entry.json(), false);
// assemble map of string/booleans into PermissionUsageData
Collection<PermissionUsageData> proposedChanges = new ArrayList<PermissionUsageData>();
for (final String permissionCode : changesOnly.getPermissions().keySet()) {
final boolean isSelected = changesOnly.getPermissions().get(permissionCode).booleanValue();
final PermissionUsageData item = PermissionUsageData.from(permissionCode, isSelected);
proposedChanges.add(item);
}
return proposedChanges;
}
private Collection<Collection<PermissionUsageData>> retrieveAllUnprocessedDataChanges(final Long roleId) {
Collection<Collection<PermissionUsageData>> allChanges = new ArrayList<Collection<PermissionUsageData>>();
final Collection<CommandSourceData> unprocessedChanges = this.commandSourceReadPlatformService.retrieveUnprocessChangesByResourceId("roles", roleId);
for (CommandSourceData commandSourceData : unprocessedChanges) {
if (commandSourceData.isRoleResource() && commandSourceData.isUpdateRolePermissions()) {
Collection<PermissionUsageData> dataChanges = assemblePermissionChanges(roleId, commandSourceData);
allChanges.add(dataChanges);
}
}
if (allChanges.isEmpty()) {
allChanges = null;
}
return allChanges;
}
@PUT @PUT
@Path("{roleId}/permissions") @Path("{roleId}/permissions")
@Consumes({MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
public String updateRolePermissions(@PathParam("roleId") final Long roleId, final String jsonRequestBody) { public String updateRolePermissions(@PathParam("roleId") final Long roleId, final String apiRequestBodyAsJson) {
final RolePermissionCommand command = this.apiDataConversionService.convertJsonToRolePermissionCommand(roleId, jsonRequestBody); final EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("UPDATEPERMISSIONS", "roles", roleId, apiRequestBodyAsJson);
this.roleWritePlatformService.updateRolePermissions(command); return this.apiJsonSerializerService.serializeEntityIdentifier(result);
return this.apiJsonSerializerService.serializeEntityIdentifier(new EntityIdentifier(roleId));
} }
} }
@@ -11,168 +11,149 @@ import org.joda.time.LocalDate;
*/ */
final public class ClientData { final public class ClientData {
private final Long id; private final Long id;
private final String firstname; private final String firstname;
private final String lastname; private final String lastname;
private final String clientOrBusinessName; private final String clientOrBusinessName;
private final String displayName; private final String displayName;
private final Long officeId; private final Long officeId;
private final String officeName; private final String officeName;
private final String externalId; private final String externalId;
private final LocalDate joinedDate; private final LocalDate joinedDate;
private final String imageKey; private final String imageKey;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final Boolean imagePresent; private final Boolean imagePresent;
private final List<OfficeLookup> allowedOffices; private final List<OfficeLookup> allowedOffices;
private final ClientData currentChange; private final ClientData currentChange;
private final Collection<ClientData> allChanges; private final Collection<ClientData> allChanges;
private static String buildDisplayNameFrom(final String firstname, final String lastname) { private static String buildDisplayNameFrom(final String firstname, final String lastname) {
String displayName = null; String displayName = null;
StringBuilder displayNameBuilder = new StringBuilder(); StringBuilder displayNameBuilder = new StringBuilder();
if (StringUtils.isNotBlank(firstname)) { if (StringUtils.isNotBlank(firstname)) {
displayNameBuilder.append(firstname).append(' '); displayNameBuilder.append(firstname).append(' ');
} }
if (StringUtils.isNotBlank(lastname)) { if (StringUtils.isNotBlank(lastname)) {
displayNameBuilder.append(lastname); displayNameBuilder.append(lastname);
displayName = displayNameBuilder.toString(); displayName = displayNameBuilder.toString();
} }
return displayName; return displayName;
} }
public static ClientData dataChangeInstance( public static ClientData dataChangeInstance(final Long id, final Long officeId, final String externalId, final String firstname,
final Long id, final String lastname, final String clientOrBusinessName, final LocalDate joiningDate) {
final Long officeId,
final String externalId,
final String firstname,
final String lastname,
final String clientOrBusinessName,
final LocalDate joiningDate) {
String firstnameValue = firstname; String firstnameValue = firstname;
String lastnameValue = lastname; String lastnameValue = lastname;
if (StringUtils.isNotBlank(clientOrBusinessName)) { if (StringUtils.isNotBlank(clientOrBusinessName)) {
firstnameValue = null; firstnameValue = null;
lastnameValue = clientOrBusinessName; lastnameValue = clientOrBusinessName;
} }
final String displayName = buildDisplayNameFrom(firstnameValue, lastnameValue); final String displayName = buildDisplayNameFrom(firstnameValue, lastnameValue);
return new ClientData(officeId, null, id, firstname, lastname, displayName, externalId, joiningDate, null, null, null, null); return new ClientData(officeId, null, id, firstname, lastname, displayName, externalId, joiningDate, null, null, null, null);
} }
public static ClientData integrateChanges(final ClientData clientData, ClientData currentChange, final Collection<ClientData> allChanges) { public static ClientData integrateChanges(final ClientData clientData, ClientData currentChange, final Collection<ClientData> allChanges) {
String firstname = clientData.firstname; String firstname = clientData.firstname;
String lastname = clientData.lastname; String lastname = clientData.lastname;
if (StringUtils.isNotBlank(clientData.clientOrBusinessName)) { if (StringUtils.isNotBlank(clientData.clientOrBusinessName)) {
firstname = null; firstname = null;
lastname = clientData.clientOrBusinessName; lastname = clientData.clientOrBusinessName;
} }
final String displayName = buildDisplayNameFrom(firstname, lastname); final String displayName = buildDisplayNameFrom(firstname, lastname);
return new ClientData(clientData.officeId, clientData.officeName, clientData.id, firstname, lastname, displayName, return new ClientData(clientData.officeId, clientData.officeName, clientData.id, firstname, lastname, displayName,
clientData.externalId, clientData.joinedDate, clientData.imageKey, clientData.allowedOffices, currentChange, allChanges); clientData.externalId, clientData.joinedDate, clientData.imageKey, clientData.allowedOffices, currentChange, allChanges);
} }
public static ClientData template(final Long officeId, final LocalDate joinedDate, final List<OfficeLookup> allowedOffices) { public static ClientData template(final Long officeId, final LocalDate joinedDate, final List<OfficeLookup> allowedOffices) {
return new ClientData(officeId, null, null, null, null, null, null, joinedDate, null, allowedOffices, null, null); return new ClientData(officeId, null, null, null, null, null, null, joinedDate, null, allowedOffices, null, null);
} }
public static ClientData templateOnTop(final ClientData clientData, final List<OfficeLookup> allowedOffices) { public static ClientData templateOnTop(final ClientData clientData, final List<OfficeLookup> allowedOffices) {
String firstname = clientData.firstname; String firstname = clientData.firstname;
String lastname = clientData.lastname; String lastname = clientData.lastname;
if (StringUtils.isNotBlank(clientData.clientOrBusinessName)) { if (StringUtils.isNotBlank(clientData.clientOrBusinessName)) {
firstname = null; firstname = null;
lastname = clientData.clientOrBusinessName; lastname = clientData.clientOrBusinessName;
} }
final String displayName = buildDisplayNameFrom(firstname, lastname); final String displayName = buildDisplayNameFrom(firstname, lastname);
return new ClientData(clientData.officeId, clientData.officeName, clientData.id, firstname, lastname, displayName, return new ClientData(clientData.officeId, clientData.officeName, clientData.id, firstname, lastname, displayName,
clientData.externalId, clientData.joinedDate, clientData.imageKey, allowedOffices, clientData.currentChange, clientData.allChanges); clientData.externalId, clientData.joinedDate, clientData.imageKey, allowedOffices, clientData.currentChange,
} clientData.allChanges);
}
public static ClientData clientIdentifier( public static ClientData clientIdentifier(final Long id, final String firstname, final String lastname, final Long officeId,
final Long id, final String officeName) {
final String firstname,
final String lastname,
final Long officeId,
final String officeName) {
final String displayName = buildDisplayNameFrom(firstname, lastname); final String displayName = buildDisplayNameFrom(firstname, lastname);
return new ClientData(officeId, officeName, id, firstname, lastname, displayName, null, null, null, null, null, null); return new ClientData(officeId, officeName, id, firstname, lastname, displayName, null, null, null, null, null, null);
} }
public ClientData( public ClientData(final Long officeId, final String officeName, final Long id, final String firstname, final String lastname,
final Long officeId, final String displayName, final String externalId, final LocalDate joinedDate, final String imageKey,
final String officeName, final List<OfficeLookup> allowedOffices, final ClientData currentChange, final Collection<ClientData> allChanges) {
final Long id, this.officeId = officeId;
final String firstname, this.officeName = officeName;
final String lastname, this.id = id;
final String displayName, this.firstname = firstname;
final String externalId,
final LocalDate joinedDate,
final String imageKey,
final List<OfficeLookup> allowedOffices,
final ClientData currentChange,
final Collection<ClientData> allChanges) {
this.officeId = officeId;
this.officeName = officeName;
this.id = id;
this.firstname = firstname;
/*** unset last name for business name **/ /*** unset last name for business name **/
if (StringUtils.isBlank(firstname)) { if (StringUtils.isBlank(firstname)) {
this.lastname = null; this.lastname = null;
this.clientOrBusinessName = lastname; this.clientOrBusinessName = lastname;
} else { } else {
this.lastname = lastname; this.lastname = lastname;
this.clientOrBusinessName = null; this.clientOrBusinessName = null;
} }
this.displayName = displayName; this.displayName = displayName;
this.externalId = externalId; this.externalId = externalId;
this.joinedDate = joinedDate; this.joinedDate = joinedDate;
this.imageKey = imageKey; this.imageKey = imageKey;
if (imageKey != null) { if (imageKey != null) {
this.imagePresent = Boolean.TRUE; this.imagePresent = Boolean.TRUE;
} else { } else {
this.imagePresent = null; this.imagePresent = null;
} }
this.allowedOffices = allowedOffices; this.allowedOffices = allowedOffices;
this.currentChange = currentChange; this.currentChange = currentChange;
this.allChanges = allChanges; this.allChanges = allChanges;
} }
public String displayName() { public String displayName() {
return this.displayName; return this.displayName;
} }
public String officeName() { public String officeName() {
return this.officeName; return this.officeName;
} }
private boolean imageKeyExists() { private boolean imageKeyExists() {
return StringUtils.isNotBlank(this.imageKey); return StringUtils.isNotBlank(this.imageKey);
} }
public boolean imageKeyDoesNotExist() { public boolean imageKeyDoesNotExist() {
return !imageKeyExists(); return !imageKeyExists();
} }
public String imageKey() { public String imageKey() {
return this.imageKey; return this.imageKey;
} }
public Long id() { public Long id() {
return this.id; return this.id;
} }
public Long officeId() { public Long officeId() {
return this.officeId; return this.officeId;
} }
public ClientData currentChange() { public ClientData currentChange() {
return this.currentChange; return this.currentChange;
} }
} }
@@ -7,33 +7,34 @@ import org.joda.time.LocalDate;
*/ */
final public class CommandSourceData { final public class CommandSourceData {
@SuppressWarnings("unused") @SuppressWarnings("unused")
private Long id; private Long id;
private String apiOperation;
private String resource;
private final Long resourceId;
private String commandJson;
@SuppressWarnings("unused")
private final LocalDate madeOnDate;
@SuppressWarnings("unused") public CommandSourceData(final Long id, final String apiOperation, final String resource, final Long resourceId,
private String apiOperation; final String commandJson, final LocalDate madeOnDate) {
this.id = id;
this.apiOperation = apiOperation;
this.resource = resource;
this.resourceId = resourceId;
this.commandJson = commandJson;
this.madeOnDate = madeOnDate;
}
@SuppressWarnings("unused") public String json() {
private String resource; return this.commandJson;
}
@SuppressWarnings("unused") public boolean isUpdateRolePermissions() {
private final Long resourceId; return this.apiOperation.equalsIgnoreCase("UPDATEPERMISSIONS") && this.resourceId != null;
}
private String commandJson; public boolean isRoleResource() {
return this.resource.equalsIgnoreCase("ROLES");
@SuppressWarnings("unused") }
private final LocalDate madeOnDate;
public CommandSourceData(final Long id, final String apiOperation, final String resource, final Long resourceId, final String commandJson, final LocalDate madeOnDate) {
this.id = id;
this.apiOperation = apiOperation;
this.resource = resource;
this.resourceId = resourceId;
this.commandJson = commandJson;
this.madeOnDate = madeOnDate;
}
public String json() {
return this.commandJson;
}
} }
@@ -16,6 +16,10 @@ public class PermissionUsageData {
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final Boolean selected; private final Boolean selected;
public static PermissionUsageData from(final String permissionCode, final boolean isSelected) {
return new PermissionUsageData(null, permissionCode, null, null, isSelected);
}
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,
final Boolean selected) { final Boolean selected) {
this.grouping = grouping; this.grouping = grouping;
@@ -16,6 +16,9 @@ public class RoleData {
private final Collection<PermissionData> availablePermissions; private final Collection<PermissionData> availablePermissions;
private final Collection<PermissionData> selectedPermissions; private final Collection<PermissionData> selectedPermissions;
// @SuppressWarnings("unused")
// private final Collection<RoleData> currentChanges;
public RoleData(final Long id, final String name, final String description) { public RoleData(final Long id, final String name, final String description) {
this.id = id; this.id = id;
this.name = name; this.name = name;
@@ -63,7 +66,9 @@ public class RoleData {
return this.selectedPermissions; return this.selectedPermissions;
} }
public RolePermissionsData toRolePermissionData(final Collection<PermissionUsageData> permissionUsageData) { public RolePermissionsData toRolePermissionData(final Collection<PermissionUsageData> permissionUsageData,
return new RolePermissionsData(id, name, description, permissionUsageData); final Collection<PermissionUsageData> currentChanges,
final Collection<Collection<PermissionUsageData>> allChanges) {
return new RolePermissionsData(id, name, description, permissionUsageData, currentChanges, allChanges);
} }
} }
@@ -3,7 +3,7 @@ package org.mifosng.platform.api.data;
import java.util.Collection; import java.util.Collection;
/** /**
* Immutable data object reprsenting a role with associated permissions. * Immutable data object representing a role with associated permissions.
*/ */
public class RolePermissionsData { public class RolePermissionsData {
@@ -16,12 +16,20 @@ public class RolePermissionsData {
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final Collection<PermissionUsageData> permissionUsageData; private final Collection<PermissionUsageData> permissionUsageData;
@SuppressWarnings("unused")
private final Collection<PermissionUsageData> currentChanges;
@SuppressWarnings("unused")
private final Collection<Collection<PermissionUsageData>> allChanges;
public RolePermissionsData(final Long id, final String name, final String description, public RolePermissionsData(final Long id, final String name, final String description,
final Collection<PermissionUsageData> permissionUsageData) { final Collection<PermissionUsageData> permissionUsageData,
final Collection<PermissionUsageData> currentChanges,
final Collection<Collection<PermissionUsageData>> allChanges) {
this.id = id; this.id = id;
this.name = name; this.name = name;
this.description = description; this.description = description;
this.permissionUsageData = permissionUsageData; this.permissionUsageData = permissionUsageData;
this.currentChanges = currentChanges;
this.allChanges = allChanges;
} }
} }
@@ -42,7 +42,7 @@ public interface PortfolioApiDataConversionService {
RoleCommand convertApiRequestJsonToRoleCommand(Long resourceIdentifier, String json); RoleCommand convertApiRequestJsonToRoleCommand(Long resourceIdentifier, String json);
RolePermissionCommand convertJsonToRolePermissionCommand(Long roleId, String jsonRequestBody); RolePermissionCommand convertApiRequestJsonToRolePermissionCommand(Long roleId, String jsonRequestBody);
UserCommand convertJsonToUserCommand(Long resourceIdentifier, String json); UserCommand convertJsonToUserCommand(Long resourceIdentifier, String json);
@@ -258,14 +258,14 @@ public class PortfolioApiDataConversionServiceImpl implements PortfolioApiDataCo
} }
@Override @Override
public RolePermissionCommand convertJsonToRolePermissionCommand(final Long roleId, final String json) { public RolePermissionCommand convertApiRequestJsonToRolePermissionCommand(final Long resourceIdentifier, final String json) {
if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); }
final Type typeOfMap = new TypeToken<Map<String, Boolean>>() {}.getType(); final Type typeOfMap = new TypeToken<Map<String, Boolean>>() {}.getType();
final Map<String, Boolean> permissionsMap = gsonConverter.fromJson(json, typeOfMap); final Map<String, Boolean> permissionsMap = gsonConverter.fromJson(json, typeOfMap);
return new RolePermissionCommand(roleId, permissionsMap); return new RolePermissionCommand(resourceIdentifier, permissionsMap, false);
} }
@Override @Override
@@ -4,11 +4,13 @@ import java.util.HashSet;
import java.util.Set; import java.util.Set;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.mifosng.platform.accounting.api.commands.RolePermissionCommand;
import org.mifosng.platform.api.commands.RoleCommand; import org.mifosng.platform.api.commands.RoleCommand;
import org.mifosng.platform.infrastructure.api.JsonParserHelper; import org.mifosng.platform.infrastructure.api.JsonParserHelper;
import org.mifosng.platform.infrastructure.errorhandling.InvalidJsonException; import org.mifosng.platform.infrastructure.errorhandling.InvalidJsonException;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import com.google.gson.Gson;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
@@ -20,9 +22,11 @@ import com.google.gson.JsonParser;
public class PortfolioCommandDeerializerServiceGoogleGson implements PortfolioCommandDeserializerService { public class PortfolioCommandDeerializerServiceGoogleGson implements PortfolioCommandDeserializerService {
private final JsonParser parser; private final JsonParser parser;
private final Gson gsonConverter;
public PortfolioCommandDeerializerServiceGoogleGson() { public PortfolioCommandDeerializerServiceGoogleGson() {
parser = new JsonParser(); parser = new JsonParser();
gsonConverter = new Gson();
} }
@Override @Override
@@ -39,4 +43,14 @@ public class PortfolioCommandDeerializerServiceGoogleGson implements PortfolioCo
return new RoleCommand(parametersPassedInRequest, makerCheckerApproval, roleId, name, description); return new RoleCommand(parametersPassedInRequest, makerCheckerApproval, roleId, name, description);
} }
@Override
public RolePermissionCommand deserializeRolePermissionCommand(final Long roleId, final String commandAsJson, final boolean makerCheckerApproval) {
if (StringUtils.isBlank(commandAsJson)) { throw new InvalidJsonException(); }
final RolePermissionCommand command = gsonConverter.fromJson(commandAsJson, RolePermissionCommand.class);
return new RolePermissionCommand(roleId, command.getPermissions(), makerCheckerApproval);
}
} }
@@ -1,5 +1,6 @@
package org.mifosng.platform.api.infrastructure; package org.mifosng.platform.api.infrastructure;
import org.mifosng.platform.accounting.api.commands.RolePermissionCommand;
import org.mifosng.platform.api.commands.RoleCommand; import org.mifosng.platform.api.commands.RoleCommand;
/** /**
@@ -15,4 +16,6 @@ import org.mifosng.platform.api.commands.RoleCommand;
public interface PortfolioCommandDeserializerService { public interface PortfolioCommandDeserializerService {
RoleCommand deserializeRoleCommand(Long roleId, String commandAsJson, boolean makerCheckerApproval); RoleCommand deserializeRoleCommand(Long roleId, String commandAsJson, boolean makerCheckerApproval);
RolePermissionCommand deserializeRolePermissionCommand(Long roleId, String commandAsJson, boolean makerCheckerApproval);
} }
@@ -1,5 +1,6 @@
package org.mifosng.platform.api.infrastructure; package org.mifosng.platform.api.infrastructure;
import org.mifosng.platform.accounting.api.commands.RolePermissionCommand;
import org.mifosng.platform.api.commands.RoleCommand; import org.mifosng.platform.api.commands.RoleCommand;
/** /**
@@ -11,4 +12,6 @@ import org.mifosng.platform.api.commands.RoleCommand;
public interface PortfolioCommandSerializerService { public interface PortfolioCommandSerializerService {
String serializeRoleCommandToJson(RoleCommand command); String serializeRoleCommandToJson(RoleCommand command);
String serializeRolePermissionCommandToJson(RolePermissionCommand command);
} }
@@ -2,6 +2,7 @@ package org.mifosng.platform.api.infrastructure;
import java.util.HashSet; import java.util.HashSet;
import org.mifosng.platform.accounting.api.commands.RolePermissionCommand;
import org.mifosng.platform.api.commands.RoleCommand; import org.mifosng.platform.api.commands.RoleCommand;
import org.mifosng.platform.infrastructure.api.GoogleGsonSerializerHelper; import org.mifosng.platform.infrastructure.api.GoogleGsonSerializerHelper;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@@ -29,4 +30,10 @@ public class PortfolioCommandSerializerServiceJson implements PortfolioCommandSe
new HashSet<String>()); new HashSet<String>());
return helper.serializedJsonFrom(gsonDeserializer, command); return helper.serializedJsonFrom(gsonDeserializer, command);
} }
@Override
public String serializeRolePermissionCommandToJson(final RolePermissionCommand command) {
final Gson gsonDeserializer = helper.createGsonBuilderWithParameterExclusionSerializationStrategy(new HashSet<String>(), false, new HashSet<String>());
return helper.serializedJsonFrom(gsonDeserializer, command);
}
} }
@@ -10,91 +10,89 @@ import org.apache.commons.lang.StringUtils;
public class ApiParameterHelper { public class ApiParameterHelper {
public static Long makerCheckerId(final MultivaluedMap<String, String> queryParams) { public static Long commandId(final MultivaluedMap<String, String> queryParams) {
Long id = null; Long id = null;
if (queryParams.getFirst("makerCheckerId") != null) { if (queryParams.getFirst("commandId") != null) {
final String value = queryParams.getFirst("makerCheckerId"); final String value = queryParams.getFirst("commandId");
if (StringUtils.isNotBlank(value)) { if (StringUtils.isNotBlank(value)) {
id = Long.valueOf(value); id = Long.valueOf(value);
} }
} }
return id; return id;
} }
public static Set<String> extractFieldsForResponseIfProvided(final MultivaluedMap<String, String> queryParams) { public static Set<String> extractFieldsForResponseIfProvided(final MultivaluedMap<String, String> queryParams) {
Set<String> fields = new HashSet<String>(); Set<String> fields = new HashSet<String>();
String commaSerperatedParameters = ""; String commaSerperatedParameters = "";
if (queryParams.getFirst("fields") != null) { if (queryParams.getFirst("fields") != null) {
commaSerperatedParameters = queryParams.getFirst("fields"); commaSerperatedParameters = queryParams.getFirst("fields");
if (StringUtils.isNotBlank(commaSerperatedParameters)) { if (StringUtils.isNotBlank(commaSerperatedParameters)) {
fields = new HashSet<String>(Arrays.asList(commaSerperatedParameters.split("\\s*,\\s*"))); fields = new HashSet<String>(Arrays.asList(commaSerperatedParameters.split("\\s*,\\s*")));
} }
} }
return fields; return fields;
} }
public static Set<String> extractAssociationsForResponseIfProvided(final MultivaluedMap<String, String> queryParams) { public static Set<String> extractAssociationsForResponseIfProvided(final MultivaluedMap<String, String> queryParams) {
Set<String> fields = new HashSet<String>(); Set<String> fields = new HashSet<String>();
String commaSerperatedParameters = ""; String commaSerperatedParameters = "";
if (queryParams.getFirst("associations") != null) { if (queryParams.getFirst("associations") != null) {
commaSerperatedParameters = queryParams.getFirst("associations"); commaSerperatedParameters = queryParams.getFirst("associations");
if (StringUtils.isNotBlank(commaSerperatedParameters)) { if (StringUtils.isNotBlank(commaSerperatedParameters)) {
fields = new HashSet<String>(Arrays.asList(commaSerperatedParameters.split("\\s*,\\s*"))); fields = new HashSet<String>(Arrays.asList(commaSerperatedParameters.split("\\s*,\\s*")));
} }
} }
return fields; return fields;
} }
public static boolean prettyPrint(final MultivaluedMap<String, String> queryParams) { public static boolean prettyPrint(final MultivaluedMap<String, String> queryParams) {
boolean prettyPrint = false; boolean prettyPrint = false;
if (queryParams.getFirst("pretty") != null) { if (queryParams.getFirst("pretty") != null) {
String prettyPrintValue = queryParams.getFirst("pretty"); String prettyPrintValue = queryParams.getFirst("pretty");
prettyPrint = "true".equalsIgnoreCase(prettyPrintValue); prettyPrint = "true".equalsIgnoreCase(prettyPrintValue);
} }
return prettyPrint; return prettyPrint;
} }
public static boolean exportCsv(final MultivaluedMap<String, String> queryParams) { public static boolean exportCsv(final MultivaluedMap<String, String> queryParams) {
boolean exportCsv = false; boolean exportCsv = false;
if (queryParams.getFirst("exportCSV") != null) { if (queryParams.getFirst("exportCSV") != null) {
String exportCsvValue = queryParams.getFirst("exportCSV"); String exportCsvValue = queryParams.getFirst("exportCSV");
exportCsv = "true".equalsIgnoreCase(exportCsvValue); exportCsv = "true".equalsIgnoreCase(exportCsvValue);
} }
return exportCsv; return exportCsv;
} }
public static boolean parameterType(final MultivaluedMap<String, String> queryParams) { public static boolean parameterType(final MultivaluedMap<String, String> queryParams) {
boolean parameterType = false; boolean parameterType = false;
if (queryParams.getFirst("parameterType") != null) { if (queryParams.getFirst("parameterType") != null) {
String parameterTypeValue = queryParams.getFirst("parameterType"); String parameterTypeValue = queryParams.getFirst("parameterType");
parameterType = "true".equalsIgnoreCase(parameterTypeValue); parameterType = "true".equalsIgnoreCase(parameterTypeValue);
} }
return parameterType; return parameterType;
} }
public static boolean template(final MultivaluedMap<String, String> queryParams) { public static boolean template(final MultivaluedMap<String, String> queryParams) {
boolean template = false; boolean template = false;
if (queryParams.getFirst("template") != null) { if (queryParams.getFirst("template") != null) {
String prettyPrintValue = queryParams.getFirst("template"); String prettyPrintValue = queryParams.getFirst("template");
template = "true".equalsIgnoreCase(prettyPrintValue); template = "true".equalsIgnoreCase(prettyPrintValue);
} }
return template; return template;
} }
public static boolean genericResultSet(final MultivaluedMap<String, String> queryParams) { public static boolean genericResultSet(final MultivaluedMap<String, String> queryParams) {
boolean genericResultSet = false; boolean genericResultSet = false;
if (queryParams.getFirst("genericResultSet") != null) { if (queryParams.getFirst("genericResultSet") != null) {
String genericResultSetValue = queryParams.getFirst("genericResultSet"); String genericResultSetValue = queryParams.getFirst("genericResultSet");
genericResultSet = "true".equalsIgnoreCase(genericResultSetValue); genericResultSet = "true".equalsIgnoreCase(genericResultSetValue);
} }
return genericResultSet; return genericResultSet;
} }
public static String sqlEncodeString(String str) { public static String sqlEncodeString(String str) {
String singleQuote = "'"; String singleQuote = "'";
String twoSingleQuotes = "''"; String twoSingleQuotes = "''";
return singleQuote return singleQuote + StringUtils.replace(str, singleQuote, twoSingleQuotes, -1) + singleQuote;
+ StringUtils.replace(str, singleQuote, twoSingleQuotes, -1)
+ singleQuote;
} }
} }
@@ -447,4 +447,5 @@ public class JsonParserHelper {
} }
return clientApplicationLocale; return clientApplicationLocale;
} }
} }
@@ -120,6 +120,10 @@ public class CommandSource extends AbstractPersistable<Long> {
return this.apiOperation.equalsIgnoreCase("DELETE") && this.resourceId != null; return this.apiOperation.equalsIgnoreCase("DELETE") && this.resourceId != null;
} }
public boolean isUpdateRolePermissions() {
return this.apiOperation.equalsIgnoreCase("UPDATEPERMISSIONS") && this.resourceId != null;
}
public boolean isClientResource() { public boolean isClientResource() {
return this.resource.equalsIgnoreCase("CLIENTS"); return this.resource.equalsIgnoreCase("CLIENTS");
} }
@@ -4,9 +4,9 @@ import org.mifosng.platform.api.data.EntityIdentifier;
public interface PortfolioCommandSourceWritePlatformService { public interface PortfolioCommandSourceWritePlatformService {
EntityIdentifier logCommandSource(String apiOperation, String resource, Long resourceId, String jsonRequestBody); EntityIdentifier logCommandSource(String apiOperation, String resource, Long resourceId, String jsonRequestBody);
EntityIdentifier approveEntry(Long id); EntityIdentifier approveEntry(Long id);
Long deleteEntry(Long makerCheckerId); Long deleteEntry(Long makerCheckerId);
} }
@@ -19,8 +19,7 @@ public class PortfolioCommandSourceWriteServiceImpl implements PortfolioCommandS
@Autowired @Autowired
public PortfolioCommandSourceWriteServiceImpl(final PlatformSecurityContext context, public PortfolioCommandSourceWriteServiceImpl(final PlatformSecurityContext context,
final CommandSourceRepository makerCheckerRepository, final CommandSourceRepository makerCheckerRepository, final CommandSourceHandlerDelegator commandSourceHandlerDelegator) {
final CommandSourceHandlerDelegator commandSourceHandlerDelegator) {
this.context = context; this.context = context;
this.commandSourceRepository = makerCheckerRepository; this.commandSourceRepository = makerCheckerRepository;
this.commandSourceHandlerDelegator = commandSourceHandlerDelegator; this.commandSourceHandlerDelegator = commandSourceHandlerDelegator;
@@ -6,10 +6,9 @@ import org.mifosng.platform.api.data.CommandSourceData;
public interface PortfolioCommandsReadPlatformService { public interface PortfolioCommandsReadPlatformService {
Collection<CommandSourceData> retrieveAllEntriesToBeChecked(); Collection<CommandSourceData> retrieveAllEntriesToBeChecked();
CommandSourceData retrieveById(Long id); CommandSourceData retrieveById(Long id);
Collection<CommandSourceData> retrieveUnprocessChangesByResourceId(String apiResource, Long clientId);
Collection<CommandSourceData> retrieveUnprocessChangesByResourceId(String apiResource, Long clientId);
} }
@@ -17,65 +17,65 @@ import org.springframework.stereotype.Service;
@Service @Service
public class PortfolioCommandsReadPlatformServiceImpl implements PortfolioCommandsReadPlatformService { public class PortfolioCommandsReadPlatformServiceImpl implements PortfolioCommandsReadPlatformService {
private final JdbcTemplate jdbcTemplate; private final JdbcTemplate jdbcTemplate;
private final PlatformSecurityContext context; private final PlatformSecurityContext context;
@Autowired @Autowired
public PortfolioCommandsReadPlatformServiceImpl( public PortfolioCommandsReadPlatformServiceImpl(final PlatformSecurityContext context, final TenantAwareRoutingDataSource dataSource) {
final PlatformSecurityContext context, this.context = context;
final TenantAwareRoutingDataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource);
this.context = context; }
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
private static final class CommandSourceMapper implements RowMapper<CommandSourceData> { private static final class CommandSourceMapper implements RowMapper<CommandSourceData> {
public String schema() { public String schema() {
return " mc.id as id, mc.api_operation as taskOperation, mc.api_resource as taskEntity, mc.resource_id as entityId," + return " mc.id as id, mc.api_operation as taskOperation, mc.api_resource as taskEntity, mc.resource_id as entityId,"
"mc.command_as_json as taskJson, mc.made_on_date as madeOnDate from m_portfolio_command_source mc "; + "mc.command_as_json as taskJson, mc.made_on_date as madeOnDate from m_portfolio_command_source mc ";
} }
@Override @Override
public CommandSourceData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) public CommandSourceData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
throws SQLException {
final Long id = rs.getLong("id"); final Long id = rs.getLong("id");
final String taskOperation = rs.getString("taskOperation"); final String taskOperation = rs.getString("taskOperation");
final String taskEntity = rs.getString("taskEntity"); final String taskEntity = rs.getString("taskEntity");
final Long entityId = JdbcSupport.getLong(rs, "entityId"); final Long entityId = JdbcSupport.getLong(rs, "entityId");
final String taskJson = rs.getString("taskJson"); final String taskJson = rs.getString("taskJson");
final LocalDate madeOnDate = JdbcSupport.getLocalDate(rs, "madeOnDate"); final LocalDate madeOnDate = JdbcSupport.getLocalDate(rs, "madeOnDate");
return new CommandSourceData(id, taskOperation, taskEntity, entityId, taskJson, madeOnDate); return new CommandSourceData(id, taskOperation, taskEntity, entityId, taskJson, madeOnDate);
} }
} }
@Override @Override
public Collection<CommandSourceData> retrieveAllEntriesToBeChecked() { public Collection<CommandSourceData> retrieveAllEntriesToBeChecked() {
context.authenticatedUser(); context.authenticatedUser();
final CommandSourceMapper rm = new CommandSourceMapper(); final CommandSourceMapper rm = new CommandSourceMapper();
final String sql = "select " + rm.schema() + " where mc.checker_id is null order by mc.made_on_date DESC, mc.api_resource ASC, mc.api_operation ASC"; final String sql = "select " + rm.schema()
+ " where mc.checker_id is null order by mc.made_on_date DESC, mc.api_resource ASC, mc.api_operation ASC";
return this.jdbcTemplate.query(sql, rm, new Object[] {}); return this.jdbcTemplate.query(sql, rm, new Object[] {});
} }
@Override @Override
public CommandSourceData retrieveById(final Long id) { public CommandSourceData retrieveById(final Long id) {
final CommandSourceMapper rm = new CommandSourceMapper(); final CommandSourceMapper rm = new CommandSourceMapper();
final String sql = "select " + rm.schema() + " where mc.id=?"; final String sql = "select " + rm.schema() + " where mc.id=?";
return this.jdbcTemplate.queryForObject(sql, rm, new Object[] {id}); return this.jdbcTemplate.queryForObject(sql, rm, new Object[] { id });
} }
@Override @Override
public Collection<CommandSourceData> retrieveUnprocessChangesByResourceId(final String apiResource, final Long resourceId) { public Collection<CommandSourceData> retrieveUnprocessChangesByResourceId(final String apiResource, final Long resourceId) {
final CommandSourceMapper rm = new CommandSourceMapper(); final CommandSourceMapper rm = new CommandSourceMapper();
final String sql = "select " + rm.schema() + " where mc.api_resource like ? and mc.resource_id = ? and mc.checker_id is null order by mc.made_on_date DESC, mc.api_operation ASC"; final String sql = "select "
+ rm.schema()
+ " where mc.api_resource like ? and mc.resource_id = ? and mc.checker_id is null order by mc.made_on_date DESC, mc.api_operation ASC";
return this.jdbcTemplate.query(sql, rm, new Object[] {apiResource, resourceId}); return this.jdbcTemplate.query(sql, rm, new Object[] { apiResource, resourceId });
} }
} }
@@ -1,6 +1,7 @@
package org.mifosng.platform.makerchecker.service; package org.mifosng.platform.makerchecker.service;
import org.joda.time.LocalDate; import org.joda.time.LocalDate;
import org.mifosng.platform.accounting.api.commands.RolePermissionCommand;
import org.mifosng.platform.api.commands.RoleCommand; import org.mifosng.platform.api.commands.RoleCommand;
import org.mifosng.platform.api.infrastructure.PortfolioApiDataConversionService; import org.mifosng.platform.api.infrastructure.PortfolioApiDataConversionService;
import org.mifosng.platform.api.infrastructure.PortfolioCommandDeserializerService; import org.mifosng.platform.api.infrastructure.PortfolioCommandDeserializerService;
@@ -53,12 +54,12 @@ public class RoleCommandHandler implements CommandSourceHandler {
final Long resourceId = commandSource.resourceId(); final Long resourceId = commandSource.resourceId();
Long newResourceId = null; Long newResourceId = null;
final RoleCommand command = this.apiDataConversionService.convertApiRequestJsonToRoleCommand(resourceId, apiRequestBodyInJson);
final String commandSerializedAsJson = this.commandSerializerService.serializeRoleCommandToJson(command);
commandSourceResult.updateJsonTo(commandSerializedAsJson);
if (commandSource.isCreate()) { if (commandSource.isCreate()) {
try { try {
final RoleCommand command = this.apiDataConversionService.convertApiRequestJsonToRoleCommand(resourceId, apiRequestBodyInJson);
final String commandSerializedAsJson = this.commandSerializerService.serializeRoleCommandToJson(command);
commandSourceResult.updateJsonTo(commandSerializedAsJson);
newResourceId = this.writePlatformService.createRole(command); newResourceId = this.writePlatformService.createRole(command);
commandSourceResult.markAsChecked(maker, asToday); commandSourceResult.markAsChecked(maker, asToday);
commandSourceResult.updateResourceId(newResourceId); commandSourceResult.updateResourceId(newResourceId);
@@ -67,6 +68,10 @@ public class RoleCommandHandler implements CommandSourceHandler {
} }
} else if (commandSource.isUpdate()) { } else if (commandSource.isUpdate()) {
try { try {
final RoleCommand command = this.apiDataConversionService.convertApiRequestJsonToRoleCommand(resourceId, apiRequestBodyInJson);
final String commandSerializedAsJson = this.commandSerializerService.serializeRoleCommandToJson(command);
commandSourceResult.updateJsonTo(commandSerializedAsJson);
final String jsonOfChangesOnly = this.changeDetectionService.detectChangesOnUpdate(commandSource.resourceName(), commandSource.resourceId(), commandSerializedAsJson); final String jsonOfChangesOnly = this.changeDetectionService.detectChangesOnUpdate(commandSource.resourceName(), commandSource.resourceId(), commandSerializedAsJson);
commandSourceResult.updateJsonTo(jsonOfChangesOnly); commandSourceResult.updateJsonTo(jsonOfChangesOnly);
@@ -74,6 +79,23 @@ public class RoleCommandHandler implements CommandSourceHandler {
newResourceId = this.writePlatformService.updateRole(changesOnly); newResourceId = this.writePlatformService.updateRole(changesOnly);
commandSourceResult.markAsChecked(maker, asToday);
} catch (RollbackTransactionAsCommandIsNotApprovedByCheckerException e) {
// swallow this rollback transaction by design
}
} else if (commandSource.isUpdateRolePermissions()) {
try {
final RolePermissionCommand command = this.apiDataConversionService.convertApiRequestJsonToRolePermissionCommand(resourceId, apiRequestBodyInJson);
final String commandSerializedAsJson = this.commandSerializerService.serializeRolePermissionCommandToJson(command);
commandSourceResult.updateJsonTo(commandSerializedAsJson);
final String jsonOfChangesOnly = this.changeDetectionService.detectChangesOnUpdate(commandSource.resourceName(), commandSource.resourceId(), commandSerializedAsJson);
commandSourceResult.updateJsonTo(jsonOfChangesOnly);
final RolePermissionCommand changesOnly = this.commandDeserializerService.deserializeRolePermissionCommand(resourceId, jsonOfChangesOnly, false);
newResourceId =this.writePlatformService.updateRolePermissions(changesOnly);
commandSourceResult.markAsChecked(maker, asToday); commandSourceResult.markAsChecked(maker, asToday);
} catch (RollbackTransactionAsCommandIsNotApprovedByCheckerException e) { } catch (RollbackTransactionAsCommandIsNotApprovedByCheckerException e) {
// swallow this rollback transaction by design // swallow this rollback transaction by design
@@ -90,14 +112,17 @@ public class RoleCommandHandler implements CommandSourceHandler {
*/ */
public CommandSource handle(final CommandSource commandSourceResult) { public CommandSource handle(final CommandSource commandSourceResult) {
Long resourceId = null; Long resourceId = commandSourceResult.resourceId();
if (commandSourceResult.isRoleResource()) { if (commandSourceResult.isRoleResource()) {
final RoleCommand command = this.commandDeserializerService.deserializeRoleCommand(resourceId, commandSourceResult.json(), true);
if (commandSourceResult.isCreate()) { if (commandSourceResult.isCreate()) {
final RoleCommand command = this.commandDeserializerService.deserializeRoleCommand(resourceId, commandSourceResult.json(), true);
resourceId = this.writePlatformService.createRole(command); resourceId = this.writePlatformService.createRole(command);
} else if (commandSourceResult.isUpdate()) { } else if (commandSourceResult.isUpdate()) {
final RoleCommand command = this.commandDeserializerService.deserializeRoleCommand(resourceId, commandSourceResult.json(), true);
resourceId = this.writePlatformService.updateRole(command); resourceId = this.writePlatformService.updateRole(command);
} else if (commandSourceResult.isUpdateRolePermissions()) {
final RolePermissionCommand command = this.commandDeserializerService.deserializeRolePermissionCommand(resourceId, commandSourceResult.json(), true);
resourceId =this.writePlatformService.updateRolePermissions(command);
} else if (commandSourceResult.isDelete()) { } else if (commandSourceResult.isDelete()) {
throw new UnsupportedCommandException(commandSourceResult.commandName()); throw new UnsupportedCommandException(commandSourceResult.commandName());
} }
@@ -30,12 +30,10 @@ public class Role extends AbstractAuditableCustom<AppUser, Long> {
@ManyToMany(fetch = FetchType.EAGER) @ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "m_role_permission", joinColumns = @JoinColumn(name = "role_id"), inverseJoinColumns = @JoinColumn(name = "permission_id")) @JoinTable(name = "m_role_permission", joinColumns = @JoinColumn(name = "role_id"), inverseJoinColumns = @JoinColumn(name = "permission_id"))
private Set<Permission> permissions; private Set<Permission> permissions = new HashSet<Permission>();
protected Role() { protected Role() {
this.name = null; //
this.description = null;
this.permissions = new HashSet<Permission>();
} }
public Role(final String name, final String description) { public Role(final String name, final String description) {
@@ -43,6 +41,24 @@ public class Role extends AbstractAuditableCustom<AppUser, Long> {
this.description = description.trim(); this.description = description.trim();
} }
public void update(final RoleCommand command) {
if (command.isNameChanged()) {
this.name = command.getName();
}
if (command.isDescriptionChanged()) {
this.description = command.getDescription();
}
}
public boolean addPermission(final Permission permission) {
return this.permissions.add(permission);
}
public boolean removePermission(final Permission permission) {
return this.permissions.remove(permission);
}
public Collection<Permission> getPermissions() { public Collection<Permission> getPermissions() {
return this.permissions; return this.permissions;
} }
@@ -60,7 +76,7 @@ public class Role extends AbstractAuditableCustom<AppUser, Long> {
public RoleData toData() { public RoleData toData() {
Collection<PermissionData> rolePermissions = new ArrayList<PermissionData>(); final Collection<PermissionData> rolePermissions = new ArrayList<PermissionData>(this.permissions.size());
for (Permission permission : this.permissions) { for (Permission permission : this.permissions) {
PermissionData permissionData = permission.toData(); PermissionData permissionData = permission.toData();
rolePermissions.add(permissionData); rolePermissions.add(permissionData);
@@ -68,20 +84,4 @@ public class Role extends AbstractAuditableCustom<AppUser, Long> {
return new RoleData(this.getId(), this.name, this.description, rolePermissions); return new RoleData(this.getId(), this.name, this.description, rolePermissions);
} }
public void update(final RoleCommand command) {
if (command.isNameChanged()) {
this.name = command.getName();
}
if (command.isDescriptionChanged()) {
this.description = command.getDescription();
}
}
public String getName() {
return name;
}
} }
@@ -82,27 +82,24 @@ public class RoleWritePlatformServiceJpaRepositoryImpl implements RoleWritePlatf
final Role role = this.roleRepository.findOne(command.getRoleId()); final Role role = this.roleRepository.findOne(command.getRoleId());
if (role == null) { throw new RoleNotFoundException(command.getRoleId()); } if (role == null) { throw new RoleNotFoundException(command.getRoleId()); }
Collection<Permission> allPermissions = this.permissionRepository.findAll(); final Collection<Permission> allPermissions = this.permissionRepository.findAll();
Map<String, Boolean> commandPermissions = command.getPermissions(); final Map<String, Boolean> commandPermissions = command.getPermissions();
for (String permissionCode : commandPermissions.keySet()) { for (final String permissionCode : commandPermissions.keySet()) {
Boolean selected = commandPermissions.get(permissionCode); final boolean isSelected = commandPermissions.get(permissionCode).booleanValue();
final Permission permission = findPermissionByCode(allPermissions, permissionCode); final Permission permission = findPermissionByCode(allPermissions, permissionCode);
if (isSelected) {
if (role.getPermissions().contains(permission)) { role.addPermission(permission);
if (!(selected)) {
role.getPermissions().remove(permission);
}
} else { } else {
if (selected) { role.removePermission(permission);
role.getPermissions().add(permission);
}
} }
} }
this.roleRepository.save(role); this.roleRepository.save(role);
if (this.makerCheckerEnabledForTask && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); }
return role.getId(); return role.getId();
} }