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
9 package org.opendaylight.groupbasedpolicy.neutron.mapper.util;
11 import org.opendaylight.controller.md.sal.binding.api.ReadTransaction;
12 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
13 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
14 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
15 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
16 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
17 import org.opendaylight.yangtools.yang.binding.DataObject;
18 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
22 import com.google.common.base.Optional;
23 import com.google.common.util.concurrent.CheckedFuture;
26 * @author Martin Sunal
28 public class DataStoreHelper {
30 private static final Logger LOG = LoggerFactory.getLogger(DataStoreHelper.class);
33 * Reads data from datastore as synchrone call.
34 * @return {@link Optional#isPresent()} is {@code true} if reading was successful and data exists in datastore; {@link Optional#isPresent()} is {@code false} otherwise
36 public static <T extends DataObject> Optional<T> readFromDs(LogicalDatastoreType store, InstanceIdentifier<T> path, ReadTransaction rTx) {
37 CheckedFuture<Optional<T>, ReadFailedException> resultFuture = rTx.read(store, path);
39 return resultFuture.checkedGet();
40 } catch (ReadFailedException e) {
41 LOG.warn("Read failed from DS.", e);
42 return Optional.absent();
47 * Calls {@link WriteTransaction#submit()} on write transaction.
48 * @param wTx write transaction
49 * @return {@code true} if transaction commit was successful; {@code false} otherwise
51 public static boolean submitToDs(WriteTransaction wTx) {
52 CheckedFuture<Void, TransactionCommitFailedException> submitFuture = wTx.submit();
54 submitFuture.checkedGet();
56 } catch (TransactionCommitFailedException e) {
57 LOG.warn("Transaction commit failed to DS.", e);
63 * If an element on the path exists in datastore the element is removed and returned as a result.
64 * {@link Optional#isPresent()} is {@code false} in case that element on path does not exist.
65 * @return removed element in {@link Optional#get()}; otherwise {@link Optional#absent()}
67 public static <T extends DataObject> Optional<T> removeIfExists(LogicalDatastoreType store, InstanceIdentifier<T> path,
68 ReadWriteTransaction rwTx) {
69 Optional<T> potentialResult = readFromDs(store, path, rwTx);
70 if (potentialResult.isPresent()) {
71 rwTx.delete(store, path);
73 return potentialResult;