+ }else{
+ // Resource name is null -> No resource with same name.
+ selfEntity = new BackUpMonitorEntity();
+ selfEntity.setResoruceNodeName(resourceNodeName);
+ selfEntity.setResourceName(resourceName);
+ selfEntity.setTimeStamp(new Date());
+ selfEntity = setSlave(selfEntity);
+ setLastNotification(null);
+ LOGGER.info("Creating: " + resourceName + " on Slave Mode");
+ em.persist(selfEntity);
+ em.flush();
+ }
+ // Correct the database if any errors and perform monitor checks.
+ if(masterEntities.size()!=1 || !getFlag()){
+ // We are either not master or there are more masters or no masters.
+ if(masterEntities.size()==0){
+ // No Masters is a problem Convert ourselves to Master.
+ selfEntity = setMaster(selfEntity);
+ selfEntity.setTimeStamp(new Date());
+ selfEntity.setNotificationRecord(notificationRecord);
+ LOGGER.info(resourceName + " changed to Master Mode - No Masters available.");
+ em.persist(selfEntity);
+ em.flush();
+ }else {
+ if(masterEntities.size()>1){
+ // More Masters is a problem, Fix the issue by looking for the latest one and make others Slave.
+ BackUpMonitorEntity masterEntity = null;
+ for(BackUpMonitorEntity currentEntity: masterEntities){
+ if(currentEntity.getFlag().equalsIgnoreCase("MASTER")){
+ if(masterEntity==null){
+ masterEntity = currentEntity;
+ }else if(currentEntity.getTimeStamp().getTime() > masterEntity.getTimeStamp().getTime()){
+ // False Master, Update master to slave and take currentMaster as Master.
+ masterEntity.setFlag("SLAVE");
+ masterEntity.setTimeStamp(new Date());
+ em.persist(masterEntity);
+ em.flush();
+ masterEntity = currentEntity;
+ }else{
+ currentEntity.setFlag("SLAVE");
+ currentEntity.setTimeStamp(new Date());
+ em.persist(currentEntity);
+ em.flush();
+ }
+ }
+ }
+ masterEntities = new ArrayList<>();
+ masterEntities.add(masterEntity);
+ }
+ if(masterEntities.size()==1){
+ // Correct Size, Check if Master is Latest, if not Change Master to Slave and Slave to Master.
+ BackUpMonitorEntity masterEntity = masterEntities.get(0);
+ if(!masterEntity.getResourceName().equals(selfEntity.getResourceName())){
+ Date currentTime = new Date();
+ long timeDiff = 0;
+ timeDiff = currentTime.getTime()-masterEntity.getTimeStamp().getTime();
+ if(timeDiff > (pingInterval+1500)){
+ // This is down or has an issue and we need to become Master while turning the Master to slave.
+ masterEntity.setFlag("SLAVE");
+ String lastNotification = null;
+ if(masterEntity.getNotificationRecord()!=null){
+ lastNotification = calculatePatch(masterEntity.getNotificationRecord());
+ }
+ setLastNotification(lastNotification);
+ em.persist(masterEntity);
+ em.flush();
+ // Lets Become Master.
+ selfEntity = setMaster(selfEntity);
+ LOGGER.info("Changing "+ resourceName + " from slave to Master Mode");
+ selfEntity.setTimeStamp(new Date());
+ selfEntity.setNotificationRecord(notificationRecord);
+ em.persist(selfEntity);
+ em.flush();
+ }