changes for crud on code table

This commit is contained in:
ismail
2012-11-15 14:07:51 +01:00
parent 0f2b5fd05d
commit 51f661de17
7 changed files with 190 additions and 25 deletions
@@ -4,6 +4,7 @@ import java.util.Collection;
import java.util.Set;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
@@ -41,10 +42,11 @@ public class CodesApiResource {
@Autowired
private PortfolioApiDataConversionService apiDataConversionService;
@Autowired
private PortfolioApiJsonSerializerService apiJsonSerializerService;
private final String entityType = "CODE";
private final PlatformSecurityContext context;
@@ -52,19 +54,20 @@ public class CodesApiResource {
public CodesApiResource(final PlatformSecurityContext context) {
this.context = context;
}
@GET
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public String retrieveCodes(@Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType);
Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
final Collection<CodeData> codes = this.readPlatformService.retrieveAllCodes();
return this.apiJsonSerializerService.serializeCodeDataToJson(prettyPrint, responseParameters, codes);
}
@@ -72,21 +75,50 @@ public class CodesApiResource {
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response createCode(final String jsonRequestBody) {
final CodeCommand command = this.apiDataConversionService.convertJsonToCodeCommand(null, jsonRequestBody);
final Long id = this.writePlatformService.createCode(command);
return Response.ok().entity(new EntityIdentifier(id)).build();
}
@GET
@Path("{codeId}")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public String retreiveOffice(@PathParam("codeId") final Long codeId, @Context final UriInfo uriInfo) {
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
final CodeData code = this.readPlatformService.retrieveCode(codeId);
return this.apiJsonSerializerService.serializeCodeDataToJson(prettyPrint, responseParameters, code);
}
@PUT
@Path("{Id}")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response updateCode(@PathParam("Id") final Long Id, final String jsonRequestBody) {
public Response updateCode(@PathParam("Id") final Long codeId, final String jsonRequestBody) {
final CodeCommand command = this.apiDataConversionService.convertJsonToCodeCommand(codeId, jsonRequestBody);
final Long entityId = this.writePlatformService.updateCode(command);
return Response.ok().entity(new EntityIdentifier(entityId)).build();
return null;
}
@DELETE
@Path("{codeId}")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public Response deleteCodeApplication(@PathParam("codeId") final Long Id) {
EntityIdentifier identifier = this.writePlatformService.deleteCode(Id);
return Response.ok().entity(identifier).build();
}
}
@@ -25,9 +25,9 @@ public class CodeCommand {
public String getCodeName() {
return codeName;
}
public boolean isNameChanged() {
return this.modifiedParameters.contains("codename");
return this.modifiedParameters.contains("name");
}
}
@@ -5,8 +5,12 @@ import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import org.apache.commons.lang.StringUtils;
import org.mifosng.platform.api.commands.CodeCommand;
import org.springframework.data.jpa.domain.AbstractPersistable;
@Entity
@Table(name = "m_code", uniqueConstraints = { @UniqueConstraint(columnNames = { "code_name" }, name = "code_name") })
public class Code extends AbstractPersistable<Long> {
@@ -27,4 +31,11 @@ public class Code extends AbstractPersistable<Long> {
this.codeName = codeName;
}
public void update(final CodeCommand command)
{
if (command.isNameChanged()) {
this.codeName = StringUtils.defaultIfEmpty(command.getCodeName(), null);
}
}
}
@@ -0,0 +1,42 @@
package org.mifosng.platform.organisation.service;
import java.util.ArrayList;
import java.util.List;
import org.mifosng.platform.DataValidatorBuilder;
import org.mifosng.platform.api.commands.CodeCommand;
import org.mifosng.platform.api.data.ApiParameterError;
import org.mifosng.platform.exceptions.PlatformApiDataValidationException;
public class CodeCommandValidator
{
private final CodeCommand command;
public CodeCommandValidator(CodeCommand command)
{
this.command = command;
}
public void validateForCreate()
{
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("code");
baseDataValidator.reset().parameter("codeName").value(command.getCodeName()).notBlank();
if (!dataValidationErrors.isEmpty()) {
throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors);
}
}
public void validateForUpdate()
{
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("code");
baseDataValidator.reset().parameter("id").value(command.getId()).notNull();
baseDataValidator.reset().parameter("codeName").value(command.getCodeName()).ignoreIfNull().notBlank();
if (!dataValidationErrors.isEmpty()) {
throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors);
}
}
}
@@ -1,13 +1,19 @@
package org.mifosng.platform.organisation.service;
import org.mifosng.platform.api.commands.CodeCommand;
import org.mifosng.platform.api.data.EntityIdentifier;
import org.springframework.security.access.prepost.PreAuthorize;
public interface CodeWritePlatformService {
@PreAuthorize(value = "hasRole('ALL_FUNCTIONS', 'ORGANISATION_ADMINISTRATION_SUPER_USER', 'CREATE_CODE')")
Long createCode(final CodeCommand command);
@PreAuthorize(value = "hasRole('ALL_FUNCTIONS', 'ORGANISATION_ADMINISTRATION_SUPER_USER', 'UPDATE_CODE)")
Long updateCode(final CodeCommand command);
@PreAuthorize(value = "hasRole('ORGANISATION_ADMINISTRATION_SUPER_USER_ROLE')")
EntityIdentifier deleteCode(Long codeId);
}
@@ -2,9 +2,17 @@ package org.mifosng.platform.organisation.service;
import org.mifosng.platform.api.commands.CodeCommand;
import org.mifosng.platform.api.commands.FundCommand;
import org.mifosng.platform.api.data.EntityIdentifier;
import org.mifosng.platform.exceptions.CodeValueNotFoundException;
import org.mifosng.platform.exceptions.FundNotFoundException;
import org.mifosng.platform.exceptions.PlatformDataIntegrityException;
import org.mifosng.platform.fund.domain.Fund;
import org.mifosng.platform.fund.service.FundWritePlatformServiceJpaRepositoryImpl;
import org.mifosng.platform.organisation.domain.Code;
import org.mifosng.platform.organisation.domain.CodeRepository;
import org.mifosng.platform.security.PlatformSecurityContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
@@ -13,6 +21,7 @@ import org.springframework.transaction.annotation.Transactional;
@Service
public class CodeWritePlatformServiceJpaRepositoryImpl implements CodeWritePlatformService {
private final static Logger logger = LoggerFactory.getLogger(CodeWritePlatformServiceJpaRepositoryImpl.class);
private final PlatformSecurityContext context;
private final CodeRepository codeRepository;
@@ -21,20 +30,22 @@ public class CodeWritePlatformServiceJpaRepositoryImpl implements CodeWritePlatf
this.context = context;
this.codeRepository = codeRepository;
}
@Transactional
@Override
public Long createCode(final CodeCommand command) {
try {
context.authenticatedUser();
CodeCommandValidator validator = new CodeCommandValidator(command);
validator.validateForCreate();
Code code = Code.createNew(command.getCodeName());
this.codeRepository.saveAndFlush(code);
return code.getId();
} catch (DataIntegrityViolationException dve) {
return Long.valueOf(-1);
@@ -45,18 +56,65 @@ public class CodeWritePlatformServiceJpaRepositoryImpl implements CodeWritePlatf
@Override
public Long updateCode(final CodeCommand command) {
/**
* TODO - NATU -
**/
return null;
try
{
context.authenticatedUser();
CodeCommandValidator validator = new CodeCommandValidator(command);
validator.validateForUpdate();
final Long codeId = command.getId();
Code code = this.codeRepository.findOne(codeId);
if (code == null) {
throw new CodeValueNotFoundException(codeId);
}
code.update(command);
this.codeRepository.saveAndFlush(code);
return code.getId();
}
catch (DataIntegrityViolationException dve) {
handleCodeDataIntegrityIssues(command, dve);
return Long.valueOf(-1);
}
}
/*
* Guaranteed to throw an exception no matter what the data integrity issue is.
*/
private void handleCodeDataIntegrityIssues(final FundCommand command, DataIntegrityViolationException dve) {
private void handleCodeDataIntegrityIssues(final CodeCommand command, DataIntegrityViolationException dve) {
Throwable realCause = dve.getMostSpecificCause();
if (realCause.getMessage().contains("code_name_org")) {
throw new PlatformDataIntegrityException("error.msg.code.duplicate.name", "A code with name '" + command.getCodeName() + "' already exists");
}
logger.error(dve.getMessage(), dve);
throw new PlatformDataIntegrityException("error.msg.cund.unknown.data.integrity.issue", "Unknown data integrity issue with resource: " + realCause.getMessage());
}
@Transactional
@Override
public EntityIdentifier deleteCode(final Long codeId) {
context.authenticatedUser();
final Code code = retrieveCodeBy(codeId);
this.codeRepository.delete(codeId);
return new EntityIdentifier(codeId);
}
private Code retrieveCodeBy(final Long codeId) {
final Code code = this.codeRepository.findOne(codeId);
if (code == null) {
throw new CodeValueNotFoundException(codeId);
}
return code;
}
}