How to set automatically assigned values and enforce that they do not change?

Petter Reinholdtsen pere at hungry.com
Tue Jun 13 21:34:33 CEST 2017


Hi.

After I added some non-null constraint to the data model, several new
attributes must be included when objects are created. But I discovered
that some of them should be set automatically.  An example is
dokumentbeskrivelse.tilknyttetDato.  I had a look at fixing this, by
making sure the value is set to 'now' when the object is created, and
that any PUT that change it is rejected.  So my question is simply - is
this the correct approach to set the value automatically and ensure it
never is modified by a API client?

diff --git a/core-webapp/src/main/java/no/arkivlab/hioa/nikita/webapp/service/impl/DocumentDescriptionService.java b/core-webapp/src/main/java/no/arkivlab/hioa/nikita/webapp/service/impl/DocumentDescriptionService.java
index ac7abb1..ee40dca 100644
--- a/core-webapp/src/main/java/no/arkivlab/hioa/nikita/webapp/service/impl/DocumentDescriptionService.java
+++ b/core-webapp/src/main/java/no/arkivlab/hioa/nikita/webapp/service/impl/DocumentDescriptionService.java
@@ -69,11 +69,13 @@ public class DocumentDescriptionService implements IDocumentDescriptionService {
 
     public DocumentDescription save(DocumentDescription documentDescription){
         String username = SecurityContextHolder.getContext().getAuthentication().getName();
+        Date now = new Date();
         documentDescription.setSystemId(UUID.randomUUID().toString());
-        documentDescription.setCreatedDate(new Date());
+        documentDescription.setCreatedDate(now);
         documentDescription.setOwnedBy(username);
         documentDescription.setCreatedBy(username);
         documentDescription.setDeleted(false);
+        documentDescription.setAssociationDate(now);
         return documentDescriptionRepository.save(documentDescription);
     }
 
@@ -378,6 +380,12 @@ public class DocumentDescriptionService implements IDocumentDescriptionService {
             existingDocumentDescription.setDocumentNumber(incomingDocumentDescription.getDocumentNumber());
         }
 
+	// Reject changes to values we are not allowed to modify
+	if (existingDocumentDescription.getAssociationdate() != incomingDocumentDescription.getAssociationdate())
+	    String msg = "Modifying " + DOCUMENT_DESCRIPTION_ASSOCIATION_DATE + " is not permitted."
+            throw new NikitaMalformedInputDataException(msg);
+	}
+
         existingDocumentDescription.setVersion(version);
         documentDescriptionRepository.save(existingDocumentDescription);
         return existingDocumentDescription;

-- 
Happy hacking
Petter Reinholdtsen


More information about the nikita-noark mailing list