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,17 +45,17 @@ 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,29 +124,31 @@ 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);
} }
@PUT @PUT
@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 EntityIdentifier result = this.commandsSourceWritePlatformService.logCommandSource("UPDATE", "roles", roleId, apiRequestBodyAsJson);
final RoleCommand command = this.apiDataConversionService.convertApiRequestJsonToRoleCommand(roleId, jsonRequestBody); return this.apiJsonSerializerService.serializeEntityIdentifier(result);
this.roleWritePlatformService.updateRole(command);
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 ClientData currentChange;
private final Collection<ClientData> allChanges;
private static String buildDisplayNameFrom(final String firstname, final String lastname) { private final List<OfficeLookup> allowedOffices;
String displayName = null;
StringBuilder displayNameBuilder = new StringBuilder();
if (StringUtils.isNotBlank(firstname)) {
displayNameBuilder.append(firstname).append(' ');
}
if (StringUtils.isNotBlank(lastname)) { private final ClientData currentChange;
displayNameBuilder.append(lastname); private final Collection<ClientData> allChanges;
displayName = displayNameBuilder.toString();
}
return displayName;
}
public static ClientData dataChangeInstance(
final Long id,
final Long officeId,
final String externalId,
final String firstname,
final String lastname,
final String clientOrBusinessName,
final LocalDate joiningDate) {
String firstnameValue = firstname;
String lastnameValue = lastname;
if (StringUtils.isNotBlank(clientOrBusinessName)) {
firstnameValue = null;
lastnameValue = clientOrBusinessName;
}
final String displayName = buildDisplayNameFrom(firstnameValue, lastnameValue);
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) {
String firstname = clientData.firstname;
String lastname = clientData.lastname;
if (StringUtils.isNotBlank(clientData.clientOrBusinessName)) {
firstname = null;
lastname = clientData.clientOrBusinessName;
}
final String displayName = buildDisplayNameFrom(firstname, lastname);
return new ClientData(clientData.officeId, clientData.officeName, clientData.id, firstname, lastname, displayName,
clientData.externalId, clientData.joinedDate, clientData.imageKey, clientData.allowedOffices, currentChange, allChanges);
}
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);
}
public static ClientData templateOnTop(final ClientData clientData, final List<OfficeLookup> allowedOffices) {
String firstname = clientData.firstname;
String lastname = clientData.lastname;
if (StringUtils.isNotBlank(clientData.clientOrBusinessName)) {
firstname = null;
lastname = clientData.clientOrBusinessName;
}
final String displayName = buildDisplayNameFrom(firstname, lastname);
return new ClientData(clientData.officeId, clientData.officeName, clientData.id, firstname, lastname, displayName,
clientData.externalId, clientData.joinedDate, clientData.imageKey, allowedOffices, clientData.currentChange, clientData.allChanges);
}
public static ClientData clientIdentifier(
final Long id,
final String firstname,
final String lastname,
final Long officeId,
final String officeName) {
final String displayName = buildDisplayNameFrom(firstname, lastname);
return new ClientData(officeId, officeName, id, firstname, lastname, displayName, null, null, null, null, null, null);
}
public ClientData( private static String buildDisplayNameFrom(final String firstname, final String lastname) {
final Long officeId, String displayName = null;
final String officeName, StringBuilder displayNameBuilder = new StringBuilder();
final Long id, if (StringUtils.isNotBlank(firstname)) {
final String firstname, displayNameBuilder.append(firstname).append(' ');
final String lastname, }
final String displayName,
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 **/ if (StringUtils.isNotBlank(lastname)) {
if (StringUtils.isBlank(firstname)) { displayNameBuilder.append(lastname);
this.lastname = null; displayName = displayNameBuilder.toString();
this.clientOrBusinessName = lastname; }
} else { return displayName;
this.lastname = lastname; }
this.clientOrBusinessName = null;
}
this.displayName = displayName;
this.externalId = externalId;
this.joinedDate = joinedDate;
this.imageKey = imageKey;
if (imageKey != null) {
this.imagePresent = Boolean.TRUE;
} else {
this.imagePresent = null;
}
this.allowedOffices = allowedOffices;
this.currentChange = currentChange;
this.allChanges = allChanges;
}
public String displayName() { public static ClientData dataChangeInstance(final Long id, final Long officeId, final String externalId, final String firstname,
return this.displayName; final String lastname, final String clientOrBusinessName, final LocalDate joiningDate) {
}
public String officeName() { String firstnameValue = firstname;
return this.officeName; String lastnameValue = lastname;
} if (StringUtils.isNotBlank(clientOrBusinessName)) {
firstnameValue = null;
private boolean imageKeyExists() { lastnameValue = clientOrBusinessName;
return StringUtils.isNotBlank(this.imageKey); }
} final String displayName = buildDisplayNameFrom(firstnameValue, lastnameValue);
public boolean imageKeyDoesNotExist() { return new ClientData(officeId, null, id, firstname, lastname, displayName, externalId, joiningDate, null, null, null, null);
return !imageKeyExists(); }
}
public String imageKey() { public static ClientData integrateChanges(final ClientData clientData, ClientData currentChange, final Collection<ClientData> allChanges) {
return this.imageKey; String firstname = clientData.firstname;
} String lastname = clientData.lastname;
if (StringUtils.isNotBlank(clientData.clientOrBusinessName)) {
firstname = null;
lastname = clientData.clientOrBusinessName;
}
final String displayName = buildDisplayNameFrom(firstname, lastname);
return new ClientData(clientData.officeId, clientData.officeName, clientData.id, firstname, lastname, displayName,
clientData.externalId, clientData.joinedDate, clientData.imageKey, clientData.allowedOffices, currentChange, allChanges);
}
public Long id() { public static ClientData template(final Long officeId, final LocalDate joinedDate, final List<OfficeLookup> allowedOffices) {
return this.id; return new ClientData(officeId, null, null, null, null, null, null, joinedDate, null, allowedOffices, null, null);
} }
public Long officeId() { public static ClientData templateOnTop(final ClientData clientData, final List<OfficeLookup> allowedOffices) {
return this.officeId;
}
public ClientData currentChange() { String firstname = clientData.firstname;
return this.currentChange; String lastname = clientData.lastname;
} if (StringUtils.isNotBlank(clientData.clientOrBusinessName)) {
firstname = null;
lastname = clientData.clientOrBusinessName;
}
final String displayName = buildDisplayNameFrom(firstname, lastname);
return new ClientData(clientData.officeId, clientData.officeName, clientData.id, firstname, lastname, displayName,
clientData.externalId, clientData.joinedDate, clientData.imageKey, allowedOffices, clientData.currentChange,
clientData.allChanges);
}
public static ClientData clientIdentifier(final Long id, final String firstname, final String lastname, final Long officeId,
final String officeName) {
final String displayName = buildDisplayNameFrom(firstname, lastname);
return new ClientData(officeId, officeName, id, firstname, lastname, displayName, null, null, null, null, null, null);
}
public ClientData(final Long officeId, final String officeName, final Long id, final String firstname, final String lastname,
final String displayName, 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 **/
if (StringUtils.isBlank(firstname)) {
this.lastname = null;
this.clientOrBusinessName = lastname;
} else {
this.lastname = lastname;
this.clientOrBusinessName = null;
}
this.displayName = displayName;
this.externalId = externalId;
this.joinedDate = joinedDate;
this.imageKey = imageKey;
if (imageKey != null) {
this.imagePresent = Boolean.TRUE;
} else {
this.imagePresent = null;
}
this.allowedOffices = allowedOffices;
this.currentChange = currentChange;
this.allChanges = allChanges;
}
public String displayName() {
return this.displayName;
}
public String officeName() {
return this.officeName;
}
private boolean imageKeyExists() {
return StringUtils.isNotBlank(this.imageKey);
}
public boolean imageKeyDoesNotExist() {
return !imageKeyExists();
}
public String imageKey() {
return this.imageKey;
}
public Long id() {
return this.id;
}
public Long officeId() {
return this.officeId;
}
public ClientData 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;
@SuppressWarnings("unused") private String resource;
private String apiOperation; private final Long resourceId;
private String commandJson;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private String resource; private final LocalDate madeOnDate;
@SuppressWarnings("unused")
private final Long resourceId;
private String commandJson;
@SuppressWarnings("unused") public CommandSourceData(final Long id, final String apiOperation, final String resource, final Long resourceId,
private final LocalDate madeOnDate; 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 CommandSourceData(final Long id, final String apiOperation, final String resource, final Long resourceId, final String commandJson, final LocalDate madeOnDate) { public String json() {
this.id = id; return this.commandJson;
this.apiOperation = apiOperation; }
this.resource = resource;
this.resourceId = resourceId; public boolean isUpdateRolePermissions() {
this.commandJson = commandJson; return this.apiOperation.equalsIgnoreCase("UPDATEPERMISSIONS") && this.resourceId != null;
this.madeOnDate = madeOnDate; }
}
public boolean isRoleResource() {
public String json() { return this.resource.equalsIgnoreCase("ROLES");
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;
@@ -15,7 +15,10 @@ public class RoleData {
@SuppressWarnings("unused") @SuppressWarnings("unused")
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) {
Set<String> fields = new HashSet<String>();
String commaSerperatedParameters = "";
if (queryParams.getFirst("fields") != null) {
commaSerperatedParameters = queryParams.getFirst("fields");
if (StringUtils.isNotBlank(commaSerperatedParameters)) {
fields = new HashSet<String>(Arrays.asList(commaSerperatedParameters.split("\\s*,\\s*")));
}
}
return fields;
}
public static Set<String> extractAssociationsForResponseIfProvided(final MultivaluedMap<String, String> queryParams) {
Set<String> fields = new HashSet<String>();
String commaSerperatedParameters = "";
if (queryParams.getFirst("associations") != null) {
commaSerperatedParameters = queryParams.getFirst("associations");
if (StringUtils.isNotBlank(commaSerperatedParameters)) {
fields = new HashSet<String>(Arrays.asList(commaSerperatedParameters.split("\\s*,\\s*")));
}
}
return fields;
}
public static boolean prettyPrint(final MultivaluedMap<String, String> queryParams) {
boolean prettyPrint = false;
if (queryParams.getFirst("pretty") != null) {
String prettyPrintValue = queryParams.getFirst("pretty");
prettyPrint = "true".equalsIgnoreCase(prettyPrintValue);
}
return prettyPrint;
}
public static boolean exportCsv(final MultivaluedMap<String, String> queryParams) {
boolean exportCsv = false;
if (queryParams.getFirst("exportCSV") != null) {
String exportCsvValue = queryParams.getFirst("exportCSV");
exportCsv = "true".equalsIgnoreCase(exportCsvValue);
}
return exportCsv;
}
public static boolean parameterType(final MultivaluedMap<String, String> queryParams) {
boolean parameterType = false;
if (queryParams.getFirst("parameterType") != null) {
String parameterTypeValue = queryParams.getFirst("parameterType");
parameterType = "true".equalsIgnoreCase(parameterTypeValue);
}
return parameterType;
}
public static boolean template(final MultivaluedMap<String, String> queryParams) { public static Set<String> extractFieldsForResponseIfProvided(final MultivaluedMap<String, String> queryParams) {
boolean template = false; Set<String> fields = new HashSet<String>();
if (queryParams.getFirst("template") != null) { String commaSerperatedParameters = "";
String prettyPrintValue = queryParams.getFirst("template"); if (queryParams.getFirst("fields") != null) {
template = "true".equalsIgnoreCase(prettyPrintValue); commaSerperatedParameters = queryParams.getFirst("fields");
} if (StringUtils.isNotBlank(commaSerperatedParameters)) {
return template; fields = new HashSet<String>(Arrays.asList(commaSerperatedParameters.split("\\s*,\\s*")));
} }
}
public static boolean genericResultSet(final MultivaluedMap<String, String> queryParams) { return fields;
boolean genericResultSet = false; }
if (queryParams.getFirst("genericResultSet") != null) {
String genericResultSetValue = queryParams.getFirst("genericResultSet"); public static Set<String> extractAssociationsForResponseIfProvided(final MultivaluedMap<String, String> queryParams) {
genericResultSet = "true".equalsIgnoreCase(genericResultSetValue); Set<String> fields = new HashSet<String>();
} String commaSerperatedParameters = "";
return genericResultSet; if (queryParams.getFirst("associations") != null) {
} commaSerperatedParameters = queryParams.getFirst("associations");
if (StringUtils.isNotBlank(commaSerperatedParameters)) {
fields = new HashSet<String>(Arrays.asList(commaSerperatedParameters.split("\\s*,\\s*")));
}
}
return fields;
}
public static boolean prettyPrint(final MultivaluedMap<String, String> queryParams) {
boolean prettyPrint = false;
if (queryParams.getFirst("pretty") != null) {
String prettyPrintValue = queryParams.getFirst("pretty");
prettyPrint = "true".equalsIgnoreCase(prettyPrintValue);
}
return prettyPrint;
}
public static boolean exportCsv(final MultivaluedMap<String, String> queryParams) {
boolean exportCsv = false;
if (queryParams.getFirst("exportCSV") != null) {
String exportCsvValue = queryParams.getFirst("exportCSV");
exportCsv = "true".equalsIgnoreCase(exportCsvValue);
}
return exportCsv;
}
public static boolean parameterType(final MultivaluedMap<String, String> queryParams) {
boolean parameterType = false;
if (queryParams.getFirst("parameterType") != null) {
String parameterTypeValue = queryParams.getFirst("parameterType");
parameterType = "true".equalsIgnoreCase(parameterTypeValue);
}
return parameterType;
}
public static boolean template(final MultivaluedMap<String, String> queryParams) {
boolean template = false;
if (queryParams.getFirst("template") != null) {
String prettyPrintValue = queryParams.getFirst("template");
template = "true".equalsIgnoreCase(prettyPrintValue);
}
return template;
}
public static boolean genericResultSet(final MultivaluedMap<String, String> queryParams) {
boolean genericResultSet = false;
if (queryParams.getFirst("genericResultSet") != null) {
String genericResultSetValue = queryParams.getFirst("genericResultSet");
genericResultSet = "true".equalsIgnoreCase(genericResultSetValue);
}
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;
@@ -51,7 +50,7 @@ public class PortfolioCommandSourceWriteServiceImpl implements PortfolioCommandS
commandSourceInput.markAsChecked(checker, new LocalDate()); commandSourceInput.markAsChecked(checker, new LocalDate());
final CommandSource commandSourceResult = this.commandSourceHandlerDelegator.handleExistingCommand(commandSourceInput); final CommandSource commandSourceResult = this.commandSourceHandlerDelegator.handleExistingCommand(commandSourceInput);
commandSourceRepository.save(commandSourceResult); commandSourceRepository.save(commandSourceResult);
return EntityIdentifier.makerChecker(commandSourceResult.resourceId(), commandSourceResult.getId()); return EntityIdentifier.makerChecker(commandSourceResult.resourceId(), commandSourceResult.getId());
@@ -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);
}
}
@@ -16,66 +16,66 @@ import org.springframework.stereotype.Service;
@Service @Service
public class PortfolioCommandsReadPlatformServiceImpl implements PortfolioCommandsReadPlatformService { public class PortfolioCommandsReadPlatformServiceImpl implements PortfolioCommandsReadPlatformService {
private final JdbcTemplate jdbcTemplate;
private final PlatformSecurityContext context;
@Autowired private final JdbcTemplate jdbcTemplate;
public PortfolioCommandsReadPlatformServiceImpl( private final PlatformSecurityContext context;
final PlatformSecurityContext context,
final TenantAwareRoutingDataSource dataSource) {
this.context = context;
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
private static final class CommandSourceMapper implements RowMapper<CommandSourceData> {
public String schema() {
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 ";
}
@Override @Autowired
public CommandSourceData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) public PortfolioCommandsReadPlatformServiceImpl(final PlatformSecurityContext context, final TenantAwareRoutingDataSource dataSource) {
throws SQLException { this.context = context;
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
final Long id = rs.getLong("id"); private static final class CommandSourceMapper implements RowMapper<CommandSourceData> {
final String taskOperation = rs.getString("taskOperation");
final String taskEntity = rs.getString("taskEntity");
final Long entityId = JdbcSupport.getLong(rs, "entityId");
final String taskJson = rs.getString("taskJson");
final LocalDate madeOnDate = JdbcSupport.getLocalDate(rs, "madeOnDate");
return new CommandSourceData(id, taskOperation, taskEntity, entityId, taskJson, madeOnDate);
}
}
@Override public String schema() {
public Collection<CommandSourceData> retrieveAllEntriesToBeChecked() { return " mc.id as id, mc.api_operation as taskOperation, mc.api_resource as taskEntity, mc.resource_id as entityId,"
context.authenticatedUser(); + "mc.command_as_json as taskJson, mc.made_on_date as madeOnDate from m_portfolio_command_source mc ";
}
final CommandSourceMapper rm = new CommandSourceMapper(); @Override
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"; public CommandSourceData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
return this.jdbcTemplate.query(sql, rm, new Object[] {}); final Long id = rs.getLong("id");
} final String taskOperation = rs.getString("taskOperation");
final String taskEntity = rs.getString("taskEntity");
final Long entityId = JdbcSupport.getLong(rs, "entityId");
final String taskJson = rs.getString("taskJson");
@Override final LocalDate madeOnDate = JdbcSupport.getLocalDate(rs, "madeOnDate");
public CommandSourceData retrieveById(final Long id) {
final CommandSourceMapper rm = new CommandSourceMapper();
final String sql = "select " + rm.schema() + " where mc.id=?";
return this.jdbcTemplate.queryForObject(sql, rm, new Object[] {id}); return new CommandSourceData(id, taskOperation, taskEntity, entityId, taskJson, madeOnDate);
} }
}
@Override @Override
public Collection<CommandSourceData> retrieveUnprocessChangesByResourceId(final String apiResource, final Long resourceId) { public Collection<CommandSourceData> retrieveAllEntriesToBeChecked() {
context.authenticatedUser();
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";
return this.jdbcTemplate.query(sql, rm, new Object[] {apiResource, resourceId}); 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";
return this.jdbcTemplate.query(sql, rm, new Object[] {});
}
@Override
public CommandSourceData retrieveById(final Long id) {
final CommandSourceMapper rm = new CommandSourceMapper();
final String sql = "select " + rm.schema() + " where mc.id=?";
return this.jdbcTemplate.queryForObject(sql, rm, new Object[] { id });
}
@Override
public Collection<CommandSourceData> retrieveUnprocessChangesByResourceId(final String apiResource, final Long resourceId) {
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";
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,18 +30,34 @@ 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) {
this.name = name.trim(); this.name = name.trim();
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,26 +82,23 @@ 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();
} }