2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.ovsdb.southbound.ovsdb.transact;
10 import static org.opendaylight.ovsdb.lib.operations.Operations.op;
12 import java.util.ArrayList;
13 import java.util.Collection;
14 import java.util.HashMap;
15 import java.util.HashSet;
16 import java.util.LinkedList;
17 import java.util.List;
19 import java.util.Map.Entry;
20 import java.util.Queue;
23 import javax.annotation.Nullable;
25 import com.google.common.base.Predicate;
26 import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
27 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
28 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
29 import org.opendaylight.ovsdb.lib.notation.Mutation;
30 import org.opendaylight.ovsdb.lib.notation.Mutator;
31 import org.opendaylight.ovsdb.lib.notation.OvsdbSet;
32 import org.opendaylight.ovsdb.lib.notation.UUID;
33 import org.opendaylight.ovsdb.lib.operations.Insert;
34 import org.opendaylight.ovsdb.lib.operations.Mutate;
35 import org.opendaylight.ovsdb.lib.operations.Operation;
36 import org.opendaylight.ovsdb.lib.operations.TransactionBuilder;
37 import org.opendaylight.ovsdb.lib.schema.ColumnSchema;
38 import org.opendaylight.ovsdb.lib.schema.GenericTableSchema;
39 import org.opendaylight.ovsdb.lib.schema.TableSchema;
40 import org.opendaylight.ovsdb.southbound.SouthboundConstants;
41 import org.opendaylight.ovsdb.southbound.SouthboundMapper;
42 import org.opendaylight.ovsdb.southbound.SouthboundUtil;
43 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
45 import org.opendaylight.yangtools.yang.binding.ChildOf;
46 import org.opendaylight.yangtools.yang.binding.DataObject;
47 import org.opendaylight.yangtools.yang.binding.Identifiable;
48 import org.opendaylight.yangtools.yang.binding.Identifier;
49 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
50 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
52 import com.google.common.base.Predicates;
53 import com.google.common.collect.ImmutableMap;
54 import com.google.common.collect.Lists;
55 import com.google.common.collect.Maps;
56 import com.google.common.collect.Sets;
58 public class TransactUtils {
59 private static <T extends DataObject> Predicate<DataObjectModification<T>> hasDataBefore() {
60 return new Predicate<DataObjectModification<T>>() {
62 public boolean apply(@Nullable DataObjectModification<T> input) {
63 return input != null && input.getDataBefore() != null;
68 private static <T extends DataObject> Predicate<DataObjectModification<T>> hasDataBeforeAndDataAfter() {
69 return new Predicate<DataObjectModification<T>>() {
71 public boolean apply(@Nullable DataObjectModification<T> input) {
72 return input != null && input.getDataBefore() != null && input.getDataAfter() != null;
77 private static <T extends DataObject> Predicate<DataObjectModification<T>> hasNoDataBefore() {
78 return new Predicate<DataObjectModification<T>>() {
80 public boolean apply(@Nullable DataObjectModification<T> input) {
81 return input != null && input.getDataBefore() == null;
86 private static <T extends DataObject> Predicate<DataObjectModification<T>> hasDataAfterAndMatchesFilter(
87 final Predicate<DataObjectModification<T>> filter) {
88 return new Predicate<DataObjectModification<T>>() {
90 public boolean apply(@Nullable DataObjectModification<T> input) {
91 return input != null && input.getDataAfter() != null && filter.apply(input);
96 private static <T extends DataObject> Predicate<DataObjectModification<T>> matchesEverything() {
97 return new Predicate<DataObjectModification<T>>() {
99 public boolean apply(@Nullable DataObjectModification<T> input) {
105 private static <T extends DataObject> Predicate<DataObjectModification<T>> modificationIsDeletion() {
106 return new Predicate<DataObjectModification<T>>() {
108 public boolean apply(@Nullable DataObjectModification<T> input) {
109 return input != null && input.getModificationType() == DataObjectModification
110 .ModificationType.DELETE;
115 private static <T extends DataObject> Predicate<DataObjectModification<T>> modificationIsDeletionAndHasDataBefore
117 return new Predicate<DataObjectModification<T>>() {
119 public boolean apply(@Nullable DataObjectModification<T> input) {
120 return input != null && input.getModificationType() == DataObjectModification
121 .ModificationType.DELETE && input.getDataBefore() != null;
126 public static Map<InstanceIdentifier<Node>,Node> extractNode(
127 Map<InstanceIdentifier<?>, DataObject> changes) {
128 Map<InstanceIdentifier<Node>,Node> result
130 if (changes != null) {
131 for (Entry<InstanceIdentifier<?>, DataObject> created : changes.entrySet()) {
132 if (created.getValue() instanceof Node) {
133 Node value = (Node) created.getValue();
134 Class<?> type = created.getKey().getTargetType();
135 if (type.equals(Node.class)) {
136 @SuppressWarnings("unchecked") // Actually checked above
137 InstanceIdentifier<Node> iid = (InstanceIdentifier<Node>) created.getKey();
138 result.put(iid, value);
146 public static <T extends DataObject> Map<InstanceIdentifier<T>,T> extractCreated(
147 AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,Class<T> klazz) {
148 return extract(changes.getCreatedData(),klazz);
152 * Extract all the instances of {@code clazz} which were created in the given set of modifications.
154 * @param changes The changes to process.
155 * @param clazz The class we're interested in.
156 * @param <T> The type of changes we're interested in.
157 * @param <U> The type of changes to process.
158 * @return The created instances, mapped by instance identifier.
160 public static <T extends DataObject, U extends DataObject> Map<InstanceIdentifier<T>, T> extractCreated(
161 Collection<DataTreeModification<U>> changes, Class<T> clazz) {
162 return extractCreatedOrUpdated(changes, clazz, hasNoDataBefore());
166 * Extract all the instance of {@code clazz} which were created or updated in the given set of modifications, and
167 * which satisfy the given filter.
169 * @param changes The changes to process.
170 * @param clazz The class we're interested in.
171 * @param filter The filter the changes must satisfy.
172 * @param <T> The type of changes we're interested in.
173 * @param <U> The type of changes to process.
174 * @return The created or updated instances which satisfy the filter, mapped by instance identifier.
176 public static <T extends DataObject, U extends DataObject> Map<InstanceIdentifier<T>, T> extractCreatedOrUpdated(
177 Collection<DataTreeModification<U>> changes, Class<T> clazz,
178 Predicate<DataObjectModification<T>> filter) {
179 Map<InstanceIdentifier<T>, T> result = new HashMap<>();
180 for (Map.Entry<InstanceIdentifier<T>, DataObjectModification<T>> entry : extractDataObjectModifications(changes,
181 clazz, hasDataAfterAndMatchesFilter(filter)).entrySet()) {
182 result.put(entry.getKey(), entry.getValue().getDataAfter());
187 public static <T extends DataObject> Map<InstanceIdentifier<T>,T> extractUpdated(
188 AsyncDataChangeEvent<InstanceIdentifier<?>,DataObject> changes,Class<T> klazz) {
189 return extract(changes.getUpdatedData(),klazz);
193 * Extract all the instances of {@code clazz} which were updated in the given set of modifications.
195 * @param changes The changes to process.
196 * @param clazz The class we're interested in.
197 * @param <T> The type of changes we're interested in.
198 * @param <U> The type of changes to process.
199 * @return The updated instances, mapped by instance identifier.
201 public static <T extends DataObject, U extends DataObject> Map<InstanceIdentifier<T>, T> extractUpdated(
202 Collection<DataTreeModification<U>> changes, Class<T> clazz) {
203 return extractCreatedOrUpdated(changes, clazz, hasDataBeforeAndDataAfter());
206 public static <T extends DataObject> Map<InstanceIdentifier<T>,T> extractCreatedOrUpdated(
207 AsyncDataChangeEvent<InstanceIdentifier<?>,DataObject> changes,Class<T> klazz) {
208 Map<InstanceIdentifier<T>,T> result = extractUpdated(changes,klazz);
209 result.putAll(extractCreated(changes,klazz));
214 * Extract all the instances of {@code clazz} which were created or updated in the given set of modifications.
216 * @param changes The changes to process.
217 * @param clazz The class we're interested in.
218 * @param <T> The type of changes we're interested in.
219 * @param <U> The type of changes to process.
220 * @return The created or updated instances, mapped by instance identifier.
222 public static <T extends DataObject, U extends DataObject> Map<InstanceIdentifier<T>, T> extractCreatedOrUpdated(
223 Collection<DataTreeModification<U>> changes, Class<T> clazz) {
224 return extractCreatedOrUpdated(changes, clazz, matchesEverything());
227 public static <T extends DataObject> Map<InstanceIdentifier<T>, T> extractCreatedOrUpdatedOrRemoved(
228 AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,
230 Map<InstanceIdentifier<T>,T> result = extractCreatedOrUpdated(changes,klazz);
231 result.putAll(extractRemovedObjects(changes, klazz));
236 * Extract all the instances of {@code clazz} which were created, updated, or removed in the given set of
237 * modifications. For instances which were created or updated, the new instances are returned; for instances
238 * which were removed, the old instances are returned.
240 * @param changes The changes to process.
241 * @param clazz The class we're interested in.
242 * @param <T> The type of changes we're interested in.
243 * @param <U> The type of changes to process.
244 * @return The created, updated or removed instances, mapped by instance identifier.
246 public static <T extends DataObject, U extends DataObject> Map<InstanceIdentifier<T>, T>
247 extractCreatedOrUpdatedOrRemoved(
248 Collection<DataTreeModification<U>> changes, Class<T> clazz) {
249 Map<InstanceIdentifier<T>, T> result = extractCreatedOrUpdated(changes, clazz);
250 result.putAll(extractRemovedObjects(changes, clazz));
254 public static <T extends DataObject> Map<InstanceIdentifier<T>,T> extractOriginal(
255 AsyncDataChangeEvent<InstanceIdentifier<?>,DataObject> changes,Class<T> klazz) {
256 return extract(changes.getOriginalData(),klazz);
260 * Extract the original instances of class {@code clazz} in the given set of modifications.
262 * @param changes The changes to process.
263 * @param clazz The class we're interested in.
264 * @param <T> The type of changes we're interested in.
265 * @param <U> The type of changes to process.
266 * @return The original instances, mapped by instance identifier.
268 public static <T extends DataObject, U extends DataObject> Map<InstanceIdentifier<T>, T> extractOriginal(
269 Collection<DataTreeModification<U>> changes, Class<T> clazz) {
270 Map<InstanceIdentifier<T>, T> result = new HashMap<>();
271 for (Map.Entry<InstanceIdentifier<T>, DataObjectModification<T>> entry :
272 extractDataObjectModifications(changes, clazz, hasDataBefore()).entrySet()) {
273 result.put(entry.getKey(), entry.getValue().getDataBefore());
278 public static <T extends DataObject> Set<InstanceIdentifier<T>> extractRemoved(
279 AsyncDataChangeEvent<InstanceIdentifier<?>,DataObject> changes,Class<T> klazz) {
280 Set<InstanceIdentifier<T>> result = new HashSet<>();
281 if (changes != null && changes.getRemovedPaths() != null) {
282 for (InstanceIdentifier<?> iid : changes.getRemovedPaths()) {
283 if (iid.getTargetType().equals(klazz)) {
284 @SuppressWarnings("unchecked") // Actually checked above
285 InstanceIdentifier<T> iidn = (InstanceIdentifier<T>)iid;
294 * Extract the instance identifier of removed instances of {@code clazz} from the given set of modifications.
296 * @param changes The changes to process.
297 * @param clazz The class we're interested in.
298 * @param <T> The type of changes we're interested in.
299 * @param <U> The type of changes to process.
300 * @return The instance identifiers of removed instances.
302 public static <T extends DataObject, U extends DataObject> Set<InstanceIdentifier<T>> extractRemoved(
303 Collection<DataTreeModification<U>> changes, Class<T> clazz) {
304 return extractDataObjectModifications(changes, clazz, modificationIsDeletion()).keySet();
308 * Extract all the modifications affecting instances of {@code clazz} which are present in the given set of
309 * modifications and satisfy the given filter.
311 * @param changes The changes to process.
312 * @param clazz The class we're interested in.
313 * @param filter The filter the changes must satisfy.
314 * @param <T> The type of changes we're interested in.
315 * @param <U> The type of changes to process.
316 * @return The modifications, mapped by instance identifier.
318 private static <T extends DataObject, U extends DataObject> Map<InstanceIdentifier<T>, DataObjectModification<T>>
319 extractDataObjectModifications(
320 Collection<DataTreeModification<U>> changes, Class<T> clazz,
321 Predicate<DataObjectModification<T>> filter) {
322 List<DataObjectModification<? extends DataObject>> dataObjectModifications = new ArrayList<>();
323 List<InstanceIdentifier<? extends DataObject>> paths = new ArrayList<>();
324 if (changes != null) {
325 for (DataTreeModification<? extends DataObject> change : changes) {
326 dataObjectModifications.add(change.getRootNode());
327 paths.add(change.getRootPath().getRootIdentifier());
330 return extractDataObjectModifications(dataObjectModifications, paths, clazz, filter);
334 * Extract all the modifications affecting instances of {@code clazz} which are present in the given set of
335 * modifications and satisfy the given filter.
337 * @param changes The changes to process.
338 * @param paths The paths of the changes.
339 * @param clazz The class we're interested in.
340 * @param filter The filter the changes must satisfy.
341 * @param <T> The type of changes we're interested in.
342 * @return The modifications, mapped by instance identifier.
344 private static <T extends DataObject> Map<InstanceIdentifier<T>, DataObjectModification<T>>
345 extractDataObjectModifications(
346 Collection<DataObjectModification<? extends DataObject>> changes,
347 Collection<InstanceIdentifier<? extends DataObject>> paths, Class<T> clazz,
348 Predicate<DataObjectModification<T>> filter) {
349 Map<InstanceIdentifier<T>, DataObjectModification<T>> result = new HashMap<>();
350 Queue<DataObjectModification<? extends DataObject>> remainingChanges = new LinkedList<>(changes);
351 Queue<InstanceIdentifier<? extends DataObject>> remainingPaths = new LinkedList<>(paths);
352 while (!remainingChanges.isEmpty()) {
353 DataObjectModification<? extends DataObject> change = remainingChanges.remove();
354 InstanceIdentifier<? extends DataObject> path = remainingPaths.remove();
355 // Is the change relevant?
356 if (clazz.isAssignableFrom(change.getDataType()) && filter.apply((DataObjectModification<T>) change)) {
357 result.put((InstanceIdentifier<T>) path, (DataObjectModification<T>) change);
359 // Add any children to the queue
360 for (DataObjectModification<? extends DataObject> child : change.getModifiedChildren()) {
361 remainingChanges.add(child);
362 remainingPaths.add(extendPath(path, child));
369 * Extends the given instance identifier path to include the given child. Augmentations are treated in the same way
370 * as children; keyed children are handled correctly.
372 * @param path The current path.
373 * @param child The child modification to include.
374 * @return The extended path.
376 private static <N extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<N>, T extends DataObject>
377 InstanceIdentifier<? extends DataObject> extendPath(
378 InstanceIdentifier path,
379 DataObjectModification child) {
380 Class<N> item = (Class<N>) child.getDataType();
381 if (child.getIdentifier() instanceof InstanceIdentifier.IdentifiableItem) {
382 K key = (K) ((InstanceIdentifier.IdentifiableItem) child.getIdentifier()).getKey();
383 KeyedInstanceIdentifier<N, K> extendedPath = path.child(item, key);
386 InstanceIdentifier<N> extendedPath = path.child(item);
391 public static <T extends DataObject> Map<InstanceIdentifier<T>, T> extractRemovedObjects(
392 AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> changes,
394 Set<InstanceIdentifier<T>> iids = extractRemoved(changes, klazz);
395 return Maps.filterKeys(extractOriginal(changes, klazz),Predicates.in(iids));
399 * Extract the removed instances of {@code clazz} from the given set of modifications.
401 * @param changes The changes to process.
402 * @param clazz The class we're interested in.
403 * @param <T> The type of changes we're interested in.
404 * @param <U> The type of changes to process.
405 * @return The removed instances, keyed by instance identifier.
407 public static <T extends DataObject, U extends DataObject> Map<InstanceIdentifier<T>, T> extractRemovedObjects(
408 Collection<DataTreeModification<U>> changes, Class<T> clazz) {
409 Map<InstanceIdentifier<T>, T> result = new HashMap<>();
410 for (Map.Entry<InstanceIdentifier<T>, DataObjectModification<T>> entry :
411 extractDataObjectModifications(changes, clazz, modificationIsDeletionAndHasDataBefore()).entrySet()) {
412 result.put(entry.getKey(), entry.getValue().getDataBefore());
417 public static <T extends DataObject> Map<InstanceIdentifier<T>,T> extract(
418 Map<InstanceIdentifier<?>, DataObject> changes, Class<T> klazz) {
419 Map<InstanceIdentifier<T>,T> result = new HashMap<>();
420 if (changes != null) {
421 for (Entry<InstanceIdentifier<?>, DataObject> created : changes.entrySet()) {
422 if (klazz.isInstance(created.getValue())) {
423 @SuppressWarnings("unchecked")
424 T value = (T) created.getValue();
425 Class<?> type = created.getKey().getTargetType();
426 if (type.equals(klazz)) {
427 @SuppressWarnings("unchecked") // Actually checked above
428 InstanceIdentifier<T> iid = (InstanceIdentifier<T>) created.getKey();
429 result.put(iid, value);
437 public static List<Insert> extractInsert(TransactionBuilder transaction, GenericTableSchema schema) {
438 List<Operation> operations = transaction.getOperations();
439 List<Insert> inserts = new ArrayList<>();
440 for (Operation operation : operations) {
441 if (operation instanceof Insert && operation.getTableSchema().equals(schema)) {
442 inserts.add((Insert) operation);
449 * Extract the NamedUuid from the Insert.
450 * If the Insert does not have a NamedUuid set, a random one will be
451 * generated, set, and returned.
453 * @param insert - Insert from which to extract the NamedUuid
454 * @return UUID - NamedUUID of the Insert
456 public static UUID extractNamedUuid(Insert insert) {
457 String uuidString = insert.getUuidName() != null
458 ? insert.getUuidName() : SouthboundMapper.getRandomUUID();
459 insert.setUuidName(uuidString);
460 return new UUID(uuidString);
463 public static <T extends TableSchema<T>> void stampInstanceIdentifier(TransactionBuilder transaction,
464 InstanceIdentifier<?> iid, TableSchema<T> tableSchema,
465 ColumnSchema<T, Map<String,String>> columnSchema) {
466 transaction.add(stampInstanceIdentifierMutation(transaction,iid,
467 tableSchema,columnSchema));
470 public static <T extends TableSchema<T>> Mutate<T> stampInstanceIdentifierMutation(TransactionBuilder transaction,
471 InstanceIdentifier<?> iid, TableSchema<T> tableSchema,
472 ColumnSchema<T, Map<String,String>> columnSchema) {
473 Map<String,String> externalIdsMap = ImmutableMap.of(SouthboundConstants.IID_EXTERNAL_ID_KEY,
474 SouthboundUtil.serializeInstanceIdentifier(iid));
475 Mutate<T> mutate = op.mutate(tableSchema)
476 .addMutation(columnSchema,
479 Mutation deleteIidMutation = new Mutation(columnSchema.getName(),
481 OvsdbSet.fromSet(Sets.newHashSet(SouthboundConstants.IID_EXTERNAL_ID_KEY)));
482 List<Mutation> mutations = Lists.newArrayList(Sets.newHashSet(deleteIidMutation));
483 mutations.addAll(mutate.getMutations());
484 mutate.setMutations(mutations);
489 * This method builds a string by concatenating the 2 character
490 * hexadecimal representation of each byte from the input byte array.
492 * For example: an input byte array containing:
500 * returns the string "6162632d313233"
503 * The byte array to convert to string
504 * @return The hexadecimal representation of the byte array. If bytes is
505 * null, the string "" is returned
507 public static String bytesToHexString(byte[] bytes) {
513 StringBuffer buf = new StringBuffer();
514 for (int i = 0; i < bytes.length; i++) {
515 short u8byte = (short) (bytes[i] & 0xff);
516 String tmp = Integer.toHexString(u8byte);
517 if (tmp.length() == 1) {
522 return buf.toString();