method2testcases
stringlengths 118
6.63k
|
---|
### Question:
IngestMetricsBuilder { public static IngestMetrics createInterpretedToHdfsViewMetrics() { return IngestMetrics.create() .addMetric(OccurrenceHdfsRecordConverterTransform.class, AVRO_TO_HDFS_COUNT); } static IngestMetrics createVerbatimToInterpretedMetrics(); static IngestMetrics createInterpretedToEsIndexMetrics(); static IngestMetrics createInterpretedToHdfsViewMetrics(); }### Answer:
@Test public void createInterpretedToHdfsViewMetricsTest() { IngestMetrics metrics = IngestMetricsBuilder.createInterpretedToHdfsViewMetrics(); metrics.incMetric(AVRO_TO_HDFS_COUNT); MetricResults result = metrics.getMetricsResult(); Map<String, Long> map = new HashMap<>(); result .allMetrics() .getCounters() .forEach(mr -> map.put(mr.getName().getName(), mr.getAttempted())); Assert.assertEquals(1, map.size()); Assert.assertEquals(Long.valueOf(1L), map.get(AVRO_TO_HDFS_COUNT)); } |
### Question:
Columns { public static String column(Term term) { if (term instanceof GbifInternalTerm || TermUtils.isOccurrenceJavaProperty(term) || GbifTerm.mediaType == term) { return column(term, ""); } else if (TermUtils.isInterpretedSourceTerm(term)) { throw new IllegalArgumentException( "The term " + term + " is interpreted and only relevant for verbatim values"); } else { return verbatimColumn(term); } } static String column(Term term); static String verbatimColumn(Term term); static final String OCCURRENCE_COLUMN_FAMILY; static final byte[] CF; static final String COUNTER_COLUMN; static final String LOOKUP_KEY_COLUMN; static final String LOOKUP_LOCK_COLUMN; static final String LOOKUP_STATUS_COLUMN; }### Answer:
@Test public void testGetColumn() { assertEquals("scientificName", Columns.column(DwcTerm.scientificName)); assertEquals("countryCode", Columns.column(DwcTerm.countryCode)); assertEquals("v_catalogNumber", Columns.column(DwcTerm.catalogNumber)); assertEquals("class", Columns.column(DwcTerm.class_)); assertEquals("order", Columns.column(DwcTerm.order)); assertEquals("kingdomKey", Columns.column(GbifTerm.kingdomKey)); assertEquals("taxonKey", Columns.column(GbifTerm.taxonKey)); assertEquals("v_occurrenceID", Columns.column(DwcTerm.occurrenceID)); assertEquals("v_taxonID", Columns.column(DwcTerm.taxonID)); assertEquals("basisOfRecord", Columns.column(DwcTerm.basisOfRecord)); assertEquals("taxonKey", Columns.column(GbifTerm.taxonKey)); }
@Test(expected = IllegalArgumentException.class) public void testGetColumnIllegal3() { Columns.column(DwcTerm.country); } |
### Question:
Columns { public static String verbatimColumn(Term term) { if (term instanceof GbifInternalTerm) { throw new IllegalArgumentException( "Internal terms (like the tried [" + term.simpleName() + "]) do not exist as verbatim columns"); } return column(term, VERBATIM_TERM_PREFIX); } static String column(Term term); static String verbatimColumn(Term term); static final String OCCURRENCE_COLUMN_FAMILY; static final byte[] CF; static final String COUNTER_COLUMN; static final String LOOKUP_KEY_COLUMN; static final String LOOKUP_LOCK_COLUMN; static final String LOOKUP_STATUS_COLUMN; }### Answer:
@Test(expected = IllegalArgumentException.class) public void testGetVerbatimColumnIllegal() { Columns.verbatimColumn(GbifInternalTerm.crawlId); }
@Test public void testGetVerbatimColumn() { assertEquals("v_basisOfRecord", Columns.verbatimColumn(DwcTerm.basisOfRecord)); } |
### Question:
XmlFragmentParser { public static List<RawOccurrenceRecord> parseRecord(RawXmlOccurrence xmlRecord) { return parseRecord(xmlRecord.getXml(), xmlRecord.getSchemaType()); } private XmlFragmentParser(); static List<RawOccurrenceRecord> parseRecord(RawXmlOccurrence xmlRecord); static List<RawOccurrenceRecord> parseRecord(String xml, OccurrenceSchemaType schemaType); static List<RawOccurrenceRecord> parseRecord(byte[] xml, OccurrenceSchemaType schemaType); static RawOccurrenceRecord parseRecord(
byte[] xml, OccurrenceSchemaType schemaType, String unitQualifier); static Set<IdentifierExtractionResult> extractIdentifiers(
UUID datasetKey,
byte[] xml,
OccurrenceSchemaType schemaType,
boolean useTriplet,
boolean useOccurrenceId); }### Answer:
@Test public void testUtf8a() throws IOException { String xml = Resources.toString( Resources.getResource("id_extraction/abcd1_umlaut.xml"), StandardCharsets.UTF_8); RawXmlOccurrence rawRecord = createFakeOcc(xml); List<RawOccurrenceRecord> results = XmlFragmentParser.parseRecord(rawRecord); assertEquals(1, results.size()); assertEquals("Oschütz", results.get(0).getCollectorName()); } |
### Question:
HttpResponseParser { static Set<String> parseIndexesInAliasResponse(HttpEntity entity) { return JsonHandler.readValue(entity).keySet(); } }### Answer:
@Test public void parseIndexesTest() { String path = "/responses/alias-indexes.json"; Set<String> indexes = HttpResponseParser.parseIndexesInAliasResponse(getEntityFromResponse(path)); assertEquals(2, indexes.size()); assertTrue(indexes.contains("idx1")); assertTrue(indexes.contains("idx2")); } |
### Question:
ResponseSchemaDetector { public OccurrenceSchemaType detectSchema(String xml) { OccurrenceSchemaType result = null; for (OccurrenceSchemaType schema : schemaSearchOrder) { log.debug("Checking for schema [{}]", schema); boolean success = checkElements(xml, distinctiveElements.get(schema).values()); if (success) { result = schema; break; } } if (result == null) { log.warn("Could not determine schema for xml [{}]", xml); } return result; } ResponseSchemaDetector(); OccurrenceSchemaType detectSchema(String xml); Map<ResponseElementEnum, String> getResponseElements(OccurrenceSchemaType schemaType); }### Answer:
@Test public void testAbcd1() throws IOException { String xml = Resources.toString( Resources.getResource("response_schema/abcd1.xml"), StandardCharsets.UTF_8); OccurrenceSchemaType result = detector.detectSchema(xml); assertEquals(OccurrenceSchemaType.ABCD_1_2, result); }
@Test public void testAbcd2() throws IOException { String xml = Resources.toString( Resources.getResource("response_schema/abcd2.xml"), StandardCharsets.UTF_8); OccurrenceSchemaType result = detector.detectSchema(xml); assertEquals(OccurrenceSchemaType.ABCD_2_0_6, result); }
@Test public void testDwc1_0() throws IOException { String xml = Resources.toString( Resources.getResource("response_schema/dwc_1_0.xml"), StandardCharsets.UTF_8); OccurrenceSchemaType result = detector.detectSchema(xml); assertEquals(OccurrenceSchemaType.DWC_1_0, result); }
@Test public void testDwc1_4() throws IOException { String xml = Resources.toString( Resources.getResource("response_schema/dwc_1_4.xml"), StandardCharsets.UTF_8); OccurrenceSchemaType result = detector.detectSchema(xml); assertEquals(OccurrenceSchemaType.DWC_1_4, result); }
@Test public void testTapirDwc1_4() throws IOException { String xml = Resources.toString( Resources.getResource("response_schema/tapir_dwc_1_4_contains_unrecorded.xml"), StandardCharsets.UTF_8); OccurrenceSchemaType result = detector.detectSchema(xml); assertEquals(OccurrenceSchemaType.DWC_1_4, result); }
@Test public void testTapirDwc1_4_2() throws IOException { String xml = Resources.toString( Resources.getResource("response_schema/tapir_dwc_1_4_s2.xml"), StandardCharsets.UTF_8); OccurrenceSchemaType result = detector.detectSchema(xml); assertEquals(OccurrenceSchemaType.DWC_1_4, result); }
@Test public void testDwcManis() throws IOException { String xml = Resources.toString( Resources.getResource("response_schema/dwc_manis.xml"), StandardCharsets.UTF_8); OccurrenceSchemaType result = detector.detectSchema(xml); assertEquals(OccurrenceSchemaType.DWC_MANIS, result); }
@Test public void testDwc2009() throws IOException { String xml = Resources.toString( Resources.getResource("response_schema/dwc_2009.xml"), StandardCharsets.UTF_8); OccurrenceSchemaType result = detector.detectSchema(xml); assertEquals(OccurrenceSchemaType.DWC_2009, result); } |
### Question:
EsIndex { public static void swapIndexInAliases(EsConfig config, Set<String> aliases, String index) { Preconditions.checkArgument(aliases != null && !aliases.isEmpty(), "alias is required"); Preconditions.checkArgument(!Strings.isNullOrEmpty(index), "index is required"); swapIndexInAliases( config, aliases, index, Collections.emptySet(), Searching.getDefaultSearchSettings()); } static String createIndex(EsConfig config, IndexParams indexParams); static Optional<String> createIndexIfNotExists(EsConfig config, IndexParams indexParams); static void swapIndexInAliases(EsConfig config, Set<String> aliases, String index); static void swapIndexInAliases(
EsConfig config,
Set<String> aliases,
String index,
Set<String> extraIdxToRemove,
Map<String, String> settings); static long countDocuments(EsConfig config, String index); static Set<String> deleteRecordsByDatasetId(
EsConfig config,
String[] aliases,
String datasetKey,
Predicate<String> indexesToDelete,
int timeoutSec,
int attempts); static Set<String> findDatasetIndexesInAliases(
EsConfig config, String[] aliases, String datasetKey); }### Answer:
@Test(expected = IllegalArgumentException.class) public void swapIndexInAliasNullAliasTest() { EsIndex.swapIndexInAliases(EsConfig.from(DUMMY_HOST), null, "index_1"); thrown.expectMessage("aliases are required"); }
@Test(expected = IllegalArgumentException.class) public void swapIndexInAliasEmptyAliasTest() { EsIndex.swapIndexInAliases(EsConfig.from(DUMMY_HOST), Collections.singleton(""), "index_1"); thrown.expectMessage("aliases are required"); }
@Test(expected = IllegalArgumentException.class) public void swapIndexInAliasNullIndexTest() { EsIndex.swapIndexInAliases(EsConfig.from(DUMMY_HOST), Collections.singleton("alias"), null); thrown.expectMessage("index is required"); }
@Test(expected = IllegalArgumentException.class) public void swapIndexInAliasEmptyIndexTest() { EsIndex.swapIndexInAliases(EsConfig.from(DUMMY_HOST), Collections.singleton("alias"), ""); thrown.expectMessage("index is required"); }
@Test(expected = IllegalArgumentException.class) public void swapIndexInAliasWrongFormatIndexTest() { EsIndex.swapIndexInAliases(EsConfig.from(DUMMY_HOST), Collections.singleton("alias"), "index"); thrown.expectMessage(CoreMatchers.containsString("index has to follow the pattern")); } |
### Question:
OccurrenceExtensionTransform extends DoFn<ExtendedRecord, ExtendedRecord> { public static SingleOutput<ExtendedRecord, ExtendedRecord> create() { return ParDo.of(new OccurrenceExtensionTransform()); } static SingleOutput<ExtendedRecord, ExtendedRecord> create(); void setCounterFn(SerializableConsumer<String> counterFn); @ProcessElement void processElement(@Element ExtendedRecord er, OutputReceiver<ExtendedRecord> out); void convert(ExtendedRecord er, Consumer<ExtendedRecord> resultConsumer); }### Answer:
@Test public void extensionContainsOccurrenceTest() { String id = "1"; String somethingCore = "somethingCore"; String somethingExt = "somethingExt"; Map<String, String> ext1 = new HashMap<>(2); ext1.put(DwcTerm.occurrenceID.qualifiedName(), id); ext1.put(somethingExt, somethingExt); Map<String, String> ext2 = new HashMap<>(2); ext2.put(DwcTerm.occurrenceID.qualifiedName(), id); ext2.put(somethingExt, somethingExt); Map<String, String> ext3 = new HashMap<>(2); ext3.put(DwcTerm.occurrenceID.qualifiedName(), id); ext3.put(somethingExt, somethingExt); ExtendedRecord er = ExtendedRecord.newBuilder() .setId(id) .setCoreTerms(Collections.singletonMap(somethingCore, somethingCore)) .setExtensions( Collections.singletonMap( Occurrence.qualifiedName(), Arrays.asList(ext1, ext2, ext3))) .build(); final List<ExtendedRecord> expected = createCollection( false, false, id + "_" + somethingCore + "_" + somethingExt, id + "_" + somethingCore + "_" + somethingExt, id + "_" + somethingCore + "_" + somethingExt); PCollection<ExtendedRecord> result = p.apply(Create.of(er)).apply(OccurrenceExtensionTransform.create()); PAssert.that(result).containsInAnyOrder(expected); p.run(); }
@Test public void occurrenceExtensionIsEmptyTest() { String id = "1"; String somethingCore = "somethingCore"; Map<String, String> ext = new HashMap<>(2); ext.put(DwcTerm.occurrenceID.qualifiedName(), id); ext.put(somethingCore, somethingCore); ExtendedRecord er = ExtendedRecord.newBuilder() .setId(id) .setCoreTerms(ext) .setExtensions( Collections.singletonMap(Occurrence.qualifiedName(), Collections.emptyList())) .build(); final List<ExtendedRecord> expected = createCollection(true, false, id + "_" + somethingCore); PCollection<ExtendedRecord> result = p.apply(Create.of(er)).apply(OccurrenceExtensionTransform.create()); PAssert.that(result).containsInAnyOrder(expected); p.run(); }
@Test public void noOccurrenceExtensionTest() { String id = "1"; String somethingCore = "somethingCore"; Map<String, String> ext = new HashMap<>(2); ext.put(DwcTerm.occurrenceID.qualifiedName(), id); ext.put(somethingCore, somethingCore); ExtendedRecord er = ExtendedRecord.newBuilder().setId(id).setCoreTerms(ext).build(); final List<ExtendedRecord> expected = createCollection(false, false, id + "_" + somethingCore); PCollection<ExtendedRecord> result = p.apply(Create.of(er)).apply(OccurrenceExtensionTransform.create()); PAssert.that(result).containsInAnyOrder(expected); p.run(); } |
### Question:
CheckTransforms extends PTransform<PCollection<T>, PCollection<T>> { public static boolean checkRecordType(Set<String> types, InterpretationType... type) { boolean matchType = Arrays.stream(type).anyMatch(x -> types.contains(x.name())); boolean all = Arrays.stream(type).anyMatch(x -> types.contains(x.all())); return all || matchType; } @Override PCollection<T> expand(PCollection<T> input); static boolean checkRecordType(Set<String> types, InterpretationType... type); }### Answer:
@Test public void checkRecordTypeAllValueTest() { Set<String> set = Collections.singleton(RecordType.ALL.name()); boolean result = CheckTransforms.checkRecordType(set, RecordType.BASIC, RecordType.AUDUBON); Assert.assertTrue(result); }
@Test public void checkRecordTypeMatchValueTest() { Set<String> set = Collections.singleton(RecordType.BASIC.name()); boolean result = CheckTransforms.checkRecordType(set, RecordType.BASIC, RecordType.AUDUBON); Assert.assertTrue(result); }
@Test public void checkRecordTypeMatchManyValueTest() { Set<String> set = new HashSet<>(); set.add(RecordType.BASIC.name()); set.add(RecordType.AUDUBON.name()); boolean result = CheckTransforms.checkRecordType(set, RecordType.BASIC, RecordType.AUDUBON); Assert.assertTrue(result); }
@Test public void checkRecordTypeMismatchOneValueTest() { Set<String> set = Collections.singleton(RecordType.AMPLIFICATION.name()); boolean result = CheckTransforms.checkRecordType(set, RecordType.BASIC, RecordType.AUDUBON); Assert.assertFalse(result); }
@Test public void checkRecordTypeMismatchManyValueTest() { Set<String> set = new HashSet<>(); set.add(RecordType.AMPLIFICATION.name()); set.add(RecordType.IMAGE.name()); boolean result = CheckTransforms.checkRecordType(set, RecordType.BASIC, RecordType.AUDUBON); Assert.assertFalse(result); } |
### Question:
HashIdTransform extends DoFn<ExtendedRecord, ExtendedRecord> { public static SingleOutput<ExtendedRecord, ExtendedRecord> create(String datasetId) { return ParDo.of(new HashIdTransform(datasetId)); } static SingleOutput<ExtendedRecord, ExtendedRecord> create(String datasetId); @ProcessElement void processElement(@Element ExtendedRecord er, OutputReceiver<ExtendedRecord> out); }### Answer:
@Test public void hashIdTest() { final String datasetId = "f349d447-1c92-4637-ab32-8ae559497032"; final List<ExtendedRecord> input = createCollection("0001_1", "0002_2", "0003_3"); final List<ExtendedRecord> expected = createCollection( "20d8ab138ab4c919cbf32f5d9e667812077a0ee4_1", "1122dc31ba32e386e3a36719699fdb5fb1d2912f_2", "f2b1c436ad680263d74bf1498bf7433d9bb4b31a_3"); PCollection<ExtendedRecord> result = p.apply(Create.of(input)).apply(HashIdTransform.create(datasetId)); PAssert.that(result).containsInAnyOrder(expected); p.run(); } |
### Question:
MetadataServiceClientFactory { public static SerializableSupplier<MetadataServiceClient> getInstanceSupplier( PipelinesConfig config) { return () -> getInstance(config); } @SneakyThrows private MetadataServiceClientFactory(PipelinesConfig config); static MetadataServiceClient getInstance(PipelinesConfig config); static SerializableSupplier<MetadataServiceClient> createSupplier(PipelinesConfig config); static SerializableSupplier<MetadataServiceClient> getInstanceSupplier(
PipelinesConfig config); }### Answer:
@Test public void sameLinkToObjectTest() { PipelinesConfig pc = new PipelinesConfig(); WsConfig wc = new WsConfig(); wc.setWsUrl("https: pc.setGbifApi(wc); SerializableSupplier<MetadataServiceClient> supplierOne = MetadataServiceClientFactory.getInstanceSupplier(pc); SerializableSupplier<MetadataServiceClient> supplierTwo = MetadataServiceClientFactory.getInstanceSupplier(pc); Assert.assertSame(supplierOne.get(), supplierTwo.get()); } |
### Question:
MetadataServiceClientFactory { public static SerializableSupplier<MetadataServiceClient> createSupplier(PipelinesConfig config) { return () -> new MetadataServiceClientFactory(config).client; } @SneakyThrows private MetadataServiceClientFactory(PipelinesConfig config); static MetadataServiceClient getInstance(PipelinesConfig config); static SerializableSupplier<MetadataServiceClient> createSupplier(PipelinesConfig config); static SerializableSupplier<MetadataServiceClient> getInstanceSupplier(
PipelinesConfig config); }### Answer:
@Test public void newObjectTest() { PipelinesConfig pc = new PipelinesConfig(); WsConfig wc = new WsConfig(); wc.setWsUrl("https: pc.setGbifApi(wc); SerializableSupplier<MetadataServiceClient> supplierOne = MetadataServiceClientFactory.createSupplier(pc); SerializableSupplier<MetadataServiceClient> supplierTwo = MetadataServiceClientFactory.createSupplier(pc); Assert.assertNotSame(supplierOne.get(), supplierTwo.get()); } |
### Question:
LocationFeatureInterpreter { public static BiConsumer<LocationRecord, LocationFeatureRecord> interpret( KeyValueStore<LatLng, String> kvStore) { return (lr, asr) -> { if (kvStore != null) { try { String json = kvStore.get(new LatLng(lr.getDecimalLatitude(), lr.getDecimalLongitude())); if (!Strings.isNullOrEmpty(json)) { json = json.substring(11, json.length() - 1); ObjectMapper objectMapper = new ObjectMapper(); Map<String, String> map = objectMapper.readValue(json, new TypeReference<HashMap<String, String>>() {}); asr.setItems(map); } } catch (NoSuchElementException | NullPointerException | IOException ex) { log.error(ex.getMessage(), ex); } } }; } static BiConsumer<LocationRecord, LocationFeatureRecord> interpret(
KeyValueStore<LatLng, String> kvStore); }### Answer:
@Test public void locationFeaturesInterpreterTest() { LocationRecord locationRecord = LocationRecord.newBuilder().setId("777").build(); LocationFeatureRecord record = LocationFeatureRecord.newBuilder().setId("777").build(); KeyValueStore<LatLng, String> kvStore = new KeyValueStore<LatLng, String>() { @Override public String get(LatLng latLng) { return "{\"layers: \"{\"cb1\":\"1\",\"cb2\":\"2\",\"cb3\":\"3\"}}"; } @Override public void close() { } }; Map<String, String> resultMap = new HashMap<>(); resultMap.put("cb1", "1"); resultMap.put("cb2", "2"); resultMap.put("cb3", "3"); LocationFeatureRecord result = LocationFeatureRecord.newBuilder().setId("777").setItems(resultMap).build(); LocationFeatureInterpreter.interpret(kvStore).accept(locationRecord, record); Assert.assertEquals(result, record); } |
### Question:
BasicInterpreter { public static void interpretIndividualCount(ExtendedRecord er, BasicRecord br) { Consumer<Optional<Integer>> fn = parseResult -> { if (parseResult.isPresent()) { br.setIndividualCount(parseResult.get()); } else { addIssue(br, INDIVIDUAL_COUNT_INVALID); } }; SimpleTypeParser.parsePositiveInt(er, DwcTerm.individualCount, fn); } static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId(
HBaseLockingKeyService keygenService,
boolean isTripletValid,
boolean isOccurrenceIdValid,
boolean useExtendedRecordId,
BiConsumer<ExtendedRecord, BasicRecord> gbifIdFn); static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId(
HBaseLockingKeyService keygenService, boolean isTripletValid, boolean isOccurrenceIdValid); static BiConsumer<ExtendedRecord, BasicRecord> interpretCopyGbifId(); static void interpretIndividualCount(ExtendedRecord er, BasicRecord br); static void interpretTypeStatus(ExtendedRecord er, BasicRecord br); static void interpretLifeStage(ExtendedRecord er, BasicRecord br); static void interpretEstablishmentMeans(ExtendedRecord er, BasicRecord br); static void interpretSex(ExtendedRecord er, BasicRecord br); static void interpretBasisOfRecord(ExtendedRecord er, BasicRecord br); static void interpretReferences(ExtendedRecord er, BasicRecord br); static void interpretTypifiedName(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeValue(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeUnit(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantity(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantityType(ExtendedRecord er, BasicRecord br); static void interpretRelativeOrganismQuantity(BasicRecord br); static void interpretLicense(ExtendedRecord er, BasicRecord br); static void interpretIdentifiedByIds(ExtendedRecord er, BasicRecord br); static void interpretRecordedByIds(ExtendedRecord er, BasicRecord br); static BiConsumer<ExtendedRecord, BasicRecord> interpretOccurrenceStatus(
KeyValueStore<String, OccurrenceStatus> occStatusKvStore); static final String GBIF_ID_INVALID; }### Answer:
@Test public void interpretIndividaulCountTest() { Map<String, String> coreMap = new HashMap<>(); coreMap.put(DwcTerm.individualCount.qualifiedName(), "2"); ExtendedRecord er = ExtendedRecord.newBuilder().setId(ID).setCoreTerms(coreMap).build(); BasicRecord br = BasicRecord.newBuilder().setId(ID).build(); BasicInterpreter.interpretIndividualCount(er, br); Assert.assertEquals(Integer.valueOf(2), br.getIndividualCount()); }
@Test public void interpretIndividaulCountNegativedTest() { Map<String, String> coreMap = new HashMap<>(); coreMap.put(DwcTerm.individualCount.qualifiedName(), "-2"); ExtendedRecord er = ExtendedRecord.newBuilder().setId(ID).setCoreTerms(coreMap).build(); BasicRecord br = BasicRecord.newBuilder().setId(ID).build(); BasicInterpreter.interpretIndividualCount(er, br); Assert.assertNull(br.getIndividualCount()); Assert.assertTrue( br.getIssues().getIssueList().contains(OccurrenceIssue.INDIVIDUAL_COUNT_INVALID.name())); }
@Test public void interpretIndividaulCountInvalidTest() { Map<String, String> coreMap = new HashMap<>(); coreMap.put(DwcTerm.individualCount.qualifiedName(), "2.666666667"); ExtendedRecord er = ExtendedRecord.newBuilder().setId(ID).setCoreTerms(coreMap).build(); BasicRecord br = BasicRecord.newBuilder().setId(ID).build(); BasicInterpreter.interpretIndividualCount(er, br); Assert.assertNull(br.getIndividualCount()); Assert.assertTrue( br.getIssues().getIssueList().contains(OccurrenceIssue.INDIVIDUAL_COUNT_INVALID.name())); } |
### Question:
BasicInterpreter { public static void interpretSampleSizeValue(ExtendedRecord er, BasicRecord br) { extractOptValue(er, DwcTerm.sampleSizeValue) .map(String::trim) .map(NumberParser::parseDouble) .filter(x -> !x.isInfinite() && !x.isNaN()) .ifPresent(br::setSampleSizeValue); } static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId(
HBaseLockingKeyService keygenService,
boolean isTripletValid,
boolean isOccurrenceIdValid,
boolean useExtendedRecordId,
BiConsumer<ExtendedRecord, BasicRecord> gbifIdFn); static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId(
HBaseLockingKeyService keygenService, boolean isTripletValid, boolean isOccurrenceIdValid); static BiConsumer<ExtendedRecord, BasicRecord> interpretCopyGbifId(); static void interpretIndividualCount(ExtendedRecord er, BasicRecord br); static void interpretTypeStatus(ExtendedRecord er, BasicRecord br); static void interpretLifeStage(ExtendedRecord er, BasicRecord br); static void interpretEstablishmentMeans(ExtendedRecord er, BasicRecord br); static void interpretSex(ExtendedRecord er, BasicRecord br); static void interpretBasisOfRecord(ExtendedRecord er, BasicRecord br); static void interpretReferences(ExtendedRecord er, BasicRecord br); static void interpretTypifiedName(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeValue(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeUnit(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantity(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantityType(ExtendedRecord er, BasicRecord br); static void interpretRelativeOrganismQuantity(BasicRecord br); static void interpretLicense(ExtendedRecord er, BasicRecord br); static void interpretIdentifiedByIds(ExtendedRecord er, BasicRecord br); static void interpretRecordedByIds(ExtendedRecord er, BasicRecord br); static BiConsumer<ExtendedRecord, BasicRecord> interpretOccurrenceStatus(
KeyValueStore<String, OccurrenceStatus> occStatusKvStore); static final String GBIF_ID_INVALID; }### Answer:
@Test public void interpretSampleSizeValueTest() { Map<String, String> coreMap = new HashMap<>(); coreMap.put(DwcTerm.sampleSizeValue.qualifiedName(), " value "); ExtendedRecord er = ExtendedRecord.newBuilder().setId(ID).setCoreTerms(coreMap).build(); BasicRecord br = BasicRecord.newBuilder().setId(ID).build(); BasicInterpreter.interpretSampleSizeValue(er, br); Assert.assertNull(br.getSampleSizeValue()); } |
### Question:
BasicInterpreter { public static void interpretSampleSizeUnit(ExtendedRecord er, BasicRecord br) { extractOptValue(er, DwcTerm.sampleSizeUnit).map(String::trim).ifPresent(br::setSampleSizeUnit); } static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId(
HBaseLockingKeyService keygenService,
boolean isTripletValid,
boolean isOccurrenceIdValid,
boolean useExtendedRecordId,
BiConsumer<ExtendedRecord, BasicRecord> gbifIdFn); static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId(
HBaseLockingKeyService keygenService, boolean isTripletValid, boolean isOccurrenceIdValid); static BiConsumer<ExtendedRecord, BasicRecord> interpretCopyGbifId(); static void interpretIndividualCount(ExtendedRecord er, BasicRecord br); static void interpretTypeStatus(ExtendedRecord er, BasicRecord br); static void interpretLifeStage(ExtendedRecord er, BasicRecord br); static void interpretEstablishmentMeans(ExtendedRecord er, BasicRecord br); static void interpretSex(ExtendedRecord er, BasicRecord br); static void interpretBasisOfRecord(ExtendedRecord er, BasicRecord br); static void interpretReferences(ExtendedRecord er, BasicRecord br); static void interpretTypifiedName(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeValue(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeUnit(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantity(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantityType(ExtendedRecord er, BasicRecord br); static void interpretRelativeOrganismQuantity(BasicRecord br); static void interpretLicense(ExtendedRecord er, BasicRecord br); static void interpretIdentifiedByIds(ExtendedRecord er, BasicRecord br); static void interpretRecordedByIds(ExtendedRecord er, BasicRecord br); static BiConsumer<ExtendedRecord, BasicRecord> interpretOccurrenceStatus(
KeyValueStore<String, OccurrenceStatus> occStatusKvStore); static final String GBIF_ID_INVALID; }### Answer:
@Test public void interpretSampleSizeUnitTest() { Map<String, String> coreMap = new HashMap<>(); coreMap.put(DwcTerm.sampleSizeUnit.qualifiedName(), " value "); ExtendedRecord er = ExtendedRecord.newBuilder().setId(ID).setCoreTerms(coreMap).build(); BasicRecord br = BasicRecord.newBuilder().setId(ID).build(); BasicInterpreter.interpretSampleSizeUnit(er, br); Assert.assertEquals("value", br.getSampleSizeUnit()); } |
### Question:
BasicInterpreter { public static void interpretOrganismQuantity(ExtendedRecord er, BasicRecord br) { extractOptValue(er, DwcTerm.organismQuantity) .map(String::trim) .map(NumberParser::parseDouble) .filter(x -> !x.isInfinite() && !x.isNaN()) .ifPresent(br::setOrganismQuantity); } static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId(
HBaseLockingKeyService keygenService,
boolean isTripletValid,
boolean isOccurrenceIdValid,
boolean useExtendedRecordId,
BiConsumer<ExtendedRecord, BasicRecord> gbifIdFn); static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId(
HBaseLockingKeyService keygenService, boolean isTripletValid, boolean isOccurrenceIdValid); static BiConsumer<ExtendedRecord, BasicRecord> interpretCopyGbifId(); static void interpretIndividualCount(ExtendedRecord er, BasicRecord br); static void interpretTypeStatus(ExtendedRecord er, BasicRecord br); static void interpretLifeStage(ExtendedRecord er, BasicRecord br); static void interpretEstablishmentMeans(ExtendedRecord er, BasicRecord br); static void interpretSex(ExtendedRecord er, BasicRecord br); static void interpretBasisOfRecord(ExtendedRecord er, BasicRecord br); static void interpretReferences(ExtendedRecord er, BasicRecord br); static void interpretTypifiedName(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeValue(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeUnit(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantity(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantityType(ExtendedRecord er, BasicRecord br); static void interpretRelativeOrganismQuantity(BasicRecord br); static void interpretLicense(ExtendedRecord er, BasicRecord br); static void interpretIdentifiedByIds(ExtendedRecord er, BasicRecord br); static void interpretRecordedByIds(ExtendedRecord er, BasicRecord br); static BiConsumer<ExtendedRecord, BasicRecord> interpretOccurrenceStatus(
KeyValueStore<String, OccurrenceStatus> occStatusKvStore); static final String GBIF_ID_INVALID; }### Answer:
@Test public void interpretOrganismQuantityTest() { Map<String, String> coreMap = new HashMap<>(); coreMap.put(DwcTerm.organismQuantity.qualifiedName(), " value "); ExtendedRecord er = ExtendedRecord.newBuilder().setId(ID).setCoreTerms(coreMap).build(); BasicRecord br = BasicRecord.newBuilder().setId(ID).build(); BasicInterpreter.interpretOrganismQuantity(er, br); Assert.assertNull(br.getOrganismQuantity()); } |
### Question:
BasicInterpreter { public static void interpretOrganismQuantityType(ExtendedRecord er, BasicRecord br) { extractOptValue(er, DwcTerm.organismQuantityType) .map(String::trim) .ifPresent(br::setOrganismQuantityType); } static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId(
HBaseLockingKeyService keygenService,
boolean isTripletValid,
boolean isOccurrenceIdValid,
boolean useExtendedRecordId,
BiConsumer<ExtendedRecord, BasicRecord> gbifIdFn); static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId(
HBaseLockingKeyService keygenService, boolean isTripletValid, boolean isOccurrenceIdValid); static BiConsumer<ExtendedRecord, BasicRecord> interpretCopyGbifId(); static void interpretIndividualCount(ExtendedRecord er, BasicRecord br); static void interpretTypeStatus(ExtendedRecord er, BasicRecord br); static void interpretLifeStage(ExtendedRecord er, BasicRecord br); static void interpretEstablishmentMeans(ExtendedRecord er, BasicRecord br); static void interpretSex(ExtendedRecord er, BasicRecord br); static void interpretBasisOfRecord(ExtendedRecord er, BasicRecord br); static void interpretReferences(ExtendedRecord er, BasicRecord br); static void interpretTypifiedName(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeValue(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeUnit(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantity(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantityType(ExtendedRecord er, BasicRecord br); static void interpretRelativeOrganismQuantity(BasicRecord br); static void interpretLicense(ExtendedRecord er, BasicRecord br); static void interpretIdentifiedByIds(ExtendedRecord er, BasicRecord br); static void interpretRecordedByIds(ExtendedRecord er, BasicRecord br); static BiConsumer<ExtendedRecord, BasicRecord> interpretOccurrenceStatus(
KeyValueStore<String, OccurrenceStatus> occStatusKvStore); static final String GBIF_ID_INVALID; }### Answer:
@Test public void interpretOrganismQuantityTypeTest() { Map<String, String> coreMap = new HashMap<>(); coreMap.put(DwcTerm.organismQuantityType.qualifiedName(), " value "); ExtendedRecord er = ExtendedRecord.newBuilder().setId(ID).setCoreTerms(coreMap).build(); BasicRecord br = BasicRecord.newBuilder().setId(ID).build(); BasicInterpreter.interpretOrganismQuantityType(er, br); Assert.assertEquals("value", br.getOrganismQuantityType()); } |
### Question:
BasicInterpreter { public static void interpretRelativeOrganismQuantity(BasicRecord br) { if (!Strings.isNullOrEmpty(br.getOrganismQuantityType()) && !Strings.isNullOrEmpty(br.getSampleSizeUnit()) && br.getOrganismQuantityType().equalsIgnoreCase(br.getSampleSizeUnit())) { Double organismQuantity = br.getOrganismQuantity(); Double sampleSizeValue = br.getSampleSizeValue(); if (organismQuantity != null && sampleSizeValue != null) { double result = organismQuantity / sampleSizeValue; if (!Double.isNaN(result) && !Double.isInfinite(result)) { br.setRelativeOrganismQuantity(organismQuantity / sampleSizeValue); } } } } static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId(
HBaseLockingKeyService keygenService,
boolean isTripletValid,
boolean isOccurrenceIdValid,
boolean useExtendedRecordId,
BiConsumer<ExtendedRecord, BasicRecord> gbifIdFn); static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId(
HBaseLockingKeyService keygenService, boolean isTripletValid, boolean isOccurrenceIdValid); static BiConsumer<ExtendedRecord, BasicRecord> interpretCopyGbifId(); static void interpretIndividualCount(ExtendedRecord er, BasicRecord br); static void interpretTypeStatus(ExtendedRecord er, BasicRecord br); static void interpretLifeStage(ExtendedRecord er, BasicRecord br); static void interpretEstablishmentMeans(ExtendedRecord er, BasicRecord br); static void interpretSex(ExtendedRecord er, BasicRecord br); static void interpretBasisOfRecord(ExtendedRecord er, BasicRecord br); static void interpretReferences(ExtendedRecord er, BasicRecord br); static void interpretTypifiedName(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeValue(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeUnit(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantity(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantityType(ExtendedRecord er, BasicRecord br); static void interpretRelativeOrganismQuantity(BasicRecord br); static void interpretLicense(ExtendedRecord er, BasicRecord br); static void interpretIdentifiedByIds(ExtendedRecord er, BasicRecord br); static void interpretRecordedByIds(ExtendedRecord er, BasicRecord br); static BiConsumer<ExtendedRecord, BasicRecord> interpretOccurrenceStatus(
KeyValueStore<String, OccurrenceStatus> occStatusKvStore); static final String GBIF_ID_INVALID; }### Answer:
@Test public void interpretRelativeOrganismQuantityTest() { Map<String, String> coreMap = new HashMap<>(); coreMap.put(DwcTerm.sampleSizeValue.qualifiedName(), "2"); coreMap.put(DwcTerm.sampleSizeUnit.qualifiedName(), "some type "); coreMap.put(DwcTerm.organismQuantity.qualifiedName(), "10"); coreMap.put(DwcTerm.organismQuantityType.qualifiedName(), " Some Type"); ExtendedRecord er = ExtendedRecord.newBuilder().setId(ID).setCoreTerms(coreMap).build(); BasicRecord br = BasicRecord.newBuilder().setId(ID).build(); BasicInterpreter.interpretOrganismQuantityType(er, br); BasicInterpreter.interpretOrganismQuantity(er, br); BasicInterpreter.interpretSampleSizeUnit(er, br); BasicInterpreter.interpretSampleSizeValue(er, br); BasicInterpreter.interpretRelativeOrganismQuantity(br); Assert.assertEquals(Double.valueOf(5d), br.getRelativeOrganismQuantity()); } |
### Question:
BasicInterpreter { public static void interpretLicense(ExtendedRecord er, BasicRecord br) { String license = extractOptValue(er, DcTerm.license) .map(BasicInterpreter::getLicense) .map(License::name) .orElse(License.UNSPECIFIED.name()); br.setLicense(license); } static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId(
HBaseLockingKeyService keygenService,
boolean isTripletValid,
boolean isOccurrenceIdValid,
boolean useExtendedRecordId,
BiConsumer<ExtendedRecord, BasicRecord> gbifIdFn); static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId(
HBaseLockingKeyService keygenService, boolean isTripletValid, boolean isOccurrenceIdValid); static BiConsumer<ExtendedRecord, BasicRecord> interpretCopyGbifId(); static void interpretIndividualCount(ExtendedRecord er, BasicRecord br); static void interpretTypeStatus(ExtendedRecord er, BasicRecord br); static void interpretLifeStage(ExtendedRecord er, BasicRecord br); static void interpretEstablishmentMeans(ExtendedRecord er, BasicRecord br); static void interpretSex(ExtendedRecord er, BasicRecord br); static void interpretBasisOfRecord(ExtendedRecord er, BasicRecord br); static void interpretReferences(ExtendedRecord er, BasicRecord br); static void interpretTypifiedName(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeValue(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeUnit(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantity(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantityType(ExtendedRecord er, BasicRecord br); static void interpretRelativeOrganismQuantity(BasicRecord br); static void interpretLicense(ExtendedRecord er, BasicRecord br); static void interpretIdentifiedByIds(ExtendedRecord er, BasicRecord br); static void interpretRecordedByIds(ExtendedRecord er, BasicRecord br); static BiConsumer<ExtendedRecord, BasicRecord> interpretOccurrenceStatus(
KeyValueStore<String, OccurrenceStatus> occStatusKvStore); static final String GBIF_ID_INVALID; }### Answer:
@Test public void interpretLicenseTest() { Map<String, String> coreMap = new HashMap<>(); coreMap.put( "http: ExtendedRecord er = ExtendedRecord.newBuilder().setId(ID).setCoreTerms(coreMap).build(); BasicRecord br = BasicRecord.newBuilder().setId(ID).build(); BasicInterpreter.interpretLicense(er, br); Assert.assertEquals(License.CC_BY_NC_4_0.name(), br.getLicense()); } |
### Question:
TemporalInterpreter implements Serializable { public void interpretDateIdentified(ExtendedRecord er, TemporalRecord tr) { if (hasValue(er, DwcTerm.dateIdentified)) { String value = extractValue(er, DwcTerm.dateIdentified); String normalizedValue = Optional.ofNullable(preprocessDateFn).map(x -> x.apply(value)).orElse(value); LocalDate upperBound = LocalDate.now().plusDays(1); Range<LocalDate> validRecordedDateRange = Range.closed(MIN_LOCAL_DATE, upperBound); OccurrenceParseResult<TemporalAccessor> parsed = temporalParser.parseLocalDate( normalizedValue, validRecordedDateRange, OccurrenceIssue.IDENTIFIED_DATE_UNLIKELY); if (parsed.isSuccessful()) { Optional.ofNullable(parsed.getPayload()) .map(TemporalAccessor::toString) .ifPresent(tr::setDateIdentified); } addIssueSet(tr, parsed.getIssues()); } } @Builder(buildMethodName = "create") private TemporalInterpreter(
List<DateComponentOrdering> orderings,
SerializableFunction<String, String> preprocessDateFn); void interpretTemporal(ExtendedRecord er, TemporalRecord tr); void interpretModified(ExtendedRecord er, TemporalRecord tr); void interpretDateIdentified(ExtendedRecord er, TemporalRecord tr); }### Answer:
@Test public void testLikelyIdentified() { Map<String, String> map = new HashMap<>(); map.put(DwcTerm.year.qualifiedName(), "1879"); map.put(DwcTerm.month.qualifiedName(), "11 "); map.put(DwcTerm.day.qualifiedName(), "1"); map.put(DwcTerm.eventDate.qualifiedName(), "1.11.1879"); map.put(DcTerm.modified.qualifiedName(), "2014-01-11"); ExtendedRecord er = ExtendedRecord.newBuilder().setId("1").setCoreTerms(map).build(); TemporalRecord tr = TemporalRecord.newBuilder().setId("1").build(); TemporalInterpreter interpreter = TemporalInterpreter.builder().create(); er.getCoreTerms().put(DwcTerm.dateIdentified.qualifiedName(), "1987-01-31"); interpreter.interpretDateIdentified(er, tr); assertEquals(0, tr.getIssues().getIssueList().size()); er.getCoreTerms().put(DwcTerm.dateIdentified.qualifiedName(), "1787-03-27"); interpreter.interpretDateIdentified(er, tr); assertEquals(0, tr.getIssues().getIssueList().size()); er.getCoreTerms().put(DwcTerm.dateIdentified.qualifiedName(), "2014-01-11"); interpreter.interpretDateIdentified(er, tr); assertEquals(0, tr.getIssues().getIssueList().size()); er.getCoreTerms().put(DwcTerm.dateIdentified.qualifiedName(), "1997"); interpreter.interpretDateIdentified(er, tr); assertEquals(0, tr.getIssues().getIssueList().size()); Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); er.getCoreTerms() .put(DwcTerm.dateIdentified.qualifiedName(), (cal.get(Calendar.YEAR) + 1) + "-01-11"); interpreter.interpretDateIdentified(er, tr); assertEquals(1, tr.getIssues().getIssueList().size()); assertEquals( OccurrenceIssue.IDENTIFIED_DATE_UNLIKELY.name(), tr.getIssues().getIssueList().iterator().next()); er.getCoreTerms().put(DwcTerm.dateIdentified.qualifiedName(), "1599-01-11"); interpreter.interpretDateIdentified(er, tr); assertEquals(1, tr.getIssues().getIssueList().size()); assertEquals( OccurrenceIssue.IDENTIFIED_DATE_UNLIKELY.name(), tr.getIssues().getIssueList().iterator().next()); } |
### Question:
TemporalInterpreter implements Serializable { public void interpretModified(ExtendedRecord er, TemporalRecord tr) { if (hasValue(er, DcTerm.modified)) { String value = extractValue(er, DcTerm.modified); String normalizedValue = Optional.ofNullable(preprocessDateFn).map(x -> x.apply(value)).orElse(value); LocalDate upperBound = LocalDate.now().plusDays(1); Range<LocalDate> validModifiedDateRange = Range.closed(MIN_EPOCH_LOCAL_DATE, upperBound); OccurrenceParseResult<TemporalAccessor> parsed = temporalParser.parseLocalDate( normalizedValue, validModifiedDateRange, OccurrenceIssue.MODIFIED_DATE_UNLIKELY); if (parsed.isSuccessful()) { Optional.ofNullable(parsed.getPayload()) .map(TemporalAccessor::toString) .ifPresent(tr::setModified); } addIssueSet(tr, parsed.getIssues()); } } @Builder(buildMethodName = "create") private TemporalInterpreter(
List<DateComponentOrdering> orderings,
SerializableFunction<String, String> preprocessDateFn); void interpretTemporal(ExtendedRecord er, TemporalRecord tr); void interpretModified(ExtendedRecord er, TemporalRecord tr); void interpretDateIdentified(ExtendedRecord er, TemporalRecord tr); }### Answer:
@Test public void testLikelyModified() { Map<String, String> map = new HashMap<>(); map.put(DwcTerm.year.qualifiedName(), "1879"); map.put(DwcTerm.month.qualifiedName(), "11 "); map.put(DwcTerm.day.qualifiedName(), "1"); map.put(DwcTerm.eventDate.qualifiedName(), "1.11.1879"); map.put(DwcTerm.dateIdentified.qualifiedName(), "1987-01-31"); ExtendedRecord er = ExtendedRecord.newBuilder().setId("1").setCoreTerms(map).build(); TemporalInterpreter interpreter = TemporalInterpreter.builder().create(); TemporalRecord tr = TemporalRecord.newBuilder().setId("1").build(); er.getCoreTerms().put(DcTerm.modified.qualifiedName(), "2014-01-11"); interpreter.interpretModified(er, tr); assertEquals(0, tr.getIssues().getIssueList().size()); tr = TemporalRecord.newBuilder().setId("1").build(); Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); er.getCoreTerms().put(DcTerm.modified.qualifiedName(), (cal.get(Calendar.YEAR) + 1) + "-01-11"); interpreter.interpretModified(er, tr); assertEquals(1, tr.getIssues().getIssueList().size()); assertEquals( OccurrenceIssue.MODIFIED_DATE_UNLIKELY.name(), tr.getIssues().getIssueList().iterator().next()); tr = TemporalRecord.newBuilder().setId("1").build(); er.getCoreTerms().put(DcTerm.modified.qualifiedName(), "1969-12-31"); interpreter.interpretModified(er, tr); assertEquals(1, tr.getIssues().getIssueList().size()); assertEquals( OccurrenceIssue.MODIFIED_DATE_UNLIKELY.name(), tr.getIssues().getIssueList().iterator().next()); tr = TemporalRecord.newBuilder().setId("1").build(); er.getCoreTerms().put(DcTerm.modified.qualifiedName(), "2018-10-15 16:21:48"); interpreter.interpretModified(er, tr); assertEquals(0, tr.getIssues().getIssueList().size()); assertEquals("2018-10-15T16:21:48", tr.getModified()); } |
### Question:
EsIndex { public static long countDocuments(EsConfig config, String index) { Preconditions.checkArgument(!Strings.isNullOrEmpty(index), "index is required"); log.info("Counting documents from index {}", index); try (EsClient esClient = EsClient.from(config)) { return EsService.countIndexDocuments(esClient, index); } } static String createIndex(EsConfig config, IndexParams indexParams); static Optional<String> createIndexIfNotExists(EsConfig config, IndexParams indexParams); static void swapIndexInAliases(EsConfig config, Set<String> aliases, String index); static void swapIndexInAliases(
EsConfig config,
Set<String> aliases,
String index,
Set<String> extraIdxToRemove,
Map<String, String> settings); static long countDocuments(EsConfig config, String index); static Set<String> deleteRecordsByDatasetId(
EsConfig config,
String[] aliases,
String datasetKey,
Predicate<String> indexesToDelete,
int timeoutSec,
int attempts); static Set<String> findDatasetIndexesInAliases(
EsConfig config, String[] aliases, String datasetKey); }### Answer:
@Test(expected = IllegalArgumentException.class) public void countIndexDocumentsNullIndexTest() { EsIndex.countDocuments(EsConfig.from(DUMMY_HOST), null); thrown.expectMessage("index is required"); }
@Test(expected = IllegalArgumentException.class) public void countIndexDocumentsEmptyIndexTest() { EsIndex.countDocuments(EsConfig.from(DUMMY_HOST), ""); thrown.expectMessage("index is required"); } |
### Question:
SwitchOperationsService implements ILinkOperationsServiceCarrier { public Switch updateSwitchUnderMaintenanceFlag(SwitchId switchId, boolean underMaintenance) throws SwitchNotFoundException { return transactionManager.doInTransaction(() -> { Optional<Switch> foundSwitch = switchRepository.findById(switchId); if (!(foundSwitch.isPresent())) { return Optional.<Switch>empty(); } Switch sw = foundSwitch.get(); if (sw.isUnderMaintenance() == underMaintenance) { switchRepository.detach(sw); return Optional.of(sw); } sw.setUnderMaintenance(underMaintenance); linkOperationsService.getAllIsls(switchId, null, null, null) .forEach(isl -> { try { linkOperationsService.updateLinkUnderMaintenanceFlag( isl.getSrcSwitchId(), isl.getSrcPort(), isl.getDestSwitchId(), isl.getDestPort(), underMaintenance); } catch (IslNotFoundException e) { } }); switchRepository.detach(sw); return Optional.of(sw); }).orElseThrow(() -> new SwitchNotFoundException(switchId)); } SwitchOperationsService(RepositoryFactory repositoryFactory,
TransactionManager transactionManager,
SwitchOperationsServiceCarrier carrier); GetSwitchResponse getSwitch(SwitchId switchId); List<GetSwitchResponse> getAllSwitches(); Switch updateSwitchUnderMaintenanceFlag(SwitchId switchId, boolean underMaintenance); boolean deleteSwitch(SwitchId switchId, boolean force); void checkSwitchIsDeactivated(SwitchId switchId); void checkSwitchHasNoFlows(SwitchId switchId); void checkSwitchHasNoFlowSegments(SwitchId switchId); void checkSwitchHasNoIsls(SwitchId switchId); SwitchPropertiesDto getSwitchProperties(SwitchId switchId); SwitchPropertiesDto updateSwitchProperties(SwitchId switchId, SwitchPropertiesDto switchPropertiesDto); PortProperties getPortProperties(SwitchId switchId, int port); Collection<SwitchConnectedDevice> getSwitchConnectedDevices(
SwitchId switchId); List<IslEndpoint> getSwitchIslEndpoints(SwitchId switchId); Switch patchSwitch(SwitchId switchId, SwitchPatch data); }### Answer:
@Test public void shouldUpdateLinkUnderMaintenanceFlag() throws SwitchNotFoundException { Switch sw = Switch.builder().switchId(TEST_SWITCH_ID).status(SwitchStatus.ACTIVE).build(); switchRepository.add(sw); switchOperationsService.updateSwitchUnderMaintenanceFlag(TEST_SWITCH_ID, true); sw = switchRepository.findById(TEST_SWITCH_ID).get(); assertTrue(sw.isUnderMaintenance()); switchOperationsService.updateSwitchUnderMaintenanceFlag(TEST_SWITCH_ID, false); sw = switchRepository.findById(TEST_SWITCH_ID).get(); assertFalse(sw.isUnderMaintenance()); } |
### Question:
StatsCollector extends Thread { void sendStats(FlowLatencyPacketBucket flowLatencyPacketBucket) throws InvalidProtocolBufferException { long currentTimeMillis = System.currentTimeMillis(); for (FlowLatencyPacket packet : flowLatencyPacketBucket.getPacketList()) { FlowRttStatsData data = new FlowRttStatsData( packet.getFlowId(), FlowDirection.fromBoolean(packet.getDirection()).name().toLowerCase(), packet.getT0(), packet.getT1() ); InfoMessage message = new InfoMessage(data, currentTimeMillis, String.format("stats42-%s-%d", sessionId, packet.getPacketId())); log.debug("InfoMessage {}", message); template.send(toStorm, packet.getFlowId(), message); } } StatsCollector(KafkaTemplate<String, Object> template); @Override void run(); }### Answer:
@Test public void sendStatsTest() throws Exception { Builder bucketBuilder = FlowLatencyPacketBucket.newBuilder(); FlowLatencyPacket packet1 = FlowLatencyPacket.newBuilder() .setFlowId("some-flow-id-1") .setDirection(false) .setT0(100) .setT1(150) .setPacketId(1).build(); FlowLatencyPacket packet2 = FlowLatencyPacket.newBuilder() .setDirection(true) .setT0(200) .setT1(250) .setPacketId(2).build(); bucketBuilder.addPacket(packet1); bucketBuilder.addPacket(packet2); statsCollector.sendStats(bucketBuilder.build()); ArgumentCaptor<InfoMessage> argument = ArgumentCaptor.forClass(InfoMessage.class); verify(template).send(eq(toStorm), eq(packet1.getFlowId()), argument.capture()); InfoMessage packet1Message = argument.getValue(); FlowRttStatsData statsPacket1 = (FlowRttStatsData) packet1Message.getData(); assertThat(statsPacket1).extracting( FlowRttStatsData::getFlowId, FlowRttStatsData::getT0, FlowRttStatsData::getT1) .contains(packet1.getFlowId(), packet1.getT0(), packet1.getT1()); assertThat(statsPacket1) .extracting(FlowRttStatsData::getDirection) .isEqualTo("forward"); verify(template).send(eq(toStorm), eq(packet2.getFlowId()), argument.capture()); InfoMessage packet2Message = argument.getValue(); FlowRttStatsData statsPacket2 = (FlowRttStatsData) packet2Message.getData(); assertThat(statsPacket2).extracting( FlowRttStatsData::getFlowId, FlowRttStatsData::getT0, FlowRttStatsData::getT1) .contains(packet2.getFlowId(), packet2.getT0(), packet2.getT1()); assertThat(statsPacket2) .extracting(FlowRttStatsData::getDirection) .isEqualTo("reverse"); } |
### Question:
SpeakerBolt extends BaseRichBolt { protected List<Values> addSwitch(AddSwitchCommand data) throws Exception { List<Values> values = new ArrayList<>(); SwitchId dpid = data.getDpid(); if (switches.get(dpid) == null) { ISwitchImpl sw = new ISwitchImpl(dpid, data.getNumOfPorts(), PortStateType.DOWN); switches.put(new SwitchId(sw.getDpid().toString()), sw); values.add(new Values("INFO", makeSwitchMessage(sw, SwitchChangeType.ADDED))); values.add(new Values("INFO", makeSwitchMessage(sw, SwitchChangeType.ACTIVATED))); } return values; } ISwitchImpl getSwitch(SwitchId name); void doSimulatorCommand(Tuple tuple); void doCommand(Tuple tuple); @Override void prepare(Map map, TopologyContext topologyContext, OutputCollector outputCollector); @Override void execute(Tuple tuple); @Override void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer); }### Answer:
@Test public void addSwitch() throws Exception { speakerBolt.addSwitch(switchMessage); assertEquals(1, speakerBolt.switches.size()); ISwitchImpl sw = speakerBolt.switches.get(dpid); assertTrue(sw.isActive()); List<IPortImpl> ports = sw.getPorts(); assertEquals(numOfPorts, ports.size()); for (IPortImpl port : ports) { if (port.getNumber() != localLinkPort) { assertFalse(port.isActive()); assertFalse(port.isActiveIsl()); } else { assertTrue(port.isActive()); assertTrue(port.isActiveIsl()); } } }
@Test public void testAddSwitchValues() throws Exception { List<Values> values = speakerBolt.addSwitch(switchMessage); assertEquals(3, values.size()); int count = 0; for (Values value : values) { InfoMessage infoMessage = mapper.readValue((String) value.get(1), InfoMessage.class); if (count < 2) { assertThat(infoMessage.getData(), instanceOf(SwitchInfoData.class)); SwitchInfoData sw = (SwitchInfoData) infoMessage.getData(); assertEquals(dpid, sw.getSwitchId()); } else { assertThat(infoMessage.getData(), instanceOf(PortInfoData.class)); PortInfoData port = (PortInfoData) infoMessage.getData(); assertEquals(dpid, port.getSwitchId()); if (port.getPortNo() == localLinkPort) { assertEquals(PortChangeType.UP, port.getState()); } else { assertEquals(PortChangeType.DOWN, port.getState()); } } count++; } } |
### Question:
ISwitchImpl implements ISwitch { @Override public void modState(SwitchChangeType state) throws SimulatorException { this.state = state; switch (state) { case ADDED: break; case ACTIVATED: activate(); break; case DEACTIVATED: case REMOVED: deactivate(); break; case CHANGED: throw new SimulatorException("Received modState of CHANGED, no idea why"); default: throw new SimulatorException(String.format("Unknown state %s", state)); } } ISwitchImpl(); ISwitchImpl(SwitchId dpid); ISwitchImpl(SwitchId dpid, int numOfPorts, PortStateType portState); @Override void modState(SwitchChangeType state); @Override void activate(); @Override void deactivate(); @Override boolean isActive(); @Override int getControlPlaneLatency(); @Override void setControlPlaneLatency(int controlPlaneLatency); @Override DatapathId getDpid(); @Override String getDpidAsString(); @Override void setDpid(DatapathId dpid); @Override void setDpid(SwitchId dpid); @Override List<IPortImpl> getPorts(); @Override IPortImpl getPort(int portNum); @Override int addPort(IPortImpl port); @Override int getMaxPorts(); @Override void setMaxPorts(int maxPorts); @Override Map<Long, IFlow> getFlows(); @Override IFlow getFlow(long cookie); @Override void addFlow(IFlow flow); @Override void modFlow(IFlow flow); @Override void delFlow(long cookie); @Override List<PortStatsEntry> getPortStats(); @Override PortStatsEntry getPortStats(int portNum); }### Answer:
@Test public void modState() throws Exception { sw.modState(SwitchChangeType.ACTIVATED); assertTrue(sw.isActive()); sw.modState(SwitchChangeType.DEACTIVATED); assertFalse(sw.isActive()); } |
### Question:
ISwitchImpl implements ISwitch { @Override public void setDpid(DatapathId dpid) { this.dpid = dpid; } ISwitchImpl(); ISwitchImpl(SwitchId dpid); ISwitchImpl(SwitchId dpid, int numOfPorts, PortStateType portState); @Override void modState(SwitchChangeType state); @Override void activate(); @Override void deactivate(); @Override boolean isActive(); @Override int getControlPlaneLatency(); @Override void setControlPlaneLatency(int controlPlaneLatency); @Override DatapathId getDpid(); @Override String getDpidAsString(); @Override void setDpid(DatapathId dpid); @Override void setDpid(SwitchId dpid); @Override List<IPortImpl> getPorts(); @Override IPortImpl getPort(int portNum); @Override int addPort(IPortImpl port); @Override int getMaxPorts(); @Override void setMaxPorts(int maxPorts); @Override Map<Long, IFlow> getFlows(); @Override IFlow getFlow(long cookie); @Override void addFlow(IFlow flow); @Override void modFlow(IFlow flow); @Override void delFlow(long cookie); @Override List<PortStatsEntry> getPortStats(); @Override PortStatsEntry getPortStats(int portNum); }### Answer:
@Test public void testSetDpid() { SwitchId newDpid = new SwitchId("01:02:03:04:05:06"); sw.setDpid(newDpid); assertEquals(newDpid.toString(), sw.getDpidAsString()); assertEquals(DatapathId.of(newDpid.toString()), sw.getDpid()); DatapathId dpid = sw.getDpid(); sw.setDpid(dpid); assertEquals(dpid, sw.getDpid()); } |
### Question:
ISwitchImpl implements ISwitch { @Override public int addPort(IPortImpl port) throws SimulatorException { if (ports.size() < maxPorts) { ports.add(port); } else { throw new SimulatorException(String.format("Switch already has reached maxPorts of %d" + "", maxPorts)); } return port.getNumber(); } ISwitchImpl(); ISwitchImpl(SwitchId dpid); ISwitchImpl(SwitchId dpid, int numOfPorts, PortStateType portState); @Override void modState(SwitchChangeType state); @Override void activate(); @Override void deactivate(); @Override boolean isActive(); @Override int getControlPlaneLatency(); @Override void setControlPlaneLatency(int controlPlaneLatency); @Override DatapathId getDpid(); @Override String getDpidAsString(); @Override void setDpid(DatapathId dpid); @Override void setDpid(SwitchId dpid); @Override List<IPortImpl> getPorts(); @Override IPortImpl getPort(int portNum); @Override int addPort(IPortImpl port); @Override int getMaxPorts(); @Override void setMaxPorts(int maxPorts); @Override Map<Long, IFlow> getFlows(); @Override IFlow getFlow(long cookie); @Override void addFlow(IFlow flow); @Override void modFlow(IFlow flow); @Override void delFlow(long cookie); @Override List<PortStatsEntry> getPortStats(); @Override PortStatsEntry getPortStats(int portNum); }### Answer:
@Test public void addPort() throws Exception { int portNum = sw.getPorts().size(); IPortImpl port = new IPortImpl(sw, PortStateType.UP, portNum); thrown.expect(SimulatorException.class); thrown.expectMessage("Switch already has reached maxPorts"); sw.addPort(port); } |
### Question:
ISwitchImpl implements ISwitch { @Override public IPortImpl getPort(int portNum) throws SimulatorException { try { return ports.get(portNum); } catch (IndexOutOfBoundsException e) { throw new SimulatorException(String.format("Port %d is not defined on %s", portNum, getDpidAsString())); } } ISwitchImpl(); ISwitchImpl(SwitchId dpid); ISwitchImpl(SwitchId dpid, int numOfPorts, PortStateType portState); @Override void modState(SwitchChangeType state); @Override void activate(); @Override void deactivate(); @Override boolean isActive(); @Override int getControlPlaneLatency(); @Override void setControlPlaneLatency(int controlPlaneLatency); @Override DatapathId getDpid(); @Override String getDpidAsString(); @Override void setDpid(DatapathId dpid); @Override void setDpid(SwitchId dpid); @Override List<IPortImpl> getPorts(); @Override IPortImpl getPort(int portNum); @Override int addPort(IPortImpl port); @Override int getMaxPorts(); @Override void setMaxPorts(int maxPorts); @Override Map<Long, IFlow> getFlows(); @Override IFlow getFlow(long cookie); @Override void addFlow(IFlow flow); @Override void modFlow(IFlow flow); @Override void delFlow(long cookie); @Override List<PortStatsEntry> getPortStats(); @Override PortStatsEntry getPortStats(int portNum); }### Answer:
@Test public void getPort() throws Exception { int numOfPorts = sw.getPorts().size(); assertEquals(1, sw.getPort(1).getNumber()); thrown.expect(SimulatorException.class); thrown.expectMessage(String.format("Port %d is not defined on %s", numOfPorts, sw.getDpidAsString())); sw.getPort(numOfPorts); } |
### Question:
ISwitchImpl implements ISwitch { @Override public IFlow getFlow(long cookie) throws SimulatorException { try { return flows.get(cookie); } catch (IndexOutOfBoundsException e) { throw new SimulatorException(String.format("Flow %d could not be found.", cookie)); } } ISwitchImpl(); ISwitchImpl(SwitchId dpid); ISwitchImpl(SwitchId dpid, int numOfPorts, PortStateType portState); @Override void modState(SwitchChangeType state); @Override void activate(); @Override void deactivate(); @Override boolean isActive(); @Override int getControlPlaneLatency(); @Override void setControlPlaneLatency(int controlPlaneLatency); @Override DatapathId getDpid(); @Override String getDpidAsString(); @Override void setDpid(DatapathId dpid); @Override void setDpid(SwitchId dpid); @Override List<IPortImpl> getPorts(); @Override IPortImpl getPort(int portNum); @Override int addPort(IPortImpl port); @Override int getMaxPorts(); @Override void setMaxPorts(int maxPorts); @Override Map<Long, IFlow> getFlows(); @Override IFlow getFlow(long cookie); @Override void addFlow(IFlow flow); @Override void modFlow(IFlow flow); @Override void delFlow(long cookie); @Override List<PortStatsEntry> getPortStats(); @Override PortStatsEntry getPortStats(int portNum); }### Answer:
@Test public void getFlow() { } |
### Question:
ISwitchImpl implements ISwitch { @Override public void addFlow(IFlow flow) throws SimulatorException { if (flows.containsKey(flow.getCookie())) { throw new SimulatorException(String.format("Flow %s already exists.", flow.toString())); } flows.put(flow.getCookie(), flow); } ISwitchImpl(); ISwitchImpl(SwitchId dpid); ISwitchImpl(SwitchId dpid, int numOfPorts, PortStateType portState); @Override void modState(SwitchChangeType state); @Override void activate(); @Override void deactivate(); @Override boolean isActive(); @Override int getControlPlaneLatency(); @Override void setControlPlaneLatency(int controlPlaneLatency); @Override DatapathId getDpid(); @Override String getDpidAsString(); @Override void setDpid(DatapathId dpid); @Override void setDpid(SwitchId dpid); @Override List<IPortImpl> getPorts(); @Override IPortImpl getPort(int portNum); @Override int addPort(IPortImpl port); @Override int getMaxPorts(); @Override void setMaxPorts(int maxPorts); @Override Map<Long, IFlow> getFlows(); @Override IFlow getFlow(long cookie); @Override void addFlow(IFlow flow); @Override void modFlow(IFlow flow); @Override void delFlow(long cookie); @Override List<PortStatsEntry> getPortStats(); @Override PortStatsEntry getPortStats(int portNum); }### Answer:
@Test public void addFlow() { } |
### Question:
ISwitchImpl implements ISwitch { @Override public void modFlow(IFlow flow) throws SimulatorException { delFlow(flow.getCookie()); addFlow(flow); } ISwitchImpl(); ISwitchImpl(SwitchId dpid); ISwitchImpl(SwitchId dpid, int numOfPorts, PortStateType portState); @Override void modState(SwitchChangeType state); @Override void activate(); @Override void deactivate(); @Override boolean isActive(); @Override int getControlPlaneLatency(); @Override void setControlPlaneLatency(int controlPlaneLatency); @Override DatapathId getDpid(); @Override String getDpidAsString(); @Override void setDpid(DatapathId dpid); @Override void setDpid(SwitchId dpid); @Override List<IPortImpl> getPorts(); @Override IPortImpl getPort(int portNum); @Override int addPort(IPortImpl port); @Override int getMaxPorts(); @Override void setMaxPorts(int maxPorts); @Override Map<Long, IFlow> getFlows(); @Override IFlow getFlow(long cookie); @Override void addFlow(IFlow flow); @Override void modFlow(IFlow flow); @Override void delFlow(long cookie); @Override List<PortStatsEntry> getPortStats(); @Override PortStatsEntry getPortStats(int portNum); }### Answer:
@Test public void modFlow() { } |
### Question:
ISwitchImpl implements ISwitch { @Override public void delFlow(long cookie) { flows.remove(cookie); } ISwitchImpl(); ISwitchImpl(SwitchId dpid); ISwitchImpl(SwitchId dpid, int numOfPorts, PortStateType portState); @Override void modState(SwitchChangeType state); @Override void activate(); @Override void deactivate(); @Override boolean isActive(); @Override int getControlPlaneLatency(); @Override void setControlPlaneLatency(int controlPlaneLatency); @Override DatapathId getDpid(); @Override String getDpidAsString(); @Override void setDpid(DatapathId dpid); @Override void setDpid(SwitchId dpid); @Override List<IPortImpl> getPorts(); @Override IPortImpl getPort(int portNum); @Override int addPort(IPortImpl port); @Override int getMaxPorts(); @Override void setMaxPorts(int maxPorts); @Override Map<Long, IFlow> getFlows(); @Override IFlow getFlow(long cookie); @Override void addFlow(IFlow flow); @Override void modFlow(IFlow flow); @Override void delFlow(long cookie); @Override List<PortStatsEntry> getPortStats(); @Override PortStatsEntry getPortStats(int portNum); }### Answer:
@Test public void delFlow() { } |
### Question:
ISwitchImpl implements ISwitch { @Override public List<PortStatsEntry> getPortStats() { return null; } ISwitchImpl(); ISwitchImpl(SwitchId dpid); ISwitchImpl(SwitchId dpid, int numOfPorts, PortStateType portState); @Override void modState(SwitchChangeType state); @Override void activate(); @Override void deactivate(); @Override boolean isActive(); @Override int getControlPlaneLatency(); @Override void setControlPlaneLatency(int controlPlaneLatency); @Override DatapathId getDpid(); @Override String getDpidAsString(); @Override void setDpid(DatapathId dpid); @Override void setDpid(SwitchId dpid); @Override List<IPortImpl> getPorts(); @Override IPortImpl getPort(int portNum); @Override int addPort(IPortImpl port); @Override int getMaxPorts(); @Override void setMaxPorts(int maxPorts); @Override Map<Long, IFlow> getFlows(); @Override IFlow getFlow(long cookie); @Override void addFlow(IFlow flow); @Override void modFlow(IFlow flow); @Override void delFlow(long cookie); @Override List<PortStatsEntry> getPortStats(); @Override PortStatsEntry getPortStats(int portNum); }### Answer:
@Test public void getPortStats() { } |
### Question:
IPortImpl implements IPort { @Override public boolean isActiveIsl() { return (peerSwitch != null && peerPortNum >= 0 && isActive && isForwarding); } IPortImpl(ISwitchImpl sw, PortStateType state, int portNumber); InfoMessage makePorChangetMessage(); @Override void enable(); @Override void disable(); @Override void block(); @Override void unblock(); void modPort(PortModMessage message); @Override boolean isActive(); @Override boolean isForwarding(); @Override int getNumber(); @Override void setLatency(int latency); @Override int getLatency(); @Override String getPeerSwitch(); @Override void setPeerSwitch(String peerSwitch); @Override void setPeerPortNum(int peerPortNum); @Override int getPeerPortNum(); @Override void setIsl(DatapathId peerSwitch, int peerPortNum); ISwitchImpl getSw(); void setSw(ISwitchImpl sw); @Override boolean isActiveIsl(); @Override PortStatsEntry getStats(); }### Answer:
@Test public void isActiveIsl() throws Exception { port.enable(); port.setPeerSwitch("00:00:00:00:00:01"); port.setPeerPortNum(10); assertTrue(port.isActiveIsl()); port.disable(); assertFalse(port.isActiveIsl()); port.enable(); port.block(); assertFalse(port.isActiveIsl()); port.unblock(); assertTrue(port.isActiveIsl()); port.disable(); port.unblock(); assertFalse(port.isActiveIsl()); } |
### Question:
IPortImpl implements IPort { @Override public PortStatsEntry getStats() { if (isForwarding && isActive) { this.rxPackets += rand.nextInt(MAX_LARGE); this.txPackets += rand.nextInt(MAX_LARGE); this.rxBytes += rand.nextInt(MAX_LARGE); this.txBytes += rand.nextInt(MAX_LARGE); this.rxDropped += rand.nextInt(MAX_SMALL); this.txDropped += rand.nextInt(MAX_SMALL); this.rxErrors += rand.nextInt(MAX_SMALL); this.txErrors += rand.nextInt(MAX_SMALL); this.rxFrameErr += rand.nextInt(MAX_SMALL); this.rxOverErr += rand.nextInt(MAX_SMALL); this.rxCrcErr += rand.nextInt(MAX_SMALL); this.collisions += rand.nextInt(MAX_SMALL); } return new PortStatsEntry(this.number, this.rxPackets, this.txPackets, this.rxBytes, this.txBytes, this.rxDropped, this.txDropped, this.rxErrors, this.txErrors, this.rxFrameErr, this.rxOverErr, this.rxCrcErr, this.collisions); } IPortImpl(ISwitchImpl sw, PortStateType state, int portNumber); InfoMessage makePorChangetMessage(); @Override void enable(); @Override void disable(); @Override void block(); @Override void unblock(); void modPort(PortModMessage message); @Override boolean isActive(); @Override boolean isForwarding(); @Override int getNumber(); @Override void setLatency(int latency); @Override int getLatency(); @Override String getPeerSwitch(); @Override void setPeerSwitch(String peerSwitch); @Override void setPeerPortNum(int peerPortNum); @Override int getPeerPortNum(); @Override void setIsl(DatapathId peerSwitch, int peerPortNum); ISwitchImpl getSw(); void setSw(ISwitchImpl sw); @Override boolean isActiveIsl(); @Override PortStatsEntry getStats(); }### Answer:
@Test public void getStats() throws Exception { } |
### Question:
CommandBuilderImpl implements CommandBuilder { @Override public List<BaseFlow> buildCommandsToSyncMissingRules(SwitchId switchId, List<Long> switchRules) { List<BaseFlow> commands = new ArrayList<>(buildInstallDefaultRuleCommands(switchId, switchRules)); commands.addAll(buildInstallFlowSharedRuleCommands(switchId, switchRules)); flowPathRepository.findBySegmentDestSwitch(switchId) .forEach(flowPath -> { if (switchRules.contains(flowPath.getCookie().getValue())) { PathSegment segment = flowPath.getSegments().stream() .filter(pathSegment -> pathSegment.getDestSwitchId().equals(switchId)) .findAny() .orElseThrow(() -> new IllegalStateException( format("PathSegment not found, path %s, switch %s", flowPath, switchId))); log.info("Rule {} is to be (re)installed on switch {}", flowPath.getCookie(), switchId); commands.addAll(buildInstallCommandFromSegment(flowPath, segment)); } }); SwitchProperties switchProperties = getSwitchProperties(switchId); flowPathRepository.findByEndpointSwitch(switchId) .forEach(flowPath -> { if (switchRules.contains(flowPath.getCookie().getValue())) { Flow flow = getFlow(flowPath); if (flowPath.isOneSwitchFlow()) { log.info("One-switch flow {} is to be (re)installed on switch {}", flowPath.getCookie(), switchId); commands.add(flowCommandFactory.makeOneSwitchRule(flow, flowPath)); } else if (flowPath.getSrcSwitchId().equals(switchId)) { log.info("Ingress flow {} is to be (re)installed on switch {}", flowPath.getCookie(), switchId); if (flowPath.getSegments().isEmpty()) { log.warn("Output port was not found for ingress flow rule"); } else { PathSegment foundIngressSegment = flowPath.getSegments().get(0); EncapsulationResources encapsulationResources = getEncapsulationResources( flowPath, flow); commands.add(flowCommandFactory.buildInstallIngressFlow(flow, flowPath, foundIngressSegment.getSrcPort(), encapsulationResources, foundIngressSegment.isSrcWithMultiTable())); } } } long server42Cookie = flowPath.getCookie().toBuilder() .type(CookieType.SERVER_42_INGRESS) .build() .getValue(); if (switchRules.contains(server42Cookie) && !flowPath.isOneSwitchFlow() && flowPath.getSrcSwitchId().equals(switchId)) { log.info("Ingress server 42 flow {} is to be (re)installed on switch {}", server42Cookie, switchId); if (flowPath.getSegments().isEmpty()) { log.warn("Output port was not found for server 42 ingress flow rule {}", server42Cookie); } else { Flow flow = getFlow(flowPath); PathSegment foundIngressSegment = flowPath.getSegments().get(0); EncapsulationResources encapsulationResources = getEncapsulationResources(flowPath, flow); commands.add(flowCommandFactory.buildInstallServer42IngressFlow( flow, flowPath, foundIngressSegment.getSrcPort(), switchProperties.getServer42Port(), switchProperties.getServer42MacAddress(), encapsulationResources, foundIngressSegment.isSrcWithMultiTable())); } } }); return commands; } CommandBuilderImpl(PersistenceManager persistenceManager, FlowResourcesConfig flowResourcesConfig); @Override List<BaseFlow> buildCommandsToSyncMissingRules(SwitchId switchId, List<Long> switchRules); @Override List<RemoveFlow> buildCommandsToRemoveExcessRules(SwitchId switchId,
List<FlowEntry> flows,
List<Long> excessRulesCookies); }### Answer:
@Test public void testCommandBuilder() { List<BaseFlow> response = commandBuilder .buildCommandsToSyncMissingRules(SWITCH_ID_B, Stream.of(1L, 2L, 3L, 4L) .map(effectiveId -> new FlowSegmentCookie(FlowPathDirection.FORWARD, effectiveId)) .map(Cookie::getValue) .collect(Collectors.toList())); assertEquals(4, response.size()); assertTrue(response.get(0) instanceof InstallEgressFlow); assertTrue(response.get(1) instanceof InstallTransitFlow); assertTrue(response.get(2) instanceof InstallOneSwitchFlow); assertTrue(response.get(3) instanceof InstallIngressFlow); } |
### Question:
SwitchValidateServiceImpl implements SwitchValidateService { @Override public void handleFlowEntriesResponse(String key, SwitchFlowEntries data) { handle(key, SwitchValidateEvent.RULES_RECEIVED, SwitchValidateContext.builder().flowEntries(data.getFlowEntries()).build()); } SwitchValidateServiceImpl(
SwitchManagerCarrier carrier, PersistenceManager persistenceManager, ValidationService validationService); @Override void handleSwitchValidateRequest(String key, SwitchValidateRequest request); @Override void handleFlowEntriesResponse(String key, SwitchFlowEntries data); @Override void handleGroupEntriesResponse(String key, SwitchGroupEntries data); @Override void handleExpectedDefaultFlowEntriesResponse(String key, SwitchExpectedDefaultFlowEntries data); @Override void handleExpectedDefaultMeterEntriesResponse(String key, SwitchExpectedDefaultMeterEntries data); @Override void handleMeterEntriesResponse(String key, SwitchMeterEntries data); @Override void handleMetersUnsupportedResponse(String key); @Override void handleTaskError(String key, ErrorMessage message); @Override void handleTaskTimeout(String key); }### Answer:
@Test public void receiveOnlyRules() { handleRequestAndInitDataReceive(); service.handleFlowEntriesResponse(KEY, new SwitchFlowEntries(SWITCH_ID, singletonList(flowEntry))); verifyNoMoreInteractions(carrier); verifyNoMoreInteractions(validationService); }
@Test public void doNothingWhenFsmNotFound() { service.handleFlowEntriesResponse(KEY, new SwitchFlowEntries(SWITCH_ID, singletonList(flowEntry))); verifyZeroInteractions(carrier); verifyZeroInteractions(validationService); } |
### Question:
SwitchValidateServiceImpl implements SwitchValidateService { @Override public void handleSwitchValidateRequest(String key, SwitchValidateRequest request) { SwitchValidateFsm fsm = builder.newStateMachine( SwitchValidateState.START, carrier, key, request, validationService, repositoryFactory); fsms.put(key, fsm); fsm.start(); handle(fsm, SwitchValidateEvent.NEXT, SwitchValidateContext.builder().build()); } SwitchValidateServiceImpl(
SwitchManagerCarrier carrier, PersistenceManager persistenceManager, ValidationService validationService); @Override void handleSwitchValidateRequest(String key, SwitchValidateRequest request); @Override void handleFlowEntriesResponse(String key, SwitchFlowEntries data); @Override void handleGroupEntriesResponse(String key, SwitchGroupEntries data); @Override void handleExpectedDefaultFlowEntriesResponse(String key, SwitchExpectedDefaultFlowEntries data); @Override void handleExpectedDefaultMeterEntriesResponse(String key, SwitchExpectedDefaultMeterEntries data); @Override void handleMeterEntriesResponse(String key, SwitchMeterEntries data); @Override void handleMetersUnsupportedResponse(String key); @Override void handleTaskError(String key, ErrorMessage message); @Override void handleTaskTimeout(String key); }### Answer:
@Test public void errorResponseOnSwitchNotFound() { request = SwitchValidateRequest .builder().switchId(SWITCH_ID_MISSING).performSync(true).processMeters(true).build(); service.handleSwitchValidateRequest(KEY, request); verify(carrier).cancelTimeoutCallback(eq(KEY)); verify(carrier).errorResponse( eq(KEY), eq(ErrorType.NOT_FOUND), eq(String.format("Switch '%s' not found", request.getSwitchId()))); verifyNoMoreInteractions(carrier); verifyNoMoreInteractions(validationService); } |
### Question:
ValidationServiceImpl implements ValidationService { @Override public ValidateRulesResult validateRules(SwitchId switchId, List<FlowEntry> presentRules, List<FlowEntry> expectedDefaultRules) { log.debug("Validating rules on switch {}", switchId); Set<Long> expectedCookies = getExpectedFlowRules(switchId); return makeRulesResponse(expectedCookies, presentRules, expectedDefaultRules, switchId); } ValidationServiceImpl(PersistenceManager persistenceManager, SwitchManagerTopologyConfig topologyConfig); @Override ValidateRulesResult validateRules(SwitchId switchId, List<FlowEntry> presentRules,
List<FlowEntry> expectedDefaultRules); @Override ValidateGroupsResult validateGroups(SwitchId switchId, List<GroupEntry> presentGroups); @Override ValidateMetersResult validateMeters(SwitchId switchId, List<MeterEntry> presentMeters,
List<MeterEntry> expectedDefaultMeters); }### Answer:
@Test public void validateRulesEmpty() throws SwitchNotFoundException { ValidationService validationService = new ValidationServiceImpl(persistenceManager().build(), topologyConfig); ValidateRulesResult response = validationService.validateRules(SWITCH_ID_A, emptyList(), emptyList()); assertTrue(response.getMissingRules().isEmpty()); assertTrue(response.getProperRules().isEmpty()); assertTrue(response.getExcessRules().isEmpty()); }
@Test public void validateRulesSimpleSegmentCookies() throws SwitchNotFoundException { ValidationService validationService = new ValidationServiceImpl(persistenceManager().withSegmentsCookies(2L, 3L).build(), topologyConfig); List<FlowEntry> flowEntries = Lists.newArrayList(FlowEntry.builder().cookie(1L).build(), FlowEntry.builder().cookie(2L).build()); ValidateRulesResult response = validationService.validateRules(SWITCH_ID_A, flowEntries, emptyList()); assertEquals(ImmutableList.of(3L), response.getMissingRules()); assertEquals(ImmutableList.of(2L), response.getProperRules()); assertEquals(ImmutableList.of(1L), response.getExcessRules()); }
@Test public void validateRulesSegmentAndIngressCookies() throws SwitchNotFoundException { ValidationService validationService = new ValidationServiceImpl(persistenceManager().withSegmentsCookies(2L).withIngressCookies(1L).build(), topologyConfig); List<FlowEntry> flowEntries = Lists.newArrayList(FlowEntry.builder().cookie(1L).build(), FlowEntry.builder().cookie(2L).build()); ValidateRulesResult response = validationService.validateRules(SWITCH_ID_A, flowEntries, emptyList()); assertTrue(response.getMissingRules().isEmpty()); assertEquals(ImmutableSet.of(1L, 2L), new HashSet<>(response.getProperRules())); assertTrue(response.getExcessRules().isEmpty()); }
@Test public void validateRulesSegmentAndIngressCookiesWithServer42Rules() { SwitchProperties switchProperties = SwitchProperties.builder() .server42FlowRtt(true) .build(); ValidationService validationService = new ValidationServiceImpl(persistenceManager() .withIngressCookies(1L) .withSwitchProperties(switchProperties) .build(), topologyConfig); List<FlowEntry> flowEntries = Lists.newArrayList(FlowEntry.builder().cookie(0xC0000000000001L).build(), FlowEntry.builder().cookie(1L).build()); ValidateRulesResult response = validationService.validateRules(SWITCH_ID_A, flowEntries, emptyList()); assertTrue(response.getMissingRules().isEmpty()); assertEquals(ImmutableSet.of(0xC0000000000001L, 1L), new HashSet<>(response.getProperRules())); assertTrue(response.getExcessRules().isEmpty()); } |
### Question:
SwitchSyncServiceImpl implements SwitchSyncService { @Override public void handleSwitchSync(String key, SwitchValidateRequest request, ValidationResult validationResult) { SwitchSyncFsm fsm = builder.newStateMachine(SwitchSyncState.INITIALIZED, carrier, key, commandBuilder, request, validationResult); process(fsm); } SwitchSyncServiceImpl(SwitchManagerCarrier carrier, PersistenceManager persistenceManager,
FlowResourcesConfig flowResourcesConfig); @Override void handleSwitchSync(String key, SwitchValidateRequest request, ValidationResult validationResult); @Override void handleInstallRulesResponse(String key); @Override void handleRemoveRulesResponse(String key); @Override void handleReinstallDefaultRulesResponse(String key, FlowReinstallResponse response); @Override void handleRemoveMetersResponse(String key); @Override void handleTaskTimeout(String key); @Override void handleTaskError(String key, ErrorMessage message); }### Answer:
@Test public void handleNothingRulesToSync() { missingRules = emptyList(); service.handleSwitchSync(KEY, request, makeValidationResult()); verify(carrier).response(eq(KEY), any(InfoMessage.class)); verify(carrier).cancelTimeoutCallback(eq(KEY)); verifyNoMoreInteractions(commandBuilder); verifyNoMoreInteractions(carrier); }
@Test public void handleCommandBuilderMissingRulesException() { String errorMessage = "test error"; when(commandBuilder.buildCommandsToSyncMissingRules(eq(SWITCH_ID), any())) .thenThrow(new IllegalArgumentException(errorMessage)); service.handleSwitchSync(KEY, request, makeValidationResult()); verify(commandBuilder).buildCommandsToSyncMissingRules(eq(SWITCH_ID), eq(missingRules)); ArgumentCaptor<ErrorMessage> errorCaptor = ArgumentCaptor.forClass(ErrorMessage.class); verify(carrier).cancelTimeoutCallback(eq(KEY)); verify(carrier).response(eq(KEY), errorCaptor.capture()); assertEquals(errorMessage, errorCaptor.getValue().getData().getErrorMessage()); verifyNoMoreInteractions(commandBuilder); verifyNoMoreInteractions(carrier); }
@Test public void handleNothingToSyncWithExcess() { request = SwitchValidateRequest.builder().switchId(SWITCH_ID).performSync(true).removeExcess(true).build(); missingRules = emptyList(); service.handleSwitchSync(KEY, request, makeValidationResult()); verify(carrier).cancelTimeoutCallback(eq(KEY)); verify(carrier).response(eq(KEY), any(InfoMessage.class)); verifyNoMoreInteractions(commandBuilder); verifyNoMoreInteractions(carrier); } |
### Question:
SwitchSyncServiceImpl implements SwitchSyncService { @Override public void handleInstallRulesResponse(String key) { SwitchSyncFsm fsm = fsms.get(key); if (fsm == null) { logFsmNotFound(key); return; } fsm.fire(SwitchSyncEvent.RULES_INSTALLED); process(fsm); } SwitchSyncServiceImpl(SwitchManagerCarrier carrier, PersistenceManager persistenceManager,
FlowResourcesConfig flowResourcesConfig); @Override void handleSwitchSync(String key, SwitchValidateRequest request, ValidationResult validationResult); @Override void handleInstallRulesResponse(String key); @Override void handleRemoveRulesResponse(String key); @Override void handleReinstallDefaultRulesResponse(String key, FlowReinstallResponse response); @Override void handleRemoveMetersResponse(String key); @Override void handleTaskTimeout(String key); @Override void handleTaskError(String key, ErrorMessage message); }### Answer:
@Test public void doNothingWhenFsmNotFound() { service.handleInstallRulesResponse(KEY); verifyZeroInteractions(carrier); verifyZeroInteractions(commandBuilder); } |
### Question:
FlowPathStatusConverter implements AttributeConverter<FlowPathStatus, String> { @Override public String toGraphProperty(FlowPathStatus value) { if (value == null) { return null; } return value.name().toLowerCase(); } @Override String toGraphProperty(FlowPathStatus value); @Override FlowPathStatus toEntityAttribute(String value); }### Answer:
@Test public void shouldConvertToGraphProperty() { FlowPathStatusConverter converter = new FlowPathStatusConverter(); assertEquals("active", converter.toGraphProperty(FlowPathStatus.ACTIVE)); assertEquals("inactive", converter.toGraphProperty(FlowPathStatus.INACTIVE)); assertEquals("in_progress", converter.toGraphProperty(FlowPathStatus.IN_PROGRESS)); } |
### Question:
FlowPathStatusConverter implements AttributeConverter<FlowPathStatus, String> { @Override public FlowPathStatus toEntityAttribute(String value) { if (value == null || value.trim().isEmpty()) { return null; } return FlowPathStatus.valueOf(value.toUpperCase()); } @Override String toGraphProperty(FlowPathStatus value); @Override FlowPathStatus toEntityAttribute(String value); }### Answer:
@Test public void shouldConvertToEntity() { FlowPathStatusConverter converter = new FlowPathStatusConverter(); assertEquals(FlowPathStatus.ACTIVE, converter.toEntityAttribute("ACTIVE")); assertEquals(FlowPathStatus.ACTIVE, converter.toEntityAttribute("active")); assertEquals(FlowPathStatus.IN_PROGRESS, converter.toEntityAttribute("In_Progress")); } |
### Question:
PathIdConverter implements AttributeConverter<PathId, String> { @Override public String toGraphProperty(PathId value) { if (value == null) { return null; } return value.getId(); } @Override String toGraphProperty(PathId value); @Override PathId toEntityAttribute(String value); static final PathIdConverter INSTANCE; }### Answer:
@Test public void shouldConvertIdToString() { PathId pathId = new PathId("test_path_id"); String graphObject = PathIdConverter.INSTANCE.toGraphProperty(pathId); assertEquals(pathId.getId(), graphObject); } |
### Question:
PathIdConverter implements AttributeConverter<PathId, String> { @Override public PathId toEntityAttribute(String value) { if (value == null || value.trim().isEmpty()) { return null; } return new PathId(value); } @Override String toGraphProperty(PathId value); @Override PathId toEntityAttribute(String value); static final PathIdConverter INSTANCE; }### Answer:
@Test public void shouldConvertStringToId() { PathId pathId = new PathId("test_path_id"); PathId actualEntity = PathIdConverter.INSTANCE.toEntityAttribute(pathId.getId()); assertEquals(pathId, actualEntity); } |
### Question:
SwitchIdConverter implements AttributeConverter<SwitchId, String> { @Override public String toGraphProperty(SwitchId value) { if (value == null) { return null; } return value.toString(); } @Override String toGraphProperty(SwitchId value); @Override SwitchId toEntityAttribute(String value); static final SwitchIdConverter INSTANCE; }### Answer:
@Test public void shouldConvertIdToString() { SwitchId switchId = new SwitchId((long) 0x123); String graphObject = SwitchIdConverter.INSTANCE.toGraphProperty(switchId); assertEquals(switchId.toString(), graphObject); } |
### Question:
SwitchIdConverter implements AttributeConverter<SwitchId, String> { @Override public SwitchId toEntityAttribute(String value) { if (value == null || value.trim().isEmpty()) { return null; } return new SwitchId(value); } @Override String toGraphProperty(SwitchId value); @Override SwitchId toEntityAttribute(String value); static final SwitchIdConverter INSTANCE; }### Answer:
@Test public void shouldConvertStringToId() { SwitchId switchId = new SwitchId((long) 0x123); SwitchId actualEntity = SwitchIdConverter.INSTANCE.toEntityAttribute(switchId.toString()); assertEquals(switchId, actualEntity); } |
### Question:
FlowStatusConverter implements AttributeConverter<FlowStatus, String> { @Override public String toGraphProperty(FlowStatus value) { if (value == null) { return null; } return value.name().toLowerCase(); } @Override String toGraphProperty(FlowStatus value); @Override FlowStatus toEntityAttribute(String value); static final FlowStatusConverter INSTANCE; }### Answer:
@Test public void shouldConvertToGraphProperty() { FlowStatusConverter converter = FlowStatusConverter.INSTANCE; assertEquals("up", converter.toGraphProperty(FlowStatus.UP)); assertEquals("down", converter.toGraphProperty(FlowStatus.DOWN)); assertEquals("in_progress", converter.toGraphProperty(FlowStatus.IN_PROGRESS)); } |
### Question:
FlowStatusConverter implements AttributeConverter<FlowStatus, String> { @Override public FlowStatus toEntityAttribute(String value) { if (value == null || value.trim().isEmpty()) { return FlowStatus.UP; } return FlowStatus.valueOf(value.toUpperCase()); } @Override String toGraphProperty(FlowStatus value); @Override FlowStatus toEntityAttribute(String value); static final FlowStatusConverter INSTANCE; }### Answer:
@Test public void shouldConvertToEntity() { FlowStatusConverter converter = FlowStatusConverter.INSTANCE; assertEquals(FlowStatus.UP, converter.toEntityAttribute("UP")); assertEquals(FlowStatus.UP, converter.toEntityAttribute("up")); assertEquals(FlowStatus.IN_PROGRESS, converter.toEntityAttribute("In_Progress")); } |
### Question:
ExclusionCookieConverter implements AttributeConverter<ExclusionCookie, Long> { @Override public Long toGraphProperty(ExclusionCookie value) { if (value == null) { return null; } return value.getValue(); } @Override Long toGraphProperty(ExclusionCookie value); @Override ExclusionCookie toEntityAttribute(Long value); static final ExclusionCookieConverter INSTANCE; }### Answer:
@Test public void shouldConvertIdToLong() { ExclusionCookie cookie = new ExclusionCookie((long) 0x123); Long graphObject = new ExclusionCookieConverter().toGraphProperty(cookie); assertEquals(cookie.getValue(), (long) graphObject); } |
### Question:
ExclusionCookieConverter implements AttributeConverter<ExclusionCookie, Long> { @Override public ExclusionCookie toEntityAttribute(Long value) { if (value == null) { return null; } return new ExclusionCookie(value); } @Override Long toGraphProperty(ExclusionCookie value); @Override ExclusionCookie toEntityAttribute(Long value); static final ExclusionCookieConverter INSTANCE; }### Answer:
@Test public void shouldConvertLongToId() { ExclusionCookie cookie = new ExclusionCookie((long) 0x123); Cookie actualEntity = new ExclusionCookieConverter().toEntityAttribute(cookie.getValue()); assertEquals(cookie, actualEntity); } |
### Question:
SwitchOperationsService implements ILinkOperationsServiceCarrier { public boolean deleteSwitch(SwitchId switchId, boolean force) throws SwitchNotFoundException { transactionManager.doInTransaction(() -> { Switch sw = switchRepository.findById(switchId) .orElseThrow(() -> new SwitchNotFoundException(switchId)); switchPropertiesRepository.findBySwitchId(sw.getSwitchId()) .ifPresent(sp -> switchPropertiesRepository.remove(sp)); portPropertiesRepository.getAllBySwitchId(sw.getSwitchId()) .forEach(portPropertiesRepository::remove); if (force) { switchRepository.remove(sw); } else { switchRepository.removeIfNoDependant(sw); } }); return !switchRepository.exists(switchId); } SwitchOperationsService(RepositoryFactory repositoryFactory,
TransactionManager transactionManager,
SwitchOperationsServiceCarrier carrier); GetSwitchResponse getSwitch(SwitchId switchId); List<GetSwitchResponse> getAllSwitches(); Switch updateSwitchUnderMaintenanceFlag(SwitchId switchId, boolean underMaintenance); boolean deleteSwitch(SwitchId switchId, boolean force); void checkSwitchIsDeactivated(SwitchId switchId); void checkSwitchHasNoFlows(SwitchId switchId); void checkSwitchHasNoFlowSegments(SwitchId switchId); void checkSwitchHasNoIsls(SwitchId switchId); SwitchPropertiesDto getSwitchProperties(SwitchId switchId); SwitchPropertiesDto updateSwitchProperties(SwitchId switchId, SwitchPropertiesDto switchPropertiesDto); PortProperties getPortProperties(SwitchId switchId, int port); Collection<SwitchConnectedDevice> getSwitchConnectedDevices(
SwitchId switchId); List<IslEndpoint> getSwitchIslEndpoints(SwitchId switchId); Switch patchSwitch(SwitchId switchId, SwitchPatch data); }### Answer:
@Test public void shouldDeletePortPropertiesWhenDeletingSwitch() throws SwitchNotFoundException { Switch sw = Switch.builder().switchId(TEST_SWITCH_ID).status(SwitchStatus.ACTIVE).build(); switchRepository.add(sw); PortProperties portProperties = PortProperties.builder().switchObj(sw).port(7).discoveryEnabled(false).build(); portPropertiesRepository.add(portProperties); switchOperationsService.deleteSwitch(TEST_SWITCH_ID, false); assertFalse(switchRepository.findById(TEST_SWITCH_ID).isPresent()); assertTrue(portPropertiesRepository.findAll().isEmpty()); } |
### Question:
FlowSegmentCookieConverter implements AttributeConverter<FlowSegmentCookie, Long> { @Override public Long toGraphProperty(FlowSegmentCookie value) { if (value == null) { return null; } return value.getValue(); } @Override Long toGraphProperty(FlowSegmentCookie value); @Override FlowSegmentCookie toEntityAttribute(Long value); static final FlowSegmentCookieConverter INSTANCE; }### Answer:
@Test public void shouldConvertIdToLong() { FlowSegmentCookie cookie = new FlowSegmentCookie((long) 0x123); Long graphObject = FlowSegmentCookieConverter.INSTANCE.toGraphProperty(cookie); assertEquals(cookie.getValue(), (long) graphObject); } |
### Question:
FlowSegmentCookieConverter implements AttributeConverter<FlowSegmentCookie, Long> { @Override public FlowSegmentCookie toEntityAttribute(Long value) { if (value == null) { return null; } return new FlowSegmentCookie(value); } @Override Long toGraphProperty(FlowSegmentCookie value); @Override FlowSegmentCookie toEntityAttribute(Long value); static final FlowSegmentCookieConverter INSTANCE; }### Answer:
@Test public void shouldConvertLongToId() { FlowSegmentCookie cookie = new FlowSegmentCookie((long) 0x123); FlowSegmentCookie actualEntity = FlowSegmentCookieConverter.INSTANCE.toEntityAttribute(cookie.getValue()); assertEquals(cookie, actualEntity); } |
### Question:
SwitchStatusConverter implements AttributeConverter<SwitchStatus, String> { @Override public String toGraphProperty(SwitchStatus value) { if (value == null) { return null; } return value.name().toLowerCase(); } @Override String toGraphProperty(SwitchStatus value); @Override SwitchStatus toEntityAttribute(String value); static final SwitchStatusConverter INSTANCE; }### Answer:
@Test public void shouldConvertToGraphProperty() { SwitchStatusConverter converter = SwitchStatusConverter.INSTANCE; assertEquals("active", converter.toGraphProperty(SwitchStatus.ACTIVE)); assertEquals("inactive", converter.toGraphProperty(SwitchStatus.INACTIVE)); } |
### Question:
SwitchStatusConverter implements AttributeConverter<SwitchStatus, String> { @Override public SwitchStatus toEntityAttribute(String value) { if (value == null || value.trim().isEmpty()) { return null; } return SwitchStatus.valueOf(value.toUpperCase()); } @Override String toGraphProperty(SwitchStatus value); @Override SwitchStatus toEntityAttribute(String value); static final SwitchStatusConverter INSTANCE; }### Answer:
@Test public void shouldConvertToEntity() { SwitchStatusConverter converter = SwitchStatusConverter.INSTANCE; assertEquals(SwitchStatus.ACTIVE, converter.toEntityAttribute("ACTIVE")); assertEquals(SwitchStatus.ACTIVE, converter.toEntityAttribute("active")); assertEquals(SwitchStatus.INACTIVE, converter.toEntityAttribute("InActive")); } |
### Question:
FlowEncapsulationTypeConverter implements AttributeConverter<FlowEncapsulationType, String> { @Override public String toGraphProperty(FlowEncapsulationType value) { if (value == null) { return null; } return value.name(); } @Override String toGraphProperty(FlowEncapsulationType value); @Override FlowEncapsulationType toEntityAttribute(String value); static final FlowEncapsulationTypeConverter INSTANCE; }### Answer:
@Test public void shouldConvertToGraphProperty() { assertEquals("TRANSIT_VLAN", FlowEncapsulationTypeConverter.INSTANCE.toGraphProperty(FlowEncapsulationType.TRANSIT_VLAN)); } |
### Question:
FlowEncapsulationTypeConverter implements AttributeConverter<FlowEncapsulationType, String> { @Override public FlowEncapsulationType toEntityAttribute(String value) { if (value == null || value.trim().isEmpty()) { return null; } return FlowEncapsulationType.valueOf(value); } @Override String toGraphProperty(FlowEncapsulationType value); @Override FlowEncapsulationType toEntityAttribute(String value); static final FlowEncapsulationTypeConverter INSTANCE; }### Answer:
@Test public void shouldConvertToEntity() { assertEquals(FlowEncapsulationType.TRANSIT_VLAN, FlowEncapsulationTypeConverter.INSTANCE.toEntityAttribute("TRANSIT_VLAN")); } |
### Question:
MeterIdConverter implements AttributeConverter<MeterId, Long> { @Override public Long toGraphProperty(MeterId value) { if (value == null) { return null; } return value.getValue(); } @Override Long toGraphProperty(MeterId value); @Override MeterId toEntityAttribute(Long value); static final MeterIdConverter INSTANCE; }### Answer:
@Test public void shouldConvertIdToString() { MeterId meterId = new MeterId(0x123); Long graphObject = MeterIdConverter.INSTANCE.toGraphProperty(meterId); assertEquals(meterId.getValue(), (long) graphObject); } |
### Question:
MeterIdConverter implements AttributeConverter<MeterId, Long> { @Override public MeterId toEntityAttribute(Long value) { if (value == null) { return null; } return new MeterId(value); } @Override Long toGraphProperty(MeterId value); @Override MeterId toEntityAttribute(Long value); static final MeterIdConverter INSTANCE; }### Answer:
@Test public void shouldConvertStringToId() { MeterId meterId = new MeterId(0x123); MeterId actualEntity = MeterIdConverter.INSTANCE.toEntityAttribute(meterId.getValue()); assertEquals(meterId, actualEntity); } |
### Question:
IslStatusConverter implements AttributeConverter<IslStatus, String> { @Override public String toGraphProperty(IslStatus value) { if (value == null) { return null; } return value.name().toLowerCase(); } @Override String toGraphProperty(IslStatus value); @Override IslStatus toEntityAttribute(String value); static final IslStatusConverter INSTANCE; }### Answer:
@Test public void shouldConvertToGraphProperty() { IslStatusConverter converter = IslStatusConverter.INSTANCE; assertEquals("active", converter.toGraphProperty(IslStatus.ACTIVE)); assertEquals("inactive", converter.toGraphProperty(IslStatus.INACTIVE)); } |
### Question:
IslStatusConverter implements AttributeConverter<IslStatus, String> { @Override public IslStatus toEntityAttribute(String value) { if (value == null || value.trim().isEmpty()) { return null; } return IslStatus.valueOf(value.toUpperCase()); } @Override String toGraphProperty(IslStatus value); @Override IslStatus toEntityAttribute(String value); static final IslStatusConverter INSTANCE; }### Answer:
@Test public void shouldConvertToEntity() { IslStatusConverter converter = IslStatusConverter.INSTANCE; assertEquals(IslStatus.ACTIVE, converter.toEntityAttribute("ACTIVE")); assertEquals(IslStatus.ACTIVE, converter.toEntityAttribute("active")); assertEquals(IslStatus.INACTIVE, converter.toEntityAttribute("InActive")); } |
### Question:
FermaPortPropertiesRepository extends FermaGenericRepository<PortProperties, PortPropertiesData, PortPropertiesFrame> implements PortPropertiesRepository { @Override public Collection<PortProperties> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(PortPropertiesFrame.FRAME_LABEL)) .toListExplicit(PortPropertiesFrame.class).stream() .map(PortProperties::new) .collect(Collectors.toList()); } FermaPortPropertiesRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<PortProperties> findAll(); @Override Optional<PortProperties> getBySwitchIdAndPort(SwitchId switchId, int port); @Override Collection<PortProperties> getAllBySwitchId(SwitchId switchId); }### Answer:
@Test public void shouldCreatePortPropertiesWithRelation() { Switch origSwitch = createTestSwitch(TEST_SWITCH_ID.getId()); PortProperties portProperties = PortProperties.builder() .switchObj(origSwitch) .discoveryEnabled(false) .build(); portPropertiesRepository.add(portProperties); Collection<PortProperties> portPropertiesResult = portPropertiesRepository.findAll(); assertEquals(1, portPropertiesResult.size()); assertNotNull(portPropertiesResult.iterator().next().getSwitchObj()); } |
### Question:
FermaPortPropertiesRepository extends FermaGenericRepository<PortProperties, PortPropertiesData, PortPropertiesFrame> implements PortPropertiesRepository { @Override public Optional<PortProperties> getBySwitchIdAndPort(SwitchId switchId, int port) { List<? extends PortPropertiesFrame> portPropertiesFrames = framedGraph().traverse(g -> g.V() .hasLabel(PortPropertiesFrame.FRAME_LABEL) .has(PortPropertiesFrame.SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(PortPropertiesFrame.PORT_NO_PROPERTY, port)) .toListExplicit(PortPropertiesFrame.class); return portPropertiesFrames.isEmpty() ? Optional.empty() : Optional.of(portPropertiesFrames.get(0)) .map(PortProperties::new); } FermaPortPropertiesRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<PortProperties> findAll(); @Override Optional<PortProperties> getBySwitchIdAndPort(SwitchId switchId, int port); @Override Collection<PortProperties> getAllBySwitchId(SwitchId switchId); }### Answer:
@Test public void shouldGetPortPropertiesBySwitchIdAndPort() { Switch origSwitch = createTestSwitch(TEST_SWITCH_ID.getId()); int port = 7; PortProperties portProperties = PortProperties.builder() .switchObj(origSwitch) .port(port) .discoveryEnabled(false) .build(); portPropertiesRepository.add(portProperties); Optional<PortProperties> portPropertiesResult = portPropertiesRepository.getBySwitchIdAndPort(origSwitch.getSwitchId(), port); assertTrue(portPropertiesResult.isPresent()); assertEquals(origSwitch.getSwitchId(), portPropertiesResult.get().getSwitchObj().getSwitchId()); assertEquals(port, portPropertiesResult.get().getPort()); assertFalse(portPropertiesResult.get().isDiscoveryEnabled()); } |
### Question:
FermaFlowCookieRepository extends FermaGenericRepository<FlowCookie, FlowCookieData, FlowCookieFrame> implements FlowCookieRepository { @Override public Collection<FlowCookie> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(FlowCookieFrame.FRAME_LABEL)) .toListExplicit(FlowCookieFrame.class).stream() .map(FlowCookie::new) .collect(Collectors.toList()); } FermaFlowCookieRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowCookie> findAll(); @Override boolean exists(long unmaskedCookie); @Override Optional<FlowCookie> findByCookie(long unmaskedCookie); @Override Optional<Long> findFirstUnassignedCookie(long lowestCookieValue, long highestCookieValue); }### Answer:
@Test public void shouldCreateFlowCookie() { createFlowCookie(); Collection<FlowCookie> allCookies = flowCookieRepository.findAll(); FlowCookie foundCookie = allCookies.iterator().next(); assertEquals(TEST_COOKIE, foundCookie.getUnmaskedCookie()); assertEquals(TEST_FLOW_ID, foundCookie.getFlowId()); }
@Test public void shouldDeleteFlowCookie() { FlowCookie cookie = createFlowCookie(); transactionManager.doInTransaction(() -> flowCookieRepository.remove(cookie)); assertEquals(0, flowCookieRepository.findAll().size()); }
@Test public void shouldDeleteFoundFlowCookie() { createFlowCookie(); transactionManager.doInTransaction(() -> { Collection<FlowCookie> allCookies = flowCookieRepository.findAll(); FlowCookie foundCookie = allCookies.iterator().next(); flowCookieRepository.remove(foundCookie); }); assertEquals(0, flowCookieRepository.findAll().size()); } |
### Question:
FermaFlowCookieRepository extends FermaGenericRepository<FlowCookie, FlowCookieData, FlowCookieFrame> implements FlowCookieRepository { @Override public Optional<FlowCookie> findByCookie(long unmaskedCookie) { List<? extends FlowCookieFrame> flowCookieFrames = framedGraph().traverse(g -> g.V() .hasLabel(FlowCookieFrame.FRAME_LABEL) .has(FlowCookieFrame.UNMASKED_COOKIE_PROPERTY, unmaskedCookie)) .toListExplicit(FlowCookieFrame.class); return flowCookieFrames.isEmpty() ? Optional.empty() : Optional.of(flowCookieFrames.get(0)) .map(FlowCookie::new); } FermaFlowCookieRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowCookie> findAll(); @Override boolean exists(long unmaskedCookie); @Override Optional<FlowCookie> findByCookie(long unmaskedCookie); @Override Optional<Long> findFirstUnassignedCookie(long lowestCookieValue, long highestCookieValue); }### Answer:
@Test public void shouldSelectNextInOrderResourceWhenFindUnassignedCookie() { long first = findUnassignedCookieAndCreate("flow_1"); assertEquals(5, first); long second = findUnassignedCookieAndCreate("flow_2"); assertEquals(6, second); long third = findUnassignedCookieAndCreate("flow_3"); assertEquals(7, third); transactionManager.doInTransaction(() -> flowCookieRepository.findByCookie(second).ifPresent(flowCookieRepository::remove)); long fourth = findUnassignedCookieAndCreate("flow_4"); assertEquals(6, fourth); long fifth = findUnassignedCookieAndCreate("flow_5"); assertEquals(8, fifth); } |
### Question:
FermaFlowPathRepository extends FermaGenericRepository<FlowPath, FlowPathData, FlowPathFrame> implements FlowPathRepository { @Override public Optional<FlowPath> findById(PathId pathId) { List<? extends FlowPathFrame> flowPathFrames = framedGraph().traverse(g -> g.V() .hasLabel(FlowPathFrame.FRAME_LABEL) .has(FlowPathFrame.PATH_ID_PROPERTY, PathIdConverter.INSTANCE.toGraphProperty(pathId))) .toListExplicit(FlowPathFrame.class); return flowPathFrames.isEmpty() ? Optional.empty() : Optional.of(flowPathFrames.get(0)) .map(FlowPath::new); } FermaFlowPathRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowPath> findAll(); @Override Optional<FlowPath> findById(PathId pathId); @Override Optional<FlowPath> findByFlowIdAndCookie(String flowId, FlowSegmentCookie cookie); @Override Collection<FlowPath> findByFlowId(String flowId); @Override Collection<FlowPath> findByFlowGroupId(String flowGroupId); @Override Collection<PathId> findPathIdsByFlowGroupId(String flowGroupId); @Override Collection<FlowPath> findActualByFlowIds(Set<String> flowIds); @Override Collection<FlowPath> findBySrcSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findByEndpointSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findInactiveBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentSwitchWithMultiTable(SwitchId switchId, boolean multiTable); @Override Collection<FlowPath> findWithPathSegment(SwitchId srcSwitchId, int srcPort,
SwitchId dstSwitchId, int dstPort); @Override Collection<FlowPath> findBySegmentDestSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentEndpoint(SwitchId switchId, int port); @Override void updateStatus(PathId pathId, FlowPathStatus pathStatus); @Override long getUsedBandwidthBetweenEndpoints(SwitchId srcSwitchId, int srcPort, SwitchId dstSwitchId, int dstPort); @Override Optional<FlowPath> remove(PathId pathId); }### Answer:
@Test public void shouldFlowPathUpdateKeepRelations() { createTestFlowPathPair(); Flow foundFlow = flowRepository.findById(TEST_FLOW_ID).get(); assertThat(foundFlow.getPaths(), hasSize(2)); FlowPath foundPath = flowPathRepository.findById(flow.getForwardPathId()).get(); foundPath.setStatus(FlowPathStatus.INACTIVE); foundFlow = flowRepository.findById(TEST_FLOW_ID).get(); assertThat(foundFlow.getPaths(), hasSize(2)); }
@Test public void shouldFlowPathUpdateKeepFlowRelations() { createTestFlowPathPair(); Flow foundFlow = flowRepository.findById(TEST_FLOW_ID).get(); assertThat(foundFlow.getPaths(), hasSize(2)); FlowPath flowPath = foundFlow.getPaths().stream() .filter(path -> path.getPathId().equals(flow.getReversePathId())) .findAny().get(); flowPath.setStatus(FlowPathStatus.INACTIVE); foundFlow = flowRepository.findById(TEST_FLOW_ID).get(); assertThat(foundFlow.getPaths(), hasSize(2)); }
@Test public void shouldFindPathById() { FlowPath flowPath = createTestFlowPath(); Optional<FlowPath> foundPath = flowPathRepository.findById(flowPath.getPathId()); assertTrue(foundPath.isPresent()); }
@Test public void shouldKeepSegmentsOrdered() { FlowPath flowPath = createTestFlowPath(); List<PathSegment> segments = asList(PathSegment.builder() .srcSwitch(switchA) .destSwitch(switchC) .build(), PathSegment.builder() .srcSwitch(switchC) .destSwitch(switchB) .build()); flowPath.setSegments(segments); Optional<FlowPath> foundPath = flowPathRepository.findById(flowPath.getPathId()); assertEquals(foundPath.get().getSegments().get(0).getDestSwitchId(), switchC.getSwitchId()); } |
### Question:
FermaFlowPathRepository extends FermaGenericRepository<FlowPath, FlowPathData, FlowPathFrame> implements FlowPathRepository { @Override public Optional<FlowPath> findByFlowIdAndCookie(String flowId, FlowSegmentCookie cookie) { List<? extends FlowPathFrame> flowPathFrames = framedGraph().traverse(g -> g.V() .hasLabel(FlowPathFrame.FRAME_LABEL) .has(FlowPathFrame.FLOW_ID_PROPERTY, flowId) .has(FlowPathFrame.COOKIE_PROPERTY, FlowSegmentCookieConverter.INSTANCE.toGraphProperty(cookie))) .toListExplicit(FlowPathFrame.class); if (flowPathFrames.size() > 1) { throw new PersistenceException(format("Found more that 1 FlowPath entity by (%s, %s)", flowId, cookie)); } return flowPathFrames.isEmpty() ? Optional.empty() : Optional.of(flowPathFrames.get(0)).map(FlowPath::new); } FermaFlowPathRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowPath> findAll(); @Override Optional<FlowPath> findById(PathId pathId); @Override Optional<FlowPath> findByFlowIdAndCookie(String flowId, FlowSegmentCookie cookie); @Override Collection<FlowPath> findByFlowId(String flowId); @Override Collection<FlowPath> findByFlowGroupId(String flowGroupId); @Override Collection<PathId> findPathIdsByFlowGroupId(String flowGroupId); @Override Collection<FlowPath> findActualByFlowIds(Set<String> flowIds); @Override Collection<FlowPath> findBySrcSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findByEndpointSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findInactiveBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentSwitchWithMultiTable(SwitchId switchId, boolean multiTable); @Override Collection<FlowPath> findWithPathSegment(SwitchId srcSwitchId, int srcPort,
SwitchId dstSwitchId, int dstPort); @Override Collection<FlowPath> findBySegmentDestSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentEndpoint(SwitchId switchId, int port); @Override void updateStatus(PathId pathId, FlowPathStatus pathStatus); @Override long getUsedBandwidthBetweenEndpoints(SwitchId srcSwitchId, int srcPort, SwitchId dstSwitchId, int dstPort); @Override Optional<FlowPath> remove(PathId pathId); }### Answer:
@Test public void shouldFindPathByFlowIdAndCookie() { FlowPath flowPath = createTestFlowPath(); Optional<FlowPath> foundPath = flowPathRepository.findByFlowIdAndCookie(TEST_FLOW_ID, flowPath.getCookie()); assertTrue(foundPath.isPresent()); } |
### Question:
FermaFlowPathRepository extends FermaGenericRepository<FlowPath, FlowPathData, FlowPathFrame> implements FlowPathRepository { @Override public Collection<FlowPath> findBySrcSwitch(SwitchId switchId, boolean includeProtected) { List<FlowPath> result = new ArrayList<>(); framedGraph().traverse(g -> g.V() .hasLabel(FlowPathFrame.FRAME_LABEL) .has(FlowPathFrame.SRC_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId))) .frameExplicit(FlowPathFrame.class) .forEachRemaining(frame -> result.add(new FlowPath(frame))); if (includeProtected) { return result; } else { return result.stream() .filter(path -> !(path.isProtected() && switchId.equals(path.getSrcSwitchId()))) .collect(Collectors.toList()); } } FermaFlowPathRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowPath> findAll(); @Override Optional<FlowPath> findById(PathId pathId); @Override Optional<FlowPath> findByFlowIdAndCookie(String flowId, FlowSegmentCookie cookie); @Override Collection<FlowPath> findByFlowId(String flowId); @Override Collection<FlowPath> findByFlowGroupId(String flowGroupId); @Override Collection<PathId> findPathIdsByFlowGroupId(String flowGroupId); @Override Collection<FlowPath> findActualByFlowIds(Set<String> flowIds); @Override Collection<FlowPath> findBySrcSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findByEndpointSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findInactiveBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentSwitchWithMultiTable(SwitchId switchId, boolean multiTable); @Override Collection<FlowPath> findWithPathSegment(SwitchId srcSwitchId, int srcPort,
SwitchId dstSwitchId, int dstPort); @Override Collection<FlowPath> findBySegmentDestSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentEndpoint(SwitchId switchId, int port); @Override void updateStatus(PathId pathId, FlowPathStatus pathStatus); @Override long getUsedBandwidthBetweenEndpoints(SwitchId srcSwitchId, int srcPort, SwitchId dstSwitchId, int dstPort); @Override Optional<FlowPath> remove(PathId pathId); }### Answer:
@Test public void shouldFindProtectedPathsBySrcSwitchIncludeProtected() { createTestFlowPathPair(); flow.setProtectedForwardPath(createFlowPath(flow, "_forward_protected", 10, 10, switchA, switchB)); flow.setProtectedReversePath(createFlowPath(flow, "_reverse_protected", 11, 11, switchB, switchA)); assertThat(flowPathRepository.findBySrcSwitch(switchA.getSwitchId(), true), containsInAnyOrder(flow.getForwardPath(), flow.getProtectedForwardPath())); assertThat(flowPathRepository.findBySrcSwitch(switchB.getSwitchId(), true), containsInAnyOrder(flow.getReversePath(), flow.getProtectedReversePath())); }
@Test public void shouldFindBySrcSwitch() { createTestFlowPathPair(); Collection<FlowPath> paths = flowPathRepository.findBySrcSwitch(switchA.getSwitchId()); assertThat(paths, containsInAnyOrder(flow.getForwardPath())); }
@Test public void shouldFindPathBySrc() { createTestFlowPath(); Collection<FlowPath> foundPaths = flowPathRepository.findBySrcSwitch(switchA.getSwitchId()); assertThat(foundPaths, hasSize(1)); }
@Test public void shouldNotFindPathByWrongSrc() { createTestFlowPath(); Collection<FlowPath> foundPaths = flowPathRepository.findBySrcSwitch(switchB.getSwitchId()); assertThat(foundPaths, Matchers.empty()); } |
### Question:
FermaFlowPathRepository extends FermaGenericRepository<FlowPath, FlowPathData, FlowPathFrame> implements FlowPathRepository { @Override public Collection<FlowPath> findWithPathSegment(SwitchId srcSwitchId, int srcPort, SwitchId dstSwitchId, int dstPort) { return framedGraph().traverse(g -> g.V() .hasLabel(PathSegmentFrame.FRAME_LABEL) .has(PathSegmentFrame.SRC_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(srcSwitchId)) .has(PathSegmentFrame.DST_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(dstSwitchId)) .has(PathSegmentFrame.SRC_PORT_PROPERTY, srcPort) .has(PathSegmentFrame.DST_PORT_PROPERTY, dstPort) .in(FlowPathFrame.OWNS_SEGMENTS_EDGE) .hasLabel(FlowPathFrame.FRAME_LABEL)) .toListExplicit(FlowPathFrame.class).stream() .map(FlowPath::new) .collect(Collectors.toList()); } FermaFlowPathRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowPath> findAll(); @Override Optional<FlowPath> findById(PathId pathId); @Override Optional<FlowPath> findByFlowIdAndCookie(String flowId, FlowSegmentCookie cookie); @Override Collection<FlowPath> findByFlowId(String flowId); @Override Collection<FlowPath> findByFlowGroupId(String flowGroupId); @Override Collection<PathId> findPathIdsByFlowGroupId(String flowGroupId); @Override Collection<FlowPath> findActualByFlowIds(Set<String> flowIds); @Override Collection<FlowPath> findBySrcSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findByEndpointSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findInactiveBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentSwitchWithMultiTable(SwitchId switchId, boolean multiTable); @Override Collection<FlowPath> findWithPathSegment(SwitchId srcSwitchId, int srcPort,
SwitchId dstSwitchId, int dstPort); @Override Collection<FlowPath> findBySegmentDestSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentEndpoint(SwitchId switchId, int port); @Override void updateStatus(PathId pathId, FlowPathStatus pathStatus); @Override long getUsedBandwidthBetweenEndpoints(SwitchId srcSwitchId, int srcPort, SwitchId dstSwitchId, int dstPort); @Override Optional<FlowPath> remove(PathId pathId); }### Answer:
@Test public void shouldFindFlowPathsForIsl() { FlowPath flowPath = createTestFlowPathWithIntermediate(switchC, 100); flow.setForwardPath(flowPath); Collection<FlowPath> paths = flowPathRepository.findWithPathSegment(switchA.getSwitchId(), 1, switchC.getSwitchId(), 100); assertThat(paths, Matchers.hasSize(1)); assertThat(paths, containsInAnyOrder(flow.getForwardPath())); } |
### Question:
FermaFlowPathRepository extends FermaGenericRepository<FlowPath, FlowPathData, FlowPathFrame> implements FlowPathRepository { @Override public Collection<FlowPath> findBySegmentEndpoint(SwitchId switchId, int port) { Map<PathId, FlowPath> result = new HashMap<>(); framedGraph().traverse(g -> g.V() .hasLabel(PathSegmentFrame.FRAME_LABEL) .has(PathSegmentFrame.SRC_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(PathSegmentFrame.SRC_PORT_PROPERTY, port) .in(FlowPathFrame.OWNS_SEGMENTS_EDGE) .hasLabel(FlowPathFrame.FRAME_LABEL)) .frameExplicit(FlowPathFrame.class) .forEachRemaining(frame -> result.put(frame.getPathId(), new FlowPath(frame))); framedGraph().traverse(g -> g.V() .hasLabel(PathSegmentFrame.FRAME_LABEL) .has(PathSegmentFrame.DST_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(PathSegmentFrame.DST_PORT_PROPERTY, port) .in(FlowPathFrame.OWNS_SEGMENTS_EDGE) .hasLabel(FlowPathFrame.FRAME_LABEL)) .frameExplicit(FlowPathFrame.class) .forEachRemaining(frame -> result.put(frame.getPathId(), new FlowPath(frame))); return result.values(); } FermaFlowPathRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowPath> findAll(); @Override Optional<FlowPath> findById(PathId pathId); @Override Optional<FlowPath> findByFlowIdAndCookie(String flowId, FlowSegmentCookie cookie); @Override Collection<FlowPath> findByFlowId(String flowId); @Override Collection<FlowPath> findByFlowGroupId(String flowGroupId); @Override Collection<PathId> findPathIdsByFlowGroupId(String flowGroupId); @Override Collection<FlowPath> findActualByFlowIds(Set<String> flowIds); @Override Collection<FlowPath> findBySrcSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findByEndpointSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findInactiveBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentSwitchWithMultiTable(SwitchId switchId, boolean multiTable); @Override Collection<FlowPath> findWithPathSegment(SwitchId srcSwitchId, int srcPort,
SwitchId dstSwitchId, int dstPort); @Override Collection<FlowPath> findBySegmentDestSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentEndpoint(SwitchId switchId, int port); @Override void updateStatus(PathId pathId, FlowPathStatus pathStatus); @Override long getUsedBandwidthBetweenEndpoints(SwitchId srcSwitchId, int srcPort, SwitchId dstSwitchId, int dstPort); @Override Optional<FlowPath> remove(PathId pathId); }### Answer:
@Test public void shouldFindActiveAffectedPaths() { FlowPath flowPath = createTestFlowPathWithIntermediate(switchC, 100); flow.setForwardPath(flowPath); Collection<FlowPath> paths = flowPathRepository.findBySegmentEndpoint( switchC.getSwitchId(), 100); assertThat(paths, containsInAnyOrder(flowPath)); } |
### Question:
FermaFlowPathRepository extends FermaGenericRepository<FlowPath, FlowPathData, FlowPathFrame> implements FlowPathRepository { @Override public Collection<FlowPath> findByFlowId(String flowId) { return framedGraph().traverse(g -> g.V() .hasLabel(FlowPathFrame.FRAME_LABEL) .has(FlowPathFrame.FLOW_ID_PROPERTY, flowId)) .toListExplicit(FlowPathFrame.class).stream() .map(FlowPath::new) .collect(Collectors.toList()); } FermaFlowPathRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowPath> findAll(); @Override Optional<FlowPath> findById(PathId pathId); @Override Optional<FlowPath> findByFlowIdAndCookie(String flowId, FlowSegmentCookie cookie); @Override Collection<FlowPath> findByFlowId(String flowId); @Override Collection<FlowPath> findByFlowGroupId(String flowGroupId); @Override Collection<PathId> findPathIdsByFlowGroupId(String flowGroupId); @Override Collection<FlowPath> findActualByFlowIds(Set<String> flowIds); @Override Collection<FlowPath> findBySrcSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findByEndpointSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findInactiveBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentSwitchWithMultiTable(SwitchId switchId, boolean multiTable); @Override Collection<FlowPath> findWithPathSegment(SwitchId srcSwitchId, int srcPort,
SwitchId dstSwitchId, int dstPort); @Override Collection<FlowPath> findBySegmentDestSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentEndpoint(SwitchId switchId, int port); @Override void updateStatus(PathId pathId, FlowPathStatus pathStatus); @Override long getUsedBandwidthBetweenEndpoints(SwitchId srcSwitchId, int srcPort, SwitchId dstSwitchId, int dstPort); @Override Optional<FlowPath> remove(PathId pathId); }### Answer:
@Test public void shouldFindPathByFlowId() { createTestFlowPath(); Collection<FlowPath> foundPaths = flowPathRepository.findByFlowId(TEST_FLOW_ID); assertThat(foundPaths, hasSize(1)); } |
### Question:
FermaFlowPathRepository extends FermaGenericRepository<FlowPath, FlowPathData, FlowPathFrame> implements FlowPathRepository { @Override public Collection<FlowPath> findBySegmentSwitch(SwitchId switchId) { Map<PathId, FlowPath> result = new HashMap<>(); framedGraph().traverse(g -> g.V() .hasLabel(PathSegmentFrame.FRAME_LABEL) .has(PathSegmentFrame.SRC_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .in(FlowPathFrame.OWNS_SEGMENTS_EDGE) .hasLabel(FlowPathFrame.FRAME_LABEL)) .frameExplicit(FlowPathFrame.class) .forEachRemaining(frame -> result.put(frame.getPathId(), new FlowPath(frame))); framedGraph().traverse(g -> g.V() .hasLabel(PathSegmentFrame.FRAME_LABEL) .has(PathSegmentFrame.DST_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .in(FlowPathFrame.OWNS_SEGMENTS_EDGE) .hasLabel(FlowPathFrame.FRAME_LABEL)) .frameExplicit(FlowPathFrame.class) .forEachRemaining(frame -> result.put(frame.getPathId(), new FlowPath(frame))); return result.values(); } FermaFlowPathRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowPath> findAll(); @Override Optional<FlowPath> findById(PathId pathId); @Override Optional<FlowPath> findByFlowIdAndCookie(String flowId, FlowSegmentCookie cookie); @Override Collection<FlowPath> findByFlowId(String flowId); @Override Collection<FlowPath> findByFlowGroupId(String flowGroupId); @Override Collection<PathId> findPathIdsByFlowGroupId(String flowGroupId); @Override Collection<FlowPath> findActualByFlowIds(Set<String> flowIds); @Override Collection<FlowPath> findBySrcSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findByEndpointSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findInactiveBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentSwitchWithMultiTable(SwitchId switchId, boolean multiTable); @Override Collection<FlowPath> findWithPathSegment(SwitchId srcSwitchId, int srcPort,
SwitchId dstSwitchId, int dstPort); @Override Collection<FlowPath> findBySegmentDestSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentEndpoint(SwitchId switchId, int port); @Override void updateStatus(PathId pathId, FlowPathStatus pathStatus); @Override long getUsedBandwidthBetweenEndpoints(SwitchId srcSwitchId, int srcPort, SwitchId dstSwitchId, int dstPort); @Override Optional<FlowPath> remove(PathId pathId); }### Answer:
@Test public void shouldFindPathBySegmentSwitch() { FlowPath flowPath = createTestFlowPathWithIntermediate(switchC, 100); flow.setForwardPath(flowPath); Collection<FlowPath> foundPaths = flowPathRepository.findBySegmentSwitch(switchC.getSwitchId()); assertThat(foundPaths, hasSize(1)); } |
### Question:
FermaFlowPathRepository extends FermaGenericRepository<FlowPath, FlowPathData, FlowPathFrame> implements FlowPathRepository { @Override public Collection<FlowPath> findBySegmentDestSwitch(SwitchId switchId) { return framedGraph().traverse(g -> g.V() .hasLabel(PathSegmentFrame.FRAME_LABEL) .has(PathSegmentFrame.DST_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .in(FlowPathFrame.OWNS_SEGMENTS_EDGE) .hasLabel(FlowPathFrame.FRAME_LABEL)) .toListExplicit(FlowPathFrame.class).stream() .map(FlowPath::new) .collect(Collectors.toList()); } FermaFlowPathRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowPath> findAll(); @Override Optional<FlowPath> findById(PathId pathId); @Override Optional<FlowPath> findByFlowIdAndCookie(String flowId, FlowSegmentCookie cookie); @Override Collection<FlowPath> findByFlowId(String flowId); @Override Collection<FlowPath> findByFlowGroupId(String flowGroupId); @Override Collection<PathId> findPathIdsByFlowGroupId(String flowGroupId); @Override Collection<FlowPath> findActualByFlowIds(Set<String> flowIds); @Override Collection<FlowPath> findBySrcSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findByEndpointSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findInactiveBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentSwitchWithMultiTable(SwitchId switchId, boolean multiTable); @Override Collection<FlowPath> findWithPathSegment(SwitchId srcSwitchId, int srcPort,
SwitchId dstSwitchId, int dstPort); @Override Collection<FlowPath> findBySegmentDestSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentEndpoint(SwitchId switchId, int port); @Override void updateStatus(PathId pathId, FlowPathStatus pathStatus); @Override long getUsedBandwidthBetweenEndpoints(SwitchId srcSwitchId, int srcPort, SwitchId dstSwitchId, int dstPort); @Override Optional<FlowPath> remove(PathId pathId); }### Answer:
@Test public void shouldFindPathBySegmentDestSwitch() { FlowPath flowPath = createTestFlowPathWithIntermediate(switchC, 100); flow.setForwardPath(flowPath); Collection<FlowPath> foundPaths = flowPathRepository.findBySegmentDestSwitch(switchC.getSwitchId()); assertThat(foundPaths, hasSize(1)); }
@Test public void shouldNotFindPathByWrongSegmentDestSwitch() { FlowPath flowPath = createTestFlowPathWithIntermediate(switchC, 100); flow.setForwardPath(flowPath); Collection<FlowPath> foundPaths = flowPathRepository.findBySegmentDestSwitch(switchA.getSwitchId()); assertThat(foundPaths, Matchers.empty()); } |
### Question:
FermaFlowPathRepository extends FermaGenericRepository<FlowPath, FlowPathData, FlowPathFrame> implements FlowPathRepository { @Override public Collection<FlowPath> findActualByFlowIds(Set<String> flowIds) { Set<String> pathIds = new HashSet<>(); framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.FLOW_ID_PROPERTY, P.within(flowIds)) .values(FlowFrame.FORWARD_PATH_ID_PROPERTY, FlowFrame.REVERSE_PATH_ID_PROPERTY, FlowFrame.PROTECTED_FORWARD_PATH_ID_PROPERTY, FlowFrame.PROTECTED_REVERSE_PATH_ID_PROPERTY)) .getRawTraversal() .forEachRemaining(pathId -> pathIds.add((String) pathId)); return framedGraph().traverse(g -> g.V() .hasLabel(FlowPathFrame.FRAME_LABEL) .has(FlowPathFrame.PATH_ID_PROPERTY, P.within(pathIds))) .toListExplicit(FlowPathFrame.class).stream() .map(FlowPath::new) .collect(Collectors.toList()); } FermaFlowPathRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowPath> findAll(); @Override Optional<FlowPath> findById(PathId pathId); @Override Optional<FlowPath> findByFlowIdAndCookie(String flowId, FlowSegmentCookie cookie); @Override Collection<FlowPath> findByFlowId(String flowId); @Override Collection<FlowPath> findByFlowGroupId(String flowGroupId); @Override Collection<PathId> findPathIdsByFlowGroupId(String flowGroupId); @Override Collection<FlowPath> findActualByFlowIds(Set<String> flowIds); @Override Collection<FlowPath> findBySrcSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findByEndpointSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findInactiveBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentSwitchWithMultiTable(SwitchId switchId, boolean multiTable); @Override Collection<FlowPath> findWithPathSegment(SwitchId srcSwitchId, int srcPort,
SwitchId dstSwitchId, int dstPort); @Override Collection<FlowPath> findBySegmentDestSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentEndpoint(SwitchId switchId, int port); @Override void updateStatus(PathId pathId, FlowPathStatus pathStatus); @Override long getUsedBandwidthBetweenEndpoints(SwitchId srcSwitchId, int srcPort, SwitchId dstSwitchId, int dstPort); @Override Optional<FlowPath> remove(PathId pathId); }### Answer:
@Test public void shouldFindFlowPathIdsByFlowIds() { Flow flowA = buildTestProtectedFlow(TEST_FLOW_ID_1, switchA, PORT_1, VLAN_1, switchB, PORT_2, VLAN_2); flowRepository.add(flowA); Flow flowB = buildTestFlow(TEST_FLOW_ID_2, switchA, PORT_1, VLAN_2, switchB, PORT_2, 0); flowRepository.add(flowB); Flow flowC = buildTestProtectedFlow(TEST_FLOW_ID_3, switchB, PORT_1, VLAN_1, switchB, PORT_3, VLAN_1); flowRepository.add(flowC); Collection<FlowPath> flowPaths = flowPathRepository.findActualByFlowIds(Sets.newHashSet(TEST_FLOW_ID_1, TEST_FLOW_ID_2)); Collection<PathId> pathIds = flowPaths.stream().map(FlowPath::getPathId).collect(Collectors.toList()); assertEquals(6, pathIds.size()); assertTrue(pathIds.contains(flowA.getForwardPathId())); assertTrue(pathIds.contains(flowA.getReversePathId())); assertTrue(pathIds.contains(flowA.getProtectedForwardPathId())); assertTrue(pathIds.contains(flowA.getProtectedReversePathId())); assertTrue(pathIds.contains(flowB.getForwardPathId())); assertTrue(pathIds.contains(flowB.getReversePathId())); } |
### Question:
FermaApplicationRepository extends FermaGenericRepository<ApplicationRule, ApplicationRuleData,
ApplicationRuleFrame> implements ApplicationRepository { @Override public Optional<ApplicationRule> lookupRuleByMatchAndFlow(SwitchId switchId, String flowId, String srcIp, Integer srcPort, String dstIp, Integer dstPort, String proto, String ethType, Long metadata) { List<? extends ApplicationRuleFrame> applicationRuleFrames = framedGraph().traverse(g -> g.V() .hasLabel(ApplicationRuleFrame.FRAME_LABEL) .has(ApplicationRuleFrame.SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(ApplicationRuleFrame.FLOW_ID_PROPERTY, flowId) .has(ApplicationRuleFrame.SRC_IP_PROPERTY, srcIp) .has(ApplicationRuleFrame.SRC_PORT_PROPERTY, srcPort) .has(ApplicationRuleFrame.DST_IP_PROPERTY, dstIp) .has(ApplicationRuleFrame.DST_PORT_PROPERTY, dstPort) .has(ApplicationRuleFrame.PROTO_PROPERTY, proto) .has(ApplicationRuleFrame.ETH_TYPE_PROPERTY, ethType) .has(ApplicationRuleFrame.METADATA_PROPERTY, metadata)) .toListExplicit(ApplicationRuleFrame.class); return applicationRuleFrames.isEmpty() ? Optional.empty() : Optional.of(applicationRuleFrames.get(0)) .map(ApplicationRule::new); } FermaApplicationRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Optional<ApplicationRule> lookupRuleByMatchAndFlow(SwitchId switchId, String flowId, String srcIp,
Integer srcPort, String dstIp, Integer dstPort,
String proto, String ethType, Long metadata); @Override Optional<ApplicationRule> lookupRuleByMatchAndCookie(SwitchId switchId, ExclusionCookie cookie, String srcIp,
Integer srcPort, String dstIp, Integer dstPort,
String proto, String ethType, Long metadata); @Override Collection<ApplicationRule> findBySwitchId(SwitchId switchId); @Override Collection<ApplicationRule> findByFlowId(String flowId); }### Answer:
@Test public void shouldLookupRuleByMatchAndFlow() { ApplicationRule ruleA = buildRuleA(); ApplicationRule foundRule = applicationRepository.lookupRuleByMatchAndFlow(ruleA.getSwitchId(), ruleA.getFlowId(), ruleA.getSrcIp(), ruleA.getSrcPort(), ruleA.getDstIp(), ruleA.getDstPort(), ruleA.getProto(), ruleA.getEthType(), ruleA.getMetadata()).get(); assertEquals(ruleA, foundRule); } |
### Question:
FermaApplicationRepository extends FermaGenericRepository<ApplicationRule, ApplicationRuleData,
ApplicationRuleFrame> implements ApplicationRepository { @Override public Optional<ApplicationRule> lookupRuleByMatchAndCookie(SwitchId switchId, ExclusionCookie cookie, String srcIp, Integer srcPort, String dstIp, Integer dstPort, String proto, String ethType, Long metadata) { List<? extends ApplicationRuleFrame> applicationRuleFrames = framedGraph().traverse(g -> g.V() .hasLabel(ApplicationRuleFrame.FRAME_LABEL) .has(ApplicationRuleFrame.SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(ApplicationRuleFrame.COOKIE_PROPERTY, ExclusionCookieConverter.INSTANCE.toGraphProperty(cookie)) .has(ApplicationRuleFrame.SRC_IP_PROPERTY, srcIp) .has(ApplicationRuleFrame.SRC_PORT_PROPERTY, srcPort) .has(ApplicationRuleFrame.DST_IP_PROPERTY, dstIp) .has(ApplicationRuleFrame.DST_PORT_PROPERTY, dstPort) .has(ApplicationRuleFrame.PROTO_PROPERTY, proto) .has(ApplicationRuleFrame.ETH_TYPE_PROPERTY, ethType) .has(ApplicationRuleFrame.METADATA_PROPERTY, metadata)) .toListExplicit(ApplicationRuleFrame.class); return applicationRuleFrames.isEmpty() ? Optional.empty() : Optional.of(applicationRuleFrames.get(0)) .map(ApplicationRule::new); } FermaApplicationRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Optional<ApplicationRule> lookupRuleByMatchAndFlow(SwitchId switchId, String flowId, String srcIp,
Integer srcPort, String dstIp, Integer dstPort,
String proto, String ethType, Long metadata); @Override Optional<ApplicationRule> lookupRuleByMatchAndCookie(SwitchId switchId, ExclusionCookie cookie, String srcIp,
Integer srcPort, String dstIp, Integer dstPort,
String proto, String ethType, Long metadata); @Override Collection<ApplicationRule> findBySwitchId(SwitchId switchId); @Override Collection<ApplicationRule> findByFlowId(String flowId); }### Answer:
@Test public void shouldLookupRuleByMatchAndCookie() { ApplicationRule ruleA = buildRuleA(); ApplicationRule foundRule = applicationRepository.lookupRuleByMatchAndCookie(ruleA.getSwitchId(), ruleA.getCookie(), ruleA.getSrcIp(), ruleA.getSrcPort(), ruleA.getDstIp(), ruleA.getDstPort(), ruleA.getProto(), ruleA.getEthType(), ruleA.getMetadata()).get(); assertEquals(ruleA, foundRule); } |
### Question:
FermaApplicationRepository extends FermaGenericRepository<ApplicationRule, ApplicationRuleData,
ApplicationRuleFrame> implements ApplicationRepository { @Override public Collection<ApplicationRule> findBySwitchId(SwitchId switchId) { return framedGraph().traverse(g -> g.V() .hasLabel(ApplicationRuleFrame.FRAME_LABEL) .has(ApplicationRuleFrame.SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId))) .toListExplicit(ApplicationRuleFrame.class).stream() .map(ApplicationRule::new) .collect(Collectors.toList()); } FermaApplicationRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Optional<ApplicationRule> lookupRuleByMatchAndFlow(SwitchId switchId, String flowId, String srcIp,
Integer srcPort, String dstIp, Integer dstPort,
String proto, String ethType, Long metadata); @Override Optional<ApplicationRule> lookupRuleByMatchAndCookie(SwitchId switchId, ExclusionCookie cookie, String srcIp,
Integer srcPort, String dstIp, Integer dstPort,
String proto, String ethType, Long metadata); @Override Collection<ApplicationRule> findBySwitchId(SwitchId switchId); @Override Collection<ApplicationRule> findByFlowId(String flowId); }### Answer:
@Test public void shouldFindBySwitchId() { Collection<ApplicationRule> foundRules = applicationRepository.findBySwitchId(TEST_SWITCH_ID); assertEquals(2, foundRules.size()); assertTrue(foundRules.contains(buildRuleA())); assertTrue(foundRules.contains(buildRuleC())); } |
### Question:
FermaApplicationRepository extends FermaGenericRepository<ApplicationRule, ApplicationRuleData,
ApplicationRuleFrame> implements ApplicationRepository { @Override public Collection<ApplicationRule> findByFlowId(String flowId) { return framedGraph().traverse(g -> g.V() .hasLabel(ApplicationRuleFrame.FRAME_LABEL) .has(ApplicationRuleFrame.FLOW_ID_PROPERTY, flowId)) .toListExplicit(ApplicationRuleFrame.class).stream() .map(ApplicationRule::new) .collect(Collectors.toList()); } FermaApplicationRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Optional<ApplicationRule> lookupRuleByMatchAndFlow(SwitchId switchId, String flowId, String srcIp,
Integer srcPort, String dstIp, Integer dstPort,
String proto, String ethType, Long metadata); @Override Optional<ApplicationRule> lookupRuleByMatchAndCookie(SwitchId switchId, ExclusionCookie cookie, String srcIp,
Integer srcPort, String dstIp, Integer dstPort,
String proto, String ethType, Long metadata); @Override Collection<ApplicationRule> findBySwitchId(SwitchId switchId); @Override Collection<ApplicationRule> findByFlowId(String flowId); }### Answer:
@Test public void shouldFindByFlowId() { Collection<ApplicationRule> foundRules = applicationRepository.findByFlowId(TEST_FLOW_ID); assertEquals(2, foundRules.size()); assertTrue(foundRules.contains(buildRuleA())); assertTrue(foundRules.contains(buildRuleB())); } |
### Question:
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public Collection<Flow> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL)) .toListExplicit(FlowFrame.class).stream() .map(Flow::new) .collect(Collectors.toList()); } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }### Answer:
@Test public void shouldCreateFlow() { createTestFlow(TEST_FLOW_ID, switchA, switchB); Collection<Flow> allFlows = flowRepository.findAll(); Flow foundFlow = allFlows.iterator().next(); assertEquals(switchA.getSwitchId(), foundFlow.getSrcSwitchId()); assertEquals(switchB.getSwitchId(), foundFlow.getDestSwitchId()); } |
### Question:
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public Optional<Flow> findById(String flowId) { List<? extends FlowFrame> flowFrames = framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.FLOW_ID_PROPERTY, flowId)) .toListExplicit(FlowFrame.class); return flowFrames.isEmpty() ? Optional.empty() : Optional.of(flowFrames.get(0)) .map(Flow::new); } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }### Answer:
@Test public void shouldNotFindByIdWithEndpoints() { assertFalse(flowRepository.findById("Non_existent").isPresent()); }
@Test public void shouldFindFlowById() { createTestFlow(TEST_FLOW_ID, switchA, switchB); Optional<Flow> foundFlow = flowRepository.findById(TEST_FLOW_ID); assertTrue(foundFlow.isPresent()); }
@Test public void shouldFind2SegmentFlowById() { Switch switchC = createTestSwitch(TEST_SWITCH_C_ID.getId()); createTestFlowWithIntermediate(TEST_FLOW_ID, switchA, switchC, 100, switchB); Optional<Flow> foundFlow = flowRepository.findById(TEST_FLOW_ID); assertTrue(foundFlow.isPresent()); } |
### Question:
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public boolean exists(String flowId) { try (GraphTraversal<?, ?> traversal = framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.FLOW_ID_PROPERTY, flowId)) .getRawTraversal()) { return traversal.hasNext(); } catch (Exception e) { throw new PersistenceException("Failed to traverse", e); } } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }### Answer:
@Test public void shouldCheckForExistence() { createTestFlow(TEST_FLOW_ID, switchA, switchB); assertTrue(flowRepository.exists(TEST_FLOW_ID)); } |
### Question:
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public Collection<Flow> findByGroupId(String flowGroupId) { return framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.GROUP_ID_PROPERTY, flowGroupId)) .toListExplicit(FlowFrame.class).stream() .map(Flow::new) .collect(Collectors.toList()); } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }### Answer:
@Test public void shouldFindFlowByGroupId() { Flow flow = createTestFlow(TEST_FLOW_ID, switchA, switchB); flow.setGroupId(TEST_GROUP_ID); List<Flow> foundFlow = Lists.newArrayList(flowRepository.findByGroupId(TEST_GROUP_ID)); assertThat(foundFlow, Matchers.hasSize(1)); assertEquals(Collections.singletonList(flow), foundFlow); } |
### Question:
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public Collection<String> findFlowsIdByGroupId(String flowGroupId) { return framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.GROUP_ID_PROPERTY, flowGroupId) .values(FlowFrame.FLOW_ID_PROPERTY)) .getRawTraversal().toStream() .map(i -> (String) i) .collect(Collectors.toList()); } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }### Answer:
@Test public void shouldFindFlowsIdByGroupId() { Flow flow = createTestFlow(TEST_FLOW_ID, switchA, switchB); flow.setGroupId(TEST_GROUP_ID); List<String> foundFlowId = Lists.newArrayList(flowRepository.findFlowsIdByGroupId(TEST_GROUP_ID)); assertThat(foundFlowId, Matchers.hasSize(1)); assertEquals(Collections.singletonList(TEST_FLOW_ID), foundFlowId); } |
### Question:
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public Collection<Flow> findByEndpoint(SwitchId switchId, int port) { Map<String, Flow> result = new HashMap<>(); framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.SRC_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(FlowFrame.SRC_PORT_PROPERTY, port)) .frameExplicit(FlowFrame.class) .forEachRemaining(frame -> result.put(frame.getFlowId(), new Flow(frame))); framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.DST_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(FlowFrame.DST_PORT_PROPERTY, port)) .frameExplicit(FlowFrame.class) .forEachRemaining(frame -> result.put(frame.getFlowId(), new Flow(frame))); return result.values(); } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }### Answer:
@Test public void shouldFindFlowByEndpoint() { Flow flow = createTestFlow(TEST_FLOW_ID, switchA, switchB); Collection<Flow> foundFlows = flowRepository.findByEndpoint(TEST_SWITCH_A_ID, 1); Set<String> foundFlowIds = foundFlows.stream().map(foundFlow -> flow.getFlowId()).collect(Collectors.toSet()); assertThat(foundFlowIds, Matchers.hasSize(1)); } |
### Question:
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan) { List<? extends FlowFrame> flowFrames = framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.SRC_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(FlowFrame.SRC_PORT_PROPERTY, port) .has(FlowFrame.SRC_VLAN_PROPERTY, vlan)) .toListExplicit(FlowFrame.class); if (!flowFrames.isEmpty()) { return Optional.of(flowFrames.get(0)).map(Flow::new); } flowFrames = framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.DST_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(FlowFrame.DST_PORT_PROPERTY, port) .has(FlowFrame.DST_VLAN_PROPERTY, vlan)) .toListExplicit(FlowFrame.class); return flowFrames.isEmpty() ? Optional.empty() : Optional.of(flowFrames.get(0)).map(Flow::new); } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }### Answer:
@Test public void shouldNotFindFlowByEndpointAndVlan() { assertFalse(flowRepository.findByEndpointAndVlan(new SwitchId(1234), 999, 999).isPresent()); } |
### Question:
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public Collection<Flow> findByEndpointSwitch(SwitchId switchId) { Map<String, Flow> result = new HashMap<>(); framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.SRC_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId))) .frameExplicit(FlowFrame.class) .forEachRemaining(frame -> result.put(frame.getFlowId(), new Flow(frame))); framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.DST_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId))) .frameExplicit(FlowFrame.class) .forEachRemaining(frame -> result.put(frame.getFlowId(), new Flow(frame))); return result.values(); } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }### Answer:
@Test public void shouldFindFlowBySwitchEndpoint() { Flow flow = createTestFlow(TEST_FLOW_ID, switchA, switchB); Collection<Flow> foundFlows = flowRepository.findByEndpointSwitch(TEST_SWITCH_A_ID); Set<String> foundFlowIds = foundFlows.stream().map(foundFlow -> flow.getFlowId()).collect(Collectors.toSet()); assertThat(foundFlowIds, Matchers.hasSize(1)); } |
### Question:
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId) { Map<String, Flow> result = new HashMap<>(); framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.SRC_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(FlowFrame.SRC_MULTI_TABLE_PROPERTY, true)) .frameExplicit(FlowFrame.class) .forEachRemaining(frame -> result.put(frame.getFlowId(), new Flow(frame))); framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.DST_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(FlowFrame.DST_MULTI_TABLE_PROPERTY, true)) .frameExplicit(FlowFrame.class) .forEachRemaining(frame -> result.put(frame.getFlowId(), new Flow(frame))); return result.values(); } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }### Answer:
@Test public void shouldFindFlowBySwitchEndpointWithMultiTable() { Flow firstFlow = createTestFlow(TEST_FLOW_ID, switchA, switchB); firstFlow.setSrcWithMultiTable(true); Flow secondFlow = createTestFlow(TEST_FLOW_ID_2, switchA, switchB); secondFlow.setSrcWithMultiTable(false); Collection<Flow> foundFlows = flowRepository.findByEndpointSwitchWithMultiTableSupport(TEST_SWITCH_A_ID); Set<String> foundFlowIds = foundFlows.stream().map(Flow::getFlowId).collect(Collectors.toSet()); assertEquals(Collections.singleton(firstFlow.getFlowId()), foundFlowIds); } |
### Question:
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public Collection<Flow> findOneSwitchFlows(SwitchId switchId) { return framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.SRC_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(FlowFrame.DST_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId))) .toListExplicit(FlowFrame.class).stream() .map(Flow::new) .collect(Collectors.toList()); } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }### Answer:
@Test public void shouldFindOneFlowByEndpoint() { Flow flow1 = createTestFlow(TEST_FLOW_ID, switchA, switchA); flow1.setSrcPort(1); flow1.setDestPort(2); Flow flow2 = createTestFlow(TEST_FLOW_ID_2, switchB, switchB); flow2.setSrcPort(1); flow2.setDestPort(2); createTestFlow(TEST_FLOW_ID_3, switchA, switchB); Collection<Flow> foundFlows = flowRepository.findOneSwitchFlows(switchA.getSwitchId()); assertEquals(1, foundFlows.size()); assertEquals(TEST_FLOW_ID, foundFlows.iterator().next().getFlowId()); } |
### Question:
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public Collection<Flow> findInactiveFlows() { String downFlowStatus = FlowStatusConverter.INSTANCE.toGraphProperty(FlowStatus.DOWN); String degragedFlowStatus = FlowStatusConverter.INSTANCE.toGraphProperty(FlowStatus.DEGRADED); return framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.STATUS_PROPERTY, P.within(downFlowStatus, degragedFlowStatus))) .toListExplicit(FlowFrame.class).stream() .map(Flow::new) .collect(Collectors.toList()); } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }### Answer:
@Test public void shouldFindDownFlowIdsByEndpoint() { Flow flow = createTestFlow(TEST_FLOW_ID, switchA, switchB); flow.setStatus(FlowStatus.DOWN); Collection<Flow> foundFlows = flowRepository.findInactiveFlows(); assertThat(foundFlows, Matchers.hasSize(1)); } |
### Question:
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public Optional<String> getOrCreateFlowGroupId(String flowId) { return transactionManager.doInTransaction(() -> findById(flowId) .map(diverseFlow -> { if (diverseFlow.getGroupId() == null) { String groupId = UUID.randomUUID().toString(); diverseFlow.setGroupId(groupId); } return diverseFlow.getGroupId(); })); } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }### Answer:
@Test public void shouldGetFlowGroupIdForFlow() { Flow flow = createTestFlow(TEST_FLOW_ID, switchA, switchB); flow.setGroupId(TEST_GROUP_ID); Optional<String> groupOptional = flowRepository.getOrCreateFlowGroupId(TEST_FLOW_ID); assertTrue(groupOptional.isPresent()); assertEquals(TEST_GROUP_ID, groupOptional.get()); } |
### Question:
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public long computeFlowsBandwidthSum(Set<String> flowIds) { try (GraphTraversal<?, ?> traversal = framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.FLOW_ID_PROPERTY, P.within(flowIds)) .values(FlowFrame.BANDWIDTH_PROPERTY).sum()) .getRawTraversal()) { return traversal.tryNext() .filter(n -> !(n instanceof Double && ((Double) n).isNaN())) .map(l -> (Long) l) .orElse(0L); } catch (Exception e) { throw new PersistenceException("Failed to traverse", e); } } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }### Answer:
@Test public void shouldComputeSumOfFlowsBandwidth() { long firstFlowBandwidth = 100000L; long secondFlowBandwidth = 500000L; Flow firstFlow = createTestFlow(TEST_FLOW_ID, switchA, switchB); firstFlow.setBandwidth(firstFlowBandwidth); Flow secondFlow = createTestFlow(TEST_FLOW_ID_2, switchA, switchB); secondFlow.setBandwidth(secondFlowBandwidth); long foundBandwidth = flowRepository.computeFlowsBandwidthSum(Sets.newHashSet(TEST_FLOW_ID, TEST_FLOW_ID_2)); assertEquals(firstFlowBandwidth + secondFlowBandwidth, foundBandwidth); } |
### Question:
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public Collection<Flow> findByFlowFilter(FlowFilter flowFilter) { return framedGraph().traverse(g -> { GraphTraversal<Vertex, Vertex> traversal = g.V() .hasLabel(FlowFrame.FRAME_LABEL); if (flowFilter.getFlowStatus() != null) { traversal = traversal.has(FlowFrame.STATUS_PROPERTY, FlowStatusConverter.INSTANCE.toGraphProperty(flowFilter.getFlowStatus())); } return traversal; }).toListExplicit(FlowFrame.class).stream() .map(Flow::new) .collect(Collectors.toList()); } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }### Answer:
@Test public void shouldGetAllDownFlows() { Flow flowA = createTestFlow(TEST_FLOW_ID, switchA, switchB); flowA.setStatus(FlowStatus.DOWN); Flow flowB = createTestFlow(TEST_FLOW_ID_2, switchA, switchB); flowB.setStatus(FlowStatus.DOWN); createTestFlow(TEST_FLOW_ID_3, switchA, switchB); Collection<String> foundDownFlows = flowRepository.findByFlowFilter(FlowFilter.builder().flowStatus(FlowStatus.DOWN).build()).stream() .map(Flow::getFlowId) .collect(Collectors.toList()); assertEquals(2, foundDownFlows.size()); assertTrue(foundDownFlows.contains(TEST_FLOW_ID)); assertTrue(foundDownFlows.contains(TEST_FLOW_ID_2)); Collection<String> foundFlows = flowRepository.findByFlowFilter(FlowFilter.builder().build()).stream() .map(Flow::getFlowId) .collect(Collectors.toList()); assertEquals(3, foundFlows.size()); } |
### Question:
FermaSwitchRepository extends FermaGenericRepository<Switch, SwitchData, SwitchFrame> implements SwitchRepository { @Override public Collection<Switch> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(SwitchFrame.FRAME_LABEL)) .toListExplicit(SwitchFrame.class).stream() .map(Switch::new) .collect(Collectors.toList()); } FermaSwitchRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<Switch> findAll(); @Override boolean exists(SwitchId switchId); @Override Collection<Switch> findActive(); @Override Optional<Switch> findById(SwitchId switchId); @Override Collection<Switch> findSwitchesInFlowPathByFlowId(String flowId); @Override @TransactionRequired boolean removeIfNoDependant(Switch entity); }### Answer:
@Test public void shouldCreateSwitch() { switchRepository.add(Switch.builder() .switchId(TEST_SWITCH_ID_A) .description("Some description") .build()); assertEquals(1, switchRepository.findAll().size()); }
@Test public void shouldDeleteSwitch() { Switch origSwitch = Switch.builder() .switchId(TEST_SWITCH_ID_A) .description("Some description") .build(); switchRepository.add(origSwitch); transactionManager.doInTransaction(() -> switchRepository.remove(origSwitch)); assertEquals(0, switchRepository.findAll().size()); } |
### Question:
FermaSwitchRepository extends FermaGenericRepository<Switch, SwitchData, SwitchFrame> implements SwitchRepository { @Override public Collection<Switch> findActive() { return framedGraph().traverse(g -> g.V() .hasLabel(SwitchFrame.FRAME_LABEL) .has(SwitchFrame.STATUS_PROPERTY, SwitchStatusConverter.INSTANCE.toGraphProperty(SwitchStatus.ACTIVE))) .toListExplicit(SwitchFrame.class).stream() .map(Switch::new) .collect(Collectors.toList()); } FermaSwitchRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<Switch> findAll(); @Override boolean exists(SwitchId switchId); @Override Collection<Switch> findActive(); @Override Optional<Switch> findById(SwitchId switchId); @Override Collection<Switch> findSwitchesInFlowPathByFlowId(String flowId); @Override @TransactionRequired boolean removeIfNoDependant(Switch entity); }### Answer:
@Test public void shouldFindActive() { Switch activeSwitch = Switch.builder().switchId(TEST_SWITCH_ID_A) .status(SwitchStatus.ACTIVE).build(); Switch inactiveSwitch = Switch.builder().switchId(TEST_SWITCH_ID_B) .status(SwitchStatus.INACTIVE).build(); switchRepository.add(activeSwitch); switchRepository.add(inactiveSwitch); Collection<Switch> switches = switchRepository.findActive(); assertEquals(1, switches.size()); assertEquals(TEST_SWITCH_ID_A, switches.iterator().next().getSwitchId()); } |
### Question:
FermaSwitchRepository extends FermaGenericRepository<Switch, SwitchData, SwitchFrame> implements SwitchRepository { @Override public Optional<Switch> findById(SwitchId switchId) { return SwitchFrame.load(framedGraph(), SwitchIdConverter.INSTANCE.toGraphProperty(switchId)).map(Switch::new); } FermaSwitchRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<Switch> findAll(); @Override boolean exists(SwitchId switchId); @Override Collection<Switch> findActive(); @Override Optional<Switch> findById(SwitchId switchId); @Override Collection<Switch> findSwitchesInFlowPathByFlowId(String flowId); @Override @TransactionRequired boolean removeIfNoDependant(Switch entity); }### Answer:
@Test public void shouldFindSwitchById() { Switch origSwitch = Switch.builder() .switchId(TEST_SWITCH_ID_A) .description("Some description") .build(); switchRepository.add(origSwitch); Switch foundSwitch = switchRepository.findById(TEST_SWITCH_ID_A).get(); assertEquals(origSwitch.getDescription(), foundSwitch.getDescription()); } |
### Question:
FermaSwitchRepository extends FermaGenericRepository<Switch, SwitchData, SwitchFrame> implements SwitchRepository { @Override public Collection<Switch> findSwitchesInFlowPathByFlowId(String flowId) { List<? extends FlowPathFrame> flowPathFrames = framedGraph().traverse(g -> g.V() .hasLabel(FlowPathFrame.FRAME_LABEL) .has(FlowPathFrame.FLOW_ID_PROPERTY, flowId)) .toListExplicit(FlowPathFrame.class); if (flowPathFrames.isEmpty()) { return emptyList(); } Map<SwitchId, Switch> result = new HashMap<>(); flowPathFrames.forEach(flowPath -> { Stream.of(flowPath.getSrcSwitch(), flowPath.getDestSwitch()) .forEach(sw -> result.put(sw.getSwitchId(), sw)); flowPath.getSegments().forEach(pathSegment -> { Stream.of(pathSegment.getSrcSwitch(), pathSegment.getDestSwitch()) .forEach(sw -> result.put(sw.getSwitchId(), sw)); }); }); return result.values(); } FermaSwitchRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<Switch> findAll(); @Override boolean exists(SwitchId switchId); @Override Collection<Switch> findActive(); @Override Optional<Switch> findById(SwitchId switchId); @Override Collection<Switch> findSwitchesInFlowPathByFlowId(String flowId); @Override @TransactionRequired boolean removeIfNoDependant(Switch entity); }### Answer:
@Test public void shouldFindSwitchesByFlowId() { createTwoFlows(); Collection<SwitchId> switches = switchRepository.findSwitchesInFlowPathByFlowId(TEST_FLOW_ID_A).stream() .map(Switch::getSwitchId) .collect(Collectors.toList()); assertEquals(2, switches.size()); assertTrue(switches.contains(TEST_SWITCH_ID_A)); assertTrue(switches.contains(TEST_SWITCH_ID_B)); assertFalse(switches.contains(TEST_SWITCH_ID_C)); }
@Test public void shouldFindSwitchOfOneSwitchFlowByFlowId() { createOneSwitchFlow(); Collection<SwitchId> switches = switchRepository.findSwitchesInFlowPathByFlowId(TEST_FLOW_ID_A).stream() .map(Switch::getSwitchId) .collect(Collectors.toList()); assertEquals(1, switches.size()); assertTrue(switches.contains(TEST_SWITCH_ID_A)); } |
### Question:
FermaTransitVlanRepository extends FermaGenericRepository<TransitVlan, TransitVlanData, TransitVlanFrame> implements TransitVlanRepository { @Override public Collection<TransitVlan> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(TransitVlanFrame.FRAME_LABEL)) .toListExplicit(TransitVlanFrame.class).stream() .map(TransitVlan::new) .collect(Collectors.toList()); } FermaTransitVlanRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<TransitVlan> findAll(); @Override Collection<TransitVlan> findByPathId(PathId pathId, PathId oppositePathId); @Override Optional<TransitVlan> findByPathId(PathId pathId); @Override boolean exists(int vlan); @Override Optional<TransitVlan> findByVlan(int vlan); @Override Optional<Integer> findFirstUnassignedVlan(int lowestTransitVlan, int highestTransitVlan); }### Answer:
@Test public void shouldCreateTransitVlan() { TransitVlan vlan = createTransitVlan(); Collection<TransitVlan> allVlans = transitVlanRepository.findAll(); TransitVlan foundVlan = allVlans.iterator().next(); assertEquals(vlan.getVlan(), foundVlan.getVlan()); assertEquals(TEST_FLOW_ID, foundVlan.getFlowId()); }
@Test public void shouldDeleteTransitVlan() { TransitVlan vlan = createTransitVlan(); transactionManager.doInTransaction(() -> transitVlanRepository.remove(vlan)); assertEquals(0, transitVlanRepository.findAll().size()); }
@Test public void shouldDeleteFoundTransitVlan() { createTransitVlan(); Collection<TransitVlan> allVlans = transitVlanRepository.findAll(); TransitVlan foundVlan = allVlans.iterator().next(); transactionManager.doInTransaction(() -> transitVlanRepository.remove(foundVlan)); assertEquals(0, transitVlanRepository.findAll().size()); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.