method2testcases
stringlengths
118
6.63k
### Question: PathMatchers { @Factory public static Matcher<Path> isDirectory() { return new IsDirectory(); } PathMatchers(); @Factory static Matcher<Path> contains(String fileName); @Factory static Matcher<Path> isDirectory(); @Factory static Matcher<Path> exists(LinkOption... options); @Factory static Matcher<Path> hasFilesCount(int expectedCount); @Factory static Matcher<Path> hasFilesCount(int expectedCount, String glob); }### Answer: @Test public void shouldIsDirectory() throws Exception { assertThat(directory, isDirectory()); } @Test(expected = AssertionError.class) public void shouldFailIfNotADirectory() throws Exception { assertThat(directory.resolve("file"), isDirectory()); } @Test public void shouldNotIsDirectory() throws Exception { Path file = directory.resolve("file"); Files.write(file, "content".getBytes(StandardCharsets.UTF_8)); assertThat(file, not(isDirectory())); } @Test public void shouldNotFailIfFileDoesNotExists() throws Exception { Path file = directory.resolve("file"); assertThat(file, not(isDirectory())); }
### Question: HasCookieMatcher extends TypeSafeMatcher<WebDriver> { @Factory public static Matcher<WebDriver> hasCookie(String name) { return new HasCookieMatcher(name); } protected HasCookieMatcher(String name); @Override void describeTo(Description description); @Factory static Matcher<WebDriver> hasCookie(String name); }### Answer: @Test public void shouldFindExistingCookie() { WebDriver driver = mock(WebDriver.class); Options options = mock(Options.class); Cookie cookie = new Cookie(cookieName, "oki-doki"); when(driver.manage()).thenReturn(options); when(options.getCookieNamed(eq(cookieName))).thenReturn(cookie); assertThat("Cookie not found!", driver, hasCookie(cookieName)); } @Test public void shouldNotFindUnexistingCookie() { final WebDriver driver = mock(WebDriver.class); Options options = mock(Options.class); when(driver.manage()).thenReturn(options); when(options.getCookieNamed(eq(cookieName))).thenReturn(null); assertThat("Cook should not be found", driver, not(hasCookie(cookieName))); }
### Question: Telemetry { public synchronized static Telemetry getInstance() { if (sTelemetryInstance == null) { new Builder().build(); } return sTelemetryInstance; } private Telemetry(final Builder builder); synchronized static Telemetry getInstance(); void addObserver(@SuppressWarnings(WarningType.rawtype_warning) final ITelemetryObserver observer); void removeObserver(final Class<?> cls); void removeObserver(@SuppressWarnings(WarningType.rawtype_warning) final ITelemetryObserver observer); @SuppressWarnings({WarningType.rawtype_warning, WarningType.unchecked_warning}) List<ITelemetryObserver> getObservers(); static void emit(final BaseEvent event); void flush(); void flush(@NonNull final String correlationId); }### Answer: @Test public void testTelemetryInstanceCreationSuccess() { Telemetry telemetry = Telemetry.getInstance(); Assert.assertNotNull(telemetry); }
### Question: ConfigurationLoader { public Map<String, Object> loadConfiguration(File file) throws IOException { Map<String, Object> config = new HashMap<>(defaultConfig); Map<String, Object> tmpConfig; try (InputStream input = new FileInputStream(file)) { Yaml yaml = new Yaml(); tmpConfig = yaml.load(input); if (tmpConfig == null) { return config; } for (Map.Entry element : tmpConfig.entrySet()) { String key = (String) element.getKey(); if (!variableNames.contains(key)) { throw new InvalidVariableException("unknown variable: " + key); } else { config.put(key, element.getValue()); } } } return config; } ConfigurationLoader(List<Variable> variables); Map<String, Object> loadConfiguration(File file); }### Answer: @Test public void load() throws Exception { List<Variable> list = new ArrayList<>(); list.add(new Variable("probe")); list.add(new Variable("mode")); list.add(new Variable("should-have-default", "should have default value", "default")); ConfigurationLoader config = new ConfigurationLoader(list); Map<String, Object> result; try { result = config.loadConfiguration(testYML); } catch (IOException e) { throw new RuntimeException(e); } assertEquals(createTestingProbeList(), result.get("probe")); assertTrue(result.get("probe") instanceof ArrayList); assertEquals("continual", result.get("mode")); assertFalse(result.get("mode") instanceof ArrayList); assertTrue(result.get("mode") instanceof String); assertEquals("default", result.get("should-have-default")); assertFalse(result.get("should-have-default") instanceof ArrayList); assertTrue(result.get("should-have-default") instanceof String); } @Test(expected = InvalidVariableException.class) public void invalidVariable() throws Exception { List<Variable> variables = Collections.singletonList(new Variable("allowed")); (new ConfigurationLoader(variables)).loadConfiguration(testYML); }
### Question: Optionality { public static boolean is_optional_of(DataType opt, DataType inner) { Ensure.not_null(opt); Ensure.not_null(inner); if (!(opt instanceof OptionalDataType)) { return false; } OptionalDataType odt = (OptionalDataType) opt; return (odt.inner_type() == inner); } private Optionality(); static boolean is_optional(DataType dt); static boolean is_optional(DataValue dv); static DataType unoptionalize(DataType dt); static DataType deep_unoptionalize(DataType dt); static DataValue unoptionalize(DataValue dv); static DataValue deep_unoptionalize(DataValue dv); static DataValue optionalize(DataValue v, DataType dt); static boolean is_optional_of(DataType opt, DataType inner); static boolean is_deep_optional_of(DataType opt, DataType inner); }### Answer: @Test public void check_deep_optional_optional_data_type_of_deep_optional() throws Exception { assertFalse(Optionality.is_optional_of(m_oodt, m_oodt)); } @Test public void check_non_optional_optional_data_type_of_non_optional() throws Exception { assertFalse(Optionality.is_optional_of(m_dt, m_dt)); } @Test public void check_non_optional_optional_data_type_of_optional() throws Exception { assertTrue(Optionality.is_optional_of(m_odt, m_dt)); } @Test public void check_non_optional_optional_data_type_of_deep_optional() throws Exception { assertFalse(Optionality.is_optional_of(m_oodt, m_dt)); } @Test public void check_optional_optional_data_type_of_non_optional() throws Exception { assertFalse(Optionality.is_optional_of(m_dt, m_odt)); } @Test public void check_optional_optional_data_type_of_optional() throws Exception { assertFalse(Optionality.is_optional_of(m_odt, m_odt)); } @Test public void check_optional_optional_data_type_of_deep_optional() throws Exception { assertTrue(Optionality.is_optional_of(m_oodt, m_odt)); } @Test public void check_deep_optional_optional_data_type_of_non_optional() throws Exception { assertFalse(Optionality.is_optional_of(m_dt, m_oodt)); } @Test public void check_deep_optional_optional_data_type_of_optional() throws Exception { assertFalse(Optionality.is_optional_of(m_odt, m_oodt)); }
### Question: Optionality { public static boolean is_deep_optional_of(DataType opt, DataType inner) { Ensure.not_null(opt); Ensure.not_null(inner); if (!(opt instanceof OptionalDataType)) { return false; } OptionalDataType odt = (OptionalDataType) opt; if (odt.inner_type() == inner) { return true; } return is_deep_optional_of(odt.inner_type(), inner); } private Optionality(); static boolean is_optional(DataType dt); static boolean is_optional(DataValue dv); static DataType unoptionalize(DataType dt); static DataType deep_unoptionalize(DataType dt); static DataValue unoptionalize(DataValue dv); static DataValue deep_unoptionalize(DataValue dv); static DataValue optionalize(DataValue v, DataType dt); static boolean is_optional_of(DataType opt, DataType inner); static boolean is_deep_optional_of(DataType opt, DataType inner); }### Answer: @Test public void check_non_optional_deep_optional_data_type_of_non_optional() throws Exception { assertFalse(Optionality.is_deep_optional_of(m_dt, m_dt)); } @Test public void check_non_optional_deep_optional_data_type_of_optional() throws Exception { assertTrue(Optionality.is_deep_optional_of(m_odt, m_dt)); } @Test public void check_non_optional_deep_optional_data_type_of_deep_optional() throws Exception { assertTrue(Optionality.is_deep_optional_of(m_oodt, m_dt)); } @Test public void check_optional_deep_optional_data_type_of_non_optional() throws Exception { assertFalse(Optionality.is_deep_optional_of(m_dt, m_odt)); } @Test public void check_optional_deep_optional_data_type_of_optional() throws Exception { assertFalse(Optionality.is_deep_optional_of(m_odt, m_odt)); } @Test public void check_optional_deep_optional_data_type_of_deep_optional() throws Exception { assertTrue(Optionality.is_deep_optional_of(m_oodt, m_odt)); } @Test public void check_deep_optional_deep_optional_data_type_of_non_optional() throws Exception { assertFalse(Optionality.is_deep_optional_of(m_dt, m_oodt)); } @Test public void check_deep_optional_deep_optional_data_type_of_optional() throws Exception { assertFalse(Optionality.is_deep_optional_of(m_odt, m_oodt)); } @Test public void check_deep_optional_deep_optional_data_type_of_deep_optional() throws Exception { assertFalse(Optionality.is_deep_optional_of(m_oodt, m_oodt)); }
### Question: FileTemplateSetLoader extends TemplateSetLoader { @Override public TemplateSet load() throws IOException { Metadata metadata = loadMetadata(); Map<String, Template> templates = new HashMap<>(); for (String file : metadata.getTemplates()) { templates.put(file, loadTemplate(file)); } try { templates.put(FILE_MAPPING_TEMPLATE_FILENAME, loadTemplate(FILE_MAPPING_TEMPLATE_FILENAME)); } catch (IOException ignored) { } return new TemplateSet(templates, metadata.getVariables()); } FileTemplateSetLoader(File root); @Override TemplateSet load(); File getRoot(); }### Answer: @Test public void load() throws Exception { TemplateSetLoader loader = new FileTemplateSetLoader(tempPath.toFile()); TemplateSet templateSet = loader.load(); assertEquals(1, templateSet.getVariables().size()); assertEquals("name", templateSet.getVariables().get(0).getName()); }
### Question: AllSuperTypes { public static Set<DataType> run(DataType t, boolean itself) { Ensure.not_null(t); Set<DataType> pending = new HashSet<>(); pending.add(t); Set<DataType> result = new HashSet<>(); if (itself) { result.add(t); } while (pending.size() > 0) { DataType dt = pending.iterator().next(); pending.remove(dt); Set<DataType> pending_super = dt.super_types(); result.addAll(pending_super); pending.addAll(pending_super); } return result; } private AllSuperTypes(); static Set<DataType> run(DataType t, boolean itself); }### Answer: @Test public void no_super_types_no_itself() throws Exception { TestDataType t1 = new TestDataType("x"); Set<DataType> r = AllSuperTypes.run(t1, false); assertEquals(0, r.size()); } @Test public void no_super_types_with_itself() throws Exception { TestDataType t1 = new TestDataType("x"); Set<DataType> r = AllSuperTypes.run(t1, true); assertEquals(1, r.size()); assertTrue(r.contains(t1)); } @Test public void one_super_type_no_itself() throws Exception { TestDataType t_x = new TestDataType("x"); TestDataType t_y = new TestDataType("y", t_x); Set<DataType> r = AllSuperTypes.run(t_y, false); assertEquals(1, r.size()); assertTrue(r.contains(t_x)); } @Test public void one_super_type_with_itself() throws Exception { TestDataType t_x = new TestDataType("x"); TestDataType t_y = new TestDataType("y", t_x); Set<DataType> r = AllSuperTypes.run(t_y, true); assertEquals(2, r.size()); assertTrue(r.contains(t_x)); assertTrue(r.contains(t_y)); } @Test public void multiple_super_types_no_itself() throws Exception { TestDataType t_x = new TestDataType("x"); TestDataType t_y = new TestDataType("y", t_x); TestDataType t_z = new TestDataType("z", t_x, t_y); TestDataType t_w = new TestDataType("w"); TestDataType t_v = new TestDataType("v", t_z, t_w); Set<DataType> r = AllSuperTypes.run(t_v, false); assertEquals(4, r.size()); assertTrue(r.contains(t_x)); assertTrue(r.contains(t_y)); assertTrue(r.contains(t_z)); assertTrue(r.contains(t_w)); } @Test public void multiple_super_types_with_itself() throws Exception { TestDataType t_x = new TestDataType("x"); TestDataType t_y = new TestDataType("y", t_x); TestDataType t_z = new TestDataType("z", t_x, t_y); TestDataType t_w = new TestDataType("w"); TestDataType t_v = new TestDataType("v", t_z, t_w); Set<DataType> r = AllSuperTypes.run(t_v, true); assertEquals(5, r.size()); assertTrue(r.contains(t_x)); assertTrue(r.contains(t_y)); assertTrue(r.contains(t_z)); assertTrue(r.contains(t_w)); assertTrue(r.contains(t_v)); }
### Question: CommonLowerSuperTypes { public static Set<DataType> run(DataType t1, DataType t2, boolean include_base) { Ensure.not_null(t1); Ensure.not_null(t2); Set<DataType> super_1 = AllSuperTypes.run(t1, include_base); Set<DataType> super_2 = AllSuperTypes.run(t2, include_base); Set<DataType> common = new HashSet<>(super_1); common.retainAll(super_2); for (DataType t : new HashSet<>(common)) { boolean is_super_of_any = false; for (DataType c : common) { if (t.super_of(c)) { is_super_of_any = true; break; } } if (is_super_of_any) { common.remove(t); } } return common; } private CommonLowerSuperTypes(); static Set<DataType> run(DataType t1, DataType t2, boolean include_base); }### Answer: @Test public void same_type_not_included() throws Exception { TestDataType x = new TestDataType("x"); m_dts.add(x); Set<DataType> r = CommonLowerSuperTypes.run(x, x, false); assertEquals(0, r.size()); } @Test public void same_type_with_included() throws Exception { TestDataType x = new TestDataType("x"); m_dts.add(x); Set<DataType> r = CommonLowerSuperTypes.run(x, x, true); assertEquals(1, r.size()); assertTrue(r.contains(x)); } @Test public void super_and_sub_type_not_included() throws Exception { TestDataType x = new TestDataType("x"); TestDataType y = new TestDataType("y", x); m_dts.add(x); m_dts.add(y); Set<DataType> r = CommonLowerSuperTypes.run(x, y, false); assertEquals(0, r.size()); } @Test public void super_and_sub_type_with_included() throws Exception { TestDataType x = new TestDataType("x"); TestDataType y = new TestDataType("y", x); m_dts.add(x); m_dts.add(y); Set<DataType> r = CommonLowerSuperTypes.run(x, y, true); assertEquals(1, r.size()); assertTrue(r.contains(x)); } @Test public void two_types_with_common_super_type() throws Exception { TestDataType x = new TestDataType("x"); TestDataType y = new TestDataType("y", x); TestDataType z = new TestDataType("z", x); m_dts.add(x); m_dts.add(y); m_dts.add(z); Set<DataType> r = CommonLowerSuperTypes.run(y, z, true); assertEquals(1, r.size()); assertTrue(r.contains(x)); } @Test public void two_types_with_two_common_super_type() throws Exception { TestDataType x = new TestDataType("x"); TestDataType y = new TestDataType("y"); TestDataType z = new TestDataType("z", x, y); TestDataType w = new TestDataType("w", x, y); m_dts.add(x); m_dts.add(y); m_dts.add(z); m_dts.add(w); Set<DataType> r = CommonLowerSuperTypes.run(w, z, true); assertEquals(2, r.size()); assertTrue(r.contains(x)); assertTrue(r.contains(y)); } @Test public void two_types_with_two_common_related_super_types() throws Exception { TestDataType x = new TestDataType("x"); TestDataType y = new TestDataType("y", x); TestDataType z = new TestDataType("z", x, y); TestDataType w = new TestDataType("w", x, y); m_dts.add(x); m_dts.add(y); m_dts.add(z); m_dts.add(w); Set<DataType> r = CommonLowerSuperTypes.run(w, z, true); assertEquals(1, r.size()); assertTrue(r.contains(y)); }
### Question: ApplicationCore { public void startup(String filename) throws Exception { sysConfig = new SystemConfiguration(filename); try { startBackground(); } catch (Exception e) { throw e; } registerWidgets(); } protected ApplicationCore(); static ApplicationCore getInstance(); void startup(String filename); void attach(); void detach(); String getWriteSession(); ArrayList<String> getSessionList(); boolean isAttached(); static void registerWidgets(); IRuntimeAggregator<?> getRuntimeAggregator(); ISystemConfiguration getSystemConfiguration(); ArrayList<String> getViewConfigurations(); ViewConfiguration getViewConfiguration(String name); String getLatestViewConfigurationName(); void saveViewConfiguration(ViewConfiguration config, String name); }### Answer: @Test public void testStartup() throws Exception { assertEquals(instance.isAttached(), true); }
### Question: TypeScope extends Scope<NamedType> { public DataType type(String name) throws AmbiguousNameException { NamedType nt = find(name); if (nt == null) { return null; } return nt.type(); } TypeScope(); DataType type(String name); }### Answer: @Test public void create_find_types() throws Exception { TypeScope ts = new TypeScope(); PrimitiveScope ps = new PrimitiveScope(); ts.add(new NamedType("a", ps.int16())); ts.add(new NamedType("d", ps.int32())); assertEquals(ps.int16(), ts.type("a")); assertEquals(ps.int32(), ts.type("d")); assertNull(ts.type("e")); }
### Question: ValueScope extends Scope<NamedValue> { public DataValue value(String name) throws AmbiguousNameException { Ensure.not_null(name, "name == null"); NamedValue nv = find(name); if (nv == null) { return null; } return nv.value(); } ValueScope(TypeScope types); TypeScope typed_scope(); DataType type(String name); DataValue value(String name); }### Answer: @Test public void create_assign_obtain_values() throws Exception { m_vs.add(new NamedValue("a", m_ps.ascii().make("bar"))); DataValue vl = m_vs.value("a"); assertTrue(vl instanceof AsciiValue); AsciiValue sv = (AsciiValue) vl; assertEquals("bar", sv.value()); } @Test public void obtain_non_existing_value() throws Exception { assertNull(m_vs.value("h")); }
### Question: ValueScope extends Scope<NamedValue> { public TypeScope typed_scope() { return m_types; } ValueScope(TypeScope types); TypeScope typed_scope(); DataType type(String name); DataValue value(String name); }### Answer: @Test public void obtain_typed_scope() throws Exception { assertEquals(m_ts, m_vs.typed_scope()); }
### Question: ListDataType extends CollectionDataType { @Override public boolean is_abstract() { return false; } ListDataType(DataType inner_type, AnyType any); static final String build_list_name(DataType inner); static ListDataType list_of(DataType inner, PrimitiveScope pscope); @Override ListDataValue make(); @Override boolean is_abstract(); }### Answer: @Test public void create_list_type_check_properties() throws Exception { assertEquals("list<b>", m_list_type.name()); assertTrue(m_list_type.sub_of(m_scope.any())); assertFalse(m_list_type.is_abstract()); assertEquals(m_type, m_list_type.inner_type()); }
### Question: ListDataType extends CollectionDataType { @Override public ListDataValue make() { return new ListDataValue(this); } ListDataType(DataType inner_type, AnyType any); static final String build_list_name(DataType inner); static ListDataType list_of(DataType inner, PrimitiveScope pscope); @Override ListDataValue make(); @Override boolean is_abstract(); }### Answer: @Test public void add_wrong_types() throws Exception { try { m_list.add(m_scope.bool().make(true)); fail(); } catch (IllegalArgumentException e) { } try { m_list.add(m_vsuper); fail(); } catch (IllegalArgumentException e) { } } @Test public void add_remove_check_invalid_parameters() throws Exception { try { m_list.add(null); fail(); } catch (IllegalArgumentException e) { } try { m_list.add(m_scope.bool().make(true)); fail(); } catch (IllegalArgumentException e) { } try { m_list.remove(-1); fail(); } catch (IllegalArgumentException e) { } try { m_list.remove(1); fail(); } catch (IllegalArgumentException e) { } try { m_list.get(-1); fail(); } catch (IllegalArgumentException e) { } try { m_list.get(0); fail(); } catch (IllegalArgumentException e) { } try { m_list.contains(null); fail(); } catch (IllegalArgumentException e) { } try { m_list.contains(m_scope.bool().make(true)); fail(); } catch (IllegalArgumentException e) { } try { m_list.index_of(null); fail(); } catch (IllegalArgumentException e) { } try { m_list.index_of(m_scope.bool().make(true)); fail(); } catch (IllegalArgumentException e) { } } @Test public void list_comparison() throws Exception { ListDataValue v = m_list_type.make(); assertTrue(v.equals(m_list)); assertTrue(v.hashCode() == m_list.hashCode()); ListDataValue sup_v = new ListDataType(m_super_type, m_scope.any()).make(); assertFalse(sup_v.equals(m_list)); assertTrue(m_list.add(m_v1)); assertFalse(v.equals(m_list)); assertFalse(v.hashCode() == m_list.hashCode()); assertTrue(m_list.add(m_v2)); assertTrue(v.add(m_v2)); assertFalse(v.equals(m_list)); assertFalse(v.hashCode() == m_list.hashCode()); assertTrue(v.add(m_v1)); assertFalse(v.equals(m_list)); assertFalse(v.hashCode() == m_list.hashCode()); v.remove(0); v.remove(0); assertTrue(v.add(m_v1)); assertTrue(v.add(m_v2)); assertTrue(v.equals(m_list)); assertTrue(v.hashCode() == m_list.hashCode()); assertFalse(m_list.equals((Object) null)); assertFalse(m_list.equals(3)); assertTrue(m_list.equals(m_list)); }
### Question: ApplicationCore { public void attach() { if (!attached) { try { runtimeAgg.start(); attached = true; if (CREATE_MOCK_RAINBOW) { mockRainbow.run(); } } catch (RuntimeAggregatorException ex) { Logger.getLogger(ApplicationCore.class.getName()).log(Level.SEVERE, "Cannot attach to the Rainbow system.", ex); } } } protected ApplicationCore(); static ApplicationCore getInstance(); void startup(String filename); void attach(); void detach(); String getWriteSession(); ArrayList<String> getSessionList(); boolean isAttached(); static void registerWidgets(); IRuntimeAggregator<?> getRuntimeAggregator(); ISystemConfiguration getSystemConfiguration(); ArrayList<String> getViewConfigurations(); ViewConfiguration getViewConfiguration(String name); String getLatestViewConfigurationName(); void saveViewConfiguration(ViewConfiguration config, String name); }### Answer: @Test public void testAttach() { instance.attach(); assertEquals(instance.isAttached(), true); }
### Question: ListDataType extends CollectionDataType { public static ListDataType list_of(DataType inner, PrimitiveScope pscope) { Ensure.not_null(inner); Ensure.not_null(pscope); Ensure.is_true(inner.in_scope(pscope)); DataTypeScope scope = inner.parent_dts(); DataType found = null; try { found = scope.find(build_list_name(inner)); } catch (AmbiguousNameException e) { } if (found == null) { found = new ListDataType(inner, pscope.any()); scope.add(found); } Ensure.not_null(found); Ensure.is_instance(found, ListDataType.class); return (ListDataType) found; } ListDataType(DataType inner_type, AnyType any); static final String build_list_name(DataType inner); static ListDataType list_of(DataType inner, PrimitiveScope pscope); @Override ListDataValue make(); @Override boolean is_abstract(); }### Answer: @Test public void obtaining_existing_data_type() throws Exception { ListDataType t = ListDataType.list_of(m_type, m_scope); assertSame(m_list_type, t); } @Test public void obtaining_new_data_type() throws Exception { ListDataType t1 = ListDataType.list_of(m_scope.int8(), m_scope); assertSame(t1, ListDataType.list_of(m_scope.int8(), m_scope)); }
### Question: BagDataType extends CollectionDataType { @Override public boolean is_abstract() { return false; } BagDataType(DataType inner_type, AnyType any); static final String build_bag_name(DataType inner); static BagDataType bag_of(DataType inner, PrimitiveScope pscope); @Override BagDataValue make(); @Override boolean is_abstract(); }### Answer: @Test public void create_bag_type_check_properties() throws Exception { assertEquals("bag<b>", m_bag_type.name()); assertTrue(m_bag_type.sub_of(m_scope.any())); assertFalse(m_bag_type.is_abstract()); assertEquals(m_type, m_bag_type.inner_type()); }
### Question: BagDataType extends CollectionDataType { @Override public BagDataValue make() { return new BagDataValue(this); } BagDataType(DataType inner_type, AnyType any); static final String build_bag_name(DataType inner); static BagDataType bag_of(DataType inner, PrimitiveScope pscope); @Override BagDataValue make(); @Override boolean is_abstract(); }### Answer: @Test(expected = IllegalArgumentException.class) public void add_wrong_types() throws Exception { assertTrue(m_bag.add(m_scope.bool().make(true))); } @Test(expected = IllegalArgumentException.class) public void remove_wrong_type_fails() throws Exception { m_bag.remove(m_scope.bool().make(true)); } @Test(expected = IllegalArgumentException.class) public void contains_wrong_type_fails() throws Exception { m_bag.contains(m_scope.bool().make(true)); } @Test(expected = IllegalArgumentException.class) public void count_wrong_type_fails() throws Exception { m_bag.count(m_scope.bool().make(true)); } @Test public void bag_comparison() throws Exception { BagDataValue v = m_bag_type.make(); assertTrue(v.equals(m_bag)); assertTrue(v.hashCode() == m_bag.hashCode()); BagDataValue sup_v = new BagDataType(m_super_type, m_scope.any()).make(); assertFalse(sup_v.equals(m_bag)); assertTrue(m_bag.add(m_v1)); assertFalse(v.equals(m_bag)); assertFalse(v.hashCode() == m_bag.hashCode()); assertTrue(m_bag.add(m_v2)); v.add(m_v2); assertFalse(v.equals(m_bag)); assertFalse(v.hashCode() == m_bag.hashCode()); assertTrue(v.add(m_v1)); assertTrue(v.equals(m_bag)); assertTrue(v.hashCode() == m_bag.hashCode()); assertTrue(v.add(m_v1)); assertFalse(v.equals(m_bag)); assertFalse(v.hashCode() == m_bag.hashCode()); assertTrue(m_bag.add(m_v1)); assertTrue(v.equals(m_bag)); assertTrue(v.hashCode() == m_bag.hashCode()); assertFalse(m_bag.equals((Object) null)); assertFalse(m_bag.equals(3)); assertTrue(m_bag.equals(m_bag)); }
### Question: BagDataType extends CollectionDataType { public static BagDataType bag_of(DataType inner, PrimitiveScope pscope) { Ensure.not_null(inner); Ensure.not_null(pscope); Ensure.is_true(inner.in_scope(pscope)); DataTypeScope scope = inner.parent_dts(); DataType found = null; try { found = scope.find(build_bag_name(inner)); } catch (AmbiguousNameException e) { } if (found == null) { found = new BagDataType(inner, pscope.any()); scope.add(found); } Ensure.not_null(found); Ensure.is_instance(found, BagDataType.class); return (BagDataType) found; } BagDataType(DataType inner_type, AnyType any); static final String build_bag_name(DataType inner); static BagDataType bag_of(DataType inner, PrimitiveScope pscope); @Override BagDataValue make(); @Override boolean is_abstract(); }### Answer: @Test public void obtaining_existing_data_type() throws Exception { BagDataType t = BagDataType.bag_of(m_type, m_scope); assertSame(m_bag_type, t); } @Test public void obtaining_new_data_type() throws Exception { BagDataType t1 = BagDataType.bag_of(m_scope.int8(), m_scope); assertSame(t1, BagDataType.bag_of(m_scope.int8(), m_scope)); }
### Question: ApplicationCore { public void detach() { if (attached) { runtimeAgg.stop(); attached = false; if (CREATE_MOCK_RAINBOW) { mockRainbow.cancel(); } } } protected ApplicationCore(); static ApplicationCore getInstance(); void startup(String filename); void attach(); void detach(); String getWriteSession(); ArrayList<String> getSessionList(); boolean isAttached(); static void registerWidgets(); IRuntimeAggregator<?> getRuntimeAggregator(); ISystemConfiguration getSystemConfiguration(); ArrayList<String> getViewConfigurations(); ViewConfiguration getViewConfiguration(String name); String getLatestViewConfigurationName(); void saveViewConfiguration(ViewConfiguration config, String name); }### Answer: @Test public void testDetach() { instance.detach(); assertEquals(instance.isAttached(), false); }
### Question: SetDataType extends CollectionDataType { @Override public boolean is_abstract() { return false; } SetDataType(DataType inner_type, AnyType any); static final String build_set_name(DataType inner); static SetDataType set_of(DataType inner, PrimitiveScope pscope); @Override SetDataValue make(); @Override boolean is_abstract(); }### Answer: @Test public void create_set_type_check_properties() throws Exception { assertEquals("set<b>", m_set_type.name()); assertTrue(m_set_type.sub_of(m_scope.any())); assertFalse(m_set_type.is_abstract()); assertEquals(m_type, m_set_type.inner_type()); }
### Question: SetDataType extends CollectionDataType { @Override public SetDataValue make() { return new SetDataValue(this); } SetDataType(DataType inner_type, AnyType any); static final String build_set_name(DataType inner); static SetDataType set_of(DataType inner, PrimitiveScope pscope); @Override SetDataValue make(); @Override boolean is_abstract(); }### Answer: @Test public void add_wrong_types() throws Exception { try { m_set.add(m_scope.bool().make(true)); fail(); } catch (IllegalArgumentException e) { } try { m_set.add(m_vsuper); fail(); } catch (IllegalArgumentException e) { } } @Test public void add_remove_check_invalid_parameters() throws Exception { try { m_set.add(null); fail(); } catch (IllegalArgumentException e) { } try { m_set.add(m_scope.bool().make(true)); fail(); } catch (IllegalArgumentException e) { } try { m_set.remove(null); fail(); } catch (IllegalArgumentException e) { } try { m_set.remove(m_scope.bool().make(true)); fail(); } catch (IllegalArgumentException e) { } try { m_set.contains(null); fail(); } catch (IllegalArgumentException e) { } try { m_set.contains(m_scope.bool().make(true)); fail(); } catch (IllegalArgumentException e) { } } @Test public void set_comparison() throws Exception { SetDataValue v = m_set_type.make(); assertTrue(v.equals(m_set)); assertTrue(v.hashCode() == m_set.hashCode()); SetDataValue sup_v = new SetDataType(m_super_type, m_scope.any()).make(); assertFalse(sup_v.equals(m_set)); m_set.add(m_v1); assertFalse(v.equals(m_set)); assertFalse(v.hashCode() == m_set.hashCode()); m_set.add(m_v2); v.add(m_v2); assertFalse(v.equals(m_set)); assertFalse(v.hashCode() == m_set.hashCode()); v.add(m_v1); assertTrue(v.equals(m_set)); assertTrue(v.hashCode() == m_set.hashCode()); assertFalse(m_set.equals((Object) null)); assertFalse(m_set.equals(3)); assertTrue(m_set.equals(m_set)); }
### Question: SetDataType extends CollectionDataType { public static SetDataType set_of(DataType inner, PrimitiveScope pscope) { Ensure.not_null(inner); Ensure.not_null(pscope); Ensure.is_true(inner.in_scope(pscope)); DataTypeScope scope = inner.parent_dts(); DataType found = null; try { found = scope.find(build_set_name(inner)); } catch (AmbiguousNameException e) { } if (found == null) { found = new SetDataType(inner, pscope.any()); scope.add(found); } Ensure.not_null(found); Ensure.is_instance(found, SetDataType.class); return (SetDataType) found; } SetDataType(DataType inner_type, AnyType any); static final String build_set_name(DataType inner); static SetDataType set_of(DataType inner, PrimitiveScope pscope); @Override SetDataValue make(); @Override boolean is_abstract(); }### Answer: @Test public void obtaining_existing_data_type() throws Exception { SetDataType t = SetDataType.set_of(m_type, m_scope); assertSame(m_set_type, t); } @Test public void obtaining_new_data_type() throws Exception { SetDataType t1 = SetDataType.set_of(m_scope.int8(), m_scope); assertSame(t1, SetDataType.set_of(m_scope.int8(), m_scope)); }
### Question: HierarchicalName { public HierarchicalName make_absolute() { Ensure.is_false(m_is_absolute); return new HierarchicalName(true, m_names); } HierarchicalName(boolean absolute, List<String> names); HierarchicalName(boolean absolute, String... names); boolean absolute(); String peek(); HierarchicalName pop_first(); boolean leaf(); HierarchicalName push(String name); HierarchicalName make_absolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test(expected = AssertionError.class) public void making_absolute_absolute() throws Exception { HierarchicalName hn = new HierarchicalName(true, "foo"); hn.make_absolute(); }
### Question: HierarchicalName { @Override public String toString() { StringBuilder sb = new StringBuilder(); if (m_is_absolute) { sb.append("::"); } for (int i = 0; i < m_names.size(); i++) { if (i > 0) { sb.append("::"); } sb.append(m_names.get(i)); } return sb.toString(); } HierarchicalName(boolean absolute, List<String> names); HierarchicalName(boolean absolute, String... names); boolean absolute(); String peek(); HierarchicalName pop_first(); boolean leaf(); HierarchicalName push(String name); HierarchicalName make_absolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void hierarchical_name_as_string() throws Exception { HierarchicalName hn1 = new HierarchicalName(true, "a"); assertEquals("::a", hn1.toString()); HierarchicalName hn2 = new HierarchicalName(true, "a", "b"); assertEquals("::a::b", hn2.toString()); HierarchicalName hn3 = new HierarchicalName(false, "a"); assertEquals("a", hn3.toString()); HierarchicalName hn4 = new HierarchicalName(false, "a", "b"); assertEquals("a::b", hn4.toString()); }
### Question: HierarchicalName { @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof HierarchicalName)) { return false; } HierarchicalName hn = (HierarchicalName) obj; return hn.m_is_absolute == m_is_absolute && hn.m_names.equals(m_names); } HierarchicalName(boolean absolute, List<String> names); HierarchicalName(boolean absolute, String... names); boolean absolute(); String peek(); HierarchicalName pop_first(); boolean leaf(); HierarchicalName push(String name); HierarchicalName make_absolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void compare_to_invalid() throws Exception { HierarchicalName hn = new HierarchicalName(false, "foo"); assertFalse(hn.equals((Object) null)); assertFalse(hn.equals(23)); }
### Question: ApplicationCore { public ArrayList<String> getSessionList() { return databaseCon.getSessionList(); } protected ApplicationCore(); static ApplicationCore getInstance(); void startup(String filename); void attach(); void detach(); String getWriteSession(); ArrayList<String> getSessionList(); boolean isAttached(); static void registerWidgets(); IRuntimeAggregator<?> getRuntimeAggregator(); ISystemConfiguration getSystemConfiguration(); ArrayList<String> getViewConfigurations(); ViewConfiguration getViewConfiguration(String name); String getLatestViewConfigurationName(); void saveViewConfiguration(ViewConfiguration config, String name); }### Answer: @Test public void testGetSessionList() { ArrayList<String> result = instance.getSessionList(); assertNotNull(result); }
### Question: Scope { public synchronized final void add(Scope<T> scope) { Ensure.not_null(scope); Ensure.is_null(scope.m_parent); Ensure.not_null(scope.m_name); if (m_objects.get(scope.m_name) != null) { throw new IllegalStateException("Scope already has an object " + "named '" + scope.m_name + "'."); } if (m_sub_scopes.get(scope.m_name) != null) { throw new IllegalStateException("Scope already has a sub scope " + "named '" + scope.m_name + "'."); } check_add(scope); m_sub_scopes.put(scope.m_name, scope); scope.m_parent = this; } Scope(String name); final String name(); final Scope<T> parent(); final HierarchicalName absolute_hname(); synchronized final void add(Scope<T> scope); synchronized final void add(T obj); synchronized T find(String name); synchronized Scope<T> find_scope(String name); synchronized T find(HierarchicalName hn); synchronized Scope<T> find_scope(HierarchicalName hn); synchronized Set<T> all(); synchronized final void link(Scope<T> scope); synchronized Set<T> all_recursive(); synchronized boolean child_scope_of(Scope<?> scope); static Scope<?> common_inner_most_parent_scope( Set<? extends Scope<?>> scopes); }### Answer: @Test(expected = AssertionError.class) public void global_scopes_cannot_be_added_to_other_scopes() throws Exception { TestScope gs = new TestScope(); TestScope gs2 = new TestScope(); gs.add(gs2); } @Test public void adding_duplicate_objects_in_scope() throws Exception { TestScope s = new TestScope(); s.add(new ScopedObject("s1")); s.add(new Scope<>("s2")); try { s.add(new ScopedObject("s1")); fail(); } catch (IllegalStateException e) { } try { s.add(new TestScope("s1")); fail(); } catch (IllegalStateException e) { } try { s.add(new ScopedObject("s2")); fail(); } catch (IllegalStateException e) { } try { s.add(new TestScope("s2")); fail(); } catch (IllegalStateException e) { } } @Test(expected = AssertionError.class) public void adding_null_scope_to_scope() throws Exception { TestScope s = new TestScope(); s.add((TestScope) null); } @Test(expected = AssertionError.class) public void adding_null_scoped_object_to_scope() throws Exception { TestScope s = new TestScope(); s.add((ScopedObject) null); } @Test public void check_object_in_its_own_scope() throws Exception { TestScope s0 = new TestScope(); ScopedObject o0 = new ScopedObject("x"); s0.add(o0); assertTrue(o0.in_scope(s0)); } @Test public void check_object_in_its_parent_scope() throws Exception { TestScope s0 = new TestScope(); TestScope s1 = new TestScope("s"); s0.add(s1); ScopedObject o1 = new ScopedObject("x"); s1.add(o1); assertTrue(o1.in_scope(s0)); } @Test public void check_object_not_in_sub_scope() throws Exception { TestScope s0 = new TestScope(); TestScope s1 = new TestScope("s"); s0.add(s1); ScopedObject o0 = new ScopedObject("x"); s0.add(o0); assertFalse(o0.in_scope(s1)); }
### Question: Scope { public synchronized final void link(Scope<T> scope) throws CyclicScopeLinkageException { Ensure.not_null(scope); Ensure.is_false(m_linked.contains(scope)); Set<Scope<T>> current = new HashSet<>(); current.addAll(m_linked); current.add(scope); Set<Scope<T>> seen = new HashSet<>(current); do { current = follow_set(current); if (current.contains(this)) { throw new CyclicScopeLinkageException("Scope '" + m_name + "' would be in a cyclic linkage graph if linked " + "with scope '" + scope.m_name + "'."); } current.removeAll(seen); seen.addAll(current); } while (current.size() > 0); check_link(scope); m_linked.add(scope); } Scope(String name); final String name(); final Scope<T> parent(); final HierarchicalName absolute_hname(); synchronized final void add(Scope<T> scope); synchronized final void add(T obj); synchronized T find(String name); synchronized Scope<T> find_scope(String name); synchronized T find(HierarchicalName hn); synchronized Scope<T> find_scope(HierarchicalName hn); synchronized Set<T> all(); synchronized final void link(Scope<T> scope); synchronized Set<T> all_recursive(); synchronized boolean child_scope_of(Scope<?> scope); static Scope<?> common_inner_most_parent_scope( Set<? extends Scope<?>> scopes); }### Answer: @Test public void creating_cyclic_linkage_structures() throws Exception { TestScope s1 = new TestScope(); TestScope s2 = new TestScope(); TestScope s3 = new TestScope(); s1.link(s2); s3.link(s1); try { s2.link(s1); fail(); } catch (CyclicScopeLinkageException e) { } try { s2.link(s3); fail(); } catch (CyclicScopeLinkageException e) { } } @Test(expected = AssertionError.class) public void linking_null_scope() throws Exception { TestScope s = new TestScope(); s.link(null); } @Test(expected = AssertionError.class) public void linking_same_scope_twice() throws Exception { TestScope s1 = new TestScope(); TestScope l = new TestScope(); s1.link(l); s1.link(l); }
### Question: Scope { public synchronized T find(String name) throws AmbiguousNameException { return find(new HierarchicalName(false, name)); } Scope(String name); final String name(); final Scope<T> parent(); final HierarchicalName absolute_hname(); synchronized final void add(Scope<T> scope); synchronized final void add(T obj); synchronized T find(String name); synchronized Scope<T> find_scope(String name); synchronized T find(HierarchicalName hn); synchronized Scope<T> find_scope(HierarchicalName hn); synchronized Set<T> all(); synchronized final void link(Scope<T> scope); synchronized Set<T> all_recursive(); synchronized boolean child_scope_of(Scope<?> scope); static Scope<?> common_inner_most_parent_scope( Set<? extends Scope<?>> scopes); }### Answer: @Test(expected = AssertionError.class) public void finding_object_with_null_string() throws Exception { TestScope s = new TestScope(); s.find((String) null); } @Test(expected = AssertionError.class) public void finding_object_with_null_hierarchical_name() throws Exception { TestScope s = new TestScope(); s.find((HierarchicalName) null); }
### Question: Scope { public synchronized Scope<T> find_scope(String name) throws AmbiguousNameException { return find_scope(new HierarchicalName(false, name)); } Scope(String name); final String name(); final Scope<T> parent(); final HierarchicalName absolute_hname(); synchronized final void add(Scope<T> scope); synchronized final void add(T obj); synchronized T find(String name); synchronized Scope<T> find_scope(String name); synchronized T find(HierarchicalName hn); synchronized Scope<T> find_scope(HierarchicalName hn); synchronized Set<T> all(); synchronized final void link(Scope<T> scope); synchronized Set<T> all_recursive(); synchronized boolean child_scope_of(Scope<?> scope); static Scope<?> common_inner_most_parent_scope( Set<? extends Scope<?>> scopes); }### Answer: @Test(expected = AssertionError.class) public void finding_scope_with_null_string() throws Exception { TestScope s = new TestScope(); s.find_scope((String) null); } @Test(expected = AssertionError.class) public void finding_scope_with_null_hierarchical_name() throws Exception { TestScope s = new TestScope(); s.find_scope((HierarchicalName) null); }
### Question: ApplicationCore { public boolean isAttached() { return attached; } protected ApplicationCore(); static ApplicationCore getInstance(); void startup(String filename); void attach(); void detach(); String getWriteSession(); ArrayList<String> getSessionList(); boolean isAttached(); static void registerWidgets(); IRuntimeAggregator<?> getRuntimeAggregator(); ISystemConfiguration getSystemConfiguration(); ArrayList<String> getViewConfigurations(); ViewConfiguration getViewConfiguration(String name); String getLatestViewConfigurationName(); void saveViewConfiguration(ViewConfiguration config, String name); }### Answer: @Test public void testIsAttached() { boolean expResult = true; instance.attach(); boolean result = instance.isAttached(); assertEquals(expResult, result); }
### Question: Scope { public synchronized boolean child_scope_of(Scope<?> scope) { Ensure.not_null(scope); for (Scope<?> p = m_parent; p != null; p = p.m_parent) { if (p == scope) { return true; } } return false; } Scope(String name); final String name(); final Scope<T> parent(); final HierarchicalName absolute_hname(); synchronized final void add(Scope<T> scope); synchronized final void add(T obj); synchronized T find(String name); synchronized Scope<T> find_scope(String name); synchronized T find(HierarchicalName hn); synchronized Scope<T> find_scope(HierarchicalName hn); synchronized Set<T> all(); synchronized final void link(Scope<T> scope); synchronized Set<T> all_recursive(); synchronized boolean child_scope_of(Scope<?> scope); static Scope<?> common_inner_most_parent_scope( Set<? extends Scope<?>> scopes); }### Answer: @Test public void self_child_check_test() throws Exception { TestScope s0 = new TestScope(); assertFalse(s0.child_scope_of(s0)); }
### Question: SyncScbSlave { public synchronized void sync_now_wait() { int prev_count = m_sync_count; do { sync_now(); try { wait(WAIT_FOR_SYNC_TIME_MS); } catch (InterruptedException e) { } } while (m_sync_count == prev_count); } SyncScbSlave(SyncScbMaster master, long poll_interval_ms); synchronized Date last_sync_date(); synchronized void sync_now(); synchronized void sync_now_wait(); synchronized SyncSlaveState state(); synchronized void add_container(String key, ScbEditableContainer<T> container, Class<ID_TYPE> idclass, Class<T> tclass); void shutdown(); }### Answer: @Test public void local_changes_are_propagated_to_server_and_back() throws Exception { m_slave.sync_now_wait(); TestSyncScb s = new TestSyncScb(0, SyncStatus.UNKNOWN, "foo"); m_c0.add_scb(s); m_dispatcher_helper.wait_dispatch_clear(); assertEquals(1, m_c0.all_scbs().size()); assertEquals(SyncStatus.LOCAL_CHANGES, s.sync_status()); assertEquals(0, m_m0.all_scbs().size()); m_slave.sync_now_wait(); m_dispatcher_helper.wait_dispatch_clear(); assertEquals(1, m_m0.all_scbs().size()); assertEquals(1, m_c0.all_scbs().size()); assertEquals(SyncStatus.SYNCHRONIZED, s.sync_status()); assertEquals("foo", s.data()); TestSyncScb ss = m_m0.all_scbs().iterator().next(); assertEquals(SyncStatus.MASTER, ss.sync_status()); assertEquals("foo", ss.data()); s.data("bar"); m_dispatcher_helper.wait_dispatch_clear(); assertEquals(1, m_c0.all_scbs().size()); assertEquals(1, m_m0.all_scbs().size()); assertTrue(m_c0.all_scbs().contains(s)); assertTrue(m_m0.all_scbs().contains(ss)); assertEquals(SyncStatus.LOCAL_CHANGES, s.sync_status()); assertEquals(SyncStatus.MASTER, ss.sync_status()); assertEquals("bar", s.data()); assertEquals("foo", ss.data()); m_slave.sync_now_wait(); m_dispatcher_helper.wait_dispatch_clear(); assertEquals(1, m_c0.all_scbs().size()); assertEquals(1, m_m0.all_scbs().size()); assertTrue(m_c0.all_scbs().contains(s)); assertTrue(m_m0.all_scbs().contains(ss)); assertEquals(SyncStatus.SYNCHRONIZED, s.sync_status()); assertEquals(SyncStatus.MASTER, ss.sync_status()); assertEquals("bar", s.data()); assertEquals("bar", ss.data()); m_c0.remove_scb(s); m_dispatcher_helper.wait_dispatch_clear(); assertEquals(0, m_c0.all_scbs().size()); assertEquals(1, m_m0.all_scbs().size()); assertTrue(m_m0.all_scbs().contains(ss)); assertEquals(SyncStatus.MASTER, ss.sync_status()); assertEquals("bar", ss.data()); m_slave.sync_now_wait(); m_dispatcher_helper.wait_dispatch_clear(); assertEquals(0, m_c0.all_scbs().size()); assertEquals(0, m_m0.all_scbs().size()); }
### Question: RmiServerPublisher { public static int publish_service(Class<?> cls, Object obj) throws RmiCommException { return publish_service(cls, obj, 0); } static int publish_service(Class<?> cls, Object obj); static int publish_service(Class<?> cls, Object obj, int port); static void shutdown_all(); }### Answer: @Test(expected = IllegalArgumentException.class) public void publish_null_object() throws Exception { RmiServerPublisher.publish_service(TService.class, null); RmiServerPublisher.publish_service(null, new TService()); } @Test(expected = IllegalArgumentException.class) public void publish_null_interface() throws Exception { RmiServerPublisher.publish_service(null, new TService()); } @Test public void publish_respects_communication_ports() throws Exception { int cnt = 5; for (int i = 0; i < cnt; i++) { TService ts = new TService(); ts.m_val = i; String pp = RmiCommunicationPorts.class.getName(); int rnd = 14000 + RandomUtils.nextInt(2000); System.setProperty(pp + ".min-port", "" + rnd); System.setProperty(pp + ".max-port", "" + (rnd + 5)); int p = RmiServerPublisher.publish_service(TServiceI.class, ts); assertEquals(rnd, p); Client c = new Client("localhost", rnd); Object obj = c.lookup(TServiceI.class); assertNotNull(obj); assertTrue(obj instanceof TServiceI); } } @Test public void publish_on_specific_port() throws Exception { final int iterationCount = 100; final int minAllowOk = 80; int done = 0; for (int i = 0; i < iterationCount; i++) { int p = 1025 + RandomUtils.nextInt(10000); try (Socket s = new Socket()) { s.connect(new InetSocketAddress(InetAddress.getLocalHost(), p), 50); continue; } catch (ConnectException|SocketTimeoutException e) { } done++; TService ts = new TService(); int pp = RmiServerPublisher.publish_service(TServiceI.class, ts, p); assertEquals(p, pp); try (Socket s = new Socket("localhost", p)) { } } assertTrue(done >= minAllowOk); }
### Question: AcmeGraph extends AcmeModelView { @Override protected void subUpdate() { IAcmeSystem newSystem = (IAcmeSystem) ModelHelper .getElementFromQualifiedName(model, currentSystem.getQualifiedName()); if (newSystem != null) { currentSystem = newSystem; } else { currentSystem = model; Logger.getLogger(AcmeGraph.class.getName()).log(Level.INFO, "The system {0} doesn''t exists. " + "Switch to top-level system.", currentSystem.getQualifiedName()); } Graph graph = createGraph(); graphLayer.setGraph(graph); } AcmeGraph(AbstractRainbowVaadinUI ui); IAcmeSystem getCurrentSystem(); void setCurrentSystem(IAcmeSystem system); void resetGraph(); }### Answer: @Test public void testSubUpdate() throws Exception { System.out.println("subUpdate"); AcmeGraph instance = new AcmeGraph(dummyUI); instance.update(); Graph graph = instance.getGraphLayer().getGraph(); Node server0 = graph.nodes.get("ZNewsSys.Server0"); assertNotNull(server0); Node server1 = graph.nodes.get("ZNewsSys.Server1"); assertNotNull(server1); String port = server0.ports.get(0); assertEquals("ZNewsSys.Server0.http0", port); Node connector = graph.nodes.get("ZNewsSys.httpConn_0_0"); assertNotNull(connector); Edge attachment = graph.edges.get("ZNewsSys.Client1.p0 to httpConn_0_0.req"); assertNotNull(attachment); }
### Question: RmiClientDiscovery { public static void find_open_ports(String host, int min_port, int max_port, PortFoundListener listener, PortScanListener scan_listener) { if (host == null) { throw new IllegalArgumentException("host == null"); } if (listener == null) { throw new IllegalArgumentException("listener == null"); } if (min_port <= 0) { throw new IllegalArgumentException("minPort <= 0"); } if (max_port < min_port) { throw new IllegalArgumentException("maxPort < minPort"); } for (int i = min_port; i <= max_port; i++) { try (Socket s = new Socket()) { s.connect(new InetSocketAddress(host, i), MAX_WAIT_OPEN_MS); if (scan_listener != null) { scan_listener.port_scanned(i); } s.close(); listener.port_found(i); } catch (IOException e) { if (scan_listener != null) { scan_listener.port_scanned(i); } } } } static void find_open_ports(String host, int min_port, int max_port, PortFoundListener listener, PortScanListener scan_listener); static T find_rmi_client(String host, int port, Class<T> iface); static void find_rmi_client(final String host, int min_port, int max_port, final Class<?> iface, final ClientFoundListener listener, PortScanListener scan_listener); static void find_rmi_client(String host, Class<?> iface, ClientFoundListener listener, PortScanListener scan_listener); }### Answer: @Test public void find_open_ports_with_no_open() throws Exception { generate_port_spawn(10); PortListener pl = new PortListener(); ScanListener sl = new ScanListener(); RmiClientDiscovery.find_open_ports("localhost", m_pmin, m_pmax, pl, sl); assertEquals(0, pl.m_ports.length); assertEquals(10, sl.m_count); assertEquals(m_pmin, sl.m_min); assertEquals(m_pmax, sl.m_max); } @Test public void find_open_ports_with_random_open() throws Exception { generate_port_spawn(10); PortListener pl = new PortListener(); ScanListener sl = new ScanListener(); open_random_ports(1, 3, m_pmin - 5, m_pmin - 1); open_random_ports(1, 3, m_pmax + 1, m_pmax + 5); int inside[] = open_random_ports(1, 5, m_pmin, m_pmax); RmiClientDiscovery.find_open_ports("localhost", m_pmin, m_pmax, pl, sl); assertEquals(inside.length, pl.m_ports.length); assertEquals(10, sl.m_count); assertEquals(m_pmin, sl.m_min); assertEquals(m_pmax, sl.m_max); }
### Question: WorkerThreadGroup implements WorkerThreadGroupCI { public synchronized void add_subgroup(WorkerThreadGroup wtg) { Ensure.not_null(wtg, "wtg == null"); Ensure.is_true(wtg != this, "wtg == this"); Ensure.is_false(m_subgroups.contains(wtg), "m_subgroups.contains(wtg)"); Ensure.is_false(wtg.all_subgroups().contains(this), "wtg.all_subgroups().contains(this)"); m_subgroups.add(wtg); } WorkerThreadGroup(String name); @Override synchronized String name(); @Override synchronized String description(); synchronized void description(String d); @Override synchronized Set<WorkerThreadCI> threads(); @Override synchronized void start(); @Override synchronized void stop(); synchronized void add_thread(WorkerThread wt); synchronized void remove_thread(WorkerThread wt); synchronized void add_subgroup(WorkerThreadGroup wtg); synchronized void remove_subgroup(WorkerThreadGroup wtg); @Override synchronized Set<WorkerThreadGroupCI> direct_subgroups(); @Override Set<WorkerThreadGroupCI> all_subgroups(); @Override void start_all(); @Override void stop_all(); }### Answer: @Test public void building_cyclic_thread_group_hierarchies() throws Exception { WorkerThreadGroup wtg1 = new WorkerThreadGroup("g1"); WorkerThreadGroup wtg2 = new WorkerThreadGroup("g2"); WorkerThreadGroup wtg3 = new WorkerThreadGroup("g3"); wtg1.add_subgroup(wtg2); wtg2.add_subgroup(wtg3); boolean fail = false; try { wtg3.add_subgroup(wtg1); fail = true; } catch (AssertionError e) { } if (fail) { fail(); } }
### Question: WorkerThread implements WorkerThreadCI { @Override public final synchronized void stop() { Ensure.is_true(m_state == WtState.RUNNING, "w_state != WtState.RUNNING"); if (Thread.currentThread() == m_thread) { throw new ClosingWorkerThreadFromWithinException(); } m_state = WtState.STOPPING; fire_state_changed(); Thread t = m_thread; while (t.isAlive()) { try { interrupt_wait(); wait(THREAD_STATE_POLL_TIME_MS); } catch (InterruptedException e) { } } if (m_thread != null) { m_state = WtState.STOPPED; fire_state_changed(); m_thread = null; } else { assert m_state == WtState.ABORTED; } } WorkerThread(String name); void add_listener(WorkerThreadListener l); void remove_listener(WorkerThreadListener l); @Override String name(); @Override synchronized String description(); @Override synchronized ThrowableCollector collector(); @Override final synchronized WtState state(); @Override final synchronized void start(); @Override final synchronized void stop(); }### Answer: @Test(expected = AssertionError.class) public void stop_thread_before_starting() throws Exception { WorkerThread wt = new WorkerThread("x"); wt.stop(); }
### Question: WorkerThread implements WorkerThreadCI { @Override public String name() { return m_name; } WorkerThread(String name); void add_listener(WorkerThreadListener l); void remove_listener(WorkerThreadListener l); @Override String name(); @Override synchronized String description(); @Override synchronized ThrowableCollector collector(); @Override final synchronized WtState state(); @Override final synchronized void start(); @Override final synchronized void stop(); }### Answer: @Test public void enumeration_checks() { WtState[] states = WtState.values(); for (WtState s : states) { WtState.valueOf(s.name()); } }
### Question: AcmeGraph extends AcmeModelView { public IAcmeSystem getCurrentSystem() { return currentSystem; } AcmeGraph(AbstractRainbowVaadinUI ui); IAcmeSystem getCurrentSystem(); void setCurrentSystem(IAcmeSystem system); void resetGraph(); }### Answer: @Test public void testRootComponent() throws Exception { System.out.println("get/set RootComponent"); AcmeGraph instance = new AcmeGraph(dummyUI); String expResult = "ZNewsSys"; IAcmeSystem result = instance.getCurrentSystem(); assertNotNull(result); assertEquals(expResult, result.getName()); }
### Question: CloseableWorkerThread extends WorkerThread implements Closeable { @Override public synchronized void close() throws IOException { if (m_closeable == null) { return; } T t = m_closeable; m_closeable = null; if (state() == WtState.RUNNING) { thread().interrupt(); } try { t.close(); } finally { m_dispatcher.dispatch(new DispatcherOp<CloseableListener>() { @Override public void dispatch(CloseableListener l) { l.closed(null); } }); } } CloseableWorkerThread(String name, T closeable, boolean close_on_abort); synchronized void add_listener(CloseableListener l); synchronized void remove_listener(CloseableListener l); @Override synchronized void close(); synchronized boolean closed(); }### Answer: @SuppressWarnings("javadoc") @Test public void starting_after_closed() throws Exception { try ( PipedInputStream pis = new PipedInputStream(15); PipedOutputStream pos = new PipedOutputStream(pis); CloseableWorkerThread<PipedInputStream> cwt = new CloseableWorkerThread<PipedInputStream>("y", pis, false) { @Override protected void do_cycle_operation( PipedInputStream closeable) throws Exception { if (closeable.read() == -1) { throw new EOFException(); } } }) { cwt.start(); assertEquals(WtState.RUNNING, cwt.state()); Thread.sleep(250); assertEquals(WtState.RUNNING, cwt.state()); cwt.close(); Thread.sleep(250); assertEquals(WtState.ABORTED, cwt.state()); cwt.start(); assertEquals(WtState.RUNNING, cwt.state()); Thread.sleep(250); assertEquals(WtState.RUNNING, cwt.state()); cwt.stop(); assertEquals(WtState.STOPPED, cwt.state()); } }
### Question: CloseableWorkerThread extends WorkerThread implements Closeable { public synchronized boolean closed() { return m_closeable == null; } CloseableWorkerThread(String name, T closeable, boolean close_on_abort); synchronized void add_listener(CloseableListener l); synchronized void remove_listener(CloseableListener l); @Override synchronized void close(); synchronized boolean closed(); }### Answer: @SuppressWarnings("javadoc") @Test public void closing_all_in_a_group() throws Exception { WorkerThreadGroup wtg1 = new WorkerThreadGroup("g1"); WorkerThreadGroup wtg2 = new WorkerThreadGroup("g2"); wtg1.add_subgroup(wtg2); WorkerThread t1 = new WorkerThread("t1"); WorkerThread t2 = new WorkerThread("t1"); WorkerThread t3 = new WorkerThread("t1"); wtg1.add_thread(t1); wtg1.add_thread(t3); wtg2.add_thread(t2); wtg2.add_thread(t3); class MyCT extends CloseableWorkerThread<TestCloseable> { public MyCT(String name, TestCloseable closeable) { super(name, closeable, false); } @Override protected void do_cycle_operation(TestCloseable closeable) throws Exception { synchronized (this) { wait(); } } } try ( TestCloseable c1 = new TestCloseable(); TestCloseable c2 = new TestCloseable(); TestCloseable c3 = new TestCloseable()){ MyCT ct1 = new MyCT("ct1", c1); MyCT ct2 = new MyCT("ct1", c2); MyCT ct3 = new MyCT("ct1", c3); wtg1.add_thread(ct1); wtg1.add_thread(ct3); wtg2.add_thread(ct2); wtg2.add_thread(ct3); assertFalse(ct1.closed()); assertFalse(ct2.closed()); assertFalse(ct3.closed()); assertEquals(0, c1.m_closed); assertEquals(0, c2.m_closed); assertEquals(0, c3.m_closed); CloseableWorkerThreadGroupOps.close_all(wtg1); assertTrue(ct1.closed()); assertTrue(ct2.closed()); assertTrue(ct3.closed()); assertEquals(1, c1.m_closed); assertEquals(1, c2.m_closed); assertEquals(1, c3.m_closed); } }
### Question: DirectoryReader { public static Set<File> listAllRecursively(File directory) { Ensure.not_null(directory, "directory == null"); Ensure.is_true(directory.isDirectory(), "file is not a directory"); Set<File> result = new HashSet<>(); File[] files = directory.listFiles(); for (File f : files) { if (f.isDirectory()) { result.addAll(listAllRecursively(f)); } else { result.add(f); } } return result; } private DirectoryReader(); static Set<File> listAllRecursively(File directory); }### Answer: @Test public void readEmptyDirectory() throws Exception { TemporaryFile tf = new TemporaryFile(true); Set<File> f = DirectoryReader.listAllRecursively(tf.getFile()); assertEquals(0, f.size()); tf.delete(); } @Test public void readDirectoryWithFiles() throws Exception { TemporaryFile tf = new TemporaryFile(true); File f1 = new File(tf.getFile(), "x"); FileContentWorker.set_contents(f1, "x"); File f2 = new File(tf.getFile(), "y"); FileContentWorker.set_contents(f2, "y"); Set<File> f = DirectoryReader.listAllRecursively(tf.getFile()); assertEquals(2, f.size()); assertTrue(f.contains(f1)); assertTrue(f.contains(f2)); tf.delete(); } @Test public void readDirectoryWithSubdirectory() throws Exception { TemporaryFile tf = new TemporaryFile(true); File f1 = new File(tf.getFile(), "x"); FileContentWorker.set_contents(f1, "x"); File d = new File(tf.getFile(), "z"); d.mkdir(); File f2 = new File(d, "y"); FileContentWorker.set_contents(f2, "y"); Set<File> f = DirectoryReader.listAllRecursively(tf.getFile()); assertEquals(2, f.size()); assertTrue(f.contains(f1)); assertTrue(f.contains(f2)); tf.delete(); }
### Question: EventFilter implements EventSink { public synchronized void connect(EventSink s) { Ensure.is_true(m_sink == null || s == null); Ensure.is_null(m_lock); m_sink = s; } EventFilter(); synchronized void connect(EventSink s); synchronized EventSink connected(); EventFilterInfo info(); synchronized void lock(Object l); synchronized void unlock(Object l); synchronized boolean locked(); }### Answer: @Test public void forwarding_with_sink_set() throws Exception { m_filter.connect(m_sink); m_filter.m_forward = true; BusData d = bus_data(); m_filter.sink(d); assertEquals(1, m_sink.m_data.size()); assertSame(d, m_sink.m_data.get(0)); } @Test(expected = AssertionError.class) public void setting_sink_with_sink_already_set() throws Exception { m_filter.connect(m_sink); m_filter.connect(m_sink); } @Test public void resetting_sink_legally() throws Exception { m_filter.connect(m_sink); m_filter.connect(null); m_filter.connect(null); m_filter.connect(m_sink); }
### Question: AcmeModelView extends CustomComponent implements IUpdatableWidget { @Override public void update() { model = (IAcmeSystem) systemViewProvider.getView().getModelInstance(); if (isModelChanged()) { subUpdate(); } } AcmeModelView(ISystemViewProvider svp); @Override void update(); @Override boolean isActive(); @Override void activate(); @Override void deactivate(); }### Answer: @Test public void testUpdate() throws IllegalStateException, AcmeException { System.out.println("update"); AcmeModelView instance = new AcmeModelViewImpl(svp); int expResult = 0; int result = ((AcmeModelViewImpl) instance).updateCnt; assertEquals(expResult, result); expResult = 1; instance.update(); result = ((AcmeModelViewImpl) instance).updateCnt; assertEquals(expResult, result); expResult = 1; instance.update(); result = ((AcmeModelViewImpl) instance).updateCnt; assertEquals(expResult, result); IAcmeSystem model = (IAcmeSystem) svp.getView().getModelInstance(); IAcmeCommand<IAcmeComponent> command = model.getCommandFactory().componentDeleteCommand(model.getComponent("Server0")); command.execute(); try { expResult = 2; instance.update(); result = ((AcmeModelViewImpl) instance).updateCnt; assertEquals(expResult, result); expResult = 2; instance.update(); result = ((AcmeModelViewImpl) instance).updateCnt; assertEquals(expResult, result); } finally { command.undo(); } }
### Question: EventFilter implements EventSink { public EventFilterInfo info() { return new EventFilterInfo(this); } EventFilter(); synchronized void connect(EventSink s); synchronized EventSink connected(); EventFilterInfo info(); synchronized void lock(Object l); synchronized void unlock(Object l); synchronized boolean locked(); }### Answer: @Test public void obtaining_filter_information() throws Exception { EventFilterInfo i = m_filter.info(); assertEquals(TestEventFilter.class.getName(), i.filter_class()); }
### Question: EventFilter implements EventSink { protected void forward(BusData data) throws IOException { Ensure.not_null(data); EventSink sink; synchronized (this) { sink = m_sink; } if (sink != null) { sink.sink(data); } } EventFilter(); synchronized void connect(EventSink s); synchronized EventSink connected(); EventFilterInfo info(); synchronized void lock(Object l); synchronized void unlock(Object l); synchronized boolean locked(); }### Answer: @Test(expected = AssertionError.class) public void event_filter_forward_null() throws Exception { m_filter.forward(null); }
### Question: EventFilter implements EventSink { public synchronized void lock(Object l) { Ensure.not_null(l); Ensure.is_null(m_lock); m_lock = l; } EventFilter(); synchronized void connect(EventSink s); synchronized EventSink connected(); EventFilterInfo info(); synchronized void lock(Object l); synchronized void unlock(Object l); synchronized boolean locked(); }### Answer: @Test(expected = AssertionError.class) public void cannot_lock_with_null_lock() throws Exception { m_filter.lock(null); }
### Question: EventFilter implements EventSink { public synchronized void unlock(Object l) { Ensure.not_null(l); Ensure.equals(m_lock, l); m_lock = null; } EventFilter(); synchronized void connect(EventSink s); synchronized EventSink connected(); EventFilterInfo info(); synchronized void lock(Object l); synchronized void unlock(Object l); synchronized boolean locked(); }### Answer: @Test(expected = AssertionError.class) public void cannot_unlock_with_null_lock() throws Exception { m_filter.unlock(null); }
### Question: BlockUnblockFilter extends StateBasedBlockerFilter<BlockedUnblockedState> { public void unblock() { state(BlockedUnblockedState.UNBLOCK); } BlockUnblockFilter(BlockedUnblockedState initial); void block(); void unblock(); }### Answer: @Test public void can_unblock_unblocked() throws Exception { assertEquals(BlockedUnblockedState.UNBLOCK, m_buf.state()); m_buf.unblock(); assertEquals(BlockedUnblockedState.UNBLOCK, m_buf.state()); }
### Question: BlockUnblockFilter extends StateBasedBlockerFilter<BlockedUnblockedState> { public void block() { state(BlockedUnblockedState.BLOCK); } BlockUnblockFilter(BlockedUnblockedState initial); void block(); void unblock(); }### Answer: @Test public void can_block_blocked() throws Exception { m_buf.block(); assertEquals(BlockedUnblockedState.BLOCK, m_buf.state()); m_buf.block(); assertEquals(BlockedUnblockedState.BLOCK, m_buf.state()); } @Test public void blocked_events_are_rejected() throws Exception { m_buf.block(); m_buf.connect(m_sink); m_buf.sink(bus_data()); assertEquals(0, m_sink.m_data.size()); } @Test public void obtaining_blocked_info() throws Exception { m_buf.block(); @SuppressWarnings("unchecked") StateBasedBlockerFilterInfo<BlockedUnblockedState> st = (StateBasedBlockerFilterInfo<BlockedUnblockedState>) m_buf.info(); assertEquals(BlockedUnblockedState.BLOCK, st.state()); }
### Question: AcmeSystemViewProvider implements ISystemViewProvider { @Override public boolean isCurrent() { return this.isCurrent; } protected AcmeSystemViewProvider( IRuntimeAggregator<IAcmeSystem> runtimeAggregator, AbstractRainbowVaadinUI ui, ISystemConfiguration systemConfig, IHistoryProvider provider); AcmeSystemViewProvider( IRuntimeAggregator<IAcmeSystem> runtimeAggregator, AbstractRainbowVaadinUI ui, ISystemConfiguration systemConfig); @Override void setUseCurrent(); @Override void setUseHistorical(Date time); @Override Date getHistoricalTime(); @Override void update(); DataValue getValue(String mapping); @Override boolean isCurrent(); @Override IModelInstance<?> getView(); @Override void getHistoricalEventRange(Date start, Date end); @Override void getHistoricalEventRangeByType(String channel, Date start, Date end); @Override void getHistoricalModelEventRange(Date start, Date end); @Override void provideHistoricalView(IModelInstance<?> view); @Override void provideHistoricalEvent(IRainbowMessage message); @Override void provideHistoricalEventRange(List<IRainbowMessage> messages); @Override List<IRainbowMessage> getNewEvents(); @Override int getNewEventsCount(); @Override ArrayList<String> getSessionList(); @Override void setSession(String session); String getReadSession(); @Override Date getStartDate(); @Override Date getMaxDate(); @Override boolean currentSessionIsWriteSession(); @Override String getSession(); @Override List<IRainbowMessage> getHistoricalEvents(); @Override List<IRainbowMessage> getNumberOfEventsBefore(Date endTime, int numEvents); @Override void stop(); }### Answer: @Test public void createSVP() { assertNotNull(provider.getHistoryProvider()); assertNotNull(provider.getTimer()); assertNotNull(provider.getSystemConfig()); assertNotNull(provider.getEventStore()); assertNotNull(provider.getUi()); assertEquals(true, provider.isCurrent()); assertEquals(sysConfig.getUpdateRate(), provider.getRefreshRate()); }
### Question: EventFilterChain implements EventSink { @Override public synchronized void sink(BusData data) throws IOException { Ensure.not_null(data); first().sink(data); } EventFilterChain(EventSink sink); synchronized EventSink chain_sink(); synchronized List<EventFilter> filters(); synchronized void add_filter(EventFilter f); synchronized void remove_filter(EventFilter f); synchronized void clear(); @Override synchronized void sink(BusData data); synchronized EventFilterChainInfo info(); }### Answer: @Test public void process_empty_event_chain() throws Exception { BusData d = bus_data(); m_chain.sink(d); assertEquals(1, m_sink.m_data.size()); assertSame(d, m_sink.m_data.get(0)); } @Test(expected = AssertionError.class) public void processing_null() throws Exception { m_chain.sink(null); }
### Question: EventFilterChain implements EventSink { public synchronized EventSink chain_sink() { return m_sink; } EventFilterChain(EventSink sink); synchronized EventSink chain_sink(); synchronized List<EventFilter> filters(); synchronized void add_filter(EventFilter f); synchronized void remove_filter(EventFilter f); synchronized void clear(); @Override synchronized void sink(BusData data); synchronized EventFilterChainInfo info(); }### Answer: @Test public void obtain_chain_sink() throws Exception { assertSame(m_sink, m_chain.chain_sink()); } @Test public void multiple_chains_same_sink() throws Exception { assertSame(m_sink, m_chain.chain_sink()); assertSame(m_sink, new EventFilterChain(m_sink).chain_sink()); }
### Question: EventFilterChain implements EventSink { public synchronized void add_filter(EventFilter f) { Ensure.not_null(f); Ensure.is_false(f.locked()); f.connect(first()); m_filters.add(f); f.lock(m_filters); } EventFilterChain(EventSink sink); synchronized EventSink chain_sink(); synchronized List<EventFilter> filters(); synchronized void add_filter(EventFilter f); synchronized void remove_filter(EventFilter f); synchronized void clear(); @Override synchronized void sink(BusData data); synchronized EventFilterChainInfo info(); }### Answer: @Test(expected = AssertionError.class) public void adding_null_filter_to_chain() throws Exception { m_chain.add_filter(null); } @Test(expected = AssertionError.class) public void adding_filter_twice_to_same_chain() throws Exception { m_chain.add_filter(m_filter); m_chain.add_filter(m_filter); } @Test(expected = AssertionError.class) public void adding_filter_in_another_chain() throws Exception { m_chain.add_filter(m_filter); new EventFilterChain(m_sink).add_filter(m_filter); } @Test public void equals_and_hash_code() throws Exception { SaveSink ss = new SaveSink(); EventFilterChain c1 = new EventFilterChain(ss); EventFilterChain c2 = new EventFilterChain(ss); EventFilterChainInfo i1 = new EventFilterChainInfo(c1); EventFilterChainInfo i2 = new EventFilterChainInfo(c2); assertEquals(i1, i2); assertEquals(i1.hashCode(), i2.hashCode()); c1.add_filter(new TestEventFilter()); i1 = new EventFilterChainInfo(c1); assertFalse(i1.equals(i2)); assertNotSame(i1.hashCode(), i2.hashCode()); assertFalse(i1.equals(null)); assertFalse(i1.equals(new Integer(2))); assertTrue(i1.equals(i1)); }
### Question: EventFilterChain implements EventSink { public synchronized void remove_filter(EventFilter f) { Ensure.not_null(f); Ensure.is_true(m_filters.contains(f)); int idx = m_filters.indexOf(f); EventFilter prev = null; if (idx != (m_filters.size() - 1)) { prev = m_filters.get(idx + 1); } if (prev != null) { prev.unlock(m_filters); prev.connect(null); prev.connect(f.connected()); prev.lock(m_filters); } f.unlock(m_filters); f.connect(null); m_filters.remove(f); } EventFilterChain(EventSink sink); synchronized EventSink chain_sink(); synchronized List<EventFilter> filters(); synchronized void add_filter(EventFilter f); synchronized void remove_filter(EventFilter f); synchronized void clear(); @Override synchronized void sink(BusData data); synchronized EventFilterChainInfo info(); }### Answer: @Test(expected = AssertionError.class) public void removing_null_filter_from_chain() throws Exception { m_chain.remove_filter(null); } @Test(expected = AssertionError.class) public void removed_filter_not_in_chain() throws Exception { m_chain.remove_filter(m_filter); }
### Question: AcmeSystemViewProvider implements ISystemViewProvider { public DataValue getValue(String mapping) throws AcmeConversionException { IAcmeProperty property = (IAcmeProperty) ModelHelper .getElementFromQualifiedName(internalModel.getModelInstance(), mapping); return AcmeConverterSupport.convertToDataValue(property); } protected AcmeSystemViewProvider( IRuntimeAggregator<IAcmeSystem> runtimeAggregator, AbstractRainbowVaadinUI ui, ISystemConfiguration systemConfig, IHistoryProvider provider); AcmeSystemViewProvider( IRuntimeAggregator<IAcmeSystem> runtimeAggregator, AbstractRainbowVaadinUI ui, ISystemConfiguration systemConfig); @Override void setUseCurrent(); @Override void setUseHistorical(Date time); @Override Date getHistoricalTime(); @Override void update(); DataValue getValue(String mapping); @Override boolean isCurrent(); @Override IModelInstance<?> getView(); @Override void getHistoricalEventRange(Date start, Date end); @Override void getHistoricalEventRangeByType(String channel, Date start, Date end); @Override void getHistoricalModelEventRange(Date start, Date end); @Override void provideHistoricalView(IModelInstance<?> view); @Override void provideHistoricalEvent(IRainbowMessage message); @Override void provideHistoricalEventRange(List<IRainbowMessage> messages); @Override List<IRainbowMessage> getNewEvents(); @Override int getNewEventsCount(); @Override ArrayList<String> getSessionList(); @Override void setSession(String session); String getReadSession(); @Override Date getStartDate(); @Override Date getMaxDate(); @Override boolean currentSessionIsWriteSession(); @Override String getSession(); @Override List<IRainbowMessage> getHistoricalEvents(); @Override List<IRainbowMessage> getNumberOfEventsBefore(Date endTime, int numEvents); @Override void stop(); }### Answer: @Test public void getValue() throws AcmeConversionException, ValueConversionException { DataValue value = provider.getValue("Znn.Server0.load"); assertEquals(new Float(0.0), DataValueSupport.converter.to_java(value, Float.class)); value = provider.getValue("Znn.Server0.fidelity"); assertEquals(new Integer(5), DataValueSupport.converter.to_java(value, Integer.class)); }
### Question: DataTypeSocketConnectionSink implements EventSink { @Override public void sink(BusData data) throws IOException { Ensure.not_null(data); m_dts.write(data); } DataTypeSocketConnectionSink(DataTypeSocketConnection c); @Override void sink(BusData data); }### Answer: @Test public void sink_data_is_written_to_connection() throws Exception { m_sc_sink.sink(bus_data()); assertEquals(1, m_written.size()); } @Test(expected = AssertionError.class) public void cannot_sink_null_data() throws Exception { m_sc_sink.sink(null); }
### Question: BusDataQueueGroupSink implements EventSink { @Override public void sink(BusData data) { Ensure.not_null(data); m_qg.add(data); } BusDataQueueGroupSink(BusDataQueueGroupImpl qg); @Override void sink(BusData data); }### Answer: @Test public void sink() throws Exception { BusDataQueueGroupImpl qg = new BusDataQueueGroupImpl(); BusDataQueue q = new BusDataQueue(); qg.add(q); BusDataQueueGroupSink s = new BusDataQueueGroupSink(qg); s.sink(bus_data()); m_dh.wait_dispatch_clear(); assertNotNull(q.poll()); assertNull(q.poll()); } @Test(expected = AssertionError.class) public void cannot_sink_null() throws Exception { BusDataQueueGroupImpl qg = new BusDataQueueGroupImpl(); BusDataQueue q = new BusDataQueue(); qg.add(q); BusDataQueueGroupSink s = new BusDataQueueGroupSink(qg); s.sink(null); }
### Question: AdaptationTree { public void addLeaf (T root, T leaf) { addLeaf (root).addLeaf (leaf); } AdaptationTree(T head); AdaptationTree(AdaptationExecutionOperatorT operator); void setId(String id); String getId(); void addLeaf(T root, T leaf); AdaptationTree<T> addLeaf(T leaf); AdaptationTree<T> setAsParent(T parentRoot); T getHead(); AdaptationTree<T> getParent(); Collection<AdaptationTree<T>> getSubTrees(); AdaptationExecutionOperatorT getOperator(); @Override String toString(); boolean visit(IAdaptationVisitor<T> visitor); }### Answer: @Test public void testSequence () throws InterruptedException { AdaptationTree root = new AdaptationTree<> (AdaptationExecutionOperatorT.SEQUENCE); root.addLeaf (new ExecutableTest (1)); root.addLeaf (new ExecutableTest (2)); root.addLeaf (new ExecutableTest (3)); CountDownLatch countdownLatch = new CountDownLatch (1); DefaultAdaptationExecutorVisitor<IEvaluable> visitor = new DefaultAdaptationExecutorVisitor<IEvaluable> (root, new ThreadGroup ("execution"), "", countdownLatch, new TestCaseReportingPort ()) { @Override protected boolean evaluate (IEvaluable adaptation) throws RainbowException{ return (Boolean )adaptation.evaluate (null); } @Override protected DefaultAdaptationExecutorVisitor<IEvaluable> spawnNewExecutorForTree (AdaptationTree<IEvaluable> adt, ThreadGroup g, CountDownLatch doneSignal) { return null; } }; visitor.start (); countdownLatch.await (5, TimeUnit.SECONDS); assertTrue (numbers.size () == 3); assertTrue (numbers.get (0) == 1); assertTrue (numbers.get (1) == 2); assertTrue (numbers.get (2) == 3); } @Test public void testSequenceFail () throws InterruptedException { AdaptationTree root = new AdaptationTree<> (AdaptationExecutionOperatorT.SEQUENCE_STOP_FAILURE); root.addLeaf (new ExecutableTest (1)); root.addLeaf (new ExecutableTest (2, false)); root.addLeaf (new ExecutableTest (3)); CountDownLatch countdownLatch = new CountDownLatch (1); DefaultAdaptationExecutorVisitor<IEvaluable> visitor = new TestAdaptationVisitor (root, new ThreadGroup ("execution"), countdownLatch); visitor.start (); countdownLatch.await (5, TimeUnit.SECONDS); assertTrue (numbers.size () == 2); assertTrue (numbers.get (0) == 1); assertTrue (numbers.get (1) == 2); } @Test public void testSequenceSuccess () throws InterruptedException { AdaptationTree root = new AdaptationTree<> (AdaptationExecutionOperatorT.SEQUENCE_STOP_SUCCESS); root.addLeaf (new ExecutableTest (1)); root.addLeaf (new ExecutableTest (2, false)); root.addLeaf (new ExecutableTest (3)); CountDownLatch countdownLatch = new CountDownLatch (1); DefaultAdaptationExecutorVisitor<IEvaluable> visitor = new TestAdaptationVisitor (root, new ThreadGroup ("test"), countdownLatch); visitor.start (); countdownLatch.await (5, TimeUnit.SECONDS); assertTrue (numbers.size () == 1); assertTrue (numbers.get (0) == 1); } @Test public void testParallel () throws InterruptedException { AdaptationTree root = new AdaptationTree<> (AdaptationExecutionOperatorT.PARALLEL); int number = 20; for (int i = 0; i < number; i++) { root.addLeaf (new ExecutableTest (i)); } CountDownLatch countdownLatch = new CountDownLatch (1); DefaultAdaptationExecutorVisitor<IEvaluable> visitor = new TestAdaptationVisitor (root, new ThreadGroup ("execution"), countdownLatch); visitor.start (); countdownLatch.await (5, TimeUnit.SECONDS); assertTrue (numbers.size () == number); }
### Question: Dashboard extends VerticalLayout { public void addPage(String pageName) { final HorizontalLayout newLayout = new HorizontalLayout(); DragAndDropWrapper layoutWrapper = new DragAndDropWrapper(newLayout); setDropHandler(newLayout, layoutWrapper); tabs.add(layoutWrapper); pageContentArea.addTab(layoutWrapper, pageName); pageContentArea.setSelectedTab(layoutWrapper); pageWidgets.add (new ArrayList<IWidget> ()); removePageBtn.setEnabled(true); } Dashboard(AbstractRainbowVaadinUI rui); void addPage(String pageName); void setPage(int pageId); void removePage(int pageId); void loadViewConfiguration(); void saveViewConfiguration(); void resetDashboard(); }### Answer: @Test public void addPage() { dashboard.newPageBtn.click(); dashboard.txtPageName.setValue("Test"); dashboard.btnCreate.click(); assertEquals(dashboard.tabs.size(), 2); boolean test = false; for (int i = 0; i < dashboard.pageContentArea.getComponentCount(); i++) { if (dashboard.pageContentArea.getTab(i).getCaption().equals("Test")) { test = true; } } assertEquals(test, true); }
### Question: ServerEnablementGauge extends RegularPatternGauge { private AcmeModelInstance getModel () { if (m_model == null) { m_model = (AcmeModelInstance) m_modelsPort.<IAcmeSystem>getModelInstance (new ModelReference (m_modelDesc .getName (), m_modelDesc.getType ())); } return m_model; } ServerEnablementGauge(String id, long beaconPeriod, TypedAttribute gaugeDesc, TypedAttribute modelDesc, List<TypedAttributeWithValue> setupParams, Map<String, IRainbowOperation> mappings); static final String NAME; static final String DEFAULT; static final Pattern PATTERN; }### Answer: @Test public void testDoMatchDesired() throws Exception { GaugeDescription gdl = YamlUtil.loadGaugeSpecs(new File("src/test/resources/ServerEnablementGaugeTest/gauges.yml")); assertTrue(gdl.instDescList().size() == 1); GaugeInstanceDescription gd = gdl.instDescList().iterator().next(); Map<String, IRainbowOperation> mappings = new HashMap<> (); mappings.putAll(gd.mappings()); ServerEnablementGauge gauge = new ServerEnablementGauge(gd.gaugeName(), 10000, new TypedAttribute(gd.gaugeName(), gd.gaugeType()), gd.modelDesc(), gd.setupParams(), mappings); gauge.configureGauge(gd.configParams()); gauge.initialize(mock(IRainbowReportingPort.class)); StandaloneResource resource = StandaloneResourceProvider.instance ().acmeResourceForString ( "src/test/resources/acme/znn.acme"); IAcmeSystem sys = resource.getModel ().getSystems ().iterator ().next (); assertTrue (sys.getDeclaredTypes ().iterator ().next ().isSatisfied ()); AcmeModelInstance mi = new BareAcmeModelInstance (sys); Whitebox.setInternalState(gauge, "m_model", mi); String testInput = "o 127.0.0.1:8080"; IProbeIdentifier testProbe = MockingUtil.mockProbeIdentifier("test", "test", "JAVA"); gauge.start(); gauge.reportFromProbe(testProbe, testInput); gauge.reportFromProbe(testProbe, testInput); gauge.reportFromProbe(testProbe, testInput); gauge.reportFromProbe(testProbe, testInput); }
### Question: Dashboard extends VerticalLayout { public void removePage(int pageId) { for (int i = 0; i < pageWidgets.get(pageId).size(); i++) { viewControl.removeWidget(pageWidgets.get(pageId).get(i)); } pageWidgets.remove(pageId); pageContentArea.removeTab(pageContentArea.getTab(pageContentArea .getSelectedTab())); tabs.remove(pageId); } Dashboard(AbstractRainbowVaadinUI rui); void addPage(String pageName); void setPage(int pageId); void removePage(int pageId); void loadViewConfiguration(); void saveViewConfiguration(); void resetDashboard(); }### Answer: @Test public void removePage() { addPage(); dashboard.removePageBtn.click(); assertEquals(dashboard.tabs.size(), 1); boolean test = false; for (int i = 0; i < dashboard.pageContentArea.getComponentCount(); i++) { if (dashboard.pageContentArea.getTab(i).getCaption().equals("Test")) { test = true; } } assertEquals(test, false); }
### Question: Dashboard extends VerticalLayout { public void setPage(int pageId) { pageContentArea.setSelectedTab(pageId); } Dashboard(AbstractRainbowVaadinUI rui); void addPage(String pageName); void setPage(int pageId); void removePage(int pageId); void loadViewConfiguration(); void saveViewConfiguration(); void resetDashboard(); }### Answer: @Test public void setPage() { for (int i = 0; i < 5; i++) { dashboard.newPageBtn.click(); dashboard.txtPageName.setValue("Test" + i); dashboard.btnCreate.click(); } assertEquals(dashboard.tabs.size(), 6); dashboard.setPage(3); assertEquals( dashboard.pageContentArea.getTab( dashboard.pageContentArea.getSelectedTab()) .getCaption(), "Test2"); } @Test public void setPageOutsideBouds() { for (int i = 0; i < 5; i++) { dashboard.newPageBtn.click(); dashboard.txtPageName.setValue("Test" + i); dashboard.btnCreate.click(); } assertEquals(dashboard.tabs.size(), 6); dashboard.setPage(3); assertEquals( dashboard.pageContentArea.getTab( dashboard.pageContentArea.getSelectedTab()) .getCaption(), "Test2"); dashboard.setPage(10); assertEquals( dashboard.pageContentArea.getTab( dashboard.pageContentArea.getSelectedTab()) .getCaption(), "Test2"); dashboard.setPage(-1); assertEquals( dashboard.pageContentArea.getTab( dashboard.pageContentArea.getSelectedTab()) .getCaption(), "Test2"); }
### Question: TimelineView extends CustomComponent implements IUpdatableWidget { boolean isCurrent() { return this.currentCheckBox.getValue(); } TimelineView(ISystemViewProvider systemViewProvider); TimelineView(ISystemViewProvider systemViewProvider, Class<? extends Timeline> tlClass); @Override void update(); @Override boolean isActive(); @Override void activate(); @Override void deactivate(); void setCurrent(boolean isCurrent); void setTimeDisplay(Date date); void enableAutoScroll(); void disableAutoScroll(); void disableStop(); void enableStop(); void setHistoricalDate(Date current); void setStartDate(Date startDate); void setAttached(); void setDetached(); }### Answer: @Test public void currentHistorical() { CheckBox currentCheckBox = timelineView.getCurrentCheckBox(); DateField timeDisplay = timelineView.getTimeDisplay(); CheckBox autoScrollCheckBox = timelineView.getAutoScrollCheckBox(); currentCheckBox.setValue(true); assertEquals(true, currentCheckBox.getValue()); assertEquals(true, timeline.isCurrent()); assertEquals(true, svp.isCurrent()); assertEquals(false, timeDisplay.isEnabled()); assertEquals(true, autoScrollCheckBox.isEnabled()); currentCheckBox.setValue(false); assertEquals(false, currentCheckBox.getValue()); assertEquals(false, timeline.isCurrent()); assertEquals(false, svp.isCurrent()); assertEquals(true, timeDisplay.isEnabled()); assertEquals(false, autoScrollCheckBox.isEnabled()); }
### Question: TimelineView extends CustomComponent implements IUpdatableWidget { public void setTimeDisplay(Date date) { this.timeDisplay.setValue(date); } TimelineView(ISystemViewProvider systemViewProvider); TimelineView(ISystemViewProvider systemViewProvider, Class<? extends Timeline> tlClass); @Override void update(); @Override boolean isActive(); @Override void activate(); @Override void deactivate(); void setCurrent(boolean isCurrent); void setTimeDisplay(Date date); void enableAutoScroll(); void disableAutoScroll(); void disableStop(); void enableStop(); void setHistoricalDate(Date current); void setStartDate(Date startDate); void setAttached(); void setDetached(); }### Answer: @Test public void timelineViewTimeDisplay() { DateField timeDisplay = timelineView.getTimeDisplay(); Date date = new Date(); timelineView.setTimeDisplay(date); assertEquals(date, timeDisplay.getValue()); }
### Question: AcmeRuntimeAggregator implements IRuntimeAggregator<IAcmeSystem> { @Override public IModelInstance<IAcmeSystem> getInternalModel() { return internalModel; } AcmeRuntimeAggregator(ISystemConfiguration config); AcmeRuntimeAggregator(ISystemConfiguration config, IDatabaseConnector dbConn); @Override void start(); @Override void stop(); @Override IModelInstance<IAcmeSystem> getInternalModel(); @Override IModelInstance<IAcmeSystem> copyInternalModel(); @Override IEventBuffer getEventBuffer(); @Override synchronized void processEvent(String channel, IRainbowMessage event); }### Answer: @Test public void testGetInternalModel() throws RuntimeAggregatorException { System.out.println("getInternalModel"); AcmeRuntimeAggregator instance = new AcmeRuntimeAggregator(systemConfig, new DummyDatabaseConnector()); IModelInstance<IAcmeSystem> modelInstance = instance.getInternalModel(); assertNotNull(modelInstance); assertEquals("Acme", modelInstance.getModelType()); assertEquals("ZNewsSys", modelInstance.getModelName()); IAcmeSystem system = modelInstance.getModelInstance(); assertNotNull(system); assertEquals("ZNewsSys", system.getName()); }
### Question: AcmeRuntimeAggregator implements IRuntimeAggregator<IAcmeSystem> { @Override public IModelInstance<IAcmeSystem> copyInternalModel() throws RainbowCopyException { synchronized (copyLock) { return internalModel.copyModelInstance("Acme"); } } AcmeRuntimeAggregator(ISystemConfiguration config); AcmeRuntimeAggregator(ISystemConfiguration config, IDatabaseConnector dbConn); @Override void start(); @Override void stop(); @Override IModelInstance<IAcmeSystem> getInternalModel(); @Override IModelInstance<IAcmeSystem> copyInternalModel(); @Override IEventBuffer getEventBuffer(); @Override synchronized void processEvent(String channel, IRainbowMessage event); }### Answer: @Test public void testCopyInternalModel() throws Exception { System.out.println("copyInternalModel"); AcmeRuntimeAggregator instance = new AcmeRuntimeAggregator(systemConfig, new DummyDatabaseConnector()); double value1 = 99.9; double value2 = 0.0; IModelInstance<IAcmeSystem> modelInstance = instance.getInternalModel(); IAcmeSystem system = modelInstance.getModelInstance(); IAcmeProperty prop = (IAcmeProperty) system.getComponent("Server0").getProperty("load"); assertNotNull(prop); IAcmePropertyValue val1 = StandaloneLanguagePackHelper.defaultLanguageHelper().propertyValueFromString( Double.toString(value1), new RegionManager()); IAcmeCommand command = system.getCommandFactory().propertyValueSetCommand(prop, val1); command.execute(); IModelInstance<IAcmeSystem> copyModelInstance = instance.copyInternalModel(); assertNotNull(copyModelInstance); IAcmePropertyValue val2 = StandaloneLanguagePackHelper.defaultLanguageHelper().propertyValueFromString( Double.toString(value2), new RegionManager()); command = system.getCommandFactory().propertyValueSetCommand(prop, val2); command.execute(); IAcmePropertyValue origValue = prop.getValue(); assertNotNull(origValue); IAcmeSystem copySystem = copyModelInstance.getModelInstance(); assertNotNull(copySystem); IAcmeProperty copyProp = (IAcmeProperty) copySystem.getComponent("Server0").getProperty("load"); assertNotNull(copyProp); IAcmePropertyValue copyVal = copyProp.getValue(); assertNotNull(copyVal); assertEquals(val2, origValue); assertEquals(val1, copyVal); }
### Question: AcmeRuntimeAggregator implements IRuntimeAggregator<IAcmeSystem> { @Override public IEventBuffer getEventBuffer() { return eventBuffer; } AcmeRuntimeAggregator(ISystemConfiguration config); AcmeRuntimeAggregator(ISystemConfiguration config, IDatabaseConnector dbConn); @Override void start(); @Override void stop(); @Override IModelInstance<IAcmeSystem> getInternalModel(); @Override IModelInstance<IAcmeSystem> copyInternalModel(); @Override IEventBuffer getEventBuffer(); @Override synchronized void processEvent(String channel, IRainbowMessage event); }### Answer: @Test public void testGetEventBuffer() throws RuntimeAggregatorException { System.out.println("getEventBuffer"); AcmeRuntimeAggregator instance = new AcmeRuntimeAggregator(systemConfig, new DummyDatabaseConnector()); IEventBuffer buffer = instance.getEventBuffer(); assertNotNull(buffer); }
### Question: UIConfigurationLoader extends ConfigurationLoader { public boolean loadConfiguration() throws IOException { for (Map.Entry<String, Object> entry : defaultConfig.entrySet()) { System.out.printf("'%s' will be initiated as: (%s)%n", entry.getKey(), entry.getValue()); } System.out.println("Is it OK(y/n)?"); Scanner scanner = new Scanner(System.in); String answer = scanner.nextLine(); int cnt = 1; while (!answer.equals("yes") && !answer.equals("y") && !answer.equals("no") && !answer.equals("n")) { System.out.println(answer); System.out.println("Please enter yes/y or no/n."); System.out.println("Is it OK(Y/N)?"); answer = scanner.nextLine(); cnt++; if (cnt == 3) { break; } } if (answer.equals("yes") || answer.equals("y")) { System.out.println("We will use the default values to initialize."); return true; } else if (answer.equals("no") || answer.equals("n")) { System.out.println("Please set your own configurations in 'config.yml' and run again."); File file = new File("config.yml"); writeDefaultConfiguration(file); return false; } else { System.out.println("Abort!"); return false; } } UIConfigurationLoader(List<Variable> variables); boolean loadConfiguration(); Map<String, Object> getDefaultConfig(); Set<String> getVariableNames(); }### Answer: @Test public void loadY() throws Exception { String input = "yes"; InputStream in = new ByteArrayInputStream(input.getBytes()); System.setIn(in); configLoader.loadConfiguration(); } @Test public void loadN() throws Exception { String input = "no"; InputStream in = new ByteArrayInputStream(input.getBytes()); System.setIn(in); configLoader.loadConfiguration(); tearDown(); } @Test public void loadOther() throws Exception { String input = "other\nother\nother"; InputStream in = new ByteArrayInputStream(input.getBytes()); System.setIn(in); configLoader.loadConfiguration(); } @Test public void loadOtherY() throws Exception { String input = "other\nother\nyes"; InputStream in = new ByteArrayInputStream(input.getBytes()); System.setIn(in); configLoader.loadConfiguration(); }
### Question: AcmeRuntimeAggregator implements IRuntimeAggregator<IAcmeSystem> { @Override synchronized public void processEvent(String channel, IRainbowMessage event) throws EventProcessingException { if (!isRunning) { return; } switch (channel) { case "MODEL_CHANGE": processModelUpdate(event); break; case "MODEL_DS": case "MODEL_US": processStreamingEvent(channel, event); break; default: throw new EventProcessingException("Unsupported channel: " + channel); } } AcmeRuntimeAggregator(ISystemConfiguration config); AcmeRuntimeAggregator(ISystemConfiguration config, IDatabaseConnector dbConn); @Override void start(); @Override void stop(); @Override IModelInstance<IAcmeSystem> getInternalModel(); @Override IModelInstance<IAcmeSystem> copyInternalModel(); @Override IEventBuffer getEventBuffer(); @Override synchronized void processEvent(String channel, IRainbowMessage event); }### Answer: @Test public void testProcessEvent() throws EventProcessingException, RainbowException, RuntimeAggregatorException { System.out.println("processEvent"); AcmeRuntimeAggregator instance = new AcmeRuntimeAggregator(systemConfig, new DummyDatabaseConnector()); String channel = "MODEL_CHANGE"; Float expRes = (float) 99.9; IRainbowMessage event = new RainbowESEBMessage(); event.setProperty(IRainbowMessageFactory.EVENT_TYPE_PROP, AcmeModelEventType.SET_PROPERTY_VALUE.toString()); event.setProperty(AcmeModelOperation.PROPERTY_PROP, "ZNewsSys.Server0.load"); event.setProperty(AcmeModelOperation.VALUE_PROP, expRes.toString()); event.setProperty(ESEBConstants.MSG_SENT, System.currentTimeMillis() + ""); instance.start(); instance.processEvent(channel, event); IModelInstance<IAcmeSystem> modelInstance = instance.getInternalModel(); assertNotNull(modelInstance); IAcmeSystem system = modelInstance.getModelInstance(); assertNotNull(system); IAcmeProperty prop = (IAcmeProperty) system.getComponent("Server0").getProperty("load"); assertNotNull(prop); IAcmePropertyValue val = prop.getValue(); assertNotNull(val); Float res = PropertyHelper.toJavaVal((IAcmeFloatValue) val); assertEquals(expRes, res); try { instance.processEvent("UNKNOWN", event); } catch (EventProcessingException ex) { } instance.stop(); }
### Question: AcmeRuntimeAggregator implements IRuntimeAggregator<IAcmeSystem> { Date getEventTimestamp(IRainbowMessage event) { long sent = Long.parseLong((String) event.getProperty(ESEBConstants.MSG_SENT)); Date timestamp = new Date(sent); return timestamp; } AcmeRuntimeAggregator(ISystemConfiguration config); AcmeRuntimeAggregator(ISystemConfiguration config, IDatabaseConnector dbConn); @Override void start(); @Override void stop(); @Override IModelInstance<IAcmeSystem> getInternalModel(); @Override IModelInstance<IAcmeSystem> copyInternalModel(); @Override IEventBuffer getEventBuffer(); @Override synchronized void processEvent(String channel, IRainbowMessage event); }### Answer: @Test public void testTimestampCoversion() throws RainbowException, RuntimeAggregatorException { System.out.println("getEventTimestamp"); AcmeRuntimeAggregator instance = new AcmeRuntimeAggregator(systemConfig, new DummyDatabaseConnector()); IRainbowMessage event = new RainbowESEBMessage(); Date expResult = new Date(System.currentTimeMillis()); event.setProperty(ESEBConstants.MSG_SENT, expResult.getTime() + ""); Date result = instance.getEventTimestamp(event); assertEquals(expResult, result); }
### Question: AcmeRuntimeAggregator implements IRuntimeAggregator<IAcmeSystem> { protected void processStreamingEvent(String channel, IRainbowMessage event) { eventBuffer.add(event); databaseConnector.writeEvent(channel, event, getEventTimestamp(event)); } AcmeRuntimeAggregator(ISystemConfiguration config); AcmeRuntimeAggregator(ISystemConfiguration config, IDatabaseConnector dbConn); @Override void start(); @Override void stop(); @Override IModelInstance<IAcmeSystem> getInternalModel(); @Override IModelInstance<IAcmeSystem> copyInternalModel(); @Override IEventBuffer getEventBuffer(); @Override synchronized void processEvent(String channel, IRainbowMessage event); }### Answer: @Test public void testProcessStreamingEvent() throws RuntimeAggregatorException, RainbowException, EventProcessingException { System.out.println("processStreamingEvent"); AcmeRuntimeAggregator instance = new AcmeRuntimeAggregator(systemConfig, new DummyDatabaseConnector()); instance.start(); IEventBuffer buffer = instance.getEventBuffer(); assertNotNull(buffer); buffer.activate(); assertEquals(true, buffer.isActive()); IRainbowMessage event = new RainbowESEBMessage(); event.setProperty(ESEBConstants.MSG_CHANNEL_KEY, "MODEL_DS"); event.setProperty(ESEBConstants.MSG_SENT, System.currentTimeMillis() + ""); instance.processEvent("MODEL_DS", event); List<IRainbowMessage> bufList = new ArrayList<>(); int num = buffer.drainToCollection(bufList); assertEquals(1, num); IRainbowMessage result = bufList.get(0); assertEquals(event.toString(), result.toString()); }
### Question: EventBuffer implements IEventBuffer { @Override public int drainToCollection(Collection<IRainbowMessage> collection) { return queue.drainTo(collection); } EventBuffer(int size); @Override int drainToCollection(Collection<IRainbowMessage> collection); @Override void add(IRainbowMessage event); @Override void clear(); @Override void activate(); @Override void deactivate(); @Override boolean isActive(); }### Answer: @Test public void testDrainToCollection() throws RainbowException { System.out.println("drainToCollection"); List<IRainbowMessage> collection = new ArrayList<>(); EventBuffer instance = new EventBuffer(10); instance.activate(); IRainbowMessage event1 = new RainbowESEBMessage(); IRainbowMessage event2 = new RainbowESEBMessage(); event1.setProperty(ESEBConstants.MSG_CHANNEL_KEY, "MODEL_DS"); event2.setProperty(ESEBConstants.MSG_CHANNEL_KEY, "MODEL_US"); instance.add(event1); instance.add(event2); int num = instance.drainToCollection(collection); assertEquals(2, num); IRainbowMessage result1 = collection.get(0); IRainbowMessage result2 = collection.get(1); assertEquals(event1.toString(), result1.toString()); assertEquals(event2.toString(), result2.toString()); }
### Question: EventBuffer implements IEventBuffer { @Override public void add(IRainbowMessage event) { if (isActive) { if (!queue.offer(event)) { Logger.getLogger(EventBuffer.class.getName()).warning( "Cannot add an event. The buffer is full."); } } } EventBuffer(int size); @Override int drainToCollection(Collection<IRainbowMessage> collection); @Override void add(IRainbowMessage event); @Override void clear(); @Override void activate(); @Override void deactivate(); @Override boolean isActive(); }### Answer: @Test public void testAdd() throws RainbowException { System.out.println("add"); IRainbowMessage event1 = new RainbowESEBMessage(); IRainbowMessage event2 = new RainbowESEBMessage(); event1.setProperty(ESEBConstants.MSG_CHANNEL_KEY, "MODEL_DS"); event2.setProperty(ESEBConstants.MSG_CHANNEL_KEY, "MODEL_US"); EventBuffer instance = new EventBuffer(1); instance.activate(); instance.add(event1); instance.add(event2); List<IRainbowMessage> collection = new ArrayList<>(); int num = instance.drainToCollection(collection); assertEquals(1, num); IRainbowMessage result = collection.get(0); assertEquals(event1.toString(), result.toString()); }
### Question: SystemConfiguration extends Properties implements ISystemConfiguration { @Override public String getRainbowHost() { String prop = getProperty("rainbow.host"); return prop; } SystemConfiguration(String filename); @Override String getRainbowHost(); @Override void setRainbowHost(String host); @Override short getRainbowPort(); @Override void setRainbowPort(short port); @Override String getModelPath(); @Override void setModelPath(String path); @Override String getNode(); @Override void setNode(String node); @Override boolean isAttached(); @Override void setAttached(boolean attached); @Override String getConfigDir(); @Override void setConfigDir(String path); @Override int getSnapshotRate(); @Override void setSnapshotRate(int rate); @Override boolean isModelLocal(); @Override void setModelLocal(boolean local); @Override String getModelName(); @Override void setModelName(String name); @Override String getModelFactoryClass(); @Override void setModelFactoryClass(String cls); @Override int getUpdateRate(); @Override void setUpdateRate(int rate); }### Answer: @Test public void testGetRainbowHost() throws IOException { System.out.println("getRainbowHost"); String expResult = "127.0.0.1"; String result = instance.getRainbowHost(); assertEquals(expResult, result); }
### Question: SystemConfiguration extends Properties implements ISystemConfiguration { @Override public short getRainbowPort() { String prop = getProperty("rainbow.port"); return Short.valueOf(prop); } SystemConfiguration(String filename); @Override String getRainbowHost(); @Override void setRainbowHost(String host); @Override short getRainbowPort(); @Override void setRainbowPort(short port); @Override String getModelPath(); @Override void setModelPath(String path); @Override String getNode(); @Override void setNode(String node); @Override boolean isAttached(); @Override void setAttached(boolean attached); @Override String getConfigDir(); @Override void setConfigDir(String path); @Override int getSnapshotRate(); @Override void setSnapshotRate(int rate); @Override boolean isModelLocal(); @Override void setModelLocal(boolean local); @Override String getModelName(); @Override void setModelName(String name); @Override String getModelFactoryClass(); @Override void setModelFactoryClass(String cls); @Override int getUpdateRate(); @Override void setUpdateRate(int rate); }### Answer: @Test public void testGetRainbowPort() { System.out.println("getRainbowPort"); short expResult = 1100; short result = instance.getRainbowPort(); assertEquals(expResult, result); }
### Question: SystemConfiguration extends Properties implements ISystemConfiguration { @Override public String getModelPath() { String prop = getProperty("ingestion.model.path"); return prop; } SystemConfiguration(String filename); @Override String getRainbowHost(); @Override void setRainbowHost(String host); @Override short getRainbowPort(); @Override void setRainbowPort(short port); @Override String getModelPath(); @Override void setModelPath(String path); @Override String getNode(); @Override void setNode(String node); @Override boolean isAttached(); @Override void setAttached(boolean attached); @Override String getConfigDir(); @Override void setConfigDir(String path); @Override int getSnapshotRate(); @Override void setSnapshotRate(int rate); @Override boolean isModelLocal(); @Override void setModelLocal(boolean local); @Override String getModelName(); @Override void setModelName(String name); @Override String getModelFactoryClass(); @Override void setModelFactoryClass(String cls); @Override int getUpdateRate(); @Override void setUpdateRate(int rate); }### Answer: @Test public void testGetModelPath() { System.out.println("getModelPath"); String expResult = "ZNewsSys.acme"; String result = instance.getModelPath(); assertEquals(expResult, result); }
### Question: SystemConfiguration extends Properties implements ISystemConfiguration { @Override public String getNode() { String prop = getProperty("storage.cassandra.node"); return prop; } SystemConfiguration(String filename); @Override String getRainbowHost(); @Override void setRainbowHost(String host); @Override short getRainbowPort(); @Override void setRainbowPort(short port); @Override String getModelPath(); @Override void setModelPath(String path); @Override String getNode(); @Override void setNode(String node); @Override boolean isAttached(); @Override void setAttached(boolean attached); @Override String getConfigDir(); @Override void setConfigDir(String path); @Override int getSnapshotRate(); @Override void setSnapshotRate(int rate); @Override boolean isModelLocal(); @Override void setModelLocal(boolean local); @Override String getModelName(); @Override void setModelName(String name); @Override String getModelFactoryClass(); @Override void setModelFactoryClass(String cls); @Override int getUpdateRate(); @Override void setUpdateRate(int rate); }### Answer: @Test public void testGetNode() { System.out.println("getNode"); String expResult = "127.0.0.1"; String result = instance.getNode(); assertEquals(expResult, result); }
### Question: SystemConfiguration extends Properties implements ISystemConfiguration { @Override public boolean isAttached() { String prop = getProperty("ingestion.attach.onstartup"); return Boolean.valueOf(prop); } SystemConfiguration(String filename); @Override String getRainbowHost(); @Override void setRainbowHost(String host); @Override short getRainbowPort(); @Override void setRainbowPort(short port); @Override String getModelPath(); @Override void setModelPath(String path); @Override String getNode(); @Override void setNode(String node); @Override boolean isAttached(); @Override void setAttached(boolean attached); @Override String getConfigDir(); @Override void setConfigDir(String path); @Override int getSnapshotRate(); @Override void setSnapshotRate(int rate); @Override boolean isModelLocal(); @Override void setModelLocal(boolean local); @Override String getModelName(); @Override void setModelName(String name); @Override String getModelFactoryClass(); @Override void setModelFactoryClass(String cls); @Override int getUpdateRate(); @Override void setUpdateRate(int rate); }### Answer: @Test public void testIsAttached() { System.out.println("isAttached"); boolean expResult = true; boolean result = instance.isAttached(); assertEquals(expResult, result); }
### Question: SystemConfiguration extends Properties implements ISystemConfiguration { @Override public void setAttached(boolean attached) { setProperty("ingestion.attach.onstartup", Boolean.toString(attached)); } SystemConfiguration(String filename); @Override String getRainbowHost(); @Override void setRainbowHost(String host); @Override short getRainbowPort(); @Override void setRainbowPort(short port); @Override String getModelPath(); @Override void setModelPath(String path); @Override String getNode(); @Override void setNode(String node); @Override boolean isAttached(); @Override void setAttached(boolean attached); @Override String getConfigDir(); @Override void setConfigDir(String path); @Override int getSnapshotRate(); @Override void setSnapshotRate(int rate); @Override boolean isModelLocal(); @Override void setModelLocal(boolean local); @Override String getModelName(); @Override void setModelName(String name); @Override String getModelFactoryClass(); @Override void setModelFactoryClass(String cls); @Override int getUpdateRate(); @Override void setUpdateRate(int rate); }### Answer: @Test public void testSetAttached() { System.out.println("setAttached"); boolean attached = false; instance.setAttached(attached); boolean result = instance.isAttached(); assertEquals(attached, result); }
### Question: SystemConfiguration extends Properties implements ISystemConfiguration { @Override public void setRainbowHost(String host) { setProperty("rainbow.host", host); } SystemConfiguration(String filename); @Override String getRainbowHost(); @Override void setRainbowHost(String host); @Override short getRainbowPort(); @Override void setRainbowPort(short port); @Override String getModelPath(); @Override void setModelPath(String path); @Override String getNode(); @Override void setNode(String node); @Override boolean isAttached(); @Override void setAttached(boolean attached); @Override String getConfigDir(); @Override void setConfigDir(String path); @Override int getSnapshotRate(); @Override void setSnapshotRate(int rate); @Override boolean isModelLocal(); @Override void setModelLocal(boolean local); @Override String getModelName(); @Override void setModelName(String name); @Override String getModelFactoryClass(); @Override void setModelFactoryClass(String cls); @Override int getUpdateRate(); @Override void setUpdateRate(int rate); }### Answer: @Test public void testSetRainbowHost() { System.out.println("setRainbowHost"); String host = "192.168.0.1"; instance.setRainbowHost(host); String result = instance.getRainbowHost(); assertEquals(host, result); }
### Question: SystemConfiguration extends Properties implements ISystemConfiguration { @Override public void setRainbowPort(short port) { setProperty("rainbow.port", Short.toString(port)); } SystemConfiguration(String filename); @Override String getRainbowHost(); @Override void setRainbowHost(String host); @Override short getRainbowPort(); @Override void setRainbowPort(short port); @Override String getModelPath(); @Override void setModelPath(String path); @Override String getNode(); @Override void setNode(String node); @Override boolean isAttached(); @Override void setAttached(boolean attached); @Override String getConfigDir(); @Override void setConfigDir(String path); @Override int getSnapshotRate(); @Override void setSnapshotRate(int rate); @Override boolean isModelLocal(); @Override void setModelLocal(boolean local); @Override String getModelName(); @Override void setModelName(String name); @Override String getModelFactoryClass(); @Override void setModelFactoryClass(String cls); @Override int getUpdateRate(); @Override void setUpdateRate(int rate); }### Answer: @Test public void testSetRainbowPort() { System.out.println("setRainbowPort"); short port = 2200; instance.setRainbowPort(port); short result = instance.getRainbowPort(); assertEquals(port, result); }
### Question: SystemConfiguration extends Properties implements ISystemConfiguration { @Override public void setModelPath(String path) { setProperty("ingestion.model.path", path); } SystemConfiguration(String filename); @Override String getRainbowHost(); @Override void setRainbowHost(String host); @Override short getRainbowPort(); @Override void setRainbowPort(short port); @Override String getModelPath(); @Override void setModelPath(String path); @Override String getNode(); @Override void setNode(String node); @Override boolean isAttached(); @Override void setAttached(boolean attached); @Override String getConfigDir(); @Override void setConfigDir(String path); @Override int getSnapshotRate(); @Override void setSnapshotRate(int rate); @Override boolean isModelLocal(); @Override void setModelLocal(boolean local); @Override String getModelName(); @Override void setModelName(String name); @Override String getModelFactoryClass(); @Override void setModelFactoryClass(String cls); @Override int getUpdateRate(); @Override void setUpdateRate(int rate); }### Answer: @Test public void testSetModelPath() { System.out.println("setModelPath"); String path = "Model.acme"; instance.setModelPath(path); String result = instance.getModelPath(); assertEquals(path, result); }
### Question: SystemConfiguration extends Properties implements ISystemConfiguration { @Override public void setNode(String node) { setProperty("storage.cassandra.node", node); } SystemConfiguration(String filename); @Override String getRainbowHost(); @Override void setRainbowHost(String host); @Override short getRainbowPort(); @Override void setRainbowPort(short port); @Override String getModelPath(); @Override void setModelPath(String path); @Override String getNode(); @Override void setNode(String node); @Override boolean isAttached(); @Override void setAttached(boolean attached); @Override String getConfigDir(); @Override void setConfigDir(String path); @Override int getSnapshotRate(); @Override void setSnapshotRate(int rate); @Override boolean isModelLocal(); @Override void setModelLocal(boolean local); @Override String getModelName(); @Override void setModelName(String name); @Override String getModelFactoryClass(); @Override void setModelFactoryClass(String cls); @Override int getUpdateRate(); @Override void setUpdateRate(int rate); }### Answer: @Test public void testSetNode() { System.out.println("setNode"); String node = ""; instance.setNode(node); String result = instance.getNode(); assertEquals(result, result); }
### Question: SystemConfiguration extends Properties implements ISystemConfiguration { @Override public String getConfigDir() { return configDir; } SystemConfiguration(String filename); @Override String getRainbowHost(); @Override void setRainbowHost(String host); @Override short getRainbowPort(); @Override void setRainbowPort(short port); @Override String getModelPath(); @Override void setModelPath(String path); @Override String getNode(); @Override void setNode(String node); @Override boolean isAttached(); @Override void setAttached(boolean attached); @Override String getConfigDir(); @Override void setConfigDir(String path); @Override int getSnapshotRate(); @Override void setSnapshotRate(int rate); @Override boolean isModelLocal(); @Override void setModelLocal(boolean local); @Override String getModelName(); @Override void setModelName(String name); @Override String getModelFactoryClass(); @Override void setModelFactoryClass(String cls); @Override int getUpdateRate(); @Override void setUpdateRate(int rate); }### Answer: @Test public void testGetConfigDir() { System.out.println("getConfigDir"); String expResult = "./"; String result = instance.getConfigDir(); assertEquals(expResult, result); }
### Question: SystemConfiguration extends Properties implements ISystemConfiguration { @Override public void setConfigDir(String path) { configDir = path; } SystemConfiguration(String filename); @Override String getRainbowHost(); @Override void setRainbowHost(String host); @Override short getRainbowPort(); @Override void setRainbowPort(short port); @Override String getModelPath(); @Override void setModelPath(String path); @Override String getNode(); @Override void setNode(String node); @Override boolean isAttached(); @Override void setAttached(boolean attached); @Override String getConfigDir(); @Override void setConfigDir(String path); @Override int getSnapshotRate(); @Override void setSnapshotRate(int rate); @Override boolean isModelLocal(); @Override void setModelLocal(boolean local); @Override String getModelName(); @Override void setModelName(String name); @Override String getModelFactoryClass(); @Override void setModelFactoryClass(String cls); @Override int getUpdateRate(); @Override void setUpdateRate(int rate); }### Answer: @Test public void testSetConfigDir() { System.out.println("setConfigDir"); String path = "dir"; instance.setConfigDir(path); String result = instance.getConfigDir(); assertEquals(path, result); }
### Question: SystemConfiguration extends Properties implements ISystemConfiguration { @Override public int getSnapshotRate() { String prop = getProperty("ingestion.snapshot.rate"); return Integer.valueOf(prop); } SystemConfiguration(String filename); @Override String getRainbowHost(); @Override void setRainbowHost(String host); @Override short getRainbowPort(); @Override void setRainbowPort(short port); @Override String getModelPath(); @Override void setModelPath(String path); @Override String getNode(); @Override void setNode(String node); @Override boolean isAttached(); @Override void setAttached(boolean attached); @Override String getConfigDir(); @Override void setConfigDir(String path); @Override int getSnapshotRate(); @Override void setSnapshotRate(int rate); @Override boolean isModelLocal(); @Override void setModelLocal(boolean local); @Override String getModelName(); @Override void setModelName(String name); @Override String getModelFactoryClass(); @Override void setModelFactoryClass(String cls); @Override int getUpdateRate(); @Override void setUpdateRate(int rate); }### Answer: @Test public void testGetSnapshotRate() { System.out.println("getSnapshotRate"); int expResult = 10; int result = instance.getSnapshotRate(); assertEquals(expResult, result); }
### Question: SystemConfiguration extends Properties implements ISystemConfiguration { @Override public void setSnapshotRate(int rate) { setProperty("ingestion.snapshot.rate", Integer.toString(rate)); } SystemConfiguration(String filename); @Override String getRainbowHost(); @Override void setRainbowHost(String host); @Override short getRainbowPort(); @Override void setRainbowPort(short port); @Override String getModelPath(); @Override void setModelPath(String path); @Override String getNode(); @Override void setNode(String node); @Override boolean isAttached(); @Override void setAttached(boolean attached); @Override String getConfigDir(); @Override void setConfigDir(String path); @Override int getSnapshotRate(); @Override void setSnapshotRate(int rate); @Override boolean isModelLocal(); @Override void setModelLocal(boolean local); @Override String getModelName(); @Override void setModelName(String name); @Override String getModelFactoryClass(); @Override void setModelFactoryClass(String cls); @Override int getUpdateRate(); @Override void setUpdateRate(int rate); }### Answer: @Test public void testSetSnapshotRate() { System.out.println("setSnapshotRate"); int rate = 100; instance.setSnapshotRate(rate); int result = instance.getSnapshotRate(); assertEquals(rate, result); }
### Question: SystemConfiguration extends Properties implements ISystemConfiguration { @Override public boolean isModelLocal() { String prop = getProperty("ingestion.model.local", "false"); return Boolean.valueOf(prop); } SystemConfiguration(String filename); @Override String getRainbowHost(); @Override void setRainbowHost(String host); @Override short getRainbowPort(); @Override void setRainbowPort(short port); @Override String getModelPath(); @Override void setModelPath(String path); @Override String getNode(); @Override void setNode(String node); @Override boolean isAttached(); @Override void setAttached(boolean attached); @Override String getConfigDir(); @Override void setConfigDir(String path); @Override int getSnapshotRate(); @Override void setSnapshotRate(int rate); @Override boolean isModelLocal(); @Override void setModelLocal(boolean local); @Override String getModelName(); @Override void setModelName(String name); @Override String getModelFactoryClass(); @Override void setModelFactoryClass(String cls); @Override int getUpdateRate(); @Override void setUpdateRate(int rate); }### Answer: @Test public void testIsModelLocal() { System.out.println("isModelLocal"); boolean expResult = true; boolean result = instance.isModelLocal(); assertEquals(expResult, result); instance.remove("ingestion.model.local"); expResult = false; result = instance.isModelLocal(); assertEquals(expResult, result); }
### Question: SystemConfiguration extends Properties implements ISystemConfiguration { @Override public void setModelLocal(boolean local) { setProperty("ingestion.model.local", Boolean.toString(local)); } SystemConfiguration(String filename); @Override String getRainbowHost(); @Override void setRainbowHost(String host); @Override short getRainbowPort(); @Override void setRainbowPort(short port); @Override String getModelPath(); @Override void setModelPath(String path); @Override String getNode(); @Override void setNode(String node); @Override boolean isAttached(); @Override void setAttached(boolean attached); @Override String getConfigDir(); @Override void setConfigDir(String path); @Override int getSnapshotRate(); @Override void setSnapshotRate(int rate); @Override boolean isModelLocal(); @Override void setModelLocal(boolean local); @Override String getModelName(); @Override void setModelName(String name); @Override String getModelFactoryClass(); @Override void setModelFactoryClass(String cls); @Override int getUpdateRate(); @Override void setUpdateRate(int rate); }### Answer: @Test public void testSetModelLocal() { System.out.println("setModelLocal"); boolean local = false; instance.setModelLocal(local); boolean result = instance.isModelLocal(); assertEquals(local, result); }
### Question: SystemConfiguration extends Properties implements ISystemConfiguration { @Override public String getModelName() { return getProperty("ingestion.model.name"); } SystemConfiguration(String filename); @Override String getRainbowHost(); @Override void setRainbowHost(String host); @Override short getRainbowPort(); @Override void setRainbowPort(short port); @Override String getModelPath(); @Override void setModelPath(String path); @Override String getNode(); @Override void setNode(String node); @Override boolean isAttached(); @Override void setAttached(boolean attached); @Override String getConfigDir(); @Override void setConfigDir(String path); @Override int getSnapshotRate(); @Override void setSnapshotRate(int rate); @Override boolean isModelLocal(); @Override void setModelLocal(boolean local); @Override String getModelName(); @Override void setModelName(String name); @Override String getModelFactoryClass(); @Override void setModelFactoryClass(String cls); @Override int getUpdateRate(); @Override void setUpdateRate(int rate); }### Answer: @Test public void testGetModelName() { System.out.println("getModelName"); String expResult = "ZNewsSys"; String result = instance.getModelName(); assertEquals(expResult, result); }
### Question: SystemConfiguration extends Properties implements ISystemConfiguration { @Override public void setModelName(String name) { setProperty("ingestion.model.name", name); } SystemConfiguration(String filename); @Override String getRainbowHost(); @Override void setRainbowHost(String host); @Override short getRainbowPort(); @Override void setRainbowPort(short port); @Override String getModelPath(); @Override void setModelPath(String path); @Override String getNode(); @Override void setNode(String node); @Override boolean isAttached(); @Override void setAttached(boolean attached); @Override String getConfigDir(); @Override void setConfigDir(String path); @Override int getSnapshotRate(); @Override void setSnapshotRate(int rate); @Override boolean isModelLocal(); @Override void setModelLocal(boolean local); @Override String getModelName(); @Override void setModelName(String name); @Override String getModelFactoryClass(); @Override void setModelFactoryClass(String cls); @Override int getUpdateRate(); @Override void setUpdateRate(int rate); }### Answer: @Test public void testSetModelName() { System.out.println("setModelName"); String name = "ZNN"; instance.setModelName(name); String result = instance.getModelName(); assertEquals(name, result); }
### Question: SystemConfiguration extends Properties implements ISystemConfiguration { @Override public String getModelFactoryClass() { return getProperty("ingestion.model.factory"); } SystemConfiguration(String filename); @Override String getRainbowHost(); @Override void setRainbowHost(String host); @Override short getRainbowPort(); @Override void setRainbowPort(short port); @Override String getModelPath(); @Override void setModelPath(String path); @Override String getNode(); @Override void setNode(String node); @Override boolean isAttached(); @Override void setAttached(boolean attached); @Override String getConfigDir(); @Override void setConfigDir(String path); @Override int getSnapshotRate(); @Override void setSnapshotRate(int rate); @Override boolean isModelLocal(); @Override void setModelLocal(boolean local); @Override String getModelName(); @Override void setModelName(String name); @Override String getModelFactoryClass(); @Override void setModelFactoryClass(String cls); @Override int getUpdateRate(); @Override void setUpdateRate(int rate); }### Answer: @Test public void testGetModelFactoryClass() { System.out.println("getModelFactoryClass"); String expResult = "edu.cmu.rainbow_ui.ingestion.AcmeInternalCommandFactory"; String result = instance.getModelFactoryClass(); assertEquals(expResult, result); }
### Question: SystemConfiguration extends Properties implements ISystemConfiguration { @Override public void setModelFactoryClass(String cls) { setProperty("ingestion.model.factory", cls); } SystemConfiguration(String filename); @Override String getRainbowHost(); @Override void setRainbowHost(String host); @Override short getRainbowPort(); @Override void setRainbowPort(short port); @Override String getModelPath(); @Override void setModelPath(String path); @Override String getNode(); @Override void setNode(String node); @Override boolean isAttached(); @Override void setAttached(boolean attached); @Override String getConfigDir(); @Override void setConfigDir(String path); @Override int getSnapshotRate(); @Override void setSnapshotRate(int rate); @Override boolean isModelLocal(); @Override void setModelLocal(boolean local); @Override String getModelName(); @Override void setModelName(String name); @Override String getModelFactoryClass(); @Override void setModelFactoryClass(String cls); @Override int getUpdateRate(); @Override void setUpdateRate(int rate); }### Answer: @Test public void testSetModelFactoryClass() { System.out.println("setModelFactoryClass"); String cls = "org.sa.rainbow.model.acme.znn.commands.ZNNCommandFactory"; instance.setModelFactoryClass(cls); String result = instance.getModelFactoryClass(); assertEquals(cls, result); }
### Question: HistoryProvider implements IHistoryProvider { @Override public IModelInstance<?> getModelState(Date time) { Logger.getLogger(HistoryProvider.class.getName()).log( Level.INFO, "Model Requested for time: {0}", time.toString()); Pair<Date, IModelInstance<?>> modelraw = databaseconn .getLatestSnapshot(time); Logger.getLogger(HistoryProvider.class.getName()).log( Level.INFO, "Got model for time: {0}", time.toString()); IModelInstance<IAcmeSystem> model = null; if (modelraw != null) { model = (IModelInstance<IAcmeSystem>) modelraw .getValue(); ArrayList<IRainbowMessage> events = (ArrayList<IRainbowMessage>) databaseconn .getModelEventRange(modelraw.getKey(), time); Logger.getLogger(HistoryProvider.class.getName()).log( Level.INFO, "Got {0} events to apply to the model", events.size()); for (IRainbowMessage event : events) { try { IAcmeCommand<?> command = deserializer.deserialize(event, model.getModelInstance()); synchronized (copyLock) { command.execute(); } }catch (IllegalStateException | AcmeException | RainbowDeserializationException ex) { Logger.getLogger(HistoryProvider.class.getName()).log( Level.SEVERE, null, ex); } } } return model; } HistoryProvider(IDatabaseConnector databaseCon); HistoryProvider(ISystemViewProvider acmeSystemViewProvider, ISystemConfiguration systemConfig); @Override IModelInstance<?> getModelState(Date time); @Override ArrayList<IRainbowMessage> getEventRange(Date startTime, Date endTime); @Override ArrayList<IRainbowMessage> getEventRangeByType(String channel, Date startTime, Date endTime); @Override ArrayList<IRainbowMessage> getModelEventRange(Date startTime, Date endTime); @Override IRainbowMessage getEvent(Date time); @Override void setSession(String name); @Override ArrayList<String> getSessionList(); String getReadSession(); @Override Date getStartDate(); @Override boolean currentSessionIsWriteSession(); @Override Date getMaxDate(); @Override List<IRainbowMessage> getNumberOfEventsBefore(Date endTime, int numEvents); @Override void closeDatabaseConnection(); }### Answer: @Test public void testgetModelState() { IModelInstance<?> modelstate = null; Calendar cal = Calendar.getInstance(); Date date = cal.getTime(); modelstate = hp.getModelState(date); assertNotNull(modelstate); }
### Question: HistoryProvider implements IHistoryProvider { @Override public ArrayList<IRainbowMessage> getEventRange(Date startTime, Date endTime) { ArrayList<IRainbowMessage> model; model = (ArrayList<IRainbowMessage>) databaseconn.getEventRange( startTime, endTime); return model; } HistoryProvider(IDatabaseConnector databaseCon); HistoryProvider(ISystemViewProvider acmeSystemViewProvider, ISystemConfiguration systemConfig); @Override IModelInstance<?> getModelState(Date time); @Override ArrayList<IRainbowMessage> getEventRange(Date startTime, Date endTime); @Override ArrayList<IRainbowMessage> getEventRangeByType(String channel, Date startTime, Date endTime); @Override ArrayList<IRainbowMessage> getModelEventRange(Date startTime, Date endTime); @Override IRainbowMessage getEvent(Date time); @Override void setSession(String name); @Override ArrayList<String> getSessionList(); String getReadSession(); @Override Date getStartDate(); @Override boolean currentSessionIsWriteSession(); @Override Date getMaxDate(); @Override List<IRainbowMessage> getNumberOfEventsBefore(Date endTime, int numEvents); @Override void closeDatabaseConnection(); }### Answer: @Test public void testgetEventRange() { List<IRainbowMessage> events = null; Calendar cal1 = Calendar.getInstance(); Date date1 = cal1.getTime(); Calendar cal2 = Calendar.getInstance(); Date date2 = cal2.getTime(); events = hp.getEventRange(date1, date2); assertNotNull(events); }
### Question: HistoryProvider implements IHistoryProvider { @Override public ArrayList<IRainbowMessage> getEventRangeByType(String channel, Date startTime, Date endTime) { ArrayList<IRainbowMessage> model; model = (ArrayList<IRainbowMessage>) databaseconn.getEventRangeByType( channel, startTime, endTime); return model; } HistoryProvider(IDatabaseConnector databaseCon); HistoryProvider(ISystemViewProvider acmeSystemViewProvider, ISystemConfiguration systemConfig); @Override IModelInstance<?> getModelState(Date time); @Override ArrayList<IRainbowMessage> getEventRange(Date startTime, Date endTime); @Override ArrayList<IRainbowMessage> getEventRangeByType(String channel, Date startTime, Date endTime); @Override ArrayList<IRainbowMessage> getModelEventRange(Date startTime, Date endTime); @Override IRainbowMessage getEvent(Date time); @Override void setSession(String name); @Override ArrayList<String> getSessionList(); String getReadSession(); @Override Date getStartDate(); @Override boolean currentSessionIsWriteSession(); @Override Date getMaxDate(); @Override List<IRainbowMessage> getNumberOfEventsBefore(Date endTime, int numEvents); @Override void closeDatabaseConnection(); }### Answer: @Test public void testgetEventRangeByType() { List<IRainbowMessage> events = null; Calendar cal1 = Calendar.getInstance(); Date date1 = cal1.getTime(); Calendar cal2 = Calendar.getInstance(); Date date2 = cal2.getTime(); events = hp.getEventRangeByType("channel", date1, date2); assertNotNull(events); }