.project
.settings
MANIFEST.MF
+opendaylight/northbound/integrationtest/logs/*
import org.junit.Test;\r
\r
public class ArphandlerTest extends TestCase {\r
- \r
- @Test\r
- public void testArphandlerCreation() {\r
- \r
- ArpHandler ah = null;\r
- ah = new ArpHandler();\r
- Assert.assertTrue(ah != null);\r
- \r
- }\r
+\r
+ @Test\r
+ public void testArphandlerCreation() {\r
+\r
+ ArpHandler ah = null;\r
+ ah = new ArpHandler();\r
+ Assert.assertTrue(ah != null);\r
+\r
+ }\r
\r
}\r
<configuration scan="true">
-
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
\r
public class TestClusteringTest extends TestCase {\r
\r
- @Test\r
- public void testComplexClass() {\r
- ComplexClass cc = new ComplexClass("cplxc1");\r
- Assert.assertTrue(cc.whoAmI().equals("ComplexClass_cplxc1"));\r
- cc.IAm("cplxc2");\r
- Assert.assertTrue(cc.whoAmI().equals("ComplexClass_cplxc2"));\r
- }\r
- \r
- @Test\r
- public void testComplexClass1() {\r
- ComplexClass1 cc1 = new ComplexClass1("cplxc1a");\r
- Assert.assertTrue(cc1.whoAmI().equals("ComplexClass1_cplxc1a"));\r
- cc1.IAm("cplxc1b");\r
- Assert.assertTrue(cc1.whoAmI().equals("ComplexClass1_cplxc1b"));\r
- }\r
- \r
- \r
- @Test\r
- public void testComplexContainer() {\r
- ComplexContainer cplxcontnr1 = new ComplexContainer("cct1", 5);\r
- Assert.assertTrue(cplxcontnr1.getIdentity().equals("[ComplexClass_cct1]-[ComplexClass1_cct1]"));\r
- Assert.assertTrue(cplxcontnr1.getState() == 5);\r
- \r
- cplxcontnr1.setIdentity("cct2");\r
- Assert.assertTrue(cplxcontnr1.getIdentity().equals("[ComplexClass_cct2]-[ComplexClass1_cct2]"));\r
- \r
- Assert.assertTrue(cplxcontnr1.toString().equals(\r
- "{ID:[ComplexClass_cct2]-[ComplexClass1_cct2],STATE:5}"));\r
- }\r
- \r
- @Test\r
- public void testStringContainer() {\r
- StringContainer strcontainer1 = new StringContainer();\r
- Assert.assertTrue(strcontainer1.getMystring() == null);\r
- Assert.assertTrue(strcontainer1.hashCode() == 0);\r
- \r
- StringContainer strcontainer2 = new StringContainer("foo");\r
- Assert.assertTrue(strcontainer2.getMystring() != null);\r
- Assert.assertTrue(strcontainer2.hashCode() != 0);\r
- \r
- strcontainer1.setMystring("foo");\r
- Assert.assertTrue(strcontainer2.equals(strcontainer1));\r
- \r
- Assert.assertTrue(strcontainer2.toString().equals("{foo}"));\r
- }\r
- \r
+ @Test\r
+ public void testComplexClass() {\r
+ ComplexClass cc = new ComplexClass("cplxc1");\r
+ Assert.assertTrue(cc.whoAmI().equals("ComplexClass_cplxc1"));\r
+ cc.IAm("cplxc2");\r
+ Assert.assertTrue(cc.whoAmI().equals("ComplexClass_cplxc2"));\r
+ }\r
+\r
+ @Test\r
+ public void testComplexClass1() {\r
+ ComplexClass1 cc1 = new ComplexClass1("cplxc1a");\r
+ Assert.assertTrue(cc1.whoAmI().equals("ComplexClass1_cplxc1a"));\r
+ cc1.IAm("cplxc1b");\r
+ Assert.assertTrue(cc1.whoAmI().equals("ComplexClass1_cplxc1b"));\r
+ }\r
+\r
+\r
+ @Test\r
+ public void testComplexContainer() {\r
+ ComplexContainer cplxcontnr1 = new ComplexContainer("cct1", 5);\r
+ Assert.assertTrue(cplxcontnr1.getIdentity().equals("[ComplexClass_cct1]-[ComplexClass1_cct1]"));\r
+ Assert.assertTrue(cplxcontnr1.getState() == 5);\r
+\r
+ cplxcontnr1.setIdentity("cct2");\r
+ Assert.assertTrue(cplxcontnr1.getIdentity().equals("[ComplexClass_cct2]-[ComplexClass1_cct2]"));\r
+\r
+ Assert.assertTrue(cplxcontnr1.toString().equals(\r
+ "{ID:[ComplexClass_cct2]-[ComplexClass1_cct2],STATE:5}"));\r
+ }\r
+\r
+ @Test\r
+ public void testStringContainer() {\r
+ StringContainer strcontainer1 = new StringContainer();\r
+ Assert.assertTrue(strcontainer1.getMystring() == null);\r
+ Assert.assertTrue(strcontainer1.hashCode() == 0);\r
+\r
+ StringContainer strcontainer2 = new StringContainer("foo");\r
+ Assert.assertTrue(strcontainer2.getMystring() != null);\r
+ Assert.assertTrue(strcontainer2.hashCode() != 0);\r
+\r
+ strcontainer1.setMystring("foo");\r
+ Assert.assertTrue(strcontainer2.equals(strcontainer1));\r
+\r
+ Assert.assertTrue(strcontainer2.toString().equals("{foo}"));\r
+ }\r
+\r
\r
}\r
<manifestLocation>${project.basedir}/META-INF</manifestLocation>\r
</configuration>\r
</plugin>\r
+ <plugin>\r
+ <groupId>org.apache.maven.plugins</groupId>\r
+ <artifactId>maven-checkstyle-plugin</artifactId>\r
+ <version>${checkstyle.version}</version>\r
+ <configuration>\r
+ <failsOnError>true</failsOnError>\r
+ <configLocation>${project.parent.parent.basedir}/space_and_tabs_checks.xml</configLocation>\r
+ </configuration>\r
+ </plugin>\r
</plugins>\r
</build>\r
<dependencies>\r
public interface Acceptor<I> {\r
\r
/**\r
- * \r
+ *\r
* @param input\r
* @return true if input is accepted.\r
*/\r
\r
import java.util.Collection;\r
/**\r
- * \r
+ *\r
* @author Tony Tkacik\r
*\r
* @param <I>\r
/**\r
* Transformer which aggregates multiple implementations of\r
* {@link InputClassBasedTransformer}.\r
- * \r
+ *\r
* The transformation process is driven by {@link Class} of input. The selection\r
* of used {@link InputClassBasedTransformer} is done by using the {@link Class}\r
* of input as a key to select the transformer.\r
- * \r
+ *\r
* This approach provides quick resolution of transformer, but does not support\r
* registering a super type of input to provide transformation support for all\r
* subclasses, one must register a new instance of transformer for each valid\r
* input class.\r
- * \r
+ *\r
* If you need more flexible selection of transformation consider using\r
* {@link CompositeConditionalTransformer} which is slower but most flexible or\r
* {@link RuleBasedTransformer} which provides declarative approach for\r
* transformation.\r
- * \r
+ *\r
* See {@link #transform(Object)} for more information about tranformation\r
* process.\r
- * \r
+ *\r
* @author Tony Tkacik <ttkacik@cisco.com>\r
- * \r
+ *\r
* @param <I>\r
* Input super-type\r
* @param <P>\r
\r
/**\r
* Transforms an input into instance of Product class.\r
- * \r
+ *\r
* The final registered transformer is the one which match following\r
* condition:\r
- * \r
+ *\r
* <code>input.getClass() == transformer.getInputClass()</code>\r
- * \r
+ *\r
* This means that transformers are not resolved by class hierarchy, only\r
* selected based on final class of the input. If you need more flexible\r
* selection of transformation consider using\r
* {@link CompositeConditionalTransformer} which is slower but more\r
* flexible.\r
- * \r
+ *\r
*/\r
@Override\r
public P transform(I input) {\r
\r
/**\r
* Registers a new transformer.\r
- * \r
+ *\r
* The transformer is registered for class returned by\r
* {@link InputClassBasedTransformer#getInputClass()}. Only one transformer\r
* can be registered for particular input class.\r
- * \r
+ *\r
*/\r
public void addTransformer(\r
InputClassBasedTransformer<I, ? extends I, P> transformer)\r
\r
/**\r
* Removes an registered transformer.\r
- * \r
+ *\r
* Note: Removal is currently unsupported.\r
- * \r
+ *\r
* @param transformer\r
* Tranformer to be removed.\r
* @throws IllegalArgumentException\r
throws IllegalArgumentException {\r
throw new UnsupportedOperationException("Not implemented yet");\r
}\r
- \r
+\r
@Override\r
public Collection<P> transformAll(Collection<? extends I> inputs) {\r
Collection<P> ret = new ArrayList<P>();\r
\r
/**\r
* Input class based transformer\r
- * \r
+ *\r
* {@link Transformer} which accepts / transforms only specific classes of\r
* input, and is useful if the selection of transformer should be based on the\r
* class of the input and there is one-to-one mapping between input class and\r
* transformer.\r
- * \r
- * \r
+ *\r
+ *\r
* @author Tony Tkacik\r
- * \r
+ *\r
* @param <S>\r
* Common supertype of input\r
* @param <I>\r
\r
/**\r
* Returns an {@link Class} of input which is acceptable for transformation.\r
- * \r
+ *\r
* @return {@link Class} of input which is acceptable for transformation.\r
*/\r
Class<? extends S> getInputClass();\r
\r
/**\r
* Transformer with set of acceptance rules\r
- * \r
+ *\r
* The transformer provides a set of {@link Acceptor}s, which could be used to\r
* verify if the input will produce result using the transformer.\r
- * \r
+ *\r
* The transormer is able to produce result if ANY of associated\r
* {@link Acceptor}s accepted result.\r
- * \r
+ *\r
* @author Tony Tkacik\r
- * \r
+ *\r
* @param <I>\r
* Input class for transformation\r
* @param <P>\r
/**\r
* Set of {@link Acceptor}, which could be used to verify if the input is\r
* usable by transformer.\r
- * \r
+ *\r
* The transformer is able to produce result if ANY of associated\r
* {@link Acceptor}s accepted result.\r
- * \r
+ *\r
* @return Set of input acceptance rules associated to this transformer.\r
*/\r
Set<Acceptor<I>> getRules();\r
\r
/**\r
* Simple condition-based transformer\r
- * \r
+ *\r
* The transformer provides {@link #isAcceptable(Object)} method,\r
* which could be used to query transformer if the input will produce\r
* result.\r
- * \r
+ *\r
* This interface is simplified version of {@link RuleBasedTransformer} - does not\r
* provide decoupling of Acceptance rule from transformer, and should be used only\r
* for simple use-cases.\r
- * \r
+ *\r
* @author Tony Tkacik\r
*\r
* @param <I> Input class for transformation\r
\r
\r
/**\r
- * Checks if the input is acceptable \r
+ * Checks if the input is acceptable\r
* for processing by the transformer.\r
- * \r
+ *\r
* @return true it the input is acceptable for processing by transformer.\r
*/\r
@Override\r
\r
/**\r
* Factory which produces product based on input object\r
- * \r
+ *\r
* @author Tony Tkacik\r
*\r
* @param <I> Input\r
public interface Transformer<I,P> {\r
/**\r
* Transforms input into instance of product.\r
- * \r
+ *\r
* @param input Input which drives transformation\r
* @return Instance of product which was created from supplied input.\r
*/\r
<plugin>
<groupId>org.ops4j.pax.exam</groupId>
<artifactId>maven-paxexam-plugin</artifactId>
+ <version>1.2.4</version>
<executions>
<execution>
<id>generate-config</id>
</execution>
</executions>
</plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <version>${checkstyle.version}</version>
+ <configuration>
+ <failsOnError>true</failsOnError>
+ <configLocation>${project.parent.parent.basedir}/space_and_tabs_checks.xml</configLocation>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>properties-maven-plugin</artifactId>
+ <version>${propertymavenplugin.version}</version>
+ <executions>
+ <execution>
+ <goals>
+ <goal>set-system-properties</goal>
+ </goals>
+ <configuration>
+ <properties>
+ <property>
+ <name>logback.configurationFile</name>
+ <value>${project.parent.parent.basedir}/logback.xml</value>
+ </property>
+ </properties>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
</plugins>
</build>
</project>
<artifactId>commons.opendaylight</artifactId>
<version>1.4.0-SNAPSHOT</version>
<packaging>pom</packaging>
+ <parent>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>commons.parent</artifactId>
+ <version>1.0.0-SNAPSHOT</version>
+ <relativePath>../parent</relativePath>
+ </parent>
<properties>
+ <propertymavenplugin.version>1.0-alpha-2</propertymavenplugin.version>
<sonar.host.url>https://sonar.opendaylight.org/</sonar.host.url>
- <nexusproxy>http://nexus.opendaylight.org/content</nexusproxy>
<sitedeploy>dav:http://nexus.opendaylight.org/content/sites/site</sitedeploy>
<siteplugin>3.2</siteplugin>
<projectinfo>2.6</projectinfo>
<jersey.version>1.17</jersey.version>
<virgo.version>3.6.0.RELEASE</virgo.version>
<geminiweb.version>2.2.0.RELEASE</geminiweb.version>
+ <checkstyle.version>2.10</checkstyle.version>
</properties>
<pluginRepositories>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
- <version>2.10</version>
+ <version>${checkstyle.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
- <version>1.0-alpha-2</version>
+ <version>${propertymavenplugin.version}</version>
<executions>
<execution>
<goals>
<properties>
<property>
<name>logback.configurationFile</name>
- <value>${project.parent.relativePath}/logback.xml</value>
+ <value>${project.parent.basedir}/logback.xml</value>
</property>
</properties>
</configuration>
<compilerSource>1.6</compilerSource>
<compilerCompliance>1.6</compilerCompliance>
<compilerTargetPlatform>1.6</compilerTargetPlatform>
- <configFile>${project.parent.relativePath}/sun_coding_style.xml</configFile>
+ <configFile>${project.parent.basedir}/sun_coding_style.xml</configFile>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <version>${checkstyle.version}</version>
+ <executions>
+ <execution>
+ <phase>process-sources</phase>
+ <goals>
+ <goal>check</goal>
+ </goals>
+ </execution>
+ </executions>
+ <configuration>
+ <failsOnError>true</failsOnError>
+ <configLocation>${project.parent.basedir}/space_and_tabs_checks.xml</configLocation>
+ <consoleOutput>true</consoleOutput>
+ <includeTestSourceDirectory>true</includeTestSourceDirectory>
</configuration>
</plugin>
<plugin>
</action>
</pluginExecution>
<pluginExecution>
- <pluginExecutionFilter>
- <groupId>org.ops4j.pax.exam</groupId>
- <artifactId>maven-paxexam-plugin</artifactId>
- <versionRange>[1.2.4,)</versionRange>
- <goals>
- <goal>generate-depends-file</goal>
- </goals>
- </pluginExecutionFilter>
- <action>
- <ignore></ignore>
- </action>
+ <pluginExecutionFilter>
+ <groupId>org.ops4j.pax.exam</groupId>
+ <artifactId>maven-paxexam-plugin</artifactId>
+ <versionRange>[1.2.4,)</versionRange>
+ <goals>
+ <goal>generate-depends-file</goal>
+ </goals>
+ </pluginExecutionFilter>
+ <action>
+ <ignore/>
+ </action>
+ </pluginExecution>
+ <pluginExecution>
+ <pluginExecutionFilter>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <versionRange>[2.0,)</versionRange>
+ <goals>
+ <goal>check</goal>
+ </goals>
+ </pluginExecutionFilter>
+ <action>
+ <ignore/>
+ </action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
--- /dev/null
+<?xml version="1.0"?>\r
+<!DOCTYPE module PUBLIC\r
+ "-//Puppy Crawl//DTD Check Configuration 1.2//EN"\r
+ "http://www.puppycrawl.com/dtds/configuration_1_2.dtd">\r
+\r
+<module name="Checker">\r
+ <module name="FileTabCharacter">\r
+ <property name="eachLine" value="true"/>\r
+ </module>\r
+\r
+ <module name="RegexpSingleline">\r
+ <!-- \s matches whitespace character, $ matches end of line. -->\r
+ <property name="format" value="\s+$"/>\r
+ <property name="message" value="Line has trailing spaces."/>\r
+ </module>\r
+\r
+</module>\r
--- /dev/null
+This contains a dummy parent project. The use case of this is for
+example the maven-checkstyle plugin call in commons/opendaylight in
+there the plugin references the spaces_tabs_checks.xml from the
+parent, it works well for all the childs of commons/opendaylight
+artifact but when trying to deploy that one itself it breaks because
+the plugin section will still refer to the parent when there is no
+parent.
+This fake parents allow to still set a parent for the
+commons/opendaylight even if pretty much empty or limited to the bare
+minimum and yet allow the commons/opendaylight to reference a parent.
--- /dev/null
+<configuration scan="true">
+
+ <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+ <encoder>
+ <pattern>%date{"yyyy-MM-dd HH:mm:ss.SSS z"} [%thread] %-5level %logger{36} - %msg%n</pattern>
+ </encoder>
+ </appender>
+
+ <root level="error">
+ <appender-ref ref="STDOUT" />
+ </root>
+</configuration>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <modelVersion>4.0.0</modelVersion>
+ <prerequisites>
+ <maven>3.0</maven>
+ </prerequisites>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>commons.parent</artifactId>
+ <version>1.0.0-SNAPSHOT</version>
+ <packaging>pom</packaging>
+
+ <properties>
+ <nexusproxy>http://nexus.opendaylight.org/content</nexusproxy>
+ </properties>
+ <distributionManagement>
+ <!-- OpenDayLight Released artifact -->
+ <repository>
+ <id>opendaylight-release</id>
+ <url>${nexusproxy}/repositories/opendaylight.release/</url>
+ </repository>
+ <!-- OpenDayLight Snapshot artifact -->
+ <snapshotRepository>
+ <id>opendaylight-snapshot</id>
+ <url>${nexusproxy}/repositories/opendaylight.snapshot/</url>
+ </snapshotRepository>
+ <!-- Site deployment -->
+ <site>
+ <id>website</id>
+ <url>${sitedeploy}</url>
+ </site>
+ </distributionManagement>
+</project>
--- /dev/null
+<?xml version="1.0"?>\r
+<!DOCTYPE module PUBLIC\r
+ "-//Puppy Crawl//DTD Check Configuration 1.2//EN"\r
+ "http://www.puppycrawl.com/dtds/configuration_1_2.dtd">\r
+\r
+<module name="Checker">\r
+ <module name="FileTabCharacter">\r
+ <property name="eachLine" value="true"/>\r
+ </module>\r
+\r
+ <module name="RegexpSingleline">\r
+ <!-- \s matches whitespace character, $ matches end of line. -->\r
+ <property name="format" value="\s+$"/>\r
+ <property name="message" value="Line has trailing spaces."/>\r
+ </module>\r
+\r
+</module>\r
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<profiles version="12">
+<profile kind="CodeFormatterProfile" name="SunCodingStyle" version="12">
+<setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.disabling_tag" value="@formatter:off"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_field" value="0"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.use_on_off_tags" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_ellipsis" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_multiple_fields" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_conditional_expression" value="80"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_binary_operator" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_array_initializer" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_package" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.continuation_indentation" value="2"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_binary_operator" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_package" value="0"/>
+<setting id="org.eclipse.jdt.core.compiler.source" value="1.7"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.format_line_comments" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.join_wrapped_lines" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_member_type" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.align_type_members_on_columns" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_unary_operator" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.indent_parameter_description" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.lineSplit" value="80"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration" value="0"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indentation.size" value="8"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.enabling_tag" value="@formatter:on"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_assignment" value="0"/>
+<setting id="org.eclipse.jdt.core.compiler.problem.assertIdentifier" value="error"/>
+<setting id="org.eclipse.jdt.core.formatter.tabulation.char" value="space"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_body" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_method" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_method_declaration" value="0"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_switch" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.compiler.problem.enumIdentifier" value="error"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_ellipsis" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_block" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_method_declaration" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.compact_else_if" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.indent_root_tags" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_constant" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.tabulation.size" value="4"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_empty_lines" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_block_in_case" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter" value="insert"/>
+<setting id="org.eclipse.jdt.core.compiler.compliance" value="1.7"/>
+<setting id="org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer" value="2"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_unary_operator" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_binary_expression" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode" value="enabled"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_label" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.format_javadoc_comments" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.line_length" value="80"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_between_import_groups" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body" value="0"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.wrap_before_binary_operator" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_block" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.join_lines_in_comments" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_compact_if" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_imports" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.format_html" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.format_source_code" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer" value="insert"/>
+<setting id="org.eclipse.jdt.core.compiler.codegen.targetPlatform" value="1.7"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_resources_in_try" value="80"/>
+<setting id="org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation" value="0"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.format_header" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.format_block_comments" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_enum_constants" value="0"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_type_declaration" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_imports" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line" value="false"/>
+</profile>
+</profiles>
}
public int getConfigurationAwareListSize() {
- return this.configurationAwareList.size();
+ return this.configurationAwareList.size();
}
-
+
public void removeConfigurationContainerAware(
IConfigurationContainerAware configurationAware) {
this.configurationAwareList.remove(configurationAware);
Status status = configurationAware.saveConfiguration();
if (!status.isSuccess()) {
- success = false;
- logger.info("Failed to save config for {}",
- configurationAware.getClass().getSimpleName());
+ success = false;
+ logger.info("Failed to save config for {}",
+ configurationAware.getClass().getSimpleName());
}
}
if (success) {
return new Status(StatusCode.SUCCESS, null);
} else {
return new Status(StatusCode.INTERNALERROR,
- "Failed to Save All Configurations");
+ "Failed to Save All Configurations");
}
}
private Set<IConfigurationAware> configurationAwareList = (Set<IConfigurationAware>) Collections
.synchronizedSet(new HashSet<IConfigurationAware>());
-
+
public int getConfigurationAwareListSize() {
- return this.configurationAwareList.size();
+ return this.configurationAwareList.size();
}
-
+
public void addConfigurationAware(IConfigurationAware configurationAware) {
if (!this.configurationAwareList.contains(configurationAware)) {
this.configurationAwareList.add(configurationAware);
public Status saveConfigurations() {
boolean success = true;
for (IConfigurationAware configurationAware : configurationAwareList) {
- Status status = configurationAware.saveConfiguration();
+ Status status = configurationAware.saveConfiguration();
if (!status.isSuccess()) {
- success = false;
- logger.info("Failed to save config for {}",
- configurationAware.getClass().getName());
+ success = false;
+ logger.info("Failed to save config for {}",
+ configurationAware.getClass().getName());
}
}
if (success) {
return new Status(StatusCode.SUCCESS, null);
} else {
return new Status(StatusCode.INTERNALERROR,
- "Failed to Save All Configurations");
+ "Failed to Save All Configurations");
}
}
public class ConfigurationAwareTest implements
IConfigurationAware {
-
- @Override
- public Status saveConfiguration() {
- return null;
- }
+
+ @Override
+ public Status saveConfiguration() {
+ return null;
+ }
}
public class ConfigurationContainerAwareTest implements
IConfigurationContainerAware {
-
-
-
- @Override
- public Status saveConfiguration() {
- return null;
- }
-
-
+
+
+
+ @Override
+ public Status saveConfiguration() {
+ return null;
+ }
+
+
}
-public class ConfigurationContainerImplTest {
-
-
- @Test
- public void testAddRemoveSaveConfiguration() {
-
- ConfigurationContainerImpl configurationContainerImpl = new ConfigurationContainerImpl();
- IConfigurationContainerAware testConfigurationContainerAware = new ConfigurationContainerAwareTest();
-
- configurationContainerImpl.addConfigurationContainerAware(testConfigurationContainerAware);
- configurationContainerImpl.addConfigurationContainerAware(testConfigurationContainerAware);
-
- Assert.assertEquals(1, configurationContainerImpl.getConfigurationAwareListSize());
-
- IConfigurationContainerAware testConfigurationAware1 = new ConfigurationContainerAwareTest();
- configurationContainerImpl.addConfigurationContainerAware(testConfigurationAware1);
-
- Assert.assertEquals(2, configurationContainerImpl.getConfigurationAwareListSize());
-
- IConfigurationContainerAware testConfigurationAware2 = new ConfigurationContainerAwareTest();
- configurationContainerImpl.addConfigurationContainerAware(testConfigurationAware2);
-
- Assert.assertEquals(3, configurationContainerImpl.getConfigurationAwareListSize());
-
- IConfigurationContainerAware testConfigurationAware3 = new ConfigurationContainerAwareTest();
- configurationContainerImpl.addConfigurationContainerAware(testConfigurationAware3);
-
- Assert.assertEquals(4, configurationContainerImpl.getConfigurationAwareListSize());
-
- configurationContainerImpl.removeConfigurationContainerAware(testConfigurationContainerAware);
- Assert.assertEquals(3, configurationContainerImpl.getConfigurationAwareListSize());
-
- configurationContainerImpl.removeConfigurationContainerAware(testConfigurationContainerAware);
- Assert.assertEquals(3, configurationContainerImpl.getConfigurationAwareListSize());
-
- configurationContainerImpl.removeConfigurationContainerAware(testConfigurationAware3);
- Assert.assertEquals(2, configurationContainerImpl.getConfigurationAwareListSize());
-
- configurationContainerImpl.removeConfigurationContainerAware(testConfigurationAware2);
- Assert.assertEquals(1, configurationContainerImpl.getConfigurationAwareListSize());
-
- configurationContainerImpl.removeConfigurationContainerAware(testConfigurationAware1);
- Assert.assertEquals(0, configurationContainerImpl.getConfigurationAwareListSize());
-
-
- }
-
-}
+public class ConfigurationContainerImplTest {
+
+
+ @Test
+ public void testAddRemoveSaveConfiguration() {
+
+ ConfigurationContainerImpl configurationContainerImpl = new ConfigurationContainerImpl();
+ IConfigurationContainerAware testConfigurationContainerAware = new ConfigurationContainerAwareTest();
+
+ configurationContainerImpl.addConfigurationContainerAware(testConfigurationContainerAware);
+ configurationContainerImpl.addConfigurationContainerAware(testConfigurationContainerAware);
+
+ Assert.assertEquals(1, configurationContainerImpl.getConfigurationAwareListSize());
+
+ IConfigurationContainerAware testConfigurationAware1 = new ConfigurationContainerAwareTest();
+ configurationContainerImpl.addConfigurationContainerAware(testConfigurationAware1);
+
+ Assert.assertEquals(2, configurationContainerImpl.getConfigurationAwareListSize());
+
+ IConfigurationContainerAware testConfigurationAware2 = new ConfigurationContainerAwareTest();
+ configurationContainerImpl.addConfigurationContainerAware(testConfigurationAware2);
+
+ Assert.assertEquals(3, configurationContainerImpl.getConfigurationAwareListSize());
+ IConfigurationContainerAware testConfigurationAware3 = new ConfigurationContainerAwareTest();
+ configurationContainerImpl.addConfigurationContainerAware(testConfigurationAware3);
+
+ Assert.assertEquals(4, configurationContainerImpl.getConfigurationAwareListSize());
+
+ configurationContainerImpl.removeConfigurationContainerAware(testConfigurationContainerAware);
+ Assert.assertEquals(3, configurationContainerImpl.getConfigurationAwareListSize());
+
+ configurationContainerImpl.removeConfigurationContainerAware(testConfigurationContainerAware);
+ Assert.assertEquals(3, configurationContainerImpl.getConfigurationAwareListSize());
+
+ configurationContainerImpl.removeConfigurationContainerAware(testConfigurationAware3);
+ Assert.assertEquals(2, configurationContainerImpl.getConfigurationAwareListSize());
+
+ configurationContainerImpl.removeConfigurationContainerAware(testConfigurationAware2);
+ Assert.assertEquals(1, configurationContainerImpl.getConfigurationAwareListSize());
+
+ configurationContainerImpl.removeConfigurationContainerAware(testConfigurationAware1);
+ Assert.assertEquals(0, configurationContainerImpl.getConfigurationAwareListSize());
+
+
+ }
+
+}
import org.junit.*;
import org.opendaylight.controller.configuration.IConfigurationAware;
-public class ConfigurationImplTest {
-
-
- @Test
- public void testAddRemoveSaveConfiguration() {
-
- ConfigurationImpl configurationImpl = new ConfigurationImpl();
- IConfigurationAware testConfigurationAware = new ConfigurationAwareTest();
-
- configurationImpl.addConfigurationAware(testConfigurationAware);
- configurationImpl.addConfigurationAware(testConfigurationAware);
-
- Assert.assertEquals(1, configurationImpl.getConfigurationAwareListSize());
-
- ConfigurationAwareTest testConfigurationAware1 = new ConfigurationAwareTest();
- configurationImpl.addConfigurationAware(testConfigurationAware1);
-
- Assert.assertEquals(2, configurationImpl.getConfigurationAwareListSize());
-
- ConfigurationAwareTest testConfigurationAware2 = new ConfigurationAwareTest();
- configurationImpl.addConfigurationAware(testConfigurationAware2);
-
- Assert.assertEquals(3, configurationImpl.getConfigurationAwareListSize());
-
- ConfigurationAwareTest testConfigurationAware3 = new ConfigurationAwareTest();
- configurationImpl.addConfigurationAware(testConfigurationAware3);
-
- Assert.assertEquals(4, configurationImpl.getConfigurationAwareListSize());
-
-
- configurationImpl.removeConfigurationAware(testConfigurationAware);
- Assert.assertEquals(3, configurationImpl.getConfigurationAwareListSize());
-
- configurationImpl.removeConfigurationAware(testConfigurationAware);
- Assert.assertEquals(3, configurationImpl.getConfigurationAwareListSize());
-
- configurationImpl.removeConfigurationAware(testConfigurationAware3);
- Assert.assertEquals(2, configurationImpl.getConfigurationAwareListSize());
-
- configurationImpl.removeConfigurationAware(testConfigurationAware1);
- Assert.assertEquals(1, configurationImpl.getConfigurationAwareListSize());
-
- configurationImpl.removeConfigurationAware(testConfigurationAware2);
- Assert.assertEquals(0, configurationImpl.getConfigurationAwareListSize());
-
- }
-
-}
+public class ConfigurationImplTest {
+
+
+ @Test
+ public void testAddRemoveSaveConfiguration() {
+
+ ConfigurationImpl configurationImpl = new ConfigurationImpl();
+ IConfigurationAware testConfigurationAware = new ConfigurationAwareTest();
+
+ configurationImpl.addConfigurationAware(testConfigurationAware);
+ configurationImpl.addConfigurationAware(testConfigurationAware);
+
+ Assert.assertEquals(1, configurationImpl.getConfigurationAwareListSize());
+
+ ConfigurationAwareTest testConfigurationAware1 = new ConfigurationAwareTest();
+ configurationImpl.addConfigurationAware(testConfigurationAware1);
+
+ Assert.assertEquals(2, configurationImpl.getConfigurationAwareListSize());
+
+ ConfigurationAwareTest testConfigurationAware2 = new ConfigurationAwareTest();
+ configurationImpl.addConfigurationAware(testConfigurationAware2);
+
+ Assert.assertEquals(3, configurationImpl.getConfigurationAwareListSize());
+ ConfigurationAwareTest testConfigurationAware3 = new ConfigurationAwareTest();
+ configurationImpl.addConfigurationAware(testConfigurationAware3);
+
+ Assert.assertEquals(4, configurationImpl.getConfigurationAwareListSize());
+
+
+ configurationImpl.removeConfigurationAware(testConfigurationAware);
+ Assert.assertEquals(3, configurationImpl.getConfigurationAwareListSize());
+
+ configurationImpl.removeConfigurationAware(testConfigurationAware);
+ Assert.assertEquals(3, configurationImpl.getConfigurationAwareListSize());
+
+ configurationImpl.removeConfigurationAware(testConfigurationAware3);
+ Assert.assertEquals(2, configurationImpl.getConfigurationAwareListSize());
+
+ configurationImpl.removeConfigurationAware(testConfigurationAware1);
+ Assert.assertEquals(1, configurationImpl.getConfigurationAwareListSize());
+
+ configurationImpl.removeConfigurationAware(testConfigurationAware2);
+ Assert.assertEquals(0, configurationImpl.getConfigurationAwareListSize());
+
+ }
+
+}
/**
* Returns a list of Containers that currently exist.
*
- * @return array of String Container names
+ * @return array of String Container names
*/
public boolean hasNonDefaultContainer();
/**
* Returns a list of Containers that currently exist.
*
- * @return array of String Container names
+ * @return array of String Container names
*/
public List<String> getContainerNames();
* TODO : REMOVE THIS FUNCTION and make Save as a service rather than the
* current hack of calling individual save routines.
*
- * @return status code
+ * @return status code
*/
public Status saveContainerConfig();
}
\r
public class ContainerImplTest {\r
\r
- @Test\r
- public void test() {\r
- \r
- ContainerImpl container1 = new ContainerImpl();\r
- \r
- //Create Component for init\r
- ComponentImpl component1 = new ComponentImpl(null, null, null);\r
- component1.setInterface("serviceTestName", null);\r
-\r
- //container1 does not have name yet\r
- container1.init(component1);\r
- assertNull(container1.getName());\r
- \r
- //Sets container1 name to TestName\r
- Hashtable<String, String> properties = new Hashtable<String, String>();\r
- properties.put("dummyKey", "dummyValue");\r
- properties.put("containerName", "TestName");\r
- component1.setInterface("serviceTestName", properties);\r
-\r
- container1.init(component1);\r
- assertEquals("TestName", container1.getName());\r
- \r
- //getContainerFlows always returns null for now\r
- assertNull(container1.getContainerFlows());\r
- \r
- //getTag always returns 0 for now\r
- Node n = NodeCreator.createOFNode(1L);\r
- assertEquals(0, container1.getTag(n));\r
- \r
- //getNodeConnectors always returns null for now\r
- assertNull(container1.getNodeConnectors());\r
- \r
- //getNodes always returns null for now\r
- assertNull(container1.getNodes());\r
- \r
- }\r
+ @Test\r
+ public void test() {\r
+\r
+ ContainerImpl container1 = new ContainerImpl();\r
+\r
+ //Create Component for init\r
+ ComponentImpl component1 = new ComponentImpl(null, null, null);\r
+ component1.setInterface("serviceTestName", null);\r
+\r
+ //container1 does not have name yet\r
+ container1.init(component1);\r
+ assertNull(container1.getName());\r
+\r
+ //Sets container1 name to TestName\r
+ Hashtable<String, String> properties = new Hashtable<String, String>();\r
+ properties.put("dummyKey", "dummyValue");\r
+ properties.put("containerName", "TestName");\r
+ component1.setInterface("serviceTestName", properties);\r
+\r
+ container1.init(component1);\r
+ assertEquals("TestName", container1.getName());\r
+\r
+ //getContainerFlows always returns null for now\r
+ assertNull(container1.getContainerFlows());\r
+\r
+ //getTag always returns 0 for now\r
+ Node n = NodeCreator.createOFNode(1L);\r
+ assertEquals(0, container1.getTag(n));\r
+\r
+ //getNodeConnectors always returns null for now\r
+ assertNull(container1.getNodeConnectors());\r
+\r
+ //getNodes always returns null for now\r
+ assertNull(container1.getNodes());\r
+\r
+ }\r
\r
}\r
\r
public class ContainerManagerTest {\r
\r
- @Test\r
- public void test() {\r
- ContainerManager cm = new ContainerManager();\r
- \r
- cm.init();\r
- \r
- ArrayList<String> names = (ArrayList<String>) cm.getContainerNames();\r
- assertEquals(1, names.size());\r
- assertEquals(GlobalConstants.DEFAULT.toString(), names.get(0));\r
- \r
- assertFalse(cm.hasNonDefaultContainer());\r
- assertNull(cm.saveContainerConfig());\r
- \r
- cm.destroy();\r
-\r
- }\r
+ @Test\r
+ public void test() {\r
+ ContainerManager cm = new ContainerManager();\r
+\r
+ cm.init();\r
+\r
+ ArrayList<String> names = (ArrayList<String>) cm.getContainerNames();\r
+ assertEquals(1, names.size());\r
+ assertEquals(GlobalConstants.DEFAULT.toString(), names.get(0));\r
+\r
+ assertFalse(cm.hasNonDefaultContainer());\r
+ assertNull(cm.saveContainerConfig());\r
+\r
+ cm.destroy();\r
+\r
+ }\r
\r
}\r
import java.net.InetAddress;
import java.util.concurrent.ConcurrentMap;
/**
- *
+ *
* This interface provides APIs to configure and manage static routes.
*
*/
import org.opendaylight.controller.sal.utils.Status;
/**
- *
+ *
* This Interface provides APIs to manage and query the static routes
*
*/
public Status isValid() {
if ((name == null) || (name.trim().length() < 1)) {
return new Status(StatusCode.BADREQUEST,
- "Invalid Static Route name");
+ "Invalid Static Route name");
}
if (!isValidStaticRouteEntry()) {
return new Status(StatusCode.BADREQUEST,
- "Invalid Static Route entry. Please use the " +
- "IPAddress/mask format. Default gateway " +
- "(0.0.0.0/0) is NOT supported.");
+ "Invalid Static Route entry. Please use the " +
+ "IPAddress/mask format. Default gateway " +
+ "(0.0.0.0/0) is NOT supported.");
}
if (!isValidNextHop()) {
return new Status(StatusCode.BADREQUEST,
- "Invalid NextHop IP Address configuration. " +
- "Please use the X.X.X.X format.");
+ "Invalid NextHop IP Address configuration. " +
+ "Please use the X.X.X.X format.");
}
return new Status(StatusCode.SUCCESS, null);
}
}
-
+
private Status saveConfig() {
// Publish the save config event to the cluster nodes
configSaveEvent.put(new Date().getTime(), SAVE);
}
@SuppressWarnings("deprecation")
- private void allocateCaches() {
+ private void allocateCaches() {
if (this.clusterContainerService == null) {
log
.info("un-initialized clusterContainerService, can't create cache");
}
@SuppressWarnings("deprecation")
- private void destroyCaches() {
+ private void destroyCaches() {
if (this.clusterContainerService == null) {
log
.info("un-initialized clusterContainerService, can't destroy cache");
return status;
}
if (staticRouteConfigs.get(config.getName()) != null) {
- return new Status(StatusCode.CONFLICT,
- "A valid Static Route configuration with this name " +
- "already exists. Please use a different name");
+ return new Status(StatusCode.CONFLICT,
+ "A valid Static Route configuration with this name " +
+ "already exists. Please use a different name");
}
for (StaticRouteConfig s : staticRouteConfigs.values()) {
if (s.equals(config)) {
- return new Status(StatusCode.CONFLICT,
- "This conflicts with an existing Static Route " +
- "Configuration. Please check the configuration " +
- "and try again");
+ return new Status(StatusCode.CONFLICT,
+ "This conflicts with an existing Static Route " +
+ "Configuration. Please check the configuration " +
+ "and try again");
}
}
StaticRoute sRoute = new StaticRoute(config);
staticRoutes.put(config.getName(), sRoute);
checkAndUpdateListeners(sRoute, true);
- return status;
+ return status;
}
public Status removeStaticRoute(String name) {
checkAndUpdateListeners(sRoute, false);
return new Status(StatusCode.SUCCESS, null);
}
- return new Status(StatusCode.NOTFOUND,
- "Static Route with name " + name + " is not found");
+ return new Status(StatusCode.NOTFOUND,
+ "Static Route with name " + name + " is not found");
}
void setClusterContainerService(IClusterContainerServices s) {
import org.opendaylight.controller.sal.utils.StatusCode;
public class StaticRouteConfigTest {
-
- @Test
- public void testStaticRouteSetGet() {
- StaticRouteConfig staticRouteConfig1 = new StaticRouteConfig();
- staticRouteConfig1.setName("route");
- staticRouteConfig1.setStaticRoute("10.1.1.2/32");
- staticRouteConfig1.setNextHop("200.2.2.2");
- staticRouteConfig1.setNextHopType(NextHopType.IPADDRESS.toString());
- StaticRouteConfig staticRouteConfig2 = new StaticRouteConfig("route", "10.1.1.2/32", "200.2.2.2");
-
- Assert.assertEquals(staticRouteConfig2.getName(), staticRouteConfig1.getName());
- Assert.assertEquals(staticRouteConfig2.getStaticRoute(), staticRouteConfig1.getStaticRoute());
- Assert.assertEquals(staticRouteConfig2.getNextHop(), staticRouteConfig1.getNextHop());
- Assert.assertEquals("nexthop-ip", staticRouteConfig1.getNextHopType());
- }
-
- @Test
- public void testStaticRouteisValid() {
+
+ @Test
+ public void testStaticRouteSetGet() {
+ StaticRouteConfig staticRouteConfig1 = new StaticRouteConfig();
+ staticRouteConfig1.setName("route");
+ staticRouteConfig1.setStaticRoute("10.1.1.2/32");
+ staticRouteConfig1.setNextHop("200.2.2.2");
+ staticRouteConfig1.setNextHopType(NextHopType.IPADDRESS.toString());
+ StaticRouteConfig staticRouteConfig2 = new StaticRouteConfig("route", "10.1.1.2/32", "200.2.2.2");
+
+ Assert.assertEquals(staticRouteConfig2.getName(), staticRouteConfig1.getName());
+ Assert.assertEquals(staticRouteConfig2.getStaticRoute(), staticRouteConfig1.getStaticRoute());
+ Assert.assertEquals(staticRouteConfig2.getNextHop(), staticRouteConfig1.getNextHop());
+ Assert.assertEquals("nexthop-ip", staticRouteConfig1.getNextHopType());
+ }
+
+ @Test
+ public void testStaticRouteisValid() {
StaticRouteConfig staticRouteConfig1 = new StaticRouteConfig("route1", "10.1.1.254/24", "100.1.1.1");
- Status receivedResponse1 = staticRouteConfig1.isValid();
- Status expectedResponse1 = new Status(StatusCode.SUCCESS, null);
- Assert.assertEquals(expectedResponse1.toString(), receivedResponse1.toString());
-
+ Status receivedResponse1 = staticRouteConfig1.isValid();
+ Status expectedResponse1 = new Status(StatusCode.SUCCESS, null);
+ Assert.assertEquals(expectedResponse1.toString(), receivedResponse1.toString());
+
StaticRouteConfig staticRouteConfig2 = new StaticRouteConfig("", "", "100.1.1.1");
- Status receivedResponse2 = staticRouteConfig2.isValid();
- Status expectedResponse2 = new Status(StatusCode.BADREQUEST,
- "Invalid Static Route name");
- Assert.assertEquals(expectedResponse2.toString(), receivedResponse2.toString());
+ Status receivedResponse2 = staticRouteConfig2.isValid();
+ Status expectedResponse2 = new Status(StatusCode.BADREQUEST,
+ "Invalid Static Route name");
+ Assert.assertEquals(expectedResponse2.toString(), receivedResponse2.toString());
StaticRouteConfig staticRouteConfig3 = new StaticRouteConfig("route1", "10.1.1.254", "100.1.1.1");
- Status receivedResponse3 = staticRouteConfig3.isValid();
- Status expectedResponse3 = new Status(StatusCode.BADREQUEST,
- "Invalid Static Route entry. Please use the " +
- "IPAddress/mask format. Default gateway " +
- "(0.0.0.0/0) is NOT supported.");
- Assert.assertEquals(expectedResponse3.toString(), receivedResponse3.toString());
+ Status receivedResponse3 = staticRouteConfig3.isValid();
+ Status expectedResponse3 = new Status(StatusCode.BADREQUEST,
+ "Invalid Static Route entry. Please use the " +
+ "IPAddress/mask format. Default gateway " +
+ "(0.0.0.0/0) is NOT supported.");
+ Assert.assertEquals(expectedResponse3.toString(), receivedResponse3.toString());
StaticRouteConfig staticRouteConfig4 = new StaticRouteConfig("route1", "289.1.1.254/24", "100.1.1.1");
- Status receivedResponse4 = staticRouteConfig4.isValid();
- Status expectedResponse4 = new Status(StatusCode.BADREQUEST,
- "Invalid Static Route entry. Please use the " +
- "IPAddress/mask format. Default gateway " +
- "(0.0.0.0/0) is NOT supported.");
- Assert.assertEquals(expectedResponse4.toString(), receivedResponse4.toString());
-
+ Status receivedResponse4 = staticRouteConfig4.isValid();
+ Status expectedResponse4 = new Status(StatusCode.BADREQUEST,
+ "Invalid Static Route entry. Please use the " +
+ "IPAddress/mask format. Default gateway " +
+ "(0.0.0.0/0) is NOT supported.");
+ Assert.assertEquals(expectedResponse4.toString(), receivedResponse4.toString());
+
StaticRouteConfig staticRouteConfig5 = new StaticRouteConfig("route1", "10.1.1.254/24", "100.1.1");
- Status receivedResponse5 = staticRouteConfig5.isValid();
- Status expectedResponse5 = new Status(StatusCode.BADREQUEST,
- "Invalid NextHop IP Address configuration. " +
- "Please use the X.X.X.X format.");
- Assert.assertEquals(expectedResponse5.toString(), receivedResponse5.toString());
- }
-
- @Test
- public void testGetStaticRouteIP() {
+ Status receivedResponse5 = staticRouteConfig5.isValid();
+ Status expectedResponse5 = new Status(StatusCode.BADREQUEST,
+ "Invalid NextHop IP Address configuration. " +
+ "Please use the X.X.X.X format.");
+ Assert.assertEquals(expectedResponse5.toString(), receivedResponse5.toString());
+ }
+
+ @Test
+ public void testGetStaticRouteIP() {
StaticRouteConfig staticRouteConfig1 = new StaticRouteConfig("route1", "10.1.1.0/24", "100.1.1.1");
InetAddress ip1 = staticRouteConfig1.getStaticRouteIP();
- Assert.assertEquals("10.1.1.0", ip1.getHostAddress());
-
+ Assert.assertEquals("10.1.1.0", ip1.getHostAddress());
+
StaticRouteConfig staticRouteConfig2 = new StaticRouteConfig("route1", "10.1.1.0/80", "100.1.1.1");
InetAddress ip2 = staticRouteConfig2.getStaticRouteIP();
- Assert.assertEquals(null, ip2);
+ Assert.assertEquals(null, ip2);
+
+ }
- }
-
- @Test
- public void testGetStaticRouteMask() {
+ @Test
+ public void testGetStaticRouteMask() {
StaticRouteConfig staticRouteConfig1 = new StaticRouteConfig("route1", "10.1.1.0/24", "100.1.1.1");
- Short receivedMaskLen1 = staticRouteConfig1.getStaticRouteMask();
- Short expectedMaskLen1 = 24;
- Assert.assertEquals(expectedMaskLen1, receivedMaskLen1);
-
- StaticRouteConfig staticRouteConfig2 = new StaticRouteConfig("route1", "10.1.1.0/40", "100.1.1.1");
- Short receivedMaskLen2 = staticRouteConfig2.getStaticRouteMask();
- Short expectedMaskLen2 = 0;
- Assert.assertEquals(expectedMaskLen2, receivedMaskLen2);
- }
-
- @Test
- public void testGetNextHopIP() {
+ Short receivedMaskLen1 = staticRouteConfig1.getStaticRouteMask();
+ Short expectedMaskLen1 = 24;
+ Assert.assertEquals(expectedMaskLen1, receivedMaskLen1);
+
+ StaticRouteConfig staticRouteConfig2 = new StaticRouteConfig("route1", "10.1.1.0/40", "100.1.1.1");
+ Short receivedMaskLen2 = staticRouteConfig2.getStaticRouteMask();
+ Short expectedMaskLen2 = 0;
+ Assert.assertEquals(expectedMaskLen2, receivedMaskLen2);
+ }
+
+ @Test
+ public void testGetNextHopIP() {
StaticRouteConfig staticRouteConfig1 = new StaticRouteConfig("route1", "10.1.1.254/24", "100.1.1.1");
InetAddress ip1 = staticRouteConfig1.getNextHopIP();
- Assert.assertEquals("100.1.1.1", ip1.getHostAddress());
+ Assert.assertEquals("100.1.1.1", ip1.getHostAddress());
- StaticRouteConfig staticRouteConfig2 = new StaticRouteConfig("route1", "10.1.1.254/24", "100.1.1");
+ StaticRouteConfig staticRouteConfig2 = new StaticRouteConfig("route1", "10.1.1.254/24", "100.1.1");
InetAddress ip2 = staticRouteConfig2.getNextHopIP();
- Assert.assertEquals(null, ip2);
- }
-
-}
+ Assert.assertEquals(null, ip2);
+ }
+}
import org.opendaylight.controller.sal.utils.NodeCreator;
public class StaticRouteTest {
-
- @Test
- public void testStaticRouteGetSet() {
- StaticRoute staticRoute = new StaticRoute();
- InetAddress networkAddress = null;
- InetAddress mask = null;
- InetAddress nextHopAddress = null;
- try {
- networkAddress = InetAddress.getByName("10.1.1.0");
- mask = InetAddress.getByName("255.255.255.0");
- nextHopAddress = InetAddress.getByName("200.0.0.1");
-
- } catch (UnknownHostException e) {
- Assert.assertTrue(false);
- }
- staticRoute.setNetworkAddress(networkAddress);
- Assert.assertEquals(networkAddress.getHostAddress(), staticRoute.getNetworkAddress().getHostAddress());
- staticRoute.setMask(mask);
- Assert.assertEquals(mask.getHostAddress(), staticRoute.getMask().getHostAddress());
- staticRoute.setType(NextHopType.IPADDRESS);
- Assert.assertEquals("nexthop-ip", staticRoute.getType().toString());
- staticRoute.setNextHopAddress(nextHopAddress);
- Assert.assertEquals(nextHopAddress.getHostAddress(), staticRoute.getNextHopAddress().getHostAddress());
- Node node = NodeCreator.createOFNode(((long)10));
- staticRoute.setNode(node);
- Assert.assertEquals(node, staticRoute.getNode());
- NodeConnector nc0 = NodeConnectorCreator.createOFNodeConnector((short)20, node);
- staticRoute.setPort(nc0);
- Assert.assertEquals(nc0, staticRoute.getPort());
+
+ @Test
+ public void testStaticRouteGetSet() {
+ StaticRoute staticRoute = new StaticRoute();
+ InetAddress networkAddress = null;
+ InetAddress mask = null;
+ InetAddress nextHopAddress = null;
+ try {
+ networkAddress = InetAddress.getByName("10.1.1.0");
+ mask = InetAddress.getByName("255.255.255.0");
+ nextHopAddress = InetAddress.getByName("200.0.0.1");
+
+ } catch (UnknownHostException e) {
+ Assert.assertTrue(false);
+ }
+ staticRoute.setNetworkAddress(networkAddress);
+ Assert.assertEquals(networkAddress.getHostAddress(), staticRoute.getNetworkAddress().getHostAddress());
+ staticRoute.setMask(mask);
+ Assert.assertEquals(mask.getHostAddress(), staticRoute.getMask().getHostAddress());
+ staticRoute.setType(NextHopType.IPADDRESS);
+ Assert.assertEquals("nexthop-ip", staticRoute.getType().toString());
+ staticRoute.setNextHopAddress(nextHopAddress);
+ Assert.assertEquals(nextHopAddress.getHostAddress(), staticRoute.getNextHopAddress().getHostAddress());
+ Node node = NodeCreator.createOFNode(((long)10));
+ staticRoute.setNode(node);
+ Assert.assertEquals(node, staticRoute.getNode());
+ NodeConnector nc0 = NodeConnectorCreator.createOFNodeConnector((short)20, node);
+ staticRoute.setPort(nc0);
+ Assert.assertEquals(nc0, staticRoute.getPort());
InetAddress ip1 = null;
HostNodeConnector h1 = null;
try {
}
staticRoute.setHost(h1);
Assert.assertEquals(h1, staticRoute.getHost());
- }
-
- @Test
- public void testStaticRouteComparison() {
+ }
+
+ @Test
+ public void testStaticRouteComparison() {
StaticRouteConfig staticRouteConfig1 = new StaticRouteConfig("route1", "10.1.1.0/24", "100.1.1.1");
StaticRouteConfig staticRouteConfig2 = new StaticRouteConfig("route2", "10.1.1.0/24", "100.2.1.1");
StaticRouteConfig staticRouteConfig3 = new StaticRouteConfig("route3", "10.2.1.0/24", "100.3.1.1");
Assert.assertTrue(staticRoute1.equals(staticRoute2));
Assert.assertFalse(staticRoute1.equals(staticRoute3));
Assert.assertFalse(staticRoute1.equals(staticRoute4));
-
+
Assert.assertTrue(staticRoute1.compareTo(staticRoute2) == 0 ? true : false);
Assert.assertFalse(staticRoute1.compareTo(staticRoute3) == 0 ? true : false);
Assert.assertTrue(staticRoute1.compareTo(staticRoute4) == 0 ? true : false);
-
- }
-
- @Test
- public void testLongestPrefixMatch() {
+
+ }
+
+ @Test
+ public void testLongestPrefixMatch() {
StaticRouteConfig staticRouteConfig1 = new StaticRouteConfig("route1", "10.1.1.254/24", "100.1.1.1");
StaticRoute staticRoute1 = new StaticRoute(staticRouteConfig1);
- InetAddress ip1 = null;
- InetAddress ip2 = null;
- try {
- ip1 = InetAddress.getByName("10.1.0.2");
- ip2 = InetAddress.getByName("10.1.1.2");
- } catch (UnknownHostException e) {
- Assert.assertTrue(false);
- }
+ InetAddress ip1 = null;
+ InetAddress ip2 = null;
+ try {
+ ip1 = InetAddress.getByName("10.1.0.2");
+ ip2 = InetAddress.getByName("10.1.1.2");
+ } catch (UnknownHostException e) {
+ Assert.assertTrue(false);
+ }
InetAddress rxdIp1 = staticRoute1.longestPrefixMatch(ip1);
InetAddress rxdIp2 = staticRoute1.longestPrefixMatch(ip2);
- Assert.assertEquals(null, rxdIp1);
- Assert.assertEquals("10.1.1.0", rxdIp2.getHostAddress());
- }
+ Assert.assertEquals(null, rxdIp1);
+ Assert.assertEquals("10.1.1.0", rxdIp2.getHostAddress());
+ }
}
import org.junit.Test;
public class StaticRoutingImplementationTest {
-
- @Test
- public void isIPv4AddressValidTest() {
- StaticRoutingImplementation staticRouteImpl = new StaticRoutingImplementation();
- Assert.assertTrue(staticRouteImpl.isIPv4AddressValid("192.168.100.0/24"));
- Assert.assertFalse(staticRouteImpl.isIPv4AddressValid("192.168.100.0/36"));
- Assert.assertFalse(staticRouteImpl.isIPv4AddressValid("192.168.300.0/32"));
- }
-}
-
-
-
+ @Test
+ public void isIPv4AddressValidTest() {
+ StaticRoutingImplementation staticRouteImpl = new StaticRoutingImplementation();
+ Assert.assertTrue(staticRouteImpl.isIPv4AddressValid("192.168.100.0/24"));
+ Assert.assertFalse(staticRouteImpl.isIPv4AddressValid("192.168.100.0/36"));
+ Assert.assertFalse(staticRouteImpl.isIPv4AddressValid("192.168.300.0/32"));
+ }
+}
/**
* Return the actual Flow contained in this entry
- *
+ *
* @return the flow
*/
public Flow getFlow() {
/**
* Merges the current Flow with the passed Container Flow
- *
+ *
* Note: Container Flow merging is not an injective function. Be m1 and m2
* two different matches, and be f() the flow merge function, such that y1 =
* f(m1) and y2 = f(m2) are the two merged matches, we may have: y1 = y2
- *
- *
+ *
+ *
* @param containerFlow
* @return this merged FlowEntry
*/
* install, the container flow with which that entry had to be merged and the
* resultant merged flow entry, which is the one that was eventually installed
* on the network node
- *
+ *
* Note: If the container flow is null, the install entry will be a clone of the
* original entry
- *
+ *
*/
public class FlowEntryInstall {
private FlowEntry original;
public void setRequestId(long rid) {
this.requestId = rid;
}
-
+
public long getRequestId() {
return requestId;
}
/**
* Interface that describes methods for installing or removing forwarding rules
* and to access to the flows database.
- *
+ *
*/
public interface IForwardingRulesManager {
* SDN protocol plugin to install the flow on the network node. Based on the
* result of this operation FRM will update its database accordingly and
* will return the proper {@code Status} code.
- *
+ *
* @param flow
* the flow entry to install
* @return the {@code Status} object indicating the result of this action.
* protocol plugin to uninstall the flow from the network node. Based on the
* result of this operation FRM will update its database accordingly and
* will return the proper {@code Status} code.
- *
+ *
* @param flow
* the flow entry to uninstall
* @return the {@code Status} object indicating the result of this action
* modify message depending on the SDN protocol specifications If the
* current flow is equal to the new one it will be a no op and success code
* is returned.
- *
+ *
* @param current
* the current flow entry to modify
* @param newone
* it, it will request plugin to add the new flow. If the passed entry is
* not valid an error code is returned. If the existing flow is equal to the
* passed one it will be a no op and success code is returned.
- *
- *
+ *
+ *
* @param newone
* the new flow entry to install
* @return the {@code Status} object indicating the result of this action
* SDN protocol plugin to install the flow on the network node. As immediate
* result of this asynchronous call, FRM will update its flow database as if
* the flow was successfully installed.
- *
+ *
* @param flow
* the flow entry to install
* @return the status of this request containing the request id associated
* SDN protocol plugin to uninstall the flow from the network node. As
* immediate result of this asynchronous call, FRM will update its flow
* database as if the flow was successfully installed.
- *
+ *
* @param flow
* the flow entry to uninstall
* @return the status of this request containing the unique id associated to
* this message to the network node. It could be a delete + add or a single
* modify message depending on the SDN protocol specifications. If the
* current flow is equal to the new one it will be a no op.
- *
+ *
* @param current
* the current flow entry to modify
* @param newone
* it, it will request plugin to add the new flow. If the passed entry is
* not valid a zero request id is returned. If the existing flow is equal to
* the passed one it will be a no op.
- *
+ *
* @param newone
* the new flow entry to install
* @return the unique id associated to this request. In case of not
* blocked until the solicitation response is received from the network node
* or receive timeout. Otherwise, it is a non-blocking call and does not
* guarantee the node will respond in any given time.
- *
+ *
* @param node
* The network node to solicit a response
* @param blocking
/**
* Check whether the passed flow entry conflicts with the Container flows
- *
+ *
* @param flow
* the flow entry to test
* @return true if conflicts, false otherwise
/**
* Returns the list of Flow entries across network nodes which are part of
* the same flow group, policy
- *
+ *
* @param group
* the group name
* @return the list of flow entries belonging to the specified group
/**
* Add a list of output port to the flow with the specified name on the
* specified network node
- *
+ *
* @param node
* the network node
* @param flowName
/**
* Remove a list of output port from the flow with the specified name on the
* specified network node
- *
+ *
* @param node
* the network node
* @param flowName
/**
* Replace the current output port in the specified flow with the specified
* one
- *
+ *
* @param node
* the network node
* @param groupName
/**
* Returns the output port configured on the specified flow
- *
+ *
* @param node
* the network node
* @param flowName
* Returns all the troubleshooting information that applications have set
* along with the policy they have configured through forwarding rules
* manger.
- *
+ *
* @return the collection of troubleshooting objects
*/
public Map<String, Object> getTSPolicyData();
/**
* Set the troubleshooting information for the policy
- *
+ *
* @param policyname
* the flow group name
* @param o
/**
* Returns the troubleshooting information that was set for the specified
* policy
- *
+ *
* @param groupName
* the flows group name
* @return the troubleshooting info object
/**
* Returns the specifications of all the flows configured for all the
* switches on the current container
- *
+ *
* @return the list of flow configurations present in the database
*/
public List<FlowConfig> getStaticFlows();
/**
* Returns the specifications of all the flows configured for the given
* switch on the current container
- *
+ *
* @param node
* the network node identifier
* @return the list of {@code FlowConfig} objects
/**
* Returns the specification of the flow configured for the given network
* node on the current container
- *
+ *
* @param name
* the flow name
* @param n
/**
* Returns the list of names of flows configured for the given Network node
* on the current container
- *
+ *
* @param node
* the network node identifier
* @return the list of flow names
/**
* Returns the list of Node(s) for which a static flow has been configured
- *
+ *
* @return the list of network nodes
*/
public List<Node> getListNodeWithConfiguredFlows();
/**
* Save the flow configured so far to file
- *
+ *
* @return the {@code Status} object indicating the result of this action.
*/
public Status saveConfig();
/**
* Add a flow specified by the {@code FlowConfig} object on the current
* container
- *
+ *
* @param config
* the {@code FlowConfig} object representing the static flow
* @param restore
/**
* Remove a flow specified by the {@code FlowConfig} object on the current
* container
- *
+ *
* @param config
* the {@code FlowConfig} object representing the static flow
* @return the {@code Status} object indicating the result of this action
* Replace the flow identified by the {@code FlowConfig.name} name for the
* {@code FlowConfig.node} network node with the new flow specified by
* {@code FlowConfig} object
- *
+ *
* @param config
* the {@code FlowConfig} object
* @returnthe {@code Status} object indicating the result of this action
/**
* Remove the flow specified by name on the passed network node
- *
+ *
* @param name
* for the static flow
* @param node
* Toggle the installation status of the specified configured flow If the
* flow configuration status is active, this call will change the flow
* status to inactive and vice-versa
- *
+ *
* @param configObject
* the {@code FlowConfig} object
* @return the {@code Status} object indicating the result of this action
* Toggle the installation status of the specified configured flow If the
* flow configuration status is active, this call will change the flow
* status to inactive and vice-versa
- *
+ *
* @param name
* for the static flow
* @param node
/**
* The interface which describes the methods forwarding rules manager will call
* for notifying the listeners of policy installation updates.
- *
+ *
*/
public interface IForwardingRulesManagerAware {
/**
* Inform the listeners that a troubleshooting information was added or
* removed for the specified policy.
- *
+ *
* @param policyName
* the policy affected
* @param add
* Inform listeners that the network node has notified us about a failure in
* executing the controller generated asynchronous request identified by the
* passed unique id.
- *
+ *
* @param requestId
* the unique id associated with the request which failed to be
* executed on the network node
/**
* PortGroup is a simple data-structure to represent any arbitrary group of
* ports on a Switch (that is represented using its switch-ID).
- *
+ *
* PortGroup is used by PortGroupProvider application to signal a set of ports
* that represent a configured PortGroupConfig.
- *
- *
+ *
+ *
*/
public class PortGroup {
private long matrixSwitchId;
/**
* PortGroup Constructor using Switch and Ports.
- *
+ *
* @param matrixSwitchId
* Switch Id that represents an openflow Switch
* @param ports
/**
* PortGroup Constructor using Switch.
- *
+ *
* @param matrixSwitchId
* Switch-Id that represents an openflow Switch
*/
/**
* Returns the switchId representing the Switch that makes this PortGroup.
- *
+ *
* @return long switchId
*/
public long getMatrixSwitchId() {
/**
* Assigns a Switch to this PortGroup
- *
+ *
* @param matrixSwitchId
* Switch-Id that represents an openflow Switch
*/
/**
* Returns the Set of Ports that makes this PortGroup.
- *
+ *
* @return Set of short values representing openflow port-ids.
*/
public Set<Short> getPorts() {
/**
* Assigns a set of openflow ports to this PortGroup
- *
+ *
* @param ports
* Set of short values representing openflow port-ids.
*/
/**
* Adds a port to this PortGroup
- *
+ *
* @param port
* Short value of a openflow port.
*/
/**
* PortGroupChangeListener listens to the PortGroup updates provided by the
* PortGroupProvider.
- *
- *
+ *
+ *
*/
public interface PortGroupChangeListener {
/**
* This method is invoked by PortGroupProvider whenever it detects a change
* in PortGroup membership for a given PortGroupConfig.
- *
+ *
* @param config
* Port Group Configuration
* @param portGroupData
/**
* PortGroupConfig class represents the User's Configuration with a Opaque
* Regular Expression String that is parsed and handled by PortGroupProvider.
- *
+ *
* Typically, the opaque matchString will be a Regular Expression String
* supported by a particular PortGroupProvider based on Customer requirements.
- *
- *
- *
+ *
+ *
+ *
*/
public class PortGroupConfig implements Serializable {
private static final long serialVersionUID = 1L;
/**
* Constructor to create a Port Group Configuration using a Group Name and
* an Opaque String that is managed by PortGroupProvider.
- *
+ *
* @param name
* Group Name representing a Port Group configuration
* @param matchString
/**
* Returns the user configured PortGroup Configuration name.
- *
+ *
* @return Configuration Name
*/
public String getName() {
/**
* Assigns a name to the configuration
- *
+ *
* @param name
* configuration name
*/
/**
* Returns the Opaque string
- *
+ *
* @return
*/
public String getMatchString() {
/**
* Assigns an opaque String to the Configuration.
- *
+ *
* @param matchString
* Opaque string handled by PortGroupProvider
*/
/**
* Returns the names of all the configurable fields in PortGroupConfig. This
* method is typically used by NorthBound apis.
- *
+ *
* @return List of Field names that can be configured.
*/
public static List<String> getFieldsNames() {
* Returns the names of all the configurable fields in PortGroupConfig in
* human readable format for UI purposes. This method is typically used by
* Web/UI apis.
- *
+ *
* @return List of Human readable Strings that corresponds to the
* configurable field names.
*/
* application to implement in order to provide Port Grouping Service. Custom
* Application that implements this interface will have to handle the opaque
* match criteria passed to it via PortGroupConfig.
- *
- *
- *
+ *
+ *
+ *
*/
public interface PortGroupProvider {
/**
* This method is invoked by the Controller towards the Provider when a new
* port group is configured.
- *
+ *
* @param config
* New PortGroupConfig object created by user Configuration.
* @return true if successful. false otherwise.
/**
* This method is invoked by the Controller towards the Provider when an
* existing port group is deleted.
- *
+ *
* @param config
* Existing Port Group Configuration deleted by the user.
* @return true if successful. false otherwise.
* Configuration. Its the PortGroupProvider Application's responsibility to
* manage the Switches & the Set of its Ports that correspond to each of the
* Configuration and return it to the Controller when requested.
- *
+ *
* @param config
* User Configuration
* @see PortGroupConfig
* PortGroupProvider Application's responsibility to manage the Switches &
* the Set of its Ports that correspond to each of the Configuration and
* return it to the Controller when requested.
- *
+ *
* @param config
* User Configuration
* @param matrixSwitchId
/**
* Registers a Listener for Port Group membership changes based on Custom
* application algorithm.
- *
+ *
* @param listener
* A Controller module that listens to events from the Custom
* Port Grouping Application.
* implement Custom Algorithm for Port Grouping. This method exposes the
* custom algorithm to the user so that the user can configure the
* matchString regular expression in PortGroupConfig appropriately.
- *
+ *
* @return Usage string.
*/
public String getApplicationDrivenMatchCriteriaUsage();
/**
* Returns the name of the Custom Application that implements
* PortGroupProvider interface.
- *
+ *
* @return Provider Name
*/
public String getProviderName();
/**
* Controller uses this method to check with the Provider supports the
* matchCriteria String configured by the User.
- *
+ *
* @param matchCriteria
* @return true if the Provider supports the matchCriteria String. false
* otherwise.
/**
* Function called when the activator starts just after some initializations
* are done by the ComponentActivatorAbstractBase.
- *
+ *
*/
public void init() {
/**
* Function called when the activator stops just before the cleanup done by
* ComponentActivatorAbstractBase
- *
+ *
*/
public void destroy() {
/**
* Function that is used to communicate to dependency manager the list of
* known implementations for services inside a container
- *
- *
+ *
+ *
* @return An array containing all the CLASS objects that will be
* instantiated in order to get an fully working implementation
* Object
/**
* Function that is called when configuration of the dependencies is
* required.
- *
+ *
* @param c
* dependency manager Component object, used for configuring the
* dependencies exported and imported
* Adds a flow entry onto the network node It runs various validity checks
* and derive the final container flows merged entries that will be
* attempted to be installed
- *
+ *
* @param flowEntry
* the original flow entry application requested to add
* @param async
* will contain the unique id assigned to this request
*/
private Status addEntry(FlowEntry flowEntry, boolean async) {
-
+
// Sanity Check
if (flowEntry == null || flowEntry.getNode() == null) {
String msg = "Invalid FlowEntry";
* complication for now and assume we will always deal with
* one flow only per request
*/
- succeded = ret;
+ succeded = ret;
} else {
error = ret;
log.warn("Failed to install the entry: {}. The failure is: {}",
* flow entry is congruent with all the N container flows, then the output
* install entry list will contain N entries. If the output list is empty,
* it means the passed flow entry conflicts with all the container flows.
- *
+ *
* @param cFlowList
* The list of container flows
* @return the list of container flow merged entries good to be installed on
/**
* Modify a flow entry with a new one It runs various validity check and
* derive the final container flows merged flow entries to work with
- *
+ *
* @param currentFlowEntry
* @param newFlowEntry
* @param async
* This is only possible when the new entry and current entry have
* different match. In this scenario the modification would ultimately
* be handled as a remove and add operations in the protocol plugin.
- *
+ *
* Also, if any of the new flow entries would clash with an existing
* one, we cannot proceed with the modify operation, because it would
* fail for some entries and leave stale entries on the network node.
* Modify path can be taken only if it can be performed completely, for
* all entries.
- *
+ *
* So, for the above two cases, to simplify, let's decouple the modify
* in: 1) remove current entries 2) install new entries
*/
* (and might be wrong) that the same container flows that were
* satisfied by the current entries are the same that are satisfied
* by the new entries. Let's take the risk for now.
- *
+ *
* Note: modification has to be complete. If any entry modification
* fails, we need to stop, restore the already modified entries, and
* declare failure.
* This is the function that modifies the final container flows merged
* entries on the network node and update the database. It expects that all
* the validity checks are passed
- *
+ *
* @param currentEntries
* @param newEntries
* @param async
private Status modifyEntryInternal(FlowEntryInstall currentEntries,
FlowEntryInstall newEntries, boolean async) {
// Modify the flow on the network node
- Status status = (async)?
+ Status status = (async)?
programmer.modifyFlowAsync(currentEntries.getNode(),
currentEntries.getInstall().getFlow(), newEntries.getInstall()
.getFlow()) :
/**
* Remove a flow entry. If the entry is not present in the software view
* (entry or node not present), it return successfully
- *
+ *
* @param flowEntry
* the flow entry to remove
* @param async
* This is the function that removes the final container flows merged entry
* from the network node and update the database. It expects that all the
* validity checks are passed
- *
+ *
* @param entry
* the flow entry to remove
* @param async
.getInstall().getFlow()) :
programmer.removeFlow(entry.getNode(), entry
.getInstall().getFlow());
-
+
if (!status.isSuccess()) {
log.warn(
* on the network node and updates the database. It expects that all the
* validity and conflict checks are passed. That means it does not check
* whether this flow would conflict or overwrite an existing one.
- *
+ *
* @param entry
* the flow entry to install
* @param async
* means that if the function returns true, the passed flow entry is
* congruent with at least one container flow, hence it is good to be
* installed on this container.
- *
+ *
* @param flowEntry
* @return true if flow conflicts with all the container flows, false
* otherwise
}
return status;
}
-
+
@Override
public Status modifyFlowEntry(FlowEntry currentFlowEntry,
FlowEntry newFlowEntry) {
}
}
-
+
/**
* Try to find in the database if a Flow with the same Match and priority of
* the passed one already exists for the specified network node. Flow,
* priority and network node are all specified in the FlowEntry If found,
* the respective FlowEntryInstall Object is returned
- *
+ *
* @param flowEntry
* the FlowEntry to be tested against the ones installed
* @param looseCheck
* multiple entry configuration (PortGroup) and hardware installation is
* NOT done directly on this event. 3. The User prefers to retain the
* configuration in Controller and skip hardware installation.
- *
+ *
* Hence it is safe to update the StaticFlow DB at this point.
- *
+ *
* Note : For the case of PortGrouping, it is essential to have this DB
* populated before the PortGroupListeners can query for the DB
* triggered using portGroupChanged event...
/**
* Remove from the databases all the flows installed on the node
- *
+ *
* @param node
*/
private synchronized void cleanDatabaseForNode(Node node) {
/**
* Function called by the dependency manager when all the required
* dependencies are satisfied
- *
+ *
*/
void init() {
frmAware = Collections
* Function called by the dependency manager when at least one dependency
* become unsatisfied or when the component is shutting down because for
* example bundle is being stopped.
- *
+ *
*/
void destroy() {
destroyCaches();
/**
* Function called by dependency manager after "init ()" is called and after
* the services provided by the class are registered in the service registry
- *
+ *
*/
void start() {
/*
* Function called by the dependency manager before the services exported by
* the component are unregistered, this will be followed by a "destroy ()"
* calls
- *
+ *
*/
void stop() {
}
/*
* If this was for a flow install, remove the corresponding entry
* from the software view. If it was a Looking for the rid going through the
- * software database.
- * TODO: A more efficient rid <-> FlowEntryInstall mapping will
+ * software database.
+ * TODO: A more efficient rid <-> FlowEntryInstall mapping will
* have to be added in future
*/
Set<FlowEntryInstall> entries = nodeFlows.get(node);
this.updateLocalDatabase(target, false);
}
}
-
+
// Notify listeners
if (frmAware != null) {
synchronized (frmAware) {
}
}
}
-
+
@Override
public Status solicitStatusResponse(Node node, boolean blocking) {
Status rv = new Status(StatusCode.INTERNALERROR);
-
+
if (this.programmer != null) {
if (blocking) {
rv = programmer.syncSendBarrierMessage(node);
} else {
- rv = programmer.asyncSendBarrierMessage(node);
+ rv = programmer.asyncSendBarrierMessage(node);
}
}
-
+
return rv;
}
}
* of coming up a new Host. For the hosts which it has already
* learned, it refreshes them.
*
- * @param host Host info encapsulated in HostNodeConnector class
+ * @param host Host info encapsulated in HostNodeConnector class
*/
public void hostListener(HostNodeConnector host);
}
* Northbound APIs. If a binding is unknown, then an ARP request is initiated
* immediately to discover the host.
*
- * @param networkAddress IP Address of the Host encapsulated in class InetAddress
- * @return {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector}
- * Class that contains the Host info such as its MAC address,
- * Switch ID, port, VLAN. If Host is not found, returns NULL
+ * @param networkAddress IP Address of the Host encapsulated in class InetAddress
+ * @return {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector}
+ * Class that contains the Host info such as its MAC address,
+ * Switch ID, port, VLAN. If Host is not found, returns NULL
*/
public HostNodeConnector hostFind(InetAddress networkAddress);
* Checks the local Host Database to see if a Host has been learned for a
* given IP address.
*
- * @param networkAddress IP Address of the Host encapsulated in class InetAddress
- * @return {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector}
- * Class that contains the Host info such as its MAC address,
- * Switch ID, port, VLAN. If Host is not found, returns NULL
+ * @param networkAddress IP Address of the Host encapsulated in class InetAddress
+ * @return {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector}
+ * Class that contains the Host info such as its MAC address,
+ * Switch ID, port, VLAN. If Host is not found, returns NULL
*
*/
public HostNodeConnector hostQuery(InetAddress networkAddress);
* Initiates an immediate discovery of the Host for a given IP address. This
* provides for the calling applications to block on the host discovery.
*
- * @param networkAddress IP address encapsulated in InetAddress class
- * @return Future {@link org.opendaylight.controller.hosttracker.HostTrackerCallable}
+ * @param networkAddress IP address encapsulated in InetAddress class
+ * @return Future {@link org.opendaylight.controller.hosttracker.HostTrackerCallable}
*/
public Future<HostNodeConnector> discoverHost(InetAddress networkAddress);
* Returns the Network Hierarchy for a given Host. This API is typically used by
* applications like Hadoop for Rack Awareness functionality.
*
- * @param IP address of the Host encapsulated in InetAddress class
- * @return List of String ArrayList containing the Hierarchies.
+ * @param IP address of the Host encapsulated in InetAddress class
+ * @return List of String ArrayList containing the Hierarchies.
*/
public List<List<String>> getHostNetworkHierarchy(InetAddress hostAddress);
* Returns all the the Hosts either learned dynamically or added statically via
* Northbound APIs.
*
- * @return Set of {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector}.
- * Class that contains the Host info such as its MAC address,
- * Switch ID, port, VLAN.
+ * @return Set of {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector}.
+ * Class that contains the Host info such as its MAC address,
+ * Switch ID, port, VLAN.
*/
public Set<HostNodeConnector> getAllHosts();
* are categorized as "Active" because the Switch and Port they are connected to, are in
* up state.
*
- * @return Set of {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector}.
- * Class that contains the Host info such as MAC address,
- * Switch ID, port, VLAN. If Host is not found, returns NULL
+ * @return Set of {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector}.
+ * Class that contains the Host info such as MAC address,
+ * Switch ID, port, VLAN. If Host is not found, returns NULL
*/
public Set<HostNodeConnector> getActiveStaticHosts();
* are categorized as "Inactive" because either the Switch or the Port they are connected
* to, is in down state.
*
- * @return Set of HostNodeConnector {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector}.
- * HostNodeConnector is Class that
- * contains the Host info such as its MAC address, OpenFlowNode
- * ID, port, VLAN.
+ * @return Set of HostNodeConnector {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector}.
+ * HostNodeConnector is Class that
+ * contains the Host info such as its MAC address, OpenFlowNode
+ * ID, port, VLAN.
*/
public Set<HostNodeConnector> getInactiveStaticHosts();
* Hosts can be learned dynamically or added statically. This method allows the addition
* of a Host to the local database statically.
*
- * @param networkAddress IP Address of the Host
- * @param dataLayerAddress MAC Address of the Host
- * @param nc NodeConnector to which the host is attached
- * @param vlan VLAN the host belongs to
- * @return The status object as described in {@code Status}
- * indicating the result of this action.
+ * @param networkAddress IP Address of the Host
+ * @param dataLayerAddress MAC Address of the Host
+ * @param nc NodeConnector to which the host is attached
+ * @param vlan VLAN the host belongs to
+ * @return The status object as described in {@code Status}
+ * indicating the result of this action.
*/
public Status addStaticHost(String networkAddress, String dataLayerAddress,
NodeConnector nc, String vlan);
* Allows the deletion of statically learned Host
*
* @param networkAddress
- * @return The status object as described in {@code Status}
- * indicating the result of this action.
+ * @return The status object as described in {@code Status}
+ * indicating the result of this action.
*/
public Status removeStaticHost(String networkAddress);
}
/**
* This Interface defines the methods for client applications of
- * Host Tracker to get notifications when a new host is learned or
+ * Host Tracker to get notifications when a new host is learned or
* existing host is removed from the network.
*
*/
/**
* Notifies the HostTracker Clients that a new Host has been learned
*
- * @param host Host Info encapsulated in HostNodeConnector class
+ * @param host Host Info encapsulated in HostNodeConnector class
*/
public void notifyHTClient(HostNodeConnector host);
* the past has been removed either due to switch/port down event or
* due to ARP Aging
*
- * @param host Host Info encapsulated in HostNodeConnector class
+ * @param host Host Info encapsulated in HostNodeConnector class
*/
public void notifyHTClientHostRemoved(HostNodeConnector host);
}
* by query of an application to the HostTracker. The requested IP address
* doesn't exist in the local database at this point.
*
- * @param networkAddress IP Address encapsulated in InetAddress class
+ * @param networkAddress IP Address encapsulated in InetAddress class
*
*/
public void find(InetAddress networkAddress);
* This method is called by HostTracker to see if a learned Host is still in the network.
* Used mostly for ARP Aging.
*
- * @param host The Host that needs to be probed
+ * @param host The Host that needs to be probed
*/
public void probe(HostNodeConnector host);
}
\r
public class HostNodeConnectorTest extends TestCase {\r
\r
- @Test\r
- public void testHostNodeConnector() throws UnknownHostException {\r
- HostNodeConnector hostnodeconnector_1, hostnodeconnector_2, hostnodeconnector_3;\r
- InetAddress hostIP_1 = InetAddress.getByName("192.168.0.8");\r
- InetAddress hostIP_2 = InetAddress.getByName("2001:420:281:1004:e123:e688:d655:a1b0");\r
- InetAddress hostIP_3 = InetAddress.getByName("192.168.0.28");\r
- byte[] hostMAC_2 = new byte[]{(byte)0x11,(byte)0x22,(byte)0x33,(byte)0x22,(byte)0x22,(byte)0x22};\r
- byte[] hostMAC_3 = new byte[]{(byte)0x11,(byte)0x22,(byte)0x33,(byte)0x33,(byte)0x33,(byte)0x33};\r
- \r
- Node node = NodeCreator.createOFNode(1L);\r
- NodeConnector nc1 = NodeConnectorCreator.createOFNodeConnector((short) 2, node);\r
- NodeConnector nc2 = NodeConnectorCreator.createOFNodeConnector((short) 1, node);\r
- \r
- try {\r
- hostnodeconnector_1 = new HostNodeConnector(hostIP_1);\r
- Assert.assertTrue(hostnodeconnector_1.equalsByIP(hostIP_1));\r
- Assert.assertTrue(hostnodeconnector_1.isV4Host());\r
- Assert.assertTrue(hostnodeconnector_1.equalsByIP(hostIP_1));\r
- } catch (ConstructionException e) {\r
- Assert.assertTrue(false);\r
- }\r
- \r
- try {\r
- hostnodeconnector_2 = new HostNodeConnector(\r
- hostMAC_2, hostIP_2, nc1, (short)2);\r
- Assert.assertTrue(hostnodeconnector_2.isV6Host());\r
- Assert.assertTrue(hostnodeconnector_2.getnodeConnector().equals(nc1));\r
- Assert.assertTrue(hostnodeconnector_2.getnodeconnectorNode().equals(node));\r
+ @Test\r
+ public void testHostNodeConnector() throws UnknownHostException {\r
+ HostNodeConnector hostnodeconnector_1, hostnodeconnector_2, hostnodeconnector_3;\r
+ InetAddress hostIP_1 = InetAddress.getByName("192.168.0.8");\r
+ InetAddress hostIP_2 = InetAddress.getByName("2001:420:281:1004:e123:e688:d655:a1b0");\r
+ InetAddress hostIP_3 = InetAddress.getByName("192.168.0.28");\r
+ byte[] hostMAC_2 = new byte[]{(byte)0x11,(byte)0x22,(byte)0x33,(byte)0x22,(byte)0x22,(byte)0x22};\r
+ byte[] hostMAC_3 = new byte[]{(byte)0x11,(byte)0x22,(byte)0x33,(byte)0x33,(byte)0x33,(byte)0x33};\r
+\r
+ Node node = NodeCreator.createOFNode(1L);\r
+ NodeConnector nc1 = NodeConnectorCreator.createOFNodeConnector((short) 2, node);\r
+ NodeConnector nc2 = NodeConnectorCreator.createOFNodeConnector((short) 1, node);\r
+\r
+ try {\r
+ hostnodeconnector_1 = new HostNodeConnector(hostIP_1);\r
+ Assert.assertTrue(hostnodeconnector_1.equalsByIP(hostIP_1));\r
+ Assert.assertTrue(hostnodeconnector_1.isV4Host());\r
+ Assert.assertTrue(hostnodeconnector_1.equalsByIP(hostIP_1));\r
+ } catch (ConstructionException e) {\r
+ Assert.assertTrue(false);\r
+ }\r
+\r
+ try {\r
+ hostnodeconnector_2 = new HostNodeConnector(\r
+ hostMAC_2, hostIP_2, nc1, (short)2);\r
+ Assert.assertTrue(hostnodeconnector_2.isV6Host());\r
+ Assert.assertTrue(hostnodeconnector_2.getnodeConnector().equals(nc1));\r
+ Assert.assertTrue(hostnodeconnector_2.getnodeconnectorNode().equals(node));\r
Assert.assertTrue(node.equals(hostnodeconnector_2.getnodeconnectorNode()));\r
- } catch (ConstructionException e) {\r
- Assert.assertTrue(false);\r
- }\r
- \r
- try {\r
- hostnodeconnector_3 = new HostNodeConnector(\r
- new EthernetAddress(hostMAC_3), hostIP_3, nc2, (short)3);\r
- byte[] hostMAC_3_rb = hostnodeconnector_3.getDataLayerAddressBytes();\r
- HostNodeConnector hostnodeconnector_3rb = new HostNodeConnector(\r
- new EthernetAddress(hostMAC_3_rb), hostIP_3, nc2, (short)3);\r
- Assert.assertTrue(hostnodeconnector_3.equals(hostnodeconnector_3rb));\r
- \r
- Assert.assertTrue(hostnodeconnector_3.getVlan() == (short)3);\r
- \r
- hostnodeconnector_3.setStaticHost(true);\r
- Assert.assertTrue(hostnodeconnector_3.isStaticHost());\r
- \r
- Assert.assertTrue(hostnodeconnector_3.isRewriteEnabled());\r
- \r
- hostnodeconnector_3.initArpSendCountDown().setArpSendCountDown((short) 10);\r
- Assert.assertTrue(hostnodeconnector_3.getArpSendCountDown() == (short)10);\r
- \r
- } catch (ConstructionException e) {\r
- Assert.assertTrue(false);\r
- }\r
- \r
- }\r
+ } catch (ConstructionException e) {\r
+ Assert.assertTrue(false);\r
+ }\r
+\r
+ try {\r
+ hostnodeconnector_3 = new HostNodeConnector(\r
+ new EthernetAddress(hostMAC_3), hostIP_3, nc2, (short)3);\r
+ byte[] hostMAC_3_rb = hostnodeconnector_3.getDataLayerAddressBytes();\r
+ HostNodeConnector hostnodeconnector_3rb = new HostNodeConnector(\r
+ new EthernetAddress(hostMAC_3_rb), hostIP_3, nc2, (short)3);\r
+ Assert.assertTrue(hostnodeconnector_3.equals(hostnodeconnector_3rb));\r
+\r
+ Assert.assertTrue(hostnodeconnector_3.getVlan() == (short)3);\r
+\r
+ hostnodeconnector_3.setStaticHost(true);\r
+ Assert.assertTrue(hostnodeconnector_3.isStaticHost());\r
+\r
+ Assert.assertTrue(hostnodeconnector_3.isRewriteEnabled());\r
+\r
+ hostnodeconnector_3.initArpSendCountDown().setArpSendCountDown((short) 10);\r
+ Assert.assertTrue(hostnodeconnector_3.getArpSendCountDown() == (short)10);\r
+\r
+ } catch (ConstructionException e) {\r
+ Assert.assertTrue(false);\r
+ }\r
+\r
+ }\r
\r
}\r
/**
* This Class provides methods to discover Host through a blocking call
- * mechanism. Applications can make use of these methods if they don't
- * find a host in HostTracker's database and want to discover the host
+ * mechanism. Applications can make use of these methods if they don't
+ * find a host in HostTracker's database and want to discover the host
* in the same thread without being called by a callback function.
*/
import java.net.InetAddress;
\r
public class HostTrackerTest extends TestCase {\r
\r
- @Test\r
- public void testHostTrackerCallable() throws UnknownHostException {\r
- \r
- HostTracker hostTracker = null;\r
- hostTracker = new HostTracker();\r
- Assert.assertFalse(hostTracker== null);\r
- \r
- InetAddress hostIP = InetAddress.getByName("192.168.0.8");\r
- \r
- HostTrackerCallable htCallable = new HostTrackerCallable (hostTracker, hostIP);\r
- Assert.assertTrue(htCallable.trackedHost.equals(hostIP));\r
- Assert.assertTrue(htCallable.hostTracker.equals(hostTracker));\r
-\r
- long count = htCallable.latch.getCount();\r
- htCallable.wakeup();\r
- Assert.assertTrue(htCallable.latch.getCount() == --count );\r
- } \r
- \r
- \r
- \r
- @Test\r
- public void testHostTracker() throws UnknownHostException {\r
- HostTracker hostTracker = null;\r
- hostTracker = new HostTracker();\r
- Assert.assertFalse(hostTracker== null);\r
- \r
- InetAddress hostIP_1 = InetAddress.getByName("192.168.0.8");\r
- InetAddress hostIP_2 = InetAddress.getByName("192.168.0.18");\r
- Future<HostNodeConnector> dschost = hostTracker.discoverHost(hostIP_1);\r
- dschost = hostTracker.discoverHost(hostIP_2);\r
- hostTracker.nonClusterObjectCreate();\r
- }\r
- \r
+ @Test\r
+ public void testHostTrackerCallable() throws UnknownHostException {\r
+\r
+ HostTracker hostTracker = null;\r
+ hostTracker = new HostTracker();\r
+ Assert.assertFalse(hostTracker== null);\r
+\r
+ InetAddress hostIP = InetAddress.getByName("192.168.0.8");\r
+\r
+ HostTrackerCallable htCallable = new HostTrackerCallable (hostTracker, hostIP);\r
+ Assert.assertTrue(htCallable.trackedHost.equals(hostIP));\r
+ Assert.assertTrue(htCallable.hostTracker.equals(hostTracker));\r
+\r
+ long count = htCallable.latch.getCount();\r
+ htCallable.wakeup();\r
+ Assert.assertTrue(htCallable.latch.getCount() == --count );\r
+ }\r
+\r
+\r
+\r
+ @Test\r
+ public void testHostTracker() throws UnknownHostException {\r
+ HostTracker hostTracker = null;\r
+ hostTracker = new HostTracker();\r
+ Assert.assertFalse(hostTracker== null);\r
+\r
+ InetAddress hostIP_1 = InetAddress.getByName("192.168.0.8");\r
+ InetAddress hostIP_2 = InetAddress.getByName("192.168.0.18");\r
+ Future<HostNodeConnector> dschost = hostTracker.discoverHost(hostIP_1);\r
+ dschost = hostTracker.discoverHost(hostIP_2);\r
+ hostTracker.nonClusterObjectCreate();\r
+ }\r
+\r
\r
}\r
this.listener.logged(entry);
}
}
-
+
/*
* Install the default exception handler so that the uncaught
* exceptions are handled by our customized handler. This new
*/
Thread.setDefaultUncaughtExceptionHandler(new org.opendaylight.
controller.logging.bridge.internal.UncaughtExceptionHandler());
-
+
/*
* Install the Shutdown handler. This will intercept SIGTERM signal and
* close the system bundle. This allows for a graceful closing of OSGI
* framework.
*/
-
+
Runtime.getRuntime().addShutdownHook(new shutdownHandler(context));
} else {
this.log.error("Cannot register the LogListener because "
this.listener = null;
this.log = null;
}
-
+
private class shutdownHandler extends Thread {
BundleContext bundlecontext;
public shutdownHandler(BundleContext ctxt) {
this.bundlecontext = ctxt;
}
-
+
public void run () {
try {
this.bundlecontext.getBundle(0).stop();
} catch (BundleException e) {
log.debug("Bundle couldn't be stopped");
}
- }
+ }
}
}
*
*/
package org.opendaylight.controller.northbound.commons.exception;
-
public class NorthboundUtils {
-
+
/**
* Returns whether the current user has the required privilege on the
* specified container
- *
+ *
* @param userName
* The user name
* @param containerName
* @param required
* Operation to be performed - READ/WRITE
* @param bundle
- * Class from where the function is invoked
+ * Class from where the function is invoked
* @return The Status of the request, either Success or Unauthorized
*/
public static boolean isAuthorized(String userName, String containerName,
Privilege required,Object bundle) {
-
+
if (containerName.equals(GlobalConstants.DEFAULT.toString())) {
IUserManager auth = (IUserManager) ServiceHelper.getGlobalInstance(
IUserManager.class, bundle);
-
+
switch (required) {
case WRITE:
return (auth.getUserLevel(userName).ordinal() <= UserLevel.NETWORKADMIN.ordinal());
case READ:
- return (auth.getUserLevel(userName).ordinal() <= UserLevel.NETWORKOPERATOR.ordinal());
+ return (auth.getUserLevel(userName).ordinal() <= UserLevel.NETWORKOPERATOR.ordinal());
default:
return false;
}
}
return true;
}
-
+
}
@XmlAccessorType(XmlAccessType.NONE)
public class FlowConfigs {
- @XmlElement
- List<FlowConfig> flowConfig;
- //To satisfy JAXB
- private FlowConfigs() {
-
- }
-
- public FlowConfigs(List<FlowConfig> flowConfig) {
- this.flowConfig = flowConfig;
- }
-
- public List<FlowConfig> getFlowConfig() {
- return flowConfig;
- }
-
- public void setFlowConfig(List<FlowConfig> flowConfig) {
- this.flowConfig = flowConfig;
- }
+ @XmlElement
+ List<FlowConfig> flowConfig;
+ //To satisfy JAXB
+ private FlowConfigs() {
+
+ }
+
+ public FlowConfigs(List<FlowConfig> flowConfig) {
+ this.flowConfig = flowConfig;
+ }
+
+ public List<FlowConfig> getFlowConfig() {
+ return flowConfig;
+ }
+
+ public void setFlowConfig(List<FlowConfig> flowConfig) {
+ this.flowConfig = flowConfig;
+ }
}
/**
* Flow Configuration Northbound API
- *
+ *
* <br>
* <br>
* Authentication scheme : <b>HTTP Basic</b><br>
* trusted authority.<br>
* More info :
* http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration
- *
+ *
*/
@Path("/")
public class FlowProgrammerNorthbound {
/**
* Returns a list of Flows configured on the given container
- *
+ *
* @param containerName
* Name of the Container. The Container name for the base
* controller is "default".
/**
* Returns a list of Flows configured on a Node in a given container
- *
+ *
* @param containerName
* Name of the Container. The Container name for the base
* controller is "default".
/**
* Returns the flow configuration matching a human-readable name and nodeId
* on a given Container.
- *
+ *
* @param containerName
* Name of the Container. The Container name for the base
* controller is "default".
/**
* Add a flow configuration
- *
+ *
* @param containerName
* Name of the Container. The Container name for the base
* controller is "default".
/**
* Delete a Flow configuration
- *
+ *
* DELETE /flows/{containerName}/{nodeType}/{nodeId}/{name}
- *
+ *
* @param containerName
* Name of the Container. The Container name for the base
* controller is "default".
/**
* Toggle a Flow configuration
- *
+ *
* @param containerName
* Name of the Container. The Container name for the base
* controller is "default".
* Location is represented by Host node connector which is essentially a logical
* entity that represents a Switch/Port. A host is represented by it's
* IP-address and mac-address.
- *
+ *
* <br>
* <br>
* Authentication scheme : <b>HTTP Basic</b><br>
* trusted authority.<br>
* More info :
* http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration
- *
+ *
*/
@Path("/")
/**
* Returns a list of all Hosts : both configured via PUT API and dynamically
* learnt on the network.
- *
+ *
* @param containerName
* Name of the Container. The Container name for the base
* controller is "default".
@ResponseCode(code = 404, condition = "The containerName is not found"),
@ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
public Hosts getActiveHosts(@PathParam("containerName") String containerName) {
-
+
if (!NorthboundUtils.isAuthorized(
getUserName(), containerName, Privilege.READ, this)) {
throw new UnauthorizedException(
/**
* Returns a list of Hosts that are statically configured and are connected
* to a NodeConnector that is down.
- *
+ *
* @param containerName
* Name of the Container. The Container name for the base
* controller is "default".
/**
* Returns a host that matches the IP Address value passed as parameter.
- *
+ *
* @param containerName
* Name of the Container. The Container name for the base
* controller is "default".
/**
* Add a Static Host configuration
- *
+ *
* @param containerName
* Name of the Container. The Container name for the base
* controller is "default".
/**
* Delete a Static Host configuration
- *
+ *
* @param containerName
* Name of the Container. The Container name for the base
* controller is "default".
public Response deleteFlow(
@PathParam(value = "containerName") String containerName,
@PathParam(value = "networkAddress") String networkAddress) {
-
+
if (!NorthboundUtils.isAuthorized(
getUserName(), containerName, Privilege.WRITE, this)) {
throw new UnauthorizedException(
@XmlAccessorType(XmlAccessType.NONE)
public class Hosts {
- @XmlElement (name="host")
- Set<HostNodeConnector> hostNodeConnector;
-
- public Hosts() {
- }
- public Hosts (Set<HostNodeConnector> hostNodeConnector) {
- this.hostNodeConnector = hostNodeConnector;
- }
- public Set<HostNodeConnector> getHostNodeConnector() {
- return hostNodeConnector;
- }
- public void setHostNodeConnector(Set<HostNodeConnector> hostNodeConnector) {
- this.hostNodeConnector = hostNodeConnector;
- }
+ @XmlElement (name="host")
+ Set<HostNodeConnector> hostNodeConnector;
+
+ public Hosts() {
+ }
+ public Hosts (Set<HostNodeConnector> hostNodeConnector) {
+ this.hostNodeConnector = hostNodeConnector;
+ }
+ public Set<HostNodeConnector> getHostNodeConnector() {
+ return hostNodeConnector;
+ }
+ public void setHostNodeConnector(Set<HostNodeConnector> hostNodeConnector) {
+ this.hostNodeConnector = hostNodeConnector;
+ }
}
fc = "{\"dynamic\":\"false\", \"name\":\"test2\", \"nwSrc\":\"1.1.1.1\", \"node\":{\"@id\":\"51966\",\"@type\":\"STUB\"}, \"actions\":[\"DROP\"]}";
result = getJsonResult(baseURL + "STUB/51966/test2", "POST", fc);
Assert.assertTrue(httpResponseCode == 201);
-
+
// check that request returns both flows given node.
result = getJsonResult(baseURL + "STUB/51966/", "GET");
jt = new JSONTokener(result);
@XmlAccessorType(XmlAccessType.NONE)
public class StaticRoutes {
- @XmlElement
- List<StaticRoute> staticRoute;
- //To satisfy JAXB
- private StaticRoutes() {
-
- }
-
- public StaticRoutes(List<StaticRoute> staticRoute) {
- this.staticRoute = staticRoute;
- }
-
- public List<StaticRoute> getFlowConfig() {
- return staticRoute;
- }
-
- public void setFlowConfig(List<StaticRoute> staticRoute) {
- this.staticRoute = staticRoute;
- }
+ @XmlElement
+ List<StaticRoute> staticRoute;
+ //To satisfy JAXB
+ private StaticRoutes() {
+
+ }
+
+ public StaticRoutes(List<StaticRoute> staticRoute) {
+ this.staticRoute = staticRoute;
+ }
+
+ public List<StaticRoute> getFlowConfig() {
+ return staticRoute;
+ }
+
+ public void setFlowConfig(List<StaticRoute> staticRoute) {
+ this.staticRoute = staticRoute;
+ }
}
* Authentication realm : <b>opendaylight</b><br>
* Transport : <b>HTTP and HTTPS</b><br>
* <br>
- * HTTPS Authentication is disabled by default. Administrator can enable it in tomcat-server.xml after adding
+ * HTTPS Authentication is disabled by default. Administrator can enable it in tomcat-server.xml after adding
* a proper keystore / SSL certificate from a trusted authority.<br>
* More info : http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration
*/
public class StaticRoutingNorthbound {
- private String username;
-
+ private String username;
+
@Context
public void setSecurityContext(SecurityContext context) {
- username = context.getUserPrincipal().getName();
+ username = context.getUserPrincipal().getName();
}
protected String getUserName() {
return username;
}
-
-
+
+
private List<StaticRoute> getStaticRoutesInternal(String containerName) {
IForwardingStaticRouting staticRouting = (IForwardingStaticRouting) ServiceHelper
public StaticRoutes getStaticRoutes(
@PathParam("containerName") String containerName) {
- if(!NorthboundUtils.isAuthorized(getUserName(), containerName,
+ if(!NorthboundUtils.isAuthorized(getUserName(), containerName,
Privilege.WRITE, this)){
- throw new
+ throw new
UnauthorizedException("User is not authorized to perform this operation on container "
+ containerName);
}
@PathParam("containerName") String containerName,
@PathParam("name") String name) {
- if(!NorthboundUtils.isAuthorized(getUserName(), containerName,
+ if(!NorthboundUtils.isAuthorized(getUserName(), containerName,
Privilege.WRITE, this)){
- throw new
+ throw new
UnauthorizedException("User is not authorized to perform this operation on container "
+ containerName);
}
@PathParam(value = "name") String name,
@TypeHint(StaticRoute.class) JAXBElement<StaticRoute> staticRouteData) {
-
- if(!NorthboundUtils.isAuthorized(getUserName(), containerName,
+
+ if(!NorthboundUtils.isAuthorized(getUserName(), containerName,
Privilege.WRITE, this)){
- throw new
+ throw new
UnauthorizedException("User is not authorized to perform this operation on container "
+ containerName);
}
public Response removeStaticRoute(
@PathParam(value = "containerName") String containerName,
@PathParam(value = "name") String name) {
-
- if(!NorthboundUtils.isAuthorized(getUserName(), containerName,
+
+ if(!NorthboundUtils.isAuthorized(getUserName(), containerName,
Privilege.WRITE, this)){
- throw new
+ throw new
UnauthorizedException("User is not authorized to perform this operation on container "
+ containerName);
}
@XmlAccessorType(XmlAccessType.NONE)
public class AllFlowStatistics {
- @XmlElement
- List<FlowStatistics> flowStatistics;
- //To satisfy JAXB
- private AllFlowStatistics() {
- }
-
- public AllFlowStatistics(List<FlowStatistics> flowStatistics) {
- this.flowStatistics = flowStatistics;
- }
-
- public List<FlowStatistics> getFlowStatistics() {
- return flowStatistics;
- }
-
- public void setFlowStatistics(List<FlowStatistics> flowStatistics) {
- this.flowStatistics = flowStatistics;
- }
+ @XmlElement
+ List<FlowStatistics> flowStatistics;
+ //To satisfy JAXB
+ private AllFlowStatistics() {
+ }
+
+ public AllFlowStatistics(List<FlowStatistics> flowStatistics) {
+ this.flowStatistics = flowStatistics;
+ }
+
+ public List<FlowStatistics> getFlowStatistics() {
+ return flowStatistics;
+ }
+
+ public void setFlowStatistics(List<FlowStatistics> flowStatistics) {
+ this.flowStatistics = flowStatistics;
+ }
}
@XmlAccessorType(XmlAccessType.NONE)
public class AllPortStatistics {
- @XmlElement
- List<PortStatistics> portStatistics;
- //To satisfy JAXB
- private AllPortStatistics() {
- }
-
- public AllPortStatistics(List<PortStatistics> portStatistics) {
- this.portStatistics = portStatistics;
- }
-
- public List<PortStatistics> getPortStatistics() {
- return portStatistics;
- }
-
- public void setPortStatistics(List<PortStatistics> portStatistics) {
- this.portStatistics = portStatistics;
- }
+ @XmlElement
+ List<PortStatistics> portStatistics;
+ //To satisfy JAXB
+ private AllPortStatistics() {
+ }
+
+ public AllPortStatistics(List<PortStatistics> portStatistics) {
+ this.portStatistics = portStatistics;
+ }
+
+ public List<PortStatistics> getPortStatistics() {
+ return portStatistics;
+ }
+
+ public void setPortStatistics(List<PortStatistics> portStatistics) {
+ this.portStatistics = portStatistics;
+ }
}
// To satisfy JAXB
@SuppressWarnings("unused")
- private FlowStatistics() {
+ private FlowStatistics() {
}
public FlowStatistics(Node node, List<FlowOnNode> flowStat) {
// To satisfy JAXB
@SuppressWarnings("unused")
- private PortStatistics() {
+ private PortStatistics() {
}
public PortStatistics(Node node, List<NodeConnectorStatistics> portStats) {
/**
* Northbound APIs that returns various Statistics exposed by the Southbound
* plugins such as Openflow.
- *
+ *
* <br>
* <br>
* Authentication scheme : <b>HTTP Basic</b><br>
* trusted authority.<br>
* More info :
* http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration
- *
+ *
*/
@Path("/")
public class StatisticsNorthbound {
/**
* Returns a list of all Flow Statistics from all the Nodes.
- *
+ *
* @param containerName
* Name of the Container. The Container name for the base
* controller is "default".
/**
* Returns a list of Flow Statistics for a given Node.
- *
+ *
* @param containerName
* Name of the Container. The Container name for the base
* controller is "default".
/**
* Returns a list of all the Port Statistics across all the NodeConnectors
* on all the Nodes.
- *
+ *
* @param containerName
* Name of the Container. The Container name for the base
* controller is "default".
/**
* Returns a list of all the Port Statistics across all the NodeConnectors
* in a given Node.
- *
+ *
* @param containerName
* Name of the Container. The Container name for the base
* controller is "default".
@XmlAccessorType(XmlAccessType.NONE)
public class SubnetConfigs {
- @XmlElement
- List<SubnetConfig> subnetConfig;
- //To satisfy JAXB
- private SubnetConfigs() {
-
- }
-
- public SubnetConfigs(List<SubnetConfig> subnetConfig) {
- this.subnetConfig = subnetConfig;
- }
-
- public List<SubnetConfig> getSubnetConfig() {
- return subnetConfig;
- }
-
- public void setSubnetConfig(List<SubnetConfig> subnetConfig) {
- this.subnetConfig = subnetConfig;
- }
+ @XmlElement
+ List<SubnetConfig> subnetConfig;
+ //To satisfy JAXB
+ private SubnetConfigs() {
+
+ }
+
+ public SubnetConfigs(List<SubnetConfig> subnetConfig) {
+ this.subnetConfig = subnetConfig;
+ }
+
+ public List<SubnetConfig> getSubnetConfig() {
+ return subnetConfig;
+ }
+
+ public void setSubnetConfig(List<SubnetConfig> subnetConfig) {
+ this.subnetConfig = subnetConfig;
+ }
}
/**
* List all the subnets in a given container
- *
+ *
* @param containerName
* container in which we want to query the subnets
- *
+ *
* @return a List of SubnetConfig
*/
@Path("/{containerName}")
/**
* List the configuration of a subnet in a given container
- *
+ *
* @param containerName
* container in which we want to query the subnet
* @param subnetName
* of the subnet being queried
- *
+ *
* @return a SubnetConfig
*/
@Path("/{containerName}/{subnetName}")
/**
* Add/Update a subnet to a container
- *
+ *
* @param containerName
* container in which we want to add/update the subnet
* @param subnetName
* @param subnet
* pair default gateway IP/mask that identify the subnet being
* added modified
- *
+ *
*/
@Path("/{containerName}/{subnetName}")
@POST
/**
* Delete a subnet from a container
- *
+ *
* @param containerName
* container in which we want to delete the subnet by name
* @param subnetName
* of the subnet to be remove.
- *
+ *
*/
@Path("/{containerName}/{subnetName}")
@DELETE
}
/*
- *
+ *
* Add or remove switch ports to a subnet POST subnets/green/sw
- *
+ *
* @param model
- *
+ *
* @param containerName
- *
+ *
* @param name
- *
+ *
* @param subnet: the subnet name name
- *
+ *
* @param switchports: datapath ID/port list =>
* xx:xx:xx:xx:xx:xx:xx:xx/a,b,c-m,r-t,y
- *
+ *
* @return
- *
+ *
* @RequestMapping(value = "/{containerName}/{name}", method =
* RequestMethod.POST)
- *
+ *
* public View addSwitchports(Map<String, Object> model,
- *
+ *
* @PathVariable(value = "containerName") String containerName,
- *
+ *
* @PathVariable(value = "name") String name,
- *
+ *
* @RequestParam(value = "nodeports") String nodePorts,
- *
+ *
* @RequestParam(value = "action") String action) {
- *
+ *
* checkDefaultDisabled(containerName); ISwitchManager switchManager = null;
* try { BundleContext bCtx = FrameworkUtil.getBundle(this.getClass())
* .getBundleContext();
- *
+ *
* ServiceReference[] services = bCtx.getServiceReferences(
* ISwitchManager.class.getName(), "(containerName=" + containerName + ")");
- *
+ *
* if (services != null) { switchManager = (ISwitchManager)
* bCtx.getService(services[0]); logger.debug("Switch manager reference is:"
* + switchManager); } } catch (Exception e) {
* logger.error("Switch Manager reference is NULL"); }
- *
+ *
* checkContainerExists(switchManager);
- *
+ *
* String ret; if (action.equals("add")) { ret =
* switchManager.addPortsToSubnet(name, nodePorts); } else if
* (action.equals("remove")) { ret =
* switchManager.removePortsFromSubnet(name, nodePorts); } else { throw new
* UnsupportedMediaTypeException(RestMessages.UNKNOWNACTION .toString() +
* ": " + action); }
- *
+ *
* return returnViewOrThrowConflicEx(model, ret); }
*/
}
@XmlAccessorType(XmlAccessType.NONE)
public class NodeConnectors {
- @XmlElement
- List<NodeConnectorProperties> nodeConnectorProperties;
- //To satisfy JAXB
- private NodeConnectors() {
-
- }
-
- public NodeConnectors(List<NodeConnectorProperties> nodeConnectorProperties) {
- this.nodeConnectorProperties = nodeConnectorProperties;
- }
-
- public List<NodeConnectorProperties> getNodeConnectorProperties() {
- return nodeConnectorProperties;
- }
-
- public void setNodeConnectorProperties(List<NodeConnectorProperties> nodeConnectorProperties) {
- this.nodeConnectorProperties = nodeConnectorProperties;
- }
+ @XmlElement
+ List<NodeConnectorProperties> nodeConnectorProperties;
+ //To satisfy JAXB
+ private NodeConnectors() {
+
+ }
+
+ public NodeConnectors(List<NodeConnectorProperties> nodeConnectorProperties) {
+ this.nodeConnectorProperties = nodeConnectorProperties;
+ }
+
+ public List<NodeConnectorProperties> getNodeConnectorProperties() {
+ return nodeConnectorProperties;
+ }
+
+ public void setNodeConnectorProperties(List<NodeConnectorProperties> nodeConnectorProperties) {
+ this.nodeConnectorProperties = nodeConnectorProperties;
+ }
}
@XmlAccessorType(XmlAccessType.NONE)
public class Nodes {
- @XmlElement
- List<NodeProperties> nodeProperties;
- //To satisfy JAXB
- private Nodes() {
-
- }
-
- public Nodes(List<NodeProperties> nodeProperties) {
- this.nodeProperties = nodeProperties;
- }
-
- public List<NodeProperties> getNodeProperties() {
- return nodeProperties;
- }
-
- public void setNodeProperties(List<NodeProperties> nodeProperties) {
- this.nodeProperties = nodeProperties;
- }
+ @XmlElement
+ List<NodeProperties> nodeProperties;
+ //To satisfy JAXB
+ private Nodes() {
+
+ }
+
+ public Nodes(List<NodeProperties> nodeProperties) {
+ this.nodeProperties = nodeProperties;
+ }
+
+ public List<NodeProperties> getNodeProperties() {
+ return nodeProperties;
+ }
+
+ public void setNodeProperties(List<NodeProperties> nodeProperties) {
+ this.nodeProperties = nodeProperties;
+ }
}
public class SwitchManagerNorthboundTest extends TestCase {
- @Test
- public void testNodes() {
- List<NodeProperties> nodeProperties = new ArrayList<NodeProperties>();
- Nodes nodes = new Nodes(nodeProperties);
- Assert.assertTrue(nodes.getNodeProperties().equals(nodeProperties));
- nodes.setNodeProperties(null);
- Assert.assertTrue(nodes.getNodeProperties() == null);
- }
-
- @Test
- public void testNodeProperties() {
- Node node = NodeCreator.createOFNode(1L);
- NodeProperties np= new NodeProperties(node, null);
- Assert.assertTrue(np.getNode().equals(node));
- Assert.assertTrue(np.getProperties() == null);
-
- Node node2 = NodeCreator.createOFNode(2L);
- np.setNode(node2);
- Assert.assertTrue(np.getNode().equals(node2));
+ @Test
+ public void testNodes() {
+ List<NodeProperties> nodeProperties = new ArrayList<NodeProperties>();
+ Nodes nodes = new Nodes(nodeProperties);
+ Assert.assertTrue(nodes.getNodeProperties().equals(nodeProperties));
+ nodes.setNodeProperties(null);
+ Assert.assertTrue(nodes.getNodeProperties() == null);
+ }
- Set<Property> props = new HashSet<Property>();
- np.setProperties(props);
- Assert.assertTrue(np.getProperties().equals(props));
- }
+ @Test
+ public void testNodeProperties() {
+ Node node = NodeCreator.createOFNode(1L);
+ NodeProperties np= new NodeProperties(node, null);
+ Assert.assertTrue(np.getNode().equals(node));
+ Assert.assertTrue(np.getProperties() == null);
- @Test
- public void testNodeConnectors() {
- List<NodeConnectorProperties> nodeConnectorProperties = new ArrayList<NodeConnectorProperties>();
- NodeConnectors ncs = new NodeConnectors(nodeConnectorProperties);
- Assert.assertTrue(ncs.getNodeConnectorProperties().equals(nodeConnectorProperties));
- ncs.setNodeConnectorProperties(null);
- Assert.assertTrue(ncs.getNodeConnectorProperties() == null);
- }
-
- @Test
- public void testNodeConnectorProperties() {
- Node node = NodeCreator.createOFNode(1L);
+ Node node2 = NodeCreator.createOFNode(2L);
+ np.setNode(node2);
+ Assert.assertTrue(np.getNode().equals(node2));
+
+ Set<Property> props = new HashSet<Property>();
+ np.setProperties(props);
+ Assert.assertTrue(np.getProperties().equals(props));
+ }
+
+ @Test
+ public void testNodeConnectors() {
+ List<NodeConnectorProperties> nodeConnectorProperties = new ArrayList<NodeConnectorProperties>();
+ NodeConnectors ncs = new NodeConnectors(nodeConnectorProperties);
+ Assert.assertTrue(ncs.getNodeConnectorProperties().equals(nodeConnectorProperties));
+ ncs.setNodeConnectorProperties(null);
+ Assert.assertTrue(ncs.getNodeConnectorProperties() == null);
+ }
+
+ @Test
+ public void testNodeConnectorProperties() {
+ Node node = NodeCreator.createOFNode(1L);
NodeConnector port = NodeConnectorCreator.createOFNodeConnector(
(short) 24, node);
-
+
NodeConnectorProperties ncp= new NodeConnectorProperties(port, null);
- Assert.assertTrue(ncp.getProperties() == null);
- Assert.assertTrue(ncp.getNodeConnector().equals(port));
-
+ Assert.assertTrue(ncp.getProperties() == null);
+ Assert.assertTrue(ncp.getNodeConnector().equals(port));
+
NodeConnector port2 = NodeConnectorCreator.createOFNodeConnector(
(short) 33, node);
- ncp.setNodeConnector(port2);
- Assert.assertTrue(ncp.getNodeConnector().equals(port2));
+ ncp.setNodeConnector(port2);
+ Assert.assertTrue(ncp.getNodeConnector().equals(port2));
+
+ Set<Property> props = new HashSet<Property>();
+ ncp.setProperties(props);
+ Assert.assertTrue(ncp.getProperties().equals(props));
+ }
- Set<Property> props = new HashSet<Property>();
- ncp.setProperties(props);
- Assert.assertTrue(ncp.getProperties().equals(props));
- }
-
}
@XmlAccessorType(XmlAccessType.NONE)
public class Topology {
- @XmlElement
- List<EdgeProperties> edgeProperties;
- //To satisfy JAXB
- private Topology() {
-
- }
-
- public Topology(List<EdgeProperties> edgeProperties) {
- this.edgeProperties = edgeProperties;
- }
-
- public List<EdgeProperties> getEdgeProperties() {
- return edgeProperties;
- }
-
- public void setEdgeProperties(List<EdgeProperties> edgeProperties) {
- this.edgeProperties = edgeProperties;
- }
+ @XmlElement
+ List<EdgeProperties> edgeProperties;
+ //To satisfy JAXB
+ private Topology() {
+
+ }
+
+ public Topology(List<EdgeProperties> edgeProperties) {
+ this.edgeProperties = edgeProperties;
+ }
+
+ public List<EdgeProperties> getEdgeProperties() {
+ return edgeProperties;
+ }
+
+ public void setEdgeProperties(List<EdgeProperties> edgeProperties) {
+ this.edgeProperties = edgeProperties;
+ }
}
/**
* Topology Northbound REST API
- *
+ *
* <br>
* <br>
* Authentication scheme : <b>HTTP Basic</b><br>
}
/**
- *
+ *
* Retrieve the Topology
- *
+ *
* @param containerName
* The container for which we want to retrieve the topology
- *
+ *
* @return A List of EdgeProps each EdgeProp represent an Edge of the grap
* with the corresponding properties attached to it.
*/
/**
* Retrieve the user configured links
- *
+ *
* @param containerName
* The container for which we want to retrieve the user links
- *
+ *
* @return A List of user configured links
*/
@Path("/{containerName}/userLink")
/**
* Add an User Link
- *
+ *
* @param containerName
* Name of the Container. The base Container is "default".
* @param TopologyUserLinkConfig
/**
* Delete an User Link
- *
+ *
* @param containerName
* Name of the Container. The base Container is "default".
* @param name
@XmlAccessorType(XmlAccessType.NONE)
public class TopologyUserLinks {
- @XmlElement
- List<TopologyUserLinkConfig> userLinks;
-
- //To satisfy JAXB
- private TopologyUserLinks() {
-
- }
-
- public List<TopologyUserLinkConfig> getUserLinks() {
- return userLinks;
- }
-
- public void setUserLinks(List<TopologyUserLinkConfig> userLinks) {
- this.userLinks = userLinks;
- }
-
- public TopologyUserLinks(List<TopologyUserLinkConfig> userLinks) {
- this.userLinks = new ArrayList<TopologyUserLinkConfig>(userLinks);
- }
+ @XmlElement
+ List<TopologyUserLinkConfig> userLinks;
+
+ //To satisfy JAXB
+ private TopologyUserLinks() {
+
+ }
+
+ public List<TopologyUserLinkConfig> getUserLinks() {
+ return userLinks;
+ }
+
+ public void setUserLinks(List<TopologyUserLinkConfig> userLinks) {
+ this.userLinks = userLinks;
+ }
+
+ public TopologyUserLinks(List<TopologyUserLinkConfig> userLinks) {
+ this.userLinks = new ArrayList<TopologyUserLinkConfig>(userLinks);
+ }
}
assertEquals(2, getEdgePropList.size());
}
-
+
}
/**
* Updates node and its properties
*
- * @param node {@link org.opendaylight.controller.sal.core.Node} being updated
- * @param type {@link org.opendaylight.controller.sal.core.UpdateType}
- * @param props set of {@link org.opendaylight.controller.sal.core.Property} such as
- * {@link org.opendaylight.controller.sal.core.Description} and/or
- * {@link org.opendaylight.controller.sal.core.Tier} etc.
+ * @param node {@link org.opendaylight.controller.sal.core.Node} being updated
+ * @param type {@link org.opendaylight.controller.sal.core.UpdateType}
+ * @param props set of {@link org.opendaylight.controller.sal.core.Property} such as
+ * {@link org.opendaylight.controller.sal.core.Description} and/or
+ * {@link org.opendaylight.controller.sal.core.Tier} etc.
*/
public void updateNode(Node node, UpdateType type, Set<Property> props);
/**
* Updates node connector and its properties
*
- * @param nodeConnector {@link org.opendaylight.controller.sal.core.NodeConnector} being updated
- * @param type {@link org.opendaylight.controller.sal.core.UpdateType}
- * @param props set of {@link org.opendaylight.controller.sal.core.Property} such as
- * {@link org.opendaylight.controller.sal.core.Description} and/or
- * {@link org.opendaylight.controller.sal.core.State} etc.
+ * @param nodeConnector {@link org.opendaylight.controller.sal.core.NodeConnector} being updated
+ * @param type {@link org.opendaylight.controller.sal.core.UpdateType}
+ * @param props set of {@link org.opendaylight.controller.sal.core.Property} such as
+ * {@link org.opendaylight.controller.sal.core.Description} and/or
+ * {@link org.opendaylight.controller.sal.core.State} etc.
*/
public void updateNodeConnector(NodeConnector nodeConnector,
UpdateType type, Set<Property> props);
* For port statistics, it is the port id. If null the query
* will be performed for all the targets for the specified
* statistics type.
- *
+ *
* @param timeout the timeout in milliseconds the system will wait for a response
* from the switch, before declaring failure
* @return the list of openflow statistics
package org.opendaylight.controller.protocol_plugin.openflow;
/**
- * @file IRefreshInternalProvider.java
+ * @file IRefreshInternalProvider.java
*
- * @brief Topology refresh notifications requested by application
- * to be fetched from the plugin
+ * @brief Topology refresh notifications requested by application
+ * to be fetched from the plugin
*
* For example, an application that has been started late, will want to
* be up to date with the latest topology. Hence, it requests for a
* is updated with new one.
*/
public interface IStatisticsListener {
- public void descriptionRefreshed(Long switchId,
- OFDescriptionStatistics description);
+ public void descriptionRefreshed(Long switchId,
+ OFDescriptionStatistics description);
}
public interface ITopologyServiceShimListener {
/**
* Called to update on Edge in the topology graph
- *
+ *
* @param topoedgeupdateList
* List of topoedgeupdates Each topoedgeupdate includes edge, its
* Properties ( BandWidth and/or Latency etc) and update type.
/**
* Called when an Edge utilization is above the safe threshold configured on
* the controller
- *
+ *
* @param {@link org.opendaylight.controller.sal.core.Edge}
*/
public void edgeOverUtilized(Edge edge);
/**
* Called when the Edge utilization is back to normal, below the safety
* threshold level configured on the controller
- *
+ *
* @param {@link org.opendaylight.controller.sal.core.Edge}
*/
public void edgeUtilBackToNormal(Edge edge);
* @return ISwitch if present, null otherwise
*/
public ISwitch getSwitch(Long switchId);
-
+
}
* encryption and decryption of the network data.
*/
public interface IMessageReadWrite {
- /**
- * Sends the OF message out over the socket channel. For secure
- * communication, the data will be encrypted.
- *
- * @param msg OF message to be sent
- * @throws Exception
- */
- public void asyncSend(OFMessage msg) throws Exception;
-
- /**
- * Resumes sending the remaining messages in the outgoing buffer
- * @throws Exception
- */
- public void resumeSend() throws Exception;
-
- /**
- * Reads the incoming network data from the socket and retrieves the OF
- * messages. For secure communication, the data will be decrypted first.
- *
- * @return list of OF messages
- * @throws Exception
- */
+ /**
+ * Sends the OF message out over the socket channel. For secure
+ * communication, the data will be encrypted.
+ *
+ * @param msg OF message to be sent
+ * @throws Exception
+ */
+ public void asyncSend(OFMessage msg) throws Exception;
+
+ /**
+ * Resumes sending the remaining messages in the outgoing buffer
+ * @throws Exception
+ */
+ public void resumeSend() throws Exception;
+
+ /**
+ * Reads the incoming network data from the socket and retrieves the OF
+ * messages. For secure communication, the data will be decrypted first.
+ *
+ * @return list of OF messages
+ * @throws Exception
+ */
public List<OFMessage> readMessages() throws Exception;
-
- /**
- * Proper clean up when the switch connection is closed
- *
- * @return
- * @throws Exception
- */
+
+ /**
+ * Proper clean up when the switch connection is closed
+ *
+ * @return
+ * @throws Exception
+ */
public void stop() throws Exception;
}
/**
* This interface defines an abstraction of an Open Flow Switch.
- *
+ *
*/
public interface ISwitch {
/**
* Gets a unique XID.
- *
+ *
* @return XID
*/
public int getNextXid();
/**
* Returns the Switch's ID.
- *
+ *
* @return the Switch's ID
*/
public Long getId();
/**
* Returns the Switch's table numbers supported by datapath
- *
+ *
* @return the tables
*/
public Byte getTables();
/**
* Returns the Switch's bitmap of supported ofp_action_type
- *
+ *
* @return the actions
*/
public Integer getActions();
/**
* Returns the Switch's bitmap of supported ofp_capabilities
- *
+ *
* @return the capabilities
*/
public Integer getCapabilities();
/**
* Returns the Switch's buffering capacity in Number of Pkts
- *
+ *
* @return the buffers
*/
public Integer getBuffers();
/**
* Returns the Date when the switch was connected.
- *
+ *
* @return Date The date when the switch was connected
*/
public Date getConnectedDate();
* should be used for non-critical messages such as statistics request,
* discovery packets, etc. An unique XID is generated automatically and
* inserted into the message.
- *
+ *
* @param msg
* The OF message to be sent
* @return The XID used
* priority. It will be served after high priority messages. The method
* should be used for non-critical messages such as statistics request,
* discovery packets, etc. The specified XID is inserted into the message.
- *
+ *
* @param msg
* The OF message to be Sent
* @param xid
* method should be used for critical messages such as hello, echo reply
* etc. An unique XID is generated automatically and inserted into the
* message.
- *
+ *
* @param msg
* The OF message to be sent
* @return The XID used
* priority. It will be served first before normal priority messages. The
* method should be used for critical messages such as hello, echo reply
* etc. The specified XID is inserted into the message.
- *
+ *
* @param msg
* The OF message to be sent
* @return The XID used
/**
* Sends the OF message followed by a Barrier Request with a unique XID
* which is automatically generated, and waits for a result from the switch.
- *
+ *
* @param msg
* The message to be sent
* @return An Object which has one of the followings instances/values:
/**
* Returns a map containing all OFPhysicalPorts of this switch.
- *
+ *
* @return The Map of OFPhysicalPort
*/
public Map<Short, OFPhysicalPort> getPhysicalPorts();
/**
* Returns a Set containing all port IDs of this switch.
- *
+ *
* @return The Set of port ID
*/
public Set<Short> getPorts();
/**
* Returns OFPhysicalPort of the specified portNumber of this switch.
- *
+ *
* @param portNumber
* The port ID
* @return OFPhysicalPort for the specified PortNumber
/**
* Returns the bandwidth of the specified portNumber of this switch.
- *
+ *
* @param portNumber
* the port ID
* @return bandwidth
/**
* Returns True if the port is enabled,
- *
+ *
* @param portNumber
* @return True if the port is enabled
*/
/**
* Returns True if the port is enabled.
- *
+ *
* @param port
* @return True if the port is enabled
*/
/**
* Returns a list containing all enabled ports of this switch.
- *
+ *
* @return: List containing all enabled ports of this switch
*/
public List<OFPhysicalPort> getEnabledPorts();
/**
* Sends OFStatisticsRequest with a unique XID generated automatically and
* waits for a result from the switch.
- *
+ *
* @param req
* the OF Statistic Request to be sent
* @return Object has one of the following instances/values::
/**
* Returns true if the switch has reached the operational state (has sent
* FEATURE_REPLY to the controller).
- *
+ *
* @return true if the switch is operational
*/
public boolean isOperational();
/**
* Function called by the dependency manager when all the required
* dependencies are satisfied
- *
+ *
*/
public void init() {
logger.debug("Initializing!");
/**
* Function called by dependency manager after "init ()" is called and after
* the services provided by the class are registered in the service registry
- *
+ *
*/
public void start() {
logger.debug("Starting!");
* Function called by the dependency manager before the services exported by
* the component are unregistered, this will be followed by a "destroy ()"
* calls
- *
+ *
*/
public void stop() {
for (Iterator<Entry<Long, ISwitch>> it = switches.entrySet().iterator(); it
* Function called by the dependency manager when at least one dependency
* become unsatisfied or when the component is shutting down because for
* example bundle is being stopped.
- *
+ *
*/
public void destroy() {
}
instanceName);
switchHandler.start();
if (sc.isConnected()) {
- logger.info("Switch:{} is connected to the Controller",
+ logger.info("Switch:{} is connected to the Controller",
sc.socket().getRemoteSocketAddress()
.toString().split("/")[1]);
}
/**
* Sends the OF message out over the socket channel.
- *
+ *
* @param msg
* OF message to be sent
* @throws Exception
/**
* Resumes sending the remaining messages in the outgoing buffer
- *
+ *
* @throws Exception
*/
@Override
/**
* Reads the incoming network data from the socket and retrieves the OF
* messages.
- *
+ *
* @return list of OF messages
* @throws Exception
*/
final static AtomicLong seq = new AtomicLong();
final long seqNum;
boolean syncReply; // set to true if we want to be blocked until the response arrives
-
+
public PriorityMessage(OFMessage msg, int priority) {
this.msg = msg;
this.priority = priority;
/**
* Bring up secure channel using SSL Engine
- *
+ *
* @param socket
* TCP socket channel
* @throws Exception
/**
* Sends the OF message out over the socket channel. The message is
* encrypted by SSL Engine.
- *
+ *
* @param msg
* OF message to be sent
* @throws Exception
/**
* Resumes sending the remaining messages in the outgoing buffer
- *
+ *
* @throws Exception
*/
@Override
/**
* Reads the incoming network data from the socket, decryptes them and then
* retrieves the OF messages.
- *
+ *
* @return list of OF messages
* @throws Exception
*/
/**
* Function called by the dependency manager when all the required
* dependencies are satisfied
- *
+ *
*/
void init() {
this.controller.addMessageListener(OFType.PACKET_IN, this);
* Function called by the dependency manager when at least one dependency
* become unsatisfied or when the component is shutting down because for
* example bundle is being stopped.
- *
+ *
*/
void destroy() {
this.controller.removeMessageListener(OFType.PACKET_IN, this);
public DescStatisticsConverter(List<OFStatistics> statsList) {
this.hwDesc = null;
- this.ofDesc = (statsList == null || statsList.isEmpty())?
+ this.ofDesc = (statsList == null || statsList.isEmpty())?
null : (OFDescriptionStatistics) statsList.get(0);
}
help.append("\t pcc - Print CC info\n");
help.append("\t psize - Print sizes of all the lists\n");
help.append("\t ptm - Print timeout info\n");
- help.append("\t ecc - Enable CC\n");
- help.append("\t dcc - Disable CC\n");
+ help.append("\t ecc - Enable CC\n");
+ help.append("\t dcc - Disable CC\n");
help.append("\t scc [multiple] - Set/show CC multiple and interval\n");
- help.append("\t sports [ports] - Set/show max ports per batch\n");
+ help.append("\t sports [ports] - Set/show max ports per batch\n");
help.append("\t spause [ticks] - Set/show pause period\n");
- help.append("\t sdi [ticks] - Set/show discovery interval in ticks\n");
+ help.append("\t sdi [ticks] - Set/show discovery interval in ticks\n");
help.append("\t stm [ticks] - Set/show per timeout ticks\n");
- help.append("\t sretry [count] - Set/show num of retries\n");
- help.append("\t addsw <swid> - Add a switch\n");
- help.append("\t remsw <swid> - Remove a switch\n");
+ help.append("\t sretry [count] - Set/show num of retries\n");
+ help.append("\t addsw <swid> - Add a switch\n");
+ help.append("\t remsw <swid> - Remove a switch\n");
help.append("\t page - Print aging info\n");
help.append("\t sage - Set/Show aging time limit\n");
- help.append("\t eage - Enable aging\n");
- help.append("\t dage - Disable aging\n");
+ help.append("\t eage - Enable aging\n");
+ help.append("\t dage - Disable aging\n");
help.append("\t pthrot - Print throttling\n");
help.append("\t ethrot - Enable throttling\n");
help.append("\t dthrot - Disable throttling\n");
}
}
ci.println("\n");
- ci.println(" NodeConnector Edge ");
+ ci.println(" NodeConnector Edge ");
Set<NodeConnector> keySet = prodMap.keySet();
if (keySet == null) {
return;
* Function called by the dependency manager when at least one dependency
* become unsatisfied or when the component is shutting down because for
* example bundle is being stopped.
- *
+ *
*/
void destroy() {
logger.debug("DESTROY called!");
/**
* Function called by dependency manager after "init ()" is called and after
* the services provided by the class are registered in the service registry
- *
+ *
*/
void start() {
logger.debug("START called!");
* Function called by the dependency manager before the services exported by
* the component are unregistered, this will be followed by a "destroy ()"
* calls
- *
+ *
*/
void stop() {
logger.debug("STOP called!");
/**
* Function called by the dependency manager when all the required
* dependencies are satisfied
- *
+ *
*/
void init() {
this.controller.addMessageListener(OFType.FLOW_REMOVED, this);
* Function called by the dependency manager when at least one dependency
* become unsatisfied or when the component is shutting down because for
* example bundle is being stopped.
- *
+ *
*/
void destroy() {
}
/**
* Function called by dependency manager after "init ()" is called and after
* the services provided by the class are registered in the service registry
- *
+ *
*/
void start() {
}
* Function called by the dependency manager before the services exported by
* the component are unregistered, this will be followed by a "destroy ()"
* calls
- *
+ *
*/
void stop() {
}
* will be inserted automatically to synchronize the
* progression.
*/
- result = asyncMsgSend(node, sw, msg, rid);
+ result = asyncMsgSend(node, sw, msg, rid);
}
return getStatusInternal(result, action, rid);
} else {
if ((rid == null) || (rid == 0)) {
return;
}
-
+
/*
* Notifies the caller that error has been reported for a previous flow
* programming request
return new Status(StatusCode.INTERNALERROR,
"Failed to send Barrier message.");
}
-
+
@Override
public Status asyncSendBarrierMessage(Node node) {
if (!node.getType().equals(NodeIDType.OPENFLOW)) {
return new Status(StatusCode.INTERNALERROR,
"Failed to send Barrier message.");
}
-
+
/**
* This method sends the message asynchronously until the number of messages
* sent reaches a threshold. Then a Barrier message is sent automatically
* for sync purpose. An unique Request ID associated with the message is
* passed down by the caller. The Request ID will be returned to the caller
* when an error message is received from the switch.
- *
+ *
* @param node
* The node
* @param msg
xid = sw.asyncSend(msg);
addXid2Rid(swid, xid, rid);
-
+
Map<Integer, Long> swxid2rid = this.xid2rid.get(swid);
if (swxid2rid == null) {
return result;
}
-
+
int size = swxid2rid.size();
if (size % barrierMessagePriorCount == 0) {
result = asyncSendBarrierMessage(node);
}
-
+
return result;
}
-
+
/**
* A number of async messages are sent followed by a synchronous Barrier
* message. This method returns the maximum async messages that can be sent
* before the Barrier message.
- *
+ *
* @return The max count of async messages sent prior to Barrier message
*/
private int getBarrierMessagePriorCount() {
return rv;
}
-
+
/**
* This method returns the message Request ID previously assigned by the
* caller for a given OF message xid
- *
+ *
* @param swid
* The switch id
* @param xid
/**
* This method returns a copy of outstanding xid to rid mappings.for a given
* switch
- *
+ *
* @param swid
* The switch id
* @return a copy of xid2rid mappings
*/
public Map<Integer, Long> getSwXid2Rid(long swid) {
Map<Integer, Long> swxid2rid = this.xid2rid.get(swid);
-
+
if (swxid2rid != null) {
return new HashMap<Integer, Long>(swxid2rid);
} else {
/**
* Adds xid to rid mapping to the local DB
- *
+ *
* @param swid
* The switch id
* @param xid
/**
* When an Error message is received, this method will be invoked to remove
* the offending xid from the local DB.
- *
+ *
* @param swid
* The switch id
* @param xid
/**
* Convert various result into Status
- *
+ *
* @param result
* The returned result from previous action
* @param action
"send", action, "Internal Error"));
}
}
-
+
/**
* When a Barrier reply is received, this method will be invoked to clear
* the local DB
- *
+ *
* @param swid
* The switch id
*/
@Override
public void updateNode(Node node, UpdateType type, Set<Property> props) {
long swid = (Long)node.getID();
-
+
switch (type) {
case ADDED:
Map<Integer, Long> swxid2rid = new HashMap<Integer, Long>();
ci.println("Please enter a valid node id");
return;
}
-
+
long sid;
try {
sid = HexEncode.stringToLong(st);
ci.println("Please enter a valid node id");
return;
}
-
+
Map<Integer, Long> swxid2rid = this.xid2rid.get(sid);
if (swxid2rid == null) {
ci.println("The node id entered does not exist");
}
ci.println("xid rid");
-
+
Set<Integer> xidSet = swxid2rid.keySet();
if (xidSet == null) {
return;
/**
* Converts an openflow list of flow statistics in a SAL list of FlowOnNode
* objects
- *
- *
- *
+ *
+ *
+ *
*/
public class FlowStatisticsConverter {
private static final Logger log = LoggerFactory
if (bw != null) {
props.add(bw);
}
-
+
Bandwidth abw = InventoryServiceHelper.OFPortToBandWidth(port.getAdvertisedFeatures());
if (abw != null) {
- AdvertisedBandwidth a = new AdvertisedBandwidth(abw.getValue());
- if (a != null) {
- props.add(a);
- }
+ AdvertisedBandwidth a = new AdvertisedBandwidth(abw.getValue());
+ if (a != null) {
+ props.add(a);
+ }
}
Bandwidth sbw = InventoryServiceHelper.OFPortToBandWidth(port.getSupportedFeatures());
if (sbw != null) {
- SupportedBandwidth s = new SupportedBandwidth(sbw.getValue());
- if (s != null) {
- props.add(s);
- }
+ SupportedBandwidth s = new SupportedBandwidth(sbw.getValue());
+ if (s != null) {
+ props.add(s);
+ }
}
Bandwidth pbw = InventoryServiceHelper.OFPortToBandWidth(port.getPeerFeatures());
if (pbw != null) {
- PeerBandwidth p = new PeerBandwidth(pbw.getValue());
- if (p != null) {
- props.add(p);
- }
+ PeerBandwidth p = new PeerBandwidth(pbw.getValue());
+ if (p != null) {
+ props.add(p);
+ }
}
props.add(new Name(port.getName()));
props.add(InventoryServiceHelper.OFPortToConfig(port.getConfig()));
/**
* Returns the average transmit rate in bps
- *
+ *
* @return the average transmit rate [bps]
*/
public long getAverageTxRate() {
/**
* Function called by the dependency manager when all the required
* dependencies are satisfied
- *
+ *
*/
void init() {
flowStatistics = new ConcurrentHashMap<Long, List<OFStatistics>>();
* Function called by the dependency manager when at least one dependency
* become unsatisfied or when the component is shutting down because for
* example bundle is being stopped.
- *
+ *
*/
void destroy() {
}
/**
* Function called by dependency manager after "init ()" is called and after
* the services provided by the class are registered in the service registry
- *
+ *
*/
void start() {
// Start managed timers
* Function called by the dependency manager before the services exported by
* the component are unregistered, this will be followed by a "destroy ()"
* calls
- *
+ *
*/
void stop() {
// Stop managed timers
/**
* Update the cached port rates for this switch with the latest retrieved
* port transmit byte count
- *
+ *
* @param switchId
*/
private synchronized void updatePortsTxRate(long switchId) {
/**
* Abstract class which provides the utilities for converting the Openflow port
* number to the equivalent NodeConnector and vice versa
- *
- *
- *
+ *
+ *
+ *
*/
public abstract class PortConverter {
private static final Logger log = LoggerFactory
/**
* Converts an openflow list of port statistics in a SAL list of
* NodeConnectorStatistics objects
- *
- *
- *
+ *
+ *
+ *
*/
public class PortStatisticsConverter {
private static final Logger log = LoggerFactory
/**
* Returns whether the passed NodeConnector belongs to the container
*
- * @param container container name
- * @param p node connector to test
- * @return true if belongs false otherwise
+ * @param container container name
+ * @param p node connector to test
+ * @return true if belongs false otherwise
*/
public boolean containerOwnsNodeConnector(String container, NodeConnector p) {
// All node connectors belong to the default container
/**
* Returns whether the passed NodeConnector belongs to the container
*
- * @param container container name
- * @param table node table to test
- * @return true if belongs false otherwise
+ * @param container container name
+ * @param table node table to test
+ * @return true if belongs false otherwise
*/
public boolean containerOwnsNodeTable(String container, NodeTable table) {
// All node table belong to the default container
/**
* Function called by the dependency manager when all the required
* dependencies are satisfied
- *
+ *
*/
@SuppressWarnings("unchecked")
void init(Component c) {
* Function called by the dependency manager when at least one dependency
* become unsatisfied or when the component is shutting down because for
* example bundle is being stopped.
- *
+ *
*/
void destroy() {
logger.trace("DESTROY called!");
/**
* Function called by dependency manager after "init ()" is called and after
* the services provided by the class are registered in the service registry
- *
+ *
*/
void start() {
logger.trace("START called!");
* Function called by the dependency manager before the services exported by
* the component are unregistered, this will be followed by a "destroy ()"
* calls
- *
+ *
*/
void stop() {
logger.trace("STOP called!");
/**
* Retrieve SAL service IPluginOutTopologyService
- *
+ *
* @param s
* Called by Dependency Manager as soon as the SAL service is
* available
/**
* called when SAL service IPluginOutTopologyService is no longer available
- *
+ *
* @param s
* Called by Dependency Manager as soon as the SAL service is
* unavailable
/**
* Retrieve OF protocol_plugin service IRefreshInternalProvider
- *
+ *
* @param s
* Called by Dependency Manager as soon as the SAL service is
* available
/**
* called when OF protocol_plugin service IRefreshInternalProvider is no
* longer available
- *
+ *
* @param s
* Called by Dependency Manager as soon as the SAL service is
* unavailable
er.readFrom(bb);
return er.toString();
}
-
+
// Handle OF1.0 errors here
OFErrorType et = OFErrorType.values()[0xffff & error.getErrorType()];
String errorStr = "Error : " + et.toString();
import org.openflow.protocol.OFError;
public class V6Error extends OFError {
- private static final long serialVersionUID = 1L;
- public static int MINIMUM_LENGTH = 20;//OfHdr(8) + NXET_VENDOR(2) + NXEC_VENDOR_ERROR(2) + struct nx_vendor_error(8)
- public static final short NICIRA_VENDOR_ERRORTYPE = (short)0xb0c2;
- protected int V6VendorId;
+ private static final long serialVersionUID = 1L;
+ public static int MINIMUM_LENGTH = 20;//OfHdr(8) + NXET_VENDOR(2) + NXEC_VENDOR_ERROR(2) + struct nx_vendor_error(8)
+ public static final short NICIRA_VENDOR_ERRORTYPE = (short)0xb0c2;
+ protected int V6VendorId;
protected short V6VendorErrorType;
protected short V6VendorErrorCode;
protected byte[] V6ErrorData;
-
+
public V6Error(OFError e) {
this.length = (short)e.getLengthU();
this.errorType = e.getErrorType();
this.errorCode = e.getErrorCode();
this.xid = e.getXid();
}
-
+
@Override
public void readFrom(ByteBuffer data) {
this.V6VendorId = data.getInt();
if (dataLength > 0) {
this.V6ErrorData = new byte[dataLength];
data.get(this.V6ErrorData);
- }
+ }
}
-
+
/**
* @return the V6VendorId
*/
public int getVendorId() {
return V6VendorId;
}
-
+
/**
* @return the V6VendorErrorType
*/
public short getVendorErrorType() {
return V6VendorErrorType;
}
-
+
/**
* @return the VendorErrorType
*/
public short getVendorErrorCode() {
return V6VendorErrorCode;
}
-
+
/**
* @return the Error Bytes
*/
public byte[] getError() {
return V6ErrorData;
}
-
+
@Override
public int hashCode() {
final int prime = 31;
/**
* This class is used to create IPv6 Vendor Extension messages. Specfically, It
* defines the methods used in creation of Vendor specific IPv6 Flow Mod message.
- *
+ *
*
*/
public class V6FlowMod extends OFVendor implements Cloneable {
private static int IPV6_EXT_MIN_HDR_LEN = 36;
/**
- * Constructor for the V6FlowMod class. Initializes OFVendor (parent class)
+ * Constructor for the V6FlowMod class. Initializes OFVendor (parent class)
* fields by calling the parent class' constructor.
*/
public V6FlowMod() {
/**
* This method sets the match fields of V6FlowMod object
- * @param match V6Match object for this V6FlowMod message
+ * @param match V6Match object for this V6FlowMod message
*/
public void setMatch(V6Match match) {
this.match = match;
/**
* Sets the list of actions V6FlowMod message
- * @param actions a list of ordered OFAction objects
+ * @param actions a list of ordered OFAction objects
*/
public void setActions(List<OFAction> actions) {
this.actions = actions;
/**
* Sets the priority field of V6FlowMod message
- * @param priority Priority of the message
+ * @param priority Priority of the message
*/
public void setPriority(short priority) {
this.priority = priority;
/**
* Sets the cookie field of V6FlowMod message
- * @param cookie Cookie of the message
+ * @param cookie Cookie of the message
*/
public void setCookie(long cookie) {
this.cookie = cookie;
/**
* Sets the command field of V6FlowMod message
- * @param command Command type of the message (ADD or DELETE)
+ * @param command Command type of the message (ADD or DELETE)
*/
public V6FlowMod setCommand(short command) {
this.command = command;
/**
* Sets the outPort field of V6FlowMod message
- * @param outPort outPort of the message
+ * @param outPort outPort of the message
*/
public V6FlowMod setOutPort(OFPort port) {
this.outPort = port.getValue();
/**
* Sets the idle_timeout of V6FlowMod message
- * @param idleTimeout idle timeout for this message
+ * @param idleTimeout idle timeout for this message
*/
public void setIdleTimeout(short idleTimeout) {
this.idleTimeout = idleTimeout;
/**
* Sets the hardTimeout field of V6FlowMod message
- * @param hardTimeout hard timeout of the message
+ * @param hardTimeout hard timeout of the message
*/
public void setHardTimeout(short hardTimeout) {
this.hardTimeout = hardTimeout;
/**
* Returns the Flow Mod message subtype for V6FlowMod message
- * @return message subtype
+ * @return message subtype
*/
private int getIPv6ExtensionFlowModAddSubType() {
return IPV6EXT_ADD_FLOW_MSG_TYPE;
}
-
+
/**
* Returns the minimum header size for V6Flow Message type
- * @return minimum header size
+ * @return minimum header size
*/
public int getV6FlowModMinHdrSize() {
return IPV6_EXT_MIN_HDR_LEN;
}
-
+
/**
* Sets the Vendor type in OFVendor message
*/
public void setVendor() {
super.setVendor(V6StatsRequest.NICIRA_VENDOR_ID);
}
-
+
/**
* Get flags
* @return
public void setFlags(short flags) {
this.flags = flags;
}
-
+
/**
* This method forms the Vendor extension IPv6 Flow Mod message.It uses the
- * fields in V6FlowMod class, and writes the data according to vendor
+ * fields in V6FlowMod class, and writes the data according to vendor
* extension format. The fields include flow properties (cookie, timeout,
- * priority, etc), flow match, and action list. It also takes care of
+ * priority, etc), flow match, and action list. It also takes care of
* required padding.
*/
/**
* Forms the clone of V6FlowMod Object. If Object is returned
- * successfully, then returns the cloned object. Throws an
+ * successfully, then returns the cloned object. Throws an
* exception if cloning is not supported.
*/
@Override
/**
* This Class forms the vendor specific IPv6 Flow Match messages as well as
* processes the vendor specific IPv6 Stats Reply message.
- *
- * For message creation, it parses the user entered IPv6 match fields, creates
- * a sub-message for each field which are later used to form the complete
- * message.
- *
+ *
+ * For message creation, it parses the user entered IPv6 match fields, creates
+ * a sub-message for each field which are later used to form the complete
+ * message.
+ *
* For message processing, it parses the incoming message and reads each field
* of the message and stores in appropriate field of V6Match object.
- *
+ *
*
*/
public class V6Match extends OFMatch implements Cloneable {
/**
* Sets this (V6Match) object's member variables based on a comma-separated key=value pair similar to OFMatch's fromString.
- *
+ *
* @param match a key=value comma separated string.
*/
@Override
/**
* This Class processes the OpenFlow Vendor Extension Reply message of a Stats
* Request. It parses the reply message and initializes fields of V6StatsReply
- * object. Multiple instances of this class objects are created and used by
+ * object. Multiple instances of this class objects are created and used by
* OpenDaylight's Troubleshooting Application.
- *
+ *
*/
public class V6StatsReply extends OFVendorStatistics {
/**
- * This Class creates the OpenFlow Vendor Extension IPv6 Flow Stats Request
+ * This Class creates the OpenFlow Vendor Extension IPv6 Flow Stats Request
* messages and also reads the Reply of a stats request message.
- *
+ *
*/
public class V6StatsRequest extends OFVendorStatistics {
/**
* stub protocol plugin Activator
- *
- *
+ *
+ *
*/
public class Activator extends ComponentActivatorAbstractBase {
protected static final Logger logger = LoggerFactory
/**
* Function called when the activator starts just after some initializations
* are done by the ComponentActivatorAbstractBase.
- *
+ *
*/
public void init() {
Node.NodeIDType.registerIDType("STUB", Integer.class);
/**
* Function called when the activator stops just before the cleanup done by
* ComponentActivatorAbstractBase
- *
+ *
*/
public void destroy() {
Node.NodeIDType.unRegisterIDType("STUB");
/**
* Function that is used to communicate to dependency manager the list of
* known implementations for services inside a container
- *
- *
+ *
+ *
* @return An array containing all the CLASS objects that will be
* instantiated in order to get an fully working implementation
* Object
/**
* Function that is called when configuration of the dependencies is
* required.
- *
+ *
* @param c
* dependency manager Component object, used for configuring the
* dependencies exported and imported
c.setInterface(IPluginInInventoryService.class.getName(), props);
}
}
-
+
public Object[] getGlobalImplementations() {
Object[] res = { FlowProgrammerService.class, StubNodeFactory.class, StubNodeConnectorFactory.class };
return res;
}
-
+
public void configureGlobalInstance(Component c, Object imp){
if (imp.equals(FlowProgrammerService.class)) {
// export the service to be used by SAL
props.put("protocolName", "STUB");
c.setInterface(INodeConnectorFactory.class.getName(), props);
}
-
+
}
}
* Function called by the dependency manager when at least one dependency
* become unsatisfied or when the component is shutting down because for
* example bundle is being stopped.
- *
+ *
*/
void destroy() {
}
/**
* Function called by dependency manager after "init ()" is called and after
* the services provided by the class are registered in the service registry
- *
+ *
*/
void start() {
}
* Function called by the dependency manager before the services exported by
* the component are unregistered, this will be followed by a "destroy ()"
* calls
- *
+ *
*/
void stop() {
}
-
-
+
+
/**
* Synchronously add a flow to the network node
- *
+ *
* @param node
* @param flow
*/
/**
* Synchronously modify existing flow on the switch
- *
+ *
* @param node
* @param flow
*/
}
/**
* Synchronously remove the flow from the network node
- *
+ *
* @param node
* @param flow
*/
/**
* Asynchronously add a flow to the network node
- *
+ *
* @param node
* @param flow
* @param rid
/**
* Asynchronously modify existing flow on the switch
- *
+ *
* @param node
* @param flow
* @param rid
/**
* Asynchronously remove the flow from the network node
- *
+ *
* @param node
* @param flow
* @param rid
/**
* Remove all flows present on the network node
- *
+ *
* @param node
*/
public Status removeAllFlows(Node node){
/**
* Send Barrier message synchronously. The caller will be blocked until the
* Barrier reply arrives.
- *
+ *
* @param node
*/
public Status syncSendBarrierMessage(Node node){
/**
* Send Barrier message asynchronously. The caller is not blocked.
- *
+ *
* @param node
*/
public Status asyncSendBarrierMessage(Node node){
node = new Node("STUB", new Integer(0xCAFE));
}catch(ConstructionException e){
node = null;
- }
-
+ }
+
nodeProps.put(node, propMap);
-
+
try{
node = new Node("STUB", 3366);
}catch(ConstructionException e){
node = null;
- }
+ }
nodeProps.put(node, propMap);
-
+
try{
node = new Node("STUB", 4477);
}catch(ConstructionException e){
node = null;
- }
+ }
nodeProps.put(node, propMap);
-
+
return nodeProps;
}
import org.opendaylight.controller.sal.reader.NodeTableStatistics;
/**
* Stub Implementation for IPluginInReadService used by SAL
- *
- *
+ *
+ *
*/
public class ReadService implements IPluginInReadService {
private static final Logger logger = LoggerFactory
/**
* Function called by the dependency manager when all the required
* dependencies are satisfied
- *
+ *
*/
void init() {
}
* Function called by the dependency manager when at least one dependency
* become unsatisfied or when the component is shutting down because for
* example bundle is being stopped.
- *
+ *
*/
void destroy() {
}
/**
* Function called by dependency manager after "init ()" is called and after
* the services provided by the class are registered in the service registry
- *
+ *
*/
void start() {
}
* Function called by the dependency manager before the services exported by
* the component are unregistered, this will be followed by a "destroy ()"
* calls
- *
+ *
*/
void stop() {
}
* Function called by the dependency manager when at least one dependency
* become unsatisfied or when the component is shutting down because for
* example bundle is being stopped.
- *
+ *
*/
void destroy() {
}
/**
* Function called by dependency manager after "init ()" is called and after
* the services provided by the class are registered in the service registry
- *
+ *
*/
void start() {
}
* Function called by the dependency manager before the services exported by
* the component are unregistered, this will be followed by a "destroy ()"
* calls
- *
+ *
*/
void stop() {
}
-
+
public NodeConnector fromStringNoNode(String typeStr, String IDStr,
Node n){
if(typeStr.equals("STUB")){
* Function called by the dependency manager when at least one dependency
* become unsatisfied or when the component is shutting down because for
* example bundle is being stopped.
- *
+ *
*/
void destroy() {
}
/**
* Function called by dependency manager after "init ()" is called and after
* the services provided by the class are registered in the service registry
- *
+ *
*/
void start() {
}
* Function called by the dependency manager before the services exported by
* the component are unregistered, this will be followed by a "destroy ()"
* calls
- *
+ *
*/
void stop() {
}
-
+
public Node fromString(String nodeType, String nodeId){
if(nodeType.equals("STUB"))
try{
/**
* Function called by the dependency manager when all the required
* dependencies are satisfied
- *
+ *
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public void init() {
* Function called by the dependency manager when at least one dependency
* become unsatisfied or when the component is shutting down because for
* example bundle is being stopped.
- *
+ *
*/
void destroy() {
log.debug("Routing destroy() is called");
/**
* Function called by dependency manager after "init ()" is called and after
* the services provided by the class are registered in the service registry
- *
+ *
*/
void start() {
log.debug("Routing start() is called");
* Function called by the dependency manager before the services exported by
* the component are unregistered, this will be followed by a "destroy ()"
* calls
- *
+ *
*/
public void stop() {
log.debug("Routing stop() is called");
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
@XmlSeeAlso({Controller.class, Drop.class, Flood.class, FloodAll.class, HwPath.class, Loopback.class, Output.class,
- PopVlan.class, PushVlan.class, SetDlDst.class, SetDlSrc.class, SetDlType.class, SetNwDst.class, SetNwSrc.class,
- SetNwTos.class, SetTpDst.class, SetTpSrc.class, SetVlanCfi.class, SetVlanId.class, SetVlanPcp.class, SwPath.class})
+ PopVlan.class, PushVlan.class, SetDlDst.class, SetDlSrc.class, SetDlType.class, SetNwDst.class, SetNwSrc.class,
+ SetNwTos.class, SetTpDst.class, SetTpSrc.class, SetVlanCfi.class, SetVlanId.class, SetVlanPcp.class, SwPath.class})
public abstract class Action {
private static final Logger logger = LoggerFactory.getLogger(Action.class);
private static boolean debug = false; // Enable to find where in the code an invalid assignment is made
/*
public Action (ActionType type, Object value) {
- this.type = type;
- this.value = value;
- this.isValid = true;
+ this.type = type;
+ this.value = value;
+ this.isValid = true;
} */
/**
/**
* Returns whether the Action is valid or not
*
- * @return boolean
+ * @return boolean
*/
public boolean isValid() {
return isValid;
@XmlAccessorType(XmlAccessType.NONE)
public class Output extends Action {
- @XmlElement
+ @XmlElement
private NodeConnector port;
/* Dummy constructor for JAXB */
* Execute it multiple times to achieve QinQ
*
* 802.1q = [TPID(16) + TCI(16)]
- * TCI = [PCP(3) + CFI(1) + VID(12)]
+ * TCI = [PCP(3) + CFI(1) + VID(12)]
*
*
*
public byte[] getDlAddress() {
return address.clone();
}
-
+
@XmlElement(name = "address")
public String getDlAddressString() {
return HexEncode.bytesToHexString(address);
}
-
+
@Override
public boolean equals(Object obj) {
if (this == obj)
public String getDlAddressString() {
return HexEncode.bytesToHexString(address);
}
-
+
@Override
public boolean equals(Object obj) {
if (this == obj)
@XmlAccessorType(XmlAccessType.NONE)
public class SetDlType extends Action {
- @XmlElement
+ @XmlElement
private int dlType;
/* Dummy constructor for JAXB */
/**
* Returns the network address this action will set
*
- * @return InetAddress
+ * @return InetAddress
*/
public InetAddress getAddress() {
return address;
}
-
+
@XmlElement (name="address")
public String getAddressAsString() {
- return address.getHostAddress();
+ return address.getHostAddress();
}
@Override
/**
* Returns the network address this action will set
*
- * @return InetAddress
+ * @return InetAddress
*/
public InetAddress getAddress() {
return address;
@XmlElement (name="address")
public String getAddressAsString() {
- return address.getHostAddress();
+ return address.getHostAddress();
}
@Override
@XmlAccessorType(XmlAccessType.NONE)
public class SetNwTos extends Action {
- @XmlElement
+ @XmlElement
private int tos;
/* Dummy constructor for JAXB */
@XmlAccessorType(XmlAccessType.NONE)
public class SetTpDst extends Action {
- @XmlElement
+ @XmlElement
private int port;
/* Dummy constructor for JAXB */
@XmlAccessorType(XmlAccessType.NONE)
public class SetTpSrc extends Action {
- @XmlElement
+ @XmlElement
private int port;
/* Dummy constructor for JAXB */
@XmlAccessorType(XmlAccessType.NONE)
public class SetVlanCfi extends Action {
- @XmlElement
+ @XmlElement
private int cfi;
/* Dummy constructor for JAXB */
@XmlAccessorType(XmlAccessType.NONE)
public class SetVlanId extends Action {
- @XmlElement
+ @XmlElement
private int vlanId;
- private SetVlanId() {
-
- }
-
+ private SetVlanId() {
+
+ }
+
public SetVlanId(int vlanId) {
type = ActionType.SET_VLAN_ID;
this.vlanId = vlanId;
@XmlAccessorType(XmlAccessType.NONE)
public class SetVlanPcp extends Action {
- @XmlElement
+ @XmlElement
private int pcp;
- private SetVlanPcp() {
-
- }
-
+ private SetVlanPcp() {
+
+ }
+
public SetVlanPcp(int pcp) {
type = ActionType.SET_VLAN_PCP;
this.pcp = pcp;
public String toStringPretty() {
return this.prettyLevel;
}
-
+
public static AppRoleLevel fromString(String levelString) {
- for (AppRoleLevel level : AppRoleLevel.values()) {
- if (level.toString().equals(levelString)) {
- return level;
- }
- }
- return null;
+ for (AppRoleLevel level : AppRoleLevel.values()) {
+ if (level.toString().equals(levelString)) {
+ return level;
+ }
+ }
+ return null;
}
-}
+}
/**
* Create a Role name for the application
*
- * @param role the role name
- * @param userLevel the user level in the application context
- * @return the status of the request
- */
+ * @param role the role name
+ * @param userLevel the user level in the application context
+ * @return the status of the request
+ */
public Status createRole(String role, AppRoleLevel userLevel);
/**
* Remove a Role
- *
+ *
* @param role the role name
* @return the status of the request
*/
public Status removeRole(String role);
-
+
/**
* Return the list of roles configured for the application
*
*
* @param roleName the role name to query
* @return the application level of the given role in the application context as specified by {@link AppRoleLevel}
- * if the role is not part of this application's roles, <code>NOUSER<code> is returned
+ * if the role is not part of this application's roles, <code>NOUSER<code> is returned
*/
public AppRoleLevel getApplicationRoleLevel(String roleName);
* Returns whether the specified role is part of this application's roles
*
* @param roleName the role name to test
- * @return true if the role belongs to this application, false otherwise
+ * @return true if the role belongs to this application, false otherwise
*/
public boolean isApplicationRole(String roleName);
* @return the status of the request
*/
public Status assignResourceGroupToRole(String groupName, String role);
-
+
/**
* Unassign the passed resource group from the specified role
- *
+ *
* @param group
* @param role
* @return the status of the request
*/
public Status unassignResourceGroupFromRole(String group, String role);
-
+
/**
* Returns the list of resource groups the given Role is authorized to use
* The returning object expresses the resource group name and the access
* Describes the user role level in the controller space
*/
public enum UserLevel implements Serializable {
- SYSTEMADMIN(0, "System-Admin", "System Administrator"), // can do everything
- NETWORKADMIN(1, "Network-Admin", "Network Administrator"), // can do everything but setting a system admin user profile
- NETWORKOPERATOR(2, "Network-Operator", "Network Operator"), // can only see what is configured anywhere
- CONTAINERUSER(4, "Container-User", "Container User"), // container context user
- APPUSER(5, "App-User", "Application User"), // application context user
+ SYSTEMADMIN(0, "System-Admin", "System Administrator"), // can do everything
+ NETWORKADMIN(1, "Network-Admin", "Network Administrator"), // can do everything but setting a system admin user profile
+ NETWORKOPERATOR(2, "Network-Operator", "Network Operator"), // can only see what is configured anywhere
+ CONTAINERUSER(4, "Container-User", "Container User"), // container context user
+ APPUSER(5, "App-User", "Application User"), // application context user
NOUSER(255, "Not Authorized", "Not Authorized");
private int userLevel;
@XmlRootElement
public class Actions extends Property {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
@XmlElement
private int actionsValue;
-
- public enum ActionType {
- OUTPUT_PORT_ACTION(1<<0),
- VLAN_VID_ACTION(1<<1),
- VLAN_PCP_ACTION(1<<2),
- VLAN_STRIP_ACTION(1<<3),
- DLSRC_ACTION(1<<4),
- DLDST_ACTION(1<<5),
- NWSRC_ACTION(1<<6),
- NWDST_ACTION(1<<7),
- NWTOS_ACTION(1<<8),
- TPTSRC_ACTION(1<<9),
- TPTDST_ACTION(1<<10),
- ENQUEUE_ACTION(1<<11),
- VENDOR_ACTION(0xffff);
- private final int at;
- ActionType(int val) {
- this.at = val;
- }
- public int getValue() {
- return at;
- }
+
+ public enum ActionType {
+ OUTPUT_PORT_ACTION(1<<0),
+ VLAN_VID_ACTION(1<<1),
+ VLAN_PCP_ACTION(1<<2),
+ VLAN_STRIP_ACTION(1<<3),
+ DLSRC_ACTION(1<<4),
+ DLDST_ACTION(1<<5),
+ NWSRC_ACTION(1<<6),
+ NWDST_ACTION(1<<7),
+ NWTOS_ACTION(1<<8),
+ TPTSRC_ACTION(1<<9),
+ TPTDST_ACTION(1<<10),
+ ENQUEUE_ACTION(1<<11),
+ VENDOR_ACTION(0xffff);
+ private final int at;
+ ActionType(int val) {
+ this.at = val;
+ }
+ public int getValue() {
+ return at;
+ }
}
-
+
public static final String ActionsPropName = "actions";
/**
* Construct a actions property
public Actions clone() {
return new Actions(this.actionsValue);
}
-
+
public int getValue() {
- return this.actionsValue;
+ return this.actionsValue;
}
-
-
+
+
@Override
public int hashCode() {
final int prime = 31;
@XmlRootElement
@SuppressWarnings("serial")
public class AdvertisedBandwidth extends Bandwidth {
- public static final String AdvertisedBandwidthPropName = "advertisedBandwidth";
-
- public AdvertisedBandwidth(long value) {
- super(AdvertisedBandwidthPropName);
- this.bandwidthValue = value;
- }
-
- /*
+ public static final String AdvertisedBandwidthPropName = "advertisedBandwidth";
+
+ public AdvertisedBandwidth(long value) {
+ super(AdvertisedBandwidthPropName);
+ this.bandwidthValue = value;
+ }
+
+ /*
* Private constructor used for JAXB mapping
*/
private AdvertisedBandwidth() {
- super(AdvertisedBandwidthPropName);
- this.bandwidthValue = 0;
+ super(AdvertisedBandwidthPropName);
+ this.bandwidthValue = 0;
}
-
- public AdvertisedBandwidth clone() {
- return new AdvertisedBandwidth(this.bandwidthValue);
+
+ public AdvertisedBandwidth clone() {
+ return new AdvertisedBandwidth(this.bandwidthValue);
}
-
+
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
super(BandwidthPropName);
this.bandwidthValue = (long) bandwidth;
}
-
+
public Bandwidth(String name) {
super(name);
}
*/
@XmlRootElement
public class Buffers extends Property {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
@XmlElement
private int buffersValue;
-
+
public static final String BuffersPropName = "buffers";
-
+
/**
* Construct a Buffers property
*
- * @param buffers the Buffers
+ * @param buffers the Buffers
* @return Constructed object
*/
public Buffers(int buffers) {
public int getValue() {
return this.buffersValue;
}
-
+
@Override
public int hashCode() {
final int prime = 31;
*/
@XmlRootElement
public class Capabilities extends Property {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
@XmlElement
private int capabilitiesValue;
-
- public enum CapabilitiesType {
- FLOW_STATS_CAPABILITY(1<<0),
- TABLE_STATS_CAPABILITY(1<<1),
- PORT_STATS_CAPABILITY(1<<2),
- STP_CAPABILITY(1<<3),
- RSVD_CAPABILITY(1<<4),
- IP_REASSEM_CAPABILITY(1<<5),
- QUEUE_STATS_CAPABILITY(1<<6),
- ARP_MATCH_IP_CAPABILITY(1<<7);
- private final int ct;
- CapabilitiesType(int val) {
- this.ct = val;
- }
- public int getValue() {
- return ct;
- }
+
+ public enum CapabilitiesType {
+ FLOW_STATS_CAPABILITY(1<<0),
+ TABLE_STATS_CAPABILITY(1<<1),
+ PORT_STATS_CAPABILITY(1<<2),
+ STP_CAPABILITY(1<<3),
+ RSVD_CAPABILITY(1<<4),
+ IP_REASSEM_CAPABILITY(1<<5),
+ QUEUE_STATS_CAPABILITY(1<<6),
+ ARP_MATCH_IP_CAPABILITY(1<<7);
+ private final int ct;
+ CapabilitiesType(int val) {
+ this.ct = val;
+ }
+ public int getValue() {
+ return ct;
+ }
}
-
+
public static final String CapabilitiesPropName = "capabilities";
/**
* Construct a Capabilities property
}
public int getValue() {
- return this.capabilitiesValue;
+ return this.capabilitiesValue;
}
-
+
@Override
public int hashCode() {
final int prime = 31;
}
}
}
-
+
// Register with OSGi the provider for the service IContainerAware
context.registerService(
IContainerAware.class.getName(), this, null);
/**
* The class represents Admin Config status
- *
- *
+ *
+ *
*/
@XmlRootElement
@SuppressWarnings("serial")
/**
* Returns whether the specified match is allowed
*
- * @param match the match to test
+ * @param match the match to test
* @return true if the match is allowed, false otherwise
*/
public boolean allowsMatch(Match target) {
*/
@XmlRootElement
public class PeerBandwidth extends Bandwidth {
- private static final long serialVersionUID = 1L;
-
- public static final String PeerBandwidthPropName = "peerBandwidth";
-
- public PeerBandwidth(long value) {
- super(PeerBandwidthPropName);
- this.bandwidthValue = value;
- }
-
- /*
+ private static final long serialVersionUID = 1L;
+
+ public static final String PeerBandwidthPropName = "peerBandwidth";
+
+ public PeerBandwidth(long value) {
+ super(PeerBandwidthPropName);
+ this.bandwidthValue = value;
+ }
+
+ /*
* Private constructor used for JAXB mapping
*/
private PeerBandwidth() {
- super(PeerBandwidthPropName);
- this.bandwidthValue = 0;
+ super(PeerBandwidthPropName);
+ this.bandwidthValue = 0;
}
- public PeerBandwidth clone() {
- return new PeerBandwidth(this.bandwidthValue);
+ public PeerBandwidth clone() {
+ return new PeerBandwidth(this.bandwidthValue);
}
-
+
@Override
public String toString() {
*/
@XmlRootElement
public class SupportedBandwidth extends Bandwidth {
- private static final long serialVersionUID = 1L;
- public static final String SupportedBandwidthPropName = "supportedBandwidth";
-
- public SupportedBandwidth(long value) {
- super(SupportedBandwidthPropName);
- this.bandwidthValue = value;
- }
-
- /*
+ private static final long serialVersionUID = 1L;
+ public static final String SupportedBandwidthPropName = "supportedBandwidth";
+
+ public SupportedBandwidth(long value) {
+ super(SupportedBandwidthPropName);
+ this.bandwidthValue = value;
+ }
+
+ /*
* Private constructor used for JAXB mapping
*/
private SupportedBandwidth() {
- super(SupportedBandwidthPropName);
- this.bandwidthValue = 0;
+ super(SupportedBandwidthPropName);
+ this.bandwidthValue = 0;
}
-
- public SupportedBandwidth clone() {
- return new SupportedBandwidth(this.bandwidthValue);
+
+ public SupportedBandwidth clone() {
+ return new SupportedBandwidth(this.bandwidthValue);
}
@Override
*/
@XmlRootElement
public class Tables extends Property {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
@XmlElement
private byte tablesValue;
-
+
public static final String TablesPropName = "tables";
/**
* Construct a Tables property
*
- * @param tables the Tables
+ * @param tables the Tables
* @return Constructed object
*/
public Tables(byte tables) {
public byte getValue() {
return this.tablesValue;
}
-
+
@Override
public int hashCode() {
final int prime = 31;
/**
* The methods is called when an edge is added/deleted/changed
*
- * @param edge {@link org.opendaylight.controller.sal.core.Edge} being updated
- * @param type {@link org.opendaylight.controller.sal.core.UpdateType}
- * @param props set of {@link org.opendaylight.controller.sal.core.Property} like
- * {@link org.opendaylight.controller.sal.core.Bandwidth} and/or
- * {@link org.opendaylight.controller.sal.core.Latency} etc.
+ * @param edge {@link org.opendaylight.controller.sal.core.Edge} being updated
+ * @param type {@link org.opendaylight.controller.sal.core.UpdateType}
+ * @param props set of {@link org.opendaylight.controller.sal.core.Property} like
+ * {@link org.opendaylight.controller.sal.core.Bandwidth} and/or
+ * {@link org.opendaylight.controller.sal.core.Latency} etc.
*/
public void notifyEdge(Edge edge, UpdateType type, Set<Property> props);
}
public class Flow implements Cloneable, Serializable {
protected static final Logger logger = LoggerFactory
.getLogger(Flow.class);
- private static final long serialVersionUID = 1L;
- @XmlElement
+ private static final long serialVersionUID = 1L;
+ @XmlElement
private Match match;
@XmlElement
private List<Action> actions;
public interface IFlowProgrammerService {
/**
* Synchronously add a flow to the network node
- *
+ *
* @param node
* The target network node
* @param flow
/**
* Synchronously modify existing flow on the switch
- *
+ *
* @param node
* The target network node
* @param oldFlow
/**
* Synchronously remove the flow from the network node
- *
+ *
* @param node
* The target network node
* @param flow
/**
* Asynchronously add a flow to the network node
- *
+ *
* @param node
* The target network node
* @param flow
/**
* Asynchronously modify existing flow on the switch
- *
+ *
* @param node
* The target network node
* @param oldFlow
/**
* Asynchronously remove the flow from the network node
- *
+ *
* @param node
* The target network node
* @param flow
/**
* Remove all flows present on the network node
- *
+ *
* @param node
* The target network node
* @return The status of this request containing the unique request id
/**
* Send Barrier message synchronously. The caller will be blocked until the
* solicitation response arrives.
- *
+ *
* Solicit the network node to report whether all the requests sent so far
* are completed. When this call is done, caller knows that all past flow
* operations requested to the node in asynchronous fashion were satisfied
* by the network node and that in case of any failure, a message was sent
* to the controller.
- *
+ *
* @param node
* The network node to solicit
* @return The status of this request containing the unique request id
/**
* Send Barrier message asynchronously. The caller is not blocked.
- *
+ *
* Solicit the network node to report whether all the requests sent so far
* are completed. When this call is done, caller knows that all past flow
* operations requested to the node in asynchronous fashion were satisfied
* by the network node and that in case of any failure, a message was sent
* to the controller.
- *
+ *
* @param node
* The network node to solicit
* @return The status of this request containing the unique request id
/**
* @file IPluginOutFlowProgrammer.java
- *
+ *
* @brief Flow programmer interface to be implemented by protocol plugins
*/
public interface IPluginInFlowProgrammerService {
/**
* Synchronously add a flow to the network node
- *
+ *
* @param node
* @param flow
*/
/**
* Synchronously modify existing flow on the switch
- *
+ *
* @param node
* @param flow
*/
/**
* Synchronously remove the flow from the network node
- *
+ *
* @param node
* @param flow
*/
/**
* Asynchronously add a flow to the network node
- *
+ *
* @param node
* @param flow
* @param rid
/**
* Asynchronously modify existing flow on the switch
- *
+ *
* @param node
* @param flow
* @param rid
/**
* Asynchronously remove the flow from the network node
- *
+ *
* @param node
* @param flow
* @param rid
/**
* Remove all flows present on the network node
- *
+ *
* @param node
*/
Status removeAllFlows(Node node);
/**
* Send Barrier message synchronously. The caller will be blocked until the
* Barrier reply arrives.
- *
+ *
* @param node
*/
Status syncSendBarrierMessage(Node node);
/**
* Send Barrier message asynchronously. The caller is not blocked.
- *
+ *
* @param node
*/
Status asyncSendBarrierMessage(Node node);
* Inform SAL that the flow on the specified node has been removed Consumer
* has to expect this notification only for flows which were installed with
* an idle or hard timeout specified.
- *
+ *
* @param node
* the network node on which the flow got removed
* @param flow
* Inform SAL that an error message has been received from a switch
* regarding a flow message previously sent to the switch. A Request ID
* associated with the offending message is also returned.
- *
+ *
* @param node
* the network node on which the error reported
* @param rid
/**
* This method is called when some properties of a node are added/deleted/changed.
*
- * @param node {@link org.opendaylight.controller.sal.core.Node} being updated
- * @param type {@link org.opendaylight.controller.sal.core.UpdateType}
- * @param props set of {@link org.opendaylight.controller.sal.core.Property} such as
- * {@link org.opendaylight.controller.sal.core.Description} and/or
- * {@link org.opendaylight.controller.sal.core.Tier} etc.
+ * @param node {@link org.opendaylight.controller.sal.core.Node} being updated
+ * @param type {@link org.opendaylight.controller.sal.core.UpdateType}
+ * @param props set of {@link org.opendaylight.controller.sal.core.Property} such as
+ * {@link org.opendaylight.controller.sal.core.Description} and/or
+ * {@link org.opendaylight.controller.sal.core.Tier} etc.
*/
public void updateNode(Node node, UpdateType type, Set<Property> props);
/**
* This method is called when some properties of a node connector are added/deleted/changed.
*
- * @param nodeConnector {@link org.opendaylight.controller.sal.core.NodeConnector} being updated
- * @param type {@link org.opendaylight.controller.sal.core.UpdateType}
- * @param props set of {@link org.opendaylight.controller.sal.core.Property} such as
- * {@link org.opendaylight.controller.sal.core.Description} and/or
- * {@link org.opendaylight.controller.sal.core.State} etc.
+ * @param nodeConnector {@link org.opendaylight.controller.sal.core.NodeConnector} being updated
+ * @param type {@link org.opendaylight.controller.sal.core.UpdateType}
+ * @param props set of {@link org.opendaylight.controller.sal.core.Property} such as
+ * {@link org.opendaylight.controller.sal.core.Description} and/or
+ * {@link org.opendaylight.controller.sal.core.State} etc.
*/
public void updateNodeConnector(NodeConnector nodeConnector,
UpdateType type, Set<Property> props);
/**
* This method is called when some properties of a node are added/deleted/changed.
*
- * @param node {@link org.opendaylight.controller.sal.core.Node} being updated
- * @param type {@link org.opendaylight.controller.sal.core.UpdateType}
- * @param props set of {@link org.opendaylight.controller.sal.core.Property} such as
- * {@link org.opendaylight.controller.sal.core.Description} and/or
- * {@link org.opendaylight.controller.sal.core.Tier} etc.
+ * @param node {@link org.opendaylight.controller.sal.core.Node} being updated
+ * @param type {@link org.opendaylight.controller.sal.core.UpdateType}
+ * @param props set of {@link org.opendaylight.controller.sal.core.Property} such as
+ * {@link org.opendaylight.controller.sal.core.Description} and/or
+ * {@link org.opendaylight.controller.sal.core.Tier} etc.
*/
public void updateNode(Node node, UpdateType type, Set<Property> props);
/**
* This method is called when some properties of a node connector are added/deleted/changed.
*
- * @param nodeConnector {@link org.opendaylight.controller.sal.core.NodeConnector} being updated
- * @param type {@link org.opendaylight.controller.sal.core.UpdateType}
- * @param props set of {@link org.opendaylight.controller.sal.core.Property} such as
- * {@link org.opendaylight.controller.sal.core.Description} and/or
- * {@link org.opendaylight.controller.sal.core.State} etc.
+ * @param nodeConnector {@link org.opendaylight.controller.sal.core.NodeConnector} being updated
+ * @param type {@link org.opendaylight.controller.sal.core.UpdateType}
+ * @param props set of {@link org.opendaylight.controller.sal.core.Property} such as
+ * {@link org.opendaylight.controller.sal.core.Description} and/or
+ * {@link org.opendaylight.controller.sal.core.State} etc.
*/
public void updateNodeConnector(NodeConnector nodeConnector,
UpdateType type, Set<Property> props);
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class Match implements Cloneable, Serializable {
- private static final long serialVersionUID = 1L;
- private static final Map<MatchType, MatchType> reversableMatches;
+ private static final long serialVersionUID = 1L;
+ private static final Map<MatchType, MatchType> reversableMatches;
static {
Map<MatchType, MatchType> map = new HashMap<MatchType, MatchType>();
map.put(MatchType.DL_SRC, MatchType.DL_DST);
* Generic setter for frame/packet/message's header fields against which to match
* Note: For MAC addresses, please pass the cloned value to this function
*
- * @param type packet's header field type
- * @param value field's value to assign to the match
- * @param mask field's bitmask to apply to the match (has to be of the same class type of value)
+ * @param type packet's header field type
+ * @param value field's value to assign to the match
+ * @param mask field's bitmask to apply to the match (has to be of the same class type of value)
*/
public void setField(MatchType type, Object value, Object mask) {
MatchField field = new MatchField(type, value, mask);
* Generic setter for frame/packet/message's header fields against which to match
* Note: For MAC addresses, please pass the cloned value to this function
*
- * @param type packet's header field type
- * @param value field's value to assign to the match
+ * @param type packet's header field type
+ * @param value field's value to assign to the match
*/
public void setField(MatchType type, Object value) {
MatchField field = new MatchField(type, value);
/**
* Generic getter for fields against which the match is programmed
*
- * @param type frame/packet/message's header field type
+ * @param type frame/packet/message's header field type
* @return
*/
public MatchField getField(MatchType type) {
/**
* Returns the list of MatchType fields the match is set for
*
- * @return List of individual MatchType fields.
+ * @return List of individual MatchType fields.
*/
public List<MatchType> getMatchesList() {
return new ArrayList<MatchType>(fields.keySet());
/**
* Returns the list of MatchFields the match is set for
*
- * @return List of individual MatchField values.
+ * @return List of individual MatchField values.
*/
@XmlElement(name="matchField")
public List<MatchField> getMatchFields() {
- return new ArrayList<MatchField>(fields.values());
+ return new ArrayList<MatchField>(fields.values());
}
-
+
/**
* Returns whether this match is for an IPv6 flow
*/
/**
* Represents the generic matching field
- *
+ *
*/
@XmlRootElement
/**
* Mask based match constructor
- *
+ *
* @param type
* @param value
* @param mask
/**
* Full match constructor
- *
+ *
* @param type
* @param value
*/
/**
* Returns the value set for this match field
- *
+ *
* @return
*/
public Object getValue() {
/**
* Returns the type field this match field object is for
- *
+ *
* @return
*/
public MatchType getType() {
/**
* Returns the mask value set for this field match A null mask means this is
* a full match
- *
+ *
* @return
*/
public Object getMask() {
/**
* Returns the bitmask set for this field match
- *
+ *
* @return
*/
public long getBitMask() {
/**
* Returns whether the field match configuration is valid or not
- *
+ *
* @return
*/
public boolean isValid() {
* Represents the binding between the id, the value and mask type and the range
* values of the elements type that can be matched on the network
* frame/packet/message
- *
- *
- *
+ *
+ *
+ *
*/
public enum MatchType {
IN_PORT("inPort", 1 << 0, NodeConnector.class, 1, 0),
/**
* Perform the assignment type validation
- *
+ *
* @param value
* @param mask
* @return
/**
* Perform the value and mask range validation
- *
+ *
* @param value
* @param mask
* @return
/**
* Return the mask value in 64 bits bitmask form
- *
+ *
* @param mask
* @return
*/
* @param int startOffset - offset to start fetching bits from data from
* @param int numBits - number of bits to be fetched from data
* @return byte [] - LSB aligned bits
- *
+ *
* @throws BufferException
* when the startOffset and numBits parameters are not congruent
* with the data buffer size
* @param byte - input byte to be inserted
* @param startOffset - offset of data[] to start inserting byte from
* @param numBits - number of bits of input to be inserted into data[]
- *
+ *
* @throws BufferException
* when the input, startOffset and numBits are not congruent
* with the data buffer size
/**
* Returns numBits 1's in the MSB position
- *
+ *
* @param numBits
* @return
*/
/**
* Returns numBits 1's in the LSB position
- *
+ *
* @param numBits
* @return
*/
/**
* Returns the numerical value of the byte array passed
- *
+ *
* @param byte[] - array
* @return long - numerical value of byte array passed
*/
/**
* Returns the numerical value of the last numBits (LSB bits) of the byte
* array passed
- *
+ *
* @param byte[] - array
* @param int - numBits
* @return long - numerical value of byte array passed
* Accepts a number as input and returns its value in byte form in LSB
* aligned form example: input = 5000 [1001110001000] bytes = 19, -120
* [00010011] [10001000]
- *
+ *
* @param Number
* @return byte[]
- *
+ *
*/
public static byte[] toByteArray(Number input) {
* Accepts a number as input and returns its value in byte form in MSB
* aligned form example: input = 5000 [1001110001000] bytes = -114, 64
* [10011100] [01000000]
- *
+ *
* @param Number
* input
* @param int numBits - the number of bits to be returned
* @return byte[]
- *
+ *
*/
public static byte[] toByteArray(Number input, int numBits) {
Class<? extends Number> dataType = input.getClass();
/**
* Takes an LSB aligned byte array and returned the LSB numBits in a MSB
* aligned byte array
- *
+ *
* @param inputbytes
* @param numBits
* @return
/**
* It aligns the last numBits bits to the head of the byte array following
* them with numBits % 8 zero bits.
- *
+ *
* Example: For inputbytes = [00000111][01110001] and numBits = 12 it
* returns: shiftedBytes = [01110111][00010000]
- *
+ *
* @param byte[] inputBytes
* @param int numBits - number of bits to be left aligned
* @return byte[]
/**
* It aligns the first numBits bits to the right end of the byte array
* preceding them with numBits % 8 zero bits.
- *
+ *
* Example: For inputbytes = [01110111][00010000] and numBits = 12 it
* returns: shiftedBytes = [00000111][01110001]
- *
+ *
* @param byte[] inputBytes
* @param int numBits - number of bits to be right aligned
* @return byte[]
* Insert in the data buffer at position dictated by the offset the number
* of bits specified from the input data byte array. The input byte array
* has the bits stored starting from the LSB
- *
+ *
* @param byte[] data
* @param byte[] inputdata
* @param int startOffset
int InputMSBbits = 0, InputLSBbits = 0;
int i;
- if (numBits == 0) {
- return;
+ if (numBits == 0) {
+ return;
}
if (extraOffsetBits == 0) {
/**
* Sets the type for the current ICMP message
- *
+ *
* @param type
* The ICMP message type
* @return This ICMP object
/**
* Sets the ICMP code (type subtype) for the current ICMP object instance
- *
+ *
* @param code
* The ICMP message type subtype
* @return This ICMP object
/**
* Computes the ICMP checksum on the serialized ICMP message
- *
+ *
* @param serialized
* The data stream
* @param start
* @param checksum the checksum to set
*/
/*public IPv4 setChecksum() {
- short ipChecksum = computeChecksum();
+ short ipChecksum = computeChecksum();
byte[] checksum = BitBufferHelper.toByteArray(ipChecksum);
- fieldValues.put(CHECKSUM, checksum);
+ fieldValues.put(CHECKSUM, checksum);
return this;
}*/
/**
* Computes the IPv4 header checksum on the passed stream of bytes
* representing the packet
- *
+ *
* @param data
* The byte stream
* @param offset
/**
* Returns the size of LLDP packet in bytes
- *
+ *
* @return int - LLDP Packet size in bytes
*/
private int getLLDPPacketLength() {
* Describes an exception that is raised when the process of serializing or
* deserializing a network packet/stream fails. This generally happens when the
* packet/stream is malformed.
- *
+ *
*/
public class PacketException extends Exception {
private static final long serialVersionUID = 1L;
import org.opendaylight.controller.sal.core.TimeStamp;
/**
- *
+ *
* Describe a raw Data Packet, this is how a packet is received from the network
* and how it will be transmitted. It essentially wraps the raw bytestream
- *
+ *
*/
public class RawPacket {
private byte[] packetData;
/**
* If the packet is being sent this parameter tells where the packet is sent
* toward
- *
- *
+ *
+ *
* @return the NodeConnector toward where the packet is being sent
*/
public NodeConnector getOutgoingNodeConnector() {
/**
* Setter method for OutGoing NodeConnector
- *
+ *
* @param outgoingNodeConnector
* NodeConnector toward where the packet is travelling
*/
/**
* Return the incoming NodeConnector if the packet was received
- *
+ *
* @return NodeConnector where the packet was received from
*/
public NodeConnector getIncomingNodeConnector() {
/**
* Setter for Incoming NodeConnector
- *
+ *
* @param incomingNodeConnector
* NodeConnector to be used and incoming one
*/
/**
* Retrieve a given property attached to the packet, if exits of course
- *
+ *
* @param key
* Key to retrieve the wanted property attached to the packet
- *
+ *
* @return The property attached to the packet
*/
public Object getProps(Object key) {
/**
* Generic data associated to the data packet
- *
+ *
* @param key
* key for the association
* @param value
/**
* Constructor for RawPacket
- *
+ *
* @param data
* content of the packet as bytestream
* @param e
* datalink encapsulation for the packet
- *
+ *
*/
public RawPacket(byte[] data, LinkEncap e) throws ConstructionException {
if (data == null) {
* Copy Constructor for RawPacket, it performs a copy of the packet so each
* packet can be modified independently without worrying that source packet
* content is touched
- *
+ *
* @param src
* packet to copy data from
- *
+ *
*/
public RawPacket(RawPacket src) throws ConstructionException {
if (src == null) {
/**
* Constructor for RawPacket with Ethernet encapsulation
- *
+ *
* @param data
* content of the packet as bytestream
- *
+ *
*/
public RawPacket(byte[] data) throws ConstructionException {
this(data, LinkEncap.ETHERNET);
/**
* Read the time stamp when the packet has entered the system
- *
+ *
* @return The time stamp when the packet has entered the system
*/
public TimeStamp getIncomingTime() {
/**
* Read the packet encapsulation
- *
+ *
* @return The encapsulation for the raw packet, necessary to start parsing
* the packet
*/
/**
* Get bytestream of the packet body
- *
+ *
* @return The raw bytestream composing the packet
*/
public byte[] getPacketData() {
/**
* Returns the time at which the current instance of RawPacket was created
* as a copy of the original one.
- *
+ *
* @return The time stamp at which this RawPacket instance was created. null
* if this is the original instance.
*/
*/
public void setHeaderField(String headerField, byte[] readValue) {
/*if (headerField.equals("Protocol")) {
- payloadClass = decodeMap.get(readValue);
+ payloadClass = decodeMap.get(readValue);
}*/
hdrFieldsMap.put(headerField, readValue);
}
/* Dummy constructor for JAXB */
private FlowOnNode () {
}
-
+
public FlowOnNode(Flow flow) {
this.flow = flow;
}
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class NodeConnectorStatistics {
- @XmlElement
+ @XmlElement
private NodeConnector nodeConnector;
- @XmlElement
+ @XmlElement
private long receivePackets;
- @XmlElement
+ @XmlElement
private long transmitPackets;
- @XmlElement
+ @XmlElement
private long receiveBytes;
- @XmlElement
+ @XmlElement
private long transmitBytes;
- @XmlElement
+ @XmlElement
private long receiveDrops;
- @XmlElement
+ @XmlElement
private long transmitDrops;
- @XmlElement
+ @XmlElement
private long receiveErrors;
- @XmlElement
+ @XmlElement
private long transmitErrors;
- @XmlElement
+ @XmlElement
private long receiveFrameError;
- @XmlElement
+ @XmlElement
private long receiveOverRunError;
- @XmlElement
+ @XmlElement
private long receiveCrcError;
- @XmlElement
+ @XmlElement
private long collisionCount;
- //To Satisfy JAXB
- public NodeConnectorStatistics() {
-
- }
+ //To Satisfy JAXB
+ public NodeConnectorStatistics() {
+
+ }
/**
* Set the node connector
* @param port
@Override
public String toString() {
return "HwDescription[manufacturer=" + manufacturer + ", hardware="
- + hardware + ", software=" + software + ", serialNumber="
- + serialNumber + ", description=" + description + "]";
+ + hardware + ", software=" + software + ", serialNumber="
+ + serialNumber + ", description=" + description + "]";
}
}
/**
* @author Aditya Prakash Vaja <aditya.vaja@bigswitch.com>
* Represents the Table statistics for the node
- *
+ *
*/
@XmlRootElement
/**
* Topology notifications provided by SAL toward the application
- *
+ *
*/
public interface IListenTopoUpdates {
/**
* Called to update on Edge in the topology graph
- *
+ *
* @param topoedgeupdateList
* List of topoedgeupdates Each topoedgeupdate includes edge, its
* Properties ( BandWidth and/or Latency etc) and update type.
/**
* Called when an Edge utilization is above the safety threshold configured
* on the controller
- *
+ *
* @param edge
* The edge which bandwidth usage is above the safety level
*/
/**
* Called when the Edge utilization is back to normal, below the safety
* threshold level configured on the controller
- *
+ *
* @param edge
*/
public void edgeUtilBackToNormal(Edge edge);
/**
* Methods that are invoked from Protocol Plugin toward SAL
- *
+ *
*/
public interface IPluginOutTopologyService {
/**
* Called to update on Edge in the topology graph
- *
+ *
* @param topoedgeupdateList
* List of topoedgeupdates Each topoedgeupdate includes edge, its
* Properties ( BandWidth and/or Latency etc) and update type.
/**
* Called when an Edge utilization is above the safety threshold configured
* on the controller
- *
+ *
* @param edge
*/
public void edgeOverUtilized(Edge edge);
/**
* Called when the Edge utilization is back to normal, below the safety
* threshold level configured on the controller
- *
+ *
* @param edge
*/
public void edgeUtilBackToNormal(Edge edge);
*
*/
public enum GlobalConstants {
- DEFAULT("default"),
- CONTAINERMANAGER("containermanager"),
- CONTAINERNAME("name"),
- STATICVLAN("staticvlan"),
- CLUSTERINGSERVICES("clusteringservices"),
+ DEFAULT("default"),
+ CONTAINERMANAGER("containermanager"),
+ CONTAINERNAME("name"),
+ STATICVLAN("staticvlan"),
+ CLUSTERINGSERVICES("clusteringservices"),
STARTUPHOME("configuration/startup/");
private GlobalConstants(String name) {
public class HexEncode {
/**
* This method converts byte array into String format without ":" inserted.
- *
+ *
* @param bytes
* The byte array to convert to string
* @return The hexadecimal representation of the byte array. If bytes is
// Openflow 1.0 supports the IP Proto match only for ICMP, TCP and UDP
public enum IPProtocols {
ANY("any", 0),
- /* HOPOPT("HOPOPT",0),
+ /* HOPOPT("HOPOPT",0),
*/ICMP("ICMP", 1),
- /* IGMP("IGMP",2),
+ /* IGMP("IGMP",2),
GGP("GGP",3),
IPV4("IPv4",4),
ST("ST",5),
*/TCP("TCP", 6),
- /* CBT("CBT",7),
+ /* CBT("CBT",7),
EGP("EGP",8),
IGP("IGP",9),
BBNRCCMON("BBN-RCC-MON",10),
XNET("XNET",15),
CHAOS("CHAOS",16),
*/UDP("UDP", 17),
- /* MUX("MUX",18),
+ /* MUX("MUX",18),
DCNMEAS("DCN-MEAS",19),
HMP("HMP",20),
PRM("PRM",21),
TLSP("TLSP",56),
SKIP("SKIP",57),
*/IPV6ICMP("IPv6-ICMP", 58);
- /* IPV6NoNxt("IPv6-NoNxt",59),
+ /* IPV6NoNxt("IPv6-NoNxt",59),
IPV6Opts("IPv6-Opts",60),
ANYHOST("ANY-HOST",61),
CFTP("CFTP",62),
/**
* Converts a 4 bytes array into an integer number
*
- * @param ba the 4 bytes long byte array
- * @return the integer number
+ * @param ba the 4 bytes long byte array
+ * @return the integer number
*/
public static int byteArray4ToInt(byte[] ba) {
if (ba == null || ba.length != 4) {
* Converts an IP address passed as integer value into the
* respective InetAddress object
*
- * @param address the IP address in integer form
- * @return the IP address in InetAddress form
+ * @param address the IP address in integer form
+ * @return the IP address in InetAddress form
*/
public static InetAddress getInetAddress(int address) {
InetAddress ip = null;
* The prefix bit mask indicates the contiguous leading bits that are NOT masked out.
* Example: A prefix bit mask length of 8 will give an InetAddress Network Mask of 255.0.0.0
*
- * @param prefixMaskLength integer representing the length of the prefix network mask
- * @param isV6 boolean representing the IP version of the returned address
+ * @param prefixMaskLength integer representing the length of the prefix network mask
+ * @param isV6 boolean representing the IP version of the returned address
* @return
*/
public static InetAddress getInetNetworkMask(int prefixMaskLength,
* while ff.00.00.00 will return a subnet mask length of 24.
* If the passed prefixMask object is null, 0 is returned
*
- * @param prefixMask the prefix mask as byte array
- * @return the length of the prefix network mask
+ * @param prefixMask the prefix mask as byte array
+ * @return the length of the prefix network mask
*/
public static int getSubnetMaskLength(byte[] prefixMask) {
int maskLength = 0;
* while ff.00.00.00 will return a subnet mask length of 24
* If the passed prefixMask object is null, 0 is returned
*
- * @param prefixMask the prefix mask as InetAddress
- * @return the length of the prefix network mask
+ * @param prefixMask the prefix mask as InetAddress
+ * @return the length of the prefix network mask
*/
public static int getSubnetMaskLength(InetAddress prefixMask) {
return (prefixMask == null) ? 0 : NetUtils
* the equivalent subnet prefix IP address
* Example: for ip = "172.28.30.254" and maskLen = 25 it will return "172.28.30.128"
*
- * @param ip the IP address in InetAddress form
- * @param maskLen the length of the prefix network mask
- * @return the subnet prefix IP address in InetAddress form
+ * @param ip the IP address in InetAddress form
+ * @param maskLen the length of the prefix network mask
+ * @return the subnet prefix IP address in InetAddress form
*/
public static InetAddress getSubnetPrefix(InetAddress ip, int maskLen) {
int bytes = maskLen / 8;
/**
* Returns true if the passed MAC address is all zero
*
- * @param mac the byte array representing the MAC address
- * @return true if all MAC bytes are zero
+ * @param mac the byte array representing the MAC address
+ * @return true if all MAC bytes are zero
*/
public static boolean isZeroMAC(byte[] mac) {
for (short i = 0; i < 6; i++) {
/**
* Returns true if the passed InetAddress contains all zero
*
- * @param ip the IP address to test
- * @return true if the address is all zero
+ * @param ip the IP address to test
+ * @return true if the address is all zero
*/
public static boolean isAny(InetAddress ip) {
for (byte b : ip.getAddress()) {
/**
* Returns the unsigned value of the passed byte variable
*
- * @param b the byte value
+ * @param b the byte value
* @return the int variable containing the unsigned byte value
*/
public static int getUnsignedByte(byte b) {
- return (b > 0)? (int)b : (b & 0x7F | 0x80);
- }
+ return (b > 0)? (int)b : (b & 0x7F | 0x80);
+ }
/**
* Return the unsigned value of the passed short variable
* @param s the short value
* @return the int variable containing the unsigned short value
*/
- public static int getUnsignedShort(short s) {
- return (s > 0)? (int)s : (s & 0x7FFF | 0x8000);
- }
+ public static int getUnsignedShort(short s) {
+ return (s > 0)? (int)s : (s & 0x7FFF | 0x8000);
+ }
}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* for internal API2 function calls. This constructor allows to specify,
* beside the Status Code, a custom human readable description to add more
* information about the status.
- *
+ *
* @param errorCode
* The status code. If passed as null, code will be stored as
* {@code StatusCode.UNDEFINED}
* Generates an instance of the Status class based on the passed StatusCode
* only. The description field of the Status object will be inferred by the
* status code.
- *
+ *
* @param errorCode
* The status code. If passed as null, code will be stored as
* {@code StatusCode.UNDEFINED}
* asynchronous call. It is supposed to be created by the underlying
* infrastructure only when it was successful in allocating the asynchronous
* request id, hence caller should expect StatusCode to be successful.
- *
+ *
* @param errorCode
* The status code. If passed as null, code will be stored as
* {@code StatusCode.UNDEFINED}
/**
* Returns the status code
- *
+ *
* @return the {@code StatusCode} representing the status code
*/
public StatusCode getCode() {
/**
* Returns a human readable description of the failure if any
- *
+ *
* @return a string representing the reason of failure
*/
public String getDescription() {
/**
* Tells whether the status is successful
- *
+ *
* @return true if the Status code is {@code StatusCode.SUCCESS}
*/
public boolean isSuccess() {
* Return the request id assigned by underlying infrastructure in case of
* asynchronous request. In case of synchronous requests, the returned id
* is expected to be 0
- *
+ *
* @return The request id assigned for this asynchronous request
*/
public long getRequestId() {
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
/**
* The enum which describes the generic error conditions.
- * Each enum value is associated with a minimal description string.
+ * Each enum value is associated with a minimal description string.
*
*/
public enum StatusCode {
- SUCCESS("Success"),
-
- BADREQUEST("Bad Request"),
- UNAUTHORIZED("UnAuthorized"),
- FORBIDDEN("Forbidden"),
- NOTFOUND("Not Found"),
- NOTALLOWED("Method Not Allowed"),
- NOTACCEPTABLE("Request Not Acceptable"),
- TIMEOUT("Request Timeout"),
- CONFLICT("Resource Conflict"),
- GONE("Resource Gone"),
- UNSUPPORTED("Unsupported"),
-
- INTERNALERROR("Internal Error"),
- NOTIMPLEMENTED("Not Implemented"),
- NOSERVICE("Service Not Available"),
-
- UNDEFINED("Undefined Error");
-
- private String description;
- private StatusCode(String description) {
- this.description = description;
- }
-
- /**
- * Prints the description associated to the code value
- */
- public String toString() {
- return description;
- }
+ SUCCESS("Success"),
+
+ BADREQUEST("Bad Request"),
+ UNAUTHORIZED("UnAuthorized"),
+ FORBIDDEN("Forbidden"),
+ NOTFOUND("Not Found"),
+ NOTALLOWED("Method Not Allowed"),
+ NOTACCEPTABLE("Request Not Acceptable"),
+ TIMEOUT("Request Timeout"),
+ CONFLICT("Resource Conflict"),
+ GONE("Resource Gone"),
+ UNSUPPORTED("Unsupported"),
+
+ INTERNALERROR("Internal Error"),
+ NOTIMPLEMENTED("Not Implemented"),
+ NOSERVICE("Service Not Available"),
+
+ UNDEFINED("Undefined Error");
+
+ private String description;
+ private StatusCode(String description) {
+ this.description = description;
+ }
+
+ /**
+ * Prints the description associated to the code value
+ */
+ public String toString() {
+ return description;
+ }
}
*/
package org.opendaylight.controller.sal.authorization;
-
+
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.opendaylight.controller.sal.core.Node;
import org.opendaylight.controller.sal.utils.NodeCreator;
-
- public class AuthorizationTest {
-
- @Test
- public void testResources () {
- Privilege p = Privilege.WRITE;
- ResourceGroup resourceGroup = new ResourceGroup("NodeGroup", p);
- Map<ResourceGroup, ArrayList<Resource>> resourceMap = new HashMap<ResourceGroup, ArrayList<Resource>>();
- ArrayList<Resource> resourceList = new ArrayList<Resource>();
-
- for (int i = 0; i < 5; i++) {
- Node node = NodeCreator.createOFNode((long)i);
- Resource resource = new Resource (node, p);
- resourceList.add(resource);
- }
-
- resourceMap.put(resourceGroup, resourceList);
-
- ArrayList<Resource> retrievedResourceList = resourceMap.get(resourceGroup);
- for (Entry<ResourceGroup, ArrayList<Resource>> entry : resourceMap.entrySet()) {
- ResourceGroup rGroup = entry.getKey();
- Assert.assertTrue(rGroup.getGroupName().equals(resourceGroup.getGroupName()));
- for (int i = 0; i < 5; i++) {
- Resource resource = retrievedResourceList.get(i);
- Assert.assertTrue(resource.getPrivilege().equals(Privilege.WRITE));
- Assert.assertTrue(((Long)((Node)resource.getResource()).getID()).equals((long)i));
- }
- }
- }
-
- @Test
- public void testAppRoleLevel() {
- AppRoleLevel appRoleLevel = AppRoleLevel.APPOPERATOR;
- Assert.assertTrue(appRoleLevel.toString().equals("App-Operator"));
- Assert.assertTrue(appRoleLevel.toNumber() == 2);
- Assert.assertTrue(appRoleLevel.toStringPretty().equals("Application Operator"));
- }
-
- @Test
- public void testUserLevel() {
- UserLevel userLevel = UserLevel.SYSTEMADMIN;
- Assert.assertTrue(userLevel.toString().equals("System-Admin"));
- Assert.assertTrue(userLevel.toNumber() == 0);
- Assert.assertTrue(userLevel.toStringPretty().equals("System Administrator"));
- }
-
- @Test
- public void testAppRoleLevelFromString() {
- Assert.assertTrue(AppRoleLevel.fromString("App-Admin") == AppRoleLevel.APPADMIN);
- Assert.assertTrue(AppRoleLevel.fromString("App-User") == AppRoleLevel.APPUSER);
- Assert.assertTrue(AppRoleLevel.fromString("App-Operator") == AppRoleLevel.APPOPERATOR);
- Assert.assertTrue(AppRoleLevel.fromString(" ") == null);
- Assert.assertTrue(AppRoleLevel.fromString("") == null);
- Assert.assertTrue(AppRoleLevel.fromString("App-Admini") == null);
- }
+
+ public class AuthorizationTest {
+
+ @Test
+ public void testResources () {
+ Privilege p = Privilege.WRITE;
+ ResourceGroup resourceGroup = new ResourceGroup("NodeGroup", p);
+ Map<ResourceGroup, ArrayList<Resource>> resourceMap = new HashMap<ResourceGroup, ArrayList<Resource>>();
+ ArrayList<Resource> resourceList = new ArrayList<Resource>();
+
+ for (int i = 0; i < 5; i++) {
+ Node node = NodeCreator.createOFNode((long)i);
+ Resource resource = new Resource (node, p);
+ resourceList.add(resource);
+ }
+
+ resourceMap.put(resourceGroup, resourceList);
+
+ ArrayList<Resource> retrievedResourceList = resourceMap.get(resourceGroup);
+ for (Entry<ResourceGroup, ArrayList<Resource>> entry : resourceMap.entrySet()) {
+ ResourceGroup rGroup = entry.getKey();
+ Assert.assertTrue(rGroup.getGroupName().equals(resourceGroup.getGroupName()));
+ for (int i = 0; i < 5; i++) {
+ Resource resource = retrievedResourceList.get(i);
+ Assert.assertTrue(resource.getPrivilege().equals(Privilege.WRITE));
+ Assert.assertTrue(((Long)((Node)resource.getResource()).getID()).equals((long)i));
+ }
+ }
+ }
+
+ @Test
+ public void testAppRoleLevel() {
+ AppRoleLevel appRoleLevel = AppRoleLevel.APPOPERATOR;
+ Assert.assertTrue(appRoleLevel.toString().equals("App-Operator"));
+ Assert.assertTrue(appRoleLevel.toNumber() == 2);
+ Assert.assertTrue(appRoleLevel.toStringPretty().equals("Application Operator"));
+ }
+
+ @Test
+ public void testUserLevel() {
+ UserLevel userLevel = UserLevel.SYSTEMADMIN;
+ Assert.assertTrue(userLevel.toString().equals("System-Admin"));
+ Assert.assertTrue(userLevel.toNumber() == 0);
+ Assert.assertTrue(userLevel.toStringPretty().equals("System Administrator"));
+ }
+
+ @Test
+ public void testAppRoleLevelFromString() {
+ Assert.assertTrue(AppRoleLevel.fromString("App-Admin") == AppRoleLevel.APPADMIN);
+ Assert.assertTrue(AppRoleLevel.fromString("App-User") == AppRoleLevel.APPUSER);
+ Assert.assertTrue(AppRoleLevel.fromString("App-Operator") == AppRoleLevel.APPOPERATOR);
+ Assert.assertTrue(AppRoleLevel.fromString(" ") == null);
+ Assert.assertTrue(AppRoleLevel.fromString("") == null);
+ Assert.assertTrue(AppRoleLevel.fromString("App-Admini") == null);
+ }
}
public void testExtensibleNode() {
// Add a new ID type
Assert.assertTrue(Node.NodeIDType.registerIDType("FOO", Integer.class));
-
+
// Trying to re-register the node must fail
Assert.assertFalse(Node.NodeIDType.registerIDType("FOO",
Integer.class));
// Got an unexpected exception
Assert.assertTrue(false);
}
-
+
// Now unregister the type and make sure the node doesn't get
// created
Node.NodeIDType.unRegisterIDType("FOO");
InetAddress ipMask2 = null;
short ethertype = EtherTypes.IPv4.shortValue();
short ethertype2 = EtherTypes.IPv4.shortValue();
-
+
/*
* Create a SAL Flow aFlow
*/
Match match1 = new Match();
Match match2 = new Match();
-
+
match1.setField(MatchType.DL_TYPE, ethertype);
match1.setField(MatchType.NW_SRC, srcIP, ipMask);
match2.setField(MatchType.NW_SRC, srcIP2, ipMask2);
Assert.assertTrue(match1.equals(match2));
-
+
ipMask2 = InetAddress.getByName("255.255.255.255");
match2.setField(MatchType.NW_SRC, srcIP2, ipMask2);
ipMask2 = InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff");
ethertype = EtherTypes.IPv6.shortValue();
ethertype2 = EtherTypes.IPv6.shortValue();
-
+
match1.setField(MatchType.DL_TYPE, ethertype);
match1.setField(MatchType.NW_SRC, srcIP, ipMask);
Assert.assertTrue(match1.equals(match2));
}
-
+
@Test
public void testCloning() throws Exception {
Node node = NodeCreator.createOFNode(7l);
Assert.assertTrue(data2[3] == 80);
// INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
- // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] // OUTPUT: [01001011] [01101000] = {75, 104}
+ // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] // OUTPUT: [01001011] [01101000] = {75, 104}
byte data10[] = new byte[2];
startOffset = 0;
numBits = 13;
Assert.assertTrue(data10[1] == 104);
// INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
- // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] // OUTPUT: [01001000] = {72}
+ // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] // OUTPUT: [01001000] = {72}
byte data11[] = new byte[4];
startOffset = 8;
numBits = 6;
Assert.assertTrue(data11[1] == 72);
// INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
- // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [01001011] [01101110] [01101000] = {75, 110, 105}
+ // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [01001011] [01101110] [01101000] = {75, 110, 105}
byte data12[] = new byte[4];
startOffset = 0;
numBits = 23;
Assert.assertTrue(data12[2] == 106);
// INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
- // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [01001011] [01101110] [01100000] = {75, 110, 96}
+ // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [01001011] [01101110] [01100000] = {75, 110, 96}
byte data13[] = new byte[4];
startOffset = 8;
numBits = 20;
Assert.assertTrue(data13[3] == 96);
// INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
- // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [01001011] [01101110] [01101011] [10100000]= {75, 110, 107, 80}
+ // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [01001011] [01101110] [01101011] [10100000]= {75, 110, 107, 80}
byte data14[] = new byte[4];
startOffset = 0;
numBits = 30;
//CASE 3: startOffset%8 != 0, numBits%8 = 0
// INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
- // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00001001] [11000000] = {72, 96}
+ // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00001001] [11000000] = {72, 96}
byte data16[] = new byte[5];
startOffset = 3;
numBits = 8;
Assert.assertTrue(data16[2] == 0);
// INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
- // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
+ // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
// OUTPUT: [00000100] [1011 0110] [1110 0000] = {4, -54, -96}
startOffset = 3;
Assert.assertTrue(data18[2] == -64);
// INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
- // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
+ // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
// OUTPUT: [0000 1001] [0110 1101] [1100 1101] [0110 1010] [0000 0001] = {9, 109, -51, 106, 0}
startOffset = 3;
Assert.assertTrue(data19[4] == 0);
// INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
- // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
+ // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
// OUTPUT: data[4, 5, 6] = [0 010 0101] [1 011 0111] [0 000 0000] = {37, -73, 0}
startOffset = 33;
numBits = 16;
//CASE 4: extranumBits != 0 AND extraOffsetBits != 0
// INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
- // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
+ // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
// OUTPUT: [0000 1001] [0100 0000] = {9, 96}
startOffset = 3;
numBits = 7;
Assert.assertTrue(data21[2] == 0);
// INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
- // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
+ // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
// OUTPUT: data = [00000 010] [01011 011] [01110 000] = {37, -73, 0}
startOffset = 5;
numBits = 17;
Assert.assertTrue(data22[2] == 112);
// INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
- // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
+ // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
// OUTPUT: [0000 1001] [0110 1101] [110 01101] [01 00000] = {9, 109, -51, 64}
startOffset = 3;
numBits = 23;
Assert.assertTrue(data23[3] == 64);
// INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
- // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
+ // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
// OUTPUT: [0000 1001] [0110 1101] = {9, 109}
startOffset = 3;
numBits = 13;
Assert.assertTrue(data24[2] == 0);
// INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
- // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
+ // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
// OUTPUT: [0000 0100] [1011 0110] [1110 0110] = {4, -74, -26}
startOffset = 4;
numBits = 20;
Assert.assertTrue(data25[3] == -0);
// INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
- // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
+ // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
// OUTPUT: [0000 0010] [0101 1011] = {0, 2, 91, 0}
startOffset = 13;
numBits = 11;
Assert.assertTrue(data26[3] == 0);
// INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
- // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
+ // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
// OUTPUT: [000 01001] [011 01101] [110 0 0000] = {9, 109, -64, 0}
startOffset = 3;
numBits = 17;
Assert.assertTrue(data27[3] == 0);
// INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
- // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
+ // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
// OUTPUT: [00 000000] [00 000000] [00 010010] [11 011011] [10 011010] [11 010100] [0000 0000] = {0, 0, 18, -37,-102,-44,0}
startOffset = 18;
numBits = 34;
Assert.assertTrue(sMAC[5] == -97);
Assert.assertTrue(etherType == 0x806);
-
+
ARP arpPacket = (ARP) eth.getPayload();
-
+
Assert.assertTrue(arpPacket.getHardwareType() == (byte)0x1);
Assert.assertTrue(arpPacket.getProtocolType() == 2048);
Assert.assertTrue(arpPacket.getHardwareAddressLength() == (byte)0x6);
Assert.assertTrue(arpPacket.getProtocolAddressLength() == (byte)0x4);
Assert.assertTrue(arpPacket.getOpCode() == 1);
-
+
byte[] senderHwAddress = arpPacket.getSenderHardwareAddress();
- byte[] senderProtocolAddress = arpPacket.getSenderProtocolAddress();
-
+ byte[] senderProtocolAddress = arpPacket.getSenderProtocolAddress();
+
byte[] targetHwAddress = arpPacket.getTargetHardwareAddress();
- byte[] targetProtocolAddress = arpPacket.getTargetProtocolAddress();
+ byte[] targetProtocolAddress = arpPacket.getTargetProtocolAddress();
+
-
Assert.assertTrue(senderHwAddress[0] == (byte)0xA6);
Assert.assertTrue(senderHwAddress[1] == (byte)0xEC);
Assert.assertTrue(senderHwAddress[2] == (byte)0x9C);
Assert.assertTrue(senderHwAddress[3] == (byte)0xAE);
Assert.assertTrue(senderHwAddress[4] == (byte)0xB2);
Assert.assertTrue(senderHwAddress[5] == (byte)0x9F);
-
+
Assert.assertTrue(senderProtocolAddress[0] == (byte)0x9);
Assert.assertTrue(senderProtocolAddress[1] == (byte)0x9);
Assert.assertTrue(senderProtocolAddress[2] == (byte)0x9);
Assert.assertTrue(targetProtocolAddress[0] == (byte)0x9);
Assert.assertTrue(targetProtocolAddress[1] == (byte)0x9);
Assert.assertTrue(targetProtocolAddress[2] == (byte)0x9);
- Assert.assertTrue(targetProtocolAddress[3] == (byte)0xFE);
+ Assert.assertTrue(targetProtocolAddress[3] == (byte)0xFE);
}
@Test
import org.opendaylight.controller.sal.utils.EtherTypes;
import org.opendaylight.controller.sal.utils.NodeConnectorCreator;
import org.opendaylight.controller.sal.utils.NodeCreator;
-
+
public class FlowOnNodeTest {
- @Test
- public void testFlowOnNodeMethods () {
- Match match = new Match();
- NodeConnector inNC = NodeConnectorCreator.createNodeConnector((short)10, NodeCreator.createOFNode((long)10));
- NodeConnector outNC = NodeConnectorCreator.createNodeConnector((short)20, NodeCreator.createOFNode((long)20));
-
- match.setField(MatchType.DL_TYPE, EtherTypes.IPv4.shortValue());
- match.setField(MatchType.IN_PORT, inNC);
-
- Output output = new Output(outNC);
- ArrayList<Action> action = new ArrayList<Action>();
- action.add(output);
-
- Flow flow = new Flow (match, action);
-
- FlowOnNode flowOnNode = new FlowOnNode (flow);
-
- Assert.assertTrue(flowOnNode.getFlow().equals(flow));
-
- flowOnNode.setPacketCount((long)100);
- flowOnNode.setByteCount((long)800);
- flowOnNode.setTableId((byte)0x55);
- flowOnNode.setDurationNanoseconds(40);
- flowOnNode.setDurationSeconds(45);
-
- Assert.assertTrue(flowOnNode.getPacketCount() == 100);
- Assert.assertTrue(flowOnNode.getByteCount() == 800);
- Assert.assertTrue(flowOnNode.getDurationNanoseconds() == 40);
- Assert.assertTrue(flowOnNode.getDurationSeconds() == 45);
- Assert.assertTrue(flowOnNode.getTableId() == (byte)0x55);
- }
+ @Test
+ public void testFlowOnNodeMethods () {
+ Match match = new Match();
+ NodeConnector inNC = NodeConnectorCreator.createNodeConnector((short)10, NodeCreator.createOFNode((long)10));
+ NodeConnector outNC = NodeConnectorCreator.createNodeConnector((short)20, NodeCreator.createOFNode((long)20));
+
+ match.setField(MatchType.DL_TYPE, EtherTypes.IPv4.shortValue());
+ match.setField(MatchType.IN_PORT, inNC);
+
+ Output output = new Output(outNC);
+ ArrayList<Action> action = new ArrayList<Action>();
+ action.add(output);
+
+ Flow flow = new Flow (match, action);
+
+ FlowOnNode flowOnNode = new FlowOnNode (flow);
+
+ Assert.assertTrue(flowOnNode.getFlow().equals(flow));
+
+ flowOnNode.setPacketCount((long)100);
+ flowOnNode.setByteCount((long)800);
+ flowOnNode.setTableId((byte)0x55);
+ flowOnNode.setDurationNanoseconds(40);
+ flowOnNode.setDurationSeconds(45);
+
+ Assert.assertTrue(flowOnNode.getPacketCount() == 100);
+ Assert.assertTrue(flowOnNode.getByteCount() == 800);
+ Assert.assertTrue(flowOnNode.getDurationNanoseconds() == 40);
+ Assert.assertTrue(flowOnNode.getDurationSeconds() == 45);
+ Assert.assertTrue(flowOnNode.getTableId() == (byte)0x55);
+ }
}
\ No newline at end of file
public class NodeConnectorStatisticsTest {
- @Test
- public void testNodeConnectorStatisticsMethods() {
- NodeConnector nc = NodeConnectorCreator.createNodeConnector((short)20, NodeCreator.createOFNode((long)20));
- NodeConnectorStatistics ncStats = new NodeConnectorStatistics();
- ncStats.setNodeConnector(nc);
- ncStats.setReceiveByteCount(800);
- ncStats.setReceiveCRCErrorCount(10);
- ncStats.setReceiveDropCount(5);
- ncStats.setReceiveErrorCount(20);
- ncStats.setReceiveFrameErrorCount(25);
- ncStats.setReceiveOverRunErrorCount(30);
- ncStats.setReceivePacketCount(100);
- ncStats.setTransmitByteCount(400);
- ncStats.setTransmitDropCount(15);
- ncStats.setTransmitErrorCount(18);
- ncStats.setTransmitPacketCount(50);
- ncStats.setCollisionCount(2);
-
- Assert.assertTrue(ncStats.getCollisionCount() == 2);
- Assert.assertTrue(ncStats.getTransmitPacketCount() == 50);
- Assert.assertTrue(ncStats.getTransmitErrorCount() == 18);
- Assert.assertTrue(ncStats.getTransmitDropCount() == 15);
- Assert.assertTrue(ncStats.getReceivePacketCount() == 100);
- Assert.assertTrue(ncStats.getReceiveOverRunErrorCount() == 30);
- Assert.assertTrue(ncStats.getReceiveFrameErrorCount() == 25);
- Assert.assertTrue(ncStats.getReceiveDropCount() == 5);
- Assert.assertTrue(ncStats.getReceiveCRCErrorCount() == 10);
- Assert.assertTrue(ncStats.getReceiveByteCount() == 800);
- Assert.assertTrue(ncStats.getNodeConnector().equals(nc));
- }
-}
+ @Test
+ public void testNodeConnectorStatisticsMethods() {
+ NodeConnector nc = NodeConnectorCreator.createNodeConnector((short)20, NodeCreator.createOFNode((long)20));
+ NodeConnectorStatistics ncStats = new NodeConnectorStatistics();
+ ncStats.setNodeConnector(nc);
+ ncStats.setReceiveByteCount(800);
+ ncStats.setReceiveCRCErrorCount(10);
+ ncStats.setReceiveDropCount(5);
+ ncStats.setReceiveErrorCount(20);
+ ncStats.setReceiveFrameErrorCount(25);
+ ncStats.setReceiveOverRunErrorCount(30);
+ ncStats.setReceivePacketCount(100);
+ ncStats.setTransmitByteCount(400);
+ ncStats.setTransmitDropCount(15);
+ ncStats.setTransmitErrorCount(18);
+ ncStats.setTransmitPacketCount(50);
+ ncStats.setCollisionCount(2);
+ Assert.assertTrue(ncStats.getCollisionCount() == 2);
+ Assert.assertTrue(ncStats.getTransmitPacketCount() == 50);
+ Assert.assertTrue(ncStats.getTransmitErrorCount() == 18);
+ Assert.assertTrue(ncStats.getTransmitDropCount() == 15);
+ Assert.assertTrue(ncStats.getReceivePacketCount() == 100);
+ Assert.assertTrue(ncStats.getReceiveOverRunErrorCount() == 30);
+ Assert.assertTrue(ncStats.getReceiveFrameErrorCount() == 25);
+ Assert.assertTrue(ncStats.getReceiveDropCount() == 5);
+ Assert.assertTrue(ncStats.getReceiveCRCErrorCount() == 10);
+ Assert.assertTrue(ncStats.getReceiveByteCount() == 800);
+ Assert.assertTrue(ncStats.getNodeConnector().equals(nc));
+ }
+}
import org.opendaylight.controller.sal.reader.NodeDescription;
public class NodeDescriptionTest {
-
- @Test
- public void testNodeDescriptionMethods() {
- NodeDescription ncDesc = new NodeDescription();
- ncDesc.setHardware("Hardware1");
- ncDesc.setManufacturer("Manufacturer1");
- ncDesc.setDescription("SDNProtocol1");
- ncDesc.setSerialNumber("serialNumber1");
- ncDesc.setSoftware("Software1");
-
- Assert.assertTrue(ncDesc.getHardware().equals("Hardware1"));
- Assert.assertTrue(ncDesc.getManufacturer().equals("Manufacturer1"));
- Assert.assertTrue(ncDesc.getDescription().equals("SDNProtocol1"));
- Assert.assertTrue(ncDesc.getSerialNumber().equals("serialNumber1"));
- Assert.assertTrue(ncDesc.getSoftware().equals("Software1"));
-
- Assert.assertFalse(ncDesc.getHardware().equals("Hardware2"));
- Assert.assertFalse(ncDesc.getManufacturer().equals("Manufacturer2"));
- Assert.assertFalse(ncDesc.getDescription().equals("SDNProtocol2"));
- Assert.assertFalse(ncDesc.getSerialNumber().equals("serialNumber2"));
- Assert.assertFalse(ncDesc.getSoftware().equals("Software2"));
-
- }
-}
-
-
+ @Test
+ public void testNodeDescriptionMethods() {
+ NodeDescription ncDesc = new NodeDescription();
+ ncDesc.setHardware("Hardware1");
+ ncDesc.setManufacturer("Manufacturer1");
+ ncDesc.setDescription("SDNProtocol1");
+ ncDesc.setSerialNumber("serialNumber1");
+ ncDesc.setSoftware("Software1");
+
+ Assert.assertTrue(ncDesc.getHardware().equals("Hardware1"));
+ Assert.assertTrue(ncDesc.getManufacturer().equals("Manufacturer1"));
+ Assert.assertTrue(ncDesc.getDescription().equals("SDNProtocol1"));
+ Assert.assertTrue(ncDesc.getSerialNumber().equals("serialNumber1"));
+ Assert.assertTrue(ncDesc.getSoftware().equals("Software1"));
+
+ Assert.assertFalse(ncDesc.getHardware().equals("Hardware2"));
+ Assert.assertFalse(ncDesc.getManufacturer().equals("Manufacturer2"));
+ Assert.assertFalse(ncDesc.getDescription().equals("SDNProtocol2"));
+ Assert.assertFalse(ncDesc.getSerialNumber().equals("serialNumber2"));
+ Assert.assertFalse(ncDesc.getSoftware().equals("Software2"));
+
+ }
+}
import java.util.ArrayList;
import org.junit.Assert;
import org.junit.Test;
-
+
public class EtherTypesTest {
-
- @Test
- public void testEthertypesCreation() {
-
- EtherTypes arp = EtherTypes.ARP;
-
- Assert.assertTrue(arp.toString().equals("ARP"));
- Assert.assertTrue(arp.intValue() == 2054);
- Assert.assertTrue(arp.shortValue() == (short)2054);
- }
-
- @Test
- public void testGetEtherTypesString() {
-
- Assert.assertTrue(EtherTypes.getEtherTypeName(34984).equals("QINQ"));
- Assert.assertTrue(EtherTypes.getEtherTypeName((short)2048).equals("IPv4"));
- Assert.assertTrue(EtherTypes.getEtherTypeName(0x010B).equals("PVSTP"));
-
- Assert.assertFalse(EtherTypes.getEtherTypeName(0x800).equals("ARP"));
- }
-
- @Test
- public void testGetEtherTypesNumber() {
- Assert.assertTrue(EtherTypes.getEtherTypeNumberInt("VLAN Tagged") == 33024);
- Assert.assertTrue(EtherTypes.getEtherTypeNumberShort("ARP") == 2054);
-
- Assert.assertFalse(EtherTypes.getEtherTypeNumberInt("CDP") == 1000);
- }
-
- @Test
- public void testGetEtherTypesList() {
- ArrayList<String> etherTypeNames = (ArrayList<String>) EtherTypes.getEtherTypesNameList();
- Assert.assertTrue(etherTypeNames.get(0).equals("PVSTP"));
- Assert.assertTrue(etherTypeNames.get(1).equals("CDP"));
- Assert.assertTrue(etherTypeNames.get(2).equals("VTP"));
- Assert.assertTrue(etherTypeNames.get(3).equals("IPv4"));
- Assert.assertTrue(etherTypeNames.get(4).equals("ARP"));
- Assert.assertTrue(etherTypeNames.get(5).equals("Reverse ARP"));
- Assert.assertTrue(etherTypeNames.get(6).equals("VLAN Tagged"));
- Assert.assertTrue(etherTypeNames.get(7).equals("IPv6"));
- Assert.assertTrue(etherTypeNames.get(8).equals("MPLS Unicast"));
- Assert.assertTrue(etherTypeNames.get(9).equals("MPLS Multicast"));
- Assert.assertTrue(etherTypeNames.get(10).equals("QINQ"));
- Assert.assertTrue(etherTypeNames.get(11).equals("LLDP"));
- Assert.assertTrue(etherTypeNames.get(12).equals("Old QINQ"));
- Assert.assertTrue(etherTypeNames.get(13).equals("Cisco QINQ"));
- }
-
- @Test
- public void testGetEtherTypesloadFromString() {
- Assert.assertTrue(EtherTypes.loadFromString("37376").equals(EtherTypes.CISCOQINQ));
- Assert.assertTrue(EtherTypes.loadFromString("100") == null);
- }
-}
+ @Test
+ public void testEthertypesCreation() {
+
+ EtherTypes arp = EtherTypes.ARP;
+
+ Assert.assertTrue(arp.toString().equals("ARP"));
+ Assert.assertTrue(arp.intValue() == 2054);
+ Assert.assertTrue(arp.shortValue() == (short)2054);
+ }
+
+ @Test
+ public void testGetEtherTypesString() {
+ Assert.assertTrue(EtherTypes.getEtherTypeName(34984).equals("QINQ"));
+ Assert.assertTrue(EtherTypes.getEtherTypeName((short)2048).equals("IPv4"));
+ Assert.assertTrue(EtherTypes.getEtherTypeName(0x010B).equals("PVSTP"));
+ Assert.assertFalse(EtherTypes.getEtherTypeName(0x800).equals("ARP"));
+ }
+ @Test
+ public void testGetEtherTypesNumber() {
+ Assert.assertTrue(EtherTypes.getEtherTypeNumberInt("VLAN Tagged") == 33024);
+ Assert.assertTrue(EtherTypes.getEtherTypeNumberShort("ARP") == 2054);
+
+ Assert.assertFalse(EtherTypes.getEtherTypeNumberInt("CDP") == 1000);
+ }
+
+ @Test
+ public void testGetEtherTypesList() {
+ ArrayList<String> etherTypeNames = (ArrayList<String>) EtherTypes.getEtherTypesNameList();
+ Assert.assertTrue(etherTypeNames.get(0).equals("PVSTP"));
+ Assert.assertTrue(etherTypeNames.get(1).equals("CDP"));
+ Assert.assertTrue(etherTypeNames.get(2).equals("VTP"));
+ Assert.assertTrue(etherTypeNames.get(3).equals("IPv4"));
+ Assert.assertTrue(etherTypeNames.get(4).equals("ARP"));
+ Assert.assertTrue(etherTypeNames.get(5).equals("Reverse ARP"));
+ Assert.assertTrue(etherTypeNames.get(6).equals("VLAN Tagged"));
+ Assert.assertTrue(etherTypeNames.get(7).equals("IPv6"));
+ Assert.assertTrue(etherTypeNames.get(8).equals("MPLS Unicast"));
+ Assert.assertTrue(etherTypeNames.get(9).equals("MPLS Multicast"));
+ Assert.assertTrue(etherTypeNames.get(10).equals("QINQ"));
+ Assert.assertTrue(etherTypeNames.get(11).equals("LLDP"));
+ Assert.assertTrue(etherTypeNames.get(12).equals("Old QINQ"));
+ Assert.assertTrue(etherTypeNames.get(13).equals("Cisco QINQ"));
+ }
+
+ @Test
+ public void testGetEtherTypesloadFromString() {
+ Assert.assertTrue(EtherTypes.loadFromString("37376").equals(EtherTypes.CISCOQINQ));
+ Assert.assertTrue(EtherTypes.loadFromString("100") == null);
+ }
+
+}
*/
package org.opendaylight.controller.sal.utils;
-
+
import org.junit.Assert;
import org.junit.Test;
-
+
public class HexEncodeTest {
-
- @Test
- public void testbytesToHexString() {
- byte[] bytes1 = {(byte)0x01, (byte)0x02, (byte)0x03};
- String str1 = HexEncode.bytesToHexString(bytes1);
- Assert.assertTrue(str1.equals("010203"));
-
- byte[] bytes2 = {(byte)0x11, (byte)0x22, (byte)0x33};
- String str2 = HexEncode.bytesToHexString(bytes2);
- Assert.assertFalse(str2.equals("010203"));
-
- }
-
- @Test
- public void testLongToHexString() {
- long value1 = 12345678L;
- String str1 = HexEncode.longToHexString(value1);
- Assert.assertTrue(str1.equals("00:00:00:00:00:bc:61:4e"));
-
- long value2 = 98765432L;
- String str2 = HexEncode.longToHexString(value2);
- Assert.assertFalse(str2.equals("00:44:33:22:11:bc:61:4e"));
-
- }
-
- @Test
- public void testBytesFromHexString() {
- String byteStr1 = "00:11:22:33:44:55";
- byte byteArray1[] = new byte[(byteStr1.length() + 1)/3];
- byteArray1 = HexEncode.bytesFromHexString(byteStr1);
-
- Assert.assertTrue(byteArray1[0] == (byte)0x0);
- Assert.assertTrue(byteArray1[1] == (byte)0x11);
- Assert.assertTrue(byteArray1[2] == (byte)0x22);
- Assert.assertTrue(byteArray1[3] == (byte)0x33);
- Assert.assertTrue(byteArray1[4] == (byte)0x44);
- Assert.assertTrue(byteArray1[5] == (byte)0x55);
-
- String byteStr2 = "00:11:22:33:44:55";
- byte byteArray2[] = new byte[(byteStr2.length() + 1)/3];
- byteArray2 = HexEncode.bytesFromHexString(byteStr2);
-
- Assert.assertFalse(byteArray2[0] == (byte)0x55);
- Assert.assertFalse(byteArray2[1] == (byte)0x44);
- Assert.assertFalse(byteArray2[2] == (byte)0x33);
- Assert.assertFalse(byteArray2[3] == (byte)0x22);
- Assert.assertFalse(byteArray2[4] == (byte)0x11);
- Assert.assertFalse(byteArray2[5] == (byte)0x0);
-
- }
-
-}
+ @Test
+ public void testbytesToHexString() {
+ byte[] bytes1 = {(byte)0x01, (byte)0x02, (byte)0x03};
+ String str1 = HexEncode.bytesToHexString(bytes1);
+ Assert.assertTrue(str1.equals("010203"));
+
+ byte[] bytes2 = {(byte)0x11, (byte)0x22, (byte)0x33};
+ String str2 = HexEncode.bytesToHexString(bytes2);
+ Assert.assertFalse(str2.equals("010203"));
+
+ }
+
+ @Test
+ public void testLongToHexString() {
+ long value1 = 12345678L;
+ String str1 = HexEncode.longToHexString(value1);
+ Assert.assertTrue(str1.equals("00:00:00:00:00:bc:61:4e"));
+
+ long value2 = 98765432L;
+ String str2 = HexEncode.longToHexString(value2);
+ Assert.assertFalse(str2.equals("00:44:33:22:11:bc:61:4e"));
+ }
+ @Test
+ public void testBytesFromHexString() {
+ String byteStr1 = "00:11:22:33:44:55";
+ byte byteArray1[] = new byte[(byteStr1.length() + 1)/3];
+ byteArray1 = HexEncode.bytesFromHexString(byteStr1);
+
+ Assert.assertTrue(byteArray1[0] == (byte)0x0);
+ Assert.assertTrue(byteArray1[1] == (byte)0x11);
+ Assert.assertTrue(byteArray1[2] == (byte)0x22);
+ Assert.assertTrue(byteArray1[3] == (byte)0x33);
+ Assert.assertTrue(byteArray1[4] == (byte)0x44);
+ Assert.assertTrue(byteArray1[5] == (byte)0x55);
+
+ String byteStr2 = "00:11:22:33:44:55";
+ byte byteArray2[] = new byte[(byteStr2.length() + 1)/3];
+ byteArray2 = HexEncode.bytesFromHexString(byteStr2);
+
+ Assert.assertFalse(byteArray2[0] == (byte)0x55);
+ Assert.assertFalse(byteArray2[1] == (byte)0x44);
+ Assert.assertFalse(byteArray2[2] == (byte)0x33);
+ Assert.assertFalse(byteArray2[3] == (byte)0x22);
+ Assert.assertFalse(byteArray2[4] == (byte)0x11);
+ Assert.assertFalse(byteArray2[5] == (byte)0x0);
+
+ }
+
+}
/**
* Function called when the activator starts just after some initializations
* are done by the ComponentActivatorAbstractBase.
- *
+ *
*/
public void init() {
/**
* Function called when the activator stops just before the cleanup done by
* ComponentActivatorAbstractBase
- *
+ *
*/
public void destroy() {
/**
* Function that is used to communicate to dependency manager the list of
* known implementations for services inside a container
- *
- *
+ *
+ *
* @return An array containing all the CLASS objects that will be
* instantiated in order to get an fully working implementation
* Object
/**
* Function that is called when configuration of the dependencies is
* required.
- *
+ *
* @param c
* dependency manager Component object, used for configuring the
* dependencies exported and imported
/**
* Function called by the dependency manager when all the required
* dependencies are satisfied
- *
+ *
*/
void init() {
logger.debug("INIT called!");
* Function called by the dependency manager when at least one dependency
* become unsatisfied or when the component is shutting down because for
* example bundle is being stopped.
- *
+ *
*/
void destroy() {
// Clear previous registration to avoid they are left hanging
/**
* Function called by dependency manager after "init ()" is called and after
* the services provided by the class are registered in the service registry
- *
+ *
*/
void start() {
logger.debug("START called!");
* Function called by the dependency manager before the services exported by
* the component are unregistered, this will be followed by a "destroy ()"
* calls
- *
+ *
*/
void stop() {
logger.debug("STOP called!");
}
ci.println(this.addFlow(node, getSampleFlow(node)));
}
-
+
public void _modifyflow(CommandInterpreter ci) throws UnknownHostException {
Node node = null;
String nodeId = ci.nextArgument();
/**
* This Request ID generator starts with 1. Each aysnc message is
* associated with an unique Request ID (!= 0).
- *
+ *
* @return Request ID
*/
private long getNextRid() {
/**
* Function called by the dependency manager when all the required
* dependencies are satisfied
- *
+ *
*/
void init() {
}
* Function called by the dependency manager when at least one dependency
* become unsatisfied or when the component is shutting down because for
* example bundle is being stopped.
- *
+ *
*/
void destroy() {
// Make sure to clear all the data structure we use to track
public class DataPacketServiceTest {
- @Test
- public void DataPacketServiceDecodeTest() throws ConstructionException, InstantiationException, IllegalAccessException {
-
- DataPacketService dService = new DataPacketService();
- RawPacket rawPkt = null;
-
- Assert.assertTrue(dService.decodeDataPacket(rawPkt) == null);
-
+ @Test
+ public void DataPacketServiceDecodeTest() throws ConstructionException, InstantiationException, IllegalAccessException {
+
+ DataPacketService dService = new DataPacketService();
+ RawPacket rawPkt = null;
+
+ Assert.assertTrue(dService.decodeDataPacket(rawPkt) == null);
+
byte[] data = { 10, 12, 14, 20, 55, 69, //DMAC
-90, -20, -100, -82, -78, -97, //SMAC
8, 6, //ethype
9, 9, 9, 1, // src proto
0, 0, 0, 0, 0, 0, // target hw addr
9, 9, 9, -2 }; // target proto
-
+
rawPkt = new RawPacket(data);
-
+
Packet decodedPkt = dService.decodeDataPacket(rawPkt);
Class<? extends Packet> payloadClass = ARP.class;
Assert.assertTrue(payloadClass == decodedPkt.getPayload().getClass());
-
+
ARP arpPacket = (ARP) decodedPkt.getPayload();
-
+
Assert.assertTrue(arpPacket.getHardwareType() == (byte)0x1);
Assert.assertTrue(arpPacket.getProtocolType() == 2048);
Assert.assertTrue(arpPacket.getHardwareAddressLength() == (byte)0x6);
Assert.assertTrue(arpPacket.getProtocolAddressLength() == (byte)0x4);
Assert.assertTrue(arpPacket.getOpCode() == 1);
-
+
byte[] senderHwAddress = arpPacket.getSenderHardwareAddress();
- byte[] senderProtocolAddress = arpPacket.getSenderProtocolAddress();
-
+ byte[] senderProtocolAddress = arpPacket.getSenderProtocolAddress();
+
byte[] targetHwAddress = arpPacket.getTargetHardwareAddress();
- byte[] targetProtocolAddress = arpPacket.getTargetProtocolAddress();
+ byte[] targetProtocolAddress = arpPacket.getTargetProtocolAddress();
+
-
Assert.assertTrue(senderHwAddress[0] == (byte)0xA6);
Assert.assertTrue(senderHwAddress[1] == (byte)0xEC);
Assert.assertTrue(senderHwAddress[2] == (byte)0x9C);
Assert.assertTrue(senderHwAddress[3] == (byte)0xAE);
Assert.assertTrue(senderHwAddress[4] == (byte)0xB2);
Assert.assertTrue(senderHwAddress[5] == (byte)0x9F);
-
+
Assert.assertTrue(senderProtocolAddress[0] == (byte)0x9);
Assert.assertTrue(senderProtocolAddress[1] == (byte)0x9);
Assert.assertTrue(senderProtocolAddress[2] == (byte)0x9);
Assert.assertTrue(targetProtocolAddress[0] == (byte)0x9);
Assert.assertTrue(targetProtocolAddress[1] == (byte)0x9);
Assert.assertTrue(targetProtocolAddress[2] == (byte)0x9);
- Assert.assertTrue(targetProtocolAddress[3] == (byte)0xFE);
- }
-
- @Test
- public void DataPacketServiceEncodeTest() throws ConstructionException, InstantiationException, IllegalAccessException {
-
- DataPacketService dService = new DataPacketService();
- Ethernet eth = new Ethernet();
+ Assert.assertTrue(targetProtocolAddress[3] == (byte)0xFE);
+ }
+
+ @Test
+ public void DataPacketServiceEncodeTest() throws ConstructionException, InstantiationException, IllegalAccessException {
+
+ DataPacketService dService = new DataPacketService();
+ Ethernet eth = new Ethernet();
ARP arp = new ARP();
- byte[] data = null;
- RawPacket rawPkt;
+ byte[] data = null;
+ RawPacket rawPkt;
byte[] dMAC = { 10, 12, 14, 20, 55, 69 };
byte[] sMAC = { 82, 97, 109, 117, 127, -50 };
short etherType = 2054;
-
+
eth.setDestinationMACAddress(dMAC);
eth.setSourceMACAddress(sMAC);
eth.setEtherType(etherType);
-
+
arp.setHardwareType((short)1);
arp.setProtocolType((short)2048);
arp.setHardwareAddressLength((byte)0x6);
arp.setProtocolAddressLength((byte)0x4);
arp.setOpCode((byte)0x1);
-
+
byte[] senderHardwareAddress = {(byte)0xA6, (byte)0xEC, (byte)0x9C, (byte)0xAE,
- (byte)0xB2, (byte)0x9F};
+ (byte)0xB2, (byte)0x9F};
byte[] senderProtocolAddress = {(byte)0x09, (byte)0x09, (byte)0x09, (byte)0x01};
byte[] targetProtocolAddress = {(byte)0x09, (byte)0x09, (byte)0x09, (byte)0xFE};
byte[] targetHardwareAddress = {(byte)0x0, (byte)0x0, (byte)0x0, (byte)0x0, (byte)0x0, (byte)0x0};
arp.setSenderProtocolAddress(senderProtocolAddress);
arp.setTargetHardwareAddress(targetHardwareAddress);
arp.setTargetProtocolAddress(targetProtocolAddress);
-
+
arp.setParent(eth);
eth.setPayload(arp);
-
+
rawPkt = dService.encodeDataPacket(eth);
data = rawPkt.getPacketData();
-
+
Assert.assertTrue(data[0] == (byte)0x0A);//Destination MAC
Assert.assertTrue(data[1] == (byte)0x0C);
Assert.assertTrue(data[2] == (byte)0x0E);
Assert.assertTrue(data[38] == (byte)0x09);//Target Protocol Address
Assert.assertTrue(data[39] == (byte)0x09);
Assert.assertTrue(data[40] == (byte)0x09);
- Assert.assertTrue(data[41] == (byte)0xFE);
- }
+ Assert.assertTrue(data[41] == (byte)0xFE);
+ }
}
/**
* This class represents a configuration manager for the Load Balancer service.
- * This class is responsible for managing(store/update/delete) the load balancer
+ * This class is responsible for managing(store/update/delete) the load balancer
* configuration that it receives through REST APIs or from any other applications
* present in the controller.
*
*/
public class ConfigManager implements IConfigManager{
-
+
/*
* Logger instance
*/
private static final Logger cmLogger = LoggerFactory.getLogger(ConfigManager.class);
-
+
/*
- * All the available VIPs
+ * All the available VIPs
*/
private HashMap<String,VIP> vips = new HashMap<String,VIP>();
-
+
/*
* All the available Pools
*/
private HashMap<String,Pool> pools = new HashMap<String,Pool>();
-
+
public ConfigManager(){
}
-
+
@Override
public boolean vipExists(String name) {
return this.vips.containsKey(name);
}
-
+
@Override
public boolean vipExists(VIP vip){
if(vip.getName()==null){
}
return true;
}
-
+
@Override
public boolean vipExists(String name,String ip,String protocol,short protocolPort,String poolName){
-
+
VIP vip = new VIP(name,ip,protocol,protocolPort,poolName);
-
+
//Check VIP with the same name
-
+
if(!vips.containsKey(name)){
//Check VIP with the same ip, protocol and protocolPort
if(!vips.containsValue(vip)){
-
+
//if you reach here, means this VIP don't exist
return false;
}
}
-
+
//Yeah, i have it.
- return true;
+ return true;
}
-
+
@Override
public Set<VIP> getAllVIPs(){
return new HashSet<VIP>(this.vips.values());
}
-
+
public VIP getVIPWithPoolName(VIP vip){
cmLogger.info("Search a VIP with name:{}",vip);
for(VIP vipTemp: this.vips.values()){
if(vipTemp.equals(vip)){
-
+
cmLogger.info("Found VIP with pool detail : {}",vipTemp);
return vipTemp;
}
}
-
+
cmLogger.info("VIP with pool detail not found ");
return null;
}
-
+
@Override
public VIP createVIP(String name,String ip,String protocol,short protocolPort,String poolName){
-
+
cmLogger.info("Create VIP with the following details :[ name : "+name
+" ip : "+ip
+" protocol : "+protocol
+" protocol_port : "+protocolPort
+" pool name : "+poolName);
-
+
VIP vip = new VIP(name,ip,protocol,protocolPort,poolName);
-
+
if(poolName !=null && !poolName.isEmpty()){
if(pools.containsKey(poolName)){
pools.get(poolName).addVIP(vip);
}
}
-
+
vip.setStatus(LBConst.STATUS_ACTIVE);
this.vips.put(name, vip);
-
+
cmLogger.info("New VIP created : "+vip.toString());
return vip;
}
-
+
@Override
public String getVIPAttachedPool(String name) {
return this.vips.get(name).getPoolName();
}
-
+
@Override
public VIP updateVIP(String name, String poolName){
-
+
cmLogger.info("Updating VIP : "+name+" pool name to "+poolName);
-
+
if(vips.containsKey(name)){
VIP vip = vips.get(name);
if(vip.getPoolName() == null){
cmLogger.error("VIP with name: "+name+" does not exist");
return null;
}
-
+
@Override
public VIP deleteVIP(String name){
-
+
cmLogger.info("Deleting VIP : "+name);
-
+
VIP vip = vips.get(name);
-
+
String poolName = vip.getPoolName();
-
+
if(poolName != null){
if(pools.containsKey(poolName)){
Pool pool = pools.get(poolName);
pool.removeVIP(vip.getName());
}
}
-
+
cmLogger.info("VIP removed : "+vip.toString());
-
+
vips.remove(vip.getName());
-
+
return vip;
}
-
+
@Override
public boolean memberExists(String name, String poolName) {
if(this.pools.containsKey(poolName)){
}
return false;
}
-
+
@Override
public boolean memberExists(String name, String memberIP,String poolName){
if(!this.pools.containsKey(poolName))
return false;
-
+
return this.pools.get(poolName).poolMemberExists(new PoolMember(name, memberIP, poolName));
}
-
+
@Override
public PoolMember addPoolMember(String name, String memberIP, String poolName){
-
+
PoolMember pm = new PoolMember(name,memberIP,poolName);
-
+
cmLogger.info("Adding pool member : "+pm.toString());
-
+
pools.get(poolName).addMember(pm);
-
+
return pm;
}
-
+
@Override
public PoolMember removePoolMember(String name, String poolName){
-
+
cmLogger.info("Removing pool member : {} from pool {}",name, poolName);
-
+
Pool pool = pools.get(poolName);
-
+
PoolMember pm = pool.getMember(name);
-
+
pool.removeMember(name);
-
+
cmLogger.info("Pool member {} removed from {} ",name,poolName);
-
+
return pm;
}
-
+
@Override
public Set<Pool> getAllPools(){
return new HashSet<Pool>(this.pools.values());
}
-
+
@Override
public boolean poolExists(String name) {
return this.pools.containsKey(name);
}
-
+
@Override
public boolean poolExists(String name, String lbMethod){
-
+
return pools.containsValue(new Pool(name,lbMethod));
}
-
+
@Override
public Pool createPool(String name, String lbMethod){
-
+
Pool newPool = new Pool(name,lbMethod);
-
+
cmLogger.info("New pool created : " + newPool.toString());
-
+
pools.put(name, newPool);
-
+
return newPool;
}
-
+
@Override
public Pool deletePool(String poolName){
-
+
Pool pool = pools.get(poolName);
-
+
for(VIP vip:pool.getAllVip()){
-
+
vip.setPoolName(null);
-
+
}
-
+
cmLogger.info("Pool removed : "+pool.toString());
-
+
pools.remove(poolName);
-
+
return pool;
}
-
+
@Override
public Pool getPool( String poolName){
if(pools.containsKey(poolName)){
}
return null;
}
-
+
@Override
public Set<PoolMember> getAllPoolMembers(String poolName) {
-
+
if(pools.containsKey(poolName)){
return new HashSet<PoolMember>(pools.get(poolName).getAllMembers());
}
return null;
}
-
+
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
*
*/
public interface IConfigManager {
-
+
/**
* Return all existing VIPs
* @return Set of VIP's
* if there is no VIP, it will return empty set.
*/
public Set<VIP> getAllVIPs();
-
+
/**
* Check if VIP with the 'name' exists
- * @param name Name of the VIP
- * @return true if exists
- * false else
+ * @param name Name of the VIP
+ * @return true if exists
+ * false else
*/
public boolean vipExists(String name);
/**
- * Check if VIP exists with the details 'VIP'
- * @param vip Search for this VIP
- * @return true if exists
- * false else
+ * Check if VIP exists with the details 'VIP'
+ * @param vip Search for this VIP
+ * @return true if exists
+ * false else
*/
public boolean vipExists(VIP vip);
/**
* Check if VIP with the provided details exists
- * @param name Name of the VIP
- * @param ip IP of the VIP
- * @param protocol IP Protocol of the VIP (TCP/UDP)
- * @param protocolPort Transport port of the VIP (e.g 5550)
- * @param poolName Name of the pool attached with the VIP
- * @return true if exists
- * false else
+ * @param name Name of the VIP
+ * @param ip IP of the VIP
+ * @param protocol IP Protocol of the VIP (TCP/UDP)
+ * @param protocolPort Transport port of the VIP (e.g 5550)
+ * @param poolName Name of the pool attached with the VIP
+ * @return true if exists
+ * false else
*/
public boolean vipExists(String name,String ip,String protocol,short protocolPort,String poolName);
-
+
/**
* Add VIP to the configuration
- * @param name Name of the VIP
- * @param ip IP of the VIP
- * @param protocol IP Protocol of the VIP (TCP/UDP)
- * @param protocolPort Transport port of the VIP
- * @param poolName Name of the pool that VIP will use for load balancing its traffic
- * @return Newly created VIP
+ * @param name Name of the VIP
+ * @param ip IP of the VIP
+ * @param protocol IP Protocol of the VIP (TCP/UDP)
+ * @param protocolPort Transport port of the VIP
+ * @param poolName Name of the pool that VIP will use for load balancing its traffic
+ * @return Newly created VIP
*/
public VIP createVIP(String name,String ip,String protocol,short protocolPort,String poolName);
-
+
/**
* Return pool attached to VIP
* @param name Name of the VIP
- * @return Name of the pool attached to VIP
- * else null
+ * @return Name of the pool attached to VIP
+ * else null
*/
public String getVIPAttachedPool(String name);
/**
* Update pool name of the VIP.
- * @param name Name of the VIP
- * @param poolName Attach this pool to VIP
- * @return Updated VIP If successful
- * null If this VIP is already attached to any existing pool.
- */
+ * @param name Name of the VIP
+ * @param poolName Attach this pool to VIP
+ * @return Updated VIP If successful
+ * null If this VIP is already attached to any existing pool.
+ */
public VIP updateVIP(String name, String poolName);
-
+
/**
* Delete the VIP
- * @param name Delete VIP with this name
- * @return Details of the deleted VIP
+ * @param name Delete VIP with this name
+ * @return Details of the deleted VIP
*/
public VIP deleteVIP(String name);
/**
- * Check if pool member with the 'name' present in the pool with name 'poolName'
- * @param name Name of the pool member
- * @param poolName Name of the pool, you want to search for pool member
- * @return true If exist
- * false else
+ * Check if pool member with the 'name' present in the pool with name 'poolName'
+ * @param name Name of the pool member
+ * @param poolName Name of the pool, you want to search for pool member
+ * @return true If exist
+ * false else
*/
public boolean memberExists(String name, String poolName);
/**
* Check if pool member with name 'name' and IP 'memberIP' exist in the pool 'poolName'
- * @param name Name of the pool member
- * @param memberIP IP of the pool member
- * @param poolName Name of the pool member you want to search
- * @return true If Exist
- * false else
+ * @param name Name of the pool member
+ * @param memberIP IP of the pool member
+ * @param poolName Name of the pool member you want to search
+ * @return true If Exist
+ * false else
*/
public boolean memberExists(String name, String memberIP,String poolName);
-
+
/**
* Return all pool members of the pool 'poolName'
- * @param poolName Name of the pool
- * @return Set of all the pool members if pool with the name present in the configuration
- * null else
- *
+ * @param poolName Name of the pool
+ * @return Set of all the pool members if pool with the name present in the configuration
+ * null else
+ *
*/
public Set<PoolMember> getAllPoolMembers(String poolName);
-
+
/**
* Add new pool member to the configuration
- * @param name Name of the pool
- * @param memberIP IP of the pool
- * @param poolName Attach pool member to this pool
- * @return Newly created pool member
+ * @param name Name of the pool
+ * @param memberIP IP of the pool
+ * @param poolName Attach pool member to this pool
+ * @return Newly created pool member
*/
public PoolMember addPoolMember(String name, String memberIP, String poolName);
-
+
/**
* Remove pool member from the pool
- * @param name Name of the pool member
- * @param poolName Name of the pool
- * @return Details of the removed pool member
+ * @param name Name of the pool member
+ * @param poolName Name of the pool
+ * @return Details of the removed pool member
*/
public PoolMember removePoolMember(String name, String poolName);
/**
* Return all the existing pools
- * @return Set of Pools
+ * @return Set of Pools
*/
public Set<Pool> getAllPools();
-
+
/**
* Return pool with input name
- * @param poolName Name of the pool
- * @return Details of the pool if pool exist
- * null else
+ * @param poolName Name of the pool
+ * @return Details of the pool if pool exist
+ * null else
*/
public Pool getPool(String poolName);
-
+
/**
- * Check if pool exists with the input name
- * @param name Name of the pool
- * @return true If exists
- * false else
+ * Check if pool exists with the input name
+ * @param name Name of the pool
+ * @return true If exists
+ * false else
*/
public boolean poolExists(String name);
/**
* Check if pool exists with the input name and loadbalancing method.
- * @param name Name of the pool
- * @param lbMethod Load balancing method name
- * @return true If exists
- * false else
+ * @param name Name of the pool
+ * @param lbMethod Load balancing method name
+ * @return true If exists
+ * false else
*/
public boolean poolExists(String name, String lbMethod);
-
+
/**
* Create new pool with the provided details
- * @param name Name of the pool
- * @param lbMethod Load balancing method this pool will use
- * @return Details of the newly created pool
+ * @param name Name of the pool
+ * @param lbMethod Load balancing method this pool will use
+ * @return Details of the newly created pool
*/
public Pool createPool(String name, String lbMethod);
-
+
/**
* Delete pool with the provided name
- * @param poolName Name of the pool
- * @return Details of the deleted pool
+ * @param poolName Name of the pool
+ * @return Details of the deleted pool
*/
public Pool deletePool(String poolName);
*
*/
public class LBConst {
-
+
public static final int FORWARD_DIRECTION_LB_FLOW = 0;
-
+
public static final int REVERSE_DIRECTION_LB_FLOW = 1;
-
+
public static final String ROUND_ROBIN_LB_METHOD = "roundrobin";
-
+
public static final String RANDOM_LB_METHOD = "random";
-
+
public static final String STATUS_ACTIVE="active";
-
+
public static final String STATUS_INACTIVE="inactive";
-
+
public static final String STATUS_PENDING="pending";
-
+
public static final String STATUS_ERROR="error";
-
-}
+}
import org.slf4j.LoggerFactory;
/**
- * Class defines utilty methods that will be used by different components
- * of the load balancer service
+ * Class defines utilty methods that will be used by different components
+ * of the load balancer service
*
*/
public class LBUtil {
-
+
private static final Logger lbuLogger = LoggerFactory.getLogger(LBUtil.class);
-
+
public LBUtil(){}
-
+
/**
- * Extract the details of the source machine that sent this packet 'inPkt'
- * @param inPkt Packet that is received by the controller
- * @return Details of the source machine in Client object.
+ * Extract the details of the source machine that sent this packet 'inPkt'
+ * @param inPkt Packet that is received by the controller
+ * @return Details of the source machine in Client object.
*/
public Client getClientFromPacket(IPv4 inPkt){
lbuLogger.info("Find client information from packet : {}",inPkt.toString());
-
+
String ip = NetUtils.getInetAddress(inPkt.getSourceAddress()).getHostAddress();
-
+
String protocol = IPProtocols.getProtocolName(inPkt.getProtocol());
-
+
lbuLogger.info("client ip {} and protocl {}",ip,protocol);
-
+
Packet tpFrame= inPkt.getPayload();
-
+
lbuLogger.info("Get protocol layer {}",tpFrame.toString());
-
+
short port = 0;
-
+
if(protocol.equals(IPProtocols.TCP.toString())){
TCP tcpFrame = (TCP)tpFrame;
port = tcpFrame.getSourcePort();
UDP udpFrame = (UDP)tpFrame;
port = udpFrame.getSourcePort();
}
-
+
lbuLogger.info("Found port {}",port);
-
+
Client source = new Client(ip, protocol,port);
-
+
lbuLogger.info("Client information : {}",source.toString());
-
+
return source;
}
-
+
/**
* Extract the details of the destination machine where this packet 'inPkt' need
* to be delivered
* @param inPkt Packet that is received by controller for forwarding
- * @return Details of the destination machine packet in VIP
+ * @return Details of the destination machine packet in VIP
*/
public VIP getVIPFromPacket(IPv4 inPkt){
-
+
lbuLogger.info("Find VIP information from packet : {}",inPkt.toString());
-
+
String ip = NetUtils.getInetAddress(inPkt.getDestinationAddress()).getHostAddress();
-
+
String protocol = IPProtocols.getProtocolName(inPkt.getProtocol());
-
+
Packet tpFrame= inPkt.getPayload();
-
+
short port = 0;
-
+
if(protocol.equals(IPProtocols.TCP.toString())){
TCP tcpFrame = (TCP)tpFrame;
port = tcpFrame.getDestinationPort();
}else{
-
+
UDP udpFrame = (UDP)tpFrame;
port = udpFrame.getDestinationPort();
}
-
+
VIP dest = new VIP(null,ip, protocol,port,null);
-
+
lbuLogger.info("VIP information : {}",dest.toString());
-
+
return dest;
}
}
\ No newline at end of file
* e.g TCP traffic from two different ports from the same host to a given VIP will be considered
* as two different clients by this service. Similarly, traffic using two different protocols
* (TCP, UDP) from the same host will be considered as two different clients.
- *
+ *
*/
public class Client {
-
+
/*
* IP address of the client (source address)
*/
private String ip;
-
+
/*
* Network protocol of the traffic sent by client
*/
private String protocol;
-
+
/*
* Port used to send network traffic (source port)
*/
private short port;
-
+
public Client(String ip, String protocol, short port){
this.ip = ip;
this.protocol = protocol;
this.port = port;
}
-
+
/**
* @return the client IP
*/
public String getIp() {
return ip;
}
-
+
/**
* @param ip the IP to set
*/
public void setIp(String ip) {
this.ip = ip;
}
-
+
/**
* @return the client network protocol
*/
public String getProtocol() {
return protocol;
}
-
+
/**
* @param protocol the protocol to set
*/
public void setProtocol(String protocol) {
this.protocol = protocol;
}
-
+
/**
* @return the client port
*/
public short getPort() {
return port;
}
-
+
/**
* @param port the port to set
*/
public void setPort(short port) {
this.port = port;
}
-
+
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
result = prime * result+ ((protocol == null) ? 0 : protocol.hashCode());
return result;
}
-
+
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
}
return true;
}
-
+
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
/**
* This class represents the pool of hosts among which incoming traffic
- * will be load balanced. Each pool will load balance the traffic among its pool members
- * based on the loadbalancing policy set for the pool.
+ * will be load balanced. Each pool will load balance the traffic among its pool members
+ * based on the loadbalancing policy set for the pool.
* Currently, the pool supports two load balancing policies:
* 1. Round Robin Policy{@link org.opendaylight.controller.samples.loadbalancer.policies.RoundRobinLBPolicy}
* 2. Random Policy {@link org.opendaylight.controller.samples.loadbalancer.policies.RandomLBPolicy}
- *
+ *
* NOTE: After creation of the pool, user can't update (change) its load balancing policy.
* NOTE: Each Pool should have a unique name.
*/
@XmlRootElement(name="pool")
@XmlAccessorType(XmlAccessType.NONE)
public class Pool {
-
+
/*
* Unique name of the pool
*/
@XmlElement
private String name;
-
+
/*
* Associated load balancing policy
*/
@XmlElement(name="lbmethod")
private String lbMethod;
-
+
/*
* Status of the pool (active/inactive)
*/
@XmlElement
private String status;
-
+
/*
* List of all the VIPs using this pool for load balancing their traffic - more than
* one VIP can be mapped to each pool.
*/
@XmlElement
private ArrayList<VIP> vips = new ArrayList<VIP>();
-
+
/*
* List of all the pool members used for load balancing the traffic
*/
@XmlElement
private ArrayList<PoolMember> members = new ArrayList<PoolMember>();
-
+
/*
* Private constructor used for JAXB mapping
*/
@SuppressWarnings("unused")
private Pool() {}
-
+
/**
* Getter/ Setter methods
*/
-
+
public Pool(String name,
String lbMethod) {
this.name = name;
this.lbMethod = lbMethod;
}
-
+
/**
* @return the name
*/
public String getName() {
return name;
}
-
+
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
-
+
/**
* @return the lbMethod
*/
public String getLbMethod() {
return lbMethod;
}
-
+
/**
* @param lbMethod the lbMethod to set
*/
public void setLbMethod(String lbMethod) {
this.lbMethod = lbMethod;
}
-
+
/**
* @return the status
*/
public String getStatus() {
return status;
}
-
+
/**
* @param status the status to set
*/
public void setStatus(String status) {
this.status = status;
}
-
+
/**
* @return the vip
*/
public ArrayList<VIP> getAllVip() {
return vips;
}
-
+
/**
* @param vip the vip to set
*/
public void setVips(ArrayList<VIP> vips) {
this.vips = vips;
}
-
+
/**
* @return the members
*/
public ArrayList<PoolMember> getAllMembers() {
return members;
}
-
+
/**
* @param members the members to set
*/
public void setMembers(ArrayList<PoolMember> members) {
this.members = members;
}
-
+
/**
* Add new VIP to the VIP list
* @param vip new VIP to add
public void addVIP(VIP vip){
this.vips.add(vip);
}
-
+
/**
* Remove VIP with given name from the VIP list of the pool
* @param name Name of the VIP
- * @return true If VIP was using this pool and removed
+ * @return true If VIP was using this pool and removed
* false IF VIP is not using this pool
*/
public boolean removeVIP(String name){
}
return false;
}
-
+
/**
* Check if the given pool member is part of this pool
* @param pm Search for this pool member
- * @return true If pool member is attached to this pool
+ * @return true If pool member is attached to this pool
* false else
*/
public boolean poolMemberExists(PoolMember pm){
return this.members.contains(pm);
}
-
+
/**
* Returns the pool member with the given name
* @param name Search for this pool member
- * @return PoolMember If pool member is attached to this pool
+ * @return PoolMember If pool member is attached to this pool
* null else
*/
public PoolMember getMember(String name){
-
+
for(PoolMember pm: this.members){
if(pm.getName().equals(name)){
return pm;
}
return null;
}
-
+
/**
* Add new pool member to the pool
* @param pm Add this new pool
public void addMember(PoolMember pm){
this.members.add(pm);
}
-
+
/**
* Remove pool member from the pool list
* @param name Remove this pool member
- * @return true If pool member was attached to this pool and successfully removed
- * false If pool member is not attached to this pool
+ * @return true If pool member was attached to this pool and successfully removed
+ * false If pool member is not attached to this pool
*/
public boolean removeMember(String name){
for(PoolMember pm: this.members){
}
return false;
}
-
+
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
-
+
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
}
return true;
}
-
+
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
* This class represents the host where load balancing service will
* redirect VIP traffic for load balancing. All these hosts have to
* register with a pool to be a part of traffic load balancing.
- * This entity is referred to as a 'PoolMember'.
- * Load balancer service differentiates each pool member based on its
+ * This entity is referred to as a 'PoolMember'.
+ * Load balancer service differentiates each pool member based on its
* two properties { ip address, attached pool }.
* A host (IP) can be attached to two different pools through creation of two
* different pool member objects.
- *
+ *
* NOTE: Each pool member should have a unique name.
*
*/
@XmlRootElement(name="poolmember")
@XmlAccessorType(XmlAccessType.NONE)
public class PoolMember {
-
+
/*
* Unique name of the pool member
*/
@XmlElement
private String name;
-
+
/*
* IP address of the pool member
*/
@XmlElement
private String ip;
-
+
/*
* Name of the pool this member is attached to.
*/
@XmlElement(name="poolname")
private String poolName;
-
+
/*
* Status (active/inactive)
*/
@XmlElement
private String status;
-
+
/**
* Private constructor used for JAXB mapping
*/
@SuppressWarnings("unused")
private PoolMember() {}
-
+
public PoolMember(String name, String memberIP, String poolName){
this.name = name;
this.ip = memberIP;
this.poolName = poolName;
}
-
+
/**
* @return the name
*/
public String getName() {
return name;
}
-
+
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
-
+
/**
* @return the ip
*/
public String getIp() {
return ip;
}
-
+
/**
* @param ip the ip to set
*/
public void setIp(String ip) {
this.ip = ip;
}
-
+
/**
* @return the poolName
*/
public String getPoolName() {
return poolName;
}
-
+
/**
* @param poolName the poolName to set
*/
public void setPoolName(String poolName) {
this.poolName = poolName;
}
-
+
/**
* @return the status
*/
public String getStatus() {
return status;
}
-
+
/**
* @param status the status to set
*/
public void setStatus(String status) {
this.status = status;
}
-
+
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
+ ((poolName == null) ? 0 : poolName.hashCode());
return result;
}
-
+
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
* 1. IP address of the VIP exposed by the application
* 2. Protocol of the network traffic (TCP/UDP)
* 3. Port to which incoming traffic is destined
- *
- * User is allowed to create mutliple VIPs with the same IP, but all such VIPs (with the same IP)
+ *
+ * User is allowed to create mutliple VIPs with the same IP, but all such VIPs (with the same IP)
* should differ at least in the protocol or port or both.
- *
+ *
* NOTE: Each VIP should have a unique name.
*/
@XmlRootElement(name="vip")
@XmlAccessorType(XmlAccessType.NONE)
public class VIP {
-
+
/*
* Unique name of the VIP
*/
@XmlElement
private String name;
-
+
/*
- * Virtual IP address of the VIP
+ * Virtual IP address of the VIP
*/
@XmlElement
private String ip;
-
+
/*
- * Network traffic protocol
+ * Network traffic protocol
*/
@XmlElement
private String protocol;
-
+
/*
* Port where network traffic is destined (destination port)
*/
@XmlElement
private short port;
-
+
/*
* Name of the pool attached to the VIP for load balancing its traffic
*/
@XmlElement(name="poolname")
private String poolName;
-
+
/*
* Status (Active/inactive)
*/
*/
@SuppressWarnings("unused")
private VIP() {}
-
+
public VIP(String name,
String ip,
String protocol,
this.port = port;
this.poolName = poolName;
}
-
+
public String getName() {
return name;
}
-
+
public void setName(String name) {
this.name = name;
}
-
+
public String getIp() {
return ip;
}
-
+
public void setIp(String ip) {
this.ip = ip;
}
-
+
public String getProtocol() {
return protocol;
}
-
+
public void setProtocol(String protocol) {
this.protocol = protocol;
}
-
+
public short getPort() {
return port;
}
-
+
public void setPort(short port) {
this.port = port;
}
-
+
public String getPoolName() {
return poolName;
}
-
+
public void setPoolName(String poolName) {
this.poolName = poolName;
}
-
+
/**
* @return the status
*/
public String getStatus() {
return status;
}
-
+
/**
* @param status the status to set
*/
public void setStatus(String status) {
this.status = status;
}
-
+
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
+ ((protocol == null) ? 0 : protocol.hashCode());
return result;
}
-
+
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
if (this == obj) {
return true;
-
+
}
if (obj == null) {
return false;
if (!(obj instanceof VIP)) {
return false;
}
-
+
VIP other = (VIP) obj;
if (ip == null) {
if (other.ip != null) {
}
return true;
}
-
+
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
import org.opendaylight.controller.samples.loadbalancer.IConfigManager;
/**
- * Main application activator class for registering the dependencies and
+ * Main application activator class for registering the dependencies and
* initialising the load balancer application.
*
*/
public class Activator extends ComponentActivatorAbstractBase {
-
+
/*
* Logger instance
*/
props.put("salListenerName", "loadbalancer");
c.setInterface(new String[] { IListenDataPacket.class.getName(),
- IConfigManager.class.getName()}, props);
+ IConfigManager.class.getName()}, props);
c.add(createContainerServiceDependency(containerName).setService(
IDataPacketService.class).setCallbacks(
"setDataPacketService", "unsetDataPacketService")
.setRequired(true));
-
+
c.add(createContainerServiceDependency(containerName).setService(
IRouting.class).setCallbacks("setRouting", "unsetRouting")
.setRequired(false));
import org.slf4j.LoggerFactory;
/**
- * This class is the main class that represents the load balancer service.
- * This is a sample load balancer application that balances traffic to backend servers
- * based on the source address and source port on each incoming packet. The service
+ * This class is the main class that represents the load balancer service.
+ * This is a sample load balancer application that balances traffic to backend servers
+ * based on the source address and source port on each incoming packet. The service
* reactively installs OpenFlow rules to direct all packets with a specific source address
- * and source port to one of the appropriate backend servers. The servers may be chosen
- * using a round robin policy or a random policy. This service can be configured via a
+ * and source port to one of the appropriate backend servers. The servers may be chosen
+ * using a round robin policy or a random policy. This service can be configured via a
* REST APIs which are similar to the OpenStack Quantum LBaaS (Load-balancer-as-a-Service)
* v1.0 API proposal (http://wiki.openstack.org/Quantum/LBaaS)
- *
+ *
* To use this service, a virtual IP (or VIP) should be exposed to the clients of this service
* and used as the destination address. A VIP is a entity that comprises of a virtual IP, port
* and protocol (TCP or UDP).
* Assumptions:
* 1. One or more VIPs may be mapped to the same server pool. All VIPs that share the same
* pool must also share the same load balancing policy (random or round robin).
- *
+ *
* 2. Only one server pool can be be assigned to a VIP.
- *
+ *
* 3. All flow rules are installed with an idle timeout of 5 seconds.
- *
+ *
* 4. Packets to a VIP must leave the OpenFlow cluster from the same switch from where
* it entered it.
- *
+ *
* 5. When you delete a VIP or a server pool or a server from a pool, the service does not
* delete the flow rules it has already installed. The flow rules should automatically
- * time out after the idle timeout of 5 seconds.
+ * time out after the idle timeout of 5 seconds.
*
*/
public class LoadBalancerService implements IListenDataPacket, IConfigManager{
-
+
/*
* Logger instance
*/
private static Logger lbsLogger = LoggerFactory.getLogger(LoadBalancerService.class);
-
+
/*
* Single instance of the configuration manager. Application passes this reference to all
* the new policies implemented for load balancing.
*/
private static ConfigManager configManager = new ConfigManager();
-
+
/*
* Round robing policy instance. Need to implement factory patterns to get
* policy instance.
*/
private static RoundRobinLBPolicy rrLBMethod= new RoundRobinLBPolicy(configManager);
-
+
/*
* Random policy instance.
*/
private static RandomLBPolicy ranLBMethod= new RandomLBPolicy(configManager);
-
+
/*
* Reference to the data packet service
*/
private IDataPacketService dataPacketService = null;
-
+
/*
* Reference to the host tracker service
*/
private IfIptoHost hostTracker;
-
+
/*
* Reference to the forwarding manager
*/
private IForwardingRulesManager ruleManager;
-
+
/*
* Reference to the routing service
*/
private IRouting routing;
-
+
/*
* Load balancer application installs all flows with priority 2.
*/
private String containerName = null;
/*
- * Set/unset methods for the service instance that load balancer
+ * Set/unset methods for the service instance that load balancer
* service requires
*/
public String getContainerName() {
return GlobalConstants.DEFAULT.toString();
return containerName;
}
-
+
void setDataPacketService(IDataPacketService s) {
this.dataPacketService = s;
}
this.dataPacketService = null;
}
}
-
+
public void setRouting(IRouting routing) {
this.routing = routing;
}
}
public void setHostTracker(IfIptoHost hostTracker) {
- lbsLogger.debug("Setting HostTracker");
+ lbsLogger.debug("Setting HostTracker");
this.hostTracker = hostTracker;
}
public void setForwardingRulesManager(
IForwardingRulesManager forwardingRulesManager) {
- lbsLogger.debug("Setting ForwardingRulesManager");
+ lbsLogger.debug("Setting ForwardingRulesManager");
this.ruleManager = forwardingRulesManager;
}
/**
* This method receives first packet of flows for which there is no
- * matching flow rule installed on the switch. IP addresses used for VIPs
+ * matching flow rule installed on the switch. IP addresses used for VIPs
* are not supposed to be used by any real/virtual host in the network.
* Hence, any forwarding/routing service will not install any flows rules matching
* these VIPs. This ensures that all the flows destined for VIPs will not find a match
* in the switch and will be forwarded to the load balancing service.
- * Service will decide where to route this traffic based on the load balancing
- * policy of the VIP's attached pool and will install appropriate flow rules
- * in a reactive manner.
+ * Service will decide where to route this traffic based on the load balancing
+ * policy of the VIP's attached pool and will install appropriate flow rules
+ * in a reactive manner.
*/
@Override
public PacketResult receiveDataPacket(RawPacket inPkt){
-
+
if (inPkt == null) {
return PacketResult.IGNORED;
}
-
+
Packet formattedPak = this.dataPacketService.decodeDataPacket(inPkt);
-
+
if (formattedPak instanceof Ethernet) {
byte[] vipMacAddr = ((Ethernet) formattedPak).getDestinationMACAddress();
Object ipPkt = formattedPak.getPayload();
-
+
if (ipPkt instanceof IPv4) {
-
+
lbsLogger.debug("Packet recieved from switch : {}",inPkt.getIncomingNodeConnector().getNode().toString());
IPv4 ipv4Pkt = (IPv4)ipPkt;
if(IPProtocols.getProtocolName(ipv4Pkt.getProtocol()).equals(IPProtocols.TCP.toString())
|| IPProtocols.getProtocolName(ipv4Pkt.getProtocol()).equals(IPProtocols.UDP.toString())){
-
+
lbsLogger.debug("Packet protocol : {}",IPProtocols.getProtocolName(ipv4Pkt.getProtocol()));
Client client = new LBUtil().getClientFromPacket(ipv4Pkt);
VIP vip = new LBUtil().getVIPFromPacket(ipv4Pkt);
-
+
if(configManager.vipExists(vip)){
VIP vipWithPoolName = configManager.getVIPWithPoolName(vip);
String poolMemberIp = null;
if(configManager.getPool(vipWithPoolName.getPoolName()).getLbMethod().equalsIgnoreCase(LBConst.ROUND_ROBIN_LB_METHOD)){
-
+
poolMemberIp = rrLBMethod.getPoolMemberForClient(client,vipWithPoolName);
}
-
+
if(configManager.getPool(vipWithPoolName.getPoolName()).getLbMethod().equalsIgnoreCase(LBConst.RANDOM_LB_METHOD)){
poolMemberIp = ranLBMethod.getPoolMemberForClient(client,vipWithPoolName);
}
-
+
try {
-
+
Node clientNode = inPkt.getIncomingNodeConnector().getNode();
HostNodeConnector hnConnector = this.hostTracker.hostFind(InetAddress.getByName(poolMemberIp));
-
+
Node destNode = hnConnector.getnodeconnectorNode();
-
+
lbsLogger.debug("Client is connected to switch : {}",clientNode.toString());
lbsLogger.debug("Destination pool machine is connected to switch : {}",destNode.toString());
-
+
//Get path between both the nodes
Path route = this.routing.getRoute(clientNode, destNode);
-
+
lbsLogger.info("Path between source (client) and destination switch nodes : {}",route.toString());
-
+
NodeConnector forwardPort = route.getEdges().get(0).getTailNodeConnector();
-
+
if(installLoadBalancerFlow(client,
vip,
clientNode,
}else{
lbsLogger.error("Not able to route traffic from client : {}",client );
}
-
+
if(installLoadBalancerFlow(client,
vip,
clientNode,
}
return PacketResult.IGNORED;
}
-
+
/*
* This method installs the flow rule for routing the traffic between two hosts.
* @param source Traffic is sent by this source
* @param destMachineMac MAC address of the pool member where traffic needs to be routed
* @param outport Use this port to send out traffic
* @param flowDirection FORWARD_DIRECTION_LB_FLOW or REVERSE_DIRECTION_LB_FLOW
- * @return true If flow installation was successful
- * false else
+ * @return true If flow installation was successful
+ * false else
* @throws UnknownHostException
*/
private boolean installLoadBalancerFlow(Client source,
VIP dest,
Node sourceSwitch,
String destMachineIp,
- byte[] destMachineMac,
+ byte[] destMachineMac,
NodeConnector outport,
int flowDirection) throws UnknownHostException{
-
+
Match match = new Match();
List<Action> actions = new ArrayList<Action>();
-
+
if(flowDirection == LBConst.FORWARD_DIRECTION_LB_FLOW){
match.setField(MatchType.DL_TYPE, EtherTypes.IPv4.shortValue());
match.setField(MatchType.NW_SRC, InetAddress.getByName(source.getIp()));
match.setField(MatchType.NW_PROTO, IPProtocols.getProtocolNumberByte(dest.getProtocol()));
match.setField(MatchType.TP_SRC, source.getPort());
match.setField(MatchType.TP_DST, dest.getPort());
-
+
actions.add(new SetNwDst(InetAddress.getByName(destMachineIp)));
actions.add(new SetDlDst(destMachineMac));
}
-
+
if(flowDirection == LBConst.REVERSE_DIRECTION_LB_FLOW){
match.setField(MatchType.DL_TYPE, EtherTypes.IPv4.shortValue());
match.setField(MatchType.NW_SRC, InetAddress.getByName(destMachineIp));
match.setField(MatchType.NW_PROTO, IPProtocols.getProtocolNumberByte(source.getProtocol()));
match.setField(MatchType.TP_SRC, dest.getPort());
match.setField(MatchType.TP_DST,source.getPort());
-
+
actions.add(new SetNwSrc(InetAddress.getByName(dest.getIp())));
actions.add(new SetDlSrc(destMachineMac));
}
-
+
actions.add(new Output(outport));
-
+
// Make sure the priority for IP switch entries is
// set to a level just above default drop entries
-
+
Flow flow = new Flow(match, actions);
flow.setIdleTimeout((short) 5);
flow.setHardTimeout((short) 0);
flow.setPriority(LB_IPSWITCH_PRIORITY);
-
+
String policyName = source.getIp()+":"+source.getProtocol()+":"+source.getPort();
String flowName =null;
-
+
if(flowDirection == LBConst.FORWARD_DIRECTION_LB_FLOW){
flowName = "["+policyName+":"+source.getIp() + ":"+dest.getIp()+"]";
}
-
+
if(flowDirection == LBConst.REVERSE_DIRECTION_LB_FLOW){
-
+
flowName = "["+policyName+":"+dest.getIp() + ":"+source.getIp()+"]";
}
-
+
FlowEntry fEntry = new FlowEntry(policyName, flowName, flow, sourceSwitch);
-
+
lbsLogger.info("Install flow entry {} on node {}",fEntry.toString(),sourceSwitch.toString());
-
+
if(!this.ruleManager.checkFlowEntryConflict(fEntry)){
if(this.ruleManager.installFlowEntry(fEntry).isSuccess()){
return true;
}
return false;
}
-
+
/**
* Function called by the dependency manager when all the required
* dependencies are satisfied
Dictionary<?, ?> props = c.getServiceProperties();
if (props != null) {
this.containerName = (String) props.get("containerName");
-
+
lbsLogger.info("Running container name:" + this.containerName);
}else {
-
+
// In the Global instance case the containerName is empty
this.containerName = "";
}
lbsLogger.info(configManager.toString());
}
-
+
/**
* Function called by the dependency manager when at least one
* dependency become unsatisfied or when the component is shutting
/*
* All the methods below are just proxy methods to direct the REST API requests to configuration
- * manager. We need this redirection as currently, opendaylight supports only one
- * implementation of the service.
+ * manager. We need this redirection as currently, opendaylight supports only one
+ * implementation of the service.
*/
@Override
public Set<VIP> getAllVIPs() {
return configManager.getAllVIPs();
}
-
+
@Override
public boolean vipExists(String name, String ip, String protocol,
short protocolPort, String poolName) {
return configManager.vipExists(name, ip, protocol, protocolPort, poolName);
}
-
+
@Override
public boolean vipExists(VIP vip) {
return configManager.vipExists(vip);
}
-
+
@Override
public VIP createVIP(String name, String ip, String protocol,
short protocolPort, String poolName) {
return configManager.createVIP(name, ip, protocol, protocolPort, poolName);
}
-
+
@Override
public VIP updateVIP(String name, String poolName) {
return configManager.updateVIP(name, poolName);
}
-
+
@Override
public VIP deleteVIP(String name) {
return configManager.deleteVIP(name);
}
-
+
@Override
public boolean memberExists(String name, String memberIP, String poolName) {
return configManager.memberExists(name, memberIP, poolName);
}
-
+
@Override
public Set<PoolMember> getAllPoolMembers(String poolName) {
-
+
return configManager.getAllPoolMembers(poolName);
}
-
+
@Override
- public PoolMember addPoolMember(String name,
+ public PoolMember addPoolMember(String name,
String memberIP,
String poolName) {
return configManager.addPoolMember(name, memberIP, poolName);
}
-
+
@Override
public PoolMember removePoolMember(String name, String poolName) {
-
+
return configManager.removePoolMember(name, poolName);
}
-
+
@Override
public Set<Pool> getAllPools() {
-
+
return configManager.getAllPools();
}
-
+
@Override
public Pool getPool(String poolName) {
return configManager.getPool(poolName);
}
-
+
@Override
public boolean poolExists(String name, String lbMethod) {
return configManager.poolExists(name, lbMethod);
}
-
+
@Override
public Pool createPool(String name, String lbMethod) {
return configManager.createPool(name, lbMethod);
}
-
+
@Override
public Pool deletePool(String poolName) {
return configManager.deletePool(poolName);
}
-
+
@Override
public boolean vipExists(String name) {
return configManager.vipExists(name);
}
-
+
@Override
public boolean memberExists(String name, String poolName) {
return configManager.memberExists(name, poolName);
}
-
+
@Override
public boolean poolExists(String name) {
return configManager.poolExists(name);
}
-
+
@Override
public String getVIPAttachedPool(String name) {
return configManager.getVIPAttachedPool(name);
* All new load balancer policies must implement this interface.
*/
public interface ILoadBalancingPolicy {
-
+
/**
* Returns IP address of the next pool member from the pool
* to which the load balancer service can direct incoming packets.
* @param source source on the packet
* @param dest virtual IP (VIP) that is used as destination on the packet
- * @return IP address of the next pool member which will serve
+ * @return IP address of the next pool member which will serve
* all incoming traffic destined for the given VIP and with the given source
* information
*/
public String getPoolMemberForClient(Client source, VIP dest);
-
+
}
\ No newline at end of file
*
*/
public class RandomLBPolicy implements ILoadBalancingPolicy {
-
+
/*
* Instance logger
*/
private static final Logger rLogger = LoggerFactory.getLogger(RandomLBPolicy.class);
-
+
/*
- * Reference to the configuration manager. This reference is passed from load balancer
+ * Reference to the configuration manager. This reference is passed from load balancer
* class.
*/
private ConfigManager cmgr;
-
+
/*
* Mapping between the client and the pool member that serves all traffic for that client.
*/
private HashMap<Client, PoolMember> clientMemberMap;
-
+
/*
* Random generator
*/
Random randomGenerator = null;
-
+
@SuppressWarnings("unused")
private RandomLBPolicy(){}
-
+
public RandomLBPolicy(ConfigManager cmgr){
this.cmgr = cmgr;
this.clientMemberMap = new HashMap<Client, PoolMember>();
}
@Override
public String getPoolMemberForClient(Client source, VIP dest){
-
+
rLogger.info("Received traffic from client : {} for VIP : {} ",source, dest);
-
+
syncWithLoadBalancerData();
-
+
PoolMember pm= null;
-
+
if(this.clientMemberMap.containsKey(source)){
pm= this.clientMemberMap.get(source);
rLogger.info("Client {} had sent traffic before,new traffic will be routed to the same pool member {}",source,pm);
}
return pm.getIp();
}
-
+
/*
* This method does the clean up. Whenever a new client packet arrives with a given VIP,
* this method checks the current configuration to see if any pool members have been deleted and
*/
private void syncWithLoadBalancerData(){
rLogger.debug("[Client - PoolMember] table before cleanup : {}",this.clientMemberMap.toString());
-
+
ArrayList<Client> removeClient = new ArrayList<Client>();
-
+
if(this.clientMemberMap.size() != 0){
for(Client client : this.clientMemberMap.keySet()){
-
+
if(!this.cmgr.memberExists(this.clientMemberMap.get(client).getName(),
this.clientMemberMap.get(client).getPoolName())){
removeClient.add(client);
}
}
}
-
+
for(Client client : removeClient){
this.clientMemberMap.remove(client);
-
+
rLogger.debug("Removed client : {} ",client);
}
rLogger.debug("[Client - PoolMember] table after cleanup : {}",this.clientMemberMap.toString());
}
-
+
}
*
*/
public class RoundRobinLBPolicy implements ILoadBalancingPolicy{
-
+
/*
* Logger instance
*/
private static final Logger rrLogger = LoggerFactory.getLogger(RoundRobinLBPolicy.class);
-
+
/*
- * Reference to the configuration manager. This reference is passed from load balancer
+ * Reference to the configuration manager. This reference is passed from load balancer
* class.
*/
private ConfigManager cmgr;
-
+
/*
* Mapping between the client and the pool member that serves all traffic for that client.
*/
private HashMap<Client, PoolMember> clientMemberMap;
-
+
/*
* Maintains the next pool member counter for the VIPs.
* More than one VIP can be attached to one pool, so each VIP
* the same pool.
*/
private HashMap<VIP,Integer> nextItemFromPool;
-
+
@SuppressWarnings("unused")
private RoundRobinLBPolicy(){}
-
+
public RoundRobinLBPolicy(ConfigManager cmgr){
this.cmgr = cmgr;
this.clientMemberMap = new HashMap<Client, PoolMember>();
this.nextItemFromPool = new HashMap<VIP, Integer>();
}
-
+
@Override
public String getPoolMemberForClient(Client source, VIP dest){
-
+
rrLogger.info("Received traffic from client : {} for VIP : {} ",source, dest);
-
+
syncWithLoadBalancerData();
-
+
PoolMember pm= null;
-
+
if(this.clientMemberMap.containsKey(source)){
-
+
pm= this.clientMemberMap.get(source);
rrLogger.info("Client {} had sent traffic before,new traffic will be routed to the same pool member {}",source,pm);
}else{
-
+
Pool pool = null;
if(nextItemFromPool.containsKey(dest)){
-
+
int memberNum = nextItemFromPool.get(dest).intValue();
rrLogger.debug("Packet is from new client for VIP {}",dest);
pool = this.cmgr.getPool(dest.getPoolName());
this.clientMemberMap.put(source, pm );
rrLogger.info("New client's packet will be directed to pool member {}",pm);
memberNum++;
-
+
if(memberNum > pool.getAllMembers().size()-1){
memberNum = 0;
}
rrLogger.debug("Next pool member for new client of VIP is set to {}",pool.getAllMembers().get(memberNum));
-
+
this.nextItemFromPool.put(dest, new Integer(memberNum));
}else{
rrLogger.debug("Network traffic for VIP : {} has appeared first time from client {}",dest,source);
pool = this.cmgr.getPool(dest.getPoolName());
pm = pool.getAllMembers().get(0);
this.clientMemberMap.put(source, pm);
-
+
rrLogger.info("Network traffic from client {} will be directed to pool member {}",pm);
this.nextItemFromPool.put(dest, new Integer(1));
rrLogger.debug("Next pool member for new client of VIP is set to {}",pool.getAllMembers().get(1));
}
return pm.getIp();
}
-
+
/*
* This method does the clean up. Whenever a new client packet arrives with a given VIP,
* this method checks the current configuration to see if any pool members have been deleted and
private void syncWithLoadBalancerData(){
rrLogger.debug("[Client - PoolMember] table before cleanup : {}",this.clientMemberMap.toString());
ArrayList<Client> removeClient = new ArrayList<Client>();
-
+
if(this.clientMemberMap.size() != 0){
for(Client client : this.clientMemberMap.keySet()){
if(!this.cmgr.memberExists(this.clientMemberMap.get(client).getName(),
this.clientMemberMap.get(client).getPoolName())){
-
+
removeClient.add(client);
}
}
}
-
+
for(Client client : removeClient){
this.clientMemberMap.remove(client);
-
+
rrLogger.debug("Removed client : {} ",client);
}
rrLogger.debug("[Client - PoolMember] table after cleanup : {}",this.clientMemberMap.toString());
-
+
rrLogger.debug("[VIP- NextMember] table before cleanup : {}",this.nextItemFromPool.toString());
-
+
ArrayList<VIP> resetVIPPoolMemberCount= new ArrayList<VIP>();
-
+
if(this.nextItemFromPool.size() != 0){
-
+
for(VIP vip:this.nextItemFromPool.keySet()){
if(this.nextItemFromPool.get(vip).intValue() > this.cmgr.getPool(vip.getPoolName()).getAllMembers().size()-1){
-
+
resetVIPPoolMemberCount.add(vip);
}
}
}
-
+
for(VIP vip:resetVIPPoolMemberCount){
rrLogger.debug("VIP next pool member counter reset to 0");
this.nextItemFromPool.put(vip, new Integer(0));
}
-
+
rrLogger.debug("[VIP- NextMember] table after cleanup : {}",this.nextItemFromPool.toString());
}
}
import junit.framework.TestCase;\r
\r
/**\r
- * \r
+ *\r
* Class to unit test the load balancing policies.\r
*\r
*/\r
ConfigManager cm = null;\r
cm = new ConfigManager();\r
Assert.assertFalse(cm== null);\r
- \r
+\r
Pool pool = cm.createPool("TestPool","roundrobin");\r
VIP vip = cm.createVIP("TestVIP","10.0.0.9","TCP",(short)5550,"TestPool");\r
PoolMember host1 = new PoolMember("host1","10.0.0.1","TestPool");\r
PoolMember host5 = new PoolMember("host5","10.0.0.5","TestPool");\r
PoolMember host6 = new PoolMember("host6","10.0.0.6","TestPool");\r
PoolMember host7 = new PoolMember("host7","10.0.0.7","TestPool");\r
- \r
+\r
pool.addMember(host1);\r
pool.addMember(host2);\r
pool.addMember(host3);\r
pool.addMember(host6);\r
pool.addMember(host7);\r
pool.addVIP(vip);\r
- \r
+\r
Assert.assertTrue(cm.getAllPoolMembers("TestPool").size() == pool.getAllMembers().size());\r
- \r
+\r
RoundRobinLBPolicy rrp = new RoundRobinLBPolicy(cm);\r
- \r
+\r
Client c1 = new Client("10.0.0.1","TCP",(short)5000);\r
Assert.assertTrue(rrp.getPoolMemberForClient(c1, vip).equals(host1.getIp()));\r
- \r
+\r
c1 = new Client("10.0.0.1","TCP",(short)5001);\r
Assert.assertTrue(rrp.getPoolMemberForClient(c1, vip).equals(host2.getIp()));\r
- \r
+\r
c1 = new Client("10.0.0.1","TCP",(short)5002);\r
Assert.assertTrue(rrp.getPoolMemberForClient(c1, vip).equals(host3.getIp()));\r
- \r
+\r
c1 = new Client("10.0.0.1","TCP",(short)5003);\r
Assert.assertTrue(rrp.getPoolMemberForClient(c1, vip).equals(host4.getIp()));\r
}\r
/**
* This class exposes North bound REST APIs for the Load Balancer Service.
* Following APIs are exposed by the Load Balancer Service:
- *
+ *
* Data retrieval REST APIs::
- * 1. Get details of all existing pools
- * Type : GET
- * URI : /one/nb/v2/lb/{container-name}/
- * NOTE: Current implementation of the opendaylight usage 'default' as a container-name
- * e.g : http://localhost:8080/one/nb/v2/lb/default will give you list of all the pools
- *
- * 2. Get details of all the existing VIPs
- * Type : GET
- * URI: /one/nb/v2/lb/{container-name}/vips
- *
+ * 1. Get details of all existing pools
+ * Type : GET
+ * URI : /one/nb/v2/lb/{container-name}/
+ * NOTE: Current implementation of the opendaylight usage 'default' as a container-name
+ * e.g : http://localhost:8080/one/nb/v2/lb/default will give you list of all the pools
+ *
+ * 2. Get details of all the existing VIPs
+ * Type : GET
+ * URI: /one/nb/v2/lb/{container-name}/vips
+ *
* Pool related REST APIs::
- * 1. Create Pool :
- * Type : POST
- * URI : /one/nb/v2/lb/{container-name}/create/pool
- * Request body :
+ * 1. Create Pool :
+ * Type : POST
+ * URI : /one/nb/v2/lb/{container-name}/create/pool
+ * Request body :
* {
* "name":"",
* "lbmethod":""
* }
- * Currently, two load balancing policies are allowed {"roundrobin" and "random" }
- *
- * 2. Delete Pool :
- * Type : DELETE
- * URI : /one/nb/v2/lb/{container-name}/delete/pool/{pool-name}
- *
+ * Currently, two load balancing policies are allowed {"roundrobin" and "random" }
+ *
+ * 2. Delete Pool :
+ * Type : DELETE
+ * URI : /one/nb/v2/lb/{container-name}/delete/pool/{pool-name}
+ *
* VIP related REST APIs::
- * 1. Create VIP:
- * Type : POST
- * URI : /one/nb/v2/lb/{container-name}/create/vip
- * Request body :
+ * 1. Create VIP:
+ * Type : POST
+ * URI : /one/nb/v2/lb/{container-name}/create/vip
+ * Request body :
* {
* "name":"",
* "ip":"ip in (xxx.xxx.xxx.xxx) format",
* "port":"any valid port number",
* "poolname":"" (optional)
* }
- * The pool name is optional and can be set up at a later stage (using the REST API given below).
- *
- * 2. Update VIP: Update pool name of the VIP
- * Type : PUT
- * URI : /one/nb/v2/lb/{container-name}/update/vip
- * Request body :
+ * The pool name is optional and can be set up at a later stage (using the REST API given below).
+ *
+ * 2. Update VIP: Update pool name of the VIP
+ * Type : PUT
+ * URI : /one/nb/v2/lb/{container-name}/update/vip
+ * Request body :
* {
* "name":"",
* "poolname":""
* and not of the VIP name itself.
* The specified pool name must already exist. If the specified VIP is already attached to a pool, the update
* will fail.
- *
- * 3. Delete VIP :
- * Type : DELETE
- * URI : /one/nb/v2/lb/{container-name}/delete/vip/{vip-name}
- *
+ *
+ * 3. Delete VIP :
+ * Type : DELETE
+ * URI : /one/nb/v2/lb/{container-name}/delete/vip/{vip-name}
+ *
* Pool member related REST APIs::
- * 1. Create pool member:
- * Type : POST
- * URI : /one/nb/v2/lb/default/create/poolmember
- * Request body :
+ * 1. Create pool member:
+ * Type : POST
+ * URI : /one/nb/v2/lb/default/create/poolmember
+ * Request body :
* {
* "name":"",
* "ip":"ip in (xxx.xxx.xxx.xxx) format",
* "poolname":"existing pool name"
* }
- *
- * 2. Delete pool member:
- * Type : DELETE
- * URI : /one/nb/v2/lb/{container-name}/delete/poolmember/{pool-member-name}/{pool-name}
- *
- * NOTE: Property "name" of each individual entity must be unique.
- * All the above REST APIs throw appropriate response codes in case of error/success.
- * Please consult the respective methods to get details of various response codes.
+ *
+ * 2. Delete pool member:
+ * Type : DELETE
+ * URI : /one/nb/v2/lb/{container-name}/delete/poolmember/{pool-member-name}/{pool-name}
+ *
+ * NOTE: Property "name" of each individual entity must be unique.
+ * All the above REST APIs throw appropriate response codes in case of error/success.
+ * Please consult the respective methods to get details of various response codes.
*/
@Path("/")
public class LoadBalancerNorthbound {
-
+
/*
* Method returns the Load balancer service instance running within
* 'default' container.
}
IConfigManager configManager = (IConfigManager) ServiceHelper.getInstance(
- IConfigManager.class, containerName, this);
+ IConfigManager.class, containerName, this);
if (configManager == null) {
throw new ServiceUnavailableException("Load Balancer"
@ResponseCode(code = 503, condition = "Load balancer service is unavailable") })
public Pools getAllPools(
@PathParam("containerName") String containerName) {
-
+
IConfigManager configManager = getConfigManagerService(containerName);
if (configManager == null) {
throw new ServiceUnavailableException("Load Balancer "
+ RestMessages.SERVICEUNAVAILABLE.toString());
}
-
+
return new Pools(configManager.getAllPools());
}
@ResponseCode(code = 503, condition = "Load balancer service is unavailable") })
public VIPs getAllVIPs(
@PathParam("containerName") String containerName) {
-
+
IConfigManager configManager = getConfigManagerService(containerName);
if (configManager == null) {
throw new ServiceUnavailableException("Load Balancer "
@ResponseCode(code = 415, condition = "Invalid input data")})
public Response addVIP(@PathParam("containerName") String containerName,
@TypeHint(VIP.class) JAXBElement<VIP> inVIP){
-
+
VIP vipInput = inVIP.getValue();
String name = vipInput.getName();
String ip = vipInput.getIp();
protocolPort < 0 ){
throw new UnsupportedMediaTypeException(RestMessages.INVALIDDATA.toString());
}
-
+
IConfigManager configManager = getConfigManagerService(containerName);
-
+
if (configManager == null) {
throw new ServiceUnavailableException("Load Balancer "
+ RestMessages.SERVICEUNAVAILABLE.toString());
}
-
+
if(!configManager.vipExists(name, ip, protocol, protocolPort, poolName)){
-
+
VIP vip = configManager.createVIP(name, ip, protocol, protocolPort, poolName);
if ( vip != null){
return Response.status(Response.Status.CREATED).build();
@ResponseCode(code = 415, condition = "Invalid input name")})
public Response updateVIP(@PathParam("containerName") String containerName,
@TypeHint(VIP.class) JAXBElement<VIP> inVIP) {
-
+
VIP vipInput = inVIP.getValue();
String name = vipInput.getName();
String poolName = vipInput.getPoolName();
poolName.isEmpty()){
throw new UnsupportedMediaTypeException(RestMessages.INVALIDDATA.toString());
}
-
+
IConfigManager configManager = getConfigManagerService(containerName);
if (configManager == null) {
throw new ServiceUnavailableException("Load Balancer "
+ RestMessages.SERVICEUNAVAILABLE.toString());
}
-
+
if(!configManager.poolExists(poolName))
throw new ResourceNotFoundException(NBConst.RES_POOL_NOT_FOUND);
-
+
if(configManager.getVIPAttachedPool(name)!=null)
throw new MethodNotAllowedException(NBConst.RES_VIP_POOL_EXIST);
-
+
if(configManager.updateVIP(name, poolName)!= null)
return Response.status(Response.Status.ACCEPTED).build();
-
+
throw new InternalServerErrorException(NBConst.RES_VIP_UPDATE_FAILED);
}
-
+
@Path("/{containerName}/delete/vip/{vipName}")
@DELETE
@Consumes( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response deleteVIP(
@PathParam(value = "containerName") String containerName,
@PathParam(value = "vipName") String vipName) {
-
+
if(vipName.isEmpty())
throw new UnsupportedMediaTypeException(RestMessages.INVALIDDATA.toString());
-
+
IConfigManager configManager = getConfigManagerService(containerName);
if (configManager == null) {
throw new ServiceUnavailableException("Load Balancer"
+ RestMessages.SERVICEUNAVAILABLE.toString());
}
-
+
if(!configManager.vipExists(vipName))
throw new ResourceNotFoundException(NBConst.RES_VIP_NOT_FOUND);
-
+
for(VIP vip : configManager.getAllVIPs()){
if(vip.getName().equals(vipName)){
configManager.deleteVIP(vipName);
@ResponseCode(code = 415, condition = "Invalid input data")})
public Response addPool(@PathParam("containerName") String containerName,
@TypeHint(Pool.class) JAXBElement<Pool> inPool) {
-
+
Pool poolInput = inPool.getValue();
String name = poolInput.getName();
String lbMethod =poolInput.getLbMethod();
lbMethod.isEmpty()){
throw new UnsupportedMediaTypeException(RestMessages.INVALIDDATA.toString());
}
-
+
IConfigManager configManager = getConfigManagerService(containerName);
if (configManager == null) {
throw new ServiceUnavailableException("Load Balancer "
+ RestMessages.SERVICEUNAVAILABLE.toString());
}
-
+
if(!configManager.poolExists(name)){
-
+
Pool pool = configManager.createPool(name, lbMethod);
if ( pool != null){
return Response.status(Response.Status.CREATED).build();
public Response deletePool(
@PathParam(value = "containerName") String containerName,
@PathParam(value = "poolName") String poolName) {
-
+
if(poolName.isEmpty())
throw new UnsupportedMediaTypeException(RestMessages.INVALIDDATA.toString());
-
+
IConfigManager configManager = getConfigManagerService(containerName);
if (configManager == null) {
throw new ServiceUnavailableException("Load Balancer"
+ RestMessages.SERVICEUNAVAILABLE.toString());
}
-
+
if(!configManager.poolExists(poolName))
throw new ResourceNotFoundException(NBConst.RES_POOL_NOT_FOUND);
-
+
for(Pool pool:configManager.getAllPools()){
if(pool.getName().equals(poolName)){
configManager.deletePool(poolName);
@ResponseCode(code = 415, condition = "Invalid input data")})
public Response addPoolMember(@PathParam("containerName") String containerName,
@TypeHint(PoolMember.class) JAXBElement<PoolMember> inPoolMember){
-
+
PoolMember pmInput = inPoolMember.getValue();
- String name = pmInput.getName();
- String memberIP = pmInput.getIp();
- String poolName = pmInput.getPoolName();
-
- if(name.isEmpty() ||
- memberIP.isEmpty()||
- poolName.isEmpty()){
- throw new UnsupportedMediaTypeException(RestMessages.INVALIDDATA.toString());
- }
-
- IConfigManager configManager = getConfigManagerService(containerName);
- if (configManager == null) {
- throw new ServiceUnavailableException("Load Balancer "
- + RestMessages.SERVICEUNAVAILABLE.toString());
- }
-
- if(!configManager.poolExists(poolName))
- throw new ResourceNotFoundException(NBConst.RES_POOL_NOT_FOUND);
-
- if(!configManager.memberExists(name, memberIP, poolName)){
-
- PoolMember poolMember = configManager.addPoolMember(name, memberIP, poolName);
- if ( poolMember != null){
- return Response.status(Response.Status.CREATED).build();
- }
- }else{
- throw new ResourceConflictException(NBConst.RES_POOLMEMBER_ALREADY_EXIST);
- }
- throw new InternalServerErrorException(NBConst.RES_POOLMEMBER_CREATION_FAILED);
+ String name = pmInput.getName();
+ String memberIP = pmInput.getIp();
+ String poolName = pmInput.getPoolName();
+
+ if(name.isEmpty() ||
+ memberIP.isEmpty()||
+ poolName.isEmpty()){
+ throw new UnsupportedMediaTypeException(RestMessages.INVALIDDATA.toString());
+ }
+
+ IConfigManager configManager = getConfigManagerService(containerName);
+ if (configManager == null) {
+ throw new ServiceUnavailableException("Load Balancer "
+ + RestMessages.SERVICEUNAVAILABLE.toString());
+ }
+
+ if(!configManager.poolExists(poolName))
+ throw new ResourceNotFoundException(NBConst.RES_POOL_NOT_FOUND);
+
+ if(!configManager.memberExists(name, memberIP, poolName)){
+
+ PoolMember poolMember = configManager.addPoolMember(name, memberIP, poolName);
+ if ( poolMember != null){
+ return Response.status(Response.Status.CREATED).build();
+ }
+ }else{
+ throw new ResourceConflictException(NBConst.RES_POOLMEMBER_ALREADY_EXIST);
+ }
+ throw new InternalServerErrorException(NBConst.RES_POOLMEMBER_CREATION_FAILED);
}
@Path("/{containerName}/delete/poolmember/{poolMemberName}/{poolName}")
@PathParam(value = "containerName") String containerName,
@PathParam(value = "poolMemberName") String poolMemberName,
@PathParam(value = "poolName") String poolName) {
-
+
if(poolMemberName.isEmpty()||
poolName.isEmpty())
throw new UnsupportedMediaTypeException(RestMessages.INVALIDDATA.toString());
-
+
IConfigManager configManager = getConfigManagerService(containerName);
-
+
if (configManager == null) {
throw new ServiceUnavailableException("Load Balancer"
+ RestMessages.SERVICEUNAVAILABLE.toString());
}
-
+
if(!configManager.poolExists(poolName))
throw new ResourceNotFoundException(NBConst.RES_POOL_NOT_FOUND);
-
+
if(configManager.memberExists(poolMemberName, poolName)){
-
+
configManager.removePoolMember(poolMemberName, poolName);
-
+
return Response.ok().build();
}
throw new ResourceNotFoundException(NBConst.RES_POOLMEMBER_NOT_FOUND);
*
*/
public class NBConst {
-
+
public static final String RES_VIP_ALREADY_EXIST= " VIP already exists";
-
+
public static final String RES_VIP_NOT_FOUND= " VIP not found";
-
+
public static final String RES_VIP_CREATION_FAILED = " Creation of VIP failed";
-
+
public static final String RES_VIP_DELETION_FAILED = " Deletion of VIP failed";
-
+
public static final String RES_VIP_UPDATE_FAILED = " Update of VIP failed";
-
+
public static final String RES_POOL_ALREADY_EXIST= " Pool already exists";
-
+
public static final String RES_POOL_NOT_FOUND= " Pool not found";
-
+
public static final String RES_POOL_CREATION_FAILED = " Creation of pool failed";
-
+
public static final String RES_POOL_DELETION_FAILED = " Deletion of pool failed";
-
+
public static final String RES_POOLMEMBER_ALREADY_EXIST= " Pool member already exists";
-
+
public static final String RES_POOLMEMBER_NOT_FOUND= " Pool member not found";
-
+
public static final String RES_POOLMEMBER_CREATION_FAILED = " Creation of pool member failed";
-
+
public static final String RES_POOLMEMBER_DELETION_FAILED = " Deletion of pool member failed";
-
+
public static final String RES_VIP_POOL_EXIST = "Pool already attached to a VIP";
}
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
/**
- * JAX-RS resource for handling details of all the available pools
+ * JAX-RS resource for handling details of all the available pools
* in response to respective REST API requests.
*/
public class Pools {
-
+
@XmlElement (name="pool")
Set<Pool> loadBalancerPools;
-
+
public Pools() {
}
-
+
public Pools (Set<Pool> loadBalancerPools) {
this.loadBalancerPools = loadBalancerPools;
}
-
+
/**
* @return the loadBalancerPools
*/
public Set<Pool> getLoadBalancerPools() {
return loadBalancerPools;
}
-
+
/**
* @param loadBalancerPools the loadBalancerPools to set
*/
@XmlAccessorType(XmlAccessType.NONE)
public class VIPs {
-
+
@XmlElement (name="vip")
Set<VIP> loadBalancerVIPs;
-
+
public VIPs() {}
-
-
+
+
public VIPs (Set<VIP> loadBalancerVIPs) {
this.loadBalancerVIPs = loadBalancerVIPs;
}
-
+
/**
* @return the loadBalancerVIPs
*/
public Set<VIP> getLoadBalancerVIPs() {
return loadBalancerVIPs;
}
-
+
/**
* @param loadBalancerVIPs the loadBalancerVIPs to set
*/
-
+
public void setLoadBalancerVIPs(Set<VIP> loadBalancerVIPs) {
this.loadBalancerVIPs = loadBalancerVIPs;
}
}
@SuppressWarnings("deprecation")
- private void allocateCaches() {
+ private void allocateCaches() {
if (this.clusterContainerService == null) {
log.info("un-initialized clusterContainerService, can't create cache");
return;
}
@SuppressWarnings("deprecation")
- private void destroyCaches() {
+ private void destroyCaches() {
if (this.clusterContainerService == null) {
log.info("un-initialized clusterContainerService, can't destroy cache");
return;
}
} else {
- log.debug("Adding policyMatch(DIP = {}) Action(outPort= {}) " +
+ log.debug("Adding policyMatch(DIP = {}) Action(outPort= {}) " +
"to node {}", new Object[] {
host.getNetworkAddress().getHostAddress(), outPort,
currNode});
updatePerHostRuleInSW(host, rootNode, rootNode, null, new HostNodePair(
host, rootNode), ports);
- // log.debug("Getting out at the end!");
+ // log.debug("Getting out at the end!");
return switchesToProgram;
}
// rest of the world
// switchesToProgram.add(rootNode);
//updatePerHostRuleInSW(host, rootNode,
- // rootNode, null,
- // new HostNodePair(host, rootNode),ports);
+ // rootNode, null,
+ // new HostNodePair(host, rootNode),ports);
- // log.debug("Getting out at the end!");
+ // log.debug("Getting out at the end!");
return switchesToProgram;
}
Status poStatus = this.frm.installFlowEntry(po);
if (!poStatus.isSuccess()) {
log.error("Failed to install policy: "
- + po.getGroupName() + " ("
+ + po.getGroupName() + " ("
+ poStatus.getDescription() + ")");
retCode = RulesProgrammingReturnCode.FAILED_FEW_SWITCHES;
swId, host);
/* // Now dump every single rule */
/* for (HostNodePair dumpkey : this.rulesDB.keySet()) { */
- /* po = this.rulesDB.get(dumpkey); */
- /* log.debug("Dumping entry H{" + dumpkey.getHost() + "} S{" + dumpkey.getSwitchId() + "} = {" + (po == null ? "null policy" : po)); */
+ /* po = this.rulesDB.get(dumpkey); */
+ /* log.debug("Dumping entry H{" + dumpkey.getHost() + "} S{" + dumpkey.getSwitchId() + "} = {" + (po == null ? "null policy" : po)); */
/* } */
}
}
* If the context is the default container, the returned statistics are for all the flows installed on the node,
* regardless of the container they belong to
*
- * @param node the network node
+ * @param node the network node
* @return the list of flows installed on the network node
*/
List<FlowOnNode> getFlows(Node node);
* Returns the statistics for the flows specified in the list
*
* @param flows
- * @return the list of flows installed on the network node
+ * @return the list of flows installed on the network node
*/
Map<Node, List<FlowOnNode>> getFlowStatisticsForFlowList(
List<FlowEntry> flows);
/**
* This method is called when some properties of a node are added/deleted/changed.
*
- * @param node {@link org.opendaylight.controller.sal.core.Node} being updated
- * @param type {@link org.opendaylight.controller.sal.core.UpdateType}
- * @param propMap map of {@link org.opendaylight.controller.sal.core.Property} such as
- * {@link org.opendaylight.controller.sal.core.Description} and/or
- * {@link org.opendaylight.controller.sal.core.Tier} etc.
+ * @param node {@link org.opendaylight.controller.sal.core.Node} being updated
+ * @param type {@link org.opendaylight.controller.sal.core.UpdateType}
+ * @param propMap map of {@link org.opendaylight.controller.sal.core.Property} such as
+ * {@link org.opendaylight.controller.sal.core.Description} and/or
+ * {@link org.opendaylight.controller.sal.core.Tier} etc.
*/
public void notifyNode(Node node, UpdateType type,
Map<String, Property> propMap);
/**
* This method is called when some properties of a node connector are added/deleted/changed.
*
- * @param nodeConnector {@link org.opendaylight.controller.sal.core.NodeConnector} being updated
- * @param type {@link org.opendaylight.controller.sal.core.UpdateType}
- * @param propMap map of {@link org.opendaylight.controller.sal.core.Property} such as
- * {@link org.opendaylight.controller.sal.core.Description} and/or
- * {@link org.opendaylight.controller.sal.core.State} etc.
+ * @param nodeConnector {@link org.opendaylight.controller.sal.core.NodeConnector} being updated
+ * @param type {@link org.opendaylight.controller.sal.core.UpdateType}
+ * @param propMap map of {@link org.opendaylight.controller.sal.core.Property} such as
+ * {@link org.opendaylight.controller.sal.core.Description} and/or
+ * {@link org.opendaylight.controller.sal.core.State} etc.
*/
public void notifyNodeConnector(NodeConnector nodeConnector,
UpdateType type, Map<String, Property> propMap);
/**
* This method is called when list of ports in a node are added/deleted as span ports.
*
- * @param node {@link org.opendaylight.controller.sal.core.Node} being updated
- * @param portList list of span {@link org.opendaylight.controller.sal.core.NodeConnector}
- * @param add true if add; false if delete.
+ * @param node {@link org.opendaylight.controller.sal.core.Node} being updated
+ * @param portList list of span {@link org.opendaylight.controller.sal.core.NodeConnector}
+ * @param add true if add; false if delete.
*/
public void spanUpdate(Node node, List<NodeConnector> portList, boolean add);
}
\ No newline at end of file
/**
* Remove a subnet configuration
*
- * @param configObject refer to {@link Open Declaration org.opendaylight.controller.switchmanager.SubnetConfig}
+ * @param configObject refer to {@link Open Declaration org.opendaylight.controller.switchmanager.SubnetConfig}
* @return "Success" or failure reason
*/
public Status removeSubnet(SubnetConfig configObject);
* Remove a subnet configuration given the name
*
* @param name subnet name
- * @return "Success" or failure reason
+ * @return "Success" or failure reason
*/
public Status removeSubnet(String name);
/**
* Return a list of all known devices in the system
*
- * @return returns a list of {@link org.opendaylight.controller.switchmanager.Switch}
+ * @return returns a list of {@link org.opendaylight.controller.switchmanager.Switch}
*/
public List<Switch> getNetworkDevices();
/**
* Return a subnet configuration given the network address
*
- * @param networkAddress the ip address in long format
- * @return the {@link org.opendaylight.controller.switchmanager.Subnet}
+ * @param networkAddress the ip address in long format
+ * @return the {@link org.opendaylight.controller.switchmanager.Subnet}
*/
public Subnet getSubnetByNetworkAddress(InetAddress networkAddress);
* Add a span port configuration
*
* @param SpanConfig refer to {@link Open Declaration org.opendaylight.controller.switchmanager.SpanConfig}
- * @return status code
+ * @return status code
*/
public Status addSpanConfig(SpanConfig configObject);
* Remove a span port configuration
*
* @param SpanConfig refer to {@link Open Declaration org.opendaylight.controller.switchmanager.SpanConfig}
- * @return status code
+ * @return status code
*/
public Status removeSpanConfig(SpanConfig cfgObject);
/**
* Remove node connectors from a subnet
*
- * @param name the subnet config name
- * @param nodeConnectors nodePorts string specified by {@link Open Declaration org.opendaylight.controller.switchmanager.SubnetConfig}
+ * @param name the subnet config name
+ * @param nodeConnectors nodePorts string specified by {@link Open Declaration org.opendaylight.controller.switchmanager.SubnetConfig}
* @return "Success" or failure reason
*/
public Status removePortsFromSubnet(String name, String nodeConnectors);
*
* @param node {@link org.opendaylight.controller.sal.core.Node}
* @return map of {@link org.opendaylight.controller.sal.core.Property} such as
- * {@link org.opendaylight.controller.sal.core.Description} and/or
- * {@link org.opendaylight.controller.sal.core.Tier} etc.
+ * {@link org.opendaylight.controller.sal.core.Description} and/or
+ * {@link org.opendaylight.controller.sal.core.Tier} etc.
*/
public Map<String, Property> getNodeProps(Node node);
/**
* Return a specific property of a node given the property name
*
- * @param node {@link org.opendaylight.controller.sal.core.Node}
- * @param propName the property name specified by {@link org.opendaylight.controller.sal.core.Property} and its extended classes
+ * @param node {@link org.opendaylight.controller.sal.core.Node}
+ * @param propName the property name specified by {@link org.opendaylight.controller.sal.core.Property} and its extended classes
* @return {@link org.opendaylight.controller.sal.core.Property}
*/
public Property getNodeProp(Node node, String propName);
/**
* Set a specific property of a node
*
- * @param node {@link org.opendaylight.controller.sal.core.Node}
- * @param prop {@link org.opendaylight.controller.sal.core.Property}
+ * @param node {@link org.opendaylight.controller.sal.core.Node}
+ * @param prop {@link org.opendaylight.controller.sal.core.Property}
*/
public void setNodeProp(Node node, Property prop);
/**
* Remove a property of a node
- *
- * @param nc {@link org.opendaylight.controller.sal.core.Node}
- * @param propName the property name specified by {@link org.opendaylight.controller.sal.core.Property} and its extended classes
+ *
+ * @param nc {@link org.opendaylight.controller.sal.core.Node}
+ * @param propName the property name specified by {@link org.opendaylight.controller.sal.core.Property} and its extended classes
* @return success or failed reason
*/
public Status removeNodeProp(Node node, String propName);
/**
* Remove all the properties of a node
- *
+ *
* @param node {@link org.opendaylight.controller.sal.core.Node}
* @return success or failed reason
*/
*
* @param nodeConnector {@link org.opendaylight.controller.sal.core.NodeConnector}
* @return map of {@link org.opendaylight.controller.sal.core.Property} such as
- * {@link org.opendaylight.controller.sal.core.Description} and/or
- * {@link org.opendaylight.controller.sal.core.State} etc.
+ * {@link org.opendaylight.controller.sal.core.Description} and/or
+ * {@link org.opendaylight.controller.sal.core.State} etc.
*/
public Map<String, Property> getNodeConnectorProps(
NodeConnector nodeConnector);
/**
* Remove a property of a node connector
- *
+ *
* @param nc {@link org.opendaylight.controller.sal.core.NodeConnector}
* @param propName property name specified by {@link org.opendaylight.controller.sal.core.Property} and its extended classes
* @return success or failed reason
/**
* Remove all the properties of a node connector
- *
+ *
* @param nodeConnector {@link org.opendaylight.controller.sal.core.NodeConnector}
* @return success or failed reason
*/
/**
* Return the node connector given its name
*
- * @param node {@link org.opendaylight.controller.sal.core.Node}
+ * @param node {@link org.opendaylight.controller.sal.core.Node}
* @param nodeConnectorName node connector identifier specified by {@link org.opendaylight.controller.sal.core.NodeConnector}
* @return {@link org.opendaylight.controller.sal.core.NodeConnector}
*/
/**
* Return controller MAC address
- *
+ *
* @return MAC address in byte array
*/
public byte[] getControllerMAC();
/**
* Return MAC address for a given node
*
- * @param node {@link org.opendaylight.controller.sal.core.Node}
+ * @param node {@link org.opendaylight.controller.sal.core.Node}
* @return MAC address in byte array
*/
public byte[] getNodeMAC(Node node);
*/
public int getHostRetryCount();
- /**
- * Create a Name/Tier/Bandwidth Property object based on given property
- * name and value. Other property types are not supported yet.
- *
+ /**
+ * Create a Name/Tier/Bandwidth Property object based on given property
+ * name and value. Other property types are not supported yet.
+ *
* @param propName Name of the Property specified by {@link org.opendaylight.controller.sal.core.Property} and its extended classes
* @param propValue Value of the Property specified by {@link org.opendaylight.controller.sal.core.Property} and its extended classes
- * @return {@link org.opendaylight.controller.sal.core.Property}
- */
+ * @return {@link org.opendaylight.controller.sal.core.Property}
+ */
public Property createProperty(String propName, String propValue);
-
+
/**
- * Returns the description for the specified node. It is either the one
+ * Returns the description for the specified node. It is either the one
* configured by user or the description advertised by the node.
- *
+ *
* @param node the network node identifier
- * @return the description of the specified node. If no description is
+ * @return the description of the specified node. If no description is
* configured and the network node does not provide its description,
* an empty string is returned.
*/
}
public boolean isProactive() {
- return Integer.parseInt(mode) != 0;
+ return Integer.parseInt(mode) != 0;
}
-
+
public static long getSerialversionuid() {
return serialVersionUID;
}
Assert.assertTrue(sw.getSpanPorts().isEmpty());
}
-
+
@Test
public void testSwitchConfig(){
SwitchConfig sc = new SwitchConfig(null, null, null, null);
SwitchConfig sc2 = new SwitchConfig(null, null, null, null);
Assert.assertTrue(sc.equals(sc2));
-
+
Assert.assertNull(sc.getMode());
Assert.assertNull(sc.getNodeId());
Assert.assertNull(sc.getTier());
Assert.assertNull(sc.getNodeDescription());
-
+
SwitchConfig sc3 = new SwitchConfig("123", "name", "tier", "mode");
SwitchConfig sc4 = new SwitchConfig("123", "name", "tier", "mode");
Assert.assertFalse(sc.equals(sc3));
Assert.assertTrue(sc3.equals(sc4));
-
+
Assert.assertTrue(sc3.getNodeId().equals("123"));
Assert.assertTrue(sc3.getNodeDescription().equals("name"));
Assert.assertTrue(sc3.getTier().equals("tier"));
return false;
}
- if (!isValidNodeConnector(srcNodeConnector) ||
+ if (!isValidNodeConnector(srcNodeConnector) ||
!isValidNodeConnector(dstNodeConnector)) {
logger.warn("Invalid NodeConnector");
return false;
+ ", srcNodeConnector=" + srcNodeConnector
+ ", dstNodeConnector=" + dstNodeConnector + "]";
}
-}
\ No newline at end of file
+}
if (srcNodeConnector == null || dstNodeConnector == null) return null;
try {
linkTuple = new Edge(srcNodeConnector, dstNodeConnector);
- } catch (Exception e) {
+ } catch (Exception e) {
}
return linkTuple;
}
* NodeConnectorId> : <1:1>--><11:11>; <1:2>--><11:12>; <3:3>--><13:13>;
* <3:4>--><13:14>; <5:5>--><15:15>; <5:6>--><15:16>; Method used by two
* tests: testGetNodeEdges and testGetEdges
- *
+ *
* @param topoManagerImpl
- *
+ *
* @throws ConstructionException
*/
public void setNodeEdges(TopologyManagerImpl topoManagerImpl)
/**
* Authenticate user with AAA server and return authentication and
* authorization info using the Provider's mechanism
- *
+ *
* @param userName
* the username
* @param password
/**
* Returns the Name of the Provider
- *
+ *
* @return Name of the AAA provider
*/
public String getName();
import javax.servlet.http.HttpSessionListener;
/**
- *
+ *
* This interface defines method(s) to invalidate a session.
*/
public interface ISessionManager extends HttpSessionListener {
/**
* Invalidates the session for a given user and a session Id
- *
+ *
* @param username
* the username
* @param sessionId
import org.springframework.security.core.GrantedAuthority;
public class ODLUserLevel implements GrantedAuthority {
- private static final long serialVersionUID = 1L;
- UserLevel userLevel;
+ private static final long serialVersionUID = 1L;
+ UserLevel userLevel;
public ODLUserLevel(UserLevel userLevel) {
this.userLevel = userLevel;
}
public ServerConfig(String ip, String secret, String protocol) {
- this.ip = ip;
- this.secret = secret;
- this.protocol = protocol;
+ this.ip = ip;
+ this.secret = secret;
+ this.protocol = protocol;
}
-
+
public String getAddress() {
return ip;
}
this.roles = (roles == null) ? new ArrayList<String>()
: new ArrayList<String>(roles);
}
-
+
public String getUser() {
return user;
}
return new Status(StatusCode.BADREQUEST,
"Current password is incorrect");
}
-
+
// Create a new object with the proposed modifications
UserConfig proposed = new UserConfig();
proposed.user = this.user;
proposed.password = (newPassword != null)? newPassword : this.password;
proposed.roles = (newRoles != null)? newRoles : this.roles;
-
+
// Validate it
Status status = proposed.validate();
if (!status.isSuccess()) {
return status;
}
-
+
// Accept the modifications
this.user = proposed.user;
this.password = proposed.password;
this.roles = new ArrayList<String>(proposed.roles);
-
+
return status;
}
}
return locResponse;
}
-
+
protected String getRolesString() {
StringBuffer buffer = new StringBuffer();
if (!roles.isEmpty()) {
while (sessIterator.hasNext()) {
HttpSession session = sessIterator.next();
if (session != null && sessionId != null && session.getId() != null && !session.getId().equals(sessionId)) {
- sessionsList.add(session);
+ sessionsList.add(session);
sessIterator.remove();
}
else {
package org.opendaylight.controller.usermanager;
public class AuthResponseTest{
-
+
}
\ No newline at end of file
public class AuthenticatedUserTest {
- static String[] roleArray;
- static AuthenticatedUser user;
-
- @BeforeClass
- public static void testSetup() {
- roleArray = new String[] { UserLevel.NETWORKOPERATOR.toString(),
- UserLevel.APPUSER.toString() };
- }
-
- @Test
- public void testAuthenticatedUser() {
- user = new AuthenticatedUser("auser");
-
- Assert.assertFalse(user.getAccessDate().isEmpty());
- Assert.assertNull(user.getUserRoles());
- }
-
- @Test
- public void testSetUserRoleList() {
- List<String> retrievedRoleList = null;
- List<String> roleList = Arrays.asList(roleArray);
-
- // list arg
- user = new AuthenticatedUser("auser");
- user.setRoleList(roleList);
- retrievedRoleList = user.getUserRoles();
- Assert.assertTrue(roleList.equals(retrievedRoleList));
-
- // array arg
- user = new AuthenticatedUser("auser");
- user.setRoleList(roleArray);
- retrievedRoleList = user.getUserRoles();
- for (int i = 0; i < roleArray.length; i++)
- Assert.assertTrue(roleArray[i].equals(retrievedRoleList.get(i)));
-
- // test addUserRole
- user.addUserRole("AnotherRole");
- Assert.assertTrue(user.getUserRoles().lastIndexOf("AnotherRole") != -1);
-
- }
-
- @Test
- public void testGetGrantedAuthorities() {
- List<GrantedAuthority> gaList = user
- .getGrantedAuthorities(UserLevel.NETWORKOPERATOR);
- Assert.assertTrue(gaList.get(0).getAuthority()
- .equals("ROLE_NETWORK-OPERATOR"));
- }
+ static String[] roleArray;
+ static AuthenticatedUser user;
+
+ @BeforeClass
+ public static void testSetup() {
+ roleArray = new String[] { UserLevel.NETWORKOPERATOR.toString(),
+ UserLevel.APPUSER.toString() };
+ }
+
+ @Test
+ public void testAuthenticatedUser() {
+ user = new AuthenticatedUser("auser");
+
+ Assert.assertFalse(user.getAccessDate().isEmpty());
+ Assert.assertNull(user.getUserRoles());
+ }
+
+ @Test
+ public void testSetUserRoleList() {
+ List<String> retrievedRoleList = null;
+ List<String> roleList = Arrays.asList(roleArray);
+
+ // list arg
+ user = new AuthenticatedUser("auser");
+ user.setRoleList(roleList);
+ retrievedRoleList = user.getUserRoles();
+ Assert.assertTrue(roleList.equals(retrievedRoleList));
+
+ // array arg
+ user = new AuthenticatedUser("auser");
+ user.setRoleList(roleArray);
+ retrievedRoleList = user.getUserRoles();
+ for (int i = 0; i < roleArray.length; i++)
+ Assert.assertTrue(roleArray[i].equals(retrievedRoleList.get(i)));
+
+ // test addUserRole
+ user.addUserRole("AnotherRole");
+ Assert.assertTrue(user.getUserRoles().lastIndexOf("AnotherRole") != -1);
+
+ }
+
+ @Test
+ public void testGetGrantedAuthorities() {
+ List<GrantedAuthority> gaList = user
+ .getGrantedAuthorities(UserLevel.NETWORKOPERATOR);
+ Assert.assertTrue(gaList.get(0).getAuthority()
+ .equals("ROLE_NETWORK-OPERATOR"));
+ }
}
roles.clear();
roles.add(UserLevel.NETWORKADMIN.toString());
assertTrue(userConfig.update("ciscocisco", null, roles).isSuccess());
-
+
// Role change and same new password
roles.clear();
roles.add(UserLevel.NETWORKOPERATOR.toString());
assertTrue(userConfig.update("ciscocisco", "ciscocisco", roles)
.isSuccess());
-
+
// New Password = null, No change in password
assertTrue(userConfig.getPassword().equals("ciscocisco"));
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
@ResponseBody
public Set<Map<String, Object>> getFlows(HttpServletRequest request, @RequestParam(required = false) String container) {
String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
-
+
// fetch frm
IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper
.getInstance(IForwardingRulesManager.class, containerName, this);
@ResponseBody
public Map<String, Object> getNodePorts(HttpServletRequest request, @RequestParam(required = false) String container) {
String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
-
+
ISwitchManager switchManager = (ISwitchManager) ServiceHelper
.getInstance(ISwitchManager.class, containerName, this);
if (switchManager == null) {
@ResponseBody
public Map<String, Object> getNodeFlows(HttpServletRequest request, @RequestParam(required = false) String container) {
String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
-
+
ISwitchManager switchManager = (ISwitchManager) ServiceHelper
.getInstance(ISwitchManager.class, containerName, this);
if (switchManager == null) {
if (!isUserAuthorized(UserLevel.NETWORKADMIN, request)) {
return "Operation not authorized";
}
-
+
String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper
if (!isUserAuthorized(UserLevel.NETWORKADMIN, request)) {
return "Operation not authorized";
}
-
+
String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper
/**
* Returns whether the current user's level is same or above the required
* authorization level.
- *
+ *
* @param requiredLevel
* the authorization level required
*/
return userManager.removeLocalUser(userName).getDescription();
}
-
+
@RequestMapping(value = "/users/password/{username}", method = RequestMethod.POST)
@ResponseBody
public Status changePassword(@PathVariable("username") String username, HttpServletRequest request,
if (userManager == null) {
return new Status(StatusCode.GONE, "User Manager not found");
}
-
+
if (!authorize(userManager, UserLevel.NETWORKADMIN, request)) {
return new Status(StatusCode.FORBIDDEN, "Operation not permitted");
}
-
+
if (newPassword.isEmpty()) {
return new Status(StatusCode.BADREQUEST, "Empty passwords not allowed");
}
-
+
Status status = userManager.changeLocalUserPassword(username, currentPassword, newPassword);
-
+
return status;
}
/**
* Is the operation permitted for the given level
- *
+ *
* @param level
*/
private boolean authorize(IUserManager userManager, UserLevel level,
public class DaylightWebUtil {
private static String defaultName = GlobalConstants.DEFAULT.toString();
-
+
/**
* Returns the container that this user is authorized to access. If the user is not authorized to the requested
* container, then this method will return the default container.
- *
+ *
* @param request - HttpServletRequest object to retrieve username
* @param container - requested container
* @param bundle - respective bundle
if (container == null) {
return defaultName;
}
-
+
String username = request.getUserPrincipal().getName();
IContainerAuthorization containerAuthorization = (IContainerAuthorization)
ServiceHelper.getGlobalInstance(IContainerAuthorization.class, bundle);
/**
* Returns the name of the bundle. In the GUI, this name will be displayed
* on the tab.
- *
+ *
* @return Name assigned to the bundle.
*/
public String getWebName();
/**
* Returns the Id assigned to the web bundle.
- *
+ *
* @return Id assigned to the web bundle.
*/
public String getWebId();
/**
* Returns the position where the bundle tab will be placed in the GUI.
- *
+ *
* @return Position number for the bundle tab.
*/
public short getWebOrder();
/**
* This method checks if the user is authorized to access the bundle.
- *
+ *
* @param userLevel
* user role level in the controller space.
- *
+ *
* @return true, if user is authorized to access the bundle, else false.
*/
public boolean isAuthorized(UserLevel userLevel);
protected Map<String, Map<String, Map<String, Object>>> metaCache = new HashMap<String, Map<String, Map<String, Object>>>();
protected Map<String, Map<String, Object>> stagedNodes;
protected Map<String, Map<String, Object>> newNodes;
-
+
protected Map<String, Integer> metaNodeHash = new HashMap<String, Integer>();
protected Map<String, Integer> metaHostHash = new HashMap<String, Integer>();
protected Map<String, Integer> metaNodeSingleHash = new HashMap<String, Integer>();
protected Map<String, Integer> metaNodeConfigurationHash = new HashMap<String, Integer>();
-
+
public Topology() {
- ServiceHelper.registerGlobalService(IConfigurationAware.class, this, null);
- topologyWebFileName = ROOT + "topologyCache.sav";
- loadConfiguration();
+ ServiceHelper.registerGlobalService(IConfigurationAware.class, this, null);
+ topologyWebFileName = ROOT + "topologyCache.sav";
+ loadConfiguration();
}
-
+
/**
* Topology of nodes and hosts in the network in JSON format.
- *
+ *
* Mainly intended for consumption by the visual topology.
- *
+ *
* @return - JSON output for visual topology
*/
@RequestMapping(value = "/visual.json", method = RequestMethod.GET)
@ResponseBody
public Collection<Map<String, Object>> getLinkData(@RequestParam(required = false) String container, HttpServletRequest request) {
- String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
-
+ String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
+
ITopologyManager topologyManager = (ITopologyManager) ServiceHelper
.getInstance(ITopologyManager.class, containerName, this);
if (topologyManager == null) {
- return null;
+ return null;
}
ISwitchManager switchManager = (ISwitchManager) ServiceHelper
.getInstance(ISwitchManager.class, containerName, this);
if (switchManager == null) {
- return null;
+ return null;
}
-
+
Map<Node, Set<Edge>> nodeEdges = topologyManager.getNodeEdges();
Map<Node, Set<NodeConnector>> hostEdges = topologyManager
.getNodesWithNodeConnectorHost();
List<Switch> nodes = switchManager.getNetworkDevices();
-
+
List<SwitchConfig> switchConfigurations = new ArrayList<SwitchConfig>();
for(Switch sw : nodes) {
- Node n = sw.getNode();
- SwitchConfig config = switchManager.getSwitchConfig(n.toString());
- switchConfigurations.add(config);
+ Node n = sw.getNode();
+ SwitchConfig config = switchManager.getSwitchConfig(n.toString());
+ switchConfigurations.add(config);
}
-
+
// initialize cache if needed
if (!metaCache.containsKey(containerName)) {
- metaCache.put(containerName, new HashMap<String, Map<String, Object>>());
- // initialize hashes
- metaNodeHash.put(containerName, null);
- metaHostHash.put(containerName, null);
- metaNodeSingleHash.put(containerName, null);
- metaNodeConfigurationHash.put(containerName, null);
+ metaCache.put(containerName, new HashMap<String, Map<String, Object>>());
+ // initialize hashes
+ metaNodeHash.put(containerName, null);
+ metaHostHash.put(containerName, null);
+ metaNodeSingleHash.put(containerName, null);
+ metaNodeConfigurationHash.put(containerName, null);
}
-
+
// return cache if topology hasn't changed
if (
- (metaNodeHash.get(containerName) != null && metaHostHash.get(containerName) != null && metaNodeSingleHash.get(containerName) != null && metaNodeConfigurationHash.get(containerName) != null) &&
- metaNodeHash.get(containerName).equals(nodeEdges.hashCode()) && metaHostHash.get(containerName).equals(hostEdges.hashCode()) && metaNodeSingleHash.get(containerName).equals(nodes.hashCode()) && metaNodeConfigurationHash.get(containerName).equals(switchConfigurations.hashCode())
+ (metaNodeHash.get(containerName) != null && metaHostHash.get(containerName) != null && metaNodeSingleHash.get(containerName) != null && metaNodeConfigurationHash.get(containerName) != null) &&
+ metaNodeHash.get(containerName).equals(nodeEdges.hashCode()) && metaHostHash.get(containerName).equals(hostEdges.hashCode()) && metaNodeSingleHash.get(containerName).equals(nodes.hashCode()) && metaNodeConfigurationHash.get(containerName).equals(switchConfigurations.hashCode())
) {
- return metaCache.get(containerName).values();
+ return metaCache.get(containerName).values();
}
-
+
// cache has changed, we must assign the new values
metaNodeHash.put(containerName, nodeEdges.hashCode());
metaHostHash.put(containerName, hostEdges.hashCode());
metaNodeSingleHash.put(containerName, nodes.hashCode());
metaNodeConfigurationHash.put(containerName, switchConfigurations.hashCode());
-
+
stagedNodes = new HashMap<String, Map<String, Object>>();
newNodes = new HashMap<String, Map<String, Object>>();
// single nodes addition
addSingleNodes(nodes, switchManager, containerName);
-
+
// hostNodes addition
addHostNodes(hostEdges, topologyManager, containerName);
-
+
repositionTopology(containerName);
-
+
return metaCache.get(containerName).values();
}
* @param topology - the topology instance
*/
private void addNodes(Map<Node, Set<Edge>> nodeEdges,
- ITopologyManager topology, ISwitchManager switchManager, String containerName) {
+ ITopologyManager topology, ISwitchManager switchManager, String containerName) {
Bandwidth bandwidth = new Bandwidth(0);
Map<Edge, Set<Property>> properties = topology.getEdges();
-
+
for (Map.Entry<Node, Set<Edge>> e : nodeEdges.entrySet()) {
Node n = e.getKey();
String description = switchManager.getNodeDescription(n);
NodeBean node = createNodeBean(description, n);
-
+
// skip production node
if (nodeIgnore(n)) {
continue;
}
-
+
List<Map<String, Object>> adjacencies = new LinkedList<Map<String, Object>>();
Set<Edge> links = e.getValue();
for (Edge link : links) {
}
for (Property p : properties.get(link)) {
if (p instanceof Bandwidth) {
- bandwidth = (Bandwidth) p;
+ bandwidth = (Bandwidth) p;
break;
}
}
EdgeBean edge = new EdgeBean(link, bandwidth);
adjacencies.add(edge.out());
}
-
+
node.setLinks(adjacencies);
if (metaCache.get(containerName).containsKey(node.id())) {
- // retrieve node from cache
- Map<String, Object> nodeEntry = metaCache.get(containerName).get(node.id());
-
- Map<String, String> data = (Map<String, String>) nodeEntry.get("data");
- data.put("$desc", description);
- nodeEntry.put("data", data);
-
- // always update adjacencies
- nodeEntry.put("adjacencies", adjacencies);
- // stage this cached node (with position)
- stagedNodes.put(node.id(), nodeEntry);
+ // retrieve node from cache
+ Map<String, Object> nodeEntry = metaCache.get(containerName).get(node.id());
+
+ Map<String, String> data = (Map<String, String>) nodeEntry.get("data");
+ data.put("$desc", description);
+ nodeEntry.put("data", data);
+
+ // always update adjacencies
+ nodeEntry.put("adjacencies", adjacencies);
+ // stage this cached node (with position)
+ stagedNodes.put(node.id(), nodeEntry);
} else {
- newNodes.put(node.id(), node.out());
+ newNodes.put(node.id(), node.out());
}
}
}
-
+
/**
* Check if this node shouldn't appear in the visual topology
- *
+ *
* @param node
* @return
*/
private boolean nodeIgnore(Node node) {
String nodeType = node.getType();
-
+
// add other node types to ignore later
if (nodeType.equals(NodeIDType.PRODUCTION)) {
return true;
}
-
+
return false;
}
-
+
/**
* Check if this edge shouldn't appear in the visual topology
- *
+ *
* @param edge
* @return
*/
if (nodeIgnore(headNode)) {
return true;
}
-
+
NodeConnector tailNodeConnector = edge.getTailNodeConnector();
Node tailNode = tailNodeConnector.getNode();
if (nodeIgnore(tailNode)) {
return true;
}
-
+
return false;
}
-
+
protected NodeBean createNodeBean(String description, Node node) {
- String name = (description == null ||
- description.trim().isEmpty() ||
- description.equalsIgnoreCase("none"))?
- node.toString() : description;
- return new NodeBean(node.toString(), name, NodeType.NODE);
+ String name = (description == null ||
+ description.trim().isEmpty() ||
+ description.equalsIgnoreCase("none"))?
+ node.toString() : description;
+ return new NodeBean(node.toString(), name, NodeType.NODE);
}
-
+
@SuppressWarnings("unchecked")
- private void addSingleNodes(List<Switch> nodes, ISwitchManager switchManager, String containerName) {
- if (nodes == null) {
- return;
- }
- for (Switch sw : nodes) {
- Node n = sw.getNode();
-
- // skip production node
- if (nodeIgnore(n)) {
- continue;
- }
-
- String description = switchManager.getNodeDescription(n);
-
- if ((stagedNodes.containsKey(n.toString()) && metaCache.get(containerName).containsKey(n.toString())) || newNodes.containsKey(n.toString())) {
- continue;
- }
- NodeBean node = createNodeBean(description, n);
-
- // FIXME still doesn't display standalone node when last remaining link is removed
- if (metaCache.get(containerName).containsKey(node.id()) && !stagedNodes.containsKey(node.id())) {
- Map<String, Object> nodeEntry = metaCache.get(containerName).get(node.id());
- Map<String, String> data = (Map<String, String>) nodeEntry.get("data");
- data.put("$desc", description);
- nodeEntry.put("data", data);
- // clear adjacencies since this is now a single node
- nodeEntry.put("adjacencies", new LinkedList<Map<String, Object>>());
- stagedNodes.put(node.id(), nodeEntry);
+ private void addSingleNodes(List<Switch> nodes, ISwitchManager switchManager, String containerName) {
+ if (nodes == null) {
+ return;
+ }
+ for (Switch sw : nodes) {
+ Node n = sw.getNode();
+
+ // skip production node
+ if (nodeIgnore(n)) {
+ continue;
+ }
+
+ String description = switchManager.getNodeDescription(n);
+
+ if ((stagedNodes.containsKey(n.toString()) && metaCache.get(containerName).containsKey(n.toString())) || newNodes.containsKey(n.toString())) {
+ continue;
+ }
+ NodeBean node = createNodeBean(description, n);
+
+ // FIXME still doesn't display standalone node when last remaining link is removed
+ if (metaCache.get(containerName).containsKey(node.id()) && !stagedNodes.containsKey(node.id())) {
+ Map<String, Object> nodeEntry = metaCache.get(containerName).get(node.id());
+ Map<String, String> data = (Map<String, String>) nodeEntry.get("data");
+ data.put("$desc", description);
+ nodeEntry.put("data", data);
+ // clear adjacencies since this is now a single node
+ nodeEntry.put("adjacencies", new LinkedList<Map<String, Object>>());
+ stagedNodes.put(node.id(), nodeEntry);
} else {
- newNodes.put(node.id(), node.out());
+ newNodes.put(node.id(), node.out());
}
- }
+ }
}
/**
addressByteBuffer.putShort((short) 0);
addressByteBuffer.put(dmac.getValue());
addressByteBuffer.rewind();
-
+
long hid = addressByteBuffer.getLong();
String hostId = String.valueOf(hid);
-
+
NodeBean hostBean = new NodeBean(hostId, host.getNetworkAddressAsString(), NodeType.HOST);
List<Map<String, Object>> adjacencies = new LinkedList<Map<String, Object>>();
EdgeBean edge = new EdgeBean(connector, hid);
adjacencies.add(edge.out());
hostBean.setLinks(adjacencies);
-
+
if (metaCache.get(containerName).containsKey(hostId)) {
- Map<String, Object> hostEntry = metaCache.get(containerName).get(hostId);
- hostEntry.put("adjacencies", adjacencies);
- stagedNodes.put(hostId, hostEntry);
+ Map<String, Object> hostEntry = metaCache.get(containerName).get(hostId);
+ hostEntry.put("adjacencies", adjacencies);
+ stagedNodes.put(hostId, hostEntry);
} else {
- newNodes.put(String.valueOf(hid), hostBean.out());
+ newNodes.put(String.valueOf(hid), hostBean.out());
}
}
}
*/
private void repositionTopology(String containerName) {
Graph<String, String> graph = new SparseMultigraph<String, String>();
-
+
metaCache.get(containerName).clear();
metaCache.get(containerName).putAll(stagedNodes);
metaCache.get(containerName).putAll(newNodes);
-
+
for (Map<String, Object> on : metaCache.get(containerName).values()) {
graph.addVertex(on.toString());
List<Map<String, Object>> adjacencies = (List<Map<String, Object>>) on.get("adjacencies");
-
+
for (Map<String, Object> adj : adjacencies) {
graph.addEdge(
- adj.toString(), adj.get("nodeFrom").toString(),
- adj.get("nodeTo").toString()
+ adj.toString(), adj.get("nodeFrom").toString(),
+ adj.get("nodeTo").toString()
);
}
}
-
+
CircleLayout<String, String> layout = new CircleLayout<String, String>(graph);
layout.setSize(new Dimension(1200, 365));
for (Map.Entry<String, Map<String, Object>> v : newNodes.entrySet()) {
/**
* Update node position
- *
+ *
* This method is mainly used by the visual topology
*
* @param nodeId - The node to update
@RequestMapping(value = "/node/{nodeId}", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> post(@PathVariable String nodeId, @RequestParam(required = true) String x,
- @RequestParam(required = true) String y, @RequestParam(required = false) String container,
- HttpServletRequest request) {
- if (!authorize(UserLevel.NETWORKADMIN, request)) {
- return new HashMap<String, Object>(); // silently disregard new node position
- }
-
- String containerName = getAuthorizedContainer(request, container);
-
+ @RequestParam(required = true) String y, @RequestParam(required = false) String container,
+ HttpServletRequest request) {
+ if (!authorize(UserLevel.NETWORKADMIN, request)) {
+ return new HashMap<String, Object>(); // silently disregard new node position
+ }
+
+ String containerName = getAuthorizedContainer(request, container);
+
String id = new String(nodeId);
-
+
if (!metaCache.get(containerName).containsKey(id)) {
return null;
}
data.put("$y", y);
node.put("data", data);
-
+
return node;
}
-
+
/**
* Node object for visual topology
*/
protected class NodeBean {
- protected String id;
- protected String name;
- protected Map<String, String> data;
- protected List<Map<String, Object>> links;
-
- public NodeBean() {
- data = new HashMap<String, String>();
- links = new ArrayList<Map<String, Object>>();
- }
-
- public NodeBean(String id, String name, String type) {
- this();
- this.id = id;
- this.name = name;
- data.put("$desc", name);
- data.put("$type", type);
- }
-
- public void setLinks(List<Map<String, Object>> links) {
- this.links = links;
- }
-
- public Map<String, Object> out() {
- Map<String, Object> node = new HashMap<String, Object>();
- node.put("id", this.id);
- node.put("name", this.name);
- node.put("data", this.data);
- node.put("adjacencies", this.links);
-
- return node;
- }
-
- public String name() {
- return this.name;
- }
-
- public String id() {
- return this.id;
- }
+ protected String id;
+ protected String name;
+ protected Map<String, String> data;
+ protected List<Map<String, Object>> links;
+
+ public NodeBean() {
+ data = new HashMap<String, String>();
+ links = new ArrayList<Map<String, Object>>();
+ }
+
+ public NodeBean(String id, String name, String type) {
+ this();
+ this.id = id;
+ this.name = name;
+ data.put("$desc", name);
+ data.put("$type", type);
+ }
+
+ public void setLinks(List<Map<String, Object>> links) {
+ this.links = links;
+ }
+
+ public Map<String, Object> out() {
+ Map<String, Object> node = new HashMap<String, Object>();
+ node.put("id", this.id);
+ node.put("name", this.name);
+ node.put("data", this.data);
+ node.put("adjacencies", this.links);
+
+ return node;
+ }
+
+ public String name() {
+ return this.name;
+ }
+
+ public String id() {
+ return this.id;
+ }
}
-
+
/**
* Edge object for visual topology
*/
protected class EdgeBean {
- protected NodeConnector source;
- protected NodeConnector destination;
- protected Map<String, String> data;
- protected Long hostId;
-
- public EdgeBean() {
- data = new HashMap<String, String>();
- }
-
- public EdgeBean(Edge link, Bandwidth bandwidth) {
- this();
- this.source = link.getHeadNodeConnector();
- this.destination = link.getTailNodeConnector();
-
- // data
- data.put("$bandwidth", bandwidth.toString());
- data.put("$color", bandwidthColor(bandwidth));
- data.put("$nodeToPort", destination.getID().toString());
- data.put("$nodeFromPort", source.getID().toString());
- data.put("$descFrom", source.getNode().toString());
- data.put("$descTo", destination.getNode().toString());
- data.put("$nodeFromPortName", source.toString());
- data.put("$nodeToPortName", destination.toString());
- }
-
- public EdgeBean(NodeConnector connector, Long hostId) {
- this();
- this.source = null;
- this.destination = connector;
- this.hostId = hostId;
-
- data.put("$bandwidth", "N/A");
- data.put("$color", bandwidthColor(new Bandwidth(0)));
- data.put("$nodeToPort", connector.getNodeConnectorIDString());
- data.put("$nodeFromPort", connector.getNodeConnectorIDString());
- data.put("$descTo", "");
- data.put("$descFrom", "");
- data.put("$nodeToPortName", "");
- data.put("$nodeFromPortName", "");
- }
-
- public Map<String, Object> out() {
- Map<String, Object> edge = new HashMap<String, Object>();
-
- edge.put("data", data);
- if (source == null) {
- edge.put("nodeFrom", String.valueOf(this.hostId));
- } else {
- edge.put("nodeFrom", source.getNode().toString());
- }
- edge.put("nodeTo", destination.getNode().toString());
-
-
- return edge;
- }
-
- private String bandwidthColor(Bandwidth bandwidth) {
- String color = null;
- long bandwidthValue = bandwidth.getValue();
-
- if (bandwidthValue == 0) {
+ protected NodeConnector source;
+ protected NodeConnector destination;
+ protected Map<String, String> data;
+ protected Long hostId;
+
+ public EdgeBean() {
+ data = new HashMap<String, String>();
+ }
+
+ public EdgeBean(Edge link, Bandwidth bandwidth) {
+ this();
+ this.source = link.getHeadNodeConnector();
+ this.destination = link.getTailNodeConnector();
+
+ // data
+ data.put("$bandwidth", bandwidth.toString());
+ data.put("$color", bandwidthColor(bandwidth));
+ data.put("$nodeToPort", destination.getID().toString());
+ data.put("$nodeFromPort", source.getID().toString());
+ data.put("$descFrom", source.getNode().toString());
+ data.put("$descTo", destination.getNode().toString());
+ data.put("$nodeFromPortName", source.toString());
+ data.put("$nodeToPortName", destination.toString());
+ }
+
+ public EdgeBean(NodeConnector connector, Long hostId) {
+ this();
+ this.source = null;
+ this.destination = connector;
+ this.hostId = hostId;
+
+ data.put("$bandwidth", "N/A");
+ data.put("$color", bandwidthColor(new Bandwidth(0)));
+ data.put("$nodeToPort", connector.getNodeConnectorIDString());
+ data.put("$nodeFromPort", connector.getNodeConnectorIDString());
+ data.put("$descTo", "");
+ data.put("$descFrom", "");
+ data.put("$nodeToPortName", "");
+ data.put("$nodeFromPortName", "");
+ }
+
+ public Map<String, Object> out() {
+ Map<String, Object> edge = new HashMap<String, Object>();
+
+ edge.put("data", data);
+ if (source == null) {
+ edge.put("nodeFrom", String.valueOf(this.hostId));
+ } else {
+ edge.put("nodeFrom", source.getNode().toString());
+ }
+ edge.put("nodeTo", destination.getNode().toString());
+
+
+ return edge;
+ }
+
+ private String bandwidthColor(Bandwidth bandwidth) {
+ String color = null;
+ long bandwidthValue = bandwidth.getValue();
+
+ if (bandwidthValue == 0) {
color = "#000";
} else if (bandwidthValue < Bandwidth.BW1Kbps) {
- color = "#148AC6";
+ color = "#148AC6";
} else if (bandwidthValue < Bandwidth.BW1Mbps) {
color = "#2858A0";
} else if (bandwidthValue < Bandwidth.BW1Gbps) {
} else if (bandwidthValue < Bandwidth.BW1Pbps) {
color = "#F9F464";
}
-
- return color;
+
+ return color;
}
}
-
+
protected class NodeType {
- public static final String NODE = "swtch";
- public static final String HOST = "host";
+ public static final String NODE = "swtch";
+ public static final String HOST = "host";
}
-
+
private boolean authorize(UserLevel level, HttpServletRequest request) {
- IUserManager userManager = (IUserManager) ServiceHelper
+ IUserManager userManager = (IUserManager) ServiceHelper
.getGlobalInstance(IUserManager.class, this);
if (userManager == null) {
- return false;
+ return false;
}
-
+
String username = request.getUserPrincipal().getName();
UserLevel userLevel = userManager.getUserLevel(username);
if (userLevel.toNumber() <= level.toNumber()) {
- return true;
+ return true;
}
return false;
}
-
+
private String getAuthorizedContainer(HttpServletRequest request, String container) {
- String username = request.getUserPrincipal().getName();
- IContainerAuthorization containerAuthorization = (IContainerAuthorization) ServiceHelper.
- getGlobalInstance(IContainerAuthorization.class, this);
- if (containerAuthorization != null) {
- Set<Resource> resources = containerAuthorization.getAllResourcesforUser(username);
- if (authorizeContainer(container, resources)) {
- return container;
- }
- }
-
- return GlobalConstants.DEFAULT.toString();
+ String username = request.getUserPrincipal().getName();
+ IContainerAuthorization containerAuthorization = (IContainerAuthorization) ServiceHelper.
+ getGlobalInstance(IContainerAuthorization.class, this);
+ if (containerAuthorization != null) {
+ Set<Resource> resources = containerAuthorization.getAllResourcesforUser(username);
+ if (authorizeContainer(container, resources)) {
+ return container;
+ }
+ }
+
+ return GlobalConstants.DEFAULT.toString();
}
-
+
private boolean authorizeContainer(String container, Set<Resource> resources) {
- for(Resource resource : resources) {
- String containerName = (String) resource.getResource();
- if (containerName.equals(container)) {
- return true;
- }
- }
-
- return false;
+ for(Resource resource : resources) {
+ String containerName = (String) resource.getResource();
+ if (containerName.equals(container)) {
+ return true;
+ }
+ }
+
+ return false;
}
@SuppressWarnings("unchecked")
- private void loadConfiguration() {
+ private void loadConfiguration() {
ObjectReader objReader = new ObjectReader();
metaCache = (Map<String, Map<String, Map<String, Object>>>) objReader.read(this, topologyWebFileName);
if (metaCache == null) metaCache = new HashMap<String, Map<String, Map<String, Object>>>();
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
import org.opendaylight.controller.sal.utils.NodeCreator;
import org.opendaylight.controller.switchmanager.SwitchConfig;
import org.opendaylight.controller.topology.web.Topology.NodeBean;
-
+
public class TopologyTest {
- @Test
- public void testCreateNodeBean() {
- Topology topology = new Topology();
- Node node = NodeCreator.createOFNode(new Long(3));
- String description = "foo";
-
- NodeBean bean = topology.createNodeBean(description, node);
-
- assertNotNull(bean);
- assertEquals(bean.id, node.toString());
- assertEquals(bean.name, "foo");
-
- bean = topology.createNodeBean(null, node);
-
- assertNotNull(bean);
- assertEquals(bean.id, node.toString());
- assertEquals(bean.name, bean.id);
-
- bean = topology.createNodeBean(" ", node);
-
- assertNotNull(bean);
- assertEquals(bean.id, node.toString());
- assertEquals(bean.name, bean.id);
- }
+ @Test
+ public void testCreateNodeBean() {
+ Topology topology = new Topology();
+ Node node = NodeCreator.createOFNode(new Long(3));
+ String description = "foo";
+
+ NodeBean bean = topology.createNodeBean(description, node);
+
+ assertNotNull(bean);
+ assertEquals(bean.id, node.toString());
+ assertEquals(bean.name, "foo");
+
+ bean = topology.createNodeBean(null, node);
+
+ assertNotNull(bean);
+ assertEquals(bean.id, node.toString());
+ assertEquals(bean.name, bean.id);
+
+ bean = topology.createNodeBean(" ", node);
+
+ assertNotNull(bean);
+ assertEquals(bean.id, node.toString());
+ assertEquals(bean.name, bean.id);
+ }
}
Match match = flow.getMatch();
ISwitchManager switchManager = (ISwitchManager) ServiceHelper
.getInstance(ISwitchManager.class, containerName, this);
- String desc = (switchManager == null)?
- "" : switchManager.getNodeDescription(node);
- desc = (desc.isEmpty() || desc.equalsIgnoreCase("none"))?
- node.toString(): desc;
+ String desc = (switchManager == null)?
+ "" : switchManager.getNodeDescription(node);
+ desc = (desc.isEmpty() || desc.equalsIgnoreCase("none"))?
+ node.toString(): desc;
row.put("nodeName", desc);
if (match.isPresent(MatchType.IN_PORT)) {
row.put(MatchType.IN_PORT.id(), ((NodeConnector) flow.getMatch()
Short tpSrc = (Short) (flow.getMatch().getField(MatchType.TP_SRC)
.getValue());
row.put(MatchType.TP_SRC.id(),
- String.valueOf(NetUtils.getUnsignedShort(tpSrc)));
+ String.valueOf(NetUtils.getUnsignedShort(tpSrc)));
} else {
row.put(MatchType.TP_SRC.id(), "*");
}
Short tpDst = (Short) (flow.getMatch().getField(MatchType.TP_DST)
.getValue());
row.put(MatchType.TP_DST.id(),
- String.valueOf(NetUtils.getUnsignedShort(tpDst)));
+ String.valueOf(NetUtils.getUnsignedShort(tpDst)));
} else {
row.put(MatchType.TP_DST.id(), "*");
}