.DS_Store
.checkstyle
.factorypath
+.fbExcludeFilterFile
.tox
yang-gen-config
yang-gen-sal
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
-
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
-
import org.apache.commons.lang3.reflect.FieldUtils;
import org.junit.After;
import org.junit.Before;
doReturn(where).when(delete).where(any());
Insert insert = mock(Insert.class);
doReturn(insert).when(insert).withId(any(String.class));
- Operations.op = PowerMockito.mock(Operations.class);
- doReturn(insert).when(Operations.op).insert(insertOpCapture.capture());
+ Operations mockOp = PowerMockito.mock(Operations.class);
+ doReturn(insert).when(mockOp).insert(insertOpCapture.capture());
Update update = mock(Update.class);
- doReturn(update).when(Operations.op).update(insertOpCapture.capture());
+ doReturn(update).when(mockOp).update(insertOpCapture.capture());
doReturn(where).when(update).where(any());
- doReturn(delete).when(Operations.op).delete(any());
+ doReturn(delete).when(mockOp).delete(any());
+
+ Field opField = PowerMockito.field(Operations.class, "op");
+ try {
+ opField.set(Operations.class, mockOp);
+ } catch (IllegalAccessException e) {
+ throw new AssertionError("Set of Operations.op field failed", e);
+ }
+
ListenableFuture<List<OperationResult>> ft = mock(ListenableFuture.class);
transactCaptor = ArgumentCaptor.forClass(List.class);
doReturn(ft).when(ovsdbClient).transact(any(DatabaseSchema.class), transactCaptor.capture());
import java.io.Serializable;
public class MonitorHandle implements Serializable {
- String id;
+ private static final long serialVersionUID = 1L;
+
+ private final String id;
public MonitorHandle(String id) {
this.id = id;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.AdaptiveRecvByteBufAllocator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
-import java.util.HashSet;
import java.util.List;
import java.util.Map;
+import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.Nullable;
* environment. Hence a single instance of the service will be active (via Service Registry in OSGi)
* and a Singleton object in a non-OSGi environment.
*/
+@SuppressFBWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
public class OvsdbConnectionService implements AutoCloseable, OvsdbConnection {
private static final Logger LOG = LoggerFactory.getLogger(OvsdbConnectionService.class);
- private static ThreadFactory passiveConnectionThreadFactory = new ThreadFactoryBuilder()
- .setNameFormat("OVSDBPassiveConnServ-%d").build();
- private static ScheduledExecutorService executorService
- = Executors.newScheduledThreadPool(10, passiveConnectionThreadFactory);
-
- private static ThreadFactory connectionNotifierThreadFactory = new ThreadFactoryBuilder()
- .setNameFormat("OVSDBConnNotifSer-%d").build();
- private static ExecutorService connectionNotifierService
- = Executors.newCachedThreadPool(connectionNotifierThreadFactory);
-
- private static Set<OvsdbConnectionListener> connectionListeners = new HashSet<>();
- private static Map<OvsdbClient, Channel> connections = new ConcurrentHashMap<>();
- private static OvsdbConnection connectionService;
- private static AtomicBoolean singletonCreated = new AtomicBoolean(false);
private static final int IDLE_READER_TIMEOUT = 30;
private static final int READ_TIMEOUT = 180;
private static final String OVSDB_RPC_TASK_TIMEOUT_PARAM = "ovsdb-rpc-task-timeout";
private static final String USE_SSL = "use-ssl";
- private static boolean useSSL = false;
- private static ICertificateManager certManagerSrv = null;
+ private static final int RETRY_PERIOD = 100; // retry after 100 milliseconds
- private static int jsonRpcDecoderMaxFrameLength = 100000;
- private static int listenerPort = 6640;
+ private static final ScheduledExecutorService EXECUTOR_SERVICE = Executors.newScheduledThreadPool(10,
+ new ThreadFactoryBuilder().setNameFormat("OVSDBPassiveConnServ-%d").build());
+
+ private static final ExecutorService CONNECTION_NOTIFIER_SERVICE = Executors
+ .newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("OVSDBConnNotifSer-%d").build());
private static final StalePassiveConnectionService STALE_PASSIVE_CONNECTION_SERVICE =
- new StalePassiveConnectionService(executorService);
- private static Channel serverChannel = null;
+ new StalePassiveConnectionService(EXECUTOR_SERVICE);
+
+ private static final OvsdbConnection CONNECTION_SERVICE = new OvsdbConnectionService();
+
+ private static final Set<OvsdbConnectionListener> CONNECTION_LISTENERS = ConcurrentHashMap.newKeySet();
+ private static final Map<OvsdbClient, Channel> CONNECTIONS = new ConcurrentHashMap<>();
- private static int retryPeriod = 100; // retry after 100 milliseconds
+ private static volatile boolean useSSL = false;
+ private static volatile ICertificateManager certManagerSrv;
+ private static volatile int jsonRpcDecoderMaxFrameLength = 100000;
+ private static volatile Channel serverChannel;
+
+ private final AtomicBoolean singletonCreated = new AtomicBoolean(false);
+ private volatile int listenerPort = 6640;
public static OvsdbConnection getService() {
- if (connectionService == null) {
- connectionService = new OvsdbConnectionService();
- }
- return connectionService;
+ return CONNECTION_SERVICE;
}
/**
if (client == null) {
return;
}
- Channel channel = connections.get(client);
+ Channel channel = CONNECTIONS.get(client);
if (channel != null) {
//It's an explicit disconnect from user, so no need to notify back
//to user about the disconnect.
client.setConnectionPublished(false);
channel.disconnect();
}
- connections.remove(client);
+ CONNECTIONS.remove(client);
}
@Override
public void registerConnectionListener(OvsdbConnectionListener listener) {
LOG.info("registerConnectionListener: registering {}", listener.getClass().getSimpleName());
- connectionListeners.add(listener);
+ CONNECTION_LISTENERS.add(listener);
notifyAlreadyExistingConnectionsToListener(listener);
}
private void notifyAlreadyExistingConnectionsToListener(final OvsdbConnectionListener listener) {
for (final OvsdbClient client : getConnections()) {
- connectionNotifierService.submit(() -> {
+ CONNECTION_NOTIFIER_SERVICE.execute(() -> {
LOG.trace("Connection {} notified to listener {}", client.getConnectionInfo(), listener);
listener.connected(client);
});
@Override
public void unregisterConnectionListener(OvsdbConnectionListener listener) {
- connectionListeners.remove(listener);
+ CONNECTION_LISTENERS.remove(listener);
}
private static OvsdbClient getChannelClient(Channel channel, ConnectionType type,
OvsdbRPC rpc = factory.getClient(channel, OvsdbRPC.class);
OvsdbClientImpl client = new OvsdbClientImpl(rpc, channel, type, socketConnType);
client.setConnectionPublished(true);
- connections.put(client, channel);
+ CONNECTIONS.put(client, channel);
ChannelFuture closeFuture = channel.closeFuture();
closeFuture.addListener(new ChannelConnectionHandler(client));
return client;
final SSLContext sslContext,
final String[] protocols,
final String[] cipherSuites) {
- if (singletonCreated.getAndSet(false) && (serverChannel != null)) {
+ if (singletonCreated.getAndSet(false) && serverChannel != null) {
serverChannel.close();
LOG.info("Server channel closed");
}
LOG.error("Probe failed to OVSDB switch. Disconnecting the channel {}", client.getConnectionInfo());
client.disconnect();
}
- }, connectionNotifierService);
+ }, CONNECTION_NOTIFIER_SERVICE);
}
private static void handleNewPassiveConnection(final Channel channel) {
SslHandler sslHandler = (SslHandler) channel.pipeline().get("ssl");
if (sslHandler != null) {
class HandleNewPassiveSslRunner implements Runnable {
- public SslHandler sslHandler;
- public final Channel channel;
- private int retryTimes;
-
- HandleNewPassiveSslRunner(Channel channel, SslHandler sslHandler) {
- this.channel = channel;
- this.sslHandler = sslHandler;
- this.retryTimes = 3;
- }
+ private int retryTimes = 3;
private void retry() {
if (retryTimes > 0) {
- executorService.schedule(this, retryPeriod, TimeUnit.MILLISECONDS);
+ EXECUTOR_SERVICE.schedule(this, RETRY_PERIOD, TimeUnit.MILLISECONDS);
} else {
LOG.debug("channel closed {}", channel);
channel.disconnect();
}
}
- executorService.schedule(new HandleNewPassiveSslRunner(channel, sslHandler),
- retryPeriod, TimeUnit.MILLISECONDS);
+ EXECUTOR_SERVICE.schedule(new HandleNewPassiveSslRunner(),
+ RETRY_PERIOD, TimeUnit.MILLISECONDS);
} else {
- executorService.execute(() -> {
+ EXECUTOR_SERVICE.execute(() -> {
OvsdbClient client = getChannelClient(channel, ConnectionType.PASSIVE,
SocketConnectionType.NON_SSL);
handleNewPassiveConnection(client);
public static void channelClosed(final OvsdbClient client) {
LOG.info("Connection closed {}", client.getConnectionInfo().toString());
- connections.remove(client);
+ CONNECTIONS.remove(client);
if (client.isConnectionPublished()) {
- for (OvsdbConnectionListener listener : connectionListeners) {
+ for (OvsdbConnectionListener listener : CONNECTION_LISTENERS) {
listener.disconnected(client);
}
}
@Override
public Collection<OvsdbClient> getConnections() {
- return connections.keySet();
+ return CONNECTIONS.keySet();
}
@Override
@Override
public OvsdbClient getClient(Channel channel) {
- for (OvsdbClient client : connections.keySet()) {
- Channel ctx = connections.get(client);
+ for (Entry<OvsdbClient, Channel> entry : CONNECTIONS.entrySet()) {
+ OvsdbClient client = entry.getKey();
+ Channel ctx = entry.getValue();
if (ctx.equals(channel)) {
return client;
}
private static List<OvsdbClient> getPassiveClientsFromSameNode(OvsdbClient ovsdbClient) {
List<OvsdbClient> passiveClients = new ArrayList<>();
- for (OvsdbClient client : connections.keySet()) {
+ for (OvsdbClient client : CONNECTIONS.keySet()) {
if (!client.equals(ovsdbClient)
&& client.getConnectionInfo().getRemoteAddress()
.equals(ovsdbClient.getConnectionInfo().getRemoteAddress())
public static void notifyListenerForPassiveConnection(final OvsdbClient client) {
client.setConnectionPublished(true);
- for (final OvsdbConnectionListener listener : connectionListeners) {
- connectionNotifierService.submit(() -> {
+ for (final OvsdbConnectionListener listener : CONNECTION_LISTENERS) {
+ CONNECTION_NOTIFIER_SERVICE.execute(() -> {
LOG.trace("Connection {} notified to listener {}", client.getConnectionInfo(), listener);
listener.connected(client);
});
import com.google.common.util.concurrent.SettableFuture;
import java.util.List;
import java.util.Map;
+import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
public class StalePassiveConnectionService implements AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(StalePassiveConnectionService.class);
- private static Map<OvsdbClient, Map<OvsdbClient, SettableFuture>> pendingConnectionClients =
+ private static Map<OvsdbClient, Map<OvsdbClient, SettableFuture<List<String>>>> pendingConnectionClients =
new ConcurrentHashMap<>();
private final ScheduledExecutorService executorService;
*/
public void handleNewPassiveConnection(final OvsdbClient newOvsdbClient,
final List<OvsdbClient> clientsFromSameNode) {
- final Map<OvsdbClient, SettableFuture> clientFutureMap = new ConcurrentHashMap<>();
+ final Map<OvsdbClient, SettableFuture<List<String>>> clientFutureMap = new ConcurrentHashMap<>();
pendingConnectionClients.put(newOvsdbClient, clientFutureMap);
// scheduled task for ping response timeout. Connections that don't response to the
// ping or haven't disconnected after the timeout will be closed
final ScheduledFuture<?> echoTimeoutFuture =
executorService.schedule(() -> {
- for (OvsdbClient client : clientFutureMap.keySet()) {
- Future<?> clientFuture = clientFutureMap.get(client);
+ for (Entry<OvsdbClient, SettableFuture<List<String>>> entry : clientFutureMap.entrySet()) {
+ OvsdbClient client = entry.getKey();
+ Future<?> clientFuture = entry.getValue();
if (!clientFuture.isDone() && !clientFuture.isCancelled()) {
clientFuture.cancel(true);
}
// The future is removed from the 'clientFutureMap' when the onSuccess event for each future arrives
// If the map is empty we proceed with new connection process
for (final OvsdbClient client : clientsFromSameNode) {
- SettableFuture clientFuture = SettableFuture.create();
+ SettableFuture<List<String>> clientFuture = SettableFuture.create();
clientFutureMap.put(client, clientFuture);
Futures.addCallback(clientFuture,
createStaleConnectionFutureCallback(client, newOvsdbClient, clientFutureMap, echoTimeoutFuture));
* @param disconnectedClient the client just disconnected
*/
public void clientDisconnected(OvsdbClient disconnectedClient) {
- for (OvsdbClient pendingClient : pendingConnectionClients.keySet()) {
+ for (Entry<OvsdbClient, Map<OvsdbClient, SettableFuture<List<String>>>> entry :
+ pendingConnectionClients.entrySet()) {
+ OvsdbClient pendingClient = entry.getKey();
+
// set the future result for pending connections that wait for this client to be disconnected
if (pendingClient.getConnectionInfo().getRemoteAddress()
.equals(disconnectedClient.getConnectionInfo().getRemoteAddress())) {
- Map<OvsdbClient, SettableFuture> clientFutureMap = pendingConnectionClients.get(pendingClient);
- if (clientFutureMap.containsKey(disconnectedClient)) {
- clientFutureMap.get(disconnectedClient).set(null);
+ Map<OvsdbClient, SettableFuture<List<String>>> clientFutureMap = entry.getValue();
+ SettableFuture<List<String>> future = clientFutureMap.get(disconnectedClient);
+ if (future != null) {
+ future.set(null);
}
}
}
private FutureCallback<List<String>> createStaleConnectionFutureCallback(
final OvsdbClient cbForClient, final OvsdbClient newClient,
- final Map<OvsdbClient, SettableFuture> clientFutureMap, final ScheduledFuture<?> echoTimeoutFuture) {
+ final Map<OvsdbClient, SettableFuture<List<String>>> clientFutureMap,
+ final ScheduledFuture<?> echoTimeoutFuture) {
return new FutureCallback<List<String>>() {
@Override
public void onSuccess(List<String> result) {
import com.google.common.util.concurrent.SettableFuture;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import io.netty.channel.Channel;
-
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
-
import org.opendaylight.ovsdb.lib.error.UnexpectedResultException;
import org.opendaylight.ovsdb.lib.error.UnsupportedArgumentException;
import org.opendaylight.ovsdb.lib.message.OvsdbRPC;
private static int reaperInterval = 1000;
- public class CallContext {
+ public static class CallContext {
Method method;
JsonRpc10Request request;
SettableFuture<Object> future;
return Reflection.newProxy(klazz, (proxy, method, args) -> {
if (method.getName().equals(OvsdbRPC.REGISTER_CALLBACK_METHOD)) {
- if ((args == null) || args.length != 1 || !(args[0] instanceof OvsdbRPC.Callback)) {
+ if (args == null || args.length != 1 || !(args[0] instanceof OvsdbRPC.Callback)) {
return false;
}
requestCallbacks.put(context, (OvsdbRPC.Callback)args[0]);
if (request.getMethod().equals("echo")) {
JsonRpc10Response response = new JsonRpc10Response(request.getId());
response.setError(null);
- String jsonString = null;
try {
- jsonString = objectMapper.writeValueAsString(response);
+ String jsonString = objectMapper.writeValueAsString(response);
nettyChannel.writeAndFlush(jsonString);
} catch (JsonProcessingException e) {
- LOG.error("Exception while processing JSON string {}", jsonString, e);
+ LOG.error("Exception while processing JSON response {}", response, e);
}
return;
}
if (request.getMethod().equals("list_dbs")) {
JsonRpc10Response response = new JsonRpc10Response(request.getId());
response.setError(null);
- String jsonString = null;
try {
- jsonString = objectMapper.writeValueAsString(response);
+ String jsonString = objectMapper.writeValueAsString(response);
nettyChannel.writeAndFlush(jsonString);
} catch (JsonProcessingException e) {
- LOG.error("Exception while processing JSON string {}", jsonString, e);
+ LOG.error("Exception while processing JSON response {}", response, e);
}
return;
}
* @see <a href="http://tools.ietf.org/html/rfc7047#section-3.1">RFC7047 Section 3.1</a>
*/
public class Version implements Comparable<Version> {
-
- int major;
- int minor;
- int patch;
-
private static final String FORMAT = "(\\d+)\\.(\\d+)\\.(\\d+)";
private static final Pattern PATTERN = Pattern.compile(Version.FORMAT);
+ private int major;
+ private int minor;
+ private int patch;
+
public Version(int major, int minor, int patch) {
this.major = major;
this.minor = minor;
if (!matcher.find()) {
throw new IllegalArgumentException("<" + version + "> does not match format " + Version.FORMAT);
}
- int major = Integer.valueOf(matcher.group(1));
- int minor = Integer.valueOf(matcher.group(2));
- int patch = Integer.valueOf(matcher.group(3));
+ int major = Integer.parseInt(matcher.group(1));
+ int minor = Integer.parseInt(matcher.group(2));
+ int patch = Integer.parseInt(matcher.group(3));
return new Version(major, minor, patch);
}
+ @Override
public String toString() {
return "" + major + "." + minor + "." + patch;
}
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.util.Map;
+import java.util.Map.Entry;
import org.opendaylight.ovsdb.lib.notation.OvsdbMap;
public class OvsdbMapSerializer extends JsonSerializer<OvsdbMap<?,?>> {
generator.writeString("map");
generator.writeStartArray();
Map<?,?> javaMap = map.delegate();
- for (Object set : javaMap.keySet()) {
+ for (Entry<?, ?> entry : javaMap.entrySet()) {
+ Object set = entry.getKey();
generator.writeStartArray();
generator.writeObject(set);
- generator.writeObject(javaMap.get(set));
+ generator.writeObject(entry.getValue());
generator.writeEndArray();
}
generator.writeEndArray();
generator.writeEndArray();
}
-}
\ No newline at end of file
+}
public class OvsdbTypesIdResolver extends TypeIdResolverBase {
- private JavaType baseType;
-
@Override
public void init(JavaType bt) {
- this.baseType = bt;
}
@Override
public JsonTypeInfo.Id getMechanism() {
throw new UnsupportedOperationException("not yet done");
}
-}
\ No newline at end of file
+}
*/
package org.opendaylight.ovsdb.lib.operations;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.ArrayList;
import java.util.List;
import org.opendaylight.ovsdb.lib.notation.Condition;
super(schema, MUTATE);
}
+ @SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT") // validate call below
public <T extends TableSchema<T>, D> Mutate<E> addMutation(ColumnSchema<T, D> columnSchema,
Mutator mutator, D value) {
columnSchema.validate(value);
public void setWhere(List<Condition> where) {
this.where = where;
}
-}
\ No newline at end of file
+}
import org.opendaylight.ovsdb.lib.schema.typed.TypedBaseTable;
public class Operations {
- public static Operations op = new Operations();
+ @SuppressWarnings("checkstyle:ConstantName")
+ public static final Operations op = new Operations();
public <E extends TableSchema<E>> Insert<E> insert(TableSchema<E> schema) {
return new Insert<>(schema);
package org.opendaylight.ovsdb.lib.operations;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
this(typedTable.getSchema(), typedTable.getRow());
}
+ @SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT") // validate call below
public <T extends TableSchema<T>, D> Update<E> set(ColumnSchema<T, D> columnSchema, D value) {
columnSchema.validate(value);
Object untypedValue = columnSchema.getNormalizeData(value);
package org.opendaylight.ovsdb.lib.schema.typed;
+import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.reflect.Reflection;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
+import java.util.Locale;
import java.util.Map;
import org.opendaylight.ovsdb.lib.error.ColumnSchemaNotFoundException;
import org.opendaylight.ovsdb.lib.error.SchemaVersionMismatchException;
*/
int index = GET_STARTS_WITH.length();
if (isGetData(method) || isSetData(method)) {
- return method.getName().substring(index, method.getName().length()).toLowerCase();
+ return method.getName().substring(index, method.getName().length()).toLowerCase(Locale.ROOT);
} else if (isGetColumn(method)) {
return method.getName().substring(index, method.getName().indexOf(GETCOLUMN_ENDS_WITH,
- index)).toLowerCase();
+ index)).toLowerCase(Locale.ROOT);
}
return null;
}
private static void checkVersion(Version schemaVersion, Version fromVersion, Version untilVersion) {
- if ((!fromVersion.equals(Version.NULL) && schemaVersion.compareTo(fromVersion) < 0) || (!untilVersion.equals(
- Version.NULL) && schemaVersion.compareTo(untilVersion) > 0)) {
+ if (!fromVersion.equals(Version.NULL) && schemaVersion.compareTo(fromVersion) < 0 || !untilVersion.equals(
+ Version.NULL) && schemaVersion.compareTo(untilVersion) > 0) {
throw new SchemaVersionMismatchException(schemaVersion, fromVersion, untilVersion);
}
}
}
private Boolean isEqualsMethod(Method method, Object[] args) {
- return (args != null
+ return args != null
&& args.length == 1
&& method.getName().equals("equals")
- && Object.class.equals(method.getParameterTypes()[0]));
+ && Object.class.equals(method.getParameterTypes()[0]);
}
private Boolean isToStringMethod(Method method, Object[] args) {
}
@Override
+ @SuppressFBWarnings({"EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS", "EQ_UNUSUAL"})
public boolean equals(Object obj) {
- if (obj == null) {
+ if (!(obj instanceof TypedBaseTable)) {
return false;
}
TypedBaseTable<?> typedRowObj = (TypedBaseTable<?>)obj;
- if (row == null && typedRowObj.getRow() == null) {
- return true;
- }
- if (row.equals(typedRowObj.getRow())) {
- return true;
- }
- return false;
+ return Objects.equal(row, typedRowObj.getRow());
}
@Override public int hashCode() {
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
-@PrepareForTest({TyperUtils.class, TransactUtils.class})
+@PrepareForTest({TyperUtils.class, TransactUtils.class, Operations.class})
public class OpenVSwitchBridgeAddCommandTest {
private OpenVSwitchBridgeAddCommand ovsBridgeAddCommand;
doNothing().when(ovs).setBridges(any(Set.class));
Mutate<GenericTableSchema> mutate = mock(Mutate.class);
- Operations op = (Operations) setField("op");
+ Operations op = OvsdbNodeUpdateCommandTest.setOpField();
when(op.mutate(any(OpenVSwitch.class))).thenReturn(mutate);
Column<GenericTableSchema, Set<UUID>> column = mock(Column.class);
when(ovs.getBridgesColumn()).thenReturn(column);
mock(InstanceIdentifierCodec.class));
verify(transaction).add(any(Operation.class));
}
-
- private Object setField(String fieldName) throws Exception {
- Field field = Operations.class.getDeclaredField(fieldName);
- field.setAccessible(true);
- field.set(field.get(Operations.class), mock(Operations.class));
- return field.get(Operations.class);
- }
}
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
-@PrepareForTest({TransactUtils.class, TyperUtils.class, OvsdbNodeUpdateCommand.class, InstanceIdentifier.class})
+@PrepareForTest({TransactUtils.class, TyperUtils.class, OvsdbNodeUpdateCommand.class, InstanceIdentifier.class,
+ Operations.class})
public class OvsdbNodeUpdateCommandTest {
private static final String EXTERNAL_ID_KEY = "external id key";
doNothing().when(ovs).setExternalIds(any(ImmutableMap.class));
Mutate<GenericTableSchema> mutate = mock(Mutate.class);
- Operations op = (Operations) setField("op");
+ Operations op = setOpField();
Column<GenericTableSchema, Map<String, String>> column = mock(Column.class);
when(ovs.getExternalIdsColumn()).thenReturn(column);
when(column.getSchema()).thenReturn(mock(ColumnSchema.class));
verify(transaction, times(2)).add(any(Operation.class));
}
- private Object setField(String fieldName) throws Exception {
- Field field = Operations.class.getDeclaredField(fieldName);
- field.setAccessible(true);
- field.set(field.get(Operations.class), mock(Operations.class));
- return field.get(Operations.class);
+ static Operations setOpField() throws Exception {
+ Field opField = PowerMockito.field(Operations.class, "op");
+ Operations mockOp = mock(Operations.class);
+ opField.set(Operations.class, mockOp);
+ return mockOp;
}
}
import static org.mockito.Mockito.when;
import com.google.common.base.Optional;
-import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
-@PrepareForTest({InstanceIdentifier.class, ProtocolUpdateCommand.class, TyperUtils.class})
+@PrepareForTest({InstanceIdentifier.class, ProtocolUpdateCommand.class, TyperUtils.class, Operations.class})
public class ProtocolUpdateCommandTest {
private static final String BRIDGE_NAME_COLUMN = null;
- private Map<InstanceIdentifier<ProtocolEntry>, ProtocolEntry> protocols = new HashMap<>();
- private ProtocolUpdateCommand protocolUpdateCommand = new ProtocolUpdateCommand();
+ private final Map<InstanceIdentifier<ProtocolEntry>, ProtocolEntry> protocols = new HashMap<>();
+ private final ProtocolUpdateCommand protocolUpdateCommand = new ProtocolUpdateCommand();
@Mock private ProtocolEntry protocolEntry;
@SuppressWarnings("unchecked")
doNothing().when(bridge).setName(anyString());
doNothing().when(bridge).setProtocols(any(Set.class));
- Operations op = (Operations) setField("op");
+ Operations op = OvsdbNodeUpdateCommandTest.setOpField();
Mutate<GenericTableSchema> mutate = mock(Mutate.class);
when(op.mutate(any(Bridge.class))).thenReturn(mutate);
Column<GenericTableSchema, Set<String>> column = mock(Column.class);
// TODO What are we trying to verify here?
// verify(transaction).add(any(Operation.class));
}
-
- private Object setField(String fieldName) throws Exception {
- Field field = Operations.class.getDeclaredField(fieldName);
- field.setAccessible(true);
- field.set(field.get(Operations.class), mock(Operations.class));
- return field.get(Operations.class);
- }
}
import static org.mockito.Mockito.when;
import com.google.common.base.Optional;
-import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ TerminationPointUpdateCommand.class, TransactUtils.class, TyperUtils.class, VlanMode.class,
- TerminationPointCreateCommand.class, InstanceIdentifier.class })
+ TerminationPointCreateCommand.class, InstanceIdentifier.class, Operations.class })
public class TerminationPointUpdateCommandTest {
private static final String TERMINATION_POINT_NAME = "termination point name";
when(TyperUtils.getTypedRowWrapper(any(DatabaseSchema.class), eq(Interface.class))).thenReturn(extraInterface);
doNothing().when(extraInterface).setName(anyString());
- Operations op = (Operations) setField("op");
+ Operations op = OvsdbNodeUpdateCommandTest.setOpField();
Update update = mock(Update.class);
when(op.update(any(Interface.class))).thenReturn(update);
mock(InstanceIdentifierCodec.class));
verify(transaction, times(1)).add(any(Operation.class));
}
-
- private Object setField(String fieldName) throws Exception {
- Field field = Operations.class.getDeclaredField(fieldName);
- field.setAccessible(true);
- field.set(field.get(Operations.class), mock(Operations.class));
- return field.get(Operations.class);
- }
}