public interface DataTreeChangeListenerRegistrationHolder {
/**
- * @return the DataTreeChangeListenerRegistration
+ * Returns the DataTreeChangeListenerRegistration.
*/
ListenerRegistration<DataTreeChangeListener> getDataTreeChangeListenerRegistration();
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-/**
- *
- */
public interface FlowCommitWrapper {
/**
- * Starts and commits data change transaction which
- * modifies provided flow path with supplied body.
- *
- * @param flowPath
- * @param flowBody
- * @return transaction commit
- *
+ * Starts and commits data change transaction which modifies provided flow path with supplied body.
+ *
+ * @param flowPath the flow path
+ * @param flowBody the flow body
+ * @return transaction commit
*/
- CheckedFuture<Void, TransactionCommitFailedException> writeFlowToConfig(InstanceIdentifier<Flow> flowPath, Flow flowBody);
+ CheckedFuture<Void, TransactionCommitFailedException> writeFlowToConfig(
+ InstanceIdentifier<Flow> flowPath, Flow flowBody);
}
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-/**
- *
- */
public class FlowCommitWrapperImpl implements FlowCommitWrapper {
- private DataBroker dataBrokerService;
+ private final DataBroker dataBrokerService;
- /**
- * @param dataBrokerService
- */
public FlowCommitWrapperImpl(DataBroker dataBrokerService) {
this.dataBrokerService = dataBrokerService;
}
import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.EthernetMatch;
import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.EthernetMatchBuilder;
-public class FlowUtils {
+public final class FlowUtils {
private FlowUtils() {
//prohibite to instantiate util class
}
/**
- * @param tableId
- * @param priority
- * @param srcMac
- * @param dstMac
- * @param dstPort
- * @return {@link FlowBuilder} forwarding all packets to controller port
+ * Returns a {@link FlowBuilder} forwarding all packets to controller port.
*/
public static FlowBuilder createDirectMacToMacFlow(final Short tableId, final int priority, final MacAddress srcMac,
final MacAddress dstMac, final NodeConnectorRef dstPort) {
}
/**
- * @param tableId
- * @param priority
- * @param flowId
- * @return {@link FlowBuilder} forwarding all packets to controller port
+ * Returns a{@link FlowBuilder} forwarding all packets to controller port.
*/
- public static FlowBuilder createFwdAllToControllerFlow(final Short tableId, final int priority, final FlowId flowId) {
- FlowBuilder allToCtrlFlow = new FlowBuilder().setTableId(tableId).setFlowName("allPacketsToCtrl").setId(flowId)
- .setKey(new FlowKey(flowId));
-
- MatchBuilder matchBuilder = new MatchBuilder();
-
+ public static FlowBuilder createFwdAllToControllerFlow(final Short tableId, final int priority,
+ final FlowId flowId) {
// Create output action -> send to controller
OutputActionBuilder output = new OutputActionBuilder();
output.setMaxLength(Integer.valueOf(0xffff));
ab.setOrder(0);
ab.setKey(new ActionKey(0));
- List<Action> actionList = new ArrayList<Action>();
+ List<Action> actionList = new ArrayList<>();
actionList.add(ab.build());
// Create an Apply Action
// Put our Instruction in a list of Instructions
InstructionsBuilder isb = new InstructionsBuilder();
- List<Instruction> instructions = new ArrayList<Instruction>();
+ List<Instruction> instructions = new ArrayList<>();
instructions.add(ib.build());
isb.setInstruction(instructions);
+ MatchBuilder matchBuilder = new MatchBuilder();
+ FlowBuilder allToCtrlFlow = new FlowBuilder().setTableId(tableId).setFlowName("allPacketsToCtrl").setId(flowId)
+ .setKey(new FlowKey(flowId));
allToCtrlFlow
.setMatch(matchBuilder.build())
.setInstructions(isb.build())
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-public class InstanceIdentifierUtils {
+public final class InstanceIdentifierUtils {
private InstanceIdentifierUtils() {
//hiding constructor for util class
}
/**
- * Creates an Instance Identifier (path) for node with specified id
+ * Creates an Instance Identifier (path) for node with specified id.
*
- * @param nodeId
- * @return
+ * @param nodeId the NodeId
*/
- public static final InstanceIdentifier<Node> createNodePath(final NodeId nodeId) {
+ public static InstanceIdentifier<Node> createNodePath(final NodeId nodeId) {
return InstanceIdentifier.builder(Nodes.class)
.child(Node.class, new NodeKey(nodeId))
.build();
* Shorten's node child path to node path.
*
* @param nodeChild child of node, from which we want node path.
- * @return
*/
- public static final InstanceIdentifier<Node> getNodePath(final InstanceIdentifier<?> nodeChild) {
+ public static InstanceIdentifier<Node> getNodePath(final InstanceIdentifier<?> nodeChild) {
return nodeChild.firstIdentifierOf(Node.class);
}
/**
- * Creates a table path by appending table specific location to node path
+ * Creates a table path by appending table specific location to node path.
*
- * @param nodePath
- * @param tableKey
- * @return
+ * @param nodePath the node path
+ * @param tableKey the table yey
*/
- public static final InstanceIdentifier<Table> createTablePath(final InstanceIdentifier<Node> nodePath,final TableKey tableKey) {
+ public static InstanceIdentifier<Table> createTablePath(final InstanceIdentifier<Node> nodePath,
+ final TableKey tableKey) {
return nodePath.augmentation(FlowCapableNode.class).child(Table.class, tableKey);
}
* Creates a path for particular flow, by appending flow-specific information
* to table path.
*
- * @param tablePath
- * @param flowKey
+ * @param tablePath the table path
+ * @param flowKey the flow key
* @return path to flow
*/
- public static InstanceIdentifier<Flow> createFlowPath(final InstanceIdentifier<Table> tablePath, final FlowKey flowKey) {
+ public static InstanceIdentifier<Flow> createFlowPath(final InstanceIdentifier<Table> tablePath,
+ final FlowKey flowKey) {
return tablePath.child(Flow.class, flowKey);
}
/**
* Extract table id from table path.
*
- * @param tablePath
- * @return
+ * @param tablePath the table path
*/
public static Short getTableId(final InstanceIdentifier<Table> tablePath) {
return tablePath.firstKeyOf(Table.class, TableKey.class).getId();
return nodeConnectorPath.firstKeyOf(NodeConnector.class, NodeConnectorKey.class);
}
- public static final InstanceIdentifier<NodeConnector> createNodeConnectorPath(final InstanceIdentifier<Node> nodeKey,final NodeConnectorKey nodeConnectorKey) {
+ public static InstanceIdentifier<NodeConnector> createNodeConnectorPath(final InstanceIdentifier<Node> nodeKey,
+ final NodeConnectorKey nodeConnectorKey) {
return nodeKey.child(NodeConnector.class,nodeConnectorKey);
}
}
import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketProcessingService;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-/**
- *
- */
public interface LearningSwitchHandler {
/**
- * @param tablePath
+ * Invoked when a switch appears.
+ *
+ * @param tablePath the table path
*/
void onSwitchAppeared(InstanceIdentifier<Table> tablePath);
/**
+ * Sets the PacketProcessingService.
+ *
* @param packetProcessingService the packetProcessingService to set
*/
- void setPacketProcessingService(PacketProcessingService packetProcessingService);
+ void setPacketProcessingService(PacketProcessingService packetProcessingService);
/**
+ * Sets the data store accessor.
+ *
* @param dataStoreAccessor the dataStoreAccessor to set
*/
- void setDataStoreAccessor(FlowCommitWrapper dataStoreAccessor);
+ void setDataStoreAccessor(FlowCommitWrapper dataStoreAccessor);
/**
+ * Sets the DataTreeChangeListener registration publisher.
+ *
* @param registrationPublisher the registrationPublisher to set
*/
- void setRegistrationPublisher(DataTreeChangeListenerRegistrationHolder registrationPublisher);
+ void setRegistrationPublisher(DataTreeChangeListenerRegistrationHolder registrationPublisher);
}
private FlowCommitWrapper dataStoreAccessor;
private PacketProcessingService packetProcessingService;
- private boolean iAmLearning = false;
+ private boolean isLearning = false;
private NodeId nodeId;
- private AtomicLong flowIdInc = new AtomicLong();
- private AtomicLong flowCookieInc = new AtomicLong(0x2a00000000000000L);
+ private final AtomicLong flowIdInc = new AtomicLong();
+ private final AtomicLong flowCookieInc = new AtomicLong(0x2a00000000000000L);
private InstanceIdentifier<Node> nodePath;
private InstanceIdentifier<Table> tablePath;
@Override
public synchronized void onSwitchAppeared(InstanceIdentifier<Table> appearedTablePath) {
- if (iAmLearning) {
+ if (isLearning) {
LOG.debug("already learning a node, skipping {}", nodeId.getValue());
return;
}
// disable listening - simple learning handles only one node (switch)
if (registrationPublisher != null) {
- try {
- LOG.debug("closing dataTreeChangeListenerRegistration");
- registrationPublisher.getDataTreeChangeListenerRegistration().close();
- } catch (Exception e) {
- LOG.warn("closing registration upon flowCapable node update listener failed: {}", e.getMessage());
- LOG.debug("closing registration upon flowCapable node update listener failed.. ", e);
- }
+ LOG.debug("closing dataTreeChangeListenerRegistration");
+ registrationPublisher.getDataTreeChangeListenerRegistration().close();
}
- iAmLearning = true;
+ isLearning = true;
tablePath = appearedTablePath;
nodePath = tablePath.firstIdentifierOf(Node.class);
@Override
public void onPacketReceived(PacketReceived notification) {
- if (!iAmLearning) {
+ if (!isLearning) {
// ignoring packets - this should not happen
return;
}
}
- /**
- * @param srcMac
- * @param dstMac
- * @param destNodeConnector
- */
private void addBridgeFlow(MacAddress srcMac, MacAddress dstMac, NodeConnectorRef destNodeConnector) {
synchronized (coveredMacPaths) {
String macPath = srcMac.toString() + dstMac.toString();
private void flood(byte[] payload, NodeConnectorRef ingress) {
NodeConnectorKey nodeConnectorKey = new NodeConnectorKey(nodeConnectorId("0xfffffffb"));
- InstanceIdentifier<?> nodeConnectorPath = InstanceIdentifierUtils.createNodeConnectorPath(nodePath, nodeConnectorKey);
+ InstanceIdentifier<?> nodeConnectorPath = InstanceIdentifierUtils.createNodeConnectorPath(
+ nodePath, nodeConnectorKey);
NodeConnectorRef egressConnectorRef = new NodeConnectorRef(nodeConnectorPath);
sendPacketOut(payload, ingress, egressConnectorRef);
import org.opendaylight.controller.sal.binding.api.NotificationService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketProcessingService;
-/**
- *
- */
public interface LearningSwitchManager {
/**
- * stop manager
+ * Stops this manager.
*/
void stop();
/**
- * start manager
+ * Starts this manager.
*/
void start();
/**
* Set's Data Broker dependency.
+ *
* <p>
- * Data Broker is used to access overal operational and configuration
- * tree.
+ * Data Broker is used to access overall operational and configuration tree.
+ *
* <p>
* In simple Learning Switch handler, data broker is used to listen
* for changes in Openflow tables and to configure flows which will
* be provisioned down to the Openflow switch.
+ *
* <p>
* inject {@link DataBroker}
- *
- * @param data
*/
void setDataBroker(DataBroker data);
/**
* Set's Packet Processing dependency.
+ *
* <p>
- * Packet Processing service is used to send packet Out on Openflow
- * switch.
+ * Packet Processing service is used to send packet Out on Openflow switch.
+ *
* <p>
* inject {@link PacketProcessingService}
- *
- * @param packetProcessingService
*/
void setPacketProcessingService(
PacketProcessingService packetProcessingService);
/**
* Set's Notification service dependency.
+ *
* <p>
- * Notification service is used to register for listening
- * packet-in notifications.
+ * Notification service is used to register for listening packet-in notifications.
+ *
* <p>
* inject {@link NotificationService}
- *
- * @param notificationService
*/
void setNotificationService(NotificationService notificationService);
}
import org.slf4j.LoggerFactory;
/**
- * Listens to packetIn notification and
+ * Listens to packetIn notification.
* <ul>
* <li>in HUB mode simply floods all switch ports (except ingress port)</li>
* <li>in LSWITCH mode collects source MAC address of packetIn and bind it with ingress port.
* corresponding MACs)</li>
* </ul>
*/
-public class LearningSwitchManagerSimpleImpl implements DataTreeChangeListenerRegistrationHolder, LearningSwitchManager {
+public class LearningSwitchManagerSimpleImpl
+ implements DataTreeChangeListenerRegistrationHolder, LearningSwitchManager {
private static final Logger LOG = LoggerFactory.getLogger(LearningSwitchManagerSimpleImpl.class);
private NotificationService notificationService;
private ListenerRegistration<DataTreeChangeListener> dataTreeChangeListenerRegistration;
/**
+ * Sets the NotificationService.
+ *
* @param notificationService the notificationService to set
*/
@Override
}
/**
+ * Sets the PacketProcessingService.
+ *
* @param packetProcessingService the packetProcessingService to set
*/
@Override
}
/**
- * @param data the data to set
+ * Sets the DataBroker.
*/
@Override
- public void setDataBroker(DataBroker data) {
- this.data = data;
+ public void setDataBroker(DataBroker broker) {
+ this.data = broker;
}
/**
- * starting learning switch
+ * Starts learning switch.
*/
@Override
public void start() {
.child(Node.class)
.augmentation(FlowCapableNode.class)
.child(Table.class);
- final DataTreeIdentifier<Table> dataTreeIdentifier = new DataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, instanceIdentifier);
+ final DataTreeIdentifier<Table> dataTreeIdentifier =
+ new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, instanceIdentifier);
dataTreeChangeListenerRegistration = data.registerDataTreeChangeListener(dataTreeIdentifier, wakeupListener);
LOG.debug("start() <--");
}
/**
- * stopping learning switch
+ * Stops the learning switch.
*/
@Override
public void stop() {
LOG.debug("stop() -->");
//TODO: remove flow (created in #start())
- try {
- packetInRegistration.close();
- } catch (Exception e) {
- LOG.warn("closing packetInRegistration failed: {}", e.getMessage());
- LOG.debug("closing packetInRegistration failed..", e);
- }
- try {
- dataTreeChangeListenerRegistration.close();
- } catch (Exception e) {
- LOG.warn("failed to close dataTreeChangeListenerRegistration: {}", e.getMessage());
- LOG.debug("failed to close dataTreeChangeListenerRegistration..", e);
- }
+
+ packetInRegistration.close();
+
+ dataTreeChangeListenerRegistration.close();
+
LOG.debug("stop() <--");
}
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-/**
- *
- */
public abstract class PacketUtils {
/**
- * size of MAC address in octets (6*8 = 48 bits)
+ * size of MAC address in octets (6*8 = 48 bits).
*/
private static final int MAC_ADDRESS_SIZE = 6;
/**
- * start position of destination MAC address in array
+ * start position of destination MAC address in array.
*/
private static final int DST_MAC_START_POSITION = 0;
/**
- * end position of destination MAC address in array
+ * end position of destination MAC address in array.
*/
private static final int DST_MAC_END_POSITION = 6;
/**
- * start position of source MAC address in array
+ * start position of source MAC address in array.
*/
private static final int SRC_MAC_START_POSITION = 6;
/**
- * end position of source MAC address in array
+ * end position of source MAC address in array.
*/
private static final int SRC_MAC_END_POSITION = 12;
/**
- * start position of ethernet type in array
+ * start position of ethernet type in array.
*/
private static final int ETHER_TYPE_START_POSITION = 12;
/**
- * end position of ethernet type in array
+ * end position of ethernet type in array.
*/
private static final int ETHER_TYPE_END_POSITION = 14;
}
/**
- * @param payload
+ * Extracts the destination MAC address.
+ *
+ * @param payload the payload bytes
* @return destination MAC address
*/
public static byte[] extractDstMac(final byte[] payload) {
}
/**
- * @param payload
+ * Extracts the source MAC address.
+ *
+ * @param payload the payload bytes
* @return source MAC address
*/
public static byte[] extractSrcMac(final byte[] payload) {
}
/**
- * @param payload
+ * Extracts the ethernet type.
+ *
+ * @param payload the payload bytes
* @return source MAC address
*/
public static byte[] extractEtherType(final byte[] payload) {
}
/**
- * @param rawMac
- * @return {@link MacAddress} wrapping string value, baked upon binary MAC
- * address
+ * Converts a raw MAC bytes to a MacAddress.
+ *
+ * @param rawMac the raw bytes
+ * @return {@link MacAddress} wrapping string value, baked upon binary MAC address
*/
public static MacAddress rawMacToMac(final byte[] rawMac) {
MacAddress mac = null;
}
/**
- * @param nodeInstId
- * @param nodeKey
- * @param port
- * @return port wrapped into {@link NodeConnectorRef}
+ * Returns the port wrapped into {@link NodeConnectorRef}.
*/
- public static NodeConnectorRef createNodeConnRef(final InstanceIdentifier<Node> nodeInstId, final NodeKey nodeKey, final String port) {
- StringBuilder sBuild = new StringBuilder(nodeKey.getId().getValue()).append(':').append(port);
- NodeConnectorKey nConKey = new NodeConnectorKey(new NodeConnectorId(sBuild.toString()));
- InstanceIdentifier<NodeConnector> portPath = nodeInstId.child(NodeConnector.class, nConKey);
+ public static NodeConnectorRef createNodeConnRef(final InstanceIdentifier<Node> nodeInstId, final NodeKey nodeKey,
+ final String port) {
+ StringBuilder builder = new StringBuilder(nodeKey.getId().getValue()).append(':').append(port);
+ NodeConnectorKey connKey = new NodeConnectorKey(new NodeConnectorId(builder.toString()));
+ InstanceIdentifier<NodeConnector> portPath = nodeInstId.child(NodeConnector.class, connKey);
return new NodeConnectorRef(portPath);
}
}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-/**
- *
- */
public class WakeupOnNode implements DataTreeChangeListener<Table> {
private static final Logger LOG = LoggerFactory.getLogger(WakeupOnNode.class);
LOG.trace("table: {}", table);
if (requiredTableId.equals(tableSure.getId())) {
- InstanceIdentifier<Table> tablePath = (InstanceIdentifier<Table>) modification.getRootPath().getRootIdentifier();
+ InstanceIdentifier<Table> tablePath =
+ modification.getRootPath().getRootIdentifier();
learningSwitchHandler.onSwitchAppeared(tablePath);
}
}
}
/**
+ * Sets the LearningSwitchHandler.
+ *
* @param learningSwitchHandler the learningSwitchHandler to set
*/
public void setLearningSwitchHandler(
LearningSwitchHandler learningSwitchHandler) {
this.learningSwitchHandler = learningSwitchHandler;
}
-
}
import org.slf4j.LoggerFactory;
/**
- * Listens to packetIn notification and
+ * Listens to packetIn notification.
* <ul>
* <li>in HUB mode simply floods all switch ports (except ingress port)</li>
* <li>in LSWITCH mode collects source MAC address of packetIn and bind it with ingress port.
private ListenerRegistration<DataTreeChangeListener> dataTreeChangeListenerRegistration;
/**
+ * Sets the NotificationService.
+ *
* @param notificationService the notificationService to set
*/
@Override
}
/**
+ * Sets the PacketProcessingService.
+ *
* @param packetProcessingService the packetProcessingService to set
*/
@Override
}
/**
- * @param data the data to set
+ * Sets the DataBroker.
+ *
+ * @param broker the data to set
*/
@Override
- public void setDataBroker(DataBroker data) {
- this.data = data;
+ public void setDataBroker(DataBroker broker) {
+ this.data = broker;
}
/**
- * starting learning switch
+ * Starts learning switch.
*/
@Override
public void start() {
.child(Node.class)
.augmentation(FlowCapableNode.class)
.child(Table.class);
- final DataTreeIdentifier<Table> dataTreeIdentifier = new DataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, instanceIdentifier);
+ final DataTreeIdentifier<Table> dataTreeIdentifier =
+ new DataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, instanceIdentifier);
dataTreeChangeListenerRegistration = data.registerDataTreeChangeListener(dataTreeIdentifier, wakeupListener);
LOG.debug("start() <--");
}
/**
- * stopping learning switch
+ * Stops learning switch.
*/
@Override
public void stop() {
LOG.debug("stop() -->");
//TODO: remove flow (created in #start())
- try {
- packetInRegistration.close();
- } catch (Exception e) {
- LOG.warn("Error unregistering packet in listener: {}", e.getMessage());
- LOG.debug("Error unregistering packet in listener.. ", e);
- }
- try {
- dataTreeChangeListenerRegistration.close();
- } catch (Exception e) {
- LOG.warn("Error unregistering data change listener: {}", e.getMessage());
- LOG.debug("Error unregistering data change listener.. ", e);
- }
+
+ packetInRegistration.close();
+
+ dataTreeChangeListenerRegistration.close();
LOG.debug("stop() <--");
}
this.packetProcessingService = packetProcessingService;
}
- /**
- * @param packetInDispatcher
- */
public void setPacketInDispatcher(PacketInDispatcherImpl packetInDispatcher) {
this.packetInDispatcher = packetInDispatcher;
}
public class PacketInDispatcherImpl implements PacketProcessingListener {
- private Map<InstanceIdentifier<Node>, PacketProcessingListener> handlerMapping;
+ private final Map<InstanceIdentifier<Node>, PacketProcessingListener> handlerMapping;
/**
- * default constructor
+ * default constructor.
*/
public PacketInDispatcherImpl() {
handlerMapping = new HashMap<>();
@Override
public void onPacketReceived(PacketReceived notification) {
// find corresponding handler
- /**
+ /*
* Notification contains reference to ingress port
* in a form of path in inventory: /nodes/node/node-connector
*
}
}
- /**
- * @return the handlerMapping
- */
public Map<InstanceIdentifier<Node>, PacketProcessingListener> getHandlerMapping() {
return handlerMapping;
}
import org.slf4j.LoggerFactory;
/**
- * Sample bundles activator
+ * Sample bundles activator.
*/
-public class Activator extends AbstractBrokerAwareActivator implements BindingAwareConsumer, ClusteredDataTreeChangeListener<FlowCapableNode>, AutoCloseable {
+public class Activator extends AbstractBrokerAwareActivator implements BindingAwareConsumer,
+ ClusteredDataTreeChangeListener<FlowCapableNode>, AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(Activator.class);
LOG.debug("inSessionInitialized() passing");
dataBroker = consumerContext.getSALService(DataBroker.class);
- final InstanceIdentifier<FlowCapableNode> path = InstanceIdentifier.create(Nodes.class).child(Node.class).
- augmentation(FlowCapableNode.class);
- final DataTreeIdentifier<FlowCapableNode> identifier = new DataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, path);
+ final InstanceIdentifier<FlowCapableNode> path = InstanceIdentifier.create(Nodes.class).child(Node.class)
+ .augmentation(FlowCapableNode.class);
+ final DataTreeIdentifier<FlowCapableNode> identifier =
+ new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, path);
dataBroker.registerDataTreeChangeListener(identifier, Activator.this);
bundleService = consumerContext.getRpcService(SalBundleService.class);
public void onDataTreeChanged(@Nonnull Collection<DataTreeModification<FlowCapableNode>> modifications) {
for (DataTreeModification modification : modifications) {
if (modification.getRootNode().getModificationType() == ModificationType.WRITE) {
- LOG.info("Node connected: {}", modification.getRootPath().getRootIdentifier().firstIdentifierOf(Node.class));
+ LOG.info("Node connected: {}",
+ modification.getRootPath().getRootIdentifier().firstIdentifierOf(Node.class));
- final NodeRef nodeRef = new NodeRef(modification.getRootPath().getRootIdentifier().firstIdentifierOf(Node.class));
+ final NodeRef nodeRef =
+ new NodeRef(modification.getRootPath().getRootIdentifier().firstIdentifierOf(Node.class));
final ControlBundleInput openBundleInput = new ControlBundleInputBuilder()
.setNode(nodeRef)
.build();
makeCompletableFuture(bundleService.controlBundle(openBundleInput))
- .thenComposeAsync(voidRpcResult -> {
- LOG.debug("Open successful: {}, msg: {}", voidRpcResult.isSuccessful(), voidRpcResult.getErrors());
-
- final CompletableFuture<RpcResult<Void>> addFuture =
- makeCompletableFuture(bundleService.addBundleMessages(addBundleMessagesInput));
-
- return addFuture;
- }).thenComposeAsync(voidRpcResult -> {
- LOG.debug("AddBundleMessages successful: {}, msg: {}", voidRpcResult.isSuccessful(), voidRpcResult.getErrors());
-
- final CompletableFuture<RpcResult<Void>> controlCommitFuture =
- makeCompletableFuture(bundleService.controlBundle(commitBundleInput));
-
- return controlCommitFuture;
- }).thenAccept(voidRpcResult -> {
- LOG.debug("Commit successful: {}, msg: {}", voidRpcResult.isSuccessful(), voidRpcResult.getErrors());
- });
+ .thenComposeAsync(voidRpcResult -> {
+ LOG.debug("Open successful: {}, msg: {}", voidRpcResult.isSuccessful(),
+ voidRpcResult.getErrors());
+
+ final CompletableFuture<RpcResult<Void>> addFuture =
+ makeCompletableFuture(bundleService.addBundleMessages(addBundleMessagesInput));
+
+ return addFuture;
+ }).thenComposeAsync(voidRpcResult -> {
+ LOG.debug("AddBundleMessages successful: {}, msg: {}", voidRpcResult.isSuccessful(),
+ voidRpcResult.getErrors());
+
+ final CompletableFuture<RpcResult<Void>> controlCommitFuture =
+ makeCompletableFuture(bundleService.controlBundle(commitBundleInput));
+
+ return controlCommitFuture;
+ }).thenAccept(voidRpcResult -> {
+ LOG.debug("Commit successful: {}, msg: {}", voidRpcResult.isSuccessful(),
+ voidRpcResult.getErrors());
+ });
}
}
}
List<Message> messages = new ArrayList<>();
- messages.add(new MessageBuilder().setNode(nodeRef).setBundleInnerMessage(
- new BundleAddGroupCaseBuilder()
- .setAddGroupCaseData(new AddGroupCaseDataBuilder(createGroup(1l)).build()).build()).build());
+ messages.add(new MessageBuilder().setNode(nodeRef).setBundleInnerMessage(new BundleAddGroupCaseBuilder()
+ .setAddGroupCaseData(new AddGroupCaseDataBuilder(createGroup(1L)).build()).build()).build());
- messages.add(new MessageBuilder().setNode(nodeRef).setBundleInnerMessage(
- new BundleAddFlowCaseBuilder()
- .setAddFlowCaseData(new AddFlowCaseDataBuilder(createFlow("42", 1l, 1, (short) 1)).build()).build()).build());
+ messages.add(new MessageBuilder().setNode(nodeRef).setBundleInnerMessage(new BundleAddFlowCaseBuilder()
+ .setAddFlowCaseData(new AddFlowCaseDataBuilder(createFlow("42", 1L, 1, (short) 1)).build()).build())
+ .build());
- messages.add(new MessageBuilder().setNode(nodeRef).setBundleInnerMessage(
- new BundleAddFlowCaseBuilder()
- .setAddFlowCaseData(new AddFlowCaseDataBuilder(createFlow("43", 1l, 2, (short) 2)).build()).build()).build());
+ messages.add(new MessageBuilder().setNode(nodeRef).setBundleInnerMessage(new BundleAddFlowCaseBuilder()
+ .setAddFlowCaseData(new AddFlowCaseDataBuilder(createFlow("43", 1L, 2, (short) 2)).build()).build())
+ .build());
LOG.debug("createMessages() passing {}", messages);
MatchBuilder matchBuilder = new MatchBuilder();
matchBuilder.setEthernetMatch(new EthernetMatchBuilder()
.setEthernetType(new EthernetTypeBuilder()
- .setType(new EtherType(2048l)).build()).build());
+ .setType(new EtherType(2048L)).build()).build());
FlowBuilder flowBuilder = new FlowBuilder();
flowBuilder.setMatch(matchBuilder.build());
}
private static BucketsBuilder createBuckets() {
- List<Bucket> bucketList = new ArrayList<>();
List<Action> actionList = new ArrayList<>();
actionList.add(new ActionBuilder()
.build()).build());
BucketBuilder bucketBuilder = new BucketBuilder();
- bucketBuilder.setBucketId(new BucketId(12l));
+ bucketBuilder.setBucketId(new BucketId(12L));
bucketBuilder.setAction(actionList);
+ List<Bucket> bucketList = new ArrayList<>();
bucketList.add(bucketBuilder.build());
actionList = new ArrayList<>();
.build());
bucketBuilder = new BucketBuilder();
- bucketBuilder.setBucketId(new BucketId(13l));
+ bucketBuilder.setBucketId(new BucketId(13L));
bucketBuilder.setAction(actionList);
bucketList.add(bucketBuilder.build());
}
private static InstructionsBuilder createGroupInstructions(long groupId) {
- List<Action> actionList = new ArrayList<>();
ActionBuilder actionBuilder = new ActionBuilder();
GroupActionBuilder groupActionBuilder = new GroupActionBuilder();
actionBuilder.setAction(new GroupActionCaseBuilder().setGroupAction(groupActionBuilder.build()).build());
actionBuilder.setOrder(1);
actionBuilder.setKey(new ActionKey(0));
+ List<Action> actionList = new ArrayList<>();
actionList.add(actionBuilder.build());
ApplyActionsBuilder applyActionsBuilder = new ApplyActionsBuilder();
applyActionsBuilder.setAction(actionList);
InstructionBuilder instructionBuilder = new InstructionBuilder();
- instructionBuilder.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(applyActionsBuilder.build()).build());
+ instructionBuilder.setInstruction(new ApplyActionsCaseBuilder()
+ .setApplyActions(applyActionsBuilder.build()).build());
instructionBuilder.setOrder(0);
instructionBuilder.setKey(new InstructionKey(0));
SimpleDropFirewall service;
private SalFlowService flowService;
private SimpleDropFirewallCli cliAdapter;
-
-
+
@Override
protected void startImpl(BundleContext context) {
service = new SimpleDropFirewall();
-
+
cliAdapter.setService(service);
}
-
+
@Override
public void onSessionInitialized(ConsumerContext session) {
service.setContext(session);
}
/**
- * Form of input is:
- *
- * node name node-connector number source ip-address destinatinon ip-address
+ * Form of input is: node name node-connector number source ip-address destinatinon ip-address.
*
* @param cliInput
* Parsed input from CLI
- * @return
*/
public AddFlowInput createTcpFlow(final List<String> cliInput) {
AddFlowInputBuilder ret = new AddFlowInputBuilder();
List<Instruction> isntructions = Collections.singletonList(instructionBldr.build());
InstructionsBuilder instructionsBldr = new InstructionsBuilder();
- instructionsBldr.setInstruction(isntructions);
+ instructionsBldr.setInstruction(isntructions);
ret.setInstructions(instructionsBldr.build());
*/
package org.opendaylight.openflowjava.protocol.impl.clients;
-import java.net.InetAddress;
-import java.util.concurrent.Callable;
-
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.SettableFuture;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
+import java.net.InetAddress;
+import java.util.concurrent.Callable;
import org.slf4j.LoggerFactory;
/**
- * Callable client class, inspired by SimpleClient class
- * Simulating device/switch connected to controller
+ * Callable client class, inspired by SimpleClient class.
+ * Simulating device/switch connected to controller.
+ *
* @author Jozef Bacigal
- * Date: 4.3.2016.
*/
public class CallableClient implements Callable<Boolean>, OFClient {
@Override
+ @SuppressWarnings("checkstyle:IllegalCatch")
public Boolean call() throws Exception {
Preconditions.checkNotNull(bootstrap);
Preconditions.checkNotNull(workerGroup);
scenarioHandler.wait();
}
}
- } catch (Exception ex) {
+ } catch (RuntimeException ex) {
LOG.error(ex.getMessage(), ex);
return false;
}
package org.opendaylight.openflowjava.protocol.impl.clients;
/**
- * Uniting interface used for scenario support
- * @author michal.polkorab
+ * Uniting interface used for scenario support.
*
+ * @author michal.polkorab
*/
public interface ClientEvent {
/**
- * Common method for triggering events
+ * Common method for triggering events.
+ *
* @return true if event executed successfully
*/
boolean eventExecuted();
package org.opendaylight.openflowjava.protocol.impl.clients;
+import java.io.IOException;
+import java.security.KeyManagementException;
import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
import java.security.Security;
-
+import java.security.UnrecoverableKeyException;
+import java.security.cert.CertificateException;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
clientContext = SSLContext.getInstance(PROTOCOL);
clientContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
- } catch (Exception e) {
+ } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException
+ | UnrecoverableKeyException | KeyManagementException e) {
throw new Error(
"Failed to initialize the client-side SSLContext", e);
}
}
/**
- * @return client context
+ * Returns the client context.
*/
public static SSLContext getClientContext() {
return CLIENT_CONTEXT;
}
-}
\ No newline at end of file
+}
import java.io.InputStream;
/**
- * Class for storing keys
+ * Class for storing keys.
*
* @author michal.polkorab
*/
}
/**
- * InputStream instance of key
+ * InputStream instance of key.
*
* @return key as InputStream
*/
}
/**
- * @return certificate password as char[]
+ * Returns the certificate password as char[].
*/
public static char[] getCertificatePassword() {
return "opendaylight".toCharArray();
}
/**
- * @return KeyStore password as char[]
+ * Returns the KeyStore password as char[].
*/
public static char[] getKeyStorePassword() {
return "opendaylight".toCharArray();
}
-}
\ No newline at end of file
+}
import java.io.InputStream;
/**
- * Class for storing keys
+ * Class for storing keys.
*
* @author michal.polkorab
*/
}
/**
- * InputStream instance of key
+ * InputStream instance of key.
*
* @return key as InputStream
*/
}
/**
- * @return certificate password as char[]
+ * Returns the certificate password as char[].
*/
public static char[] getCertificatePassword() {
return "opendaylight".toCharArray();
}
/**
- * @return KeyStore password as char[]
+ * Returns the KeyStore password as char[].
*/
public static char[] getKeyStorePassword() {
return "opendaylight".toCharArray();
}
-}
\ No newline at end of file
+}
/**
- * <p>Java class for eventType.
+ * Java class for eventType.
*/
@XmlType(name = "eventType")
@XmlEnum
SEND_EVENT("sendEvent");
private final String value;
- EventType(String v) {
- value = v;
+ EventType(String val) {
+ value = val;
}
public String value() {
return value;
}
- public static EventType fromValue(String v) {
+ public static EventType fromValue(String val) {
for (EventType c: EventType.values()) {
- if (c.value.equals(v)) {
+ if (c.value.equals(val)) {
return c;
}
}
- throw new IllegalArgumentException(v);
+ throw new IllegalArgumentException(val);
}
}
*/
package org.opendaylight.openflowjava.protocol.impl.clients;
+import com.google.common.util.concurrent.SettableFuture;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.Future;
-
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutionException;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.util.concurrent.SettableFuture;
-
/**
- * Listening client for testing purposes
- * @author martin.uhlir
+ * Listening client for testing purposes.
*
+ * @author martin.uhlir
*/
public class ListeningSimpleClient implements OFClient {
private ScenarioHandler scenarioHandler;
/**
- * Constructor of the class
+ * Constructor of the class.
*
* @param port host listening port
*/
}
/**
- * Starting class of {@link ListeningSimpleClient}
+ * Starting class of {@link ListeningSimpleClient}.
*/
@Override
public void run() {
SimpleClientInitializer clientInitializer = new SimpleClientInitializer(isOnlineFuture, securedClient);
clientInitializer.setScenario(scenarioHandler);
try {
- ServerBootstrap b = new ServerBootstrap();
- b.group(bossGroup, workerGroup)
+ ServerBootstrap bootstrap = new ServerBootstrap();
+ bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(clientInitializer);
- ChannelFuture f = b.bind(port).sync();
+ ChannelFuture future = bootstrap.bind(port).sync();
// Update port, as it may have been specified as 0
- this.port = ((InetSocketAddress) f.channel().localAddress()).getPort();
+ this.port = ((InetSocketAddress) future.channel().localAddress()).getPort();
isOnlineFuture.set(true);
synchronized (scenarioHandler) {
scenarioHandler.wait();
}
}
- } catch (Exception ex) {
+ } catch (InterruptedException ex) {
LOG.error(ex.getMessage(), ex);
} finally {
LOG.debug("listening client shutting down");
}
/**
+ * Disconnect.
+ *
* @return close future
*/
public Future<?> disconnect() {
}
/**
- * @return actual port number
+ * Returns the actual port number.
*/
public int getPort() {
return this.port;
import com.google.common.util.concurrent.SettableFuture;
/**
- * Unifying interface for simple clients / switch simulators
+ * Unifying interface for simple clients / switch simulators.
*
* @author michal.polkorab
*/
public interface OFClient extends Runnable {
/**
- * @return the isOnlineFuture which is set when client is started
+ * Returns the isOnlineFuture which is set when client is started.
*/
SettableFuture<Boolean> getIsOnlineFuture();
/**
- * @return the scenarioDone when scenario is successfully finished
+ * Returns the scenarioDone when scenario is successfully finished.
*/
SettableFuture<Boolean> getScenarioDone();
/**
+ * Sets the ScenarioHandler.
+ *
* @param scenario list of desired actions
*/
void setScenarioHandler(ScenarioHandler scenario);
/**
- * @param securedClient true is client should use encrypted communication,
- * false otherwise
+ * Sets wether client should use encrypted communication.
+ *
+ * @param securedClient true is client should use encrypted communication, false otherwise
*/
void setSecuredClient(boolean securedClient);
-}
\ No newline at end of file
+}
/**
- * <p>Java class for scenarioType complex type.
+ * Java class for scenarioType complex type.
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "scenario", propOrder = {
"step"
-})
+ })
public class Scenario {
@XmlElement(required = true)
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Map;
-
+import javax.xml.bind.JAXBException;
import org.opendaylight.openflowjava.util.ByteBufUtils;
import org.xml.sax.SAXException;
-import javax.xml.bind.JAXBException;
-
/**
- * Class for providing prepared handshake scenario
+ * Class for providing prepared handshake scenario.
*
* @author michal.polkorab
*/
public static Deque<ClientEvent> createHandshakeScenarioWithBarrier() {
Deque<ClientEvent> stack = new ArrayDeque<>();
stack.addFirst(new SendEvent(ByteBufUtils.hexStringToBytes("04 00 00 08 00 00 00 01")));
- stack.addFirst(new WaitForMessageEvent(ByteBufUtils.hexStringToBytes("04 00 00 10 00 00 00 15 00 01 00 08 00 00 00 12"))); //Hello message 21
+ stack.addFirst(new WaitForMessageEvent(ByteBufUtils.hexStringToBytes(
+ "04 00 00 10 00 00 00 15 00 01 00 08 00 00 00 12"))); //Hello message 21
stack.addFirst(new WaitForMessageEvent(ByteBufUtils.hexStringToBytes("04 05 00 08 00 00 00 02")));
stack.addFirst(new SendEvent(ByteBufUtils.hexStringToBytes("04 06 00 20 00 00 00 02 "
+ "00 01 02 03 04 05 06 07 00 01 02 03 01 00 00 00 00 01 02 03 00 01 02 03")));
- stack.addFirst(new WaitForMessageEvent(ByteBufUtils.hexStringToBytes("04 14 00 08 00 00 00 00"))); //Barrier request
+ stack.addFirst(new WaitForMessageEvent(ByteBufUtils.hexStringToBytes(
+ "04 14 00 08 00 00 00 00"))); //Barrier request
stack.addFirst(new SendEvent(ByteBufUtils.hexStringToBytes("04 15 00 08 00 00 00 04"))); //Barrier reply
return stack;
}
/**
- * Creates stack from XML file
+ * Creates stack from XML file.
+ *
* @return stack filled with Handshake messages
*/
- public static Deque<ClientEvent> getScenarioFromXml(String scenarioName, String scenarioFile) throws JAXBException, SAXException, IOException {
+ public static Deque<ClientEvent> getScenarioFromXml(String scenarioName, String scenarioFile)
+ throws JAXBException, SAXException, IOException {
ScenarioService scenarioService = new ScenarioServiceImpl(scenarioFile);
Deque<ClientEvent> stack = new ArrayDeque<>();
- for (Map.Entry<Integer, ClientEvent> clientEvent : scenarioService.getEventsFromScenario(scenarioService.unMarshallData(scenarioName)).entrySet()) {
+ for (Map.Entry<Integer, ClientEvent> clientEvent : scenarioService.getEventsFromScenario(
+ scenarioService.unMarshallData(scenarioName)).entrySet()) {
stack.addFirst(clientEvent.getValue());
}
return stack;
queue.addFirst(new WaitForMessageEvent(ByteBufUtils.hexStringToBytes("04 00 00 08 00 00 00 02")));
queue.addFirst(new WaitForMessageEvent(ByteBufUtils.hexStringToBytes("04 05 00 08 00 00 00 03")));
queue.addFirst(new SendEvent(ByteBufUtils.hexStringToBytes("04 06 00 20 00 00 00 03 "
- + "00 01 02 03 04 05 06 07 00 01 02 03 01 " + String.format("%02x ", auxiliaryId) + " 00 00 00 01 02 03 00 01 02 03")));
+ + "00 01 02 03 04 05 06 07 00 01 02 03 01 " + String.format("%02x ", auxiliaryId)
+ + " 00 00 00 01 02 03 00 01 02 03")));
return queue;
}
package org.opendaylight.openflowjava.protocol.impl.clients;
import io.netty.channel.ChannelHandlerContext;
-
import java.util.Deque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
+ * Scenario handler thread.
*
* @author michal.polkorab
- *
*/
public class ScenarioHandler extends Thread {
private boolean finishedOK = true;
/**
+ * Constructor.
*
* @param scenario {@link Deque}
*/
ofMsg = new LinkedBlockingQueue<>();
}
- public ScenarioHandler(Deque<ClientEvent> scenario, int freeze, long sleepBetweenTries){
+ public ScenarioHandler(Deque<ClientEvent> scenario, int freeze, long sleepBetweenTries) {
this.scenario = scenario;
ofMsg = new LinkedBlockingQueue<>();
this.sleepBetweenTries = sleepBetweenTries;
}
/**
- * @return true if scenario is done / empty
+ * Returns true if scenario is done / empty.
*/
public boolean isEmpty() {
return scenario.isEmpty();
}
/**
- * @return scenario
+ * Returns the scenario.
*/
public Deque<ClientEvent> getScenario() {
return scenario;
}
/**
+ * Sets the scenario.
+ *
* @param scenario scenario filled with desired events
*/
public void setScenario(Deque<ClientEvent> scenario) {
}
/**
+ * Sets the ChannelHandlerContext.
+ *
* @param ctx context which will be used for sending messages (SendEvents)
*/
public void setCtx(ChannelHandlerContext ctx) {
}
/**
+ * Adds a message.
+ *
* @param message received message that is compared to expected message
*/
public void addOfMsg(byte[] message) {
}
/**
- * @return true is scenario is finished
+ * Returns true is scenario is finished.
*/
public boolean isScenarioFinished() {
return scenarioFinished;
*/
package org.opendaylight.openflowjava.protocol.impl.clients;
-import org.xml.sax.SAXException;
-
-import javax.xml.bind.JAXBException;
import java.io.IOException;
import java.util.SortedMap;
+import javax.xml.bind.JAXBException;
+import org.xml.sax.SAXException;
/**
+ * Interface for a scenario service.
*
* @author Jozef Bacigal
- * Date: 8.3.2016
*/
interface ScenarioService {
* Method to load data from XML configuration file. Each configuration has a name.
* @param scenarioName {@link String}
* @return scenarios
- * @throws SAXException
- * @throws JAXBException
*/
Scenario unMarshallData(String scenarioName) throws SAXException, JAXBException;
import org.xml.sax.SAXException;
/**
+ * Implementation of ScenarioService.
+ *
* @author Jozef Bacigal
- * Date: 9.3.2016
*/
public class ScenarioServiceImpl implements ScenarioService {
private static final Logger LOG = LoggerFactory.getLogger(ScenarioServiceImpl.class);
- private String XML_FILE_PATH_WITH_FILE_NAME = SIMPLE_CLIENT_SRC_MAIN_RESOURCES + SCENARIO_XML;
+ private String xmlFilePathWithFileName = SIMPLE_CLIENT_SRC_MAIN_RESOURCES + SCENARIO_XML;
- public ScenarioServiceImpl(String scenarioFile){
+ public ScenarioServiceImpl(String scenarioFile) {
if (null != scenarioFile && !scenarioFile.isEmpty()) {
- this.XML_FILE_PATH_WITH_FILE_NAME = scenarioFile;
+ this.xmlFilePathWithFileName = scenarioFile;
}
}
Unmarshaller unmarshaller = jc.createUnmarshaller();
unmarshaller.setSchema(schema);
- Scenarios scenarios = (Scenarios) unmarshaller.unmarshal(new File(XML_FILE_PATH_WITH_FILE_NAME));
- LOG.debug("Scenarios ({}) are un-marshaled from {}", scenarios.getScenario().size(), XML_FILE_PATH_WITH_FILE_NAME);
+ Scenarios scenarios = (Scenarios) unmarshaller.unmarshal(new File(xmlFilePathWithFileName));
+ LOG.debug("Scenarios ({}) are un-marshaled from {}", scenarios.getScenario().size(),
+ xmlFilePathWithFileName);
boolean foundConfiguration = false;
Scenario scenarioType = null;
SortedMap<Integer, ClientEvent> events = new TreeMap<>();
Integer counter = 0;
for (Step step : scenario.getStep()) {
- LOG.debug("Step {}: {}, type {}, bytes {}", step.getOrder(), step.getName(), step.getEvent().value(), step.getBytes().toArray());
+ LOG.debug("Step {}: {}, type {}, bytes {}", step.getOrder(), step.getName(), step.getEvent().value(),
+ step.getBytes().toArray());
switch (step.getEvent()) {
- case SLEEP_EVENT: events.put(counter++, new SleepEvent(1000)); break;
- case SEND_EVENT: events.put(counter++, new SendEvent(ByteBufUtils.serializeList(step.getBytes()))); break;
- case WAIT_FOR_MESSAGE_EVENT: events.put(counter++, new WaitForMessageEvent(ByteBufUtils.serializeList(step.getBytes()))); break;
+ case SLEEP_EVENT:
+ events.put(counter++, new SleepEvent(1000));
+ break;
+ case SEND_EVENT:
+ events.put(counter++, new SendEvent(ByteBufUtils.serializeList(step.getBytes())));
+ break;
+ case WAIT_FOR_MESSAGE_EVENT:
+ events.put(counter++, new WaitForMessageEvent(ByteBufUtils.serializeList(step.getBytes())));
+ break;
+ default:
+ break;
}
}
return events;
/**
- * <p>Java class for anonymous complex type.
+ * Java class for anonymous complex type.
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"scenario"
-})
+ })
@XmlRootElement(name = "scenarios")
public class Scenarios {
* <pre>
* getScenario().add(newItem);
* </pre>
+ *
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Scenario }
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
-
import org.opendaylight.openflowjava.util.ByteBufUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * Class representing sending message event
+ * Class representing sending message event.
*
* @author michal.polkorab
*/
protected ChannelHandlerContext ctx;
/**
+ * Constructor.
+ *
* @param msgToSend message to be sent
*/
public SendEvent(byte[] msgToSend) {
}
/**
+ * Sets the ChannelHandlerContext.
+ *
* @param ctx context which will be used for sending messages (SendEvents)
*/
public void setCtx(ChannelHandlerContext ctx) {
package org.opendaylight.openflowjava.protocol.impl.clients;
+import com.google.common.util.concurrent.SettableFuture;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.Future;
-
import java.net.InetAddress;
import java.util.concurrent.ExecutionException;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.util.concurrent.SettableFuture;
-
/**
- * Simple client for testing purposes
+ * Simple client for testing purposes.
*
* @author michal.polkorab
*/
private ScenarioHandler scenarioHandler;
/**
- * Constructor of class
+ * Constructor of class.
*
* @param host address of host
* @param port host listening port
}
/**
- * Starting class of {@link SimpleClient}
+ * Starting class of {@link SimpleClient}.
*/
@Override
public void run() {
SimpleClientInitializer clientInitializer = new SimpleClientInitializer(isOnlineFuture, securedClient);
clientInitializer.setScenario(scenarioHandler);
try {
- Bootstrap b = new Bootstrap();
- b.group(group)
+ Bootstrap bootstrap = new Bootstrap();
+ bootstrap.group(group)
.channel(NioSocketChannel.class)
.handler(clientInitializer);
- b.connect(host, port).sync();
+ bootstrap.connect(host, port).sync();
synchronized (scenarioHandler) {
LOG.debug("WAITING FOR SCENARIO");
scenarioHandler.wait();
}
}
- } catch (Exception ex) {
+ } catch (InterruptedException ex) {
LOG.error(ex.getMessage(), ex);
} finally {
LOG.debug("shutting down");
}
/**
+ * Disconnect.
+ *
* @return close future
*/
public Future<?> disconnect() {
}
/**
- * Sets up {@link SimpleClient} and fires run()
- *
- * @param args
- * @throws Exception
+ * Sets up {@link SimpleClient} and fires run().
*/
public static void main(String[] args) throws Exception {
String host;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
-
import java.util.List;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
*/
public class SimpleClientFramer extends ByteToMessageDecoder {
- /** Length of OpenFlow 1.3 header */
+ /** Length of OpenFlow 1.3 header. */
public static final byte LENGTH_OF_HEADER = 8;
private static final byte LENGTH_INDEX_IN_HEADER = 2;
private static final Logger LOG = LoggerFactory.getLogger(SimpleClientFramer.class);
package org.opendaylight.openflowjava.protocol.impl.clients;
+import com.google.common.util.concurrent.SettableFuture;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
-
import org.opendaylight.openflowjava.util.ByteBufUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.util.concurrent.SettableFuture;
-
/**
+ * Simple client handler.
*
* @author michal.polkorab
*/
protected ScenarioHandler scenarioHandler;
/**
+ * Constructor.
+ *
* @param isOnlineFuture future notifier of connected channel
* @param scenarioHandler handler of scenario events
*/
}
/**
- * @param scenarioHandler handler of scenario events
+ * Sets the ScenarioHandler.
+ *
+ * @param handler handler of scenario events
*/
- public void setScenario(ScenarioHandler scenarioHandler) {
- this.scenarioHandler = scenarioHandler;
+ public void setScenario(ScenarioHandler handler) {
+ this.scenarioHandler = handler;
}
}
package org.opendaylight.openflowjava.protocol.impl.clients;
+import com.google.common.util.concurrent.SettableFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.ssl.SslHandler;
-
import javax.net.ssl.SSLEngine;
-import com.google.common.util.concurrent.SettableFuture;
-
-/** Initializes secured {@link SimpleClient} pipeline
+/**
+ * Initializes secured {@link SimpleClient} pipeline.
*
* @author michal.polkorab
*/
private ScenarioHandler scenarioHandler;
/**
+ * Constructor.
+ *
* @param isOnlineFuture future notifier of connected channel
* @param secured true if {@link SimpleClient} should use encrypted communication
*/
}
/**
- * @param scenarioHandler handler of scenario events
+ * Sets the ScenarioHandler.
+ *
+ * @param handler handler of scenario events
*/
- public void setScenario(ScenarioHandler scenarioHandler) {
- this.scenarioHandler = scenarioHandler;
+ public void setScenario(ScenarioHandler handler) {
+ this.scenarioHandler = handler;
}
-}
\ No newline at end of file
+}
import org.slf4j.LoggerFactory;
/**
- * Class representing sleep (wait) event
+ * Class representing sleep (wait) event.
*
* @author michal.polkorab
*/
public class SleepEvent implements ClientEvent {
private static final Logger LOG = LoggerFactory.getLogger(SleepEvent.class);
- private long sleepTime;
+ private final long sleepTime;
/**
+ * Constructor.
*
* @param sleepTime time of {@link Thread#sleep(long)} in milliseconds
*/
/**
- * <p>Java class for stepType complex type.
+ * Java class for stepType complex type.
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "step", propOrder = {
"name",
"event",
"bytes"
-})
+ })
public class Step {
protected short order;
* <pre>
* getBytes().add(newItem);
* </pre>
+ *
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Short }
package org.opendaylight.openflowjava.protocol.impl.clients;
+import com.google.common.util.concurrent.SettableFuture;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.concurrent.Future;
-
import java.net.InetAddress;
import java.util.concurrent.ExecutionException;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.util.concurrent.SettableFuture;
-
/**
- * Simple client for testing purposes
+ * Simple client for testing purposes.
*
* @author michal.polkorab
*/
private ScenarioHandler scenarioHandler;
/**
- * Constructor of class
+ * Constructor of class.
*
* @param host address of host
* @param port host listening port
}
/**
- * Starting class of {@link UdpSimpleClient}
+ * Starting class of {@link UdpSimpleClient}.
*/
@Override
public void run() {
UdpSimpleClientInitializer clientInitializer = new UdpSimpleClientInitializer(isOnlineFuture);
clientInitializer.setScenario(scenarioHandler);
try {
- Bootstrap b = new Bootstrap();
- b.group(group)
+ Bootstrap bootstrap = new Bootstrap();
+ bootstrap.group(group)
.channel(NioDatagramChannel.class)
.option(ChannelOption.SO_BROADCAST, false)
.handler(clientInitializer);
- b.connect(host, port).sync();
+ bootstrap.connect(host, port).sync();
synchronized (scenarioHandler) {
LOG.debug("WAITING FOR SCENARIO");
scenarioHandler.wait();
}
}
- } catch (Exception ex) {
+ } catch (InterruptedException ex) {
LOG.error(ex.getMessage(), ex);
} finally {
LOG.debug("shutting down");
}
/**
+ * Disconnect.
+ *
* @return close future
*/
public Future<?> disconnect() {
}
/**
- * Sets up {@link UdpSimpleClient} and fires run()
- *
- * @param args
- * @throws Exception
+ * Sets up {@link UdpSimpleClient} and fires run().
*/
public static void main(String[] args) throws Exception {
String host;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageDecoder;
-
import java.util.List;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
*/
public class UdpSimpleClientFramer extends MessageToMessageDecoder<DatagramPacket> {
- /** Length of OpenFlow 1.3 header */
+ /** Length of OpenFlow 1.3 header .*/
public static final byte LENGTH_OF_HEADER = 8;
private static final byte LENGTH_INDEX_IN_HEADER = 2;
private static final Logger LOG = LoggerFactory.getLogger(UdpSimpleClientFramer.class);
package org.opendaylight.openflowjava.protocol.impl.clients;
+import com.google.common.util.concurrent.SettableFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.DatagramChannel;
-import com.google.common.util.concurrent.SettableFuture;
-
-/** Initializes udp pipeline
+/**
+ * Initializes udp pipeline.
*
* @author michal.polkorab
*/
private ScenarioHandler scenarioHandler;
/**
+ * Constructor.
+ *
* @param isOnlineFuture future notifier of connected channel
*/
public UdpSimpleClientInitializer(SettableFuture<Boolean> isOnlineFuture) {
}
/**
- * @param scenarioHandler handler of scenario events
+ * Sets the ScenarioHandler.
+ *
+ * @param handler handler of scenario events
*/
- public void setScenario(ScenarioHandler scenarioHandler) {
- this.scenarioHandler = scenarioHandler;
+ public void setScenario(ScenarioHandler handler) {
+ this.scenarioHandler = handler;
}
-}
\ No newline at end of file
+}
package org.opendaylight.openflowjava.protocol.impl.clients;
import java.util.Arrays;
-
import org.opendaylight.openflowjava.util.ByteBufUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * Class representing waiting on message
+ * Class representing waiting on message.
+ *
* @author michal.polkorab
*/
public class WaitForMessageEvent implements ClientEvent {
private static final Logger LOG = LoggerFactory.getLogger(WaitForMessageEvent.class);
- private byte[] headerExpected;
+ private final byte[] headerExpected;
private byte[] headerReceived;
/**
+ * Constructor.
+ *
* @param headerExpected header (first 8 bytes) of expected message
*/
public WaitForMessageEvent(byte[] headerExpected) {
}
/**
+ * Sets the received header.
+ *
* @param headerReceived header (first 8 bytes) of expected message
*/
public void setHeaderReceived(byte[] headerReceived) {