http://git-wip-us.apache.org/repos/asf/cloudstack/blob/90157f7b/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java
----------------------------------------------------------------------
diff --git 
a/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java 
b/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java
index ca60529..17a3a1c 100644
--- a/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java
+++ b/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java
@@ -38,9 +38,6 @@ import javax.ejb.Local;
 import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
-import com.cloud.network.router.VirtualRouter;
-import org.apache.log4j.Logger;
-
 import org.apache.cloudstack.affinity.dao.AffinityGroupVMMapDao;
 import org.apache.cloudstack.context.CallContext;
 import 
org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
@@ -69,6 +66,7 @@ import 
org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
 import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
 import org.apache.cloudstack.storage.to.VolumeObjectTO;
 import org.apache.cloudstack.utils.identity.ManagementServerNode;
+import org.apache.log4j.Logger;
 
 import com.cloud.agent.AgentManager;
 import com.cloud.agent.Listener;
@@ -149,6 +147,7 @@ import com.cloud.network.Network;
 import com.cloud.network.NetworkModel;
 import com.cloud.network.dao.NetworkDao;
 import com.cloud.network.dao.NetworkVO;
+import com.cloud.network.router.VirtualRouter;
 import com.cloud.network.rules.RulesManager;
 import com.cloud.offering.DiskOfferingInfo;
 import com.cloud.offering.ServiceOffering;
@@ -284,7 +283,7 @@ public class VirtualMachineManagerImpl extends ManagerBase 
implements VirtualMac
         return hostAllocators;
     }
 
-    public void setHostAllocators(List<HostAllocator> hostAllocators) {
+    public void setHostAllocators(final List<HostAllocator> hostAllocators) {
         this.hostAllocators = hostAllocators;
     }
 
@@ -358,7 +357,7 @@ public class VirtualMachineManagerImpl extends ManagerBase 
implements VirtualMac
     protected long _nodeId;
 
     @Override
-    public void registerGuru(VirtualMachine.Type type, VirtualMachineGuru 
guru) {
+    public void registerGuru(final VirtualMachine.Type type, final 
VirtualMachineGuru guru) {
         synchronized (_vmGurus) {
             _vmGurus.put(type, guru);
         }
@@ -366,12 +365,12 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
 
     @Override
     @DB
-    public void allocate(String vmInstanceName, final VirtualMachineTemplate 
template, ServiceOffering serviceOffering,
+    public void allocate(final String vmInstanceName, final 
VirtualMachineTemplate template, final ServiceOffering serviceOffering,
             final DiskOfferingInfo rootDiskOfferingInfo, final 
List<DiskOfferingInfo> dataDiskOfferings,
-            final LinkedHashMap<? extends Network, List<? extends NicProfile>> 
auxiliaryNetworks, DeploymentPlan plan, HypervisorType hyperType)
+            final LinkedHashMap<? extends Network, List<? extends NicProfile>> 
auxiliaryNetworks, final DeploymentPlan plan, final HypervisorType hyperType)
                     throws InsufficientCapacityException {
 
-        VMInstanceVO vm = _vmDao.findVMByInstanceName(vmInstanceName);
+        final VMInstanceVO vm = _vmDao.findVMByInstanceName(vmInstanceName);
         final Account owner = _entityMgr.findById(Account.class, 
vm.getAccountId());
 
         if (s_logger.isDebugEnabled()) {
@@ -382,78 +381,79 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
         if (plan.getPodId() != null) {
             vm.setPodIdToDeployIn(plan.getPodId());
         }
-        assert (plan.getClusterId() == null && plan.getPoolId() == null) : "We 
currently don't support cluster and pool preset yet";
+        assert plan.getClusterId() == null && plan.getPoolId() == null : "We 
currently don't support cluster and pool preset yet";
         final VMInstanceVO vmFinal = _vmDao.persist(vm);
 
-                final VirtualMachineProfileImpl vmProfile = new 
VirtualMachineProfileImpl(vmFinal, template, serviceOffering, null, null);
+        final VirtualMachineProfileImpl vmProfile = new 
VirtualMachineProfileImpl(vmFinal, template, serviceOffering, null, null);
 
-                Transaction.execute(new 
TransactionCallbackWithExceptionNoReturn<InsufficientCapacityException>() {
-                    @Override
-                    public void doInTransactionWithoutResult(TransactionStatus 
status) throws InsufficientCapacityException {
-                        if (s_logger.isDebugEnabled()) {
-                            s_logger.debug("Allocating nics for " + vmFinal);
-                        }
+        Transaction.execute(new 
TransactionCallbackWithExceptionNoReturn<InsufficientCapacityException>() {
+            @Override
+            public void doInTransactionWithoutResult(final TransactionStatus 
status) throws InsufficientCapacityException {
+                if (s_logger.isDebugEnabled()) {
+                    s_logger.debug("Allocating nics for " + vmFinal);
+                }
 
-                        try {
-                            _networkMgr.allocate(vmProfile, auxiliaryNetworks);
-                        } catch (ConcurrentOperationException e) {
-                            throw new CloudRuntimeException("Concurrent 
operation while trying to allocate resources for the VM", e);
-                        }
+                try {
+                    _networkMgr.allocate(vmProfile, auxiliaryNetworks);
+                } catch (final ConcurrentOperationException e) {
+                    throw new CloudRuntimeException("Concurrent operation 
while trying to allocate resources for the VM", e);
+                }
 
-                        if (s_logger.isDebugEnabled()) {
-                            s_logger.debug("Allocating disks for " + vmFinal);
-                        }
+                if (s_logger.isDebugEnabled()) {
+                    s_logger.debug("Allocating disks for " + vmFinal);
+                }
 
-                        if (template.getFormat() == ImageFormat.ISO) {
-                            volumeMgr.allocateRawVolume(Type.ROOT, "ROOT-" + 
vmFinal.getId(), rootDiskOfferingInfo.getDiskOffering(), 
rootDiskOfferingInfo.getSize(),
-                                    rootDiskOfferingInfo.getMinIops(), 
rootDiskOfferingInfo.getMaxIops(), vmFinal, template, owner);
-                        } else if (template.getFormat() == 
ImageFormat.BAREMETAL) {
-                            // Do nothing
-                        } else {
-                            volumeMgr.allocateTemplatedVolume(Type.ROOT, 
"ROOT-" + vmFinal.getId(), rootDiskOfferingInfo.getDiskOffering(), 
rootDiskOfferingInfo.getSize(),
-                                    rootDiskOfferingInfo.getMinIops(), 
rootDiskOfferingInfo.getMaxIops(), template, vmFinal, owner);
-                        }
+                if (template.getFormat() == ImageFormat.ISO) {
+                    volumeMgr.allocateRawVolume(Type.ROOT, "ROOT-" + 
vmFinal.getId(), rootDiskOfferingInfo.getDiskOffering(), 
rootDiskOfferingInfo.getSize(),
+                            rootDiskOfferingInfo.getMinIops(), 
rootDiskOfferingInfo.getMaxIops(), vmFinal, template, owner);
+                } else if (template.getFormat() == ImageFormat.BAREMETAL) {
+                    // Do nothing
+                } else {
+                    volumeMgr.allocateTemplatedVolume(Type.ROOT, "ROOT-" + 
vmFinal.getId(), rootDiskOfferingInfo.getDiskOffering(), 
rootDiskOfferingInfo.getSize(),
+                            rootDiskOfferingInfo.getMinIops(), 
rootDiskOfferingInfo.getMaxIops(), template, vmFinal, owner);
+                }
 
-                        if (dataDiskOfferings != null) {
-                            for (DiskOfferingInfo dataDiskOfferingInfo : 
dataDiskOfferings) {
-                                volumeMgr.allocateRawVolume(Type.DATADISK, 
"DATA-" + vmFinal.getId(), dataDiskOfferingInfo.getDiskOffering(), 
dataDiskOfferingInfo.getSize(),
-                                        dataDiskOfferingInfo.getMinIops(), 
dataDiskOfferingInfo.getMaxIops(), vmFinal, template, owner);
-                            }
-                        }
+                if (dataDiskOfferings != null) {
+                    for (final DiskOfferingInfo dataDiskOfferingInfo : 
dataDiskOfferings) {
+                        volumeMgr.allocateRawVolume(Type.DATADISK, "DATA-" + 
vmFinal.getId(), dataDiskOfferingInfo.getDiskOffering(), 
dataDiskOfferingInfo.getSize(),
+                                dataDiskOfferingInfo.getMinIops(), 
dataDiskOfferingInfo.getMaxIops(), vmFinal, template, owner);
                     }
-                });
-
-                if (s_logger.isDebugEnabled()) {
-                    s_logger.debug("Allocation completed for VM: " + vmFinal);
                 }
+            }
+        });
+
+        if (s_logger.isDebugEnabled()) {
+            s_logger.debug("Allocation completed for VM: " + vmFinal);
+        }
     }
 
     @Override
-    public void allocate(String vmInstanceName, VirtualMachineTemplate 
template, ServiceOffering serviceOffering,
-            LinkedHashMap<? extends Network, List<? extends NicProfile>> 
networks, DeploymentPlan plan, HypervisorType hyperType) throws 
InsufficientCapacityException {
+    public void allocate(final String vmInstanceName, final 
VirtualMachineTemplate template, final ServiceOffering serviceOffering,
+            final LinkedHashMap<? extends Network, List<? extends NicProfile>> 
networks, final DeploymentPlan plan, final HypervisorType hyperType) throws 
InsufficientCapacityException {
         allocate(vmInstanceName, template, serviceOffering, new 
DiskOfferingInfo(serviceOffering), new ArrayList<DiskOfferingInfo>(), networks, 
plan, hyperType);
     }
 
-    private VirtualMachineGuru getVmGuru(VirtualMachine vm) {
-        if(vm != null)
+    private VirtualMachineGuru getVmGuru(final VirtualMachine vm) {
+        if(vm != null) {
             return _vmGurus.get(vm.getType());
+        }
         return null;
     }
 
     @Override
-    public void expunge(String vmUuid) throws ResourceUnavailableException {
+    public void expunge(final String vmUuid) throws 
ResourceUnavailableException {
         try {
             advanceExpunge(vmUuid);
-        } catch (OperationTimedoutException e) {
+        } catch (final OperationTimedoutException e) {
             throw new CloudRuntimeException("Operation timed out", e);
-        } catch (ConcurrentOperationException e) {
+        } catch (final ConcurrentOperationException e) {
             throw new CloudRuntimeException("Concurrent operation ", e);
         }
     }
 
     @Override
-    public void advanceExpunge(String vmUuid) throws 
ResourceUnavailableException, OperationTimedoutException, 
ConcurrentOperationException {
-        VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
+    public void advanceExpunge(final String vmUuid) throws 
ResourceUnavailableException, OperationTimedoutException, 
ConcurrentOperationException {
+        final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
         advanceExpunge(vm);
     }
 
@@ -474,7 +474,7 @@ public class VirtualMachineManagerImpl extends ManagerBase 
implements VirtualMac
                 throw new CloudRuntimeException("Unable to destroy " + vm);
 
             }
-        } catch (NoTransitionException e) {
+        } catch (final NoTransitionException e) {
             s_logger.debug("Unable to destroy the vm because it is not in the 
correct state: " + vm);
             throw new CloudRuntimeException("Unable to destroy " + vm, e);
         }
@@ -483,31 +483,31 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
             s_logger.debug("Destroying vm " + vm);
         }
 
-        VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
+        final VirtualMachineProfile profile = new 
VirtualMachineProfileImpl(vm);
 
-        HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
+        final HypervisorGuru hvGuru = 
_hvGuruMgr.getGuru(vm.getHypervisorType());
 
         s_logger.debug("Cleaning up NICS");
-        List<Command> nicExpungeCommands = hvGuru.finalizeExpungeNics(vm, 
profile.getNics());
+        final List<Command> nicExpungeCommands = 
hvGuru.finalizeExpungeNics(vm, profile.getNics());
         _networkMgr.cleanupNics(profile);
 
         s_logger.debug("Cleaning up hypervisor data structures (ex. SRs in 
XenServer) for managed storage");
 
-        List<Command> volumeExpungeCommands = 
hvGuru.finalizeExpungeVolumes(vm);
+        final List<Command> volumeExpungeCommands = 
hvGuru.finalizeExpungeVolumes(vm);
 
-        Long hostId = vm.getHostId() != null ? vm.getHostId() : 
vm.getLastHostId();
+        final Long hostId = vm.getHostId() != null ? vm.getHostId() : 
vm.getLastHostId();
 
         if (volumeExpungeCommands != null && volumeExpungeCommands.size() > 0 
&& hostId != null) {
-            Commands cmds = new Commands(Command.OnError.Stop);
+            final Commands cmds = new Commands(Command.OnError.Stop);
 
-            for (Command volumeExpungeCommand : volumeExpungeCommands) {
+            for (final Command volumeExpungeCommand : volumeExpungeCommands) {
                 cmds.addCommand(volumeExpungeCommand);
             }
 
             _agentMgr.send(hostId, cmds);
 
             if (!cmds.isSuccessful()) {
-                for (Answer answer : cmds.getAnswers()) {
+                for (final Answer answer : cmds.getAnswers()) {
                     if (!answer.getResult()) {
                         s_logger.warn("Failed to expunge vm due to: " + 
answer.getDetails());
 
@@ -524,27 +524,27 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
         // Clean up volumes based on the vm's instance id
         volumeMgr.cleanupVolumes(vm.getId());
 
-        VirtualMachineGuru guru = getVmGuru(vm);
+        final VirtualMachineGuru guru = getVmGuru(vm);
         guru.finalizeExpunge(vm);
         //remove the overcommit detials from the uservm details
         _uservmDetailsDao.removeDetails(vm.getId());
 
         // send hypervisor-dependent commands before removing
-        List<Command> finalizeExpungeCommands = hvGuru.finalizeExpunge(vm);
+        final List<Command> finalizeExpungeCommands = 
hvGuru.finalizeExpunge(vm);
         if (finalizeExpungeCommands != null && finalizeExpungeCommands.size() 
> 0) {
             if (hostId != null) {
-                Commands cmds = new Commands(Command.OnError.Stop);
-                for (Command command : finalizeExpungeCommands) {
+                final Commands cmds = new Commands(Command.OnError.Stop);
+                for (final Command command : finalizeExpungeCommands) {
                     cmds.addCommand(command);
                 }
                 if (nicExpungeCommands != null) {
-                    for (Command command : nicExpungeCommands) {
+                    for (final Command command : nicExpungeCommands) {
                         cmds.addCommand(command);
                     }
                 }
                 _agentMgr.send(hostId, cmds);
                 if (!cmds.isSuccessful()) {
-                    for (Answer answer : cmds.getAnswers()) {
+                    for (final Answer answer : cmds.getAnswers()) {
                         if (!answer.getResult()) {
                             s_logger.warn("Failed to expunge vm due to: " + 
answer.getDetails());
                             throw new CloudRuntimeException("Unable to expunge 
" + vm + " due to " + answer.getDetails());
@@ -579,7 +579,7 @@ public class VirtualMachineManagerImpl extends ManagerBase 
implements VirtualMac
     }
 
     @Override
-    public boolean configure(String name, Map<String, Object> xmlParams) 
throws ConfigurationException {
+    public boolean configure(final String name, final Map<String, Object> 
xmlParams) throws ConfigurationException {
         ReservationContextImpl.init(_entityMgr);
         VirtualMachineProfileImpl.init(_entityMgr);
         VmWorkMigrate.init(_entityMgr);
@@ -599,19 +599,19 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
     }
 
     @Override
-    public void start(String vmUuid, Map<VirtualMachineProfile.Param, Object> 
params) {
+    public void start(final String vmUuid, final 
Map<VirtualMachineProfile.Param, Object> params) {
         start(vmUuid, params, null, null);
     }
 
     @Override
-    public void start(String vmUuid, Map<VirtualMachineProfile.Param, Object> 
params, DeploymentPlan planToDeploy, DeploymentPlanner planner) {
+    public void start(final String vmUuid, final 
Map<VirtualMachineProfile.Param, Object> params, final DeploymentPlan 
planToDeploy, final DeploymentPlanner planner) {
         try {
             advanceStart(vmUuid, params, planToDeploy, planner);
-        } catch (ConcurrentOperationException e) {
+        } catch (final ConcurrentOperationException e) {
             throw new CloudRuntimeException("Unable to start a VM due to 
concurrent operation", e).add(VirtualMachine.class, vmUuid);
-        } catch (InsufficientCapacityException e) {
+        } catch (final InsufficientCapacityException e) {
             throw new CloudRuntimeException("Unable to start a VM due to 
insufficient capacity", e).add(VirtualMachine.class, vmUuid);
-        } catch (ResourceUnavailableException e) {
+        } catch (final ResourceUnavailableException e) {
             if(e.getScope() != null && 
e.getScope().equals(VirtualRouter.class)){
                 throw new CloudRuntimeException("Network is unavailable. 
Please contact administrator", e).add(VirtualMachine.class, vmUuid);
             }
@@ -620,9 +620,9 @@ public class VirtualMachineManagerImpl extends ManagerBase 
implements VirtualMac
 
     }
 
-    protected boolean checkWorkItems(VMInstanceVO vm, State state) throws 
ConcurrentOperationException {
+    protected boolean checkWorkItems(final VMInstanceVO vm, final State state) 
throws ConcurrentOperationException {
         while (true) {
-            ItWorkVO vo = _workDao.findByOutstandingWork(vm.getId(), state);
+            final ItWorkVO vo = _workDao.findByOutstandingWork(vm.getId(), 
state);
             if (vo == null) {
                 if (s_logger.isDebugEnabled()) {
                     s_logger.debug("Unable to find work for VM: " + vm + " and 
state: " + state);
@@ -638,7 +638,7 @@ public class VirtualMachineManagerImpl extends ManagerBase 
implements VirtualMac
             }
 
             // also check DB to get latest VM state to detect vm update from 
concurrent process before idle waiting to get an early exit
-            VMInstanceVO instance = _vmDao.findById(vm.getId());
+            final VMInstanceVO instance = _vmDao.findById(vm.getId());
             if (instance != null && instance.getState() == State.Running) {
                 if (s_logger.isDebugEnabled()) {
                     s_logger.debug("VM is already started in DB: " + vm);
@@ -653,7 +653,7 @@ public class VirtualMachineManagerImpl extends ManagerBase 
implements VirtualMac
 
             try {
                 Thread.sleep(VmOpWaitInterval.value()*1000);
-            } catch (InterruptedException e) {
+            } catch (final InterruptedException e) {
                 s_logger.info("Waiting for " + vm + " but is interrupted");
                 throw new ConcurrentOperationException("Waiting for " + vm + " 
but is interrupted");
             }
@@ -663,22 +663,22 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
     }
 
     @DB
-    protected Ternary<VMInstanceVO, ReservationContext, ItWorkVO> 
changeToStartState(VirtualMachineGuru vmGuru, final VMInstanceVO vm, final User 
caller,
+    protected Ternary<VMInstanceVO, ReservationContext, ItWorkVO> 
changeToStartState(final VirtualMachineGuru vmGuru, final VMInstanceVO vm, 
final User caller,
             final Account account) throws ConcurrentOperationException {
-        long vmId = vm.getId();
+        final long vmId = vm.getId();
 
         ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, 
State.Starting, vm.getType(), vm.getId());
         int retry = VmOpLockStateRetry.value();
         while (retry-- != 0) {
             try {
                 final ItWorkVO workFinal = work;
-                Ternary<VMInstanceVO, ReservationContext, ItWorkVO> result =
+                final Ternary<VMInstanceVO, ReservationContext, ItWorkVO> 
result =
                         Transaction.execute(new 
TransactionCallbackWithException<Ternary<VMInstanceVO, ReservationContext, 
ItWorkVO>, NoTransitionException>() {
                             @Override
-                            public Ternary<VMInstanceVO, ReservationContext, 
ItWorkVO> doInTransaction(TransactionStatus status) throws 
NoTransitionException {
-                                Journal journal = new 
Journal.LogJournal("Creating " + vm, s_logger);
-                                ItWorkVO work = _workDao.persist(workFinal);
-                                ReservationContextImpl context = new 
ReservationContextImpl(work.getId(), journal, caller, account);
+                            public Ternary<VMInstanceVO, ReservationContext, 
ItWorkVO> doInTransaction(final TransactionStatus status) throws 
NoTransitionException {
+                                final Journal journal = new 
Journal.LogJournal("Creating " + vm, s_logger);
+                                final ItWorkVO work = 
_workDao.persist(workFinal);
+                                final ReservationContextImpl context = new 
ReservationContextImpl(work.getId(), journal, caller, account);
 
                                 if (stateTransitTo(vm, Event.StartRequested, 
null, work.getId())) {
                                     if (s_logger.isDebugEnabled()) {
@@ -692,15 +692,16 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
                         });
 
                 work = result.third();
-                if (result.first() != null)
+                if (result.first() != null) {
                     return result;
-            } catch (NoTransitionException e) {
+                }
+            } catch (final NoTransitionException e) {
                 if (s_logger.isDebugEnabled()) {
                     s_logger.debug("Unable to transition into Starting state 
due to " + e.getMessage());
                 }
             }
 
-            VMInstanceVO instance = _vmDao.findById(vmId);
+            final VMInstanceVO instance = _vmDao.findById(vmId);
             if (instance == null) {
                 throw new ConcurrentOperationException("Unable to acquire lock 
on " + vm);
             }
@@ -709,7 +710,7 @@ public class VirtualMachineManagerImpl extends ManagerBase 
implements VirtualMac
                 s_logger.debug("Determining why we're unable to update the 
state to Starting for " + instance + ".  Retry=" + retry);
             }
 
-            State state = instance.getState();
+            final State state = instance.getState();
             if (state == State.Running) {
                 if (s_logger.isDebugEnabled()) {
                     s_logger.debug("VM is already started: " + vm);
@@ -734,9 +735,9 @@ public class VirtualMachineManagerImpl extends ManagerBase 
implements VirtualMac
         throw new ConcurrentOperationException("Unable to change the state of 
" + vm);
     }
 
-    protected <T extends VMInstanceVO> boolean changeState(T vm, Event event, 
Long hostId, ItWorkVO work, Step step) throws NoTransitionException {
+    protected <T extends VMInstanceVO> boolean changeState(final T vm, final 
Event event, final Long hostId, final ItWorkVO work, final Step step) throws 
NoTransitionException {
         // FIXME: We should do this better.
-        Step previousStep = work.getStep();
+        final Step previousStep = work.getStep();
         _workDao.updateStep(work, step);
         boolean result = false;
         try {
@@ -749,9 +750,9 @@ public class VirtualMachineManagerImpl extends ManagerBase 
implements VirtualMac
         }
     }
 
-    protected boolean areAffinityGroupsAssociated(VirtualMachineProfile 
vmProfile) {
-        VirtualMachine vm = vmProfile.getVirtualMachine();
-        long vmGroupCount = 
_affinityGroupVMMapDao.countAffinityGroupsForVm(vm.getId());
+    protected boolean areAffinityGroupsAssociated(final VirtualMachineProfile 
vmProfile) {
+        final VirtualMachine vm = vmProfile.getVirtualMachine();
+        final long vmGroupCount = 
_affinityGroupVMMapDao.countAffinityGroupsForVm(vm.getId());
 
         if (vmGroupCount > 0) {
             return true;
@@ -760,20 +761,20 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
     }
 
     @Override
-    public void advanceStart(String vmUuid, Map<VirtualMachineProfile.Param, 
Object> params, DeploymentPlanner planner)
+    public void advanceStart(final String vmUuid, final 
Map<VirtualMachineProfile.Param, Object> params, final DeploymentPlanner 
planner)
             throws InsufficientCapacityException, 
ConcurrentOperationException, ResourceUnavailableException {
         advanceStart(vmUuid, params, null, planner);
     }
 
     @Override
-    public void advanceStart(String vmUuid, Map<VirtualMachineProfile.Param, 
Object> params, DeploymentPlan planToDeploy, DeploymentPlanner planner)
+    public void advanceStart(final String vmUuid, final 
Map<VirtualMachineProfile.Param, Object> params, final DeploymentPlan 
planToDeploy, final DeploymentPlanner planner)
             throws InsufficientCapacityException, 
ConcurrentOperationException, ResourceUnavailableException {
 
-        AsyncJobExecutionContext jobContext = 
AsyncJobExecutionContext.getCurrentExecutionContext();
+        final AsyncJobExecutionContext jobContext = 
AsyncJobExecutionContext.getCurrentExecutionContext();
         if ( 
jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
             // avoid re-entrance
             VmWorkJobVO placeHolder = null;
-            VirtualMachine vm = _vmDao.findByUuid(vmUuid);
+            final VirtualMachine vm = _vmDao.findByUuid(vmUuid);
             placeHolder = createPlaceHolderWork(vm.getId());
             try {
                 orchestrateStart(vmUuid, params, planToDeploy, planner);
@@ -783,57 +784,58 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
                 }
             }
         } else {
-            Outcome<VirtualMachine> outcome = startVmThroughJobQueue(vmUuid, 
params, planToDeploy, planner);
+            final Outcome<VirtualMachine> outcome = 
startVmThroughJobQueue(vmUuid, params, planToDeploy, planner);
 
             try {
-                VirtualMachine vm = outcome.get();
-            } catch (InterruptedException e) {
+                final VirtualMachine vm = outcome.get();
+            } catch (final InterruptedException e) {
                 throw new RuntimeException("Operation is interrupted", e);
-            } catch (java.util.concurrent.ExecutionException e) {
+            } catch (final java.util.concurrent.ExecutionException e) {
                 throw new RuntimeException("Execution excetion", e);
             }
 
-            Object jobResult = 
_jobMgr.unmarshallResultObject(outcome.getJob());
+            final Object jobResult = 
_jobMgr.unmarshallResultObject(outcome.getJob());
             if (jobResult != null) {
-                if (jobResult instanceof ConcurrentOperationException)
+                if (jobResult instanceof ConcurrentOperationException) {
                     throw (ConcurrentOperationException)jobResult;
-                else if (jobResult instanceof ResourceUnavailableException)
+                } else if (jobResult instanceof ResourceUnavailableException) {
                     throw (ResourceUnavailableException)jobResult;
-                else if (jobResult instanceof InsufficientCapacityException)
+                } else if (jobResult instanceof InsufficientCapacityException) 
{
                     throw (InsufficientCapacityException)jobResult;
-                else if (jobResult instanceof RuntimeException)
+                } else if (jobResult instanceof RuntimeException) {
                     throw (RuntimeException)jobResult;
-                else if (jobResult instanceof Throwable)
+                } else if (jobResult instanceof Throwable) {
                     throw new RuntimeException("Unexpected exception", 
(Throwable)jobResult);
+                }
             }
         }
     }
 
 
     @Override
-    public void orchestrateStart(String vmUuid, 
Map<VirtualMachineProfile.Param, Object> params, DeploymentPlan planToDeploy, 
DeploymentPlanner planner)
+    public void orchestrateStart(final String vmUuid, final 
Map<VirtualMachineProfile.Param, Object> params, final DeploymentPlan 
planToDeploy, final DeploymentPlanner planner)
             throws InsufficientCapacityException, 
ConcurrentOperationException, ResourceUnavailableException {
 
-        CallContext cctxt = CallContext.current();
-        Account account = cctxt.getCallingAccount();
-        User caller = cctxt.getCallingUser();
+        final CallContext cctxt = CallContext.current();
+        final Account account = cctxt.getCallingAccount();
+        final User caller = cctxt.getCallingUser();
 
         VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
 
-        VirtualMachineGuru vmGuru = getVmGuru(vm);
+        final VirtualMachineGuru vmGuru = getVmGuru(vm);
 
-        Ternary<VMInstanceVO, ReservationContext, ItWorkVO> start = 
changeToStartState(vmGuru, vm, caller, account);
+        final Ternary<VMInstanceVO, ReservationContext, ItWorkVO> start = 
changeToStartState(vmGuru, vm, caller, account);
         if (start == null) {
             return;
         }
 
         vm = start.first();
-        ReservationContext ctx = start.second();
+        final ReservationContext ctx = start.second();
         ItWorkVO work = start.third();
 
         VMInstanceVO startedVm = null;
-        ServiceOfferingVO offering = _offeringDao.findById(vm.getId(), 
vm.getServiceOfferingId());
-        VirtualMachineTemplate template = 
_entityMgr.findByIdIncludingRemoved(VirtualMachineTemplate.class, 
vm.getTemplateId());
+        final ServiceOfferingVO offering = _offeringDao.findById(vm.getId(), 
vm.getServiceOfferingId());
+        final VirtualMachineTemplate template = 
_entityMgr.findByIdIncludingRemoved(VirtualMachineTemplate.class, 
vm.getTemplateId());
 
         if (s_logger.isDebugEnabled()) {
             s_logger.debug("Trying to deploy VM, vm has dcId: " + 
vm.getDataCenterId() + " and podId: " + vm.getPodIdToDeployIn());
@@ -849,12 +851,12 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
                             planToDeploy.getPoolId(), 
planToDeploy.getPhysicalNetworkId(), ctx);
         }
 
-        HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
+        final HypervisorGuru hvGuru = 
_hvGuruMgr.getGuru(vm.getHypervisorType());
 
         boolean canRetry = true;
         ExcludeList avoids = null;
         try {
-            Journal journal = start.second().getJournal();
+            final Journal journal = start.second().getJournal();
 
             if (planToDeploy != null) {
                 avoids = planToDeploy.getAvoids();
@@ -868,19 +870,19 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
 
             boolean planChangedByVolume = false;
             boolean reuseVolume = true;
-            DataCenterDeployment originalPlan = plan;
+            final DataCenterDeployment originalPlan = plan;
 
             int retry = StartRetry.value();
             while (retry-- != 0) { // It's != so that it can match -1.
 
                 if (reuseVolume) {
                     // edit plan if this vm's ROOT volume is in READY state 
already
-                    List<VolumeVO> vols = 
_volsDao.findReadyRootVolumesByInstance(vm.getId());
-                    for (VolumeVO vol : vols) {
+                    final List<VolumeVO> vols = 
_volsDao.findReadyRootVolumesByInstance(vm.getId());
+                    for (final VolumeVO vol : vols) {
                         // make sure if the templateId is unchanged. If it is 
changed,
                         // let planner
                         // reassign pool for the volume even if it ready.
-                        Long volTemplateId = vol.getTemplateId();
+                        final Long volTemplateId = vol.getTemplateId();
                         if (volTemplateId != null && volTemplateId.longValue() 
!= template.getId()) {
                             if (s_logger.isDebugEnabled()) {
                                 s_logger.debug(vol + " of " + vm + " is READY, 
but template ids don't match, let the planner reassign a new pool");
@@ -888,16 +890,16 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
                             continue;
                         }
 
-                        StoragePool pool = 
(StoragePool)dataStoreMgr.getPrimaryDataStore(vol.getPoolId());
+                        final StoragePool pool = 
(StoragePool)dataStoreMgr.getPrimaryDataStore(vol.getPoolId());
                         if (!pool.isInMaintenance()) {
                             if (s_logger.isDebugEnabled()) {
                                 s_logger.debug("Root volume is ready, need to 
place VM in volume's cluster");
                             }
-                            long rootVolDcId = pool.getDataCenterId();
-                            Long rootVolPodId = pool.getPodId();
-                            Long rootVolClusterId = pool.getClusterId();
+                            final long rootVolDcId = pool.getDataCenterId();
+                            final Long rootVolPodId = pool.getPodId();
+                            final Long rootVolClusterId = pool.getClusterId();
                             if (planToDeploy != null && 
planToDeploy.getDataCenterId() != 0) {
-                                Long clusterIdSpecified = 
planToDeploy.getClusterId();
+                                final Long clusterIdSpecified = 
planToDeploy.getClusterId();
                                 if (clusterIdSpecified != null && 
rootVolClusterId != null) {
                                     if (rootVolClusterId.longValue() != 
clusterIdSpecified.longValue()) {
                                         // cannot satisfy the plan passed in 
to the
@@ -926,12 +928,12 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
                     }
                 }
 
-                Account owner = _entityMgr.findById(Account.class, 
vm.getAccountId());
-                VirtualMachineProfileImpl vmProfile = new 
VirtualMachineProfileImpl(vm, template, offering, owner, params);
+                final Account owner = _entityMgr.findById(Account.class, 
vm.getAccountId());
+                final VirtualMachineProfileImpl vmProfile = new 
VirtualMachineProfileImpl(vm, template, offering, owner, params);
                 DeployDestination dest = null;
                 try {
                     dest = _dpMgr.planDeployment(vmProfile, plan, avoids, 
planner);
-                } catch (AffinityConflictException e2) {
+                } catch (final AffinityConflictException e2) {
                     s_logger.warn("Unable to create deployment, affinity rules 
associted to the VM conflict", e2);
                     throw new CloudRuntimeException("Unable to create 
deployment, affinity rules associted to the VM conflict");
 
@@ -956,12 +958,12 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
 
                 long destHostId = dest.getHost().getId();
                 vm.setPodIdToDeployIn(dest.getPod().getId());
-                Long cluster_id = dest.getCluster().getId();
-                ClusterDetailsVO cluster_detail_cpu = 
_clusterDetailsDao.findDetail(cluster_id, "cpuOvercommitRatio");
-                ClusterDetailsVO cluster_detail_ram = 
_clusterDetailsDao.findDetail(cluster_id, "memoryOvercommitRatio");
+                final Long cluster_id = dest.getCluster().getId();
+                final ClusterDetailsVO cluster_detail_cpu = 
_clusterDetailsDao.findDetail(cluster_id, "cpuOvercommitRatio");
+                final ClusterDetailsVO cluster_detail_ram = 
_clusterDetailsDao.findDetail(cluster_id, "memoryOvercommitRatio");
                 //storing the value of overcommit in the vm_details table for 
doing a capacity check in case the cluster overcommit ratio is changed.
                 if (_uservmDetailsDao.findDetail(vm.getId(), 
"cpuOvercommitRatio") == null &&
-                        ((Float.parseFloat(cluster_detail_cpu.getValue()) > 1f 
|| Float.parseFloat(cluster_detail_ram.getValue()) > 1f))) {
+                        (Float.parseFloat(cluster_detail_cpu.getValue()) > 1f 
|| Float.parseFloat(cluster_detail_ram.getValue()) > 1f)) {
                     _uservmDetailsDao.addDetail(vm.getId(), 
"cpuOvercommitRatio", cluster_detail_cpu.getValue(), true);
                     _uservmDetailsDao.addDetail(vm.getId(), 
"memoryOvercommitRatio", cluster_detail_ram.getValue(), true);
                 } else if (_uservmDetailsDao.findDetail(vm.getId(), 
"cpuOvercommitRatio") != null) {
@@ -976,7 +978,7 @@ public class VirtualMachineManagerImpl extends ManagerBase 
implements VirtualMac
                     if (!changeState(vm, Event.OperationRetry, destHostId, 
work, Step.Prepare)) {
                         throw new ConcurrentOperationException("Unable to 
update the state of the Virtual Machine");
                     }
-                } catch (NoTransitionException e1) {
+                } catch (final NoTransitionException e1) {
                     throw new ConcurrentOperationException(e1.getMessage());
                 }
 
@@ -996,7 +998,7 @@ public class VirtualMachineManagerImpl extends ManagerBase 
implements VirtualMac
                     Commands cmds = null;
                     vmGuru.finalizeVirtualMachineProfile(vmProfile, dest, ctx);
 
-                    VirtualMachineTO vmTO = hvGuru.implement(vmProfile);
+                    final VirtualMachineTO vmTO = hvGuru.implement(vmProfile);
 
                     handlePath(vmTO.getDisks(), vm.getHypervisorType());
 
@@ -1021,9 +1023,9 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
                     startAnswer = cmds.getAnswer(StartAnswer.class);
                     if (startAnswer != null && startAnswer.getResult()) {
                         handlePath(vmTO.getDisks(), 
startAnswer.getIqnToPath());
-                        String host_guid = startAnswer.getHost_guid();
+                        final String host_guid = startAnswer.getHost_guid();
                         if (host_guid != null) {
-                            HostVO finalHost = 
_resourceMgr.findHostByGuid(host_guid);
+                            final HostVO finalHost = 
_resourceMgr.findHostByGuid(host_guid);
                             if (finalHost == null) {
                                 throw new CloudRuntimeException("Host Guid " + 
host_guid + " doesn't exist in DB, something wrong here");
                             }
@@ -1037,7 +1039,7 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
                             }
 
                             // Update GPU device capacity
-                            GPUDeviceTO gpuDevice = 
startAnswer.getVirtualMachine().getGpuDevice();
+                            final GPUDeviceTO gpuDevice = 
startAnswer.getVirtualMachine().getGpuDevice();
                             if (gpuDevice != null) {
                                 _resourceMgr.updateGPUDetails(destHostId, 
gpuDevice.getGroupDetails());
                             }
@@ -1052,14 +1054,14 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
                                 s_logger.info("The guru did not like the 
answers so stopping " + vm);
                             }
 
-                            StopCommand cmd = new StopCommand(vm, 
getExecuteInSequence(vm.getHypervisorType()), false);
-                            Answer answer = _agentMgr.easySend(destHostId, 
cmd);
+                            final StopCommand cmd = new StopCommand(vm, 
getExecuteInSequence(vm.getHypervisorType()), false);
+                            final Answer answer = 
_agentMgr.easySend(destHostId, cmd);
                             if (answer != null && answer instanceof 
StopAnswer) {
-                                StopAnswer stopAns = (StopAnswer)answer;
+                                final StopAnswer stopAns = (StopAnswer)answer;
                                 if (vm.getType() == VirtualMachine.Type.User) {
-                                    String platform = stopAns.getPlatform();
+                                    final String platform = 
stopAns.getPlatform();
                                     if (platform != null) {
-                                        Map<String,String> vmmetadata = new 
HashMap<String,String>();
+                                        final Map<String,String> vmmetadata = 
new HashMap<String,String>();
                                         vmmetadata.put(vm.getInstanceName(), 
platform);
                                         syncVMMetaData(vmmetadata);
                                     }
@@ -1079,14 +1081,14 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
                         break;
                     }
 
-                } catch (OperationTimedoutException e) {
+                } catch (final OperationTimedoutException e) {
                     s_logger.debug("Unable to send the start command to host " 
+ dest.getHost());
                     if (e.isActive()) {
                         _haMgr.scheduleStop(vm, destHostId, 
WorkType.CheckStop);
                     }
                     canRetry = false;
                     throw new AgentUnavailableException("Unable to start " + 
vm.getHostName(), destHostId, e);
-                } catch (ResourceUnavailableException e) {
+                } catch (final ResourceUnavailableException e) {
                     s_logger.info("Unable to contact resource.", e);
                     if (!avoids.add(e)) {
                         if (e.getScope() == Volume.class || e.getScope() == 
Nic.class) {
@@ -1096,7 +1098,7 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
                             throw e;
                         }
                     }
-                } catch (InsufficientCapacityException e) {
+                } catch (final InsufficientCapacityException e) {
                     s_logger.info("Insufficient capacity ", e);
                     if (!avoids.add(e)) {
                         if (e.getScope() == Volume.class || e.getScope() == 
Nic.class) {
@@ -1105,15 +1107,18 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
                             s_logger.warn("unexpected 
InsufficientCapacityException : " + e.getScope().getName(), e);
                         }
                     }
-                } catch (Exception e) {
+                } catch (final ExecutionException e) {
+                    s_logger.error("Failed to start instance " + vm, e);
+                    throw new AgentUnavailableException("Unable to start 
instance due to " + e.getMessage(), destHostId, e);
+                } catch (final NoTransitionException e) {
                     s_logger.error("Failed to start instance " + vm, e);
                     throw new AgentUnavailableException("Unable to start 
instance due to " + e.getMessage(), destHostId, e);
                 } finally {
                     if (startedVm == null && canRetry) {
-                        Step prevStep = work.getStep();
+                        final Step prevStep = work.getStep();
                         _workDao.updateStep(work, Step.Release);
                         // If previous step was started/ing && we got a valid 
answer
-                        if ((prevStep == Step.Started || prevStep == 
Step.Starting) && (startAnswer != null && startAnswer.getResult())) {  //TODO 
check the response of cleanup and record it in DB for retry
+                        if ((prevStep == Step.Started || prevStep == 
Step.Starting) && startAnswer != null && startAnswer.getResult()) {  //TODO 
check the response of cleanup and record it in DB for retry
                             cleanup(vmGuru, vmProfile, work, 
Event.OperationFailed, false);
                         } else {
                             //if step is not starting/started, send cleanup 
command with force=true
@@ -1127,7 +1132,7 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
                 if (canRetry) {
                     try {
                         changeState(vm, Event.OperationFailed, null, work, 
Step.Done);
-                    } catch (NoTransitionException e) {
+                    } catch (final NoTransitionException e) {
                         throw new ConcurrentOperationException(e.getMessage());
                     }
                 }
@@ -1144,24 +1149,24 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
     }
 
     // for managed storage on KVM, need to make sure the path field of the 
volume in question is populated with the IQN
-    private void handlePath(DiskTO[] disks, HypervisorType hypervisorType) {
+    private void handlePath(final DiskTO[] disks, final HypervisorType 
hypervisorType) {
         if (hypervisorType != HypervisorType.KVM) {
             return;
         }
 
         if (disks != null) {
-            for (DiskTO disk : disks) {
-                Map<String, String> details = disk.getDetails();
-                boolean isManaged = details != null && 
Boolean.parseBoolean(details.get(DiskTO.MANAGED));
+            for (final DiskTO disk : disks) {
+                final Map<String, String> details = disk.getDetails();
+                final boolean isManaged = details != null && 
Boolean.parseBoolean(details.get(DiskTO.MANAGED));
 
                 if (isManaged && disk.getPath() == null) {
-                    Long volumeId = disk.getData().getId();
-                    VolumeVO volume = _volsDao.findById(volumeId);
+                    final Long volumeId = disk.getData().getId();
+                    final VolumeVO volume = _volsDao.findById(volumeId);
 
                     disk.setPath(volume.get_iScsiName());
 
                     if (disk.getData() instanceof VolumeObjectTO) {
-                        VolumeObjectTO volTo = (VolumeObjectTO)disk.getData();
+                        final VolumeObjectTO volTo = 
(VolumeObjectTO)disk.getData();
 
                         volTo.setPath(volume.get_iScsiName());
                     }
@@ -1175,17 +1180,17 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
     }
 
     // for managed storage on XenServer and VMware, need to update the DB with 
a path if the VDI/VMDK file was newly created
-    private void handlePath(DiskTO[] disks, Map<String, String> iqnToPath) {
+    private void handlePath(final DiskTO[] disks, final Map<String, String> 
iqnToPath) {
         if (disks != null && iqnToPath != null) {
-            for (DiskTO disk : disks) {
-                Map<String, String> details = disk.getDetails();
-                boolean isManaged = details != null && 
Boolean.parseBoolean(details.get(DiskTO.MANAGED));
+            for (final DiskTO disk : disks) {
+                final Map<String, String> details = disk.getDetails();
+                final boolean isManaged = details != null && 
Boolean.parseBoolean(details.get(DiskTO.MANAGED));
 
                 if (isManaged) {
-                    Long volumeId = disk.getData().getId();
-                    VolumeVO volume = _volsDao.findById(volumeId);
-                    String iScsiName = volume.get_iScsiName();
-                    String path = iqnToPath.get(iScsiName);
+                    final Long volumeId = disk.getData().getId();
+                    final VolumeVO volume = _volsDao.findById(volumeId);
+                    final String iScsiName = volume.get_iScsiName();
+                    final String path = iqnToPath.get(iScsiName);
 
                     if (path != null) {
                         volume.setPath(path);
@@ -1197,13 +1202,13 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
         }
     }
 
-    private void syncDiskChainChange(StartAnswer answer) {
-        VirtualMachineTO vmSpec = answer.getVirtualMachine();
+    private void syncDiskChainChange(final StartAnswer answer) {
+        final VirtualMachineTO vmSpec = answer.getVirtualMachine();
 
-        for (DiskTO disk : vmSpec.getDisks()) {
+        for (final DiskTO disk : vmSpec.getDisks()) {
             if (disk.getType() != Volume.Type.ISO) {
-                VolumeObjectTO vol = (VolumeObjectTO)disk.getData();
-                VolumeVO volume = _volsDao.findById(vol.getId());
+                final VolumeObjectTO vol = (VolumeObjectTO)disk.getData();
+                final VolumeVO volume = _volsDao.findById(vol.getId());
 
                 // Use getPath() from VolumeVO to get a fresh copy of what's 
in the DB.
                 // Before doing this, in a certain situation, getPath() from 
VolumeObjectTO
@@ -1218,51 +1223,51 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
     }
 
     @Override
-    public void stop(String vmUuid) throws ResourceUnavailableException {
+    public void stop(final String vmUuid) throws ResourceUnavailableException {
         try {
             advanceStop(vmUuid, false);
-        } catch (OperationTimedoutException e) {
+        } catch (final OperationTimedoutException e) {
             throw new AgentUnavailableException("Unable to stop vm because the 
operation to stop timed out", e.getAgentId(), e);
-        } catch (ConcurrentOperationException e) {
+        } catch (final ConcurrentOperationException e) {
             throw new CloudRuntimeException("Unable to stop vm because of a 
concurrent operation", e);
         }
     }
 
 
-    protected boolean getExecuteInSequence(HypervisorType hypervisorType) {
+    protected boolean getExecuteInSequence(final HypervisorType 
hypervisorType) {
         if (HypervisorType.KVM == hypervisorType || HypervisorType.LXC == 
hypervisorType || HypervisorType.XenServer == hypervisorType) {
             return false;
         } else if(HypervisorType.VMware == hypervisorType) {
-            Boolean fullClone = HypervisorGuru.VmwareFullClone.value();
+            final Boolean fullClone = HypervisorGuru.VmwareFullClone.value();
             return fullClone;
         } else {
             return ExecuteInSequence.value();
         }
     }
 
-    protected boolean sendStop(VirtualMachineGuru guru, VirtualMachineProfile 
profile, boolean force, boolean checkBeforeCleanup) {
-        VirtualMachine vm = profile.getVirtualMachine();
-        StopCommand stop = new StopCommand(vm, 
getExecuteInSequence(vm.getHypervisorType()), checkBeforeCleanup);
+    protected boolean sendStop(final VirtualMachineGuru guru, final 
VirtualMachineProfile profile, final boolean force, final boolean 
checkBeforeCleanup) {
+        final VirtualMachine vm = profile.getVirtualMachine();
+        final StopCommand stop = new StopCommand(vm, 
getExecuteInSequence(vm.getHypervisorType()), checkBeforeCleanup);
         try {
-            Answer answer = _agentMgr.send(vm.getHostId(), stop);
+            final Answer answer = _agentMgr.send(vm.getHostId(), stop);
             if (answer != null && answer instanceof StopAnswer) {
-                StopAnswer stopAns = (StopAnswer)answer;
+                final StopAnswer stopAns = (StopAnswer)answer;
                 if (vm.getType() == VirtualMachine.Type.User) {
-                    String platform = stopAns.getPlatform();
+                    final String platform = stopAns.getPlatform();
                     if (platform != null) {
-                        UserVmVO userVm = _userVmDao.findById(vm.getId());
+                        final UserVmVO userVm = 
_userVmDao.findById(vm.getId());
                         _userVmDao.loadDetails(userVm);
                         userVm.setDetail("platform", platform);
                         _userVmDao.saveDetails(userVm);
                     }
                 }
 
-                GPUDeviceTO gpuDevice = stop.getGpuDevice();
+                final GPUDeviceTO gpuDevice = stop.getGpuDevice();
                 if (gpuDevice != null) {
                     _resourceMgr.updateGPUDetails(vm.getHostId(), 
gpuDevice.getGroupDetails());
                 }
                 if (answer == null || !answer.getResult()) {
-                    String details = (answer != null) ? answer.getDetails() : 
"null answer returned";
+                    final String details = answer != null ? 
answer.getDetails() : "null answer returned";
                     s_logger.debug("Unable to stop VM due to " + details);
                     return false;
                 }
@@ -1273,11 +1278,11 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
                 return false;
             }
 
-        } catch (AgentUnavailableException e) {
+        } catch (final AgentUnavailableException e) {
             if (!force) {
                 return false;
             }
-        } catch (OperationTimedoutException e) {
+        } catch (final OperationTimedoutException e) {
             if (!force) {
                 return false;
             }
@@ -1286,14 +1291,14 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
         return true;
     }
 
-    protected boolean cleanup(VirtualMachineGuru guru, VirtualMachineProfile 
profile, ItWorkVO work, Event event, boolean cleanUpEvenIfUnableToStop) {
-        VirtualMachine vm = profile.getVirtualMachine();
-        State state = vm.getState();
+    protected boolean cleanup(final VirtualMachineGuru guru, final 
VirtualMachineProfile profile, final ItWorkVO work, final Event event, final 
boolean cleanUpEvenIfUnableToStop) {
+        final VirtualMachine vm = profile.getVirtualMachine();
+        final State state = vm.getState();
         s_logger.debug("Cleaning up resources for the vm " + vm + " in " + 
state + " state");
         try {
             if (state == State.Starting) {
                 if (work != null) {
-                    Step step = work.getStep();
+                    final Step step = work.getStep();
                     if (step == Step.Starting && !cleanUpEvenIfUnableToStop) {
                         s_logger.warn("Unable to cleanup vm " + vm + "; work 
state is incorrect: " + step);
                         return false;
@@ -1311,7 +1316,7 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
                     if (step != Step.Release && step != Step.Prepare && step 
!= Step.Started && step != Step.Starting) {
                         s_logger.debug("Cleanup is not needed for vm " + vm + 
"; work state is incorrect: " + step);
                         return true;
-                     }
+                    }
                 } else {
                     if (vm.getHostId() != null) {
                         if (!sendStop(guru, profile, 
cleanUpEvenIfUnableToStop, false)) {
@@ -1351,7 +1356,7 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
             try {
                 _networkMgr.release(profile, cleanUpEvenIfUnableToStop);
                 s_logger.debug("Successfully released network resources for 
the vm " + vm);
-            } catch (Exception e) {
+            } catch (final Exception e) {
                 s_logger.warn("Unable to release some network resources.", e);
             }
 
@@ -1363,15 +1368,15 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
     }
 
     @Override
-    public void advanceStop(String vmUuid, boolean cleanUpEvenIfUnableToStop)
+    public void advanceStop(final String vmUuid, final boolean 
cleanUpEvenIfUnableToStop)
             throws AgentUnavailableException, OperationTimedoutException, 
ConcurrentOperationException {
 
-        AsyncJobExecutionContext jobContext = 
AsyncJobExecutionContext.getCurrentExecutionContext();
+        final AsyncJobExecutionContext jobContext = 
AsyncJobExecutionContext.getCurrentExecutionContext();
         if 
(jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
             // avoid re-entrance
 
             VmWorkJobVO placeHolder = null;
-            VirtualMachine vm = _vmDao.findByUuid(vmUuid);
+            final VirtualMachine vm = _vmDao.findByUuid(vmUuid);
             placeHolder = createPlaceHolderWork(vm.getId());
             try {
                 orchestrateStop(vmUuid, cleanUpEvenIfUnableToStop);
@@ -1382,41 +1387,42 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
             }
 
         } else {
-            Outcome<VirtualMachine> outcome = stopVmThroughJobQueue(vmUuid, 
cleanUpEvenIfUnableToStop);
+            final Outcome<VirtualMachine> outcome = 
stopVmThroughJobQueue(vmUuid, cleanUpEvenIfUnableToStop);
 
             try {
-                VirtualMachine vm = outcome.get();
-            } catch (InterruptedException e) {
+                final VirtualMachine vm = outcome.get();
+            } catch (final InterruptedException e) {
                 throw new RuntimeException("Operation is interrupted", e);
-            } catch (java.util.concurrent.ExecutionException e) {
+            } catch (final java.util.concurrent.ExecutionException e) {
                 throw new RuntimeException("Execution excetion", e);
             }
 
-            Object jobResult = 
_jobMgr.unmarshallResultObject(outcome.getJob());
+            final Object jobResult = 
_jobMgr.unmarshallResultObject(outcome.getJob());
             if (jobResult != null) {
-                if (jobResult instanceof AgentUnavailableException)
+                if (jobResult instanceof AgentUnavailableException) {
                     throw (AgentUnavailableException)jobResult;
-                else if (jobResult instanceof ConcurrentOperationException)
+                } else if (jobResult instanceof ConcurrentOperationException) {
                     throw (ConcurrentOperationException)jobResult;
-                else if (jobResult instanceof OperationTimedoutException)
+                } else if (jobResult instanceof OperationTimedoutException) {
                     throw (OperationTimedoutException)jobResult;
-                else if (jobResult instanceof RuntimeException)
+                } else if (jobResult instanceof RuntimeException) {
                     throw (RuntimeException)jobResult;
-                else if (jobResult instanceof Throwable)
+                } else if (jobResult instanceof Throwable) {
                     throw new RuntimeException("Unexpected exception", 
(Throwable)jobResult);
+                }
             }
         }
     }
 
-    private void orchestrateStop(String vmUuid, boolean 
cleanUpEvenIfUnableToStop) throws AgentUnavailableException, 
OperationTimedoutException, ConcurrentOperationException {
-        VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
+    private void orchestrateStop(final String vmUuid, final boolean 
cleanUpEvenIfUnableToStop) throws AgentUnavailableException, 
OperationTimedoutException, ConcurrentOperationException {
+        final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
 
         advanceStop(vm, cleanUpEvenIfUnableToStop);
     }
 
-    private void advanceStop(VMInstanceVO vm, boolean 
cleanUpEvenIfUnableToStop) throws AgentUnavailableException, 
OperationTimedoutException,
+    private void advanceStop(final VMInstanceVO vm, final boolean 
cleanUpEvenIfUnableToStop) throws AgentUnavailableException, 
OperationTimedoutException,
     ConcurrentOperationException {
-        State state = vm.getState();
+        final State state = vm.getState();
         if (state == State.Stopped) {
             if (s_logger.isDebugEnabled()) {
                 s_logger.debug("VM is already stopped: " + vm);
@@ -1431,13 +1437,13 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
             return;
         }
         // grab outstanding work item if any
-        ItWorkVO work = _workDao.findByOutstandingWork(vm.getId(), 
vm.getState());
+        final ItWorkVO work = _workDao.findByOutstandingWork(vm.getId(), 
vm.getState());
         if (work != null) {
             if (s_logger.isDebugEnabled()) {
                 s_logger.debug("Found an outstanding work item for this vm " + 
vm + " with state:" + vm.getState() + ", work id:" + work.getId());
             }
         }
-        Long hostId = vm.getHostId();
+        final Long hostId = vm.getHostId();
         if (hostId == null) {
             if (!cleanUpEvenIfUnableToStop) {
                 if (s_logger.isDebugEnabled()) {
@@ -1447,7 +1453,7 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
             }
             try {
                 stateTransitTo(vm, Event.AgentReportStopped, null, null);
-            } catch (NoTransitionException e) {
+            } catch (final NoTransitionException e) {
                 s_logger.warn(e.getMessage());
             }
             // mark outstanding work item if any as done
@@ -1461,18 +1467,18 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
             return;
         }
 
-        VirtualMachineGuru vmGuru = getVmGuru(vm);
-        VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
+        final VirtualMachineGuru vmGuru = getVmGuru(vm);
+        final VirtualMachineProfile profile = new 
VirtualMachineProfileImpl(vm);
 
         try {
             if (!stateTransitTo(vm, Event.StopRequested, vm.getHostId())) {
                 throw new ConcurrentOperationException("VM is being operated 
on.");
             }
-        } catch (NoTransitionException e1) {
+        } catch (final NoTransitionException e1) {
             if (!cleanUpEvenIfUnableToStop) {
                 throw new CloudRuntimeException("We cannot stop " + vm + " 
when it is in state " + vm.getState());
             }
-            boolean doCleanup = true;
+            final boolean doCleanup = true;
             if (s_logger.isDebugEnabled()) {
                 s_logger.debug("Unable to transition the state but we're 
moving on because it's forced stop");
             }
@@ -1486,7 +1492,7 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
                         if (!changeState(vm, Event.AgentReportStopped, null, 
work, Step.Done)) {
                             throw new CloudRuntimeException("Unable to stop " 
+ vm);
                         }
-                    } catch (NoTransitionException e) {
+                    } catch (final NoTransitionException e) {
                         s_logger.warn("Unable to cleanup " + vm);
                         throw new CloudRuntimeException("Unable to stop " + 
vm, e);
                     }
@@ -1505,7 +1511,7 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
 
         vmGuru.prepareStop(profile);
 
-        StopCommand stop = new StopCommand(vm, 
getExecuteInSequence(vm.getHypervisorType()), false);
+        final StopCommand stop = new StopCommand(vm, 
getExecuteInSequence(vm.getHypervisorType()), false);
 
         boolean stopped = false;
         Answer answer = null;
@@ -1513,11 +1519,11 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
             answer = _agentMgr.send(vm.getHostId(), stop);
             if (answer != null) {
                 if (answer instanceof StopAnswer) {
-                    StopAnswer stopAns = (StopAnswer)answer;
+                    final StopAnswer stopAns = (StopAnswer)answer;
                     if (vm.getType() == VirtualMachine.Type.User) {
-                        String platform = stopAns.getPlatform();
+                        final String platform = stopAns.getPlatform();
                         if (platform != null) {
-                            UserVmVO userVm = _userVmDao.findById(vm.getId());
+                            final UserVmVO userVm = 
_userVmDao.findById(vm.getId());
                             _userVmDao.loadDetails(userVm);
                             userVm.setDetail("platform", platform);
                             _userVmDao.saveDetails(userVm);
@@ -1529,7 +1535,7 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
                     throw new CloudRuntimeException("Unable to stop the 
virtual machine due to " + answer.getDetails());
                 }
                 vmGuru.finalizeStop(profile, answer);
-                GPUDeviceTO gpuDevice = stop.getGpuDevice();
+                final GPUDeviceTO gpuDevice = stop.getGpuDevice();
                 if (gpuDevice != null) {
                     _resourceMgr.updateGPUDetails(vm.getHostId(), 
gpuDevice.getGroupDetails());
                 }
@@ -1537,9 +1543,9 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
                 throw new CloudRuntimeException("Invalid answer received in 
response to a StopCommand on " + vm.instanceName);
             }
 
-        } catch (AgentUnavailableException e) {
+        } catch (final AgentUnavailableException e) {
             s_logger.warn("Unable to stop vm, agent unavailable: " + 
e.toString());
-        } catch (OperationTimedoutException e) {
+        } catch (final OperationTimedoutException e) {
             s_logger.warn("Unable to stop vm, operation timed out: " + 
e.toString());
         } finally {
             if (!stopped) {
@@ -1547,7 +1553,7 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
                     s_logger.warn("Unable to stop vm " + vm);
                     try {
                         stateTransitTo(vm, Event.OperationFailed, 
vm.getHostId());
-                    } catch (NoTransitionException e) {
+                    } catch (final NoTransitionException e) {
                         s_logger.warn("Unable to transition the state " + vm);
                     }
                     throw new CloudRuntimeException("Unable to stop " + vm);
@@ -1565,7 +1571,7 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
         try {
             _networkMgr.release(profile, cleanUpEvenIfUnableToStop);
             s_logger.debug("Successfully released network resources for the vm 
" + vm);
-        } catch (Exception e) {
+        } catch (final Exception e) {
             s_logger.warn("Unable to release some network resources.", e);
         }
 
@@ -1574,7 +1580,7 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
                 volumeMgr.release(profile);
                 s_logger.debug("Successfully released storage resources for 
the vm " + vm);
             }
-        } catch (Exception e) {
+        } catch (final Exception e) {
             s_logger.warn("Unable to release storage resources.", e);
         }
 
@@ -1590,7 +1596,7 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
             if (!stateTransitTo(vm, Event.OperationSucceeded, null)) {
                 throw new CloudRuntimeException("unable to stop " + vm);
             }
-        } catch (NoTransitionException e) {
+        } catch (final NoTransitionException e) {
             s_logger.warn(e.getMessage());
             throw new CloudRuntimeException("Unable to stop " + vm);
         }
@@ -1600,7 +1606,7 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
         _stateMachine = VirtualMachine.State.getStateMachine();
     }
 
-    protected boolean stateTransitTo(VMInstanceVO vm, VirtualMachine.Event e, 
Long hostId, String reservationId) throws NoTransitionException {
+    protected boolean stateTransitTo(final VMInstanceVO vm, final 
VirtualMachine.Event e, final Long hostId, final String reservationId) throws 
NoTransitionException {
         // if there are active vm snapshots task, state change is not allowed
 
         // Disable this hacking thing, VM snapshot task need to be managed by 
its orchestartion flow istelf instead of
@@ -1610,14 +1616,14 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
                     s_logger.error("State transit with event: " + e + " failed 
due to: " + vm.getInstanceName() + " has active VM snapshots tasks");
                     return false;
                 }
-        */
+         */
         vm.setReservationId(reservationId);
         return _stateMachine.transitTo(vm, e, new Pair<Long, 
Long>(vm.getHostId(), hostId), _vmDao);
     }
 
     @Override
-    public boolean stateTransitTo(VirtualMachine vm1, VirtualMachine.Event e, 
Long hostId) throws NoTransitionException {
-        VMInstanceVO vm = (VMInstanceVO)vm1;
+    public boolean stateTransitTo(final VirtualMachine vm1, final 
VirtualMachine.Event e, final Long hostId) throws NoTransitionException {
+        final VMInstanceVO vm = (VMInstanceVO)vm1;
 
         /*
          *  Remove the hacking logic here.
@@ -1626,9 +1632,9 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
                     s_logger.error("State transit with event: " + e + " failed 
due to: " + vm.getInstanceName() + " has active VM snapshots tasks");
                     return false;
                 }
-        */
+         */
 
-        State oldState = vm.getState();
+        final State oldState = vm.getState();
         if (oldState == State.Starting) {
             if (e == Event.OperationSucceeded) {
                 vm.setLastHostId(hostId);
@@ -1642,7 +1648,7 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
     }
 
     @Override
-    public void destroy(String vmUuid) throws AgentUnavailableException, 
OperationTimedoutException, ConcurrentOperationException {
+    public void destroy(final String vmUuid) throws AgentUnavailableException, 
OperationTimedoutException, ConcurrentOperationException {
         VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
         if (vm == null || vm.getState() == State.Destroyed || vm.getState() == 
State.Expunging || vm.getRemoved() != null) {
             if (s_logger.isDebugEnabled()) {
@@ -1669,19 +1675,19 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
                 s_logger.debug("Unable to destroy the vm because it is not in 
the correct state: " + vm);
                 throw new CloudRuntimeException("Unable to destroy " + vm);
             }
-        } catch (NoTransitionException e) {
+        } catch (final NoTransitionException e) {
             s_logger.debug(e.getMessage());
             throw new CloudRuntimeException("Unable to destroy " + vm, e);
         }
     }
 
-    protected boolean checkVmOnHost(VirtualMachine vm, long hostId) throws 
AgentUnavailableException, OperationTimedoutException {
-        Answer answer = _agentMgr.send(hostId, new 
CheckVirtualMachineCommand(vm.getInstanceName()));
+    protected boolean checkVmOnHost(final VirtualMachine vm, final long 
hostId) throws AgentUnavailableException, OperationTimedoutException {
+        final Answer answer = _agentMgr.send(hostId, new 
CheckVirtualMachineCommand(vm.getInstanceName()));
         if (answer == null || !answer.getResult()) {
             return false;
         }
         if (answer instanceof CheckVirtualMachineAnswer) {
-            CheckVirtualMachineAnswer vmAnswer = 
(CheckVirtualMachineAnswer)answer;
+            final CheckVirtualMachineAnswer vmAnswer = 
(CheckVirtualMachineAnswer)answer;
             if (vmAnswer.getState() == PowerState.PowerOff) {
                 return false;
             }
@@ -1691,12 +1697,12 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
     }
 
     @Override
-    public void storageMigration(String vmUuid, StoragePool destPool) {
-        AsyncJobExecutionContext jobContext = 
AsyncJobExecutionContext.getCurrentExecutionContext();
+    public void storageMigration(final String vmUuid, final StoragePool 
destPool) {
+        final AsyncJobExecutionContext jobContext = 
AsyncJobExecutionContext.getCurrentExecutionContext();
         if 
(jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
             // avoid re-entrance
             VmWorkJobVO placeHolder = null;
-            VirtualMachine vm = _vmDao.findByUuid(vmUuid);
+            final VirtualMachine vm = _vmDao.findByUuid(vmUuid);
             placeHolder = createPlaceHolderWork(vm.getId());
             try {
                 orchestrateStorageMigration(vmUuid, destPool);
@@ -1706,40 +1712,41 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
                 }
             }
         } else {
-            Outcome<VirtualMachine> outcome = 
migrateVmStorageThroughJobQueue(vmUuid, destPool);
+            final Outcome<VirtualMachine> outcome = 
migrateVmStorageThroughJobQueue(vmUuid, destPool);
 
             try {
-                VirtualMachine vm = outcome.get();
-            } catch (InterruptedException e) {
+                final VirtualMachine vm = outcome.get();
+            } catch (final InterruptedException e) {
                 throw new RuntimeException("Operation is interrupted", e);
-            } catch (java.util.concurrent.ExecutionException e) {
+            } catch (final java.util.concurrent.ExecutionException e) {
                 throw new RuntimeException("Execution excetion", e);
             }
 
-            Object jobResult = 
_jobMgr.unmarshallResultObject(outcome.getJob());
+            final Object jobResult = 
_jobMgr.unmarshallResultObject(outcome.getJob());
             if (jobResult != null) {
-                if (jobResult instanceof RuntimeException)
+                if (jobResult instanceof RuntimeException) {
                     throw (RuntimeException)jobResult;
-                else if (jobResult instanceof Throwable)
+                } else if (jobResult instanceof Throwable) {
                     throw new RuntimeException("Unexpected exception", 
(Throwable)jobResult);
+                }
             }
         }
     }
 
-    private void orchestrateStorageMigration(String vmUuid, StoragePool 
destPool) {
-        VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
-        Long srchostId = vm.getHostId() != null ? vm.getHostId() : 
vm.getLastHostId();
-        HostVO srcHost = _hostDao.findById(srchostId);
-        Long srcClusterId = srcHost.getClusterId();
+    private void orchestrateStorageMigration(final String vmUuid, final 
StoragePool destPool) {
+        final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
+        final Long srchostId = vm.getHostId() != null ? vm.getHostId() : 
vm.getLastHostId();
+        final HostVO srcHost = _hostDao.findById(srchostId);
+        final Long srcClusterId = srcHost.getClusterId();
 
         try {
             stateTransitTo(vm, VirtualMachine.Event.StorageMigrationRequested, 
null);
-        } catch (NoTransitionException e) {
+        } catch (final NoTransitionException e) {
             s_logger.debug("Unable to migrate vm: " + e.toString());
             throw new CloudRuntimeException("Unable to migrate vm: " + 
e.toString());
         }
 
-        VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
+        final VirtualMachineProfile profile = new 
VirtualMachineProfileImpl(vm);
         boolean migrationResult = false;
         try {
             migrationResult = volumeMgr.storageMigration(profile, destPool);
@@ -1748,8 +1755,8 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
                 //if the vm is migrated to different pod in basic mode, need 
to reallocate ip
 
                 if (!vm.getPodIdToDeployIn().equals(destPool.getPodId())) {
-                    DataCenterDeployment plan = new 
DataCenterDeployment(vm.getDataCenterId(), destPool.getPodId(), null, null, 
null, null);
-                    VirtualMachineProfileImpl vmProfile = new 
VirtualMachineProfileImpl(vm, null, null, null, null);
+                    final DataCenterDeployment plan = new 
DataCenterDeployment(vm.getDataCenterId(), destPool.getPodId(), null, null, 
null, null);
+                    final VirtualMachineProfileImpl vmProfile = new 
VirtualMachineProfileImpl(vm, null, null, null, null);
                     _networkMgr.reallocate(vmProfile, plan);
                 }
 
@@ -1760,18 +1767,18 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
                 // If VM was cold migrated between clusters belonging to two 
different VMware DCs,
                 // unregister the VM from the source host and cleanup the 
associated VM files.
                 if (vm.getHypervisorType().equals(HypervisorType.VMware)) {
-                    Long destClusterId = destPool.getClusterId();
+                    final Long destClusterId = destPool.getClusterId();
                     if (srcClusterId != null && destClusterId != null && 
srcClusterId != destClusterId) {
-                        String srcDcName = 
_clusterDetailsDao.getVmwareDcName(srcClusterId);
-                        String destDcName = 
_clusterDetailsDao.getVmwareDcName(destClusterId);
+                        final String srcDcName = 
_clusterDetailsDao.getVmwareDcName(srcClusterId);
+                        final String destDcName = 
_clusterDetailsDao.getVmwareDcName(destClusterId);
                         if (srcDcName != null && destDcName != null && 
!srcDcName.equals(destDcName)) {
                             s_logger.debug("Since VM's storage was 
successfully migrated across VMware Datacenters, unregistering VM: " + 
vm.getInstanceName() +
                                     " from source host: " + srcHost.getId());
-                            UnregisterVMCommand uvc = new 
UnregisterVMCommand(vm.getInstanceName());
+                            final UnregisterVMCommand uvc = new 
UnregisterVMCommand(vm.getInstanceName());
                             uvc.setCleanupVmFiles(true);
                             try {
                                 _agentMgr.send(srcHost.getId(), uvc);
-                            } catch (Exception e) {
+                            } catch (final Exception e) {
                                 throw new CloudRuntimeException("Failed to 
unregister VM: " + vm.getInstanceName() + " from source host: " + 
srcHost.getId() +
                                         " after successfully migrating VM's 
storage across VMware Datacenters");
                             }
@@ -1782,25 +1789,25 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
             } else {
                 s_logger.debug("Storage migration failed");
             }
-        } catch (ConcurrentOperationException e) {
+        } catch (final ConcurrentOperationException e) {
             s_logger.debug("Failed to migration: " + e.toString());
             throw new CloudRuntimeException("Failed to migration: " + 
e.toString());
-        } catch (InsufficientVirtualNetworkCapacityException e) {
+        } catch (final InsufficientVirtualNetworkCapacityException e) {
             s_logger.debug("Failed to migration: " + e.toString());
             throw new CloudRuntimeException("Failed to migration: " + 
e.toString());
-        } catch (InsufficientAddressCapacityException e) {
+        } catch (final InsufficientAddressCapacityException e) {
             s_logger.debug("Failed to migration: " + e.toString());
             throw new CloudRuntimeException("Failed to migration: " + 
e.toString());
-        } catch (InsufficientCapacityException e) {
+        } catch (final InsufficientCapacityException e) {
             s_logger.debug("Failed to migration: " + e.toString());
             throw new CloudRuntimeException("Failed to migration: " + 
e.toString());
-        } catch (StorageUnavailableException e) {
+        } catch (final StorageUnavailableException e) {
             s_logger.debug("Failed to migration: " + e.toString());
             throw new CloudRuntimeException("Failed to migration: " + 
e.toString());
         } finally {
             try {
                 stateTransitTo(vm, VirtualMachine.Event.AgentReportStopped, 
null);
-            } catch (NoTransitionException e) {
+            } catch (final NoTransitionException e) {
                 s_logger.debug("Failed to change vm state: " + e.toString());
                 throw new CloudRuntimeException("Failed to change vm state: " 
+ e.toString());
             }
@@ -1808,14 +1815,14 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
     }
 
     @Override
-    public void migrate(String vmUuid, long srcHostId, DeployDestination dest)
+    public void migrate(final String vmUuid, final long srcHostId, final 
DeployDestination dest)
             throws ResourceUnavailableException, ConcurrentOperationException {
 
-        AsyncJobExecutionContext jobContext = 
AsyncJobExecutionContext.getCurrentExecutionContext();
+        final AsyncJobExecutionContext jobContext = 
AsyncJobExecutionContext.getCurrentExecutionContext();
         if 
(jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
             // avoid re-entrance
             VmWorkJobVO placeHolder = null;
-            VirtualMachine vm = _vmDao.findByUuid(vmUuid);
+            final VirtualMachine vm = _vmDao.findByUuid(vmUuid);
             placeHolder = createPlaceHolderWork(vm.getId());
             try {
                 orchestrateMigrate(vmUuid, srcHostId, dest);
@@ -1825,33 +1832,34 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
                 }
             }
         } else {
-            Outcome<VirtualMachine> outcome = migrateVmThroughJobQueue(vmUuid, 
srcHostId, dest);
+            final Outcome<VirtualMachine> outcome = 
migrateVmThroughJobQueue(vmUuid, srcHostId, dest);
 
             try {
-                VirtualMachine vm = outcome.get();
-            } catch (InterruptedException e) {
+                final VirtualMachine vm = outcome.get();
+            } catch (final InterruptedException e) {
                 throw new RuntimeException("Operation is interrupted", e);
-            } catch (java.util.concurrent.ExecutionException e) {
+            } catch (final java.util.concurrent.ExecutionException e) {
                 throw new RuntimeException("Execution excetion", e);
             }
 
-            Object jobResult = 
_jobMgr.unmarshallResultObject(outcome.getJob());
+            final Object jobResult = 
_jobMgr.unmarshallResultObject(outcome.getJob());
             if (jobResult != null) {
-                if (jobResult instanceof ResourceUnavailableException)
+                if (jobResult instanceof ResourceUnavailableException) {
                     throw (ResourceUnavailableException)jobResult;
-                else if (jobResult instanceof ConcurrentOperationException)
+                } else if (jobResult instanceof ConcurrentOperationException) {
                     throw (ConcurrentOperationException)jobResult;
-                else if (jobResult instanceof RuntimeException)
+                } else if (jobResult instanceof RuntimeException) {
                     throw (RuntimeException)jobResult;
-                else if (jobResult instanceof Throwable)
+                } else if (jobResult instanceof Throwable) {
                     throw new RuntimeException("Unexpected exception", 
(Throwable)jobResult);
+                }
 
             }
         }
     }
 
-    private void orchestrateMigrate(String vmUuid, long srcHostId, 
DeployDestination dest) throws ResourceUnavailableException, 
ConcurrentOperationException {
-        VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
+    private void orchestrateMigrate(final String vmUuid, final long srcHostId, 
final DeployDestination dest) throws ResourceUnavailableException, 
ConcurrentOperationException {
+        final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
         if (vm == null) {
             if (s_logger.isDebugEnabled()) {
                 s_logger.debug("Unable to find the vm " + vmUuid);
@@ -1861,20 +1869,20 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
         migrate(vm, srcHostId, dest);
     }
 
-    protected void migrate(VMInstanceVO vm, long srcHostId, DeployDestination 
dest) throws ResourceUnavailableException, ConcurrentOperationException {
+    protected void migrate(final VMInstanceVO vm, final long srcHostId, final 
DeployDestination dest) throws ResourceUnavailableException, 
ConcurrentOperationException {
         s_logger.info("Migrating " + vm + " to " + dest);
 
-        long dstHostId = dest.getHost().getId();
-        Host fromHost = _hostDao.findById(srcHostId);
+        final long dstHostId = dest.getHost().getId();
+        final Host fromHost = _hostDao.findById(srcHostId);
         if (fromHost == null) {
             s_logger.info("Unable to find the host to migrate from: " + 
srcHostId);
             throw new CloudRuntimeException("Unable to find the host to 
migrate from: " + srcHostId);
         }
 
         if (fromHost.getClusterId().longValue() != dest.getCluster().getId()) {
-            List<VolumeVO> volumes = 
_volsDao.findCreatedByInstance(vm.getId());
-            for (VolumeVO volume : volumes) {
-                if 
(!(_storagePoolDao.findById(volume.getPoolId())).getScope().equals(ScopeType.ZONE))
 {
+            final List<VolumeVO> volumes = 
_volsDao.findCreatedByInstance(vm.getId());
+            for (final VolumeVO volume : volumes) {
+                if 
(!_storagePoolDao.findById(volume.getPoolId()).getScope().equals(ScopeType.ZONE))
 {
                     s_logger.info("Source and destination host are not in same 
cluster and all volumes are not on zone wide primary store, unable to migrate 
to host: "
                             + dest.getHost().getId());
                     throw new CloudRuntimeException(
@@ -1884,7 +1892,7 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
             }
         }
 
-        VirtualMachineGuru vmGuru = getVmGuru(vm);
+        final VirtualMachineGuru vmGuru = getVmGuru(vm);
 
         if (vm.getState() != State.Running) {
             if (s_logger.isDebugEnabled()) {
@@ -1900,17 +1908,17 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
             alertType = 
AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY_MIGRATE;
         }
 
-        VirtualMachineProfile vmSrc = new VirtualMachineProfileImpl(vm);
-        for (NicProfile nic : _networkMgr.getNicProfiles(vm)) {
+        final VirtualMachineProfile vmSrc = new VirtualMachineProfileImpl(vm);
+        for (final NicProfile nic : _networkMgr.getNicProfiles(vm)) {
             vmSrc.addNic(nic);
         }
 
-        VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm, 
null, _offeringDao.findById(vm.getId(), vm.getServiceOfferingId()), null, null);
+        final VirtualMachineProfile profile = new 
VirtualMachineProfileImpl(vm, null, _offeringDao.findById(vm.getId(), 
vm.getServiceOfferingId()), null, null);
         _networkMgr.prepareNicForMigration(profile, dest);
         volumeMgr.prepareForMigration(profile, dest);
 
-        VirtualMachineTO to = toVmTO(profile);
-        PrepareForMigrationCommand pfmc = new PrepareForMigrationCommand(to);
+        final VirtualMachineTO to = toVmTO(profile);
+        final PrepareForMigrationCommand pfmc = new 
PrepareForMigrationCommand(to);
 
         ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, 
State.Migrating, vm.getType(), vm.getId());
         work.setStep(Step.Prepare);
@@ -1922,12 +1930,12 @@ public class VirtualMachineManagerImpl extends 
ManagerBase implements VirtualMac
         try {
             pfma = _agentMgr.send(dstHostId, pfmc);
             if (pfma == null || !pfma.getResult()) {
-                String details = (pfma != null) ? pfma.getDetails() : "null 
answer returned";
-                String msg = "Unable to prepare for migration due to " + 
details;
+                final String details = pfma != null ? pfma.getDetails() : 
"null answer returned";
+                final String msg = "Unable to prepare for migration due to " + 
details;
                 pfma = null;
                 throw new AgentUnavailableException(msg, dstHostId);
             }
-  

<TRUNCATED>

Reply via email to