Projects >> floodlight >>441d120e80ba69666c12d2d4a6a63f5317126ae8

Chunk
Conflicting content
import net.floodlightcontroller.packet.DHCP;
import net.floodlightcontroller.packet.Ethernet;
import net.floodlightcontroller.packet.IPv4;
<<<<<<< HEAD
import net.floodlightcontroller.packet.UDP;
import net.floodlightcontroller.restserver.IRestApiService;
=======
import net.floodlightcontroller.restserver.IRestApiService;
import net.floodlightcontroller.routing.ForwardingBase;
import net.floodlightcontroller.storage.IResultSet;
import net.floodlightcontroller.storage.IStorageSourceListener;
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
import net.floodlightcontroller.storage.IStorageSourceService;
import net.floodlightcontroller.storage.IStorageSourceListener;
import net.floodlightcontroller.threadpool.IThreadPoolService;
Solution content
import net.floodlightcontroller.packet.DHCP;
import net.floodlightcontroller.packet.Ethernet;
import net.floodlightcontroller.packet.IPv4;
import net.floodlightcontroller.packet.UDP;
import net.floodlightcontroller.restserver.IRestApiService;
import net.floodlightcontroller.storage.IStorageSourceService;
import net.floodlightcontroller.storage.IStorageSourceListener;
import net.floodlightcontroller.threadpool.IThreadPoolService;
File
DeviceManagerImpl.java
Developer's decision
Version 1
Kind of conflict
Import
Chunk
Conflicting content
 * within the network.
 * @author readams
 */
<<<<<<< HEAD
public class DeviceManagerImpl implements 
        IDeviceService, IOFMessageListener,
        IStorageSourceListener, IFloodlightModule,
        IInfoProvider {  
    protected static Logger logger = 
        LoggerFactory.getLogger(DeviceManagerImpl.class);

    protected IFloodlightProviderService floodlightProvider;
    protected ITopologyService topology;
    protected IStorageSourceService storageSource;
    protected IRestApiService restApi;
    protected IThreadPoolService threadPool;
    
=======
public class DeviceManagerImpl implements IDeviceManagerService, IOFMessageListener,
        IOFSwitchListener, ILinkDiscoveryListener, IFloodlightModule, IStorageSourceListener,
        ITopologyListener, IInfoProvider {

>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
    /**
     * Time in milliseconds before entities will expire
     */
Solution content
 * within the network.
 * @author readams
 */
public class DeviceManagerImpl implements 
        IDeviceService, IOFMessageListener,
        IStorageSourceListener, IFloodlightModule,
        IInfoProvider {  
    protected static Logger logger = 
        LoggerFactory.getLogger(DeviceManagerImpl.class);

    protected IFloodlightProviderService floodlightProvider;
    protected ITopologyService topology;
    protected IStorageSourceService storageSource;
    protected IRestApiService restApi;
    protected IThreadPoolService threadPool;
    
    /**
     * Time in milliseconds before entities will expire
     */
File
DeviceManagerImpl.java
Developer's decision
Version 1
Kind of conflict
Attribute
Class signature
Method invocation
Chunk
Conflicting content
         * Allocate a new {@link ClassState} object for the class
         * @param clazz the class to use for the state
         */
<<<<<<< HEAD
        public ClassState(IEntityClass clazz) {
            EnumSet keyFields = clazz.getKeyFields();
            EnumSet primaryKeyFields = 
                    entityClassifier.getKeyFields();
            boolean keyFieldsMatchPrimary = 
                    primaryKeyFields.equals(keyFields);
            
            if (!keyFieldsMatchPrimary)
                classIndex = new DeviceUniqueIndex(keyFields);
            
            secondaryIndexMap = 
                    new HashMap, DeviceIndex>();
            for (EnumSet fields : perClassIndices) {
                secondaryIndexMap.put(fields, 
                                      new DeviceMultiIndex(fields));
=======
        protected void removeSwPort(SwitchPortTuple swPrt) {

            Map switchPortDevices = 
                                            switchPortDeviceMap.remove(swPrt);

            if (switchPortDevices == null) {
                return;
            }

            // Update the individual devices by updating its attachment points
            for (Device d : switchPortDevices.values()) {
                // Remove the device from the switch->device mapping
                delDevAttachmentPoint(d.getDataLayerAddressAsLong(), swPrt);
                evHistAttachmtPt(d.getDataLayerAddressAsLong(), swPrt, EvAction.REMOVED,
                                                        "SwitchPort removed");
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
            }
        }
    }
Solution content
         * Allocate a new {@link ClassState} object for the class
         * @param clazz the class to use for the state
         */
        public ClassState(IEntityClass clazz) {
            EnumSet keyFields = clazz.getKeyFields();
            EnumSet primaryKeyFields = 
                    entityClassifier.getKeyFields();
            boolean keyFieldsMatchPrimary = 
                    primaryKeyFields.equals(keyFields);
            
            if (!keyFieldsMatchPrimary)
                classIndex = new DeviceUniqueIndex(keyFields);
            
            secondaryIndexMap = 
                    new HashMap, DeviceIndex>();
            for (EnumSet fields : perClassIndices) {
                secondaryIndexMap.put(fields, 
                                      new DeviceMultiIndex(fields));
            }
        }
    }
File
DeviceManagerImpl.java
Developer's decision
Version 1
Kind of conflict
Attribute
Comment
For statement
If statement
Method invocation
Method signature
Variable
Chunk
Conflicting content
=======
        /**
         * The change that was made
         */
<<<<<<< HEAD
        protected Change change;
        protected void delNwAddrByDataLayerAddr(long dlAddr,
                                                int nwAddr) {
            Device d = getDeviceByDataLayerAddr(dlAddr);
            if (d == null) return;
            Device dCopy = new Device(d);
            DeviceNetworkAddress na = dCopy.getNetworkAddress(nwAddr);
            
            if (na != null) {
                delFromIpv4AddressDeviceMap(nwAddr, d);
                dCopy.removeNetworkAddress(na);
                updateMaps(dCopy);
                removeNetworkAddressFromStorage(d.getDlAddrString(), na);
            }
        }
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
        
        /**
         * If not added, then this is the list of fields changed
Solution content
        /**
         * The change that was made
         */
        protected Change change;
        
        /**
         * If not added, then this is the list of fields changed
File
DeviceManagerImpl.java
Developer's decision
Version 1
Kind of conflict
Attribute
Method declaration
Chunk
Conflicting content
                                             switchPort, null));
    }

<<<<<<< HEAD
    @Override
    public IDevice findDestDevice(IDevice source, long macAddress,
                                  Short vlan, Integer ipv4Address) {
        if (vlan != null && vlan.shortValue() <= 0)
            vlan = null;
        if (ipv4Address != null && ipv4Address == 0)
            ipv4Address = null;
        return findDestByEntity(source,
                                new Entity(macAddress, 
                                           vlan, 
                                           ipv4Address, 
                                           null, 
                                           null,
                                           null));
    }
=======
        /**
         * Delete an attachment point from a device
         * @param d the device
         * @param swPort the {@link SwitchPortTuple} to remove
         */
        protected void delDevAttachmentPoint(long dlAddr, SwitchPortTuple swPort) {
            delDevAttachmentPoint(devMgrMaps.getDeviceByDataLayerAddr(dlAddr), 
                swPort.getSw(), swPort.getPort());
        }
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f

    @Override
    public Collection getAllDevices() {
Solution content
                                             switchPort, null));
    }

    @Override
    public IDevice findDestDevice(IDevice source, long macAddress,
                                  Short vlan, Integer ipv4Address) {
        if (vlan != null && vlan.shortValue() <= 0)
            vlan = null;
        if (ipv4Address != null && ipv4Address == 0)
            ipv4Address = null;
        return findDestByEntity(source,
                                new Entity(macAddress, 
                                           vlan, 
                                           ipv4Address, 
                                           null, 
                                           null,
                                           null));
    }

    @Override
    public Collection getAllDevices() {
File
DeviceManagerImpl.java
Developer's decision
Version 1
Kind of conflict
Annotation
Comment
Method declaration
Chunk
Conflicting content
        return Collections.unmodifiableCollection(deviceMap.values());
    }

<<<<<<< HEAD
    @Override
    public void addIndex(boolean perClass,
                         EnumSet keyFields) {
        if (perClass) {
            perClassIndices.add(keyFields);
        } else {
            secondaryIndexMap.put(keyFields, 
                                  new DeviceMultiIndex(keyFields));
=======
            // Make a copy of this device
            Device dCopy = new Device(d);
            DeviceAttachmentPoint dap = dCopy.removeAttachmentPoint(swPort);
            // Remove the original device from the Switch-port map
            // This is a no-op when this fn is called from removeSwPort
            // as the switch-pot itself would be deleted from the map 
            delFromSwitchPortDeviceMap(swPort, d);
            // Remove the original device from the Switch map
            delFromSwitchDeviceMap(sw, d);  
            // Now add this updated device to the maps, which will replace
            // the old copy
            updateMaps(dCopy);
            if (log.isDebugEnabled()) {
                log.debug("Remove AP {} post {} prev {} for Device {}", 
                          new Object[] {dap, dCopy.getAttachmentPoints().size(),
                                        d.getAttachmentPoints().size(), dCopy});
            }
            removeAttachmentPointFromStorage(d.getDlAddrString(),
                    HexString.toHexString(dap.getSwitchPort().getSw().getId()),
                    dap.getSwitchPort().getPort().toString());
            d = null;
            return true;
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
        }
    }
Solution content
        return Collections.unmodifiableCollection(deviceMap.values());
    }

    @Override
    public void addIndex(boolean perClass,
                         EnumSet keyFields) {
        if (perClass) {
            perClassIndices.add(keyFields);
        } else {
            secondaryIndexMap.put(keyFields, 
                                  new DeviceMultiIndex(keyFields));
        }
    }
File
DeviceManagerImpl.java
Developer's decision
Version 1
Kind of conflict
Annotation
Comment
If statement
Method invocation
Method signature
Return statement
Variable
Chunk
Conflicting content
    }

<<<<<<< HEAD
    @Override
        return new MultiIterator(iterators.iterator());
    public void addListener(IDeviceListener listener) {
        deviceListeners.add(listener);
    }

    @Override
    public void setEntityClassifier(IEntityClassifier classifier) {
        entityClassifier = classifier;
    }
=======
    // Our dependencies
    protected IFloodlightProviderService floodlightProvider;
    protected ILinkDiscoveryService linkDiscovery;
    protected ITopologyService topology;
    protected IStorageSourceService storageSource;
    protected IThreadPoolService threadPool;
    protected IRestApiService restApi;

    protected Runnable deviceAgingTimer;
    protected SingletonTask deviceUpdateTask;
    protected Date previousStorageAudit;

    protected static int DEVICE_MAX_AGE    = 60 * 60 * 24;
    protected static int DEVICE_NA_MAX_AGE = 60 * 60 *  2;
    protected static int DEVICE_AP_MAX_AGE = 60 * 60 *  2;
    protected static long NBD_TO_BD_TIMEDIFF_MS = 300000; // 5 minutes
    protected static long BD_TO_BD_TIMEDIFF_MS = 5000; // 5 seconds
    // This the amount of time that we need for a device to move from
    // a non-broadcast domain port to a broadcast domain port.

    // Constants for accessing storage
    // Table names
    private static final String DEVICE_TABLE_NAME = "controller_host";
    private static final String DEVICE_ATTACHMENT_POINT_TABLE_NAME = 
                                            "controller_hostattachmentpoint";
    private static final String DEVICE_NETWORK_ADDRESS_TABLE_NAME = 
                                            "controller_hostnetworkaddress";
    protected static final String PORT_CHANNEL_TABLE_NAME = "controller_portchannelconfig";
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
    
    @Override
    public void flushEntityCache(IEntityClass entityClass, 
Solution content
        return new MultiIterator(iterators.iterator());
    }

    @Override
    public void addListener(IDeviceListener listener) {
        deviceListeners.add(listener);
    }

    @Override
    public void setEntityClassifier(IEntityClassifier classifier) {
        entityClassifier = classifier;
    }
    
    @Override
    public void flushEntityCache(IEntityClass entityClass, 
File
DeviceManagerImpl.java
Developer's decision
Version 1
Kind of conflict
Annotation
Attribute
Comment
Method declaration
Chunk
Conflicting content
        }



        // Add this packet-in to event history
        return m;
    }

<<<<<<< HEAD
    @Override
    public Collection> getModuleDependencies() {
        Collection> l =
                new ArrayList>();
        l.add(IFloodlightProviderService.class);
        l.add(IStorageSourceService.class);
        l.add(ITopologyService.class);
        l.add(IRestApiService.class);
        l.add(IThreadPoolService.class);
        return l;
    }
=======
    /**
     * This method is called for every packet-in and should be optimized for
     * performance.
     * @param sw
     * @param pi
     * @param cntx
     * @return
     */
    public Command processPacketInMessage(IOFSwitch sw, OFPacketIn pi, 
                                          FloodlightContext cntx) {

        Ethernet eth = IFloodlightProviderService.bcStore.get(
                    cntx, IFloodlightProviderService.CONTEXT_PI_PAYLOAD);
        /** If a broadcast or multicast packetIn comes from a port that's not allowed by higher
         *  level topology, it should be dropped.
         *  If it is an unicast packetIn, let it go through. This is the case when the broadcast
         *  domain where the unicast packet originated learned the dst device on the wrong port.
         *  Hopefully, the response from dst device will correct the learning of the BD.
         */
        short pinPort = pi.getInPort();
        long pinSw = sw.getId();
        if (topology.isAllowed(pinSw, pinPort) == false) {
            if (eth.getEtherType() == Ethernet.TYPE_BDDP ||
                (eth.isBroadcast() == false && eth.isMulticast() == false)) {
                return Command.CONTINUE;
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("deviceManager: Stopping packet as it is coming" +
                            "in on a port blocked by higher layer on." +
                            "switch ={}, port={}", new Object[] {sw.getStringId(), pinPort});
                }
                return Command.STOP;
            }
                }
            }
        Command ret = Command.CONTINUE;
        OFMatch match = new OFMatch();
        match.loadFromPacket(pi.getPacketData(), pi.getInPort(), sw.getId());
        evHistPktIn(match);
        if (log.isDebugEnabled())
            log.debug("Entering packet_in processing sw {}, port {}. {} --> {}, type {}",
                      new Object[] { sw.getStringId(), pi.getInPort(), 
                               HexString.toHexString(match.getDataLayerSource()),
                               HexString.toHexString(match.getDataLayerDestination()),
                               match.getDataLayerType()
                      });

        /**
         * Drop all broadcast and multicast packets from not-allowed incoming broadcast ports
         */
        if ((eth.isBroadcast() || eth.isMulticast()) &&
            !topology.isIncomingBroadcastAllowed(pinSw, pinPort)) {
            if (log.isDebugEnabled()) {
                log.debug("Drop broadcast/multicast packets with src {} from not-allowed incoming broadcast ports {} {}",
                        new Object[] {HexString.toHexString(eth.getSourceMACAddress()),
                        HexString.toHexString(pinSw), pinPort});
            }
            return Command.STOP;
        }

        // Create attachment point/update network address if required
        SwitchPortTuple switchPort = new SwitchPortTuple(sw, pi.getInPort());
        // Don't learn from internal port or invalid port
        if (topology.isInternal(switchPort.getSw().getId(), switchPort.getPort()) || 
                !isValidInputPort(switchPort.getPort())) {
            processUpdates();
            return Command.CONTINUE;
        }

        // Packet arrive at a port from where we can learn the device
        // if the source is multicast/broadcast ignore it
        if ((match.getDataLayerSource()[0] & 0x1) != 0) {
            return Command.CONTINUE;
        }

        Long dlAddr = Ethernet.toLong(match.getDataLayerSource());
        Short vlan = match.getDataLayerVirtualLan();
        if (vlan < 0) vlan = null;
        int nwSrc = getSrcNwAddr(eth, dlAddr);
        Device device = devMgrMaps.getDeviceByDataLayerAddr(dlAddr);
        if (log.isTraceEnabled()) {
            long dstAddr = Ethernet.toLong(match.getDataLayerDestination());
            Device dstDev = devMgrMaps.getDeviceByDataLayerAddr(dstAddr);
            if (device != null)
                log.trace("    Src.AttachmentPts: {}", device.getAttachmentPointsMap().keySet());
            if (dstDev != null)
                log.trace("    Dst.AttachmentPts: {}", dstDev.getAttachmentPointsMap().keySet());
        }
        Date currentDate = new Date(); 
        if (device != null) { 
            // Write lock is expensive, check if we have an update first
            boolean newAttachmentPoint = false;
            boolean newNetworkAddress = false;
            boolean updateAttachmentPointLastSeen = false;
            boolean updateNetworkAddressLastSeen = false;
            boolean updateNeworkAddressMap = false;
            boolean updateDeviceVlan = false;
            boolean clearAttachmentPoints = false;
            boolean updateDevice = false;

            DeviceAttachmentPoint attachmentPoint = null;
            DeviceNetworkAddress networkAddress = null;

            // Copy-replace of device would be too expensive here
            device.setLastSeen(currentDate);
            updateDevice = device.shouldWriteLastSeenToStorage();
            
            if (isGratArp(eth)) {
                clearAttachmentPoints = true;
            }

            attachmentPoint = device.getAttachmentPoint(switchPort);
            if (attachmentPoint != null) {
                updateAttachmentPointLastSeen = true;
            } else {
                newAttachmentPoint = true;
                if ((eth.isBroadcast() || eth.isMulticast()) &&
                    topology.isIncomingBroadcastAllowed(pinSw, pinPort) == false) {
                    if (log.isDebugEnabled()) {
                        log.debug("Port {} {} is not allowed for incoming broadcast packet",
                                  HexString.toHexString(pinSw), pinPort);
                    }
                    newAttachmentPoint = false;
            if (nwSrc != 0) {
                networkAddress = device.getNetworkAddress(nwSrc);
                if (networkAddress != null) {
                    updateNetworkAddressLastSeen = true;
                } else if (eth != null && (eth.getPayload() instanceof ARP)) {
                    /** MAC-IP association should be learnt from both ARP request and reply.
                     *  Since a host learns some other host's mac to ip mapping after receiving 
                     *  an ARP request from the host.
                     *  
                     *  However, device's MAC-IP mapping could be wrong if a host sends a ARP request with
                     *  an IP other than its own. Unfortunately, there isn't an easy way to allow both learning
                     *  and prevent incorrect learning.
                     */
                    networkAddress = new DeviceNetworkAddress(nwSrc, 
                                                            currentDate);
                    newNetworkAddress = true;
                }

                // Also, if this address is currently mapped to a different 
                // device, fix it. This should be rare, so it is OK to do update
                // the storage from here.
                //
                // NOTE: the mapping is observed, and the decision is made based
                // on that, outside a lock. So the state may change by the time 
                // we get to do the map update. But that is OK since the mapping
                // will eventually get consistent.
                Device deviceByNwaddr = this.getDeviceByIPv4Address(nwSrc);
                if ((deviceByNwaddr != null) &&
                    (deviceByNwaddr.getDataLayerAddressAsLong() != 
                                    device.getDataLayerAddressAsLong())) {
                    updateNeworkAddressMap = true;
                    Device dCopy = new Device(deviceByNwaddr);
                    DeviceNetworkAddress naOld = dCopy.getNetworkAddress(nwSrc);
                    Map namap = 
                                                dCopy.getNetworkAddressesMap();
                    if (namap.containsKey(nwSrc)) namap.remove(nwSrc);
                    dCopy.setNetworkAddresses(namap.values());
                    this.devMgrMaps.updateMaps(dCopy);
                    if (naOld !=null) 
                        removeNetworkAddressFromStorage(dCopy.getDlAddrString(), naOld);
                }

            }
            if ((vlan == null && device.getVlanId() != null) ||
                    (vlan != null && !vlan.equals(device.getVlanId()))) {
                updateDeviceVlan = true;
            }

            if (newAttachmentPoint || newNetworkAddress || updateDeviceVlan || 
                                updateNeworkAddressMap) {

                Device nd = new Device(device);

                try {
                    // Check if we have seen this attachmentPoint recently,
                    // An exception is thrown if the attachmentPoint is blocked.
                    if (newAttachmentPoint) {
                        attachmentPoint = getNewAttachmentPoint(nd, switchPort);
                        if (attachmentPoint == null) {
                            newAttachmentPoint = false;
                        } else {
                            if (log.isDebugEnabled()) {
                                log.debug("Learned new AP for device {} at {}",
                                        HexString.toHexString(nd.getDataLayerAddressAsLong()),
                                        attachmentPoint);
                            }
                            nd.addAttachmentPoint(attachmentPoint);
                            evHistAttachmtPt(nd.getDataLayerAddressAsLong(), 
                                             attachmentPoint.getSwitchPort(),
                                             EvAction.ADDED, 
                                             "New AP from pkt-in");
                        }
                    }
                    if (clearAttachmentPoints) {
                        nd.clearAttachmentPoints();
                        evHistAttachmtPt(nd, 0L, (short)(-1),
                                EvAction.CLEARED, "Grat. ARP from pkt-in");
                    }

                    if (newNetworkAddress) {
                        // add the address
                        nd.addNetworkAddress(networkAddress);
                        if (log.isTraceEnabled()) {
                            log.trace("Device {} added IP {}", 
                                      new Object[] {nd, IPv4.fromIPv4Address(nwSrc)});
                        }
                    }
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f

    @Override
    public void init(FloodlightModuleContext fmc) {
Solution content
        return m;
    }

    @Override
    public Collection> getModuleDependencies() {
        Collection> l =
                new ArrayList>();
        l.add(IFloodlightProviderService.class);
        l.add(IStorageSourceService.class);
        l.add(ITopologyService.class);
        l.add(IRestApiService.class);
        l.add(IThreadPoolService.class);
        return l;
    }

    @Override
    public void init(FloodlightModuleContext fmc) {
File
DeviceManagerImpl.java
Developer's decision
Version 1
Kind of conflict
Annotation
Comment
If statement
Method declaration
Method invocation
Method signature
Try statement
Variable
Chunk
Conflicting content
        }

     * @param cntx
     * @return
     */
<<<<<<< HEAD
    protected Command processPacketInMessage(IOFSwitch sw, OFPacketIn pi, 
                                             FloodlightContext cntx) {
        Ethernet eth = 
                IFloodlightProviderService.bcStore.
                get(cntx,IFloodlightProviderService.CONTEXT_PI_PAYLOAD);

        // Extract source entity information
        Entity srcEntity = 
                getSourceEntityFromPacket(eth, sw, pi.getInPort());
        if (srcEntity == null)
            return Command.STOP;


        if (isGratArp(eth) ||
            isBroadcastDHCPReq(eth)) {
            // XXX - TODO - Clear attachment points from other clusters
=======
    private DeviceAttachmentPoint getNewAttachmentPoint(Device device, 
                                                        SwitchPortTuple swPort)
            throws APBlockedException {
        Date currentDate = new Date();

        // First, check if we have an existing attachment point
        DeviceAttachmentPoint curAttachmentPoint = null;
        for (DeviceAttachmentPoint existingAttachmentPoint: 
                                                device.getAttachmentPoints()) {
            // if the two switches are in the same cluster
            long currSw = existingAttachmentPoint.getSwitchPort().getSw().getId();
            short currPort = existingAttachmentPoint.getSwitchPort().getPort();
            long newSw = swPort.getSw().getId();
            short newPort = swPort.getPort();
            long dt = currentDate.getTime() - existingAttachmentPoint.getLastSeen().getTime();
            if (topology.inSameCluster(currSw, newSw)) {
                if ((topology.isBroadcastDomainPort(currSw, currPort) == false) &&
                    (topology.isBroadcastDomainPort(newSw, newPort) == true)) {
                    if (dt < NBD_TO_BD_TIMEDIFF_MS) {
                        // if the packet was seen within the last 5 minutes, we should ignore.
                        // it should also ignore processing the packet.
                        if (log.isDebugEnabled()) {
                            log.debug("Surpressing too quick move of {} from non broadcast domain port {} {}" +
                                    " to broadcast domain port {} {}. Last seen on non-BD {} sec ago",
                                    new Object[] {device.getDlAddrString(),
                                                existingAttachmentPoint.getSwitchPort().getSw().getStringId(), currPort,
                                                swPort.getSw().getStringId(), newPort,
                                                dt/1000 }
                                    );
                        }
                        return null;
                    } else {
                        if (log.isDebugEnabled()) {
                            log.debug("AP move of {} from non broadcast domain port {} {}" +
                                    " to broadcast domain port {} {}. Last seen on BD {} sec ago",
                                    new Object[] { device.getDlAddrString(),
                                                   existingAttachmentPoint.getSwitchPort().getSw().getStringId(), currPort,
                                                   swPort.getSw().getStringId(), newPort,
                                                   dt/1000 }
                                    );
                        }
                        curAttachmentPoint = existingAttachmentPoint;
                        break;
                    }
                } else if ((topology.isBroadcastDomainPort(currSw, currPort) == true) &&
                          (topology.isBroadcastDomainPort(newSw, newPort) == true)) {
                    if (topology.isInSameBroadcastDomain(currSw, currPort, newSw, newPort)) {
                        if (log.isDebugEnabled()) {
                            log.debug("new AP {} {} and current AP {} {} belong to the same broadcast domain",
                                    new Object[] {HexString.toHexString(newSw), newPort,
                                    HexString.toHexString(currSw), currPort});
                        }
                        return null;
                    }
                    if (dt < BD_TO_BD_TIMEDIFF_MS) {
                        // if the packet was seen within the last 5 seconds, we should ignore.
                        // it should also ignore processing the packet.
                        if (log.isDebugEnabled()) {
                            log.debug("Surpressing too quick move of {} from one broadcast domain port {} {}" +
                                    " to another broadcast domain port {} {}. Last seen on BD {} sec ago",
                                    new Object[] {device.getDlAddrString(),
                                                existingAttachmentPoint.getSwitchPort().getSw().getStringId(), currPort,
                                                swPort.getSw().getStringId(), newPort,
                                                dt/1000 }
                                    );
                        }
                        return null;
                    } else {
                        if (log.isDebugEnabled()) {
                            log.debug("AP move of {} from one broadcast domain port {} {}" +
                                    " to another broadcast domain port {} {}. Last seen on BD {} sec ago",
                                    new Object[] { device.getDlAddrString(),
                                                   existingAttachmentPoint.getSwitchPort().getSw().getStringId(), currPort,
                                                   swPort.getSw().getStringId(), newPort,
                                                   dt/1000 }
                                    );
                        }
                        curAttachmentPoint = existingAttachmentPoint;
                        break;
                    }
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("AP move of {} from port {} {}" +
                                " to port {} {}. Last seen {} sec ago",
                                new Object[] { device.getDlAddrString(),
                                               existingAttachmentPoint.getSwitchPort().getSw().getStringId(), currPort,
                                               swPort.getSw().getStringId(), newPort,
                                               dt/1000 }
                                );
                    }
                    curAttachmentPoint = existingAttachmentPoint;
                    break;
                }
            }
        }
        
        // Do we have an old attachment point?
        DeviceAttachmentPoint attachmentPoint = 
                                    device.getOldAttachmentPoint(swPort);
        if (attachmentPoint == null) {
            attachmentPoint = new DeviceAttachmentPoint(swPort, currentDate);
        } else {
            attachmentPoint.setLastSeen(currentDate);
            if (attachmentPoint.isBlocked()) {
                // Attachment point is currently in blocked state
                // If curAttachmentPoint exists and active, drop the packet
                if (curAttachmentPoint != null &&
                    currentDate.getTime() - 
                    curAttachmentPoint.getLastSeen().getTime() < 600000) {
                    throw new APBlockedException("Attachment point is blocked");
                }
                log.info("Unblocking {} for device {}",
                         attachmentPoint.getSwitchPort(), device);
                attachmentPoint.setBlocked(false);
                evHistAttachmtPt(device.getDataLayerAddressAsLong(), swPort,
                    EvAction.UNBLOCKED, "packet-in after block timer expired");
            }
            // Remove from old list
            device.removeOldAttachmentPoint(attachmentPoint);
        // Update mappings
        devMgrMaps.addDevAttachmentPoint(
                device.getDataLayerAddressAsLong(), swPort, currentDate);
        evHistAttachmtPt(device.getDataLayerAddressAsLong(), swPort,
                EvAction.ADDED, "packet-in GNAP");

        // If curAttachmentPoint exists, we mark it a conflict and may block it.
        if (curAttachmentPoint != null) {
            device.removeAttachmentPoint(curAttachmentPoint);
            device.addOldAttachmentPoint(curAttachmentPoint);
            // If two ports are in the same port-channel, we don't treat it
            // as conflict, but will forward based on the last seen switch-port
            if (!devMgrMaps.inSamePortChannel(swPort,
                    curAttachmentPoint.getSwitchPort())) {
                curAttachmentPoint.setConflict(currentDate);
                if (curAttachmentPoint.isFlapping()) {
                    curAttachmentPoint.setBlocked(true);
                    evHistAttachmtPt(device.getDataLayerAddressAsLong(),
                            curAttachmentPoint.getSwitchPort(),
                            EvAction.BLOCKED, "Conflict");
                    writeAttachmentPointToStorage(device, curAttachmentPoint,
                                                currentDate);
                    log.warn(
                        "Device {}: flapping between {} and {}, block the latter",
                        new Object[] {device, swPort, 
                        curAttachmentPoint.getSwitchPort()});
                    // Check if flapping is between the same switch port
                    if (swPort.getSw().getId() ==
                        curAttachmentPoint.getSwitchPort().getSw().getId() &&
                        swPort.getPort() ==
                        curAttachmentPoint.getSwitchPort().getPort()) {
                        log.warn("Fake flapping on port " + swPort.getPort() +
                            " between sw " + swPort.getSw() + " and " +
                            curAttachmentPoint.getSwitchPort().getSw());
                        device.removeOldAttachmentPoint(curAttachmentPoint);
                        removeAttachmentPointFromStorage(device.getDlAddrString(),
                            HexString.toHexString(curAttachmentPoint.getSwitchPort().getSw().getId()),
                            curAttachmentPoint.getSwitchPort().getPort().toString());
                    }
                } else {
                    removeAttachmentPointFromStorage(device.getDlAddrString(),
                        HexString.toHexString(curAttachmentPoint.getSwitchPort().getSw().getId()),
                        curAttachmentPoint.getSwitchPort().getPort().toString());
                    evHistAttachmtPt(device.getDataLayerAddressAsLong(),
                            curAttachmentPoint.getSwitchPort(),
                            EvAction.REMOVED, "Conflict");
                }
            }
            updateMoved(device, curAttachmentPoint.getSwitchPort(),
                                                            attachmentPoint);

            if (log.isDebugEnabled()) {
                log.debug("Device {} moved from {} to {}", new Object[] {
                           device.getDlAddrString(), curAttachmentPoint.getSwitchPort(), swPort});
            }
        } else {
            updateStatus(device, true);
            log.debug("Device {} added {}", device, swPort);
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
        }

        // Learn/lookup device information
Solution content
     * @param cntx
     * @return
     */
    protected Command processPacketInMessage(IOFSwitch sw, OFPacketIn pi, 
                                             FloodlightContext cntx) {
        Ethernet eth = 
                IFloodlightProviderService.bcStore.
                get(cntx,IFloodlightProviderService.CONTEXT_PI_PAYLOAD);

        // Extract source entity information
        Entity srcEntity = 
                getSourceEntityFromPacket(eth, sw, pi.getInPort());
        if (srcEntity == null)
            return Command.STOP;


        if (isGratArp(eth) ||
            isBroadcastDHCPReq(eth)) {
            // XXX - TODO - Clear attachment points from other clusters
        }

        // Learn/lookup device information
File
DeviceManagerImpl.java
Developer's decision
Version 1
Kind of conflict
Comment
For statement
If statement
Method invocation
Method signature
Variable
Chunk
Conflicting content
    @Override
     * @param switchPort the port
     * @return true if it's a valid attachment point
     */
<<<<<<< HEAD
    protected boolean isValidAttachmentPoint(long switchDPID,
                                             int switchPort) {
        IOFSwitch sw = floodlightProvider.getSwitches().get(switchDPID);
        if (sw == null) return false;
        OFPhysicalPort port = sw.getPort((short)switchPort);
        if (port == null || !sw.portEnabled(port)) return false;
        if (topology.isInternal(switchDPID, (short)switchPort))
            return false;
        
        // Check whether the port is a physical port. We should not learn 
        // attachment points on "special" ports.
        if (((switchPort & 0xff00) == 0xff00) && 
             (switchPort != (short)0xfffe))
            return false;
        
        return true;            
=======
    public void setLinkDiscovery(ILinkDiscoveryService linkDiscovery) {
        this.linkDiscovery = linkDiscovery;
    }

    public Device getDeviceByDataLayerAddress(byte[] address) {
        if (address.length != Ethernet.DATALAYER_ADDRESS_LENGTH) return null;
        return getDeviceByDataLayerAddress(Ethernet.toLong(address));
    }

    @Override
    public Device getDeviceByDataLayerAddress(long address) {
        return this.devMgrMaps.dataLayerAddressDeviceMap.get(address);
    }

    @Override
    public Device getDeviceByIPv4Address(Integer address) {
        lock.readLock().lock();
        try {
            return this.devMgrMaps.ipv4AddressDeviceMap.get(address);
        } finally {
            lock.readLock().unlock();
        }
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
    }
    
    private boolean isGratArp(Ethernet eth) {
Solution content
     * @param switchPort the port
     * @return true if it's a valid attachment point
     */
    protected boolean isValidAttachmentPoint(long switchDPID,
                                             int switchPort) {
        IOFSwitch sw = floodlightProvider.getSwitches().get(switchDPID);
        if (sw == null) return false;
        OFPhysicalPort port = sw.getPort((short)switchPort);
        if (port == null || !sw.portEnabled(port)) return false;
        if (topology.isInternal(switchDPID, (short)switchPort))
            return false;
        
        // Check whether the port is a physical port. We should not learn 
        // attachment points on "special" ports.
        if (((switchPort & 0xff00) == 0xff00) && 
             (switchPort != (short)0xfffe))
            return false;
        
        return true;            
    }
    
    private boolean isGratArp(Ethernet eth) {
File
DeviceManagerImpl.java
Developer's decision
Version 1
Kind of conflict
Annotation
Comment
If statement
Method declaration
Method invocation
Method signature
Return statement
Try statement
Variable
Chunk
Conflicting content
                    if (d == null) continue;

        lock.writeLock().lock();
        }
        return false;
    }
<<<<<<< HEAD
    
    private boolean isBroadcastDHCPReq(Ethernet eth) {
        return ((eth.getPayload() instanceof DHCP) && (eth.isBroadcast()));
    }

    private int getSrcNwAddr(Ethernet eth, long dlAddr) {
        if (eth.getPayload() instanceof ARP) {
            ARP arp = (ARP) eth.getPayload();
            if ((arp.getProtocolType() == ARP.PROTO_TYPE_IP) &&
                (Ethernet.toLong(arp.getSenderHardwareAddress()) == dlAddr)) {
                return IPv4.toIPv4Address(arp.getSenderProtocolAddress());
            }
        } else if (eth.getPayload() instanceof IPv4) {
            IPv4 ipv4 = (IPv4) eth.getPayload();
            if (ipv4.getPayload() instanceof UDP) {
                UDP udp = (UDP)ipv4.getPayload();
                if (udp.getPayload() instanceof DHCP) {
                    DHCP dhcp = (DHCP)udp.getPayload();
                    if (dhcp.getOpCode() == DHCP.OPCODE_REPLY) {
                        return ipv4.getSourceAddress();
                    }
                }
            }
=======

    @Override
    public boolean isDeviceKnownToCluster(long deviceId, long switchId) {
        Device device = devMgrMaps.getDeviceByDataLayerAddr(deviceId);
        if (device == null) {
            return false;
        }
        /** 
         * Iterate through all APs and check if the switch clusterID matches
         * with the given clusterId
         */
        for(DeviceAttachmentPoint dap : device.getAttachmentPoints()) {
            if (dap == null) continue;
            if (topology.getSwitchClusterId(switchId) == 
                topology.getSwitchClusterId(dap.getSwitchPort().getSw().getId())) {
                    return true;
            }
        }
        return false;
    }
    
    @Override
    public List getDevices() {
        lock.readLock().lock();
        try {
            return new ArrayList(
                    this.devMgrMaps.dataLayerAddressDeviceMap.values());
        } finally {
            lock.readLock().unlock();
        }
    }

    @Override
    public void addedSwitch(IOFSwitch sw) {
        /**
         * No point to restore the old APs on the switch since
         * the hosts connecting to the switch will be discovered
         * by ARP if anyone wants to talk to the hosts.
         */
        // Fix up attachment points related to the switch
        /*
        try {
                for (PendingAttachmentPoint pap : papl) {
                    Device d = devMgrMaps.getDeviceByDataLayerAddr(pap.mac);
            Long swDpid = sw.getId();
            List papl = 
                devMgrMaps.getSwitchUnresolvedAPMap().get(swDpid);
            if (papl != null) {
                    // Add attachment point
                    devMgrMaps.addDevAttachmentPoint(
                            pap.mac, sw, pap.switchPort, pap.lastSeen);
                    evHistAttachmtPt(pap.mac,
                            sw.getId(), pap.switchPort,
                            EvAction.ADDED, "Switch Added");
                }
                devMgrMaps.getSwitchUnresolvedAPMap().remove(swDpid);
            }
        } finally {
            lock.writeLock().unlock();
        }*/
    }

    @Override
    public void removedSwitch (IOFSwitch sw) {
        // remove all devices attached to this switch
        if (!devMgrMaps.isSwitchPresent(sw)) {
            // Switch not present
            return;
        }
        lock.writeLock().lock();
        try {
            devMgrMaps.delSwitchfromMaps(sw);
        } finally {
            lock.writeLock().unlock();
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
        }
        return 0;
    }
Solution content
        }
        return false;
    }
    
    private boolean isBroadcastDHCPReq(Ethernet eth) {
        return ((eth.getPayload() instanceof DHCP) && (eth.isBroadcast()));
    }

    private int getSrcNwAddr(Ethernet eth, long dlAddr) {
        if (eth.getPayload() instanceof ARP) {
            ARP arp = (ARP) eth.getPayload();
            if ((arp.getProtocolType() == ARP.PROTO_TYPE_IP) &&
                (Ethernet.toLong(arp.getSenderHardwareAddress()) == dlAddr)) {
                return IPv4.toIPv4Address(arp.getSenderProtocolAddress());
            }
        } else if (eth.getPayload() instanceof IPv4) {
            IPv4 ipv4 = (IPv4) eth.getPayload();
            if (ipv4.getPayload() instanceof UDP) {
                UDP udp = (UDP)ipv4.getPayload();
                if (udp.getPayload() instanceof DHCP) {
                    DHCP dhcp = (DHCP)udp.getPayload();
                    if (dhcp.getOpCode() == DHCP.OPCODE_REPLY) {
                        return ipv4.getSourceAddress();
                    }
                }
            }
        }
        return 0;
    }
File
DeviceManagerImpl.java
Developer's decision
Version 1
Kind of conflict
Annotation
Cast expression
Comment
If statement
Method declaration
Method invocation
Method signature
Try statement
Variable
Chunk
Conflicting content
        //}

     * @param dstEntity the entity to look up
     * @return an {@link Device} or null if no device is found.
     */
<<<<<<< HEAD
    protected Device findDestByEntity(IDevice source,
                                      Entity dstEntity) {
        Device dstDevice = findDeviceByEntity(dstEntity);

        //if (dstDevice == null) {
            // This could happen because:
            // 1) no destination known, or a broadcast destination
            // 2) if we have attachment point key fields since 
            // attachment point information isn't available for
            // destination devices.
            // For the second case, we'll need to match up the 
            // destination device with the class of the source 
            // device.  
            /*
                ArrayList candidates = new ArrayList();
                for (IEntityClass clazz : srcDevice.getEntityClasses()) {
                    Device c = findDeviceInClassByEntity(clazz, dstEntity);
                    if (c != null)
                        candidates.add(c);
                }
                if (candidates.size() == 1) {
                    dstDevice = candidates.get(0);
                } else if (candidates.size() > 1) {
                    // ambiguous device.  A higher-order component will 
                    // need to deal with it by assigning priority
                    // XXX - TODO
                }
             */
=======
    protected void updateMoved(Device device, SwitchPortTuple oldSwPort, 
                                                DeviceAttachmentPoint newDap) {
        // We also clear the attachment points on other islands
        device.clearAttachmentPoints();
        evHistAttachmtPt(device, 0L, (short)(-1), EvAction.CLEARED, "Moved");
        device.addAttachmentPoint(newDap);
        evHistAttachmtPt(device.getDataLayerAddressAsLong(), 
                newDap.getSwitchPort(), 
                EvAction.ADDED, "Moved");
        
        synchronized (updates) {
            Update update = new Update(UpdateType.MOVED);
            update.device = device;
            update.oldSw = oldSwPort.getSw();
            update.oldSwPort = oldSwPort.getPort();
            update.sw = newDap.getSwitchPort().getSw();
            update.swPort = newDap.getSwitchPort().getPort();
            this.updates.add(update);
        }
    }
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
Solution content
     * @param dstEntity the entity to look up
     * @return an {@link Device} or null if no device is found.
     */
    protected Device findDestByEntity(IDevice source,
                                      Entity dstEntity) {
        Device dstDevice = findDeviceByEntity(dstEntity);

        //if (dstDevice == null) {
            // This could happen because:
            // 1) no destination known, or a broadcast destination
            // 2) if we have attachment point key fields since 
            // attachment point information isn't available for
            // destination devices.
            // For the second case, we'll need to match up the 
            // destination device with the class of the source 
            // device.  
            /*
                ArrayList candidates = new ArrayList();
                for (IEntityClass clazz : srcDevice.getEntityClasses()) {
                    Device c = findDeviceInClassByEntity(clazz, dstEntity);
                    if (c != null)
                        candidates.add(c);
                }
                if (candidates.size() == 1) {
                    dstDevice = candidates.get(0);
                } else if (candidates.size() > 1) {
                    // ambiguous device.  A higher-order component will 
                    // need to deal with it by assigning priority
                    // XXX - TODO
                }
             */
        //}
File
DeviceManagerImpl.java
Developer's decision
Version 1
Kind of conflict
Comment
Method declaration
Method invocation
Method signature
Variable
Chunk
Conflicting content
    }

    /**
<<<<<<< HEAD
        // XXX - TODO
     * Look up a {@link Device} within a particular entity class based on 
     * the provided {@link Entity}.
     * @param clazz the entity class to search for the entity
     * @param entity the entity to search for
     * @return The {@link Device} object if found
    private Device findDeviceInClassByEntity(IEntityClass clazz,
                                               Entity entity) {
        throw new UnsupportedOperationException();
    }
     */
    
    /**
     * Look up a {@link Device} based on the provided {@link Entity}.  Also
     * learns based on the new entity, and will update existing devices as 
     * required. 
     * 
     * @param entity the {@link Entity}
     * @return The {@link Device} object if found
     */
    protected Device learnDeviceByEntity(Entity entity) {
        ArrayList deleteQueue = null;
        LinkedList deviceUpdates = null;
        Device device = null;
        
        // we may need to restart the learning process if we detect
        // concurrent modification.  Note that we ensure that at least
        // one thread should always succeed so we don't get into infinite
        // starvation loops
        while (true) {
            deviceUpdates = null;
            
            // Look up the fully-qualified entity to see if it already
            // exists in the primary entity index.
            Long deviceKey = primaryIndex.findByEntity(entity);
            Collection classes = null;
            
            if (deviceKey == null) {
                // If the entity does not exist in the primary entity index, 
                // use the entity classifier for find the classes for the 
                // entity. Look up the entity in each of the returned classes'
                // class entity indexes.
                classes = entityClassifier.classifyEntity(entity);
                for (IEntityClass clazz : classes) {
                    ClassState classState = getClassState(clazz);
                        
                    if (classState.classIndex != null) {
                        deviceKey = 
                                classState.classIndex.findByEntity(entity);
                    }
=======
     * Iterates through all devices and cleans up attachment points
     */
    @Override
    public void topologyChanged() {
        deviceUpdateTask.reschedule(10, TimeUnit.MILLISECONDS);
    }

    protected boolean isNewer(DeviceAttachmentPoint dap1,
                            DeviceAttachmentPoint dap2) {
        // dap 1 is newer than dap 2 if
        // (1) if dap 1 is a non-broadcast domain attachment point
        //      (a) if (dap 2 is a non-broadcast domain attachment point
        //          and dap1.lastseen time is after dap2.last seentime
        //      OR
        //      (b) if (dap 2 is a braodcast domain attachment point
        //          and dap1.lastseen time is after (dap2.lastseen-5minutes)
        // (2) if dap 1 is a broadcast domain attachment point
        //      (a) if dap 2 is a non-broadcast attachment point and
        //          dap1.lastseen is after (dap2.lastseen + 5 minutes)
        //      OR
        //      (b) if dap2 is a broadcastdomain attachment point and
        //          dap2.lastseen

        SwitchPortTuple sp1, sp2;
        boolean sp1IsBDPort, sp2IsBDPort;
        sp1 = dap1.getSwitchPort();
        sp2 = dap2.getSwitchPort();

        sp1IsBDPort = topology.isBroadcastDomainPort(sp1.getSw().getId(),
                                               sp1.getPort());
        sp2IsBDPort = topology.isBroadcastDomainPort(sp2.getSw().getId(),
                                               sp2.getPort());
        long ls1 = dap1.getLastSeen().getTime();
        long ls2 = dap2.getLastSeen().getTime();

        if (sp1IsBDPort == false) {
            if (sp2IsBDPort == false) {
                return (ls1 > ls2);
            } else {
                return (ls1 > (ls2 - NBD_TO_BD_TIMEDIFF_MS));
            }
        } else {
            if (sp2IsBDPort == false) {
                return (ls1 > (ls2 + NBD_TO_BD_TIMEDIFF_MS));
            } else {
                return ((ls1 > ls2 + BD_TO_BD_TIMEDIFF_MS) ||
                        (ls1 < ls2 && ls1 > ls2 - BD_TO_BD_TIMEDIFF_MS));
            }
        }
    }
    /**
     * Removes any attachment points that are in the same
     * {@link net.floodlightcontroller.topology.SwitchCluster SwitchCluster}
     * @param d The device to update the attachment points
     */
    public void cleanupAttachmentPoints(Device d) {
        // The long here is the SwitchCluster ID
        Map tempAPMap =
                            new HashMap();
        Map tempOldAPMap =
            new HashMap();

        // Get only the latest DAPs into a map
        for (DeviceAttachmentPoint dap : d.getAttachmentPoints()) {
            if (DeviceAttachmentPoint.isNotNull(dap) &&
                            !topology.isInternal(dap.getSwitchPort().getSw().getId(), dap.getSwitchPort().getPort())) {
                long clusterId = topology.getSwitchClusterId(
                            dap.getSwitchPort().getSw().getId());
                // do not use attachment points if the attachment point is
                // not allowed by topology
                long swid = dap.getSwitchPort().getSw().getId();
                short port = dap.getSwitchPort().getPort();
                if (topology.isAllowed(swid, port) == false)
                    continue;

                if (tempAPMap.containsKey(clusterId)) {
                    // We compare to see which one is newer, move attachment 
                    // point to "old" list.
                    // They are removed after deleting from storage.

                    DeviceAttachmentPoint existingDap = tempAPMap.get(clusterId);
                    if (isNewer(dap, existingDap)) {
                        tempAPMap.put(clusterId, dap);
                        tempOldAPMap.put(clusterId, existingDap);
                    }
                } else {
                    tempAPMap.put(clusterId, dap);
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
                }
            }
            if (deviceKey != null) {
Solution content
            
    }

    /**
     * Look up a {@link Device} within a particular entity class based on 
     * the provided {@link Entity}.
     * @param clazz the entity class to search for the entity
     * @param entity the entity to search for
     * @return The {@link Device} object if found
    private Device findDeviceInClassByEntity(IEntityClass clazz,
                                               Entity entity) {
        // XXX - TODO
        throw new UnsupportedOperationException();
    }
     */
    
    /**
     * Look up a {@link Device} based on the provided {@link Entity}.  Also
     * learns based on the new entity, and will update existing devices as 
     * required. 
     * 
     * @param entity the {@link Entity}
     * @return The {@link Device} object if found
     */
    protected Device learnDeviceByEntity(Entity entity) {
        ArrayList deleteQueue = null;
        LinkedList deviceUpdates = null;
        Device device = null;
        
        // we may need to restart the learning process if we detect
        // concurrent modification.  Note that we ensure that at least
        // one thread should always succeed so we don't get into infinite
        // starvation loops
        while (true) {
            deviceUpdates = null;
            
            // Look up the fully-qualified entity to see if it already
            // exists in the primary entity index.
            Long deviceKey = primaryIndex.findByEntity(entity);
            Collection classes = null;
            if (deviceKey == null) {
                // If the entity does not exist in the primary entity index, 
                // use the entity classifier for find the classes for the 
                // entity. Look up the entity in each of the returned classes'
                // class entity indexes.
                classes = entityClassifier.classifyEntity(entity);
                for (IEntityClass clazz : classes) {
                    ClassState classState = getClassState(clazz);
                        
                    if (classState.classIndex != null) {
                        deviceKey = 
                                classState.classIndex.findByEntity(entity);
                    }
                }
            }
            if (deviceKey != null) {
File
DeviceManagerImpl.java
Developer's decision
Version 1
Kind of conflict
Annotation
Comment
For statement
If statement
Method declaration
Method invocation
Method signature
Variable
While statement
Chunk
Conflicting content
                break;
            }
        }
<<<<<<< HEAD
           
        if (deleteQueue != null) {
            for (Long l : deleteQueue) {
                deviceMap.remove(l);
            }
=======

        synchronized (d) {
            // Since the update below is happening on a copy of the device it
            // should not impact packetIn processing time due to lock contention
            d.setAttachmentPoints(tempAPMap.values());
            for (DeviceAttachmentPoint dap : tempOldAPMap.values()) {
                d.addOldAttachmentPoint(dap);
            }

            log.debug("After cleanup, device {}", d);
        }
    }

    public void clearAllDeviceStateFromMemory() {
        devMgrMaps.clearMaps();
    }

    private Date ageBoundaryDifference(Date currentDate, long expire) {
        if (expire == 0) {
            return new Date(0);
        }
        return new Date(currentDate.getTime() - 1000*expire);
    }

    // *********************
    // Storage Write Methods
    // *********************

    protected void writeDeviceToStorage(Device device, Date currentDate) {
        Map rowValues = new HashMap();
        String macString = device.getDlAddrString();
        rowValues.put(MAC_COLUMN_NAME, macString);
        if (device.getVlanId() != null)
            rowValues.put(VLAN_COLUMN_NAME, device.getVlanId());
        rowValues.put(LAST_SEEN_COLUMN_NAME, currentDate);
        storageSource.updateRowAsync(DEVICE_TABLE_NAME, rowValues);
        device.lastSeenWrittenToStorage(currentDate);

        for (DeviceAttachmentPoint attachmentPoint: 
                                            device.getAttachmentPoints()) {
            writeAttachmentPointToStorage(device, attachmentPoint, currentDate);
        }
        for (DeviceNetworkAddress networkAddress: 
                                            device.getNetworkAddresses()) {
            writeNetworkAddressToStorage(device, networkAddress, currentDate);
        }
    }

    protected void writeAttachmentPointToStorage(Device device,
            DeviceAttachmentPoint attachmentPoint, Date currentDate) {
        assert(device != null);
        assert(attachmentPoint != null);
        String deviceId = device.getDlAddrString();
        SwitchPortTuple switchPort = attachmentPoint.getSwitchPort();
        assert(switchPort != null);
        String switchId = switchPort.getSw().getStringId();
        Short port = switchPort.getPort();
        String attachmentPointId = 
                            deviceId + "|" + switchId + "|" + port.toString();

        Map rowValues = new HashMap();
        rowValues.put(ID_COLUMN_NAME, attachmentPointId);
        rowValues.put(DEVICE_COLUMN_NAME, deviceId);
        rowValues.put(SWITCH_COLUMN_NAME, switchId);
        rowValues.put(PORT_COLUMN_NAME, port);
        rowValues.put(LAST_SEEN_COLUMN_NAME, attachmentPoint.getLastSeen());
        String status = null;
        if (attachmentPoint.isBlocked())
            status = "blocked: duplicate mac";
        rowValues.put(AP_STATUS_COLUMN_NAME, status);

        storageSource.updateRowAsync(DEVICE_ATTACHMENT_POINT_TABLE_NAME, 
                                                                    rowValues);
        attachmentPoint.lastSeenWrittenToStorage(currentDate);
    }

    // **********************
    // Storage Remove Methods
    // **********************

    protected void removeAttachmentPointFromStorage(String deviceId,
                                    String switchId, String port) {
        String attachmentPointId =
                        deviceId + "|" + switchId + "|" + port;
        try {
            storageSource.deleteRowAsync(
                        DEVICE_ATTACHMENT_POINT_TABLE_NAME, attachmentPointId);
        } catch (NullPointerException e) {
            log.warn("Null ptr exception for device {} on sw {} port {}",
                    new Object[] {deviceId, switchId, port});
        }
    }

    protected void writeNetworkAddressToStorage(Device device,
            DeviceNetworkAddress networkAddress, Date currentDate) {
        assert(device != null);
        assert(networkAddress != null);
        String deviceId = device.getDlAddrString();
        String networkAddressString = IPv4.fromIPv4Address(
                                            networkAddress.getNetworkAddress());
        String networkAddressId = deviceId + "|" + networkAddressString;

        if (networkAddress.getNetworkAddress() == 0) {
            log.error("Zero network address for device {}\n {}",
                device, Thread.currentThread().getStackTrace());
            return;
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
        }
        
        processUpdates(deviceUpdates);
Solution content
                break;
            }
        }
           
        if (deleteQueue != null) {
            for (Long l : deleteQueue) {
                deviceMap.remove(l);
            }
        }
        
        processUpdates(deviceUpdates);
File
DeviceManagerImpl.java
Developer's decision
Version 1
Kind of conflict
Assert statement
Comment
For statement
If statement
Method declaration
Method invocation
Method signature
Return statement
Synchronized statement
Variable
Chunk
Conflicting content
    }

        
        processUpdates(deviceUpdates);

<<<<<<< HEAD
        return device;
=======
    protected void removeNetworkAddressFromStorage(String deviceId,
                                        DeviceNetworkAddress networkAddress) {
        assert(deviceId != null);
        assert(networkAddress != null);
        String networkAddressString = IPv4.fromIPv4Address(
                                            networkAddress.getNetworkAddress());
        String networkAddressId = deviceId + "|" + networkAddressString;
        storageSource.deleteRowAsync(DEVICE_NETWORK_ADDRESS_TABLE_NAME, 
                                                            networkAddressId);
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
    protected EnumSet findChangedFields(Device device, 
Solution content
        
        processUpdates(deviceUpdates);

        return device;
    }

    protected EnumSet findChangedFields(Device device, 
File
DeviceManagerImpl.java
Developer's decision
Version 1
Kind of conflict
Assert statement
Attribute
Method invocation
Method signature
Return statement
Variable
Chunk
Conflicting content
        }
    }

<<<<<<< HEAD
    private LinkedList 
        updateUpdates(LinkedList list, DeviceUpdate update) {
        if (update == null) return list;
        if (list == null)
            list = new LinkedList();
        list.add(update);
        
        return list;
=======
    private void readDeviceAttachmentPointsFromStorage(Date currentDate) 
        throws StorageException {

        String [] colNames = new String[] {
                DEVICE_COLUMN_NAME, SWITCH_COLUMN_NAME, 
                PORT_COLUMN_NAME, LAST_SEEN_COLUMN_NAME};

        IResultSet dapResultSet = storageSource.executeQuery(
                DEVICE_ATTACHMENT_POINT_TABLE_NAME, colNames, null, null);

        while (dapResultSet.next()) {
           Date lastSeen = dapResultSet.getDate(LAST_SEEN_COLUMN_NAME);
           if (lastSeen == null) lastSeen = new Date();

           String macString  = dapResultSet.getString(DEVICE_COLUMN_NAME);
           String dpidString = dapResultSet.getString(SWITCH_COLUMN_NAME);

           if (macString == null || dpidString == null)
               continue;

           long mac     = HexString.toLong(macString);
           long swDpid  = HexString.toLong(dpidString);
           IOFSwitch sw = floodlightProvider.getSwitches().get(swDpid);
           Integer port = dapResultSet.getIntegerObject(PORT_COLUMN_NAME);

           if (port == null || port > Short.MAX_VALUE) continue;

           if (sw == null) { // switch has not joined yet
               removeAttachmentPointFromStorage(macString, dpidString, port.toString());
               devMgrMaps.updateSwitchUnresolvedAPMap(
                       swDpid, mac, port.shortValue(), lastSeen);
           } else {
               devMgrMaps.addDevAttachmentPoint(
                                       mac, sw, port.shortValue(), lastSeen);
               evHistAttachmtPt(mac, sw.getId(), port.shortValue(), 
                                       EvAction.ADDED, "Read from storage");
           }
        }
    }

    private void readDeviceNetworkAddressesFromStorage(Date currentDate) 
                                                    throws StorageException {

        String [] colNames = new String[]{  DEVICE_COLUMN_NAME, 
                                            NETWORK_ADDRESS_COLUMN_NAME, 
                                            LAST_SEEN_COLUMN_NAME};
        IResultSet dnaResultSet = storageSource.executeQuery(
                    DEVICE_NETWORK_ADDRESS_TABLE_NAME, colNames, null, null);

        while (dnaResultSet.next()) {
            Date lastSeen = dnaResultSet.getDate(LAST_SEEN_COLUMN_NAME);
            if (lastSeen == null) lastSeen = new Date();

            String macStr  = dnaResultSet.getString(DEVICE_COLUMN_NAME);
            String netaddr = dnaResultSet.getString(
                                                NETWORK_ADDRESS_COLUMN_NAME);

            if (macStr == null) {
                continue;
            }
            if (netaddr == null) {
                // If the key is in the database then ignore this record
                continue;
            }
            devMgrMaps.addNwAddrByDataLayerAddr(HexString.toLong(macStr), 
                                        IPv4.toIPv4Address(netaddr),
                                        lastSeen);
        }
    }

    public void removeDeviceDiscoveredStateFromStorage(Device device) {
        String deviceId = device.getDlAddrString();

        // Remove all of the attachment points
        storageSource.deleteMatchingRowsAsync(DEVICE_ATTACHMENT_POINT_TABLE_NAME,
                new OperatorPredicate(DEVICE_COLUMN_NAME, 
                        OperatorPredicate.Operator.EQ, deviceId));
        storageSource.deleteMatchingRowsAsync(DEVICE_NETWORK_ADDRESS_TABLE_NAME,
                new OperatorPredicate(DEVICE_COLUMN_NAME, 
                        OperatorPredicate.Operator.EQ, deviceId));

        // Remove the device
        storageSource.deleteRow(DEVICE_TABLE_NAME, deviceId);
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
    }
    
    /**
Solution content
        }
    }

    private LinkedList 
        updateUpdates(LinkedList list, DeviceUpdate update) {
        if (update == null) return list;
        if (list == null)
            list = new LinkedList();
        list.add(update);
        
        return list;
    }
    
    /**
File
DeviceManagerImpl.java
Developer's decision
Version 1
Kind of conflict
Comment
If statement
Method declaration
Method invocation
Method signature
Return statement
Variable
Chunk
Conflicting content
     * @param clazz the class for the index
     * @return
     */
<<<<<<< HEAD
    private ClassState getClassState(IEntityClass clazz) {
        ClassState classState = classStateMap.get(clazz);
        if (classState != null) return classState;
=======

    private Device removeAgedNetworkAddresses(Device device, Date currentDate) {
        Collection addresses = 
                                                device.getNetworkAddresses();

        for (DeviceNetworkAddress address : addresses) {
            long expire = address.getExpire();

            if (expire == 0) {
                expire = DEVICE_NA_MAX_AGE;
            }
            Date agedBoundary = ageBoundaryDifference(currentDate, expire);

            if (address.getLastSeen().before(agedBoundary)) {
                devMgrMaps.delNwAddrByDataLayerAddr(device.getDataLayerAddressAsLong(), 
                    address.getNetworkAddress().intValue());
            }
        }
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
        
        classState = new ClassState(clazz);
        ClassState r = classStateMap.putIfAbsent(clazz, classState);
Solution content
     * @param clazz the class for the index
     * @return
     */
    private ClassState getClassState(IEntityClass clazz) {
        ClassState classState = classStateMap.get(clazz);
        if (classState != null) return classState;
        
        classState = new ClassState(clazz);
        ClassState r = classStateMap.putIfAbsent(clazz, classState);
File
DeviceManagerImpl.java
Developer's decision
Version 1
Kind of conflict
For statement
If statement
Method invocation
Method signature
Variable
Chunk
Conflicting content
     * @param deviceKey the device key for the device
     * @return true if the update succeeded, false otherwise.
     */
<<<<<<< HEAD
    private boolean updateIndices(Device device, Long deviceKey) {
        if (!primaryIndex.updateIndex(device, deviceKey)) {
            return false;
        }
        for (IEntityClass clazz : device.getEntityClasses()) {
            ClassState classState = getClassState(clazz); 

            if (classState.classIndex != null) {
                if (!classState.classIndex.updateIndex(device, 
                                                       deviceKey))
                    return false;
=======
    private Device removeAgedAttachmentPoints(Device device, Date currentDate) {
        if (device == null) return null;

        long dlAddr = device.getDataLayerAddressAsLong();
        Collection aps = device.getAttachmentPoints();

        for (DeviceAttachmentPoint ap : aps) {
            int expire = ap.getExpire();

            if (expire == 0) {
                expire = DEVICE_AP_MAX_AGE;
            }
            Date agedBoundary = ageBoundaryDifference(currentDate, expire);
            if (ap.getLastSeen().before(agedBoundary)) {
                log.debug("remove AP {} from device {}", ap, HexString.toHexString(dlAddr));
                devMgrMaps.delDevAttachmentPoint(dlAddr, ap.getSwitchPort());
                evHistAttachmtPt(device.getDataLayerAddressAsLong(), 
                        ap.getSwitchPort(), EvAction.REMOVED,
                        "Aged");
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
            }
        }
        return true;
Solution content
     * @param deviceKey the device key for the device
     * @return true if the update succeeded, false otherwise.
     */
    private boolean updateIndices(Device device, Long deviceKey) {
        if (!primaryIndex.updateIndex(device, deviceKey)) {
            return false;
        }
        for (IEntityClass clazz : device.getEntityClasses()) {
            ClassState classState = getClassState(clazz); 

            if (classState.classIndex != null) {
                if (!classState.classIndex.updateIndex(device, 
                                                       deviceKey))
                    return false;
            }
        }
        return true;
File
DeviceManagerImpl.java
Developer's decision
Version 1
Kind of conflict
For statement
If statement
Method invocation
Method signature
Variable
Chunk
Conflicting content
     */
<<<<<<< HEAD
     * @param entityClasses the entity classes for the entity
     * @param deviceKey the device key to set up
    private void updateSecondaryIndices(Entity entity, 
                                        Collection entityClasses, 
                                        Long deviceKey) {
        for (DeviceIndex index : secondaryIndexMap.values()) {
            index.updateIndex(entity, deviceKey);
        }
        for (IEntityClass clazz : entityClasses) {
            ClassState state = getClassState(clazz);
            for (DeviceIndex index : state.secondaryIndexMap.values()) {
                index.updateIndex(entity, deviceKey);
            }
        }
    }
    
    /**
     * Update the secondary indices for the given entity and associated
     * entity classes
     * @param entity the entity to update
     * @param entityClasses the entity classes for the entity
     * @param deviceKey the device key to set up
     */
    private void updateSecondaryIndices(Entity entity, 
                                        IEntityClass[] entityClasses, 
                                        Long deviceKey) {
        updateSecondaryIndices(entity, Arrays.asList(entityClasses), deviceKey);
    }

=======
    private void removeAgedDevices(Date currentDate) {
        Date deviceAgeBoundary = ageBoundaryDifference(currentDate, 
                                        DEVICE_MAX_AGE);

        Collection deviceColl = devMgrMaps.getDevices();
        for (Device device: deviceColl) {
             device = removeAgedNetworkAddresses(device, currentDate);
             device = removeAgedAttachmentPoints(device, currentDate);

             if ((device.getAttachmentPoints().size() == 0) &&
                 (device.getNetworkAddresses().size() == 0) &&
                 (device.getLastSeen().before(deviceAgeBoundary))) {
                 delDevice(device);
             }
        }
    }

    protected static int DEVICE_AGING_TIMER= 60 * 15; // in seconds
    protected static final int DEVICE_AGING_TIMER_INTERVAL = 1; // in seconds

>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
    /**
     * Clean up expired entities/devices
     */
Solution content
     * @param entityClasses the entity classes for the entity
     * @param deviceKey the device key to set up
     */
    private void updateSecondaryIndices(Entity entity, 
                                        Collection entityClasses, 
                                        Long deviceKey) {
        for (DeviceIndex index : secondaryIndexMap.values()) {
            index.updateIndex(entity, deviceKey);
        }
        for (IEntityClass clazz : entityClasses) {
            ClassState state = getClassState(clazz);
            for (DeviceIndex index : state.secondaryIndexMap.values()) {
                index.updateIndex(entity, deviceKey);
            }
        }
    }
    
    /**
     * Update the secondary indices for the given entity and associated
     * entity classes
     * @param entity the entity to update
     * @param entityClasses the entity classes for the entity
     * @param deviceKey the device key to set up
     */
    private void updateSecondaryIndices(Entity entity, 
                                        IEntityClass[] entityClasses, 
                                        Long deviceKey) {
        updateSecondaryIndices(entity, Arrays.asList(entityClasses), deviceKey);
    }

    /**
     * Clean up expired entities/devices
     */
File
DeviceManagerImpl.java
Developer's decision
Version 1
Kind of conflict
Attribute
Comment
Method declaration
Chunk
Conflicting content
    /**
     * Clean up expired entities/devices
     */
<<<<<<< HEAD
    protected void cleanupEntities() {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MILLISECOND, -ENTITY_TIMEOUT);
        Date cutoff = c.getTime();
=======
    private void enableDeviceAgingTimer() {
        if (deviceAgingTimer != null) {
            return;
        }

        deviceAgingTimer = new Runnable() {
            @Override
            public void run() {
                Date currentDate = new Date();
                removeAgedDevices(currentDate);

                if (deviceAgingTimer != null) {
                    ScheduledExecutorService ses =
                        threadPool.getScheduledExecutor();
                    ses.schedule(this, DEVICE_AGING_TIMER, TimeUnit.SECONDS);
                }
            }
        };
        threadPool.getScheduledExecutor().schedule(
            deviceAgingTimer, DEVICE_AGING_TIMER_INTERVAL, TimeUnit.SECONDS);
    }
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f

        ArrayList toRemove = new ArrayList();
        ArrayList toKeep = new ArrayList();
Solution content
    /**
     * Clean up expired entities/devices
     */
    protected void cleanupEntities() {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MILLISECOND, -ENTITY_TIMEOUT);
        Date cutoff = c.getTime();

        ArrayList toRemove = new ArrayList();
        ArrayList toKeep = new ArrayList();
File
DeviceManagerImpl.java
Developer's decision
Version 1
Kind of conflict
Method declaration
Method invocation
Method signature
Variable
Chunk
Conflicting content
                    removeEntity(e, d.getEntityClasses(), d.deviceKey, toKeep);
                }

<<<<<<< HEAD
                if (toKeep.size() > 0) {
                    Device newDevice = allocateDevice(d.getDeviceKey(),
                                                      toKeep,
                                                      d.entityClasses);

                    EnumSet changedFields = 
                            EnumSet.noneOf(DeviceField.class);
                    for (Entity e : toRemove) {
                        changedFields.addAll(findChangedFields(newDevice, e));
=======
    protected class DeviceUpdateWorker implements Runnable {
        @Override
        public void run() {
            boolean updatePortChannel = portChannelConfigChanged;
            portChannelConfigChanged = false;

            if (updatePortChannel) {
                readPortChannelConfigFromStorage();
            }

            try { 
                log.debug("DeviceUpdateWorker: cleaning up attachment points.");
                for (IOFSwitch sw  : devMgrMaps.getSwitches()) {
                    // If the set of devices connected to the switches we 
                    // re-iterate a max of 3 times - WHY? TODO
                    int maxIter = 3;
                    while (maxIter > 0) {
                        try {
                            for (Device d: devMgrMaps.getDevicesOnASwitch(sw)) {
                                Device dCopy = new Device(d);
                                cleanupAttachmentPoints(dCopy);
                                for (DeviceAttachmentPoint dap : 
                                    dCopy.getOldAttachmentPoints()) {
                                    // Don't remove conflict attachment points 
                                    // with recent activities
                                    if (dap.isInConflict() && !updatePortChannel)
                                        continue;
                                    // Delete from memory after storage,
                                    // otherwise an exception will
                                    // leave stale attachment points on storage.
                                    log.debug("Remove AP {} from storage for device {}", dap, dCopy.getDlAddrString());
                                    removeAttachmentPointFromStorage(dCopy.getDlAddrString(),
                                        HexString.toHexString(dap.getSwitchPort().getSw().getId()),
                                        dap.getSwitchPort().getPort().toString());
                                    dCopy.removeOldAttachmentPoint(dap);
                                }
                                // Update the maps with the new device copy
                                devMgrMaps.updateMaps(dCopy);
                            }
                            break;
                        }  catch (ConcurrentModificationException e) {
                            maxIter--;
                        } catch (NullPointerException e) { }
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
                    }
                    deviceUpdates.add(new DeviceUpdate(d, CHANGE, 
                                                       changedFields));
Solution content
                    removeEntity(e, d.getEntityClasses(), d.deviceKey, toKeep);
                }

                if (toKeep.size() > 0) {
                    Device newDevice = allocateDevice(d.getDeviceKey(),
                                                      toKeep,
                                                      d.entityClasses);

                    EnumSet changedFields = 
                            EnumSet.noneOf(DeviceField.class);
                    for (Entity e : toRemove) {
                        changedFields.addAll(findChangedFields(newDevice, e));
                    }
                    deviceUpdates.add(new DeviceUpdate(d, CHANGE, 
                                                       changedFields));
File
DeviceManagerImpl.java
Developer's decision
Version 1
Kind of conflict
Annotation
Attribute
Class signature
Comment
For statement
If statement
Method invocation
Method signature
Try statement
Variable
While statement
Chunk
Conflicting content
                        // concurrent modification; try again
                        continue;
                }
<<<<<<< HEAD
                processUpdates(deviceUpdates);
                break;
=======
            } catch (StorageException e) {
                log.error("DeviceUpdateWorker had a storage exception, " +
                        "Floodlight exiting");
                System.exit(1);
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
            }
        }
    }
Solution content
                        // concurrent modification; try again
                        continue;
                }
                processUpdates(deviceUpdates);
                break;
            }
        }
    }
File
DeviceManagerImpl.java
Developer's decision
Version 1
Kind of conflict
Break statement
Catch clause
Method invocation
Chunk
Conflicting content
        }
    }
    
<<<<<<< HEAD
    private void removeEntity(Entity removed, 
                              IEntityClass[] classes,
                              Long deviceKey,
                              Collection others) {
        for (DeviceIndex index : secondaryIndexMap.values()) {
            index.removeEntityIfNeeded(removed, deviceKey, others);
        }
        for (IEntityClass clazz : classes) {
            ClassState classState = getClassState(clazz);
            for (DeviceIndex index : classState.secondaryIndexMap.values()) {
                index.removeEntityIfNeeded(removed, deviceKey, others);
            }
        }
            
        primaryIndex.removeEntityIfNeeded(removed, deviceKey, others);
=======
    // **************************************************
    // Device Manager's Event History members and methods
    // **************************************************

    // Attachment-point event history
    public EventHistory evHistDevMgrAttachPt;
    public EventHistoryAttachmentPoint evHAP;

    private void evHistAttachmtPt(long dlAddr, SwitchPortTuple swPrt,
                                            EvAction action, String reason) {
        evHistAttachmtPt(
                dlAddr,
                swPrt.getSw().getId(),
                swPrt.getPort(), action, reason);
    }

    private void evHistAttachmtPt(byte [] mac, SwitchPortTuple swPrt,
                                          EvAction action, String reason) {
        evHistAttachmtPt(Ethernet.toLong(mac), swPrt.getSw().getId(),
                                            swPrt.getPort(), action, reason);
    }
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f

        for (IEntityClass clazz : classes) {
            ClassState classState = getClassState(clazz);
Solution content
        }
    }
    
    private void removeEntity(Entity removed, 
                              IEntityClass[] classes,
                              Long deviceKey,
                              Collection others) {
        for (DeviceIndex index : secondaryIndexMap.values()) {
            index.removeEntityIfNeeded(removed, deviceKey, others);
        }
        for (IEntityClass clazz : classes) {
            ClassState classState = getClassState(clazz);
            for (DeviceIndex index : classState.secondaryIndexMap.values()) {
                index.removeEntityIfNeeded(removed, deviceKey, others);
            }
        }
            
        primaryIndex.removeEntityIfNeeded(removed, deviceKey, others);

        for (IEntityClass clazz : classes) {
            ClassState classState = getClassState(clazz);
File
DeviceManagerImpl.java
Developer's decision
Version 1
Kind of conflict
Attribute
Comment
For statement
Method declaration
Method invocation
Method signature
Chunk
Conflicting content
    @Override
    }
    

<<<<<<< HEAD
    protected Iterator queryClassByEntity(IEntityClass clazz,
                                                EnumSet keyFields,
                                                Entity entity) {
        ClassState classState = getClassState(clazz);
        DeviceIndex index = classState.secondaryIndexMap.get(keyFields);
        if (index == null) return Collections.emptySet().iterator();
        return new DeviceIndexInterator(this, index.queryByEntity(entity));
    }
    
    protected Device allocateDevice(Long deviceKey,
                                    Entity entity, 
                                    Collection entityClasses) {
        return new Device(this, deviceKey, entity, entityClasses);
=======
    @Override
    public Map, IFloodlightService>
            getServiceImpls() {
        Map,
            IFloodlightService> m = 
            new HashMap,
                        IFloodlightService>();
        // We are the class that implements the service
        m.put(IDeviceManagerService.class, this);
        return m;
    }

    @Override
    public Collection> getModuleDependencies() {
        Collection> l = 
                new ArrayList>();
        l.add(IFloodlightProviderService.class);
        l.add(ITopologyService.class);
        l.add(ILinkDiscoveryService.class);
        l.add(IStorageSourceService.class);
        l.add(IThreadPoolService.class);
        l.add(IRestApiService.class);
        return l;
    }

    @Override
    public void init(FloodlightModuleContext context)
            throws FloodlightModuleException {
        // Wire up all our dependencies
        floodlightProvider = 
                context.getServiceImpl(IFloodlightProviderService.class);
        topology =
                context.getServiceImpl(ITopologyService.class);
        linkDiscovery = 
                context.getServiceImpl(ILinkDiscoveryService.class);
        storageSource =
                context.getServiceImpl(IStorageSourceService.class);
        threadPool =
                context.getServiceImpl(IThreadPoolService.class);
        restApi =
                context.getServiceImpl(IRestApiService.class);
        
        // We create this here because there is no ordering guarantee
        this.deviceManagerAware = new HashSet();
        this.updates = new LinkedList();
        this.devMgrMaps = new DevMgrMaps();
        this.lock = new ReentrantReadWriteLock();
        
        this.evHistDevMgrAttachPt = 
                new EventHistory("Attachment-Point");
        this.evHistDevMgrPktIn =
                new EventHistory("Pakcet-In");
    }

    public void startUp(FloodlightModuleContext context) {
        // This is our 'constructor'

        if (linkDiscovery != null) {
            // Register to get updates from topology
            linkDiscovery.addListener(this);
        } else {
            log.error("Could not add linkdiscovery listener");
        }
        if (topology != null) {
            topology.addListener(this);
        } else {
            log.error("Could not add topology listener");
        }

        // Create our database tables
        storageSource.createTable(DEVICE_TABLE_NAME, null);
        storageSource.setTablePrimaryKeyName(
                        DEVICE_TABLE_NAME, MAC_COLUMN_NAME);
        storageSource.createTable(DEVICE_ATTACHMENT_POINT_TABLE_NAME, null);
        storageSource.setTablePrimaryKeyName(
                        DEVICE_ATTACHMENT_POINT_TABLE_NAME, ID_COLUMN_NAME);
        storageSource.createTable(DEVICE_NETWORK_ADDRESS_TABLE_NAME, null);
        storageSource.setTablePrimaryKeyName(
                        DEVICE_NETWORK_ADDRESS_TABLE_NAME, ID_COLUMN_NAME);
        storageSource.createTable(PORT_CHANNEL_TABLE_NAME, null);
        storageSource.setTablePrimaryKeyName(
                        PORT_CHANNEL_TABLE_NAME, PC_ID_COLUMN_NAME);
        storageSource.addListener(PORT_CHANNEL_TABLE_NAME, this);

        ScheduledExecutorService ses = threadPool.getScheduledExecutor();
        deviceUpdateTask = new SingletonTask(ses, new DeviceUpdateWorker());
         
        // Register for the OpenFlow messages we want
        floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this);
        floodlightProvider.addOFMessageListener(OFType.PORT_STATUS, this);
        // Register for switch events
        floodlightProvider.addOFSwitchListener(this);
        floodlightProvider.addInfoProvider("summary", this);

        // Register our REST API
        restApi.addRestletRoutable(new DeviceManagerWebRoutable());
        
        // Read all our device state (MACs, IPs, attachment points) from storage
        readAllDeviceStateFromStorage();
        // Device and storage aging.
        enableDeviceAgingTimer();
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
    }
    
    protected Device allocateDevice(Long deviceKey,
Solution content
    }
    

    protected Iterator queryClassByEntity(IEntityClass clazz,
                                                EnumSet keyFields,
                                                Entity entity) {
        ClassState classState = getClassState(clazz);
        DeviceIndex index = classState.secondaryIndexMap.get(keyFields);
        if (index == null) return Collections.emptySet().iterator();
        return new DeviceIndexInterator(this, index.queryByEntity(entity));
    }
    
    protected Device allocateDevice(Long deviceKey,
                                    Entity entity, 
                                    Collection entityClasses) {
        return new Device(this, deviceKey, entity, entityClasses);
    }
    
    protected Device allocateDevice(Long deviceKey,
File
DeviceManagerImpl.java
Developer's decision
Version 1
Kind of conflict
Annotation
Attribute
Comment
If statement
Method declaration
Method invocation
Method signature
Return statement
Variable
Chunk
Conflicting content
     * @param cntx The FloodlightContext associated with this OFPacketIn
     */
    protected void doFlood(IOFSwitch sw, OFPacketIn pi, FloodlightContext cntx) {
<<<<<<< HEAD
        if (topology.isIncomingBroadcastAllowedOnSwitchPort(sw.getId(),
                                                            pi.getInPort()) == false) {
=======
        SwitchPortTuple srcSwTuple =  new SwitchPortTuple(sw, pi.getInPort());
        if (topology.isIncomingBroadcastAllowed(sw.getId(),pi.getInPort()) == false) {
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
            if (log.isTraceEnabled()) {
                log.trace("doFlood, drop broadcast packet, pi={}, " + 
                          "from a blocked port, srcSwitch=[{},{}], linkInfo={}",
Solution content
     * @param cntx The FloodlightContext associated with this OFPacketIn
     */
    protected void doFlood(IOFSwitch sw, OFPacketIn pi, FloodlightContext cntx) {
        if (topology.isIncomingBroadcastAllowed(sw.getId(),
                                                pi.getInPort()) == false) {
            if (log.isTraceEnabled()) {
                log.trace("doFlood, drop broadcast packet, pi={}, " + 
                          "from a blocked port, srcSwitch=[{},{}], linkInfo={}",
File
Forwarding.java
Developer's decision
Manual
Kind of conflict
If statement
Method invocation
Variable
Chunk
Conflicting content
        return "forwarding";
    }

<<<<<<< HEAD
=======
    // Comparator for sorting by SwitchCluster
    public Comparator clusterIdComparator = new Comparator() {
        @Override
        public int compare(DeviceAttachmentPoint d1, DeviceAttachmentPoint d2) {
            Long d1ClusterId = topology.getSwitchClusterId(d1.getSwitchPort().getSw().getId());
            Long d2ClusterId = topology.getSwitchClusterId(d2.getSwitchPort().getSw().getId());
            return d1ClusterId.compareTo(d2ClusterId);
        }
    };

    // Comparator for sorting the attachment points by last seen.
    public Comparator lastSeenComparator = new Comparator() {
        @Override
        public int compare(DeviceAttachmentPoint d1, DeviceAttachmentPoint d2) {
            return d1.getLastSeen().compareTo(d2.getLastSeen());
        }
    };
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
    /**
     * All subclasses must define this function if they want any specific
     * forwarding action
Solution content
        return "forwarding";
    }

    /**
     * All subclasses must define this function if they want any specific
     * forwarding action
File
ForwardingBase.java
Developer's decision
Version 1
Kind of conflict
Attribute
Comment
Method invocation
Chunk
Conflicting content
        try {
            counterStore.updatePktOutFMCounterStore(sw, fm);
<<<<<<< HEAD
            log.debug("pushRoute flowmod sw={} inPort={} outPort={}",
                      new Object[] {
                                    sw,
                                    fm.getMatch().getInputPort(),
                                    ((OFActionOutput) fm.getActions().get(0)).getPort() });
            log.info("Flow mod sent: Wildcard={} match={}",
                     Integer.toHexString(fm.getMatch().getWildcards()),
                     fm.getMatch().toString());
=======
            if (log.isTraceEnabled()) {
                log.debug("pushRoute flowmod sw={} inPort={} outPort={}",
                      new Object[] { sw, fm.getMatch().getInputPort(), 
                                    ((OFActionOutput)fm.getActions().get(0)).getPort() });
            }
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
            sw.write(fm, cntx);
            if (doFlush) {
                sw.flush();
Solution content
        try {
            counterStore.updatePktOutFMCounterStore(sw, fm);
            if (log.isTraceEnabled()) {
                log.trace("pushRoute flowmod sw={} inPort={} outPort={}",
                      new Object[] { sw, fm.getMatch().getInputPort(), 
                                    ((OFActionOutput)fm.getActions().get(0)).getPort() });
            }
            sw.write(fm, cntx);
            if (doFlush) {
                sw.flush();
File
ForwardingBase.java
Developer's decision
Manual
Kind of conflict
If statement
Method invocation
Chunk
Conflicting content
            }
        }
        
<<<<<<< HEAD
        if (log.isDebugEnabled()) {
            log.debug("PacketOut srcSwitch={} match={} pi={}",
                      new Object[] { sw, match, pi });
=======
        if (log.isTraceEnabled()) {
            log.debug("PacketOut srcSwitch={} match={} pi={}", new Object[] {sw, match, pi});
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
        }

        OFPacketOut po =
Solution content
            }
        }
        
        if (log.isTraceEnabled()) {
            log.trace("PacketOut srcSwitch={} match={} pi={}", 
                      new Object[] {sw, match, pi});
        }

        OFPacketOut po =
File
ForwardingBase.java
Developer's decision
Manual
Kind of conflict
If statement
Method invocation
Chunk
Conflicting content
        OFMatch match = new OFMatch();
        match.setDataLayerDestination(Ethernet.toByteArray(device.getMACAddress()));
        match.setWildcards(OFMatch.OFPFW_ALL ^ OFMatch.OFPFW_DL_DST);
<<<<<<< HEAD
        OFMessage fm =
                ((OFFlowMod) floodlightProvider.getOFMessageFactory()
                                               .getMessage(OFType.FLOW_MOD)).setCommand(OFFlowMod.OFPFC_DELETE)
                                                                            .setOutPort((short) OFPort.OFPP_NONE.getValue())
                                                                            .setMatch(match)
                                                                            .setLength(U16.t(OFFlowMod.MINIMUM_LENGTH));
=======
        long cookie =
                AppCookie.makeCookie(FORWARDING_APP_ID, 0);
        OFMessage fm = ((OFFlowMod) floodlightProvider.getOFMessageFactory()
            .getMessage(OFType.FLOW_MOD))
            .setCommand(OFFlowMod.OFPFC_DELETE)
            .setOutPort((short) OFPort.OFPP_NONE.getValue())
            .setMatch(match)
            .setCookie(cookie)
            .setLength(U16.t(OFFlowMod.MINIMUM_LENGTH));
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f

        // Flush to all switches
        for (IOFSwitch outSw : floodlightProvider.getSwitches().values()) {
Solution content
        OFMatch match = new OFMatch();
        match.setDataLayerDestination(Ethernet.toByteArray(device.getMACAddress()));
        match.setWildcards(OFMatch.OFPFW_ALL ^ OFMatch.OFPFW_DL_DST);
        long cookie =
                AppCookie.makeCookie(FORWARDING_APP_ID, 0);
        OFMessage fm = ((OFFlowMod) floodlightProvider.getOFMessageFactory()
            .getMessage(OFType.FLOW_MOD))
            .setCommand(OFFlowMod.OFPFC_DELETE)
            .setOutPort((short) OFPort.OFPP_NONE.getValue())
            .setMatch(match)
            .setCookie(cookie)
            .setLength(U16.t(OFFlowMod.MINIMUM_LENGTH));

        // Flush to all switches
        for (IOFSwitch outSw : floodlightProvider.getSwitches().values()) {
File
ForwardingBase.java
Developer's decision
Version 2
Kind of conflict
Method invocation
Variable
Chunk
Conflicting content
     * @param switch2 the DPID of the second switch
     * @return true if the switches are in the same cluster
     */
<<<<<<< HEAD
    public boolean inSameCluster(Long switch1, Long switch2);
=======
    public boolean inSameCluster(long switch1, long switch2);

    /**
     * Queries whether two switches are in the same island.
     * Currently, island and cluster are the same. In future,
     * islands could be different than clusters.
     * @param switch1
     * @param switch2
     * @return
     */
    public boolean inSameIsland(long switch1, long switch2);
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f

    public void addListener(ITopologyListener listener);
Solution content
     * @param switch2 the DPID of the second switch
     * @return true if the switches are in the same cluster
     */
    public boolean inSameCluster(long switch1, long switch2);

    /**
     * Queries whether two switches are in the same island.
     * Currently, island and cluster are the same. In future,
     * islands could be different than clusters.
     * @param switch1
     * @param switch2
     * @return
     */
    public boolean inSameIsland(long switch1, long switch2);

    public void addListener(ITopologyListener listener);
File
ITopologyService.java
Developer's decision
Version 2
Kind of conflict
Comment
Method interface
Chunk
Conflicting content
    @Test
    }
    
    @Test
<<<<<<< HEAD
    public void testAttachmentPointLearning() throws Exception {
        IDeviceListener mockListener = 
                createStrictMock(IDeviceListener.class);
        
        deviceManager.addListener(mockListener);

        ITopologyService mockTopology = createMock(ITopologyService.class);
        expect(mockTopology.getSwitchClusterId(1L)).
        andReturn(1L).anyTimes();
        expect(mockTopology.getSwitchClusterId(5L)).
        andReturn(1L).anyTimes();
        expect(mockTopology.getSwitchClusterId(10L)).
        andReturn(10L).anyTimes();
        expect(mockTopology.getSwitchClusterId(50L)).
        andReturn(10L).anyTimes();
        
        expect(mockTopology.isInternal(anyLong(), 
                                       anyShort())).andReturn(false).anyTimes();
        
        replay(mockTopology);
        
        deviceManager.topology = mockTopology;
        
        Calendar c = Calendar.getInstance();
        Entity entity1 = new Entity(1L, null, 1, 1L, 1, c.getTime());
        c.add(Calendar.SECOND, 1);
        Entity entity2 = new Entity(1L, null, null, 5L, 1, c.getTime());
        c.add(Calendar.SECOND, 1);
        Entity entity3 = new Entity(1L, null, null, 10L, 1, c.getTime());
        c.add(Calendar.SECOND, 1);
        Entity entity4 = new Entity(1L, null, null, 50L, 1, c.getTime());
        
        IDevice d;
        SwitchPort[] aps;
        Integer[] ips;

        mockListener.deviceAdded(isA(IDevice.class));
        replay(mockListener);

        d = deviceManager.learnDeviceByEntity(entity1);
        assertEquals(1, deviceManager.getAllDevices().size());
        aps = d.getAttachmentPoints(); 
        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1) }, aps);
        ips = d.getIPv4Addresses();
        assertArrayEquals(new Integer[] { 1 }, ips);
        verify(mockListener);

        reset(mockListener);
        mockListener.deviceMoved((isA(IDevice.class)));
        replay(mockListener);

        d = deviceManager.learnDeviceByEntity(entity2);
        assertEquals(1, deviceManager.getAllDevices().size());
        aps = d.getAttachmentPoints(); 
        assertArrayEquals(new SwitchPort[] { new SwitchPort(5L, 1) }, aps);
        ips = d.getIPv4Addresses();
        assertArrayEquals(new Integer[] { 1 }, ips);
        verify(mockListener);

        reset(mockListener);
        mockListener.deviceMoved((isA(IDevice.class)));
        replay(mockListener);

        d = deviceManager.learnDeviceByEntity(entity3);
        assertEquals(1, deviceManager.getAllDevices().size());
        aps = d.getAttachmentPoints(); 
        assertArrayEquals(new SwitchPort[] { new SwitchPort(5L, 1),
                                             new SwitchPort(10L, 1) }, aps);
        ips = d.getIPv4Addresses();
        assertArrayEquals(new Integer[] { 1 }, ips);
        verify(mockListener);

        reset(mockListener);
        mockListener.deviceMoved((isA(IDevice.class)));
        replay(mockListener);

        d = deviceManager.learnDeviceByEntity(entity4);
        assertEquals(1, deviceManager.getAllDevices().size());
        aps = d.getAttachmentPoints(); 
        assertArrayEquals(new SwitchPort[] { new SwitchPort(5L, 1), 
                                             new SwitchPort(50L, 1) }, aps);
        ips = d.getIPv4Addresses();
        assertArrayEquals(new Integer[] { 1 }, ips);
        verify(mockListener);
    }

    @Test
    public void testPacketIn() throws Exception {
        byte[] dataLayerSource = 
                ((Ethernet)this.testARPReplyPacket_1).getSourceMACAddress();
=======
    public void testIsNewer() throws Exception {
        long delta = 100;

        IOFSwitch bdsw1 = createMock(IOFSwitch.class);
        IOFSwitch bdsw2 = createMock(IOFSwitch.class);
        IOFSwitch nonbdsw1 = createMock(IOFSwitch.class);
        IOFSwitch nonbdsw2 = createMock(IOFSwitch.class);
        expect(bdsw1.getId()).andReturn(1L).anyTimes();
        expect(bdsw2.getId()).andReturn(2L).anyTimes();
        expect(nonbdsw1.getId()).andReturn(3L).anyTimes();
        expect(nonbdsw2.getId()).andReturn(4L).anyTimes();

        ITopologyService mockTopology = createMock(ITopologyService.class);
        SwitchPortTuple bdspt1 = new SwitchPortTuple(bdsw1, (short)1);
        SwitchPortTuple bdspt2 = new SwitchPortTuple(bdsw2, (short)1);
        SwitchPortTuple nonbdspt1 = new SwitchPortTuple(nonbdsw1, (short)1);
        SwitchPortTuple nonbdspt2 = new SwitchPortTuple(nonbdsw2, (short)1);
        deviceManager.setTopology(mockTopology);
        expect(mockTopology.isBroadcastDomainPort(1L, (short)1)).andReturn(true).anyTimes();
        expect(mockTopology.isBroadcastDomainPort(2L, (short)1)).andReturn(true).anyTimes();
        expect(mockTopology.isBroadcastDomainPort(3L, (short)1)).andReturn(false).anyTimes();
        expect(mockTopology.isBroadcastDomainPort(4L, (short)1)).andReturn(false).anyTimes();

        // Two BD APs comparison
        Date lastSeen_bd1 = new Date();
        Date lastSeen_bd2 = new Date(lastSeen_bd1.getTime() + DeviceManagerImpl.BD_TO_BD_TIMEDIFF_MS + delta);
        DeviceAttachmentPoint dap_bd1 = new DeviceAttachmentPoint(bdspt1, lastSeen_bd1);
        DeviceAttachmentPoint dap_bd2 = new DeviceAttachmentPoint(bdspt2, lastSeen_bd2);

        Date lastSeen_bd3 = new Date();
        Date lastSeen_bd4 = new Date(lastSeen_bd3.getTime() - DeviceManagerImpl.BD_TO_BD_TIMEDIFF_MS + delta);
        DeviceAttachmentPoint dap_bd3 = new DeviceAttachmentPoint(bdspt1, lastSeen_bd3);
        DeviceAttachmentPoint dap_bd4 = new DeviceAttachmentPoint(bdspt2, lastSeen_bd4);

        // Two non-BD APs comparison
        Date lastSeen_nonbd1 = new Date();
        Date lastSeen_nonbd2 = new Date(lastSeen_nonbd1.getTime() + delta);
        DeviceAttachmentPoint dap_nonbd1 = new DeviceAttachmentPoint(nonbdspt1, lastSeen_nonbd1);
        DeviceAttachmentPoint dap_nonbd2 = new DeviceAttachmentPoint(nonbdspt2, lastSeen_nonbd2);

        Date lastSeen_nonbd3 = new Date();
        Date lastSeen_nonbd4 = new Date(lastSeen_bd3.getTime() - delta);
        DeviceAttachmentPoint dap_nonbd3 = new DeviceAttachmentPoint(nonbdspt1, lastSeen_nonbd3);
        DeviceAttachmentPoint dap_nonbd4 = new DeviceAttachmentPoint(nonbdspt2, lastSeen_nonbd4);

        // BD and non-BD APs comparison
        Date lastSeen_bd5 = new Date();
        Date lastSeen_nonbd5 = new Date(lastSeen_bd3.getTime() - DeviceManagerImpl.NBD_TO_BD_TIMEDIFF_MS + delta);
        DeviceAttachmentPoint dap_bd5 = new DeviceAttachmentPoint(bdspt1, lastSeen_bd5);
        DeviceAttachmentPoint dap_nonbd5 = new DeviceAttachmentPoint(bdspt2, lastSeen_nonbd5);

        Date lastSeen_bd6 = new Date();
        Date lastSeen_nonbd6 = new Date(lastSeen_bd6.getTime() + DeviceManagerImpl.NBD_TO_BD_TIMEDIFF_MS + delta);
        DeviceAttachmentPoint dap_bd6 = new DeviceAttachmentPoint(nonbdspt1, lastSeen_bd6);
        DeviceAttachmentPoint dap_nonbd6 = new DeviceAttachmentPoint(nonbdspt2, lastSeen_nonbd6);

        replay(bdsw1, bdsw2, nonbdsw1, nonbdsw2, mockTopology);

        boolean testbd1_2 = deviceManager.isNewer(dap_bd1, dap_bd2);
        boolean testbd2_1 = deviceManager.isNewer(dap_bd2, dap_bd1);
        boolean testbd3_4 = deviceManager.isNewer(dap_bd3, dap_bd4);
        boolean testbd4_3 = deviceManager.isNewer(dap_bd4, dap_bd3);

        boolean testnonbd1_2 = deviceManager.isNewer(dap_nonbd1, dap_nonbd2);
        boolean testnonbd2_1 = deviceManager.isNewer(dap_nonbd2, dap_nonbd1);
        boolean testnonbd3_4 = deviceManager.isNewer(dap_nonbd3, dap_nonbd4);
        boolean testnonbd4_3 = deviceManager.isNewer(dap_nonbd4, dap_nonbd3);

        boolean testbdnonbd5_5 = deviceManager.isNewer(dap_bd5, dap_nonbd5);
        boolean testnonbdbd5_5 = deviceManager.isNewer(dap_nonbd5, dap_bd5);
        boolean testbdnonbd6_6 = deviceManager.isNewer(dap_bd6, dap_nonbd6);
        boolean testnonbdbd6_6 = deviceManager.isNewer(dap_nonbd6, dap_bd6);

        verify(bdsw1, bdsw2, nonbdsw1, nonbdsw2, mockTopology);

        assertFalse(testbd1_2);
        assertTrue(testbd2_1);
        assertFalse(testbd3_4);
        assertTrue(testbd4_3);

        assertFalse(testnonbd1_2);
        assertTrue(testnonbd2_1);
        assertTrue(testnonbd3_4);
        assertFalse(testnonbd4_3);

        assertTrue(testbdnonbd5_5);
        assertFalse(testnonbdbd5_5);
        assertFalse(testbdnonbd6_6);
        assertTrue(testnonbdbd6_6);
    }

    public void testDeviceAging() throws Exception {

        byte[] dataLayerSource = ((Ethernet)this.testARPReplyPacket_1).getSourceMACAddress();

        // Mock up our expected behavior
        IOFSwitch mockSwitch1 = createMock(IOFSwitch.class);
        expect(mockSwitch1.getId()).andReturn(1L).anyTimes();
        expect(mockSwitch1.getStringId()).andReturn("00:00:00:00:00:00:00:01").anyTimes();
        IOFSwitch mockSwitch2 = createMock(IOFSwitch.class);
        ITopologyService mockTopology = createMock(ITopologyService.class);
        expect(mockTopology.isInternal(1L, (short)1)).andReturn(false);
        deviceManager.setTopology(mockTopology);

        // reduce the aging period to a few seconds
        DeviceManagerImpl.DEVICE_AGING_TIMER = 2;
        DeviceManagerImpl.DEVICE_AP_MAX_AGE = 1;
        DeviceManagerImpl.DEVICE_NA_MAX_AGE = 1;
        DeviceManagerImpl.DEVICE_MAX_AGE = 3;

        Date currentDate = new Date();

        // build our expected Device
        Device device = new Device();
        device.setDataLayerAddress(dataLayerSource);
        device.addAttachmentPoint(new SwitchPortTuple(mockSwitch1, (short)1), currentDate);
        Integer ipaddr = IPv4.toIPv4Address("192.168.1.1");
        device.addNetworkAddress(ipaddr, currentDate);

        expect(mockSwitch2.getId()).andReturn(2L).anyTimes();
        expect(mockSwitch2.getStringId()).andReturn("00:00:00:00:00:00:00:02").anyTimes();
        expect(mockTopology.isInternal(2L, (short)2)).andReturn(false);
        expect(mockTopology.inSameCluster(1L, 2L)).andReturn(false).atLeastOnce();
        expect(mockTopology.isAllowed(EasyMock.anyLong(), EasyMock.anyShort())).andReturn(true).anyTimes();

        // Start recording the replay on the mocks
        replay(mockSwitch1, mockSwitch2, mockTopology);
        // Get the listener and trigger the packet in
        mockFloodlightProvider.dispatchMessage(mockSwitch1, this.packetIn_1);

        // Get the listener and trigger the packet in
        mockFloodlightProvider.dispatchMessage(mockSwitch2, this.packetIn_3.setInPort((short)2));

        // Verify the replay matched our expectations
        verify(mockSwitch1, mockSwitch2, mockTopology);
        // Verify the device
        Device rdevice = deviceManager.getDeviceByDataLayerAddress(dataLayerSource);
        assertEquals(device, rdevice);
        assertEquals(2, rdevice.getAttachmentPoints().size());
        assertEquals(2, rdevice.getNetworkAddresses().size());

        // Sleep to make sure the aging thread has run
        Thread.sleep((DeviceManagerImpl.DEVICE_AGING_TIMER + DeviceManagerImpl.DEVICE_AGING_TIMER_INTERVAL)*1000);

        rdevice = deviceManager.getDeviceByDataLayerAddress(dataLayerSource);
        assertEquals(0, rdevice.getAttachmentPoints().size());
        assertEquals(0, rdevice.getNetworkAddresses().size());

        // Make sure the device's AP and NA were removed from storage
        deviceManager.readAllDeviceStateFromStorage();
        rdevice = deviceManager.getDeviceByDataLayerAddress(dataLayerSource);
        assertEquals(0, rdevice.getAttachmentPoints().size());
        assertEquals(0, rdevice.getNetworkAddresses().size());

        // Sleep 4 more seconds to allow device aging thread to run
        Thread.sleep(DeviceManagerImpl.DEVICE_MAX_AGE*1000);

        assertNull(deviceManager.getDeviceByDataLayerAddress(dataLayerSource));

        // Make sure the device's AP and NA were removed from storage
        deviceManager.readAllDeviceStateFromStorage();
        assertNull(deviceManager.getDeviceByDataLayerAddress(dataLayerSource));

        // Reset the device cache
        deviceManager.clearAllDeviceStateFromMemory();
    }

    @Test
    public void testDeviceDiscover() throws Exception {

        byte[] dataLayerSource = ((Ethernet)this.testARPReplyPacket_1).getSourceMACAddress();
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f

        // Mock up our expected behavior
        ITopologyService mockTopology = createMock(ITopologyService.class);
Solution content
    }
    
    @Test
    public void testAttachmentPointLearning() throws Exception {
        IDeviceListener mockListener = 
                createStrictMock(IDeviceListener.class);
        
        deviceManager.addListener(mockListener);

        ITopologyService mockTopology = createMock(ITopologyService.class);
        expect(mockTopology.getSwitchClusterId(1L)).
        andReturn(1L).anyTimes();
        expect(mockTopology.getSwitchClusterId(5L)).
        andReturn(1L).anyTimes();
        expect(mockTopology.getSwitchClusterId(10L)).
        andReturn(10L).anyTimes();
        expect(mockTopology.getSwitchClusterId(50L)).
        andReturn(10L).anyTimes();
        
        expect(mockTopology.isInternal(anyLong(), 
                                       anyShort())).andReturn(false).anyTimes();
        
        replay(mockTopology);
        
        deviceManager.topology = mockTopology;
        
        Calendar c = Calendar.getInstance();
        Entity entity1 = new Entity(1L, null, 1, 1L, 1, c.getTime());
        c.add(Calendar.SECOND, 1);
        Entity entity2 = new Entity(1L, null, null, 5L, 1, c.getTime());
        c.add(Calendar.SECOND, 1);
        Entity entity3 = new Entity(1L, null, null, 10L, 1, c.getTime());
        c.add(Calendar.SECOND, 1);
        Entity entity4 = new Entity(1L, null, null, 50L, 1, c.getTime());
        
        IDevice d;
        SwitchPort[] aps;
        Integer[] ips;

        mockListener.deviceAdded(isA(IDevice.class));
        replay(mockListener);

        d = deviceManager.learnDeviceByEntity(entity1);
        assertEquals(1, deviceManager.getAllDevices().size());
        aps = d.getAttachmentPoints(); 
        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1) }, aps);
        ips = d.getIPv4Addresses();
        assertArrayEquals(new Integer[] { 1 }, ips);
        verify(mockListener);

        reset(mockListener);
        mockListener.deviceMoved((isA(IDevice.class)));
        replay(mockListener);

        d = deviceManager.learnDeviceByEntity(entity2);
        assertEquals(1, deviceManager.getAllDevices().size());
        aps = d.getAttachmentPoints(); 
        assertArrayEquals(new SwitchPort[] { new SwitchPort(5L, 1) }, aps);
        ips = d.getIPv4Addresses();
        assertArrayEquals(new Integer[] { 1 }, ips);
        verify(mockListener);

        reset(mockListener);
        mockListener.deviceMoved((isA(IDevice.class)));
        replay(mockListener);

        d = deviceManager.learnDeviceByEntity(entity3);
        assertEquals(1, deviceManager.getAllDevices().size());
        aps = d.getAttachmentPoints(); 
        assertArrayEquals(new SwitchPort[] { new SwitchPort(5L, 1),
                                             new SwitchPort(10L, 1) }, aps);
        ips = d.getIPv4Addresses();
        assertArrayEquals(new Integer[] { 1 }, ips);
        verify(mockListener);

        reset(mockListener);
        mockListener.deviceMoved((isA(IDevice.class)));
        replay(mockListener);

        d = deviceManager.learnDeviceByEntity(entity4);
        assertEquals(1, deviceManager.getAllDevices().size());
        aps = d.getAttachmentPoints(); 
        assertArrayEquals(new SwitchPort[] { new SwitchPort(5L, 1), 
                                             new SwitchPort(50L, 1) }, aps);
        ips = d.getIPv4Addresses();
        assertArrayEquals(new Integer[] { 1 }, ips);
        verify(mockListener);
    }

    @Test
    public void testPacketIn() throws Exception {
        byte[] dataLayerSource = 
                ((Ethernet)this.testARPReplyPacket_1).getSourceMACAddress();

        // Mock up our expected behavior
        ITopologyService mockTopology = createMock(ITopologyService.class);
File
DeviceManagerImplTest.java
Developer's decision
Version 1
Kind of conflict
Annotation
Method declaration
Method invocation
Method signature
Variable
Chunk
Conflicting content
        mockFloodlightProvider.dispatchMessage(switch1, this.packetIn_1);

        // Verify the replay matched our expectations
<<<<<<< HEAD
        verify(mockTopology);
=======
        verify(mockSwitch);
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f

        // Verify the device
        Device rdevice = (Device)
Solution content
        mockFloodlightProvider.dispatchMessage(switch1, this.packetIn_1);

        // Verify the replay matched our expectations
        verify(mockTopology);

        // Verify the device
        Device rdevice = (Device)
File
DeviceManagerImplTest.java
Developer's decision
Version 1
Kind of conflict
Method invocation
Chunk
Conflicting content
            result = (Device)dstiter.next();
        }

<<<<<<< HEAD
        assertEquals(device, result);
        
        device = 
                new Device(device,
                           new Entity(Ethernet.toLong(dataLayerSource),
                                      (short)5,
                                      ipaddr,
                                      5L,
                                      2,
                                      currentDate),
                           DefaultEntityClassifier.entityClasses);

        reset(mockTopology);
        expect(mockTopology.isInternal(anyLong(), 
                                       anyShort())).andReturn(false).anyTimes();
        expect(mockTopology.getSwitchClusterId(1L)).andReturn(1L).anyTimes();
        expect(mockTopology.getSwitchClusterId(5L)).andReturn(1L).anyTimes();
        
=======
        // move the port on this device
        device.addAttachmentPoint(new SwitchPortTuple(mockSwitch, (short)2), currentDate);

        reset(mockSwitch, mockTopology);
        expect(mockSwitch.getId()).andReturn(2L).anyTimes();
        expect(mockSwitch.getStringId()).andReturn("00:00:00:00:00:00:00:02").anyTimes();
        expect(mockTopology.isInternal(2L, (short)2)).andReturn(false);

        assertEquals(1, deviceManager.getDeviceByIPv4Address(ipaddr).getAttachmentPoints().size());
        deviceManager.invalidateDeviceAPsByIPv4Address(ipaddr);
        assertEquals(0, deviceManager.getDeviceByIPv4Address(ipaddr).getAttachmentPoints().size());

        expect(mockTopology.isAllowed(EasyMock.anyLong(), EasyMock.anyShort())).andReturn(true).anyTimes();
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
        // Start recording the replay on the mocks
        replay(mockTopology);
        // Get the listener and trigger the packet in
Solution content
            result = (Device)dstiter.next();
        }

        assertEquals(device, result);
        
        device = 
                new Device(device,
                           new Entity(Ethernet.toLong(dataLayerSource),
                                      (short)5,
                                      ipaddr,
                                      5L,
                                      2,
                                      currentDate),
                           DefaultEntityClassifier.entityClasses);

        reset(mockTopology);
        expect(mockTopology.isInternal(anyLong(), 
                                       anyShort())).andReturn(false).anyTimes();
        expect(mockTopology.getSwitchClusterId(1L)).andReturn(1L).anyTimes();
        expect(mockTopology.getSwitchClusterId(5L)).andReturn(1L).anyTimes();
        
        // Start recording the replay on the mocks
        replay(mockTopology);
        // Get the listener and trigger the packet in
File
DeviceManagerImplTest.java
Developer's decision
Version 1
Kind of conflict
Comment
Method invocation
Variable
Chunk
Conflicting content

        Iterator diter = 
        verify(mockTopology);

        // Verify the device
<<<<<<< HEAD
        rdevice = (Device)
                deviceManager.findDevice(Ethernet.toLong(dataLayerSource), 
                                         (short)5, null, null, null);
        assertEquals(device, rdevice);
    }

    @Test
    public void testEntityExpiration() throws Exception {
        IDeviceListener mockListener = 
                createStrictMock(IDeviceListener.class);
        mockListener.deviceIPV4AddrChanged(isA(IDevice.class));
        mockListener.deviceMoved(isA(IDevice.class));
        
        ITopologyService mockTopology = createMock(ITopologyService.class);
        expect(mockTopology.isInternal(anyLong(), 
                                       anyShort())).andReturn(false).anyTimes();
        expect(mockTopology.getSwitchClusterId(1L)).andReturn(1L).anyTimes();
        Date currentDate = new Date();
        expect(mockTopology.getSwitchClusterId(5L)).andReturn(5L).anyTimes();
        replay(mockTopology);
        deviceManager.topology = mockTopology;
        
        Calendar c = Calendar.getInstance();
        Entity entity1 = new Entity(1L, null, 2, 1L, 1, c.getTime());
        c.add(Calendar.MILLISECOND, -DeviceManagerImpl.ENTITY_TIMEOUT-1);
        Entity entity2 = new Entity(1L, null, 1, 5L, 1, c.getTime());

        deviceManager.learnDeviceByEntity(entity1);
        IDevice d = deviceManager.learnDeviceByEntity(entity2);
        assertArrayEquals(new Integer[] { 1, 2 }, d.getIPv4Addresses());
        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1),
                                             new SwitchPort(5L, 1) }, 
                          d.getAttachmentPoints());
                deviceManager.queryClassDevices(d, null, null, 1, null, null);
        assertTrue(diter.hasNext());
        assertEquals(d.getDeviceKey(), diter.next().getDeviceKey());
        diter = deviceManager.queryClassDevices(d, null, null, 2, null, null);
        assertTrue(diter.hasNext());
        assertEquals(d.getDeviceKey(), diter.next().getDeviceKey());
        
        deviceManager.addListener(mockListener);
        replay(mockListener);
        deviceManager.entityCleanupTask.reschedule(0, null);
        
        d = deviceManager.getDevice(d.getDeviceKey());
        assertArrayEquals(new Integer[] { 2 }, d.getIPv4Addresses());
        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1) }, 
                          d.getAttachmentPoints());
        diter = deviceManager.queryClassDevices(d, null, null, 2, null, null);
        assertTrue(diter.hasNext());
        assertEquals(d.getDeviceKey(), diter.next().getDeviceKey());
        diter = deviceManager.queryClassDevices(d, null, null, 1, null, null);
        assertFalse(diter.hasNext());
        
        d = deviceManager.findDevice(1L, null, null, null, null);
        assertArrayEquals(new Integer[] { 2 }, d.getIPv4Addresses());
        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1) }, 
                          d.getAttachmentPoints());
        
        verify(mockListener);
    }

    @Test
    public void testDeviceExpiration() throws Exception {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MILLISECOND, -DeviceManagerImpl.ENTITY_TIMEOUT-1);
        Entity entity1 = new Entity(1L, null, 1, 1L, 1, c.getTime());
        Entity entity2 = new Entity(1L, null, 2, 5L, 1, c.getTime());

        IDevice d = deviceManager.learnDeviceByEntity(entity2);
        d = deviceManager.learnDeviceByEntity(entity1);
        assertArrayEquals(new Integer[] { 1, 2 }, d.getIPv4Addresses());
        
        deviceManager.entityCleanupTask.reschedule(0, null);

        IDevice r = deviceManager.getDevice(d.getDeviceKey());
        assertNull(r);
        Iterator diter = 
                deviceManager.queryClassDevices(d, null, null, 1, null, null);
        assertFalse(diter.hasNext());
        
        r = deviceManager.findDevice(1L, null, null, null, null);
        assertNull(r);
   }
    
    @Test
    public void testAttachmentPointFlapping() throws Exception {
        fail();
        /*
    	OFPhysicalPort port1 = new OFPhysicalPort();
    	OFPhysicalPort port2 = new OFPhysicalPort();
=======
        assertEquals(device, deviceManager.getDeviceByDataLayerAddress(dataLayerSource));

        // Reset the device cache
        deviceManager.clearAllDeviceStateFromMemory();
    }

    @Test
    public void testDeviceRecoverFromStorage() throws Exception {
        byte[] dataLayerSource = ((Ethernet)this.testARPReplyPacket_2).getSourceMACAddress();

        // Mock up our expected behavior
        IOFSwitch mockSwitch = createMock(IOFSwitch.class);
        ITopologyService mockTopology = createNiceMock(ITopologyService.class);
        expect(mockSwitch.getId()).andReturn(1L).anyTimes();
        expect(mockSwitch.getStringId()).andReturn("00:00:00:00:00:00:00:01").anyTimes();
        expect(mockTopology.isInternal(1L, (short)1)).andReturn(false);
        expect(mockTopology.isAllowed(EasyMock.anyLong(), EasyMock.anyShort())).andReturn(true).anyTimes();
        deviceManager.setTopology(mockTopology);

        // Start recording the replay on the mocks
        replay(mockSwitch, mockTopology);

        // Add the switch so the list isn't empty
        mockFloodlightProvider.getSwitches().put(mockSwitch.getId(), mockSwitch);

        // build our expected Device
        Device device = new Device();
        Date currentDate = new Date();
        Integer ipaddr = IPv4.toIPv4Address("192.168.1.1");
        Integer ipaddr2 = IPv4.toIPv4Address("192.168.1.3");
        device.setDataLayerAddress(dataLayerSource);
        SwitchPortTuple spt = new SwitchPortTuple(mockSwitch, (short)1);
        DeviceAttachmentPoint dap = new DeviceAttachmentPoint(spt, currentDate);
        device.addAttachmentPoint(dap);
        device.addNetworkAddress(ipaddr, currentDate);
        device.addNetworkAddress(ipaddr2, currentDate);

        // Get the listener and trigger the packet ins
        mockFloodlightProvider.dispatchMessage(mockSwitch, this.packetIn_2);
        mockFloodlightProvider.dispatchMessage(mockSwitch, this.packetIn_3);

        // Verify the device
        assertEquals(device, deviceManager.getDeviceByDataLayerAddress(dataLayerSource));
        assertEquals(device, deviceManager.getDeviceByIPv4Address(ipaddr));
        assertEquals(device, deviceManager.getDeviceByIPv4Address(ipaddr2));
        assertEquals(dap, device.getAttachmentPoint(spt));

        // Reset the device cache
        deviceManager.clearAllDeviceStateFromMemory();

        // Verify the device
        assertNull(deviceManager.getDeviceByDataLayerAddress(dataLayerSource));
        assertNull(deviceManager.getDeviceByIPv4Address(ipaddr));
        assertNull(deviceManager.getDeviceByIPv4Address(ipaddr2));

        // Load the device cache from storage
        deviceManager.readAllDeviceStateFromStorage();

        // Verify the device
        Device device2 = deviceManager.getDeviceByDataLayerAddress(dataLayerSource);
        assertEquals(device, device2);
        assertEquals(dap, device2.getAttachmentPoint(spt));

        deviceManager.clearAllDeviceStateFromMemory();
        mockFloodlightProvider.setSwitches(new HashMap());
        deviceManager.removedSwitch(mockSwitch);
        deviceManager.readAllDeviceStateFromStorage();

        device2 = deviceManager.getDeviceByDataLayerAddress(dataLayerSource);
        assertEquals(device, device2);

        assertNull(device2.getAttachmentPoint(spt));
        // The following two asserts seems to be incorrect, need to
        // replace NULL check with the correct value TODO
        //assertNull(deviceManager.getDeviceByIPv4Address(ipaddr));
        //assertNull(deviceManager.getDeviceByIPv4Address(ipaddr2));
        deviceManager.addedSwitch(mockSwitch);
        assertEquals(dap, device.getAttachmentPoint(spt));
        assertEquals(device, deviceManager.getDeviceByIPv4Address(ipaddr));
        assertEquals(device, deviceManager.getDeviceByIPv4Address(ipaddr2));
    }

    @Test
    public void testDeviceUpdateLastSeenToStorage() throws Exception {
        deviceManager.clearAllDeviceStateFromMemory();

        MockFloodlightProvider mockFloodlightProvider = getMockFloodlightProvider();
        byte[] dataLayerSource = ((Ethernet)this.testARPReplyPacket_1).getSourceMACAddress();

        // Mock up our expected behavior
        IOFSwitch mockSwitch = createNiceMock(IOFSwitch.class);
        expect(mockSwitch.getId()).andReturn(1L).atLeastOnce();
        ITopologyService mockTopology = createNiceMock(ITopologyService.class);
        //expect(mockTopology.isInternal(new SwitchPortTuple(mockSwitch, 1))).andReturn(false);
        deviceManager.setTopology(mockTopology);
        expect(mockTopology.isAllowed(EasyMock.anyLong(), EasyMock.anyShort())).andReturn(true).anyTimes();
        // build our expected Device
        Device device = new Device();
        // Set Device to always update last-seen to storage
        Device.setStorageUpdateInterval(1);
        device.setDataLayerAddress(dataLayerSource);
        device.addAttachmentPoint(new SwitchPortTuple(mockSwitch, (short)1), currentDate);
        Integer ipaddr = IPv4.toIPv4Address("192.168.1.1");
        device.addNetworkAddress(ipaddr, currentDate);

        // Start recording the replay on the mocks
        replay(mockSwitch, mockTopology);
        // Get the listener and trigger the packet in
        mockFloodlightProvider.dispatchMessage(mockSwitch, this.packetIn_1);

        Thread.sleep(100);

        // Get the listener and trigger the packet in
        mockFloodlightProvider.dispatchMessage(mockSwitch, this.packetIn_1);

        // Clear the device cache
        deviceManager.clearAllDeviceStateFromMemory();
        // Load the device cache from storage
        deviceManager.readAllDeviceStateFromStorage();

        // Make sure the last seen is after our date
        device = deviceManager.getDeviceByDataLayerAddress(dataLayerSource);
        assertTrue(device.getLastSeen().after(currentDate));
    }

    @Test
    public void testAttachmentPointFlapping() throws Exception {
        OFPhysicalPort port1 = new OFPhysicalPort();
        OFPhysicalPort port2 = new OFPhysicalPort();
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
        port1.setName("port1");
        port2.setName("port2");
Solution content
        verify(mockTopology);

        // Verify the device
        rdevice = (Device)
                deviceManager.findDevice(Ethernet.toLong(dataLayerSource), 
                                         (short)5, null, null, null);
        assertEquals(device, rdevice);
    }

    @Test
    public void testEntityExpiration() throws Exception {
        IDeviceListener mockListener = 
                createStrictMock(IDeviceListener.class);
        mockListener.deviceIPV4AddrChanged(isA(IDevice.class));
        mockListener.deviceMoved(isA(IDevice.class));
        
        ITopologyService mockTopology = createMock(ITopologyService.class);
        expect(mockTopology.isInternal(anyLong(), 
                                       anyShort())).andReturn(false).anyTimes();
        expect(mockTopology.getSwitchClusterId(1L)).andReturn(1L).anyTimes();
        expect(mockTopology.getSwitchClusterId(5L)).andReturn(5L).anyTimes();
        replay(mockTopology);
        deviceManager.topology = mockTopology;
        
        Calendar c = Calendar.getInstance();
        Entity entity1 = new Entity(1L, null, 2, 1L, 1, c.getTime());
        c.add(Calendar.MILLISECOND, -DeviceManagerImpl.ENTITY_TIMEOUT-1);
        Entity entity2 = new Entity(1L, null, 1, 5L, 1, c.getTime());

        deviceManager.learnDeviceByEntity(entity1);
        IDevice d = deviceManager.learnDeviceByEntity(entity2);
        assertArrayEquals(new Integer[] { 1, 2 }, d.getIPv4Addresses());
        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1),
                                             new SwitchPort(5L, 1) }, 
                          d.getAttachmentPoints());
        Iterator diter = 
                deviceManager.queryClassDevices(d, null, null, 1, null, null);
        assertTrue(diter.hasNext());
        assertEquals(d.getDeviceKey(), diter.next().getDeviceKey());
        diter = deviceManager.queryClassDevices(d, null, null, 2, null, null);
        assertTrue(diter.hasNext());
        assertEquals(d.getDeviceKey(), diter.next().getDeviceKey());
        
        deviceManager.addListener(mockListener);
        replay(mockListener);
        deviceManager.entityCleanupTask.reschedule(0, null);
        
        d = deviceManager.getDevice(d.getDeviceKey());
        assertArrayEquals(new Integer[] { 2 }, d.getIPv4Addresses());
        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1) }, 
                          d.getAttachmentPoints());
        diter = deviceManager.queryClassDevices(d, null, null, 2, null, null);
        assertTrue(diter.hasNext());
        assertEquals(d.getDeviceKey(), diter.next().getDeviceKey());
        diter = deviceManager.queryClassDevices(d, null, null, 1, null, null);
        assertFalse(diter.hasNext());
        
        d = deviceManager.findDevice(1L, null, null, null, null);
        assertArrayEquals(new Integer[] { 2 }, d.getIPv4Addresses());
        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1) }, 
                          d.getAttachmentPoints());
        
        verify(mockListener);
    }

    @Test
    public void testDeviceExpiration() throws Exception {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MILLISECOND, -DeviceManagerImpl.ENTITY_TIMEOUT-1);
        Entity entity1 = new Entity(1L, null, 1, 1L, 1, c.getTime());
        Entity entity2 = new Entity(1L, null, 2, 5L, 1, c.getTime());

        IDevice d = deviceManager.learnDeviceByEntity(entity2);
        d = deviceManager.learnDeviceByEntity(entity1);
        assertArrayEquals(new Integer[] { 1, 2 }, d.getIPv4Addresses());
        
        deviceManager.entityCleanupTask.reschedule(0, null);

        IDevice r = deviceManager.getDevice(d.getDeviceKey());
        assertNull(r);
        Iterator diter = 
                deviceManager.queryClassDevices(d, null, null, 1, null, null);
        assertFalse(diter.hasNext());
        
        r = deviceManager.findDevice(1L, null, null, null, null);
        assertNull(r);
   }
    
    @Test
    public void testAttachmentPointFlapping() throws Exception {
        fail();
        /*
    	OFPhysicalPort port1 = new OFPhysicalPort();
    	OFPhysicalPort port2 = new OFPhysicalPort();
        port1.setName("port1");
        port2.setName("port2");
File
DeviceManagerImplTest.java
Developer's decision
Version 1
Kind of conflict
Annotation
Cast expression
Comment
Method declaration
Method invocation
Method signature
Variable
Chunk
Conflicting content
        // Reset the device cache
        deviceManager.clearAllDeviceStateFromMemory();
<<<<<<< HEAD
        */
=======
    }

    private static final Map pcPort1;
    static {
        pcPort1 = new HashMap();
        pcPort1.put(DeviceManagerImpl.PORT_CHANNEL_COLUMN_NAME, "channel");
        pcPort1.put(DeviceManagerImpl.PC_PORT_COLUMN_NAME, "port1");
        pcPort1.put(DeviceManagerImpl.PC_SWITCH_COLUMN_NAME, "00:00:00:00:00:00:00:01");
        pcPort1.put(DeviceManagerImpl.PC_ID_COLUMN_NAME, "00:00:00:00:00:00:00:01|port1");
    }

    private static final Map pcPort2;
    static {
        pcPort2 = new HashMap();
        pcPort2.put(DeviceManagerImpl.PORT_CHANNEL_COLUMN_NAME, "channel");
        pcPort2.put(DeviceManagerImpl.PC_PORT_COLUMN_NAME, "port2");
        pcPort2.put(DeviceManagerImpl.PC_SWITCH_COLUMN_NAME, "00:00:00:00:00:00:00:01");
        pcPort2.put(DeviceManagerImpl.PC_ID_COLUMN_NAME, "00:00:00:00:00:00:00:01|port2");
    }

    private void setupPortChannel() {
        storageSource.insertRow(DeviceManagerImpl.PORT_CHANNEL_TABLE_NAME, pcPort1);
        storageSource.insertRow(DeviceManagerImpl.PORT_CHANNEL_TABLE_NAME, pcPort2);
        deviceManager.readPortChannelConfigFromStorage();
    }

    private void teardownPortChannel() {
        storageSource.deleteRow(DeviceManagerImpl.PORT_CHANNEL_TABLE_NAME,
                pcPort1.get(DeviceManagerImpl.PC_ID_COLUMN_NAME));
        storageSource.deleteRow(DeviceManagerImpl.PORT_CHANNEL_TABLE_NAME,
                pcPort2.get(DeviceManagerImpl.PC_ID_COLUMN_NAME));
        deviceManager.readPortChannelConfigFromStorage();
    }

    /**
     * The same test as testAttachmentPointFlapping except for port-channel
     * @throws Exception
     */
    @Test
    public void testPortChannel() throws Exception {
        OFPhysicalPort port1 = new OFPhysicalPort();
        OFPhysicalPort port2 = new OFPhysicalPort();
        port1.setName("port1");
        port2.setName("port2");

        setupPortChannel();
        byte[] dataLayerSource = ((Ethernet)this.testARPReplyPacket_1).getSourceMACAddress();

        // Mock up our expected behavior
        IOFSwitch mockSwitch = createMock(IOFSwitch.class);
        expect(mockSwitch.getPort((short)1)).andReturn(port1).anyTimes();
        expect(mockSwitch.getPort((short)2)).andReturn(port2).anyTimes();
        expect(mockSwitch.getId()).andReturn(1L).anyTimes();
        expect(mockSwitch.getStringId()).andReturn("00:00:00:00:00:00:00:01").anyTimes();
        ITopologyService mockTopology = createMock(ITopologyService.class);
        expect(mockTopology.isInternal(1L, (short)1))
                           .andReturn(false).atLeastOnce();
        expect(mockTopology.isInternal(1L, (short)2))
                           .andReturn(false).atLeastOnce();
        expect(mockTopology.isBroadcastDomainPort(1L, (short)1))
                           .andReturn(false).atLeastOnce();
        expect(mockTopology.isBroadcastDomainPort(1L, (short)2))
                           .andReturn(false).atLeastOnce();
        expect(mockTopology.inSameCluster(1L, 1L)).andReturn(true).atLeastOnce();
        expect(mockTopology.isInSameBroadcastDomain((long)1, (short)1, 
                                                    (long)1, (short)2)).andReturn(false).anyTimes();
        expect(mockTopology.isInSameBroadcastDomain((long)1, (short)2, 
                                                    (long)1, (short)1)).andReturn(false).anyTimes();

        deviceManager.setTopology(mockTopology);
        expect(mockTopology.isAllowed(EasyMock.anyLong(), EasyMock.anyShort())).andReturn(true).anyTimes();
        // Start recording the replay on the mocks
        replay(mockSwitch, mockTopology);

        // Get the listener and trigger the packet in
        mockFloodlightProvider.dispatchMessage(mockSwitch, this.packetIn_1);
        mockFloodlightProvider.dispatchMessage(mockSwitch, this.packetIn_1.setInPort((short)2));
        mockFloodlightProvider.dispatchMessage(mockSwitch, this.packetIn_1.setInPort((short)1));
        mockFloodlightProvider.dispatchMessage(mockSwitch, this.packetIn_1.setInPort((short)2));
        mockFloodlightProvider.dispatchMessage(mockSwitch, this.packetIn_1.setInPort((short)1));
        mockFloodlightProvider.dispatchMessage(mockSwitch, this.packetIn_1.setInPort((short)2));

        Device device = deviceManager.getDeviceByDataLayerAddress(dataLayerSource);

        // Verify the replay matched our expectations
        verify(mockSwitch, mockTopology);

        // Verify the device
        assertEquals(device.getAttachmentPoints().size(), 1);
        assertEquals(device.getOldAttachmentPoints().size(), 1);
        for (DeviceAttachmentPoint ap : device.getOldAttachmentPoints()) {
            assertFalse(ap.isBlocked());
        }

        // Reset the device cache
        deviceManager.clearAllDeviceStateFromMemory();

        teardownPortChannel();
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
    }
}
Solution content
        // Reset the device cache
        deviceManager.clearAllDeviceStateFromMemory();
        */
    }
}
File
DeviceManagerImplTest.java
Developer's decision
Version 1
Kind of conflict
Annotation
Attribute
Comment
For statement
Method declaration
Method invocation
Method signature
Static initializer
Variable
Chunk
Conflicting content
=======
        return res;
package net.floodlightcontroller.devicemanager.test;

import java.util.Collection;
<<<<<<< HEAD
import java.util.Collections;
import java.util.Set;

import net.floodlightcontroller.devicemanager.IDevice;
import net.floodlightcontroller.devicemanager.IDeviceListener;
import net.floodlightcontroller.devicemanager.IEntityClass;
import net.floodlightcontroller.devicemanager.internal.Device;
import net.floodlightcontroller.devicemanager.internal.DeviceManagerImpl;
import net.floodlightcontroller.devicemanager.internal.Entity;

/**
 * Mock device manager useful for unit tests
 * @author readams
 */
public class MockDeviceManager extends DeviceManagerImpl {
    /**
     * Learn a device using the given characteristics. 
     * @param macAddress the MAC
     * @param vlan the VLAN (can be null)
     * @param ipv4Address the IP (can be null)
     * @param switchDPID the attachment point switch DPID (can be null)
     * @param switchPort the attachment point switch port (can be null)
     * @param processUpdates if false, will not send updates.  Note that this 
     * method is not thread safe if this is false
     * @return the device, either new or not
     */
    public IDevice learnEntity(long macAddress, Short vlan, 
                               Integer ipv4Address, Long switchDPID, 
                               Integer switchPort,
                               boolean processUpdates) {
        Set listeners = deviceListeners;
        if (!processUpdates) {
            deviceListeners = Collections.emptySet();
        }
        
        if (vlan != null && vlan.shortValue() <= 0)
            vlan = null;
        if (ipv4Address != null && ipv4Address == 0)
            ipv4Address = null;
        IDevice res =  learnDeviceByEntity(new Entity(macAddress, vlan, 
                                                      ipv4Address, switchDPID, 
                                                      switchPort, null));
        deviceListeners = listeners;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;

import net.floodlightcontroller.core.module.FloodlightModuleContext;
import net.floodlightcontroller.core.module.FloodlightModuleException;
import net.floodlightcontroller.core.module.IFloodlightModule;
import net.floodlightcontroller.core.module.IFloodlightService;
import net.floodlightcontroller.devicemanager.Device;
import net.floodlightcontroller.devicemanager.DeviceAttachmentPoint;
import net.floodlightcontroller.devicemanager.IDeviceManagerAware;
import net.floodlightcontroller.devicemanager.IDeviceManagerService;
import net.floodlightcontroller.packet.Ethernet;

public class MockDeviceManager implements IFloodlightModule, IDeviceManagerService {
    protected Map devices;
    protected Map clusters;

    public MockDeviceManager() {
        devices = new HashMap();
        clusters = new HashMap();
    }
    
    @Override
    public Device getDeviceByDataLayerAddress(byte[] address) {
        return devices.get(Ethernet.toLong(address));
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
    }
    
    /**
Solution content
package net.floodlightcontroller.devicemanager.test;

import java.util.Collection;
import java.util.Collections;
import java.util.Set;

import net.floodlightcontroller.devicemanager.IDevice;
import net.floodlightcontroller.devicemanager.IDeviceListener;
import net.floodlightcontroller.devicemanager.IEntityClass;
import net.floodlightcontroller.devicemanager.internal.Device;
import net.floodlightcontroller.devicemanager.internal.DeviceManagerImpl;
import net.floodlightcontroller.devicemanager.internal.Entity;

/**
 * Mock device manager useful for unit tests
 * @author readams
 */
public class MockDeviceManager extends DeviceManagerImpl {
    /**
     * Learn a device using the given characteristics. 
     * @param macAddress the MAC
     * @param vlan the VLAN (can be null)
     * @param ipv4Address the IP (can be null)
     * @param switchDPID the attachment point switch DPID (can be null)
     * @param switchPort the attachment point switch port (can be null)
     * @param processUpdates if false, will not send updates.  Note that this 
     * method is not thread safe if this is false
     * @return the device, either new or not
     */
    public IDevice learnEntity(long macAddress, Short vlan, 
                               Integer ipv4Address, Long switchDPID, 
                               Integer switchPort,
                               boolean processUpdates) {
        Set listeners = deviceListeners;
        if (!processUpdates) {
            deviceListeners = Collections.emptySet();
        }
        
        if (vlan != null && vlan.shortValue() <= 0)
            vlan = null;
        if (ipv4Address != null && ipv4Address == 0)
            ipv4Address = null;
        IDevice res =  learnDeviceByEntity(new Entity(macAddress, vlan, 
                                                      ipv4Address, switchDPID, 
                                                      switchPort, null));
        deviceListeners = listeners;
        return res;
    }
    
    /**
File
MockDeviceManager.java
Developer's decision
Version 1
Kind of conflict
Annotation
Attribute
Class signature
Comment
If statement
Import
Method declaration
Method invocation
Method signature
Return statement
Variable
Chunk
Conflicting content
    }
    
    @Override
<<<<<<< HEAD
    protected Device allocateDevice(Device device,
                                    Entity entity, 
                                    Collection entityClasses) {
        return new MockDevice(device, entity, entityClasses);
=======
    public List getDevices() {
        List devices = new ArrayList();
        Iterator> it = this.devices.entrySet().iterator();
        while (it.hasNext()) {
            devices.add(it.next().getValue());
        }
        return devices;
    }

    @Override
    public boolean isDeviceKnownToCluster(long deviceId, long switchId) {
        Device device = this.devices.get(deviceId);
        if (device == null) {
            return false;
        }
        /** 
         * Iterate through all APs and check if the switch clusterID matches
         * with the given clusterId
         */
        for(DeviceAttachmentPoint dap : device.getAttachmentPoints()) {
            if (dap == null) continue;
            if (this.clusters.get(switchId) == 
                this.clusters.get(dap.getSwitchPort().getSw().getId())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void addListener(IDeviceManagerAware listener) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public Collection> getModuleServices() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Map, IFloodlightService>
            getServiceImpls() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Collection>
            getModuleDependencies() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public
            void
            init(FloodlightModuleContext context)
                                                 throws FloodlightModuleException {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void startUp(FloodlightModuleContext context) {
        // TODO Auto-generated method stub
        
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
    }
}
Solution content
    
    @Override
    protected Device allocateDevice(Device device,
                                    Entity entity, 
                                    Collection entityClasses) {
        return new MockDevice(device, entity, entityClasses);
    }
}
File
MockDeviceManager.java
Developer's decision
Version 1
Kind of conflict
Annotation
Comment
Method declaration
Method invocation
Method signature
Return statement
Chunk
Conflicting content
        // expect no Flow-mod or packet out
                
        // Reset mocks, trigger the packet in, and validate results
<<<<<<< HEAD
        expect(topology.isIncomingBroadcastAllowedOnSwitchPort(1L, (short)1)).andReturn(true).anyTimes();
        replay(sw1, sw2, routingEngine, topology);
=======
        expect(topology.isIncomingBroadcastAllowed(1L, (short)1)).andReturn(true).anyTimes();
        replay(sw1, sw2, deviceManager, routingEngine, topology);
>>>>>>> 6c645fd3e8b77caae66cc3296b7a201495d9714f
        forwarding.receive(sw1, this.packetIn, cntx);
        verify(sw1, sw2, routingEngine);
    }
Solution content
        // expect no Flow-mod or packet out
                
        // Reset mocks, trigger the packet in, and validate results
        expect(topology.isIncomingBroadcastAllowed(1L, (short)1)).andReturn(true).anyTimes();
        replay(sw1, sw2, routingEngine, topology);
        forwarding.receive(sw1, this.packetIn, cntx);
        verify(sw1, sw2, routingEngine);
    }
File
ForwardingTest.java
Developer's decision
Combination
Kind of conflict
Method invocation