Example usage for org.apache.commons.lang3.tuple Triple getLeft

List of usage examples for org.apache.commons.lang3.tuple Triple getLeft

Introduction

In this page you can find the example usage for org.apache.commons.lang3.tuple Triple getLeft.

Prototype

public abstract L getLeft();

Source Link

Document

Gets the left element from this triple.

Usage

From source file:org.lightjason.agentspeak.language.execution.action.CLambdaExpression.java

/**
 * run sequential execution/* w  w w. jav a 2  s  . c o  m*/
 *
 * @param p_context execution context
 * @param p_input input list
 * @return return list
 */
private List<?> executeSequential(final IContext p_context, final List<ITerm> p_input) {
    final Triple<IContext, IVariable<?>, IVariable<?>> l_localcontext = this.getLocalContext(p_context);

    return CCommon.flatcollection(p_input).map(i -> {

        l_localcontext.getMiddle().set(i.raw());
        m_body.forEach(j -> j.execute(l_localcontext.getLeft(), m_parallel, Collections.<ITerm>emptyList(),
                new LinkedList<>(), Collections.<ITerm>emptyList()));
        return l_localcontext.getRight() != null ? l_localcontext.getRight().raw() : null;

    }).filter(Objects::nonNull).collect(Collectors.toList());
}

From source file:org.lightjason.agentspeak.language.execution.action.CLambdaExpression.java

/**
 * run parallel execution/*from  w w w  .  ja  v  a 2s . c  o m*/
 *
 * @param p_context execution context
 * @param p_input input list
 * @return return list
 */
private List<?> executeParallel(final IContext p_context, final List<ITerm> p_input) {
    return CCommon.flatcollection(p_input).parallel().map(i -> {

        final Triple<IContext, IVariable<?>, IVariable<?>> l_localcontext = this.getLocalContext(p_context);
        l_localcontext.getMiddle().set(i.raw());
        m_body.forEach(j -> j.execute(l_localcontext.getLeft(), m_parallel, Collections.<ITerm>emptyList(),
                new LinkedList<>(), Collections.<ITerm>emptyList()));
        return l_localcontext.getRight() != null ? l_localcontext.getRight().raw() : null;

    }).filter(Objects::nonNull).collect(Collectors.toList());
}

From source file:org.matsim.contrib.drt.optimizer.rebalancing.mincostflow.AggregatedMinCostRelocationCalculator.java

private List<Relocation> calcRelocations(Map<String, List<Vehicle>> rebalancableVehiclesPerZone,
        List<Triple<String, String, Integer>> interZonalRelocations) {
    List<Relocation> relocations = new ArrayList<>();
    for (Triple<String, String, Integer> r : interZonalRelocations) {
        List<Vehicle> rebalancableVehicles = rebalancableVehiclesPerZone.get(r.getLeft());

        String toZone = r.getMiddle();
        Geometry z = zonalSystem.getZone(toZone);
        Coord zoneCentroid = MGC.point2Coord(z.getCentroid());
        Link destinationLink = NetworkUtils.getNearestLink(network, zoneCentroid);

        int flow = r.getRight();
        for (int f = 0; f < flow; f++) {
            // TODO use BestDispatchFinder (needs to be moved from taxi to dvrp) instead
            Vehicle nearestVehicle = findNearestVehicle(rebalancableVehicles, destinationLink);
            relocations.add(new Relocation(nearestVehicle, destinationLink));
            rebalancableVehicles.remove(nearestVehicle);// TODO use map to have O(1) removal
        }//from   w  ww .  ja  v a 2  s .  c  o m
    }
    return relocations;
}

From source file:org.opendaylight.vtn.manager.internal.util.concurrent.FutureCancellerTest.java

/**
 * Test method for/*from   ww  w.j  a  v  a 2 s . c  o m*/
 * {@link FutureCanceller#set(Timer,long,ListenableFuture)} and
 * {@link FutureCanceller#set(Timer,long,ListenableFuture,boolean)}.
 *
 * @throws Exception  An error occurred.
 */
@Test
public void testSet() throws Exception {
    TestTimer timer = new TestTimer();
    List<Triple<SettableVTNFuture<Void>, Long, Boolean>> list = new ArrayList<>();
    IllegalStateException cause = new IllegalStateException();
    ListenableFuture<Void> succeeded = Futures.<Void>immediateFuture(null);
    ListenableFuture<Void> failed = Futures.<Void>immediateFailedFuture(cause);
    ListenableFuture<Void> cancelled = Futures.<Void>immediateCancelledFuture();
    List<ListenableFuture<Void>> ignored = new ArrayList<>();
    Collections.addAll(ignored, succeeded, failed, cancelled);

    long[] timeouts = { 1L, 10L, 333333L };
    boolean[] bools = { true, false };
    for (long timeout : timeouts) {
        SettableVTNFuture<Void> f = new SettableVTNFuture<>();
        f.setThread(Thread.currentThread());
        Triple<SettableVTNFuture<Void>, Long, Boolean> expected = new ImmutableTriple<>(f, timeout, false);
        list.add(expected);
        FutureCanceller.set(timer, timeout, f);

        // Completed future should be ignored.
        for (ListenableFuture<Void> completed : ignored) {
            FutureCanceller.set(timer, timeout, completed);
        }

        for (boolean intr : bools) {
            f = new SettableVTNFuture<>();
            f.setThread(Thread.currentThread());
            expected = new ImmutableTriple<>(f, timeout, intr);
            list.add(expected);
            FutureCanceller.set(timer, timeout, f, intr);

            // Completed future should be ignored.
            for (ListenableFuture<Void> completed : ignored) {
                FutureCanceller.set(timer, timeout, completed, intr);
            }
        }
    }

    Iterator<Triple<SettableVTNFuture<Void>, Long, Boolean>> it = list.iterator();
    for (Pair<Long, TimerTask> pair : timer.getTasks()) {
        assertTrue(it.hasNext());
        Triple<SettableVTNFuture<Void>, Long, Boolean> expected = it.next();

        // Check delay.
        assertEquals(expected.getMiddle(), pair.getLeft());

        // Check the target future.
        TimerTask task = pair.getRight();
        assertTrue(task instanceof FutureCanceller<?>);
        ListenableFuture target = getFieldValue(task, ListenableFuture.class, "targetTask");
        SettableVTNFuture<Void> f = expected.getLeft();
        assertEquals(target, f);

        // Check intr flag.
        Boolean intr = getFieldValue(task, Boolean.class, "needInterrupt");
        assertEquals(intr, expected.getRight());

        // Cancel the target future.
        assertEquals(false, f.isCancelled());
        assertEquals(false, f.isDone());
        task.run();
        assertEquals(intr.booleanValue(), Thread.interrupted());
        assertEquals(true, f.isCancelled());
        assertEquals(true, f.isDone());
    }

    assertFalse(it.hasNext());
}

From source file:org.opendaylight.vtn.manager.internal.util.vnode.VTNMacMapStatusTest.java

/**
 * Ensure that {@link VTNMacMapStatus} maintains mapped host information
 * correctly./*from w  ww.j a  v  a  2s  .  co m*/
 *
 * <ul>
 *   <li>{@link VTNMacMapStatus#activate(MacMapIdentifier, MacVlan, SalPort)}</li>
 *   <li>{@link VTNMacMapStatus#getPort(MacVlan)}</li>
 *   <li>{@link VTNMacMapStatus#getPortVlan(long)}</li>
 *   <li>{@link VTNMacMapStatus#hasMapping(PortVlan)}</li>
 *   <li>{@link VTNMacMapStatus#hasMapping()}</li>
 *   <li>{@link VTNMacMapStatus#getNetworks()}</li>
 *   <li>{@link VTNMacMapStatus#getDuplicate(MacVlan)}</li>
 *   <li>{@link VTNMacMapStatus#isDirty()}</li>
 *   <li>{@link VTNMacMapStatus#inactivate(MacVlan, Set)}</li>
 *   <li>{@link VTNMacMapStatus#inactivate(PortVlan)}</li>
 *   <li>{@link VTNMacMapStatus#inactivate(PortFilter, Set)}</li>
 *   <li>{@link VTNMacMapStatus#inactivate(MacMapIdentifier, Set, Set, Set)}</li>
 * </ul>
 *
 * @throws Exception  An error occurred.
 */
@Test
public void testStatus() throws Exception {
    // Test case for an empty instance.
    VTNMacMapStatus vmst = new VTNMacMapStatus();
    assertFalse(vmst.hasMapping());
    assertNull(vmst.getNetworks());
    assertFalse(vmst.isDirty());

    NetworkMap nwMap = new NetworkMap();
    HostMap hostMap = new HostMap();

    // Activate MAC mappings with specifying MAC addresses in which the
    // MSB is not set.
    VnodeName vtnName = new VnodeName("tenant");
    VnodeName vbrName = new VnodeName("bridge");
    MacMapIdentifier mapId = new MacMapIdentifier(vtnName, vbrName);
    int[] vlans = { 0, 1, 4094, 4095 };
    long mac = 0x1000L;
    for (int i = 0; i < 10; i++) {
        for (int vid : vlans) {
            checkActivate(vmst, mapId, mac, vid, null, nwMap, hostMap);
            mac++;
        }
    }

    // Activate MAC mappings with specifying MAC addresses in which the
    // MSB is set.
    mac = 0xfeffffffff00L;
    for (int i = 0; i < 10; i++) {
        for (int vid : vlans) {
            checkActivate(vmst, mapId, mac, vid, null, nwMap, hostMap);
            mac++;
        }
    }

    // Ensure that duplicate MAC addresses are rejected.
    for (Entry<MacVlan, SalPort> entry : hostMap.entrySet()) {
        MacVlan mapped = entry.getKey();
        SalPort sport = entry.getValue();
        mac = mapped.getAddress();
        MacVlan mvlan = new MacVlan(mac, 2000);

        assertEquals(mapped, vmst.getDuplicate(mvlan));
        try {
            vmst.activate(mapId, mvlan, sport);
            fail("An exception must be thrown.");
        } catch (MacMapDuplicateException e) {
            assertEquals(mvlan, e.getHost());
            assertEquals(mapId, e.getIdentifier());
            assertEquals(mapped, e.getDuplicate());
        }

        assertFalse(vmst.isDirty());
        hostMap.verify(vmst.toMacMapStatus());
    }

    Set<PortVlan> nw = vmst.getNetworks();
    assertEquals(nwMap.getNetworks(), nw);

    // Move all hosts to one port.
    SalPort newPort = unusedPortList.get(0);
    HostMap hmap = new HostMap(hostMap);
    for (Entry<MacVlan, SalPort> entry : hmap.entrySet()) {
        MacVlan mvlan = entry.getKey();
        mac = mvlan.getAddress();
        int vid = mvlan.getVlanId();
        SalPort sport = entry.getValue();
        PortVlan pvlan = new PortVlan(sport, vid);
        assertNull(vmst.getDuplicate(mvlan));
        assertEquals(pvlan, vmst.getPortVlan(mac));
        assertEquals(sport, vmst.getPort(mvlan));
        assertFalse(vmst.isDirty());

        Triple<Boolean, SalPort, PortVlan> result = vmst.activate(mapId, mvlan, newPort);
        assertTrue(vmst.isDirty());
        assertFalse(vmst.isDirty());
        assertFalse(result.getLeft().booleanValue());
        assertEquals(sport, result.getMiddle());
        PortVlan released = (nwMap.remove(pvlan)) ? pvlan : null;
        assertEquals(released, result.getRight());
        hostMap.put(mvlan, newPort);
        hostMap.verify(vmst.toMacMapStatus());

        assertNull(vmst.activate(mapId, mvlan, newPort));
        assertFalse(vmst.isDirty());
        hostMap.verify(vmst.toMacMapStatus());

        pvlan = new PortVlan(newPort, mvlan.getVlanId());
        assertNull(vmst.getDuplicate(mvlan));
        assertEquals(pvlan, vmst.getPortVlan(mac));
        assertEquals(newPort, vmst.getPort(mvlan));

        nwMap.add(pvlan);
        assertEquals(nwMap.getNetworks(), vmst.getNetworks());
        assertTrue(vmst.hasMapping());
    }

    // Restore mappings.
    checkActivate(vmst, mapId, hmap, nwMap, hostMap);
    assertEquals(hmap, hostMap);

    // Inactivate all hosts by specifying MacVlan instance.
    for (Entry<MacVlan, SalPort> entry : hmap.entrySet()) {
        assertTrue(vmst.hasMapping());
        MacVlan mvlan = entry.getKey();
        mac = mvlan.getAddress();
        SalPort sport = entry.getValue();
        PortVlan pvlan = new PortVlan(sport, mvlan.getVlanId());
        assertTrue(vmst.hasMapping(pvlan));

        Set<PortVlan> released = new HashSet<PortVlan>();
        assertEquals(sport, vmst.inactivate(mvlan, released));
        assertTrue(vmst.isDirty());
        assertFalse(vmst.isDirty());
        assertEquals(sport, hostMap.remove(mvlan));
        hostMap.verify(vmst.toMacMapStatus());

        boolean removed = nwMap.remove(pvlan);
        if (removed) {
            assertEquals(1, released.size());
            assertTrue(released.contains(pvlan));
        } else {
            assertTrue(released.isEmpty());
        }
        assertEquals(!removed, vmst.hasMapping(pvlan));

        assertNull(vmst.getDuplicate(mvlan));
        assertNull(vmst.getPortVlan(mac));
        assertNull(vmst.getPort(mvlan));

        // Try to inactivate the same host.
        released.clear();
        assertNull(vmst.inactivate(mvlan, released));
        assertFalse(vmst.isDirty());
        assertTrue(released.isEmpty());
        hostMap.verify(vmst.toMacMapStatus());
    }
    assertFalse(vmst.hasMapping());

    // Restore mappings again.
    checkActivate(vmst, mapId, hmap, nwMap, hostMap);
    assertEquals(hmap, hostMap);

    // Inactivate all hosts by specifying PortVlan instance.
    Set<PortVlan> nwSet = new HashSet<>(nwMap.getNetworks());
    for (PortVlan pvlan : nwSet) {
        assertTrue(vmst.hasMapping());
        assertTrue(vmst.hasMapping(pvlan));
        Set<MacVlan> removed = vmst.inactivate(pvlan);
        assertTrue(vmst.isDirty());
        assertFalse(vmst.isDirty());
        assertEquals(removeHosts(hostMap, pvlan).keySet(), removed);
        nwMap.removeForce(pvlan);
        hostMap.verify(vmst.toMacMapStatus());

        assertFalse(vmst.hasMapping(pvlan));
        Set<PortVlan> nw1 = nwMap.getNetworks();
        if (nw1.isEmpty()) {
            nw1 = null;
        }
        assertEquals(nw1, vmst.getNetworks());

        for (MacVlan mvlan : removed) {
            assertNull(vmst.getDuplicate(mvlan));
            assertNull(vmst.getPortVlan(mvlan.getAddress()));
            assertNull(vmst.getPort(mvlan));
        }

        // Try to inactivate the same network.
        assertNull(vmst.inactivate(pvlan));
        assertFalse(vmst.isDirty());
        hostMap.verify(vmst.toMacMapStatus());
    }
    assertFalse(vmst.hasMapping());

    // Restore mappings again.
    checkActivate(vmst, mapId, hmap, nwMap, hostMap);
    assertEquals(hmap, hostMap);

    // Inactivate all hosts on the specified switch.
    SalNode removedNode = portList.get(0).getSalNode();
    PortFilter filter = new NodePortFilter(removedNode);
    Set<PortVlan> released = new HashSet<>();
    Map<MacVlan, SalPort> removedMap = vmst.inactivate(filter, released);
    assertTrue(vmst.isDirty());
    assertFalse(vmst.isDirty());
    assertFalse(removedMap.isEmpty());
    assertFalse(released.isEmpty());
    assertEquals(removedMap, removeHosts(hostMap, filter));
    assertEquals(released, nwMap.removeForce(filter));
    assertEquals(nwMap.getNetworks(), vmst.getNetworks());
    hostMap.verify(vmst.toMacMapStatus());

    for (Entry<MacVlan, SalPort> entry : removedMap.entrySet()) {
        MacVlan mvlan = entry.getKey();
        SalPort sport = entry.getValue();
        assertEquals(removedNode, sport.getSalNode());
        assertNull(vmst.getDuplicate(mvlan));
        assertNull(vmst.getPortVlan(mvlan.getAddress()));
        assertNull(vmst.getPort(mvlan));
        PortVlan pvlan = new PortVlan(sport, mvlan.getVlanId());
        assertFalse(vmst.hasMapping(pvlan));
    }
    assertTrue(vmst.hasMapping());

    // Try to inactivate again.
    released.clear();
    assertTrue(vmst.inactivate(filter, released).isEmpty());
    assertFalse(vmst.isDirty());
    assertTrue(released.isEmpty());
    hostMap.verify(vmst.toMacMapStatus());

    // Inactivate all hosts by specifying switch port.
    for (SalPort sport : portList) {
        SalNode snode = sport.getSalNode();
        boolean inactivated = snode.equals(removedNode);
        filter = new SpecificPortFilter(sport);
        released.clear();
        removedMap = vmst.inactivate(filter, released);
        assertEquals(!inactivated, vmst.isDirty());
        assertFalse(vmst.isDirty());
        assertEquals(inactivated, removedMap.isEmpty());
        assertEquals(inactivated, released.isEmpty());
        assertEquals(removedMap, removeHosts(hostMap, filter));
        assertEquals(released, nwMap.removeForce(filter));
        hostMap.verify(vmst.toMacMapStatus());

        Set<PortVlan> nw1 = nwMap.getNetworks();
        if (nw1.isEmpty()) {
            nw1 = null;
        }
        assertEquals(nw1, vmst.getNetworks());

        for (Entry<MacVlan, SalPort> entry : removedMap.entrySet()) {
            MacVlan mvlan = entry.getKey();
            assertEquals(sport, entry.getValue());
            assertFalse(removedNode.equals(sport.getSalNode()));
            assertNull(vmst.getDuplicate(mvlan));
            assertNull(vmst.getPortVlan(mvlan.getAddress()));
            assertNull(vmst.getPort(mvlan));
            PortVlan pvlan = new PortVlan(sport, mvlan.getVlanId());
            assertFalse(vmst.hasMapping(pvlan));
        }

        // Try to inactivate again.
        released.clear();
        assertTrue(vmst.inactivate(filter, released).isEmpty());
        assertFalse(vmst.isDirty());
        assertTrue(released.isEmpty());
        hostMap.verify(vmst.toMacMapStatus());
    }
    assertFalse(vmst.hasMapping());

    // Restore mappings again.
    checkActivate(vmst, mapId, hmap, nwMap, hostMap);
    assertEquals(hmap, hostMap);

    // Test case for inactivate(MacMapIdentifier, Set, Set, Set).
    // In order to simplify the test code, hosts to be inactivated are
    // determined by PortVlan instances.
    // At first, choose 2 arbitrary VLAN networks.
    Set<PortVlan> expectedNw = new HashSet<>();
    Map<MacVlan, SalPort> expectedHosts = new HashMap<>();
    Set<Integer> unmappedVlans = new HashSet<>();
    for (int i = 1; i <= 2; i++) {
        int idx = (i * i) + 2;
        int vid = vlans[i];
        SalPort sport = portList.get(idx);
        PortVlan pvlan = new PortVlan(sport, vid);
        expectedNw.add(pvlan);
        nwMap.removeForce(pvlan);
        Map<MacVlan, SalPort> m = removeHosts(hostMap, pvlan);
        assertFalse(m.isEmpty());
        expectedHosts.putAll(m);

        // This test case assumes that this host is mapped by MAC mapping
        // with wildcard MAC address. So this VLAN ID needs to be added
        // to unmappedVlans.
        unmappedVlans.add(vid);
    }
    assertFalse(expectedNw.isEmpty());
    assertFalse(expectedHosts.isEmpty());
    assertFalse(unmappedVlans.isEmpty());

    // Construct an allowed host set.
    Set<MacVlan> allowed = new HashSet<>();
    for (MacVlan mvlan : hmap.keySet()) {
        int vid = mvlan.getVlanId();
        if (unmappedVlans.contains(vid) && !expectedHosts.containsKey(mvlan)) {
            // This host should be retained.
            allowed.add(mvlan);
        }
    }
    assertFalse(allowed.isEmpty());

    // Inactivate all hosts on the specified VLAN except for hosts
    // which are mapped explicitly.
    released.clear();
    removedMap = vmst.inactivate(mapId, allowed, unmappedVlans, released);
    assertTrue(vmst.isDirty());
    assertFalse(vmst.isDirty());
    assertFalse(removedMap.isEmpty());
    assertFalse(released.isEmpty());
    assertEquals(removedMap, expectedHosts);
    assertEquals(released, expectedNw);
    assertEquals(nwMap.getNetworks(), vmst.getNetworks());
    hostMap.verify(vmst.toMacMapStatus());

    for (Entry<MacVlan, SalPort> entry : removedMap.entrySet()) {
        MacVlan mvlan = entry.getKey();
        SalPort sport = entry.getValue();
        assertNull(vmst.getDuplicate(mvlan));
        assertNull(vmst.getPortVlan(mvlan.getAddress()));
        assertNull(vmst.getPort(mvlan));
        PortVlan pvlan = new PortVlan(sport, mvlan.getVlanId());
        assertFalse(vmst.hasMapping(pvlan));
    }
    assertTrue(vmst.hasMapping());

    // Try to inactivate again.
    released.clear();
    assertTrue(vmst.inactivate(mapId, allowed, unmappedVlans, released).isEmpty());
    assertFalse(vmst.isDirty());
    assertTrue(released.isEmpty());
    assertTrue(vmst.hasMapping());
    hostMap.verify(vmst.toMacMapStatus());

    // No host should be inactivated if unmappedVlans is empty.
    allowed.clear();
    unmappedVlans.clear();
    assertTrue(vmst.inactivate(mapId, allowed, unmappedVlans, released).isEmpty());
    assertFalse(vmst.isDirty());
    assertTrue(released.isEmpty());
    assertTrue(vmst.hasMapping());
    hostMap.verify(vmst.toMacMapStatus());

    // No host should be inactivated if all hosts are explicitly mapped.
    for (int vid : vlans) {
        unmappedVlans.add(vid);
    }
    allowed.clear();
    allowed.addAll(hostMap.keySet());
    assertTrue(vmst.inactivate(mapId, allowed, unmappedVlans, released).isEmpty());
    assertFalse(vmst.isDirty());
    assertTrue(released.isEmpty());
    assertTrue(vmst.hasMapping());
    hostMap.verify(vmst.toMacMapStatus());

    // All hosts should be inactivated if no host is explicitly mapped
    // and all VLANs are unmapped.
    allowed.clear();
    hostMap.verify(vmst.inactivate(mapId, allowed, unmappedVlans, released));
    assertTrue(vmst.isDirty());
    assertFalse(vmst.isDirty());
    assertEquals(nwMap.getNetworks(), released);
    assertFalse(vmst.hasMapping());
    assertNull(vmst.getNetworks());

    for (Entry<MacVlan, SalPort> entry : hostMap.entrySet()) {
        MacVlan mvlan = entry.getKey();
        SalPort sport = entry.getValue();
        assertNull(vmst.getDuplicate(mvlan));
        assertNull(vmst.getPortVlan(mvlan.getAddress()));
        assertNull(vmst.getPort(mvlan));
        PortVlan pvlan = new PortVlan(sport, mvlan.getVlanId());
        assertFalse(vmst.hasMapping(pvlan));
    }

    hostMap.clear();
    hostMap.verify(vmst.toMacMapStatus());

    // Try to inactivate again.
    released.clear();
    assertTrue(vmst.inactivate(mapId, allowed, unmappedVlans, released).isEmpty());
    assertFalse(vmst.isDirty());
    assertTrue(released.isEmpty());
    assertFalse(vmst.hasMapping());
    hostMap.verify(vmst.toMacMapStatus());
}

From source file:org.opendaylight.vtn.manager.internal.util.vnode.VTNMacMapStatusTest.java

/**
 * Activate the given host and verify results.
 *
 * @param vmst     A {@link VTNMacMapStatus} instance to be tested.
 * @param mapId    A {@link MacMapIdentifier} instance.
 * @param mac      A long value which represents the MAC address.
 * @param vid      A VLAN ID./*w  ww .  j  av  a 2s. com*/
 * @param sport    A {@link SalPort} instance.
 *                 An arbitrary port is chosen if {@code null} is
 *                 specified.
 * @param nwMap    A {@link NetworkMap} instance to store mapped
 *                 networks.
 * @param hostMap  A map to store activated hosts.
 * @throws Exception  An error occurred.
 */
private void checkActivate(VTNMacMapStatus vmst, MacMapIdentifier mapId, long mac, int vid, SalPort sport,
        NetworkMap nwMap, HostMap hostMap) throws Exception {
    boolean active = !vmst.hasMapping();
    MacVlan mvlan = new MacVlan(mac, vid);
    SalPort port = sport;
    if (port == null) {
        port = getPort();
    }
    PortVlan pvlan = new PortVlan(port, vid);
    assertEquals(nwMap.getNetworks().contains(pvlan), vmst.hasMapping(pvlan));
    assertNull(vmst.getDuplicate(mvlan));

    SalPort oldPort = hostMap.get(mvlan);
    PortVlan oldPv;
    if (oldPort == null) {
        oldPv = null;
        assertNull(vmst.getPortVlan(mac));
        assertNull(vmst.getPort(mvlan));
    } else {
        oldPv = new PortVlan(oldPort, vid);
        assertEquals(oldPv, vmst.getPortVlan(mac));
        assertEquals(oldPort, vmst.getPort(mvlan));
    }

    Triple<Boolean, SalPort, PortVlan> result = vmst.activate(mapId, mvlan, port);
    assertTrue(vmst.isDirty());
    assertFalse(vmst.isDirty());
    assertEquals(active, result.getLeft().booleanValue());
    assertEquals(oldPort, result.getMiddle());
    PortVlan released;
    if (oldPv == null) {
        released = null;
    } else {
        released = (nwMap.remove(oldPv)) ? oldPv : null;
    }
    assertEquals(released, result.getRight());
    hostMap.put(mvlan, port);
    hostMap.verify(vmst.toMacMapStatus());

    // null should be returned if the host is already
    // activated.
    assertNull(vmst.activate(mapId, mvlan, port));
    assertFalse(vmst.isDirty());
    hostMap.verify(vmst.toMacMapStatus());

    assertTrue(vmst.hasMapping(pvlan));
    assertNull(vmst.getDuplicate(mvlan));
    assertEquals(pvlan, vmst.getPortVlan(mac));
    assertEquals(port, vmst.getPort(mvlan));

    nwMap.add(pvlan);

    assertEquals(nwMap.getNetworks(), vmst.getNetworks());
    assertTrue(vmst.hasMapping());
}

From source file:org.opendaylight.vtn.manager.internal.vnode.MacMapActivation.java

/**
 * Activate the specified host in the MAC mapping.
 *
 * @param ctx    MD-SAL datastore transaction context.
 * @return  {@code true} is returned if the specified MAC mapping was
 *          activated. In other words, {@code true} is returned if the
 *          specified host was activated, and it is the only active host
 *          in the MAC mapping. Otherwise {@code false} is returned.
 * @throws MacMapGoneException/*from   ww  w  .j  a  v a  2  s.  c  o m*/
 *    The specified host is no longer mapped by the target MAC mapping.
 * @throws MacMapPortBusyException
 *    The specified VLAN network on a switch port is reserved by
 *    another virtual mapping.
 * @throws org.opendaylight.vtn.manager.internal.util.vnode.MacMapDuplicateException
 *    The same MAC address as {@code mv} is already mapped to the same
 *    vBridge.
 * @throws VTNException  A fatal error occurred.
 */
public boolean activate(TxContext ctx) throws VTNException {
    // Ensure that the specified host is mapped by the specified
    // MAC mapping.
    ReadWriteTransaction tx = ctx.getReadWriteTransaction();
    checkMacMapping(tx);

    // Reserve the VLAN on the specified switch port for the MAC mapping.
    int vid = targetHost.getVlanId();
    PortVlan pv = new PortVlan(targetPort, vid);
    boolean reserved = reservePort(tx, pv);

    // Activate the MAC mapping.
    boolean activated;
    Triple<Boolean, SalPort, PortVlan> result = activate(ctx, pv, reserved);
    if (result == null) {
        // The specified host is already activated.
        activated = false;
    } else {
        activated = result.getLeft().booleanValue();
        cleanUp(ctx, result.getMiddle());
    }

    return activated;
}

From source file:org.openecomp.sdc.be.tosca.CsarUtils.java

private Either<ZipOutputStream, ResponseFormat> populateZip(Component component, boolean getFromCS,
        ZipOutputStream zip, boolean isInCertificationRequest, boolean mockGenerator, boolean shouldLock,
        boolean inTransaction) {

    LifecycleStateEnum lifecycleState = component.getLifecycleState();
    String componentYaml = null;/* w w  w. j  a va  2s. co m*/
    Either<ToscaRepresentation, ToscaError> exportComponent = null;
    byte[] mainYaml = null;
    // <file name, esid, component>
    List<Triple<String, String, Component>> dependencies = null;
    List<ImmutablePair<Component, byte[]>> generatorInputs = new LinkedList<>();

    String fileName;
    Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
    ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
    fileName = artifactDefinition.getArtifactName();

    if (getFromCS || !(lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN
            || lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
        String esId = artifactDefinition.getEsId();
        Either<byte[], ActionStatus> fromCassandra = getFromCassandra(esId);
        if (fromCassandra.isRight()) {
            ResponseFormat responseFormat = componentsUtils.getResponseFormat(fromCassandra.right().value());
            return Either.right(responseFormat);
        }
        mainYaml = fromCassandra.left().value();

    } else {
        exportComponent = toscaExportUtils.exportComponent(component);
        if (exportComponent.isRight()) {
            log.debug("exportComponent failed", exportComponent.right().value());
            ActionStatus convertedFromToscaError = componentsUtils
                    .convertFromToscaError(exportComponent.right().value());
            ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertedFromToscaError);
            return Either.right(responseFormat);
        }
        ToscaRepresentation exportResult = exportComponent.left().value();
        componentYaml = exportResult.getMainYaml();
        mainYaml = componentYaml.getBytes();
        dependencies = exportResult.getDependencies();
    }

    try {
        zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName));
        zip.write(mainYaml);

        generatorInputs.add(new ImmutablePair<Component, byte[]>(component, mainYaml));

        if (dependencies == null) {
            Either<ToscaTemplate, ToscaError> dependenciesRes = toscaExportUtils.getDependencies(component);
            if (dependenciesRes.isRight()) {
                log.debug("Failed to retrieve dependencies for component {}, error {}", component.getUniqueId(),
                        dependenciesRes.right().value());
                ActionStatus convertFromToscaError = componentsUtils
                        .convertFromToscaError(dependenciesRes.right().value());
                ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertFromToscaError);
                return Either.right(responseFormat);
            }
            dependencies = dependenciesRes.left().value().getDependencies();
        }
        if (dependencies != null && !dependencies.isEmpty()) {
            for (Triple<String, String, Component> d : dependencies) {
                String esId = d.getMiddle();
                Component childComponent = d.getRight();
                fileName = d.getLeft();
                Either<byte[], ActionStatus> entryData = getEntryData(esId, childComponent);

                if (entryData.isRight()) {
                    ResponseFormat responseFormat = componentsUtils
                            .getResponseFormat(entryData.right().value());
                    return Either.right(responseFormat);
                }

                byte[] content = entryData.left().value();
                zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName));
                zip.write(content);

                generatorInputs.add(new ImmutablePair<Component, byte[]>(childComponent, content));
            }
        }

        List<ArtifactDefinition> aiiArtifactList = new LinkedList<>();
        // Artifact Generation
        if (component.getComponentType() == ComponentTypeEnum.SERVICE
                && (lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN
                        || lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
            Either<List<ArtifactDefinition>, ResponseFormat> handleAAIArtifacts = handleAAIArtifacts(component,
                    zip, mockGenerator, shouldLock, inTransaction, generatorInputs);

            if (handleAAIArtifacts.isLeft()) {
                aiiArtifactList = handleAAIArtifacts.left().value();
            } else {
                log.debug("AAI Artifacts handling failed");
                return Either.right(handleAAIArtifacts.right().value());
            }

            if (isInCertificationRequest) {
                Either<ActionStatus, ResponseFormat> handleAllAAIArtifactsInDataModel = handleAllAAIArtifactsInDataModel(
                        component, aiiArtifactList, shouldLock, inTransaction);

                if (handleAllAAIArtifactsInDataModel.isRight()) {
                    log.debug("AAI Artifacts handling (create, update, delete) failed");
                    return Either.right(handleAllAAIArtifactsInDataModel.right().value());
                }
            }

        }

        // Collecting All Deployment Artifacts
        Either<ZipOutputStream, ActionStatus> collectAndWriteToScarDeploymentArtifacts = collectAndWriteToScarDeploymentArtifacts(
                zip, component, aiiArtifactList);

        if (collectAndWriteToScarDeploymentArtifacts.isRight()) {
            return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
        }
    } catch (IOException e) {
        log.debug("Failed to create CSAR zip for component {}", component.getUniqueId(), e);
    }

    return Either.left(zip);
}

From source file:org.shaman.terrain.sketch.SketchTerrain_old.java

/**
 * Finds the features (silhouettes and ringelines) of the terrain.
 * Input: {@link #map}/*w  w  w  . j a v a  2  s .  c  o  m*/
 * Output: {@link #features}
 */
private void findFeatures() {
    featureNode.detachAllChildren();
    Camera cam = app.getCamera();

    //1. find silhouettes: edges were the front face is visible, but not the back face
    //collect distances and visibility
    LOG.info("compute visibility");
    boolean[][] visible = new boolean[map.getSize()][map.getSize()];
    float[][] distance = new float[map.getSize()][map.getSize()];
    Ray ray = new Ray();
    CollisionResults results = new CollisionResults();
    for (int x = 0; x < map.getSize(); ++x) {
        for (int y = 0; y < map.getSize(); ++y) {
            Vector3f p3 = app.getHeightmapPoint(x, y);
            Vector3f p2 = cam.getScreenCoordinates(p3);
            distance[x][y] = p2.z;
            if (p2.x < 0 || p2.x >= width || p2.y < 0 || p2.y >= height) {
                visible[x][y] = false; //outside of the screen
            } else {
                //shoot a ray to detect visibility
                Vector3f dir = cam.getLocation().subtract(p3).normalizeLocal();
                ray.setDirection(dir);
                ray.setOrigin(p3.add(dir.mult(5f)));
                results.clear();
                app.getHeightmapSpatial().collideWith(ray, results);
                visible[x][y] = results.size() == 0;
                //               visible[x][y] = true;
            }
        }
    }
    //Test
    LOG.info("show visibility");
    List<Vector3f> visiblePoints = new ArrayList<>();
    List<Vector3f> hiddenPoints = new ArrayList<>();
    Material vmat = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md");
    vmat.setColor("Color", ColorRGBA.Red);
    Material hmat = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md");
    hmat.setColor("Color", ColorRGBA.Gray);
    for (int x = 0; x < map.getSize(); ++x) {
        for (int y = 0; y < map.getSize(); ++y) {
            Vector3f p = app.getHeightmapPoint(x, y);
            p.addLocal(0, 0.5f, 0);
            if (visible[x][y]) {
                visiblePoints.add(p);
            } else {
                hiddenPoints.add(p);
            }
        }
    }
    Mesh vm = new Mesh();
    vm.setMode(Mesh.Mode.Points);
    vm.setPointSize(10);
    vm.setBuffer(VertexBuffer.Type.Position, 3,
            BufferUtils.createFloatBuffer(visiblePoints.toArray(new Vector3f[visiblePoints.size()])));
    vm.updateCounts();
    vm.updateBound();
    Geometry vg = new Geometry("visible", vm);
    vg.setMaterial(vmat);
    featureNode.attachChild(vg);
    Mesh hm = new Mesh();
    hm.setMode(Mesh.Mode.Points);
    hm.setPointSize(10);
    hm.setBuffer(VertexBuffer.Type.Position, 3,
            BufferUtils.createFloatBuffer(hiddenPoints.toArray(new Vector3f[hiddenPoints.size()])));
    hm.updateCounts();
    hm.updateBound();
    Geometry hg = new Geometry("hidden", hm);
    hg.setMaterial(hmat);
    featureNode.attachChild(hg);

    //build graph
    int[][] nodes = new int[map.getSize()][map.getSize()];
    Graph graph = new Graph();
    ArrayList<Vector3f> positions = new ArrayList<>();
    ArrayList<Vector2f> indices = new ArrayList<>();
    for (int x = 0; x < map.getSize(); ++x) {
        for (int y = 0; y < map.getSize(); ++y) {
            if (visible[x][y]) {
                nodes[x][y] = graph.addNode();
                positions.add(app.getHeightmapPoint(x, y).add(0, 0.5f, 0));
                indices.add(new Vector2f(x, y));
            } else {
                nodes[x][y] = -1;
            }
        }
    }
    for (int x = 0; x < map.getSize(); ++x) {
        for (int y = 0; y < map.getSize(); ++y) {
            if (nodes[x][y] == -1) {
                continue;
            }
            if (x > 0 && nodes[x - 1][y] >= 0) {
                graph.addEdge(nodes[x - 1][y], nodes[x][y], -100);
            }
            if (y > 0 && nodes[x][y - 1] >= 0) {
                graph.addEdge(nodes[x][y - 1], nodes[x][y], -100);
            }
            if (x > 0 && y > 0 && nodes[x - 1][y - 1] >= 0) {
                graph.addEdge(nodes[x - 1][y - 1], nodes[x][y], -100);
            }
            if (x > 0 && y > 0 && nodes[x - 1][y] >= 0 && nodes[x][y - 1] >= 0) {
                graph.addEdge(nodes[x - 1][y], nodes[x][y - 1], -100);
            }
        }
    }

    //find silhouettes
    for (Triple<Integer, Integer, Float> e : graph) {
        Vector2f a = indices.get(e.getLeft());
        Vector2f b = indices.get(e.getMiddle());
        int ax = (int) a.x;
        int ay = (int) a.y;
        int bx = (int) b.x;
        int by = (int) b.y;
        Vector3f A = app.getHeightmapPoint(ax, ay);
        Vector3f B = app.getHeightmapPoint(bx, by);
        Vector3f C, D;
        if (a.x == b.x) {
            //vertical step
            if (a.x > 0) {
                C = app.getHeightmapPoint(ax - 1, ay).add(app.getHeightmapPoint(bx - 1, by)).multLocal(0.5f);
            } else {
                C = A.add(B).multLocal(0.5f);
            }
            if (a.x < map.getSize() - 1) {
                D = app.getHeightmapPoint(ax + 1, ay).add(app.getHeightmapPoint(bx + 1, by)).multLocal(0.5f);
            } else {
                D = A.add(B).multLocal(0.5f);
            }
        } else if (a.y == b.y) {
            //horizontal step
            if (a.y > 0) {
                C = app.getHeightmapPoint(ax, ay - 1).add(app.getHeightmapPoint(bx, by - 1)).multLocal(0.5f);
            } else {
                C = A.add(B).multLocal(0.5f);
            }
            if (a.y < map.getSize() - 1) {
                D = app.getHeightmapPoint(ax, ax + 1).add(app.getHeightmapPoint(bx, by + 1)).multLocal(0.5f);
            } else {
                D = A.add(B).multLocal(0.5f);
            }
        } else {
            //diagonal step
            C = app.getHeightmapPoint(ax, by);
            D = app.getHeightmapPoint(bx, ay);
        }
        //check silhouette
        Vector3f pA = cam.getScreenCoordinates(A);
        Vector3f pB = cam.getScreenCoordinates(B);
        Vector3f pC = cam.getScreenCoordinates(C);
        Vector3f pD = cam.getScreenCoordinates(D);
        Vector2f ppA = new Vector2f(pA.x, pA.y);
        Vector2f ppB = new Vector2f(pB.x, pB.y);
        Vector2f ppC = new Vector2f(pC.x, pC.y);
        Vector2f ppD = new Vector2f(pD.x, pD.y);
        if (FastMath.counterClockwise(ppA, ppB, ppC) == FastMath.counterClockwise(ppA, ppB, ppD)) {
            //silhouette detected
            graph.setEdgeWeight(e.getLeft(), e.getMiddle(), 1000);
            continue;
        }

        //check ringes
    }
    showGraph(graph, visiblePoints);

    LOG.info("features: " + features);
    displayFeatures();
}

From source file:org.shaman.terrain.sketch.SketchTerrain_old.java

private void showGraph(Graph g, List<Vector3f> positions) {
    ArrayList<Vector3f> lines = new ArrayList<>();
    ArrayList<ColorRGBA> colors = new ArrayList<>();
    for (Triple<Integer, Integer, Float> e : g) {
        lines.add(positions.get(e.getLeft()));
        lines.add(positions.get(e.getMiddle()));
        float v = 1 - (e.getRight() + 100) / 200f;
        ColorRGBA col = new ColorRGBA(1, v, v, 1);
        //         ColorRGBA col = ColorRGBA.White;
        colors.add(col);//from  w  ww .j a  v  a 2 s  .c  om
        colors.add(col);
    }
    Mesh m = new Mesh();
    m.setBuffer(VertexBuffer.Type.Position, 3,
            BufferUtils.createFloatBuffer(lines.toArray(new Vector3f[lines.size()])));
    m.setBuffer(VertexBuffer.Type.Color, 4,
            BufferUtils.createFloatBuffer(colors.toArray(new ColorRGBA[colors.size()])));
    m.setMode(Mesh.Mode.Lines);
    m.setLineWidth(2);
    m.updateCounts();
    m.updateBound();
    Material mat = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md");
    //mat.setColor("Color", ColorRGBA.White);
    mat.setBoolean("VertexColor", true);
    Geometry geom = new Geometry("graph", m);
    geom.setMaterial(mat);
    featureNode.attachChild(geom);
}