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

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

Introduction

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

Prototype

public abstract R getRight();

Source Link

Document

Gets the right element from this triple.

Usage

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

/**
 * run sequential execution//  www  .  j a  va  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// ww w.  ja  v  a 2  s.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 .  j a va2  s .  co  m
    }
    return relocations;
}

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

/**
 * Test method for//  w  w w. ja  v  a  2s .  com
 * {@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.// w  w  w.j a v a2  s .c  o  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./*from  w ww. j a  v  a  2s.co m*/
 * @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 target MAC mapping.//  w  w w. ja va  2s .  c o m
 *
 * @param ctx       MD-SAL datastore transaction context.
 * @param pv        A {@link PortVlan} instance that indicates the VLAN to
 *                  be reserved.
 * @param reserved  {@code true} means that the target VLAN on the switch
 *                  port is reserved.
 * @return
 *   <p>
 *     A {@link Triple} instance is returned if the MAC mapping was
 *     successfully activated.
 *   </p>
 *   <ul>
 *     <li>
 *       A boolean value that indicates the result is set to the left.
 *       {@code true} means that the target MAC mapping has been activated.
 *       {@code false} means that the target MAC mapping is already
 *       activated.
 *     </li>
 *     <li>
 *       A {@link SalPort} instance that specifies the physical switch port
 *       previously associated with the L2 host in the MAC mapping is set
 *       to the middle.
 *     </li>
 *     <li>
 *       A {@link PortVlan} instance that specifies the VLAN to be released
 *       is set to the right.
 *     </li>
 *   </ul>
 *   <p>
 *     {@code null} is returned if the MAC mapping for the specified
 *     host is already activated.
 *   </p>
 * @throws org.opendaylight.vtn.manager.internal.util.vnode.MacMapDuplicateException
 *    The specified MAC address is already mapped by this MAC mapping.
 * @throws VTNException  A fatal error occurred.
 */
private Triple<Boolean, SalPort, PortVlan> activate(TxContext ctx, PortVlan pv, boolean reserved)
        throws VTNException {
    MacMapStatusReader reader = ctx.getSpecific(MacMapStatusReader.class);
    VTNMacMapStatus vmst = reader.get(targetId);
    Triple<Boolean, SalPort, PortVlan> result = vmst.activate(targetId, targetHost, targetPort);
    if (result != null) {
        PortVlan released = result.getRight();
        if (released != null) {
            // Release the switch port which is no longer used by the
            // target MAC mapping.
            MappingRegistry.releasePort(ctx, released, targetId);
        }
        if (reserved) {
            ReadWriteTransaction tx = ctx.getReadWriteTransaction();
            VlanMapIdentifier vmapId = MappingRegistry.getVlanMapping(tx, pv.getPort(), pv.getVlanId());
            if (vmapId != null) {
                // Need to purge network caches superseded by the
                // MAC mapping.
                vlanMap = vmapId;
                reservedNetwork = pv;
            }
        }
    } else if (reserved) {
        // This should never happen.
        String msg = "Port is reserved by MAC mapping unexpectedly: " + "map=" + targetId + ", host="
                + targetHost + ", port=" + targetPort;
        throw new VTNException(msg);
    }

    return result;
}

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 v a 2  s . c o  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

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);// ww  w .j ava 2s. 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);
}

From source file:org.tango.server.attribute.log.AttributeAppender.java

public String[][] getLog() {
    final String[][] result = new String[log.size()][3];
    int i = 0;//from w w w .ja  v a 2 s . com
    for (final Triple<String, String, String> triple : log) {
        result[i][0] = triple.getLeft();
        result[i][1] = triple.getMiddle();
        result[i][2] = triple.getRight();
        i++;
    }
    return result;
}