Program: 45345
Project: 45345
Buggy source:
private void listenForIncomingMessages(){
  (new Thread(){
    @Override public void run(){
      while (true) {
        try {
          Thread.sleep(10);
          Message msg=mp.receive();
          if (msg != null) {
            if (!(msg instanceof MulticastMessage)) {
switch (msg.getNormalMsgType()) {
case TASK_ADV:
                Task receivedTask=(Task)msg.getData();
synchronized (nodes) {
                logMessage("String_Node_Str" + msg.getSource());
                Node host_node=nodes.get(host);
                if (receivedTask.getTaskProcessorLoad() > (Preferences.TOTAL_PROCESSOR_LOAD_AT_NODE - host_node.getProcessorLoad() - Preferences.RESERVED_PROCESSOR_AT_NODE)) {
                  logMessage("String_Node_Str" + receivedTask.taskId + "String_Node_Str"+ receivedTask.getTaskProcessorLoad()+ "String_Node_Str"+ (Preferences.TOTAL_PROCESSOR_LOAD_AT_NODE - host_node.getProcessorLoad() - Preferences.RESERVED_PROCESSOR_AT_NODE));
                  break;
                }
                if (receivedTask.getTaskMemoryLoad() > (Preferences.TOTAL_MEMORY_LOAD_AT_NODE - host_node.getMemoryLoad() - Preferences.RESERVED_MEMORY_AT_NODE)) {
                  logMessage("String_Node_Str" + receivedTask.taskId + "String_Node_Str"+ receivedTask.getTaskMemoryLoad()+ "String_Node_Str"+ (Preferences.TOTAL_MEMORY_LOAD_AT_NODE - host_node.getMemoryLoad() - Preferences.RESERVED_MEMORY_AT_NODE));
                  break;
                }
                int remaining_battrey_load=host_node.getBatteryLevel() - (receivedTask.getTaskBattreyLoad() + Preferences.BATTERY_SPENT_IN_TASK_CHUNK_EXECUTION + host_node.getPromisedBattreyLoad());
                int battreyLoadCanServe=0;
                if (remaining_battrey_load > Preferences.RESERVED_BATTERY_AT_NODE) {
                  battreyLoadCanServe=receivedTask.getTaskBattreyLoad();
                }
 else {
                  battreyLoadCanServe=host_node.getBatteryLevel() - (Preferences.RESERVED_BATTERY_AT_NODE + Preferences.BATTERY_SPENT_IN_TASK_CHUNK_EXECUTION + host_node.getPromisedBattreyLoad());
                }
                if (remaining_battrey_load > Preferences.MAX_TASK_CHUNK_LOAD_SIZE) {
                  remaining_battrey_load=Preferences.MAX_TASK_CHUNK_LOAD_SIZE;
                }
                if (battreyLoadCanServe > Preferences.MINIMUM_LOAD_REQUEST) {
                  Integer tempTaskAdvReplyId=++taskAdvReplyId;
                  String tempTaskAdvReplyIdStr=host_node.getName() + tempTaskAdvReplyId;
                  receivedTask.setPromisedTaskBattreyLoad(battreyLoadCanServe + Preferences.BATTERY_SPENT_IN_TASK_CHUNK_EXECUTION);
                  receivedTask.setPromisedTimeStamp(new Date().getTime());
                  host_node.addToAcceptedTask(tempTaskAdvReplyIdStr,receivedTask);
                  host_node.incrPromisedBattreyLoad(receivedTask.getPromisedBattreyTaskLoad());
                  host_node.incrProcessorLoad(receivedTask.getTaskProcessorLoad());
                  host_node.incrMemoryLoad(receivedTask.getTaskMemoryLoad());
                  TaskAdvReply taskAdvReply=new TaskAdvReply(tempTaskAdvReplyIdStr,receivedTask.getTaskId(),host_node,battreyLoadCanServe);
                  Message profileMsg=new Message(msg.getSource(),"String_Node_Str","String_Node_Str",taskAdvReply,host);
                  profileMsg.setNormalMsgType(Message.NormalMsgType.PROFILE_XCHG);
                  try {
                    if (Preferences.DEBUG_MODE) {
                      System.out.println("String_Node_Str" + host + "String_Node_Str"+ nodes.get(host).getAdrress()+ "String_Node_Str"+ nodes.get(host).getNodePort());
                    }
                    mp.send(profileMsg);
                  }
 catch (                  InvalidMessageException ex) {
                    host_node.removeFromAcceptedTask(tempTaskAdvReplyIdStr);
                    host_node.decrProcessorLoad(receivedTask.getTaskProcessorLoad());
                    host_node.decrMemoryLoad(receivedTask.getTaskMemoryLoad());
                    host_node.decrPromisedBattreyLoad(receivedTask.getPromisedBattreyTaskLoad());
                    ex.printStackTrace();
                  }
catch (                  UnknownHostException e) {
                    e.printStackTrace();
                  }
                  logMessage("String_Node_Str" + receivedTask.taskId + "String_Node_Str"+ remaining_battrey_load);
                }
 else {
                  logMessage("String_Node_Str" + receivedTask.taskId + "String_Node_Str"+ battreyLoadCanServe);
                }
              }
            break;
case NORMAL:
          logMessage(msg.getData().toString());
        break;
case PROFILE_XCHG:
      TaskAdvReply taskAdvReply=(TaskAdvReply)msg.getData();
    if (Preferences.DEBUG_MODE) {
      System.out.println("String_Node_Str" + taskAdvReply.getNode().getName() + "String_Node_Str"+ taskAdvReply.getNode().getAdrress()+ "String_Node_Str"+ taskAdvReply.getNode().getNodePort());
    }
  TaskLookup taskLookup=taskLookups.get(taskAdvReply.getTaskId());
taskLookup.setRetry(0);
distributeTask(taskAdvReply);
break;
case DISTRIBUTED_TASK:
TaskChunk taskChunk=(TaskChunk)msg.getData();
DistributedTask distTask=taskChunk.getDsTask();
Node host_node=nodes.get(host);
if (host_node.getAcceptedTaskByTaskId(taskChunk.getTaskAdvReplyId()) == null) {
break;
}
host_node.getAcceptedTaskByTaskId(taskChunk.getTaskAdvReplyId()).setInExecution(true);
TaskResult result;
Map<Integer,TaskResult> tempResults=taskResults.get(distTask.getTaskId());
result=new TaskResult(distTask.getTaskProcessorLoad(),distTask.getTaskMemoryLoad(),distTask.getTaskBattreyLoad(),distTask.taskId,host,handleDistributedTask(distTask),taskChunk.getSequenceNumber());
if (tempResults == null) {
tempResults=new HashMap<Integer,TaskResult>();
}
tempResults.put(taskChunk.getSequenceNumber(),result);
taskResults.put(distTask.getTaskId(),tempResults);
int loadServed=host_node.getAcceptedTaskByTaskId(taskChunk.getTaskAdvReplyId()).getPromisedBattreyTaskLoad();
if (host_node.getAcceptedTaskByTaskId(taskChunk.getTaskAdvReplyId()) != null) {
host_node.decrPromisedBattreyLoad(loadServed);
}
host_node.removeFromAcceptedTask(taskChunk.getTaskAdvReplyId());
nodes.get(host).decrBatteryLevel(loadServed);
host_node.decrProcessorLoad(distTask.getTaskProcessorLoad());
host_node.decrMemoryLoad(distTask.getTaskMemoryLoad());
logMessage(result.getTaskResult().toString());
Message resultMsg=new Message(distTask.getSource(),"String_Node_Str","String_Node_Str",result,host_node.getName());
resultMsg.setNormalMsgType(Message.NormalMsgType.TASK_RESULT);
try {
mp.send(resultMsg);
}
 catch (InvalidMessageException ex) {
Logger.getLogger(TaskDistributor.class.getName()).log(Level.SEVERE,null,ex);
}
break;
case TASK_RESULT:
TaskResult taskResult=(TaskResult)msg.getData();
Integer seqNumber=taskResult.getSeqNumber();
taskLookup=taskLookups.get(taskResult.getTaskId());
synchronized (taskLookup) {
taskLookup.getTaskGroup().get(taskLookup.getResultTracker().get(taskResult.getSeqNumber())).setStatus(Preferences.TASK_CHUNK_STATUS.RECEIVED);
taskLookup.removeFromResultTracker(seqNumber);
addAndMergeResults(taskResult);
}
logMessage("String_Node_Str" + seqNumber + "String_Node_Str"+ taskLookup.printResultTracker()+ "String_Node_Str"+ taskResult.getSource()+ "String_Node_Str"+ taskResult.getTaskResult());
break;
}
}
}
}
 catch (InterruptedException ex) {
ex.printStackTrace();
}
catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
private Serializable handleDistributedTask(DistributedTask gotTask){
try {
Class cl=Class.forName(gotTask.getClassName());
HashMap<String,Class[]> mthdDef=new HashMap<String,Class[]>();
Method mthds[]=cl.getDeclaredMethods();
for (Method m : mthds) {
mthdDef.put(m.getName(),m.getParameterTypes());
}
if (gotTask.getParameters() != null && ((mthdDef.get(gotTask.getMethodName())).length != gotTask.getParameters().length)) {
logMessage("String_Node_Str");
}
 else {
Class params[]=mthdDef.get(gotTask.getMethodName());
Object parameters[]=(Object[])gotTask.getParameters();
try {
Method invokedMethod=cl.getMethod(gotTask.getMethodName(),params);
return (Serializable)invokedMethod.invoke(new SampleApplicationLocal(),parameters);
}
 catch (IllegalAccessException ex) {
ex.printStackTrace();
}
catch (InvocationTargetException ex) {
ex.printStackTrace();
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (SecurityException e) {
e.printStackTrace();
}
catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
 catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
private void distributeTask(TaskAdvReply taskAdvReply){
String taskId=taskAdvReply.getTaskId();
Node node=taskAdvReply.getNode();
TaskLookup taskLookup=taskLookups.get(taskId);
Task taskToDistribute=(taskLookups.get(taskId)).getTask();
if (taskToDistribute.getTaskBattreyLoad() <= 0) {
return;
}
if (taskLookup.getStatus() == Preferences.TASK_STATUS.DISTRIBUTED) {
return;
}
if (!isNodeSuitableForDistribution(node,taskLookup)) {
return;
}
int loadDistributed=(int)Math.ceil((taskToDistribute.getTaskBattreyLoad() > taskAdvReply.getLoadCanServe()) ? (taskAdvReply.getLoadCanServe()) : taskToDistribute.getTaskBattreyLoad());
taskToDistribute.setTaskBattreyLoad(taskToDistribute.getTaskBattreyLoad() - loadDistributed);
if (taskToDistribute.getTaskBattreyLoad() <= 0) {
taskLookup.setStatus(Preferences.TASK_STATUS.DISTRIBUTED);
}
Serializable[] parameters=new Serializable[2];
parameters[0]=10;
parameters[1]=20;
DistributedTask dsTask=new DistributedTask(taskToDistribute.getTaskProcessorLoad(),taskToDistribute.getTaskMemoryLoad(),loadDistributed,taskId,taskToDistribute.getSource(),"String_Node_Str","String_Node_Str",parameters);
TaskChunk taskChunk=new TaskChunk(taskId,node,taskLookup.nextSequenceNumber(),dsTask,taskAdvReply.getTaskAdvReplyId());
taskLookup.addToTaskGroup(taskChunk.getTaskAdvReplyId(),taskChunk);
Message distMsg=new Message(node.getName(),"String_Node_Str","String_Node_Str",taskChunk,host);
distMsg.setNormalMsgType(Message.NormalMsgType.DISTRIBUTED_TASK);
if (Preferences.DEBUG_MODE) {
try {
System.out.println("String_Node_Str" + node.getName() + "String_Node_Str"+ node.getAdrress()+ "String_Node_Str"+ node.getNodePort());
}
 catch (UnknownHostException e) {
e.printStackTrace();
}
}
sendAndRetryTaskChunk(taskChunk,distMsg,dsTask,loadDistributed,taskLookup);
}
private boolean isNodeSuitableForDistribution(Node node,TaskLookup taskLookup){
return isNodeSuitableForEfficientDistributionCheck(node,taskLookup);
}
private boolean isNodeSuitableForNaiveDistributionCheck(Node node,TaskLookup taskLookup){
return true;
}
private boolean isNodeSuitableForEfficientDistributionCheck(Node node,TaskLookup taskLookup){
boolean isSuitable=true;
float alpha=Preferences.ALPHA_MIN;
float beta=Preferences.BETA;
float gama=Preferences.GAMA;
float weight=beta;
BattreyInfo oldBattreyInfo=null;
float lastAvgNodeLoad;
Queue<BattreyInfo> nodeBattreyLoadInfo=battreyLoadInfo.get(node.getName());
if (nodeBattreyLoadInfo == null) {
nodeBattreyLoadInfo=new LinkedList<BattreyInfo>();
battreyLoadInfo.put(node.getName(),nodeBattreyLoadInfo);
}
if (nodeBattreyLoadInfo.size() >= Preferences.NODE_BATTERY_INFO_QUEUE_SIZE) {
oldBattreyInfo=nodeBattreyLoadInfo.remove();
}
advReplyTotalCount++;
if (advReplyCount > 1) {
double stdDevNodeLoad=Math.sqrt(varianceNodeLoad / advReplyCount);
if (oldBattreyInfo != null) {
advReplyCount--;
lastAvgNodeLoad=avgNodeLoad;
avgNodeLoad=avgNodeLoad - (oldBattreyInfo.getWeight() * ((oldBattreyInfo.getBattreyLoad() - avgNodeLoad) / advReplyCount));
varianceNodeLoad=varianceNodeLoad - (oldBattreyInfo.getWeight() * ((oldBattreyInfo.getBattreyLoad() - lastAvgNodeLoad) * (oldBattreyInfo.getBattreyLoad() - avgNodeLoad)));
}
if (advReplyTotalCount < Preferences.NUMBER_PACKETS_NETWORK_STABLIZE) {
alpha=Preferences.ALPHA_MIN + (((Preferences.NUMBER_PACKETS_NETWORK_STABLIZE - advReplyTotalCount) / (Preferences.NUMBER_PACKETS_NETWORK_STABLIZE * 1.0f)) * (Preferences.ALPHA_MAX - Preferences.ALPHA_MIN));
}
if (Math.abs(node.getBatteryLevel() - avgNodeLoad) > alpha * stdDevNodeLoad) {
isSuitable=false;
}
}
advReplyCount++;
lastAvgNodeLoad=avgNodeLoad;
if (!isSuitable) {
weight=gama;
}
nodeBattreyLoadInfo.add(new BattreyInfo(node.getBatteryLevel(),weight));
avgNodeLoad=avgNodeLoad + weight * ((node.getBatteryLevel() - avgNodeLoad) / advReplyCount);
if (advReplyCount == 1) {
varianceNodeLoad=0;
}
 else {
varianceNodeLoad=varianceNodeLoad + weight * ((node.getBatteryLevel() - lastAvgNodeLoad) * (node.getBatteryLevel() - avgNodeLoad));
}
return isSuitable;
}
private void addAndMergeResults(TaskResult taskResult){
TaskLookup taskLookup=taskLookups.get(taskResult.getTaskId());
taskLookup.getTaskResults().put(taskResult.getSeqNumber(),taskResult);
if (taskLookup.getTask().getTaskBattreyLoad() <= 0 && taskLookup.getTaskGroup().size() == taskLookup.getTaskResults().size()) {
taskLookup.setStatus(Preferences.TASK_STATUS.RECEIVED_RESULTS);
}
if (taskLookup.getStatus() == Preferences.TASK_STATUS.RECEIVED_RESULTS) {
String result="String_Node_Str";
for (int i=0; i < taskLookup.getTaskResults().size(); i++) {
result+=(taskLookup.getTaskResults().get(i)).toString() + "String_Node_Str";
}
logMessage("String_Node_Str" + result);
nodes.get(host).decrBatteryLevel(Preferences.BATTERY_SPENT_IN_TASK_DISTRIBUTION);
}
}
}
).start();
}

Fixed version (ground truth):
private void listenForIncomingMessages(){
  (new Thread(){
    @Override public void run(){
      while (true) {
        try {
          Thread.sleep(10);
          Message msg=mp.receive();
          if (msg != null) {
            if (!(msg instanceof MulticastMessage)) {
switch (msg.getNormalMsgType()) {
case TASK_ADV:
                Task receivedTask=(Task)msg.getData();
synchronized (nodes) {
                logMessage("String_Node_Str" + msg.getSource() + "String_Node_Str"+ receivedTask.getTaskBattreyLoad());
                Node host_node=nodes.get(host);
                if (receivedTask.getTaskBattreyLoad() <= 0) {
                  System.out.println("String_Node_Str" + host_node.getName() + "String_Node_Str"+ receivedTask.getTaskBattreyLoad());
                  break;
                }
                if (receivedTask.getTaskProcessorLoad() > (Preferences.TOTAL_PROCESSOR_LOAD_AT_NODE - host_node.getProcessorLoad() - Preferences.RESERVED_PROCESSOR_AT_NODE)) {
                  logMessage("String_Node_Str" + receivedTask.taskId + "String_Node_Str"+ receivedTask.getTaskProcessorLoad()+ "String_Node_Str"+ (Preferences.TOTAL_PROCESSOR_LOAD_AT_NODE - host_node.getProcessorLoad() - Preferences.RESERVED_PROCESSOR_AT_NODE));
                  break;
                }
                if (receivedTask.getTaskMemoryLoad() > (Preferences.TOTAL_MEMORY_LOAD_AT_NODE - host_node.getMemoryLoad() - Preferences.RESERVED_MEMORY_AT_NODE)) {
                  logMessage("String_Node_Str" + receivedTask.taskId + "String_Node_Str"+ receivedTask.getTaskMemoryLoad()+ "String_Node_Str"+ (Preferences.TOTAL_MEMORY_LOAD_AT_NODE - host_node.getMemoryLoad() - Preferences.RESERVED_MEMORY_AT_NODE));
                  break;
                }
                int remaining_battrey_load=host_node.getBatteryLevel() - (receivedTask.getTaskBattreyLoad() + Preferences.BATTERY_SPENT_IN_TASK_CHUNK_EXECUTION + host_node.getPromisedBattreyLoad());
                int battreyLoadCanServe=0;
                if (remaining_battrey_load > Preferences.RESERVED_BATTERY_AT_NODE) {
                  battreyLoadCanServe=receivedTask.getTaskBattreyLoad();
                }
 else {
                  battreyLoadCanServe=host_node.getBatteryLevel() - (Preferences.RESERVED_BATTERY_AT_NODE + Preferences.BATTERY_SPENT_IN_TASK_CHUNK_EXECUTION + host_node.getPromisedBattreyLoad());
                }
                if (battreyLoadCanServe > Preferences.MAX_TASK_CHUNK_LOAD_SIZE) {
                  battreyLoadCanServe=Preferences.MAX_TASK_CHUNK_LOAD_SIZE;
                }
                if (battreyLoadCanServe > Preferences.MINIMUM_LOAD_REQUEST) {
                  Integer tempTaskAdvReplyId=++taskAdvReplyId;
                  String tempTaskAdvReplyIdStr=host_node.getName() + tempTaskAdvReplyId;
                  receivedTask.setPromisedTaskBattreyLoad(battreyLoadCanServe + Preferences.BATTERY_SPENT_IN_TASK_CHUNK_EXECUTION);
                  receivedTask.setPromisedTimeStamp(new Date().getTime());
                  host_node.addToAcceptedTask(tempTaskAdvReplyIdStr,receivedTask);
                  host_node.incrPromisedBattreyLoad(receivedTask.getPromisedBattreyTaskLoad());
                  host_node.incrProcessorLoad(receivedTask.getTaskProcessorLoad());
                  host_node.incrMemoryLoad(receivedTask.getTaskMemoryLoad());
                  TaskAdvReply taskAdvReply=new TaskAdvReply(tempTaskAdvReplyIdStr,receivedTask.getTaskId(),host_node,battreyLoadCanServe);
                  Message profileMsg=new Message(msg.getSource(),"String_Node_Str","String_Node_Str",taskAdvReply,host);
                  profileMsg.setNormalMsgType(Message.NormalMsgType.PROFILE_XCHG);
                  try {
                    if (Preferences.DEBUG_MODE) {
                      System.out.println("String_Node_Str" + host + "String_Node_Str"+ nodes.get(host).getAdrress()+ "String_Node_Str"+ nodes.get(host).getNodePort());
                    }
                    mp.send(profileMsg);
                  }
 catch (                  InvalidMessageException ex) {
                    host_node.removeFromAcceptedTask(tempTaskAdvReplyIdStr);
                    host_node.decrProcessorLoad(receivedTask.getTaskProcessorLoad());
                    host_node.decrMemoryLoad(receivedTask.getTaskMemoryLoad());
                    host_node.decrPromisedBattreyLoad(receivedTask.getPromisedBattreyTaskLoad());
                    ex.printStackTrace();
                  }
catch (                  UnknownHostException e) {
                    e.printStackTrace();
                  }
                  logMessage("String_Node_Str" + receivedTask.taskId + "String_Node_Str"+ remaining_battrey_load);
                }
 else {
                  System.out.println("String_Node_Str" + host_node.getName() + "String_Node_Str"+ battreyLoadCanServe+ "String_Node_Str"+ remaining_battrey_load+ "String_Node_Str"+ receivedTask.getTaskBattreyLoad()+ "String_Node_Str"+ host_node.getPromisedBattreyLoad());
                  logMessage("String_Node_Str" + receivedTask.taskId + "String_Node_Str"+ battreyLoadCanServe);
                }
              }
            break;
case NORMAL:
          logMessage(msg.getData().toString());
        break;
case PROFILE_XCHG:
      TaskAdvReply taskAdvReply=(TaskAdvReply)msg.getData();
    if (Preferences.DEBUG_MODE) {
      System.out.println("String_Node_Str" + taskAdvReply.getNode().getName() + "String_Node_Str"+ taskAdvReply.getNode().getAdrress()+ "String_Node_Str"+ taskAdvReply.getNode().getNodePort());
    }
  TaskLookup taskLookup=taskLookups.get(taskAdvReply.getTaskId());
taskLookup.setRetry(0);
distributeTask(taskAdvReply);
break;
case DISTRIBUTED_TASK:
TaskChunk taskChunk=(TaskChunk)msg.getData();
DistributedTask distTask=taskChunk.getDsTask();
Node host_node=nodes.get(host);
TaskResult result;
Map<Integer,TaskResult> tempResults=taskResults.get(distTask.getTaskId());
if (tempResults != null && tempResults.get(distTask.getSeqNumber()) != null) {
result=taskResults.get(distTask.getTaskId()).get(taskChunk.getSequenceNumber());
}
 else {
if (host_node.getAcceptedTaskByTaskId(taskChunk.getTaskAdvReplyId()) == null) {
break;
}
host_node.getAcceptedTaskByTaskId(taskChunk.getTaskAdvReplyId()).setInExecution(true);
result=new TaskResult(distTask.getTaskProcessorLoad(),distTask.getTaskMemoryLoad(),distTask.getTaskBattreyLoad(),distTask.taskId,host,handleDistributedTask(distTask),taskChunk.getSequenceNumber());
if (tempResults == null) {
tempResults=new HashMap<Integer,TaskResult>();
}
tempResults.put(taskChunk.getSequenceNumber(),result);
taskResults.put(distTask.getTaskId(),tempResults);
int loadServed=host_node.getAcceptedTaskByTaskId(taskChunk.getTaskAdvReplyId()).getPromisedBattreyTaskLoad();
if (host_node.getAcceptedTaskByTaskId(taskChunk.getTaskAdvReplyId()) != null) {
host_node.decrPromisedBattreyLoad(loadServed);
}
host_node.removeFromAcceptedTask(taskChunk.getTaskAdvReplyId());
nodes.get(host).decrBatteryLevel(loadServed);
host_node.decrProcessorLoad(distTask.getTaskProcessorLoad());
host_node.decrMemoryLoad(distTask.getTaskMemoryLoad());
}
logMessage(result.getTaskResult().toString());
Message resultMsg=new Message(distTask.getSource(),"String_Node_Str","String_Node_Str",result,host_node.getName());
resultMsg.setNormalMsgType(Message.NormalMsgType.TASK_RESULT);
try {
mp.send(resultMsg);
}
 catch (InvalidMessageException ex) {
Logger.getLogger(TaskDistributor.class.getName()).log(Level.SEVERE,null,ex);
}
break;
case TASK_RESULT:
TaskResult taskResult=(TaskResult)msg.getData();
Integer seqNumber=taskResult.getSeqNumber();
taskLookup=taskLookups.get(taskResult.getTaskId());
synchronized (taskLookup) {
taskLookup.getTaskGroup().get(taskLookup.getResultTracker().get(taskResult.getSeqNumber())).setStatus(Preferences.TASK_CHUNK_STATUS.RECEIVED);
taskLookup.removeFromResultTracker(seqNumber);
addAndMergeResults(taskResult);
}
logMessage("String_Node_Str" + seqNumber + "String_Node_Str"+ taskLookup.printResultTracker()+ "String_Node_Str"+ taskResult.getSource()+ "String_Node_Str"+ taskResult.getTaskResult());
break;
}
}
}
}
 catch (InterruptedException ex) {
ex.printStackTrace();
}
catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
private Serializable handleDistributedTask(DistributedTask gotTask){
try {
Class cl=Class.forName(gotTask.getClassName());
HashMap<String,Class[]> mthdDef=new HashMap<String,Class[]>();
Method mthds[]=cl.getDeclaredMethods();
for (Method m : mthds) {
mthdDef.put(m.getName(),m.getParameterTypes());
}
if (gotTask.getParameters() != null && ((mthdDef.get(gotTask.getMethodName())).length != gotTask.getParameters().length)) {
logMessage("String_Node_Str");
}
 else {
Class params[]=mthdDef.get(gotTask.getMethodName());
Object parameters[]=(Object[])gotTask.getParameters();
try {
Method invokedMethod=cl.getMethod(gotTask.getMethodName(),params);
return (Serializable)invokedMethod.invoke(new SampleApplicationLocal(),parameters);
}
 catch (IllegalAccessException ex) {
ex.printStackTrace();
}
catch (InvocationTargetException ex) {
ex.printStackTrace();
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (SecurityException e) {
e.printStackTrace();
}
catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
 catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
private synchronized void distributeTask(TaskAdvReply taskAdvReply){
String taskId=taskAdvReply.getTaskId();
Node node=taskAdvReply.getNode();
TaskLookup taskLookup=taskLookups.get(taskId);
Task taskToDistribute=(taskLookups.get(taskId)).getTask();
int loadDistributed;
if (taskToDistribute.getTaskBattreyLoad() <= 0) {
return;
}
if (taskLookup.getStatus() == Preferences.TASK_STATUS.DISTRIBUTED) {
return;
}
if (!isNodeSuitableForDistribution(node,taskLookup)) {
return;
}
loadDistributed=(int)Math.ceil((taskToDistribute.getTaskBattreyLoad() > taskAdvReply.getLoadCanServe()) ? (taskAdvReply.getLoadCanServe()) : taskToDistribute.getTaskBattreyLoad());
taskToDistribute.setTaskBattreyLoad(taskToDistribute.getTaskBattreyLoad() - loadDistributed);
if (taskToDistribute.getTaskBattreyLoad() <= 0) {
taskLookup.setStatus(Preferences.TASK_STATUS.DISTRIBUTED);
}
Serializable[] parameters=new Serializable[2];
parameters[0]=10;
parameters[1]=20;
DistributedTask dsTask=new DistributedTask(taskToDistribute.getTaskProcessorLoad(),taskToDistribute.getTaskMemoryLoad(),loadDistributed,taskId,taskToDistribute.getSource(),"String_Node_Str","String_Node_Str",parameters);
TaskChunk taskChunk=new TaskChunk(taskId,node,taskLookup.nextSequenceNumber(),dsTask,taskAdvReply.getTaskAdvReplyId());
taskLookup.addToTaskGroup(taskChunk.getTaskAdvReplyId(),taskChunk);
Message distMsg=new Message(node.getName(),"String_Node_Str","String_Node_Str",taskChunk,host);
distMsg.setNormalMsgType(Message.NormalMsgType.DISTRIBUTED_TASK);
if (Preferences.DEBUG_MODE) {
try {
System.out.println("String_Node_Str" + node.getName() + "String_Node_Str"+ node.getAdrress()+ "String_Node_Str"+ node.getNodePort());
}
 catch (UnknownHostException e) {
e.printStackTrace();
}
}
sendAndRetryTaskChunk(taskChunk,distMsg,dsTask,loadDistributed,taskLookup);
}
private boolean isNodeSuitableForDistribution(Node node,TaskLookup taskLookup){
return isNodeSuitableForEfficientDistributionCheck(node,taskLookup);
}
private boolean isNodeSuitableForNaiveDistributionCheck(Node node,TaskLookup taskLookup){
return true;
}
private boolean isNodeSuitableForEfficientDistributionCheck(Node node,TaskLookup taskLookup){
boolean isSuitable=true;
float alpha=Preferences.ALPHA_MIN;
float beta=Preferences.BETA;
float gama=Preferences.GAMA;
float weight=beta;
BattreyInfo oldBattreyInfo=null;
float lastAvgNodeLoad;
Queue<BattreyInfo> nodeBattreyLoadInfo=battreyLoadInfo.get(node.getName());
if (nodeBattreyLoadInfo == null) {
nodeBattreyLoadInfo=new LinkedList<BattreyInfo>();
battreyLoadInfo.put(node.getName(),nodeBattreyLoadInfo);
}
if (nodeBattreyLoadInfo.size() >= Preferences.NODE_BATTERY_INFO_QUEUE_SIZE) {
oldBattreyInfo=nodeBattreyLoadInfo.remove();
}
advReplyTotalCount++;
if (advReplyCount > 1) {
double stdDevNodeLoad=Math.sqrt(varianceNodeLoad / advReplyCount);
if (oldBattreyInfo != null) {
advReplyCount--;
lastAvgNodeLoad=avgNodeLoad;
avgNodeLoad=avgNodeLoad - (oldBattreyInfo.getWeight() * ((oldBattreyInfo.getBattreyLoad() - avgNodeLoad) / advReplyCount));
varianceNodeLoad=varianceNodeLoad - (oldBattreyInfo.getWeight() * ((oldBattreyInfo.getBattreyLoad() - lastAvgNodeLoad) * (oldBattreyInfo.getBattreyLoad() - avgNodeLoad)));
}
if (advReplyTotalCount < Preferences.NUMBER_PACKETS_NETWORK_STABLIZE) {
alpha=Preferences.ALPHA_MIN + (((Preferences.NUMBER_PACKETS_NETWORK_STABLIZE - advReplyTotalCount) / (Preferences.NUMBER_PACKETS_NETWORK_STABLIZE * 1.0f)) * (Preferences.ALPHA_MAX - Preferences.ALPHA_MIN));
}
alpha=alpha + (22 - nodes.size()) * (Preferences.ALPHA_SAFE - Preferences.ALPHA_MIN) / 20.0f;
if ((node.getBatteryLevel() - avgNodeLoad) > (Preferences.ALPHA_POSITIVE_RANGE * stdDevNodeLoad)) {
isSuitable=true;
}
 else if (Math.abs(node.getBatteryLevel() - avgNodeLoad) > (alpha * stdDevNodeLoad)) {
isSuitable=false;
}
System.out.println("String_Node_Str" + node.getName() + "String_Node_Str"+ node.getBatteryLevel()+ "String_Node_Str"+ avgNodeLoad+ "String_Node_Str"+ stdDevNodeLoad+ "String_Node_Str"+ alpha+ "String_Node_Str"+ isSuitable);
}
advReplyCount++;
lastAvgNodeLoad=avgNodeLoad;
if (!isSuitable) {
weight=gama;
}
nodeBattreyLoadInfo.add(new BattreyInfo(node.getBatteryLevel(),weight));
avgNodeLoad=avgNodeLoad + weight * ((node.getBatteryLevel() - avgNodeLoad) / advReplyCount);
if (advReplyCount == 1) {
varianceNodeLoad=0;
}
 else {
varianceNodeLoad=varianceNodeLoad + weight * ((node.getBatteryLevel() - lastAvgNodeLoad) * (node.getBatteryLevel() - avgNodeLoad));
}
return isSuitable;
}
private void addAndMergeResults(TaskResult taskResult){
TaskLookup taskLookup=taskLookups.get(taskResult.getTaskId());
taskLookup.getTaskResults().put(taskResult.getSeqNumber(),taskResult);
if (taskLookup.getTask().getTaskBattreyLoad() <= 0 && taskLookup.getTaskGroup().size() == taskLookup.getTaskResults().size()) {
taskLookup.setStatus(Preferences.TASK_STATUS.RECEIVED_RESULTS);
}
if (taskLookup.getStatus() == Preferences.TASK_STATUS.RECEIVED_RESULTS) {
String result="String_Node_Str";
for (int i=0; i < taskLookup.getTaskResults().size(); i++) {
result+=(taskLookup.getTaskResults().get(i)).toString() + "String_Node_Str";
}
logMessage("String_Node_Str" + result);
nodes.get(host).decrBatteryLevel(Preferences.BATTERY_SPENT_IN_TASK_DISTRIBUTION);
}
}
}
).start();
}