org.opendaylight.yangtools.yang.binding.DataObject Java Examples

The following examples show how to use org.opendaylight.yangtools.yang.binding.DataObject. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TransactUtilsTest.java    From ovsdb with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testExtractRemovedObjects() {
    Set<InstanceIdentifier<DataObject>> iids = new HashSet<>();

    PowerMockito.doReturn(iids).when(TransactUtils.class);
    TransactUtils.extractRemoved(any(DataChangeEvent.class), eq(DataObject.class));

    Map<InstanceIdentifier<DataObject>, DataObject> result = new HashMap<>();

    PowerMockito.doReturn(result).when(TransactUtils.class);
    TransactUtils.extractOriginal(any(DataChangeEvent.class), eq(DataObject.class));

    Class<DataObject> klazz = DataObject.class;
    DataChangeEvent changes = mock(DataChangeEvent.class);
    assertEquals(Maps.filterKeys(result, Predicates.in(iids)), TransactUtils.extractRemovedObjects(changes, klazz));
}
 
Example #2
Source File: SouthboundUtil.java    From ovsdb with Eclipse Public License 1.0 6 votes vote down vote up
public static <D extends DataObject> Optional<D> readNode(ReadWriteTransaction transaction,
    InstanceIdentifier<D> connectionIid) {
    Optional<D> node;
    try {
        Node cachedNode = OvsdbOperGlobalListener.OPER_NODE_CACHE.get(connectionIid);
        if (cachedNode != null) {
            node = Optional.of((D)cachedNode);
        } else {
            node = transaction.read(LogicalDatastoreType.OPERATIONAL, connectionIid).get();
        }
    } catch (InterruptedException | ExecutionException e) {
        LOG.warn("Read Operational/DS for Node failed! {}", connectionIid, e);
        throw new RuntimeException(e);
    }
    return node;
}
 
Example #3
Source File: CheckTestUtil.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
private static <R, T extends DataObject> R readData(final DataBroker dataBroker, final LogicalDatastoreType ldt,
    final InstanceIdentifier<T> iid, final Function<T, R> function, final int timeout)
    throws ExecutionException, InterruptedException {
    AssertionError lastError = null;
    final Stopwatch sw = Stopwatch.createStarted();
    do {
        try (ReadTransaction tx = dataBroker.newReadOnlyTransaction()) {
            final Optional<T> data = tx.read(ldt, iid).get();
            if (data.isPresent()) {
                try {
                    return function.apply(data.get());
                } catch (final AssertionError e) {
                    lastError = e;
                    Uninterruptibles.sleepUninterruptibly(SLEEP_FOR, TimeUnit.MILLISECONDS);
                }
            }
        }
    } while (sw.elapsed(TimeUnit.SECONDS) <= timeout);
    throw lastError;
}
 
Example #4
Source File: BridgeConfigReconciliationTaskTest.java    From ovsdb with Eclipse Public License 1.0 6 votes vote down vote up
private Map<InstanceIdentifier<?>, DataObject> createExpectedConfigurationChanges(final Node bridgeNode) {
    OvsdbBridgeAugmentation ovsdbBridge = bridgeNode.augmentation(OvsdbBridgeAugmentation.class);

    Map<InstanceIdentifier<?>, DataObject> changes = new HashMap<>();
    final InstanceIdentifier<Node> bridgeNodeIid =
            SouthboundMapper.createInstanceIdentifier(bridgeNode.getNodeId());
    final InstanceIdentifier<OvsdbBridgeAugmentation> ovsdbBridgeIid =
            bridgeNodeIid.builder().augmentation(OvsdbBridgeAugmentation.class).build();
    changes.put(bridgeNodeIid, bridgeNode);
    changes.put(ovsdbBridgeIid, ovsdbBridge);
    for (ProtocolEntry protocolEntry : ovsdbBridge.getProtocolEntry().values()) {
        KeyedInstanceIdentifier<ProtocolEntry, ProtocolEntryKey> protocolIid =
                ovsdbBridgeIid.child(ProtocolEntry.class, protocolEntry.key());
        changes.put(protocolIid, protocolEntry);
    }
    for (ControllerEntry controller : ovsdbBridge.getControllerEntry().values()) {
        KeyedInstanceIdentifier<ControllerEntry, ControllerEntryKey> controllerIid =
                ovsdbBridgeIid.child(ControllerEntry.class, controller.key());
        changes.put(controllerIid, controller);
    }
    return changes;
}
 
Example #5
Source File: TransactUtilsTest.java    From ovsdb with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testExtractCreatedOrUpdatedOrRemoved() {
    Map<InstanceIdentifier<DataObject>, DataObject> result = new HashMap<>();

    PowerMockito.doReturn(result).when(TransactUtils.class);
    TransactUtils.extractCreatedOrUpdated(any(DataChangeEvent.class), eq(DataObject.class));

    Map<InstanceIdentifier<DataObject>, DataObject> map = new HashMap<>();
    InstanceIdentifier<DataObject> iid = mock(InstanceIdentifier.class);
    DataObject db = mock(DataObject.class);
    map.put(iid, db);

    PowerMockito.doReturn(map).when(TransactUtils.class);
    TransactUtils.extractRemovedObjects(any(DataChangeEvent.class), eq(DataObject.class));

    Map<InstanceIdentifier<DataObject>, DataObject> testResult = new HashMap<>();
    testResult.put(iid, db);
    Class<DataObject> klazz = DataObject.class;
    DataChangeEvent changes = mock(DataChangeEvent.class);
    assertEquals(testResult, TransactUtils.extractCreatedOrUpdatedOrRemoved(changes, klazz));
}
 
Example #6
Source File: MdsalUtils.java    From ovsdb with Eclipse Public License 1.0 6 votes vote down vote up
public <D extends DataObject> Optional<D> readOptional(
        final LogicalDatastoreType store, final InstanceIdentifier<? extends DataObject> path)  {
    int trialNo = 0;
    ReadTransaction transaction = databroker.newReadOnlyTransaction();
    do {
        try {
            Optional<D> result = transaction.read(store, (InstanceIdentifier<D>)path).get();
            transaction.close();
            return result;
        } catch (InterruptedException | ExecutionException e) {
            if (trialNo == 0) {
                logReadFailureError(path, " mdsal Read failed exception retrying the read after sleep");
            }
            try {
                transaction.close();
                Thread.sleep(MDSAL_READ_SLEEP_INTERVAL_MS);
                transaction = databroker.newReadOnlyTransaction();
            } catch (InterruptedException e1) {
                logReadFailureError(path, " Sleep interrupted");
            }
        }
    } while (trialNo++ < MDSAL_MAX_READ_TRIALS);
    logReadFailureError(path, " All read trials exceeded");
    return Optional.empty();
}
 
Example #7
Source File: ProtocolsConfigFileProcessor.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public synchronized void loadConfiguration(final NormalizedNode<?, ?> dto) {
    final ContainerNode protocolsContainer = (ContainerNode) dto;
    final MapNode protocolList = (MapNode) protocolsContainer
            .getChild(protocolYIId.getLastPathArgument()).get();
    final Collection<MapEntryNode> protocolsCollection = protocolList.getValue();
    final WriteTransaction wtx = this.dataBroker.newWriteOnlyTransaction();
    for (final MapEntryNode protocolEntry : protocolsCollection) {
        final Map.Entry<InstanceIdentifier<?>, DataObject> bi = this.bindingSerializer
                .fromNormalizedNode(this.protocolYIId, protocolEntry);
        if (bi != null) {
            final Protocol protocol = (Protocol) bi.getValue();
            processProtocol(protocol, wtx);
        }
    }
    try {
        wtx.commit().get();
    } catch (final ExecutionException | InterruptedException e) {
        LOG.warn("Failed to create Protocol", e);
    }
}
 
Example #8
Source File: TransactUtils.java    From ovsdb with Eclipse Public License 1.0 6 votes vote down vote up
public static Map<InstanceIdentifier<Node>,Node> extractNode(
        Map<InstanceIdentifier<?>, DataObject> changes) {
    Map<InstanceIdentifier<Node>,Node> result
        = new HashMap<>();
    if (changes != null) {
        for (Entry<InstanceIdentifier<?>, DataObject> created : changes.entrySet()) {
            if (created.getValue() instanceof Node) {
                Node value = (Node) created.getValue();
                Class<?> type = created.getKey().getTargetType();
                if (type.equals(Node.class)) {
                    // Actually checked above
                    @SuppressWarnings("unchecked")
                    InstanceIdentifier<Node> iid = (InstanceIdentifier<Node>) created.getKey();
                    result.put(iid, value);
                }
            }
        }
    }
    return result;
}
 
Example #9
Source File: HwvtepOperationalDataChangeListener.java    From ovsdb with Eclipse Public License 1.0 6 votes vote down vote up
private void updateDeviceOpData(InstanceIdentifier<Node> key, DataObjectModification<? extends DataObject> mod) {
    Class<? extends Identifiable> childClass = (Class<? extends Identifiable>) mod.getDataType();
    InstanceIdentifier instanceIdentifier = getKey(key, mod, mod.getDataAfter());
    switch (mod.getModificationType()) {
        case WRITE:
            connectionInstance.getDeviceInfo().updateDeviceOperData(childClass, instanceIdentifier,
                    new UUID("uuid"), mod.getDataAfter());
            break;
        case DELETE:
            connectionInstance.getDeviceInfo().clearDeviceOperData(childClass, instanceIdentifier);
            break;
        case SUBTREE_MODIFIED:
            break;
        default:
            break;
    }
}
 
Example #10
Source File: MdsalUtils.java    From ovsdb with Eclipse Public License 1.0 6 votes vote down vote up
public boolean exists(
    final LogicalDatastoreType store, final InstanceIdentifier<? extends DataObject> path) {
    int trialNo = 0;
    ReadTransaction transaction = databroker.newReadOnlyTransaction();
    do {
        try {
            FluentFuture<Boolean> result = transaction.exists(store, path);
            transaction.close();
            return result.get().booleanValue();
        } catch (InterruptedException | ExecutionException e) {
            if (trialNo == 0) {
                logReadFailureError(path, " mdsal Read failed exception retrying the read after sleep");
            }
            try {
                transaction.close();
                Thread.sleep(MDSAL_READ_SLEEP_INTERVAL_MS);
                transaction = databroker.newReadOnlyTransaction();
            } catch (InterruptedException e1) {
                logReadFailureError(path, " Sleep interrupted");
            }
        }
    } while (trialNo++ < MDSAL_MAX_READ_TRIALS);
    logReadFailureError(path, " All read trials exceeded");
    return false;
}
 
Example #11
Source File: TransactUtils.java    From ovsdb with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Extract all the modifications affecting instances of {@code clazz} which are present in the given set of
 * modifications and satisfy the given filter.
 *
 * @param changes The changes to process.
 * @param paths The paths of the changes.
 * @param clazz The class we're interested in.
 * @param filter The filter the changes must satisfy.
 * @param <T> The type of changes we're interested in.
 * @return The modifications, mapped by instance identifier.
 */
private static <T extends DataObject> Map<InstanceIdentifier<T>, DataObjectModification<T>>
    extractDataObjectModifications(
        Collection<DataObjectModification<? extends DataObject>> changes,
        Collection<InstanceIdentifier<? extends DataObject>> paths, Class<T> clazz,
        Predicate<DataObjectModification<T>> filter) {
    Map<InstanceIdentifier<T>, DataObjectModification<T>> result = new HashMap<>();
    Queue<DataObjectModification<? extends DataObject>> remainingChanges = new LinkedList<>(changes);
    Queue<InstanceIdentifier<? extends DataObject>> remainingPaths = new LinkedList<>(paths);
    while (!remainingChanges.isEmpty()) {
        DataObjectModification<? extends DataObject> change = remainingChanges.remove();
        InstanceIdentifier<? extends DataObject> path = remainingPaths.remove();
        // Is the change relevant?
        if (clazz.isAssignableFrom(change.getDataType()) && filter.test((DataObjectModification<T>) change)) {
            result.put((InstanceIdentifier<T>) path, (DataObjectModification<T>) change);
        }
        // Add any children to the queue
        for (DataObjectModification<? extends DataObject> child : change.getModifiedChildren()) {
            remainingChanges.add(child);
            remainingPaths.add(extendPath(path, child));
        }
    }
    return result;
}
 
Example #12
Source File: ConnectedGraphServer.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Remove Graph or Graph components to the Data Store.
 *
 * @param <T>  As a generic method, T must be a Graph, Vertex, Edge or Prefix.
 * @param id   Instance Identifier of the Data Object
 * @param info Information to be logged
 */
private synchronized <T extends DataObject> void removeFromDataStore(final InstanceIdentifier<T> id,
        final String info) {
    final ReadWriteTransaction trans = this.chain.newReadWriteTransaction();
    trans.delete(LogicalDatastoreType.OPERATIONAL, id);
    trans.commit().addCallback(new FutureCallback<CommitInfo>() {
        @Override
        public void onSuccess(final CommitInfo result) {
            LOG.info("GraphModel: {} has been deleted in operational datastore ", info);
        }

        @Override
        public void onFailure(final Throwable throwable) {
            LOG.error("GraphModel: Cannot delete {} to the operational datastore (transaction: {})", info,
                    trans.getIdentifier());
        }
    }, MoreExecutors.directExecutor());
}
 
Example #13
Source File: DataChangeListenerTestBase.java    From ovsdb with Eclipse Public License 1.0 6 votes vote down vote up
Node addData(final LogicalDatastoreType logicalDatastoreType, final Class<? extends DataObject> dataObject,
        final String[]... data) {
    NodeBuilder nodeBuilder = prepareNode(nodeIid);
    HwvtepGlobalAugmentationBuilder builder = new HwvtepGlobalAugmentationBuilder();
    if (LogicalSwitches.class == dataObject) {
        TestBuilders.addLogicalSwitches(builder, data);
    }
    if (TerminationPoint.class == dataObject) {
        TestBuilders.addGlobalTerminationPoints(nodeBuilder, nodeIid, data);
    }
    if (RemoteUcastMacs.class == dataObject) {
        TestBuilders.addRemoteUcastMacs(nodeIid, builder, data);
    }
    if (RemoteMcastMacs.class == dataObject) {
        TestBuilders.addRemoteMcastMacs(nodeIid, builder, data);
    }
    nodeBuilder.addAugmentation(HwvtepGlobalAugmentation.class, builder.build());
    return mergeNode(logicalDatastoreType, nodeIid, nodeBuilder);
}
 
Example #14
Source File: DataChangesManagedByOvsdbNodeEvent.java    From ovsdb with Eclipse Public License 1.0 6 votes vote down vote up
private InstanceIdentifier<?> getManagedByIid(Map<InstanceIdentifier<?>, DataObject> map,
        InstanceIdentifier<?> iidToCheck) {
    // Get the InstanceIdentifier of the containing node
    InstanceIdentifier<Node> nodeEntryIid = iidToCheck.firstIdentifierOf(Node.class);

    // Look for the Node in the created/updated data
    DataObject dataObject = null;
    if (map != null && map.get(nodeEntryIid) != null) {
        dataObject = map.get(nodeEntryIid);
    }
    // If we are contained in a bridge managed by this iid
    if (dataObject != null && dataObject instanceof Node) {
        Node node = (Node)dataObject;
        OvsdbBridgeAugmentation bridge = node.augmentation(OvsdbBridgeAugmentation.class);
        if (bridge != null && bridge.getManagedBy() != null && bridge.getManagedBy().getValue().equals(this.iid)) {
            return bridge.getManagedBy().getValue();
        }
    }
    return null;
}
 
Example #15
Source File: ConnectedGraphServer.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Update Graph components (Vertex, Edge or Prefix ) to the Data Store. Old value identified by its Instance ID
 * will be remove first before adding the new value.
 *
 * @param <T>   As a generic method, T must be a Vertex, Edge or Prefix.
 * @param id    Instance Identifier of the Data Object
 * @param data  Data Object (Vertex, Edge or Prefix)
 * @param old   Instance Identifier of the previous version of the Data Object
 * @param info  Information to be logged
 */
private synchronized <T extends DataObject> void updateToDataStore(final InstanceIdentifier<T> id, final T data,
        final InstanceIdentifier<T> old, final String info) {
    final ReadWriteTransaction trans = this.chain.newReadWriteTransaction();
    if (old != null) {
        trans.delete(LogicalDatastoreType.OPERATIONAL, old);
    }
    trans.put(LogicalDatastoreType.OPERATIONAL, id, data);
    trans.commit().addCallback(new FutureCallback<CommitInfo>() {
        @Override
        public void onSuccess(final CommitInfo result) {
            LOG.info("GraphModel: {} has been published in operational datastore ", info);
        }

        @Override
        public void onFailure(final Throwable throwable) {
            LOG.error("GrahModel: Cannot write {} to the operational datastore (transaction: {})", info,
                    trans.getIdentifier());
        }
    }, MoreExecutors.directExecutor());
}
 
Example #16
Source File: SimpleNlriRegistry.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
synchronized Registration registerNlriSerializer(final Class<? extends DataObject> nlriClass,
        final NlriSerializer serializer) {
    final NlriSerializer prev = this.serializers.get(nlriClass);
    checkState(prev == null, "Serializer already bound to class " + prev);

    this.serializers.put(nlriClass, serializer);

    final Object lock = this;
    return new AbstractRegistration() {
        @Override
        protected void removeRegistration() {
            synchronized (lock) {
                SimpleNlriRegistry.this.serializers.remove(nlriClass);
            }
        }
    };
}
 
Example #17
Source File: HwvtepSouthboundUtil.java    From ovsdb with Eclipse Public License 1.0 6 votes vote down vote up
public static <D extends org.opendaylight.yangtools.yang.binding.DataObject> Optional<D> readNode(
        DataBroker db,
        LogicalDatastoreType logicalDatastoreType, final InstanceIdentifier<D> connectionIid) {
    if (logicalDatastoreType == LogicalDatastoreType.OPERATIONAL) {
        Node node = HwvtepOperGlobalListener.getNode((InstanceIdentifier<Node>) connectionIid);
        if (node != null) {
            return Optional.of((D)node);
        } else {
            LOG.debug("Node not available in cache. Read from datastore - {}", connectionIid);
        }
    }
    try (ReadTransaction transaction = db.newReadOnlyTransaction()) {
        return transaction.read(logicalDatastoreType, connectionIid).get();
    } catch (InterruptedException | ExecutionException e) {
        LOG.error("Read failed from datastore for Node : {}",connectionIid,e);
        throw new RuntimeException(e);
    }
}
 
Example #18
Source File: ConnectedGraphServer.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Add Graph or Graph components to the Data Store.
 *
 * @param <T>   As a generic method, T must be a Graph, Vertex, Edge or Prefix.
 * @param id    Instance Identifier of the Data Object
 * @param data  Data Object (Graph, Vertex, Edge or Prefix)
 * @param info  Information to be logged
 */
private synchronized <T extends DataObject> void addToDataStore(final InstanceIdentifier<T> id, final T data,
        final String info) {
    final ReadWriteTransaction trans = this.chain.newReadWriteTransaction();
    trans.put(LogicalDatastoreType.OPERATIONAL, id, data);
    trans.commit().addCallback(new FutureCallback<CommitInfo>() {
        @Override
        public void onSuccess(final CommitInfo result) {
            LOG.info("GraphModel: {} has been published in operational datastore ", info);
        }

        @Override
        public void onFailure(final Throwable throwable) {
            LOG.error("GrahModel: Cannot write {} to the operational datastore (transaction: {})", info,
                    trans.getIdentifier());
        }
    }, MoreExecutors.directExecutor());
}
 
Example #19
Source File: AbstractDataChangeListener.java    From atrium-odl with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void createData(final Map<InstanceIdentifier<?>, DataObject> createdData) {
    final Set<InstanceIdentifier<?>> keys = createdData.keySet() != null
            ? createdData.keySet() : Collections.<InstanceIdentifier<?>> emptySet();
    for (InstanceIdentifier<?> key : keys) {
        if (clazz.equals(key.getTargetType())) {
             InstanceIdentifier<T> createKeyIdent = key.firstIdentifierOf(clazz);
             final Optional<DataObject> value = Optional.of(createdData.get(key));
             if (value.isPresent()) {
                 this.add(createKeyIdent, (T)value.get());
             }
        }
    }
}
 
Example #20
Source File: MdsalUtils.java    From ovsdb with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Executes put as a blocking transaction.
 *
 * @param logicalDatastoreType {@link LogicalDatastoreType} which should be modified
 * @param path {@link InstanceIdentifier} for path to read
 * @param <D> the data object type
 * @return the result of the request
 */
public <D extends DataObject> boolean put(
        final LogicalDatastoreType logicalDatastoreType, final InstanceIdentifier<D> path, D data)  {
    boolean result = false;
    final WriteTransaction transaction = databroker.newWriteOnlyTransaction();
    transaction.mergeParentStructurePut(logicalDatastoreType, path, data);
    FluentFuture<? extends CommitInfo> future = transaction.commit();
    try {
        future.get();
        result = true;
    } catch (InterruptedException | ExecutionException e) {
        LOG.warn("Failed to put {} ", path, e);
    }
    return result;
}
 
Example #21
Source File: AbstractPeer.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
private <C extends Routes & DataObject & ChoiceIn<Tables>, S extends ChildOf<? super C>,
        R extends Route & ChildOf<? super S> & Identifiable<I>, I extends Identifier<R>> void deleteRoute(
        final RIBSupport<C, S, R, I> ribSupport,  final boolean addPathSupported,
        final KeyedInstanceIdentifier<Tables, TablesKey> tableRibout,
        final AbstractAdvertizedRoute<C, S , R, I> advRoute, final WriteTransaction tx) {
    final InstanceIdentifier<R> ribOutTarget = ribSupport.createRouteIdentifier(tableRibout,
        addPathSupported ? advRoute.getAddPathRouteKeyIdentifier() : advRoute.getNonAddPathRouteKeyIdentifier());
    LOG.trace("Removing {} from transaction for peer {}", ribOutTarget, getPeerId());
    tx.delete(LogicalDatastoreType.OPERATIONAL, ribOutTarget);
}
 
Example #22
Source File: MdsalUtilsAsync.java    From ovsdb with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Executes merge as non blocking transaction and return the future.
 *
 * @param logicalDatastoreType
 *            {@link LogicalDatastoreType} which should be modified
 * @param path
 *            {@link InstanceIdentifier} for path to read
 * @param <D>
 *            The data object type
 * @param withParent
 *            Whether or not to create missing parent.
 * @return The {@link FluentFuture} object to which you can assign a
 *         callback
 */
// FIXME: eliminate the boolean flag here to separate out the distinct code paths
public <D extends DataObject> FluentFuture<? extends CommitInfo> merge(
                                    final LogicalDatastoreType logicalDatastoreType,
                                    final InstanceIdentifier<D> path,
                                    final D data,
                                    final boolean withParent)  {
    final WriteTransaction transaction = databroker.newWriteOnlyTransaction();
    if (withParent) {
        transaction.mergeParentStructureMerge(logicalDatastoreType, path, data);
    } else {
        transaction.merge(logicalDatastoreType, path, data);
    }
    return transaction.commit();
}
 
Example #23
Source File: HwvtepDataChangeListenerTest.java    From ovsdb with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public <T extends DataObject> void testMcastMacAdd() throws Exception {
    addData(LogicalDatastoreType.CONFIGURATION, LogicalSwitches.class, logicalSwitches);
    addData(LogicalDatastoreType.OPERATIONAL, LogicalSwitches.class, logicalSwitches);
    resetOperations();
    addData(LogicalDatastoreType.CONFIGURATION, TerminationPoint.class, terminationPoints);
    addData(LogicalDatastoreType.CONFIGURATION, RemoteMcastMacs.class, mcastMacs);
    //2 mcast macs + 2 locator sets + 3 termination points
    verify(Operations.op,  times(7)).insert(ArgumentMatchers.<McastMacsRemote>any());
}
 
Example #24
Source File: HwvtepDataChangeListenerTest.java    From ovsdb with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public <T extends DataObject> void testMcastMacAddWithoutConfigTep() throws Exception {
    addData(LogicalDatastoreType.CONFIGURATION, LogicalSwitches.class, logicalSwitches);
    addData(LogicalDatastoreType.OPERATIONAL, LogicalSwitches.class, logicalSwitches);
    resetOperations();
    addData(LogicalDatastoreType.CONFIGURATION, RemoteMcastMacs.class, mcastMacs);
    //2 mcast macs + 2 locator sets + 3 termination points
    verify(Operations.op,  times(7)).insert(ArgumentMatchers.<McastMacsRemote>any());
}
 
Example #25
Source File: LocRibWriter.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
public static <C extends Routes & DataObject & ChoiceIn<Tables>, S extends ChildOf<? super C>,
            R extends Route & ChildOf<? super S> & Identifiable<I>, I extends Identifier<R>>
            LocRibWriter<C, S, R, I> create(
        final @NonNull RIBSupport<C, S, R, I> ribSupport,
        final @NonNull Class<? extends AfiSafiType> afiSafiType,
        final @NonNull TransactionChain chain,
        final @NonNull KeyedInstanceIdentifier<Rib, RibKey> ribIId,
        final @NonNull AsNumber ourAs,
        final @NonNull DataBroker dataBroker,
        final BGPRibRoutingPolicy ribPolicies,
        final @NonNull BGPPeerTracker peerTracker,
        final @NonNull PathSelectionMode pathSelectionStrategy) {
    return new LocRibWriter<>(ribSupport, chain, ribIId, ourAs.getValue(), dataBroker, ribPolicies,
            peerTracker, afiSafiType, pathSelectionStrategy);
}
 
Example #26
Source File: AbstractReachabilityTopologyBuilder.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
private static <T extends DataObject> T read(final ReadOperations rt, final InstanceIdentifier<T> id) {
    final Optional<T> optional;
    try {
        optional = rt.read(LogicalDatastoreType.OPERATIONAL, id).get();
    } catch (InterruptedException | ExecutionException e) {
        LOG.warn("Failed to read {}, assuming non-existent", id, e);
        return null;
    }

    return optional.orElse(null);
}
 
Example #27
Source File: MdsalUtilsTest.java    From ovsdb with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testPut() {
    WriteTransaction writeTransaction = mock(WriteTransaction.class);
    when(databroker.newWriteOnlyTransaction()).thenReturn(writeTransaction);
    doReturn(CommitInfo.emptyFluentFuture()).when(writeTransaction).commit();

    boolean result = mdsalUtils.put(LogicalDatastoreType.CONFIGURATION,
            mock(InstanceIdentifier.class), mock(DataObject.class));

    verify(writeTransaction, times(1)).mergeParentStructurePut(any(LogicalDatastoreType.class),
            any(InstanceIdentifier.class), any(DataObject.class));
    verify(writeTransaction, times(1)).commit();

    assertTrue("Error, the put transaction failed", result);
}
 
Example #28
Source File: AbstractRIBTestSetup.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void mockedMethods() throws Exception {
    MockitoAnnotations.initMocks(this);
    final ReadTransaction readTx = mock(ReadTransaction.class);
    doReturn(new TestListenerRegistration()).when(this.service)
            .registerDataTreeChangeListener(any(DOMDataTreeIdentifier.class),
                    any(ClusteredDOMDataTreeChangeListener.class));
    doNothing().when(readTx).close();
    doNothing().when(this.domTransWrite).put(eq(LogicalDatastoreType.OPERATIONAL),
            any(YangInstanceIdentifier.class), any(NormalizedNode.class));
    doNothing().when(this.domTransWrite).delete(eq(LogicalDatastoreType.OPERATIONAL),
            any(YangInstanceIdentifier.class));
    doNothing().when(this.domTransWrite).merge(eq(LogicalDatastoreType.OPERATIONAL),
            any(YangInstanceIdentifier.class), any(NormalizedNode.class));
    doReturn(FluentFutures.immediateFluentFuture(Optional.empty())).when(readTx)
        .read(eq(LogicalDatastoreType.OPERATIONAL), any(InstanceIdentifier.class));
    doNothing().when(this.domChain).close();
    doReturn(this.domTransWrite).when(this.domChain).newWriteOnlyTransaction();
    doNothing().when(getTransaction()).put(eq(LogicalDatastoreType.OPERATIONAL),
            eq(YangInstanceIdentifier.of(BgpRib.QNAME)), any(NormalizedNode.class));
    doReturn(ImmutableClassToInstanceMap.of(DOMDataTreeChangeService.class, this.service)).when(this.dom)
        .getExtensions();
    doReturn(this.domChain).when(this.dom).createMergingTransactionChain(any(AbstractPeer.class));
    doReturn(this.transWrite).when(this.chain).newWriteOnlyTransaction();
    doReturn(Optional.empty()).when(this.future).get();
    doReturn(this.future).when(this.domTransWrite).commit();
    doNothing().when(this.future).addListener(any(Runnable.class), any(Executor.class));
    doNothing().when(this.transWrite).mergeParentStructurePut(eq(LogicalDatastoreType.OPERATIONAL),
            any(InstanceIdentifier.class), any(DataObject.class));
    doNothing().when(this.transWrite).put(eq(LogicalDatastoreType.OPERATIONAL),
            any(InstanceIdentifier.class), any(DataObject.class));
    doReturn(this.future).when(this.transWrite).commit();
}
 
Example #29
Source File: RibManagerTest.java    From atrium-odl with Apache License 2.0 5 votes vote down vote up
public DataTreeModification getRouteUpdate(String prefix, String nextHopIp, ModificationType operation) {
	DataTreeModification routeUpdate = mock(DataTreeModification.class);
	
	Ipv4Prefix ipv4Prefix = new Ipv4Prefix(prefix);
	Ipv4Address ipv4Address = new Ipv4Address(nextHopIp);
	
	DataObjectModification root = mock(DataObjectModification.class);
	InstanceIdentifier instanceIdentifier = mock(InstanceIdentifier.class);
	DataTreeIdentifier treeIdentifier = new DataTreeIdentifier(LogicalDatastoreType.CONFIGURATION,
			instanceIdentifier);

	DataObject dataObject = mock(DataObject.class);
	Ipv4Route route = mock(Ipv4Route.class);
	Attributes attributes = mock(Attributes.class);
	Ipv4NextHopCase nhc = mock(Ipv4NextHopCase.class);
	Ipv4NextHop ipv4NextHop = mock(Ipv4NextHop.class);

	when(routeUpdate.getRootNode()).thenReturn(root);
	when(root.getModificationType()).thenReturn(operation);
	when(root.getDataAfter()).thenReturn(route);
	when(route.getAttributes()).thenReturn(attributes);
	when(attributes.getCNextHop()).thenReturn(nhc);
	when(nhc.getIpv4NextHop()).thenReturn(ipv4NextHop);
	when(ipv4NextHop.getGlobal()).thenReturn(ipv4Address);
	when(route.getPrefix()).thenReturn(ipv4Prefix);
	when(routeUpdate.getRootPath()).thenReturn(treeIdentifier);
	
	return routeUpdate;
}
 
Example #30
Source File: TransactUtils.java    From ovsdb with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Extract the original instances of class {@code clazz} in the given set of modifications.
 *
 * @param changes The changes to process.
 * @param clazz The class we're interested in.
 * @param <T> The type of changes we're interested in.
 * @param <U> The type of changes to process.
 * @return The original instances, mapped by instance identifier.
 */
public static <T extends DataObject, U extends DataObject> Map<InstanceIdentifier<T>, T> extractOriginal(
        Collection<DataTreeModification<U>> changes, Class<T> clazz) {
    Map<InstanceIdentifier<T>, T> result = new HashMap<>();
    for (Map.Entry<InstanceIdentifier<T>, DataObjectModification<T>> entry :
            extractDataObjectModifications(changes, clazz, hasDataBefore()).entrySet()) {
        result.put(entry.getKey(), entry.getValue().getDataBefore());
    }
    return result;
}