Fix Bug 473505 - Container attribute maxNrOfInstances not working as
expected

Change-Id: I16cc7c2e5839d03bdf5900964385e7e42b0cf76c
diff --git a/org.eclipse.om2m.core/src/main/java/org/eclipse/om2m/core/controller/ContentInstanceController.java b/org.eclipse.om2m.core/src/main/java/org/eclipse/om2m/core/controller/ContentInstanceController.java
index dfa31a6..3e55bf8 100644
--- a/org.eclipse.om2m.core/src/main/java/org/eclipse/om2m/core/controller/ContentInstanceController.java
+++ b/org.eclipse.om2m.core/src/main/java/org/eclipse/om2m/core/controller/ContentInstanceController.java
@@ -169,16 +169,21 @@
 		contentInstances.setCurrentByteSize(contentInstances.getCurrentByteSize() + contentInstance.getContentSize());

 		DAOFactory.getContentInstancesDAO().update(contentInstances, em);

 		// delete the oldest contentInstance if the CurrentNrOfInstances reaches MaxNrOfInstances

-		if (contentInstances.getCurrentNrOfInstances() > container.getMaxNrOfInstances()-1) {

-			final String oldestCI = requestIndication.getTargetID()+"/oldest";

+		if (contentInstances.getCurrentNrOfInstances() > container.getMaxNrOfInstances()) {

+			final String targetID = requestIndication.getTargetID();

+			

 			new Thread(){

 				public void run(){

 					Router.readWriteLock.readLock().lock();

 					EntityManager em = DBAccess.createEntityManager();

 					em.getTransaction().begin();

-					ContentInstance contentInstanceOldest = DAOFactory.getContentInstanceDAO().find(oldestCI, em);

+					ContentInstance contentInstanceOldest = DAOFactory.getContentInstanceDAO().find(targetID+"/oldest", em);

 					//Delete the oldest contentInstance

 					DAOFactory.getContentInstanceDAO().delete(contentInstanceOldest,em);

+					ContentInstances contentInstances = DAOFactory.getContentInstancesDAO().find(targetID, em);

+					contentInstances.setCurrentNrOfInstances(contentInstances.getCurrentNrOfInstances() - 1);

+					contentInstances.setCurrentByteSize(contentInstances.getCurrentByteSize() - contentInstanceOldest.getContentSize());

+					DAOFactory.getContentInstancesDAO().update(contentInstances, em);

 					em.getTransaction().commit();

 					em.close();

 					Router.readWriteLock.readLock().unlock();