src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
|---|---|
JDKImperativeDeckOfCardsAsList { public Map<Rank, Long> countsByRank() { var result = new HashMap<Rank, Long>(); for (var card : this.cards) { var rank = card.rank(); var value = result.computeIfAbsent(rank, r -> Long.valueOf(0)); result.put(rank, value + 1); } return result; } JDKImperativeDeckOfCardsAsList(); Deque<Card> shuffle(Random random); Set<Card> deal(Deque<Card> deque, int count); List<Set<Card>> shuffleAndDeal(Random random, int hands, int cardsPerHand); List<Set<Card>> dealHands(Deque<Card> shuffled, int hands, int cardsPerHand); List<Card> diamonds(); List<Card> hearts(); List<Card> spades(); List<Card> clubs(); Map<Suit, Long> countsBySuit(); Map<Rank, Long> countsByRank(); List<Card> getCards(); Map<Suit, List<Card>> getCardsBySuit(); }
|
@Test public void countsByRank() { Assert.assertEquals(Long.valueOf(4), this.jdkDeck.countsByRank().get(Rank.TEN)); }
|
VavrDeckOfCardsAsList { public List<Card> getCards() { return this.cards; } VavrDeckOfCardsAsList(); List<Card> shuffle(Random random); Tuple2<Set<Card>, ? extends List<Card>> deal(List<Card> stack, int count); List<Set<Card>> shuffleAndDeal(Random random, int hands, int cardsPerHand); List<Set<Card>> dealHands(
List<Card> shuffled,
int hands,
int cardsPerHand); List<Card> diamonds(); List<Card> hearts(); List<Card> spades(); List<Card> clubs(); Map<Suit, Long> countsBySuit(); Map<Rank, Long> countsByRank(); List<Card> getCards(); Map<Suit, ? extends List<Card>> getCardsBySuit(); }
|
@Test public void allCards() { Assert.assertEquals(this.jdkDeck.getCards(), this.vavrDeck.getCards().toJavaList()); }
|
VavrDeckOfCardsAsList { public List<Card> diamonds() { return null; } VavrDeckOfCardsAsList(); List<Card> shuffle(Random random); Tuple2<Set<Card>, ? extends List<Card>> deal(List<Card> stack, int count); List<Set<Card>> shuffleAndDeal(Random random, int hands, int cardsPerHand); List<Set<Card>> dealHands(
List<Card> shuffled,
int hands,
int cardsPerHand); List<Card> diamonds(); List<Card> hearts(); List<Card> spades(); List<Card> clubs(); Map<Suit, Long> countsBySuit(); Map<Rank, Long> countsByRank(); List<Card> getCards(); Map<Suit, ? extends List<Card>> getCardsBySuit(); }
|
@Test public void diamonds() { Assert.assertEquals(this.jdkDeck.diamonds(), this.vavrDeck.diamonds().toJavaList()); }
|
VavrDeckOfCardsAsList { public List<Card> hearts() { return null; } VavrDeckOfCardsAsList(); List<Card> shuffle(Random random); Tuple2<Set<Card>, ? extends List<Card>> deal(List<Card> stack, int count); List<Set<Card>> shuffleAndDeal(Random random, int hands, int cardsPerHand); List<Set<Card>> dealHands(
List<Card> shuffled,
int hands,
int cardsPerHand); List<Card> diamonds(); List<Card> hearts(); List<Card> spades(); List<Card> clubs(); Map<Suit, Long> countsBySuit(); Map<Rank, Long> countsByRank(); List<Card> getCards(); Map<Suit, ? extends List<Card>> getCardsBySuit(); }
|
@Test public void hearts() { Assert.assertEquals(this.jdkDeck.hearts(), this.vavrDeck.hearts().toJavaList()); }
|
VavrDeckOfCardsAsList { public List<Card> spades() { return null; } VavrDeckOfCardsAsList(); List<Card> shuffle(Random random); Tuple2<Set<Card>, ? extends List<Card>> deal(List<Card> stack, int count); List<Set<Card>> shuffleAndDeal(Random random, int hands, int cardsPerHand); List<Set<Card>> dealHands(
List<Card> shuffled,
int hands,
int cardsPerHand); List<Card> diamonds(); List<Card> hearts(); List<Card> spades(); List<Card> clubs(); Map<Suit, Long> countsBySuit(); Map<Rank, Long> countsByRank(); List<Card> getCards(); Map<Suit, ? extends List<Card>> getCardsBySuit(); }
|
@Test public void spades() { Assert.assertEquals(this.jdkDeck.spades(), this.vavrDeck.spades().toJavaList()); }
|
VavrDeckOfCardsAsList { public List<Card> clubs() { return null; } VavrDeckOfCardsAsList(); List<Card> shuffle(Random random); Tuple2<Set<Card>, ? extends List<Card>> deal(List<Card> stack, int count); List<Set<Card>> shuffleAndDeal(Random random, int hands, int cardsPerHand); List<Set<Card>> dealHands(
List<Card> shuffled,
int hands,
int cardsPerHand); List<Card> diamonds(); List<Card> hearts(); List<Card> spades(); List<Card> clubs(); Map<Suit, Long> countsBySuit(); Map<Rank, Long> countsByRank(); List<Card> getCards(); Map<Suit, ? extends List<Card>> getCardsBySuit(); }
|
@Test public void clubs() { Assert.assertEquals(this.jdkDeck.clubs(), this.vavrDeck.clubs().toJavaList()); }
|
EclipseCollectionsDeckOfCardsAsList { public MutableSet<Card> deal(MutableStack<Card> stack, int count) { return stack.pop(count).toSet(); } EclipseCollectionsDeckOfCardsAsList(); MutableStack<Card> shuffle(Random random); MutableSet<Card> deal(MutableStack<Card> stack, int count); ImmutableList<Set<Card>> shuffleAndDeal(Random random, int hands, int cardsPerHand); ImmutableList<Set<Card>> dealHands(
MutableStack<Card> shuffled,
int hands,
int cardsPerHand); ImmutableList<Card> diamonds(); ImmutableList<Card> hearts(); ImmutableList<Card> spades(); ImmutableList<Card> clubs(); Bag<Suit> countsBySuit(); Bag<Rank> countsByRank(); ImmutableList<Card> getCards(); ImmutableListMultimap<Suit, Card> getCardsBySuit(); }
|
@Test public void deal() { var ecShuffle = this.ecDeck.shuffle(new Random(1)); var jdkShuffle = this.jdkDeck.shuffle(new Random(1)); var ecHand = this.ecDeck.deal(ecShuffle, 5); var jdkHand = this.jdkDeck.deal(jdkShuffle, 5); Assert.assertEquals(jdkHand, ecHand); }
|
VavrDeckOfCardsAsList { public Tuple2<Set<Card>, ? extends List<Card>> deal(List<Card> stack, int count) { var hand = HashSet.<Card>empty(); for (int i = 0; i < count; i++) { var cardTuple2 = stack.pop2(); stack = cardTuple2._2(); hand = hand.add(cardTuple2._1()); } return Tuple.of(hand, stack); } VavrDeckOfCardsAsList(); List<Card> shuffle(Random random); Tuple2<Set<Card>, ? extends List<Card>> deal(List<Card> stack, int count); List<Set<Card>> shuffleAndDeal(Random random, int hands, int cardsPerHand); List<Set<Card>> dealHands(
List<Card> shuffled,
int hands,
int cardsPerHand); List<Card> diamonds(); List<Card> hearts(); List<Card> spades(); List<Card> clubs(); Map<Suit, Long> countsBySuit(); Map<Rank, Long> countsByRank(); List<Card> getCards(); Map<Suit, ? extends List<Card>> getCardsBySuit(); }
|
@Test public void deal() { var jdkShuffle = this.jdkDeck.shuffle(new Random(1)); var vavrShuffle = this.vavrDeck.shuffle(new Random(1)); var jdkHand = this.jdkDeck.deal(jdkShuffle, 5); var vavrHand = this.vavrDeck.deal(vavrShuffle, 5)._1().toJavaSet(); Assert.assertEquals(jdkHand, vavrHand); }
|
VavrDeckOfCardsAsList { public List<Set<Card>> shuffleAndDeal(Random random, int hands, int cardsPerHand) { var shuffled = this.shuffle(random); return this.dealHands(shuffled, hands, cardsPerHand); } VavrDeckOfCardsAsList(); List<Card> shuffle(Random random); Tuple2<Set<Card>, ? extends List<Card>> deal(List<Card> stack, int count); List<Set<Card>> shuffleAndDeal(Random random, int hands, int cardsPerHand); List<Set<Card>> dealHands(
List<Card> shuffled,
int hands,
int cardsPerHand); List<Card> diamonds(); List<Card> hearts(); List<Card> spades(); List<Card> clubs(); Map<Suit, Long> countsBySuit(); Map<Rank, Long> countsByRank(); List<Card> getCards(); Map<Suit, ? extends List<Card>> getCardsBySuit(); }
|
@Test public void shuffleAndDealHands() { var jdkHands = this.jdkDeck.shuffleAndDeal(new Random(1), 5, 5); var vavrHands = this.vavrDeck.shuffleAndDeal(new Random(1), 5, 5); Assert.assertEquals(jdkHands.get(0), vavrHands.get(0).toJavaSet()); Assert.assertEquals(jdkHands.get(1), vavrHands.get(1).toJavaSet()); Assert.assertEquals(jdkHands.get(2), vavrHands.get(2).toJavaSet()); Assert.assertEquals(jdkHands.get(3), vavrHands.get(3).toJavaSet()); Assert.assertEquals(jdkHands.get(4), vavrHands.get(4).toJavaSet()); }
|
VavrDeckOfCardsAsList { public List<Set<Card>> dealHands( List<Card> shuffled, int hands, int cardsPerHand) { return null; } VavrDeckOfCardsAsList(); List<Card> shuffle(Random random); Tuple2<Set<Card>, ? extends List<Card>> deal(List<Card> stack, int count); List<Set<Card>> shuffleAndDeal(Random random, int hands, int cardsPerHand); List<Set<Card>> dealHands(
List<Card> shuffled,
int hands,
int cardsPerHand); List<Card> diamonds(); List<Card> hearts(); List<Card> spades(); List<Card> clubs(); Map<Suit, Long> countsBySuit(); Map<Rank, Long> countsByRank(); List<Card> getCards(); Map<Suit, ? extends List<Card>> getCardsBySuit(); }
|
@Test public void dealHands() { var jdkShuffled = this.jdkDeck.shuffle(new Random(1)); var vavrShuffled = this.vavrDeck.shuffle(new Random(1)); var jdkHands = this.jdkDeck.dealHands(jdkShuffled, 5, 5); var vavrHands = this.vavrDeck.dealHands(vavrShuffled, 5, 5); Assert.assertEquals(jdkHands.get(0), vavrHands.get(0).toJavaSet()); Assert.assertEquals(jdkHands.get(1), vavrHands.get(1).toJavaSet()); Assert.assertEquals(jdkHands.get(2), vavrHands.get(2).toJavaSet()); Assert.assertEquals(jdkHands.get(3), vavrHands.get(3).toJavaSet()); Assert.assertEquals(jdkHands.get(4), vavrHands.get(4).toJavaSet()); }
|
VavrDeckOfCardsAsList { public Map<Suit, ? extends List<Card>> getCardsBySuit() { return this.cardsBySuit; } VavrDeckOfCardsAsList(); List<Card> shuffle(Random random); Tuple2<Set<Card>, ? extends List<Card>> deal(List<Card> stack, int count); List<Set<Card>> shuffleAndDeal(Random random, int hands, int cardsPerHand); List<Set<Card>> dealHands(
List<Card> shuffled,
int hands,
int cardsPerHand); List<Card> diamonds(); List<Card> hearts(); List<Card> spades(); List<Card> clubs(); Map<Suit, Long> countsBySuit(); Map<Rank, Long> countsByRank(); List<Card> getCards(); Map<Suit, ? extends List<Card>> getCardsBySuit(); }
|
@Test public void cardsBySuit() { var jdkCardsBySuit = this.jdkDeck.getCardsBySuit(); var vavrCardsBySuit = this.vavrDeck.getCardsBySuit(); Assert.assertEquals(jdkCardsBySuit.get(Suit.CLUBS), vavrCardsBySuit.get(Suit.CLUBS).get().toJavaList()); }
|
VavrDeckOfCardsAsList { public Map<Suit, Long> countsBySuit() { return null; } VavrDeckOfCardsAsList(); List<Card> shuffle(Random random); Tuple2<Set<Card>, ? extends List<Card>> deal(List<Card> stack, int count); List<Set<Card>> shuffleAndDeal(Random random, int hands, int cardsPerHand); List<Set<Card>> dealHands(
List<Card> shuffled,
int hands,
int cardsPerHand); List<Card> diamonds(); List<Card> hearts(); List<Card> spades(); List<Card> clubs(); Map<Suit, Long> countsBySuit(); Map<Rank, Long> countsByRank(); List<Card> getCards(); Map<Suit, ? extends List<Card>> getCardsBySuit(); }
|
@Test public void countsBySuit() { Assert.assertEquals( this.jdkDeck.countsBySuit().get(Suit.CLUBS), this.vavrDeck.countsBySuit().get(Suit.CLUBS).get()); }
|
VavrDeckOfCardsAsList { public Map<Rank, Long> countsByRank() { return null; } VavrDeckOfCardsAsList(); List<Card> shuffle(Random random); Tuple2<Set<Card>, ? extends List<Card>> deal(List<Card> stack, int count); List<Set<Card>> shuffleAndDeal(Random random, int hands, int cardsPerHand); List<Set<Card>> dealHands(
List<Card> shuffled,
int hands,
int cardsPerHand); List<Card> diamonds(); List<Card> hearts(); List<Card> spades(); List<Card> clubs(); Map<Suit, Long> countsBySuit(); Map<Rank, Long> countsByRank(); List<Card> getCards(); Map<Suit, ? extends List<Card>> getCardsBySuit(); }
|
@Test public void countsByRank() { Assert.assertEquals( this.jdkDeck.countsByRank().get(Rank.TEN), this.vavrDeck.countsByRank().get(Rank.TEN).get()); }
|
HashSetMultimap extends AbstractMutableMultimap<K, V, MutableSet<V>> implements MutableSetMultimap<K, V> { @Override public int size() { return this.size; } static HashSetMultimap<K, V> newMultimap(); @Override int size(); }
|
@Test public void get_put() { this.testObj.put("A", 1); Assert.assertEquals(MutableSet.of(1), this.testObj.get("A")); Assert.assertEquals(1, this.testObj.size()); this.testObj.put("A", 2); Assert.assertEquals(MutableSet.of(1, 2), this.testObj.get("A")); Assert.assertEquals(2, this.testObj.size()); this.testObj.put("A", 1); Assert.assertEquals(MutableSet.of(1, 2), this.testObj.get("A")); Assert.assertEquals(2, this.testObj.size()); this.testObj.put("B", 10); Assert.assertEquals(MutableSet.of(10), this.testObj.get("B")); Assert.assertEquals(3, this.testObj.size()); this.testObj.put("B", 11); Assert.assertEquals(MutableSet.of(10, 11), this.testObj.get("B")); Assert.assertEquals(4, this.testObj.size()); this.testObj.put("A", 2); Assert.assertEquals(MutableSet.of(1, 2), this.testObj.get("A")); Assert.assertEquals(4, this.testObj.size()); }
@Test public void get_putIterable() { this.testObj.put("A", MutableSet.of(1)); Assert.assertEquals(MutableSet.of(1), this.testObj.get("A")); Assert.assertEquals(1, this.testObj.size()); this.testObj.put("A", MutableSet.of(2, 1)); Assert.assertEquals(MutableSet.of(1, 2), this.testObj.get("A")); Assert.assertEquals(2, this.testObj.size()); this.testObj.put("B", MutableSet.of(10, 11)); Assert.assertEquals(MutableSet.of(10, 11), this.testObj.get("B")); Assert.assertEquals(4, this.testObj.size()); this.testObj.put("A", MutableSet.of(2, 3, 4)); Assert.assertEquals(MutableSet.of(1, 2, 3, 4), this.testObj.get("A")); Assert.assertEquals(6, this.testObj.size()); }
@Test public void putAll() { this.testObj.putAll(MutableMap.of("A", MutableList.of(1, 2, 3))); Assert.assertEquals(MutableSet.of(1, 2, 3), this.testObj.get("A")); Assert.assertEquals(3, this.testObj.size()); this.testObj.putAll(MutableMap.of("B", MutableList.of(10, 10))); Assert.assertEquals(MutableSet.of(10, 10), this.testObj.get("B")); Assert.assertEquals(4, this.testObj.size()); }
@Test public void remove() { Assert.assertEquals(MutableSet.empty(), this.testObj.remove("A")); this.testObj.putAll(MutableMap.of("A", MutableList.of(1, 2, 3))); this.testObj.putAll(MutableMap.of("B", MutableList.of(10, 10))); Assert.assertEquals(4, this.testObj.size()); this.testObj.remove("A"); Assert.assertEquals(1, this.testObj.size()); this.testObj.remove("B"); Assert.assertEquals(0, this.testObj.size()); }
@Test public void remove_keyValue() { Assert.assertEquals(MutableSet.empty(), this.testObj.remove("A")); this.testObj.putAll(MutableMap.of("A", MutableList.of(1, 2, 3, 1))); this.testObj.putAll(MutableMap.of("B", MutableList.of(10, 10))); Assert.assertEquals(4, this.testObj.size()); this.testObj.remove("A", 1); Assert.assertEquals(MutableSet.of(2, 3), this.testObj.get("A")); Assert.assertEquals(3, this.testObj.size()); this.testObj.remove("B", 10); MutableSet<Integer> getForB = this.testObj.get("B"); Assert.assertEquals(MutableSet.empty(), getForB); Assert.assertEquals(2, this.testObj.size()); Assert.assertNotSame(getForB, this.testObj.get("B")); }
@Test public void clear() { Assert.assertEquals(0, this.testObj.size()); this.testObj.clear(); this.testObj.putAll(MutableMap.of("A", MutableList.of(1, 2, 3, 1))); this.testObj.putAll(MutableMap.of("B", MutableList.of(10, 10))); Assert.assertEquals(4, this.testObj.size()); this.testObj.clear(); Assert.assertEquals(0, this.testObj.size()); }
|
EclipseCollectionsDeckOfCardsAsList { public ImmutableList<Set<Card>> shuffleAndDeal(Random random, int hands, int cardsPerHand) { var shuffled = this.shuffle(random); return this.dealHands(shuffled, hands, cardsPerHand); } EclipseCollectionsDeckOfCardsAsList(); MutableStack<Card> shuffle(Random random); MutableSet<Card> deal(MutableStack<Card> stack, int count); ImmutableList<Set<Card>> shuffleAndDeal(Random random, int hands, int cardsPerHand); ImmutableList<Set<Card>> dealHands(
MutableStack<Card> shuffled,
int hands,
int cardsPerHand); ImmutableList<Card> diamonds(); ImmutableList<Card> hearts(); ImmutableList<Card> spades(); ImmutableList<Card> clubs(); Bag<Suit> countsBySuit(); Bag<Rank> countsByRank(); ImmutableList<Card> getCards(); ImmutableListMultimap<Suit, Card> getCardsBySuit(); }
|
@Test public void shuffleAndDealHands() { var ecHands = this.ecDeck.shuffleAndDeal(new Random(1), 5, 5); var jdkHands = this.jdkDeck.shuffleAndDeal(new Random(1), 5, 5); Assert.assertEquals(jdkHands, ecHands); }
|
HashSetMultimap extends AbstractMutableMultimap<K, V, MutableSet<V>> implements MutableSetMultimap<K, V> { public static <K, V> HashSetMultimap<K, V> newMultimap() { return new HashSetMultimap<>(); } static HashSetMultimap<K, V> newMultimap(); @Override int size(); }
|
@Test public void hashCodeEquals() { this.testObj.putAll(MutableMap.of("A", MutableList.of(1, 2, 3, 1))); this.testObj.putAll(MutableMap.of("B", MutableList.of(10, 10))); HashSetMultimap<String, Integer> other = HashSetMultimap.newMultimap(); other.putAll(MutableMap.of("A", MutableList.of(1, 2, 3, 1))); Assert.assertTrue(this.testObj.equals(this.testObj)); Assert.assertFalse(this.testObj.equals(other)); Assert.assertFalse(other.equals(this.testObj)); other.putAll(MutableMap.of("B", MutableList.of(10, 10))); Verify.assertEqualsAndHashCode(this.testObj, this.testObj); Verify.assertEqualsAndHashCode(this.testObj, other); Verify.assertEqualsAndHashCode(other, this.testObj); }
|
CustomCollectionsDeckOfCardsAsList { public MutableList<Card> getCards() { return this.cards; } CustomCollectionsDeckOfCardsAsList(); Deque<Card> shuffle(Random random); MutableSet<Card> deal(Deque<Card> deque, int count); MutableList<MutableSet<Card>> shuffleAndDeal(Random random, int hands, int cardsPerHand); MutableList<MutableSet<Card>> dealHands(Deque<Card> shuffled, int hands, int cardsPerHand); MutableList<Card> diamonds(); MutableList<Card> hearts(); MutableList<Card> spades(); MutableList<Card> clubs(); MutableBag<Suit> countsBySuit(); MutableBag<Rank> countsByRank(); MutableList<Card> getCards(); MutableListMultimap<Suit, Card> getCardsBySuit(); }
|
@Test public void allCards() { Assert.assertEquals(this.jdkDeck.getCards(), this.customDeck.getCards()); }
@Test public void cardsAreImmutable() { var jdk2Cards = this.customDeck.getCards(); Verify.assertThrows( UnsupportedOperationException.class, () -> jdk2Cards.remove(0)); Verify.assertThrows( UnsupportedOperationException.class, jdk2Cards::clear); Verify.assertThrows( UnsupportedOperationException.class, () -> jdk2Cards.add(null)); }
|
CustomCollectionsDeckOfCardsAsList { public MutableList<Card> diamonds() { return this.cardsBySuit.get(Suit.DIAMONDS); } CustomCollectionsDeckOfCardsAsList(); Deque<Card> shuffle(Random random); MutableSet<Card> deal(Deque<Card> deque, int count); MutableList<MutableSet<Card>> shuffleAndDeal(Random random, int hands, int cardsPerHand); MutableList<MutableSet<Card>> dealHands(Deque<Card> shuffled, int hands, int cardsPerHand); MutableList<Card> diamonds(); MutableList<Card> hearts(); MutableList<Card> spades(); MutableList<Card> clubs(); MutableBag<Suit> countsBySuit(); MutableBag<Rank> countsByRank(); MutableList<Card> getCards(); MutableListMultimap<Suit, Card> getCardsBySuit(); }
|
@Test public void diamonds() { Assert.assertEquals(this.jdkDeck.diamonds(), this.customDeck.diamonds()); }
|
CustomCollectionsDeckOfCardsAsList { public MutableList<Card> hearts() { return this.cardsBySuit.get(Suit.HEARTS); } CustomCollectionsDeckOfCardsAsList(); Deque<Card> shuffle(Random random); MutableSet<Card> deal(Deque<Card> deque, int count); MutableList<MutableSet<Card>> shuffleAndDeal(Random random, int hands, int cardsPerHand); MutableList<MutableSet<Card>> dealHands(Deque<Card> shuffled, int hands, int cardsPerHand); MutableList<Card> diamonds(); MutableList<Card> hearts(); MutableList<Card> spades(); MutableList<Card> clubs(); MutableBag<Suit> countsBySuit(); MutableBag<Rank> countsByRank(); MutableList<Card> getCards(); MutableListMultimap<Suit, Card> getCardsBySuit(); }
|
@Test public void hearts() { Assert.assertEquals(this.jdkDeck.hearts(), this.customDeck.hearts()); }
|
CustomCollectionsDeckOfCardsAsList { public MutableList<Card> spades() { return this.cardsBySuit.get(Suit.SPADES); } CustomCollectionsDeckOfCardsAsList(); Deque<Card> shuffle(Random random); MutableSet<Card> deal(Deque<Card> deque, int count); MutableList<MutableSet<Card>> shuffleAndDeal(Random random, int hands, int cardsPerHand); MutableList<MutableSet<Card>> dealHands(Deque<Card> shuffled, int hands, int cardsPerHand); MutableList<Card> diamonds(); MutableList<Card> hearts(); MutableList<Card> spades(); MutableList<Card> clubs(); MutableBag<Suit> countsBySuit(); MutableBag<Rank> countsByRank(); MutableList<Card> getCards(); MutableListMultimap<Suit, Card> getCardsBySuit(); }
|
@Test public void spades() { Assert.assertEquals(this.jdkDeck.spades(), this.customDeck.spades()); }
|
CustomCollectionsDeckOfCardsAsList { public MutableList<Card> clubs() { return this.cardsBySuit.get(Suit.CLUBS); } CustomCollectionsDeckOfCardsAsList(); Deque<Card> shuffle(Random random); MutableSet<Card> deal(Deque<Card> deque, int count); MutableList<MutableSet<Card>> shuffleAndDeal(Random random, int hands, int cardsPerHand); MutableList<MutableSet<Card>> dealHands(Deque<Card> shuffled, int hands, int cardsPerHand); MutableList<Card> diamonds(); MutableList<Card> hearts(); MutableList<Card> spades(); MutableList<Card> clubs(); MutableBag<Suit> countsBySuit(); MutableBag<Rank> countsByRank(); MutableList<Card> getCards(); MutableListMultimap<Suit, Card> getCardsBySuit(); }
|
@Test public void clubs() { Assert.assertEquals(this.jdkDeck.clubs(), this.customDeck.clubs()); }
|
CustomCollectionsDeckOfCardsAsList { public MutableSet<Card> deal(Deque<Card> deque, int count) { var hand = MutableSet.<Card>empty(); IntStream.range(0, count).forEach(i -> hand.add(deque.pop())); return hand; } CustomCollectionsDeckOfCardsAsList(); Deque<Card> shuffle(Random random); MutableSet<Card> deal(Deque<Card> deque, int count); MutableList<MutableSet<Card>> shuffleAndDeal(Random random, int hands, int cardsPerHand); MutableList<MutableSet<Card>> dealHands(Deque<Card> shuffled, int hands, int cardsPerHand); MutableList<Card> diamonds(); MutableList<Card> hearts(); MutableList<Card> spades(); MutableList<Card> clubs(); MutableBag<Suit> countsBySuit(); MutableBag<Rank> countsByRank(); MutableList<Card> getCards(); MutableListMultimap<Suit, Card> getCardsBySuit(); }
|
@Test public void deal() { var jdk1Shuffle = this.jdkDeck.shuffle(new Random(1)); var jdk2Shuffle = this.customDeck.shuffle(new Random(1)); var jdk1Hand = this.jdkDeck.deal(jdk1Shuffle, 5); var jdk2Hand = this.customDeck.deal(jdk2Shuffle, 5); Assert.assertEquals(jdk1Hand, jdk2Hand); }
|
EclipseCollectionsDeckOfCardsAsList { public ImmutableList<Set<Card>> dealHands( MutableStack<Card> shuffled, int hands, int cardsPerHand) { return null; } EclipseCollectionsDeckOfCardsAsList(); MutableStack<Card> shuffle(Random random); MutableSet<Card> deal(MutableStack<Card> stack, int count); ImmutableList<Set<Card>> shuffleAndDeal(Random random, int hands, int cardsPerHand); ImmutableList<Set<Card>> dealHands(
MutableStack<Card> shuffled,
int hands,
int cardsPerHand); ImmutableList<Card> diamonds(); ImmutableList<Card> hearts(); ImmutableList<Card> spades(); ImmutableList<Card> clubs(); Bag<Suit> countsBySuit(); Bag<Rank> countsByRank(); ImmutableList<Card> getCards(); ImmutableListMultimap<Suit, Card> getCardsBySuit(); }
|
@Test public void dealHands() { var ecShuffled = this.ecDeck.shuffle(new Random(1)); var jdkShuffled = this.jdkDeck.shuffle(new Random(1)); var ecHands = this.ecDeck.dealHands(ecShuffled, 5, 5); var jdkHands = this.jdkDeck.dealHands(jdkShuffled, 5, 5); Assert.assertEquals(jdkHands, ecHands); }
|
CustomCollectionsDeckOfCardsAsList { public MutableList<MutableSet<Card>> shuffleAndDeal(Random random, int hands, int cardsPerHand) { var shuffled = this.shuffle(random); return this.dealHands(shuffled, hands, cardsPerHand); } CustomCollectionsDeckOfCardsAsList(); Deque<Card> shuffle(Random random); MutableSet<Card> deal(Deque<Card> deque, int count); MutableList<MutableSet<Card>> shuffleAndDeal(Random random, int hands, int cardsPerHand); MutableList<MutableSet<Card>> dealHands(Deque<Card> shuffled, int hands, int cardsPerHand); MutableList<Card> diamonds(); MutableList<Card> hearts(); MutableList<Card> spades(); MutableList<Card> clubs(); MutableBag<Suit> countsBySuit(); MutableBag<Rank> countsByRank(); MutableList<Card> getCards(); MutableListMultimap<Suit, Card> getCardsBySuit(); }
|
@Test public void shuffleAndDealHands() { var jdk1Hands = this.jdkDeck.shuffleAndDeal(new Random(1), 5, 5); var jdk2Hands = this.customDeck.shuffleAndDeal(new Random(1), 5, 5); Assert.assertEquals(jdk1Hands, jdk2Hands); }
|
CustomCollectionsDeckOfCardsAsList { public MutableList<MutableSet<Card>> dealHands(Deque<Card> shuffled, int hands, int cardsPerHand) { return MutableList.fromStream(IntStream.range(0, hands) .mapToObj(each -> this.deal(shuffled, cardsPerHand))) .asUnmodifiable(); } CustomCollectionsDeckOfCardsAsList(); Deque<Card> shuffle(Random random); MutableSet<Card> deal(Deque<Card> deque, int count); MutableList<MutableSet<Card>> shuffleAndDeal(Random random, int hands, int cardsPerHand); MutableList<MutableSet<Card>> dealHands(Deque<Card> shuffled, int hands, int cardsPerHand); MutableList<Card> diamonds(); MutableList<Card> hearts(); MutableList<Card> spades(); MutableList<Card> clubs(); MutableBag<Suit> countsBySuit(); MutableBag<Rank> countsByRank(); MutableList<Card> getCards(); MutableListMultimap<Suit, Card> getCardsBySuit(); }
|
@Test public void dealHands() { var jdk1Shuffled = this.jdkDeck.shuffle(new Random(1)); var jdk2Shuffled = this.customDeck.shuffle(new Random(1)); var jdk1Hands = this.jdkDeck.dealHands(jdk1Shuffled, 5, 5); var jdk2Hands = this.customDeck.dealHands(jdk2Shuffled, 5, 5); Assert.assertEquals(jdk1Hands, jdk2Hands); }
|
CustomCollectionsDeckOfCardsAsList { public MutableListMultimap<Suit, Card> getCardsBySuit() { return this.cardsBySuit; } CustomCollectionsDeckOfCardsAsList(); Deque<Card> shuffle(Random random); MutableSet<Card> deal(Deque<Card> deque, int count); MutableList<MutableSet<Card>> shuffleAndDeal(Random random, int hands, int cardsPerHand); MutableList<MutableSet<Card>> dealHands(Deque<Card> shuffled, int hands, int cardsPerHand); MutableList<Card> diamonds(); MutableList<Card> hearts(); MutableList<Card> spades(); MutableList<Card> clubs(); MutableBag<Suit> countsBySuit(); MutableBag<Rank> countsByRank(); MutableList<Card> getCards(); MutableListMultimap<Suit, Card> getCardsBySuit(); }
|
@Test public void cardsBySuit() { var jdk1CardsBySuit = this.jdkDeck.getCardsBySuit(); var jdk2CardsBySuit = this.customDeck.getCardsBySuit(); Assert.assertEquals(jdk1CardsBySuit.get(Suit.CLUBS), jdk2CardsBySuit.get(Suit.CLUBS)); }
@Test public void cardsBySuitIsImmutable() { var jdk2CardsBySuit = this.customDeck.getCardsBySuit(); Verify.assertThrows( UnsupportedOperationException.class, () -> jdk2CardsBySuit.remove(Suit.CLUBS)); Verify.assertThrows( UnsupportedOperationException.class, jdk2CardsBySuit::clear); Verify.assertThrows( UnsupportedOperationException.class, () -> jdk2CardsBySuit.get(Suit.CLUBS).remove(0)); Verify.assertThrows( UnsupportedOperationException.class, () -> jdk2CardsBySuit.get(Suit.CLUBS).add(null)); Verify.assertThrows( UnsupportedOperationException.class, jdk2CardsBySuit.get(Suit.CLUBS)::clear); }
|
CustomCollectionsDeckOfCardsAsList { public MutableBag<Suit> countsBySuit() { return this.cards.countBy(Card::suit); } CustomCollectionsDeckOfCardsAsList(); Deque<Card> shuffle(Random random); MutableSet<Card> deal(Deque<Card> deque, int count); MutableList<MutableSet<Card>> shuffleAndDeal(Random random, int hands, int cardsPerHand); MutableList<MutableSet<Card>> dealHands(Deque<Card> shuffled, int hands, int cardsPerHand); MutableList<Card> diamonds(); MutableList<Card> hearts(); MutableList<Card> spades(); MutableList<Card> clubs(); MutableBag<Suit> countsBySuit(); MutableBag<Rank> countsByRank(); MutableList<Card> getCards(); MutableListMultimap<Suit, Card> getCardsBySuit(); }
|
@Test public void countsBySuit() { for (Suit suit : Suit.values()) { Assert.assertEquals( this.jdkDeck.countsBySuit().get(suit).intValue(), this.customDeck.countsBySuit().getOccurrences(suit)); } }
|
CustomCollectionsDeckOfCardsAsList { public MutableBag<Rank> countsByRank() { return this.cards.countBy(Card::rank); } CustomCollectionsDeckOfCardsAsList(); Deque<Card> shuffle(Random random); MutableSet<Card> deal(Deque<Card> deque, int count); MutableList<MutableSet<Card>> shuffleAndDeal(Random random, int hands, int cardsPerHand); MutableList<MutableSet<Card>> dealHands(Deque<Card> shuffled, int hands, int cardsPerHand); MutableList<Card> diamonds(); MutableList<Card> hearts(); MutableList<Card> spades(); MutableList<Card> clubs(); MutableBag<Suit> countsBySuit(); MutableBag<Rank> countsByRank(); MutableList<Card> getCards(); MutableListMultimap<Suit, Card> getCardsBySuit(); }
|
@Test public void countsByRank() { for (Rank rank : Rank.values()) { Assert.assertEquals( this.jdkDeck.countsByRank().get(rank).intValue(), this.customDeck.countsByRank().getOccurrences(rank)); } }
|
HashBag implements MutableBag<T> { HashBag<T> withAll(T... elements) { for (T element : elements) { this.backingMap.merge(element, 1, (existingValue, newValue) -> existingValue + 1); this.size++; } return this; } @Override int sizeDistinct(); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Object[] toArray(); void forEachWithIndex(BiConsumer<? super T, Integer> biConsumer); @Override T1[] toArray(T1[] array); @Override boolean add(T element); @Override boolean remove(Object o); @Override boolean containsAll(Collection<?> c); @Override boolean addAll(Collection<? extends T> c); @Override boolean removeAll(Collection<?> c); @Override boolean retainAll(Collection<?> c); @Override void clear(); @Override Iterator<T> iterator(); @Override int getOccurrences(T element); @Override boolean addOccurrence(T element); @Override boolean addOccurrences(T element, int occurrences); @Override boolean removeOccurrence(T element); @Override boolean removeOccurrences(T element, int occurrences); @Override void forEachWithOccurrences(BiConsumer<? super T, Integer> biConsumer); @Override void forEach(Consumer<? super T> consumer); @Override int hashCode(); @Override boolean equals(Object other); }
|
@Test public void withAll() { HashBag<String> bag = this.testObj.withAll("1", "2", "3", "2", "3", "3"); Assert.assertEquals(1, bag.getOccurrences("1")); Assert.assertEquals(2, bag.getOccurrences("2")); Assert.assertEquals(3, bag.getOccurrences("3")); }
|
HashBag implements MutableBag<T> { @Override public boolean isEmpty() { return this.size == 0; } @Override int sizeDistinct(); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Object[] toArray(); void forEachWithIndex(BiConsumer<? super T, Integer> biConsumer); @Override T1[] toArray(T1[] array); @Override boolean add(T element); @Override boolean remove(Object o); @Override boolean containsAll(Collection<?> c); @Override boolean addAll(Collection<? extends T> c); @Override boolean removeAll(Collection<?> c); @Override boolean retainAll(Collection<?> c); @Override void clear(); @Override Iterator<T> iterator(); @Override int getOccurrences(T element); @Override boolean addOccurrence(T element); @Override boolean addOccurrences(T element, int occurrences); @Override boolean removeOccurrence(T element); @Override boolean removeOccurrences(T element, int occurrences); @Override void forEachWithOccurrences(BiConsumer<? super T, Integer> biConsumer); @Override void forEach(Consumer<? super T> consumer); @Override int hashCode(); @Override boolean equals(Object other); }
|
@Test public void isEmpty() { Assert.assertTrue(this.testObj.isEmpty()); this.testObj.withAll("1", "2", "3", "2", "3", "3"); Assert.assertFalse(this.testObj.isEmpty()); }
|
HashBag implements MutableBag<T> { @Override public boolean contains(Object o) { return this.backingMap.containsKey(o); } @Override int sizeDistinct(); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Object[] toArray(); void forEachWithIndex(BiConsumer<? super T, Integer> biConsumer); @Override T1[] toArray(T1[] array); @Override boolean add(T element); @Override boolean remove(Object o); @Override boolean containsAll(Collection<?> c); @Override boolean addAll(Collection<? extends T> c); @Override boolean removeAll(Collection<?> c); @Override boolean retainAll(Collection<?> c); @Override void clear(); @Override Iterator<T> iterator(); @Override int getOccurrences(T element); @Override boolean addOccurrence(T element); @Override boolean addOccurrences(T element, int occurrences); @Override boolean removeOccurrence(T element); @Override boolean removeOccurrences(T element, int occurrences); @Override void forEachWithOccurrences(BiConsumer<? super T, Integer> biConsumer); @Override void forEach(Consumer<? super T> consumer); @Override int hashCode(); @Override boolean equals(Object other); }
|
@Test public void contains() { Assert.assertFalse(this.testObj.contains("1")); this.testObj.withAll("1", "2", "3", "2", "3", "3"); Assert.assertTrue(this.testObj.contains("1")); Assert.assertFalse(this.testObj.contains("4")); }
|
HashBag implements MutableBag<T> { @Override public Object[] toArray() { Object[] result = new Object[this.size()]; this.forEachWithIndex((each, index) -> result[index] = each); return result; } @Override int sizeDistinct(); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Object[] toArray(); void forEachWithIndex(BiConsumer<? super T, Integer> biConsumer); @Override T1[] toArray(T1[] array); @Override boolean add(T element); @Override boolean remove(Object o); @Override boolean containsAll(Collection<?> c); @Override boolean addAll(Collection<? extends T> c); @Override boolean removeAll(Collection<?> c); @Override boolean retainAll(Collection<?> c); @Override void clear(); @Override Iterator<T> iterator(); @Override int getOccurrences(T element); @Override boolean addOccurrence(T element); @Override boolean addOccurrences(T element, int occurrences); @Override boolean removeOccurrence(T element); @Override boolean removeOccurrences(T element, int occurrences); @Override void forEachWithOccurrences(BiConsumer<? super T, Integer> biConsumer); @Override void forEach(Consumer<? super T> consumer); @Override int hashCode(); @Override boolean equals(Object other); }
|
@Test public void toArray() { Assert.assertArrayEquals(new String[]{}, this.testObj.toArray()); this.testObj.withAll("1", "2", "3", "2", "3", "3"); Assert.assertArrayEquals(new String[]{"1", "2", "2", "3", "3", "3"}, this.testObj.toArray()); }
|
AuthenticationController { @DELETE @Path("{userName}") @Consumes(MediaType.APPLICATION_JSON + ";charset=UTF-8") @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") public Response<AccountEntry> deleteAccount(Request<AccountEntry> request, @PathParam("userName") String userName) { Data<AccountEntry> data, returnData; boolean deleted = false; try { userName = validateUsername(userName); RequestValidator.validateRequest(request); data = request.getMessage().getData(); Collection<AccountEntry> accounts = data.getEntries(); if (accounts.size() != 1) { return Response.badRequest("Number of entries must be 1.", null); } deleted = userManager.disable(userName); } catch (AccessDeniedException ex) { return Response.badRequest(ex.getMessage(), ex); } catch (IllegalArgumentException e) { return Response.badRequest(e.getMessage(), e); } catch (Exception e) { return Response.serverError(e.getMessage(), e); } if (deleted) { return Response.ok(); } else { return Response.serverError("could not delete account.", null); } } void setUserManager(UserManager userManager); void setAccessControlManager(AccessControlManager accessControlManager); @GET @Path("{userName}") @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") Response<AccountEntry> getUser(
@PathParam("userName") String userName); @POST @Path("{userName}")// can be @me - then updating the current user @Consumes(MediaType.APPLICATION_JSON + ";charset=UTF-8") @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") Response<AccountEntry> updateUser(
@PathParam("said") String said,
@PathParam("userName") String userName,
Request<AccountEntry> request); @DELETE @Path("{userName}") @Consumes(MediaType.APPLICATION_JSON + ";charset=UTF-8") @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") Response<AccountEntry> deleteAccount(Request<AccountEntry> request,
@PathParam("userName") String userName); @GET @Path("/username") String getCurrentUserName(); @GET @Path("/role") String getCurrentRole(); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/credentials/{contact-said}") Response<AccountEntry> getCredentials(
@PathParam("said") String saidLocal,
@PathParam("contact-said") String saidRequester); @POST @Produces(MediaType.APPLICATION_JSON) @Path("/credentials/{contact-said}") Response<?> confirmCredentials(
@PathParam("said") String saidLocal,
@PathParam("contact-said") String saidRequester); }
|
@Test public void testDeleteAccount() { }
|
DimeServiceAdapter extends ServiceAdapterBase implements InternalServiceAdapter { @Override public String getAdapterName() { return DimeServiceAdapter.NAME; } DimeServiceAdapter(String identifier); void setProxyFactory(ProxyFactory proxyFactory); void setAccountRegistrar(AccountRegistrar accountRegistrar); void setPublicResolverService(HttpRestProxy publicResolverService); void setCredentialStore(CredentialStore credentialStore); void setPolicyManager(PolicyManager policyManager); @Override String getAdapterName(); Collection<T> get(String receiverSAID, String senderSAID,
String attribute, Class<T> returnType, Tenant tenant); BinaryFile getBinary(String receiverSAID, String senderSAID,
String resourceId, Tenant tenant); @Override void _set(String attribute, Object value); @Override Collection<T> search(String attribute,
Resource values, Class<T> returnType); @Override Collection<T> search(Resource values,
Class<T> returnType); PersonContact getProfile(String targetSaidName, Token token); Token getUserToken(String username, Tenant tenant); boolean confirmToken(Token token, Tenant tenant); @Override Boolean isConnected(); ServiceResponse[] getRaw(String attribute); @Override Collection<T> get(String attribute, Class<T> returnType); @Override void response(String attribute, Resource value); @Override void delete(String attribute); static final String NAME; }
|
@Test public void testGetAdapterName() throws Exception { DimeServiceAdapter adapter = new DimeServiceAdapter("test"); assertEquals("di.me", adapter.getAdapterName()); }
|
DimeServiceAdapter extends ServiceAdapterBase implements InternalServiceAdapter { public PersonContact getProfile(String targetSaidName, Token token) throws AttributeNotSupportedException, ServiceNotAvailableException { HttpRestProxy proxy = null; PersonContact profile = null; final String path = SHARED_PROFILE_PATH.replace(":target", targetSaidName); try { URL baseURL = accountRegistrar.resolve(targetSaidName); proxy = proxyFactory.createProxy(baseURL, token.getToken(), token.getSecret()); Map<String, String> headers = headers( "Accept", MediaType.APPLICATION_JSONLD); String response = proxy.get(path, headers); logger.info("GET "+path+" [username="+token.getToken()+", password="+token.getSecret()+"] responded with: "+response); profile = JSONLDUtils.deserialize(response, PersonContact.class); if (logger.isDebugEnabled()) { logger.debug("Profile metadata for "+path+" response is:\n"+profile.getModel().serialize(Syntax.Turtle)); } } catch (AccountCannotResolveException e) { throw new ServiceNotAvailableException("said not registered at dns: " + targetSaidName, e); } catch (JsonParseException e) { throw new ServiceNotAvailableException( "Could not process response from "+path+", invalid JSON returned: "+e.getMessage(), "SERV-100"); } catch (JsonMappingException e) { throw new ServiceNotAvailableException( "Could not process response, invalid JSON returned: "+e.getMessage(), "SERV-100"); } catch (Exception e) { throw new ServiceNotAvailableException("Unknown error occurred: "+e.getMessage(), e); } finally { if (proxy != null) { proxy.close(); } } return profile; } DimeServiceAdapter(String identifier); void setProxyFactory(ProxyFactory proxyFactory); void setAccountRegistrar(AccountRegistrar accountRegistrar); void setPublicResolverService(HttpRestProxy publicResolverService); void setCredentialStore(CredentialStore credentialStore); void setPolicyManager(PolicyManager policyManager); @Override String getAdapterName(); Collection<T> get(String receiverSAID, String senderSAID,
String attribute, Class<T> returnType, Tenant tenant); BinaryFile getBinary(String receiverSAID, String senderSAID,
String resourceId, Tenant tenant); @Override void _set(String attribute, Object value); @Override Collection<T> search(String attribute,
Resource values, Class<T> returnType); @Override Collection<T> search(Resource values,
Class<T> returnType); PersonContact getProfile(String targetSaidName, Token token); Token getUserToken(String username, Tenant tenant); boolean confirmToken(Token token, Tenant tenant); @Override Boolean isConnected(); ServiceResponse[] getRaw(String attribute); @Override Collection<T> get(String attribute, Class<T> returnType); @Override void response(String attribute, Resource value); @Override void delete(String attribute); static final String NAME; }
|
@Test public void testGetProfile() throws Exception { String said = "12345"; URL baseUrl = new URL("http: String path = "/api/dime/rest/:target/shared/profile".replace(":target", said); String json = "[{`@context`:{`nco`:`http: URI profileUri = new URIImpl("urn:uuid:3dcb73e4-399f-41af-b4f2-a8bb48c315a1"); URI phoneUri = new URIImpl("urn:uuid:e9e07fd8-f53f-453b-b2dc-307e04c4fb61"); URI nameUri = new URIImpl("urn:uuid:18e938b1-935d-4cb4-b763-3ca1d654305f"); AccountRegistrar mockRegistrar = Mockito.mock(AccountRegistrar.class); Mockito.when(mockRegistrar.resolve(said)).thenReturn(baseUrl); HttpRestProxy mockProxy = Mockito.mock(HttpRestProxy.class); Mockito.when(mockProxy.get(Mockito.eq(path), Mockito.anyMap())).thenReturn(json); ProxyFactory mockFactory = Mockito.mock(ProxyFactory.class); Mockito.when(mockFactory.createProxy(Mockito.eq(baseUrl), Mockito.anyString(), Mockito.anyString())).thenReturn(mockProxy); DimeServiceAdapter adapter = new DimeServiceAdapter("1"); adapter.setProxyFactory(mockFactory); adapter.setAccountRegistrar(mockRegistrar); PersonContact profile = adapter.getProfile(said, new Token("token", "secret")); Model metadata = profile.getModel(); assertEquals(profileUri, profile.asURI()); assertTrue(metadata.contains(profileUri, NCO.hasPersonName, nameUri)); assertTrue(metadata.contains(profileUri, NCO.hasPhoneNumber, phoneUri)); assertTrue(metadata.contains(nameUri, RDF.type, NCO.PersonName)); assertEquals("Ismael Rivera", ModelUtils.findObject(metadata, nameUri, NCO.fullname).asLiteral().getValue()); assertEquals("Ismael", ModelUtils.findObject(metadata, nameUri, NCO.nameGiven).asLiteral().getValue()); assertEquals("Rivera", ModelUtils.findObject(metadata, nameUri, NCO.nameFamily).asLiteral().getValue()); assertTrue(metadata.contains(phoneUri, RDF.type, NCO.PhoneNumber)); assertEquals("555-55-55", ModelUtils.findObject(metadata, phoneUri, NCO.phoneNumber).asLiteral().getValue()); }
|
AttributeMap { public String getAttribute (String input) { Iterator<String> iterator = this.attributes.iterator(); while (iterator.hasNext()) { String candidate = iterator.next(); String attr = candidate.replaceAll("\\{\\w+\\}", "([^/]+)"); if (input.matches(attr)) { return candidate; } } return null; } AttributeMap(); String getAttribute(String input); Map<String, String> extractIds(String attribute, String input); static final String EVENT_ID; static final String USER_ID; static final String EVENT_ALL; static final String EVENT_ALLMINE; static final String EVENT_DETAILS; static final String EVENT_ATTENDEES; static final String EVENT_ATTENDEEDETAILS; static final String PROFILE_ME; static final String PROFILE_MYDETAILS; static final String PROFILE_DETAILS; static final String PROFILEATTRIBUTE_MYDETAILS; static final String PROFILEATTRIBUTE_DETAILS; static final String FRIEND_ALL; static final String FRIEND_DETAILS; static final String GROUP_ALL; static final String LIVEPOST_ALL; static final String LIVEPOST_ALLMINE; static final String LIVEPOST_ALLUSER; static final String NOTIFICATION; static final String PLACE_ALL; static final String ACTIVITY_ALL; static final String ACTIVITY_DETAILS; }
|
@Test public void testGetAttribute() { AttributeMap attributeMap = new AttributeMap(); assertTrue("Wrong mapping found for getAttribute(/event/@all).", attributeMap.getAttribute("/event/@all").equals(AttributeMap.EVENT_ALL)); assertTrue("Wrong mapping found for getAttribute(/event/@me/123).", attributeMap.getAttribute("/event/@me/123").equals(AttributeMap.EVENT_DETAILS)); }
|
AttributeMap { public Map<String, String> extractIds (String attribute, String input) { HashMap<String, String> idMap = new HashMap<String, String>(); Iterator<String> iterator = this.idnames.iterator(); while (iterator.hasNext()) { String candidate = iterator.next(); String attr = attribute.replaceAll("\\{"+candidate+"\\}", "([^/]+)").replaceAll("\\{\\w+\\}", "[^/]+"); Pattern pattern = Pattern.compile(attr); Matcher matcher = pattern.matcher(input); if (matcher.find() && matcher.groupCount() >= 1) { idMap.put(candidate, matcher.group(1)); } } return idMap; } AttributeMap(); String getAttribute(String input); Map<String, String> extractIds(String attribute, String input); static final String EVENT_ID; static final String USER_ID; static final String EVENT_ALL; static final String EVENT_ALLMINE; static final String EVENT_DETAILS; static final String EVENT_ATTENDEES; static final String EVENT_ATTENDEEDETAILS; static final String PROFILE_ME; static final String PROFILE_MYDETAILS; static final String PROFILE_DETAILS; static final String PROFILEATTRIBUTE_MYDETAILS; static final String PROFILEATTRIBUTE_DETAILS; static final String FRIEND_ALL; static final String FRIEND_DETAILS; static final String GROUP_ALL; static final String LIVEPOST_ALL; static final String LIVEPOST_ALLMINE; static final String LIVEPOST_ALLUSER; static final String NOTIFICATION; static final String PLACE_ALL; static final String ACTIVITY_ALL; static final String ACTIVITY_DETAILS; }
|
@Test public void testExtractIds() { AttributeMap attributeMap = new AttributeMap(); Map<String, String> details = attributeMap.extractIds(AttributeMap.EVENT_ALL, "/event/@all"); assertTrue("Wrong eventId detected for /event/@all", details.get(AttributeMap.EVENT_ID) == null); assertTrue("Wrong userId detected for /event/@all", details.get(AttributeMap.USER_ID) == null); details = attributeMap.extractIds(AttributeMap.EVENT_DETAILS, "/event/@me/123"); assertTrue("Wrong eventId detected for /event/@me/123", details.get(AttributeMap.EVENT_ID).equals("123")); assertTrue("Wrong userId detected for /event/@me/123", details.get(AttributeMap.USER_ID) == null); details = attributeMap.extractIds(AttributeMap.EVENT_ATTENDEEDETAILS, "/event/@me/123/456"); assertTrue("Wrong eventId detected for /event/@me/123/456", details.get(AttributeMap.EVENT_ID).equals("123")); assertTrue("Wrong userId detected for /event/@me/123/456", details.get(AttributeMap.USER_ID).equals("456")); }
|
HistoryLogService { public URI createLogForContext(URI contextGraph) { TripleStore tripleStore = resourceStore.getTripleStore(); URI logGraph = resourceStore.createGraph(DUHO.ContextLog); URI metadataGraph = tripleStore.getOrCreateMetadataGraph(logGraph); Model metadata = RDF2Go.getModelFactory().createModel().open(); metadata.addAll(tripleStore.getModel(contextGraph).iterator()); metadata.removeStatements(Variable.ANY, NAO.hasDataGraph, Variable.ANY); metadata.removeStatements(Variable.ANY, NAO.isDataGraphFor, Variable.ANY); tripleStore.addAll(logGraph, metadata.iterator()); tripleStore.addStatement(metadataGraph, logGraph, DUHO.timestamp, DateUtil.currentDateTimeAsLiteral()); broadcastManager.sendBroadcast(new Event(resourceStore.getName(), Event.ACTION_GRAPH_ADD, logGraph)); return logGraph; } HistoryLogService(ResourceStore resourceStore); void cleanup(URI type, Calendar from); URI createLogForContext(URI contextGraph); URI createLogForPrivacyPreference(PrivacyPreference privacyPref); }
|
@Test public void testCreateLogForContext() throws ResourceExistsException { URI liveContext = new URIImpl("urn:live-context"); Environment environment = modelFactory.getDCONFactory().createEnvironment(); URI temperatureUri = new URIImpl("urn:temperature:123"); environment.setCurrentTemperature(temperatureUri); resourceStore.createGraph(liveContext); resourceStore.create(liveContext, environment); URI logUri = historyLogService.createLogForContext(liveContext); URI metadataUri = tripleStore.getOrCreateMetadataGraph(logUri); assertTrue(tripleStore.containsStatements(metadataUri, logUri, RDF.type, DUHO.ContextLog)); assertTrue(tripleStore.containsStatements(metadataUri, logUri, DUHO.timestamp, Variable.ANY)); assertFalse(tripleStore.containsStatements(logUri, liveContext, Variable.ANY, Variable.ANY)); assertTrue(tripleStore.containsStatements(logUri, environment.asResource(), RDF.type, DCON.Environment)); assertTrue(tripleStore.containsStatements(logUri, environment.asResource(), DCON.currentTemperature, temperatureUri)); assertFalse(tripleStore.containsStatements(logUri, Variable.ANY, NAO.hasDataGraph, Variable.ANY)); assertFalse(tripleStore.containsStatements(logUri, Variable.ANY, NAO.isDataGraphFor, Variable.ANY)); }
|
HistoryLogService { public URI createLogForPrivacyPreference(PrivacyPreference privacyPref) { TripleStore tripleStore = resourceStore.getTripleStore(); URI logGraph = resourceStore.createGraph(DUHO.PrivacyPreferenceLog); URI metadataGraph = tripleStore.getOrCreateMetadataGraph(logGraph); tripleStore.addAll(logGraph, privacyPref.getModel().iterator()); try { tripleStore.addAll(logGraph, resourceStore.get(privacyPref.getAllAccessSpace().next().asResource()).getModel().iterator()); } catch (NoSuchElementException e) { logger.error("The privacy preference "+privacyPref.asResource()+" does not contain any AccessSpace: "+e.getMessage(), e); } catch (NotFoundException e) { logger.error("The privacy preference "+privacyPref.asResource()+" references an AccessSpace which does not exist: "+e.getMessage(), e); } tripleStore.addStatement(metadataGraph, logGraph, DUHO.timestamp, DateUtil.currentDateTimeAsLiteral()); broadcastManager.sendBroadcast(new Event(resourceStore.getName(), Event.ACTION_GRAPH_ADD, logGraph)); return logGraph; } HistoryLogService(ResourceStore resourceStore); void cleanup(URI type, Calendar from); URI createLogForContext(URI contextGraph); URI createLogForPrivacyPreference(PrivacyPreference privacyPref); }
|
@Test public void testCreateLogForPrivacyPreference() throws ResourceExistsException { URI testGraph = new URIImpl("test:graph"); URI group1 = new URIImpl("urn:group:1"); URI person3 = new URIImpl("urn:person:3"); URI person14 = new URIImpl("urn:person:14"); PrivacyPreference privacyPref = modelFactory.getPPOFactory().createPrivacyPreference(); privacyPref.setPrefLabel("example"); AccessSpace accessSpace = modelFactory.getNSOFactory().createAccessSpace(); accessSpace.addIncludes(group1); accessSpace.addExcludes(person3); privacyPref.setAccessSpace(accessSpace); resourceStore.createOrUpdate(testGraph, privacyPref); resourceStore.createOrUpdate(testGraph, accessSpace); URI logUri = historyLogService.createLogForPrivacyPreference(privacyPref); URI metadataUri = tripleStore.getOrCreateMetadataGraph(logUri); accessSpace.addIncludes(person14); resourceStore.createOrUpdate(testGraph, accessSpace); assertTrue(tripleStore.containsStatements(metadataUri, logUri, RDF.type, DUHO.PrivacyPreferenceLog)); assertTrue(tripleStore.containsStatements(logUri, privacyPref, RDF.type, PPO.PrivacyPreference)); assertTrue(tripleStore.containsStatements(logUri, privacyPref, PPO.hasAccessSpace, accessSpace)); assertTrue(tripleStore.containsStatements(logUri, accessSpace, NSO.includes, group1)); assertTrue(tripleStore.containsStatements(logUri, accessSpace, NSO.excludes, person3)); assertFalse(tripleStore.containsStatements(logUri, accessSpace, NSO.includes, person14)); assertTrue(tripleStore.containsStatements(testGraph, accessSpace, NSO.includes, person14)); }
|
AspectBasedStrategy implements UpdateStrategy { @Override public void update(List<Statement> toAdd, List<Statement> toRemove) { ClosableIterator<Statement> lcStmts = liveContext.iterator(); List<URI> aspects = new ArrayList<URI>(); List<Statement> toKeep = new ArrayList<Statement>(); while (lcStmts.hasNext()) { Statement statement = lcStmts.next(); Node object = statement.getObject(); if (object instanceof URI && ArrayUtils.contains(ASPECTS, object.asURI())) { aspects.add(statement.getSubject().asURI()); toKeep.add(statement); } } lcStmts.close(); lcStmts = liveContext.iterator(); while (lcStmts.hasNext()) { Statement statement = lcStmts.next(); Resource subject = statement.getSubject(); if (subject instanceof URI && aspects.contains(subject.asURI())) { toKeep.add(statement); } } lcStmts.close(); for (Statement stmt : toRemove) { URI resource = stmt.getSubject().asURI(); if (!aspects.contains(resource)) { previousContext.removeStatements(resource.asResource(), Variable.ANY, Variable.ANY); } } List<Statement> all = new ArrayList<Statement>(); all.addAll(toAdd); all.addAll(toRemove); for (Statement stmt : all) { URI resource = stmt.getSubject().asURI(); if (!aspects.contains(resource)) { previousContext.addAll(liveContext.findStatements(resource, Variable.ANY, Variable.ANY)); } } previousContext.addAll(toKeep.iterator()); liveContext.removeAll(toRemove.iterator()); liveContext.addAll(toAdd.iterator()); } AspectBasedStrategy(Model previousContext, Model liveContext); @Override void update(List<Statement> toAdd, List<Statement> toRemove); }
|
@Test public void testUpdateSeveralResources() throws LiveContextException { List<Statement> toAdd = new ArrayList<Statement>(); List<Statement> toRemove = new ArrayList<Statement>(); URI environment = new URIImpl("urn:uuid:"+UUID.randomUUID()); URI temp = new URIImpl("urn:uuid:"+UUID.randomUUID()); URI weather = new URIImpl("urn:uuid:"+UUID.randomUUID()); toAdd.add(new StatementImpl(null, environment, RDF.type, DCON.Environment)); toAdd.add(new StatementImpl(null, environment, DCON.currentTemperature, temp)); toAdd.add(new StatementImpl(null, environment, DCON.currentWeather, weather)); toAdd.add(new StatementImpl(null, temp, RDF.type, DPO.Temperature)); toAdd.add(new StatementImpl(null, temp, DCON.temperature, new DatatypeLiteralImpl("34.0", XSD._double))); toAdd.add(new StatementImpl(null, weather, RDF.type, DPO.WeatherConditions)); toAdd.add(new StatementImpl(null, weather, DCON.cloudcover, new DatatypeLiteralImpl("5", XSD._int))); strategy.update(toAdd, toRemove); Resource aspectURI = null; URI weatherConditionsURI = null; URI temperatureURI = null; assertEquals(0, this.previousContext.size()); assertEquals(7, this.liveContext.size()); assertTrue(this.liveContext.findStatements(environment, RDF.type, DCON.Environment).hasNext()); aspectURI = this.liveContext.findStatements(environment, RDF.type, DCON.Environment).next().getSubject(); assertTrue(this.liveContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).hasNext()); weatherConditionsURI = this.liveContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).next().getObject().asURI(); assertTrue(this.liveContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).hasNext()); temperatureURI = this.liveContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).next().getObject().asURI(); assertTrue(this.liveContext.findStatements(temperatureURI, RDF.type, DPO.Temperature).hasNext()); assertTrue(this.liveContext.findStatements(temperatureURI, DCON.temperature, new DatatypeLiteralImpl("34.0", XSD._double)).hasNext()); assertTrue(this.liveContext.findStatements(weatherConditionsURI, RDF.type, DPO.WeatherConditions).hasNext()); assertTrue(this.liveContext.findStatements(weatherConditionsURI, DCON.cloudcover, new DatatypeLiteralImpl("5", XSD._int)).hasNext()); toAdd.clear(); toRemove.clear(); toAdd.add(new StatementImpl(null, temp, DCON.temperature, new DatatypeLiteralImpl("36.0", XSD._double))); toRemove.add(new StatementImpl(null, temp, DCON.temperature, new DatatypeLiteralImpl("34.0", XSD._double))); strategy.update(toAdd, toRemove); assertEquals(5, this.previousContext.size()); assertTrue(this.previousContext.findStatements(environment, RDF.type, DCON.Environment).hasNext()); assertTrue(this.previousContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).hasNext()); temperatureURI = this.previousContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).next().getObject().asURI(); assertTrue(this.previousContext.findStatements(temperatureURI, RDF.type, DPO.Temperature).hasNext()); assertTrue(this.previousContext.findStatements(temperatureURI, DCON.temperature, new DatatypeLiteralImpl("34.0", XSD._double)).hasNext()); assertEquals(7, this.liveContext.size()); assertTrue(this.liveContext.findStatements(environment, RDF.type, DCON.Environment).hasNext()); aspectURI = this.liveContext.findStatements(environment, RDF.type, DCON.Environment).next().getSubject(); assertTrue(this.liveContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).hasNext()); weatherConditionsURI = this.liveContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).next().getObject().asURI(); assertTrue(this.liveContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).hasNext()); temperatureURI = this.liveContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).next().getObject().asURI(); assertTrue(this.liveContext.findStatements(temperatureURI, RDF.type, DPO.Temperature).hasNext()); assertTrue(this.liveContext.findStatements(temperatureURI, DCON.temperature, new DatatypeLiteralImpl("36.0", XSD._double)).hasNext()); assertTrue(this.liveContext.findStatements(weatherConditionsURI, RDF.type, DPO.WeatherConditions).hasNext()); assertTrue(this.liveContext.findStatements(weatherConditionsURI, DCON.cloudcover, new DatatypeLiteralImpl("5", XSD._int)).hasNext()); toAdd.clear(); toRemove.clear(); toAdd.add(new StatementImpl(null, weather, DCON.humidity, new DatatypeLiteralImpl("70", XSD._int))); strategy.update(toAdd, toRemove); assertEquals(7, this.previousContext.size()); assertTrue(this.previousContext.findStatements(environment, RDF.type, DCON.Environment).hasNext()); aspectURI = this.previousContext.findStatements(environment, RDF.type, DCON.Environment).next().getSubject(); assertTrue(this.previousContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).hasNext()); weatherConditionsURI = this.previousContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).next().getObject().asURI(); assertTrue(this.previousContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).hasNext()); temperatureURI = this.previousContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).next().getObject().asURI(); assertTrue(this.previousContext.findStatements(temperatureURI, RDF.type, DPO.Temperature).hasNext()); assertTrue(this.previousContext.findStatements(temperatureURI, DCON.temperature, new DatatypeLiteralImpl("34.0", XSD._double)).hasNext()); assertTrue(this.previousContext.findStatements(weatherConditionsURI, RDF.type, DPO.WeatherConditions).hasNext()); assertTrue(this.previousContext.findStatements(weatherConditionsURI, DCON.cloudcover, new DatatypeLiteralImpl("5", XSD._int)).hasNext()); assertEquals(8, this.liveContext.size()); assertTrue(this.liveContext.findStatements(environment, RDF.type, DCON.Environment).hasNext()); aspectURI = this.liveContext.findStatements(environment, RDF.type, DCON.Environment).next().getSubject(); assertTrue(this.liveContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).hasNext()); weatherConditionsURI = this.liveContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).next().getObject().asURI(); assertTrue(this.liveContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).hasNext()); temperatureURI = this.liveContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).next().getObject().asURI(); assertTrue(this.liveContext.findStatements(temperatureURI, RDF.type, DPO.Temperature).hasNext()); assertTrue(this.liveContext.findStatements(temperatureURI, DCON.temperature, new DatatypeLiteralImpl("36.0", XSD._double)).hasNext()); assertTrue(this.liveContext.findStatements(weatherConditionsURI, RDF.type, DPO.WeatherConditions).hasNext()); assertTrue(this.liveContext.findStatements(weatherConditionsURI, DCON.cloudcover, new DatatypeLiteralImpl("5", XSD._int)).hasNext()); assertTrue(this.liveContext.findStatements(weatherConditionsURI, DCON.humidity, new DatatypeLiteralImpl("70", XSD._int)).hasNext()); toAdd.clear(); toRemove.clear(); toAdd.add(new StatementImpl(null, temp, DCON.temperature, new DatatypeLiteralImpl("20.0", XSD._double))); toRemove.add(new StatementImpl(null, temp, DCON.temperature, new DatatypeLiteralImpl("36.0", XSD._double))); strategy.update(toAdd, toRemove); toAdd.clear(); toRemove.clear(); toAdd.add(new StatementImpl(null, weather, DCON.humidity, new DatatypeLiteralImpl("80", XSD._int))); toRemove.add(new StatementImpl(null, weather, DCON.humidity, new DatatypeLiteralImpl("70", XSD._int))); strategy.update(toAdd, toRemove); assertEquals(8, this.previousContext.size()); assertTrue(this.previousContext.findStatements(environment, RDF.type, DCON.Environment).hasNext()); aspectURI = this.previousContext.findStatements(environment, RDF.type, DCON.Environment).next().getSubject(); assertTrue(this.previousContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).hasNext()); weatherConditionsURI = this.previousContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).next().getObject().asURI(); assertTrue(this.previousContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).hasNext()); temperatureURI = this.previousContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).next().getObject().asURI(); assertTrue(this.previousContext.findStatements(temperatureURI, RDF.type, DPO.Temperature).hasNext()); assertTrue(this.previousContext.findStatements(temperatureURI, DCON.temperature, new DatatypeLiteralImpl("36.0", XSD._double)).hasNext()); assertTrue(this.previousContext.findStatements(weatherConditionsURI, RDF.type, DPO.WeatherConditions).hasNext()); assertTrue(this.previousContext.findStatements(weatherConditionsURI, DCON.cloudcover, new DatatypeLiteralImpl("5", XSD._int)).hasNext()); assertTrue(this.previousContext.findStatements(weatherConditionsURI, DCON.humidity, new DatatypeLiteralImpl("70", XSD._int)).hasNext()); assertEquals(8, this.liveContext.size()); assertTrue(this.liveContext.findStatements(environment, RDF.type, DCON.Environment).hasNext()); aspectURI = this.liveContext.findStatements(environment, RDF.type, DCON.Environment).next().getSubject(); assertTrue(this.liveContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).hasNext()); weatherConditionsURI = this.liveContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).next().getObject().asURI(); assertTrue(this.liveContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).hasNext()); temperatureURI = this.liveContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).next().getObject().asURI(); assertTrue(this.liveContext.findStatements(temperatureURI, RDF.type, DPO.Temperature).hasNext()); assertTrue(this.liveContext.findStatements(temperatureURI, DCON.temperature, new DatatypeLiteralImpl("20.0", XSD._double)).hasNext()); assertTrue(this.liveContext.findStatements(weatherConditionsURI, RDF.type, DPO.WeatherConditions).hasNext()); assertTrue(this.liveContext.findStatements(weatherConditionsURI, DCON.cloudcover, new DatatypeLiteralImpl("5", XSD._int)).hasNext()); assertTrue(this.liveContext.findStatements(weatherConditionsURI, DCON.humidity, new DatatypeLiteralImpl("80", XSD._int)).hasNext()); toAdd.clear(); toRemove.clear(); toAdd.add(new StatementImpl(null, weather, DCON.cloudcover, new DatatypeLiteralImpl("10", XSD._int))); toAdd.add(new StatementImpl(null, weather, DCON.humidity, new DatatypeLiteralImpl("70", XSD._int))); toRemove.add(new StatementImpl(null, weather, DCON.cloudcover, new DatatypeLiteralImpl("5", XSD._int))); toRemove.add(new StatementImpl(null, weather, DCON.humidity, new DatatypeLiteralImpl("80", XSD._int))); strategy.update(toAdd, toRemove); assertEquals(8, this.previousContext.size()); assertTrue(this.previousContext.findStatements(environment, RDF.type, DCON.Environment).hasNext()); aspectURI = this.previousContext.findStatements(environment, RDF.type, DCON.Environment).next().getSubject(); assertTrue(this.previousContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).hasNext()); weatherConditionsURI = this.previousContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).next().getObject().asURI(); assertTrue(this.previousContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).hasNext()); temperatureURI = this.previousContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).next().getObject().asURI(); assertTrue(this.previousContext.findStatements(temperatureURI, RDF.type, DPO.Temperature).hasNext()); assertTrue(this.previousContext.findStatements(temperatureURI, DCON.temperature, new DatatypeLiteralImpl("36.0", XSD._double)).hasNext()); assertTrue(this.previousContext.findStatements(weatherConditionsURI, RDF.type, DPO.WeatherConditions).hasNext()); assertTrue(this.previousContext.findStatements(weatherConditionsURI, DCON.cloudcover, new DatatypeLiteralImpl("5", XSD._int)).hasNext()); assertTrue(this.previousContext.findStatements(weatherConditionsURI, DCON.humidity, new DatatypeLiteralImpl("80", XSD._int)).hasNext()); assertEquals(8, this.liveContext.size()); assertTrue(this.liveContext.findStatements(environment, RDF.type, DCON.Environment).hasNext()); aspectURI = this.liveContext.findStatements(environment, RDF.type, DCON.Environment).next().getSubject(); assertTrue(this.liveContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).hasNext()); weatherConditionsURI = this.liveContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).next().getObject().asURI(); assertTrue(this.liveContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).hasNext()); temperatureURI = this.liveContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).next().getObject().asURI(); assertTrue(this.liveContext.findStatements(temperatureURI, RDF.type, DPO.Temperature).hasNext()); assertTrue(this.liveContext.findStatements(temperatureURI, DCON.temperature, new DatatypeLiteralImpl("20.0", XSD._double)).hasNext()); assertTrue(this.liveContext.findStatements(weatherConditionsURI, RDF.type, DPO.WeatherConditions).hasNext()); assertTrue(this.liveContext.findStatements(weatherConditionsURI, DCON.cloudcover, new DatatypeLiteralImpl("10", XSD._int)).hasNext()); assertTrue(this.liveContext.findStatements(weatherConditionsURI, DCON.humidity, new DatatypeLiteralImpl("70", XSD._int)).hasNext()); }
|
ElementBasedStrategy implements UpdateStrategy { @Override public void update(List<Statement> toAdd, List<Statement> toRemove) { Model newData = RDF2Go.getModelFactory().createModel().open(); for (Statement s : toAdd) { newData.addStatement(s); } Set<URI> elements = new HashSet<URI>(); elements.addAll(findElements(toAdd)); elements.addAll(findElements(toRemove)); logger.debug("Updating live context... elements to be updated: "+StringUtils.join(elements, ", ")); for (URI element : elements) { if (liveContext.contains(Variable.ANY, Variable.ANY, element)) { previousContext.removeStatements(Variable.ANY, Variable.ANY, element); previousContext.removeStatements(element, Variable.ANY, Variable.ANY); previousContext.addAll(liveContext.findStatements(Variable.ANY, Variable.ANY, element)); previousContext.addAll(liveContext.findStatements(element, Variable.ANY, Variable.ANY)); } else { URI aspect = newData.findStatements(Variable.ANY, Variable.ANY, element).next().getSubject().asURI(); String query = "SELECT DISTINCT ?element WHERE { "+aspect.toSPARQL()+" ?p ?element . }"; Set<URI> existing = new HashSet<URI>(); ClosableIterator<QueryRow> results = liveContext.sparqlSelect(query).iterator(); while (results.hasNext()) { existing.add(results.next().getValue("element").asURI()); } results.close(); for (URI e : existing) { if (!previousContext.contains(aspect, Variable.ANY, e)) { previousContext.addAll(liveContext.findStatements(aspect, Variable.ANY, e)); previousContext.addAll(liveContext.findStatements(e, Variable.ANY, Variable.ANY)); } } } } newData.close(); liveContext.removeAll(toRemove.iterator()); liveContext.addAll(toAdd.iterator()); } ElementBasedStrategy(Model previousContext, Model liveContext); @Override void update(List<Statement> toAdd, List<Statement> toRemove); }
|
@Test public void testAddElementToLiveContext() throws Exception { List<Statement> toAdd = new ArrayList<Statement>(); List<Statement> toRemove = new ArrayList<Statement>(); URI ismael = new URIImpl("urn:ismael"); toAdd.add(new StatementImpl(null, PEERS, DCON.nearbyPerson, ismael)); strategy.update(toAdd, toRemove); toAdd.clear(); toRemove.clear(); assertTrue(liveContext.contains(PEERS, DCON.nearbyPerson, ismael)); assertFalse(previousContext.contains(PEERS, DCON.nearbyPerson, Variable.ANY)); }
@Test public void testAddSecondElementToLiveContext() throws Exception { List<Statement> toAdd = new ArrayList<Statement>(); List<Statement> toRemove = new ArrayList<Statement>(); URI ismael = new URIImpl("urn:ismael"); toAdd.add(new StatementImpl(null, PEERS, DCON.nearbyPerson, ismael)); strategy.update(toAdd, toRemove); toAdd.clear(); toRemove.clear(); URI simon = new URIImpl("urn:simon"); toAdd.add(new StatementImpl(null, PEERS, DCON.nearbyPerson, simon)); strategy.update(toAdd, toRemove); toAdd.clear(); toRemove.clear(); assertTrue(liveContext.contains(PEERS, DCON.nearbyPerson, ismael)); assertTrue(liveContext.contains(PEERS, DCON.nearbyPerson, simon)); assertTrue(previousContext.contains(PEERS, DCON.nearbyPerson, ismael)); assertFalse(previousContext.contains(PEERS, DCON.nearbyPerson, simon)); }
@Test public void testAddRemoveElementFromLiveContext() throws Exception { List<Statement> toAdd = new ArrayList<Statement>(); List<Statement> toRemove = new ArrayList<Statement>(); URI ismael = new URIImpl("urn:ismael"); toAdd.add(new StatementImpl(null, PEERS, DCON.nearbyPerson, ismael)); strategy.update(toAdd, toRemove); toAdd.clear(); toRemove.clear(); toRemove.add(new StatementImpl(null, PEERS, DCON.nearbyPerson, ismael)); strategy.update(toAdd, toRemove); toAdd.clear(); toRemove.clear(); assertTrue(previousContext.contains(PEERS, DCON.nearbyPerson, ismael)); assertFalse(liveContext.contains(PEERS, DCON.nearbyPerson, Variable.ANY)); }
@Test public void testAddUpdateRemoveElementFromLiveContext() throws Exception { List<Statement> toAdd = new ArrayList<Statement>(); List<Statement> toRemove = new ArrayList<Statement>(); URI temperature = new URIImpl("urn:uuid:" + UUID.randomUUID()); toAdd.add(new StatementImpl(null, ENVIRONMENT, DCON.currentTemperature, temperature)); toAdd.add(new StatementImpl(null, temperature, DCON.temperature, new PlainLiteralImpl("34"))); strategy.update(toAdd, toRemove); toAdd.clear(); toRemove.clear(); assertTrue(liveContext.contains(temperature, DCON.temperature, new PlainLiteralImpl("34"))); assertFalse(previousContext.contains(ENVIRONMENT, DCON.currentTemperature, temperature)); assertFalse(previousContext.contains(temperature, Variable.ANY, Variable.ANY)); toRemove.add(new StatementImpl(null, temperature, DCON.temperature, new PlainLiteralImpl("34"))); toAdd.add(new StatementImpl(null, temperature, DCON.temperature, new PlainLiteralImpl("39"))); strategy.update(toAdd, toRemove); toAdd.clear(); toRemove.clear(); assertTrue(liveContext.contains(temperature, DCON.temperature, new PlainLiteralImpl("39"))); assertTrue(previousContext.contains(temperature, DCON.temperature, new PlainLiteralImpl("34"))); }
@Test public void testCombinedAddition() throws LiveContextException { List<Statement> toAdd = new ArrayList<Statement>(); List<Statement> toRemove = new ArrayList<Statement>(); URI temperature = new URIImpl("urn:uuid:" + UUID.randomUUID()); toAdd.add(new StatementImpl(null, ENVIRONMENT, DCON.currentTemperature, temperature)); toAdd.add(new StatementImpl(null, temperature, DCON.temperature, new PlainLiteralImpl("34"))); URI weather = new URIImpl("urn:uuid:" + UUID.randomUUID()); toAdd.add(new StatementImpl(null, ENVIRONMENT, DCON.currentWeather, weather)); toAdd.add(new StatementImpl(null, weather, DCON.cloudcover, new PlainLiteralImpl("5"))); strategy.update(toAdd, toRemove); toAdd.clear(); toRemove.clear(); assertTrue(liveContext.contains(ENVIRONMENT, DCON.currentWeather, weather)); assertTrue(liveContext.contains(temperature, DCON.temperature, new PlainLiteralImpl("34"))); assertTrue(liveContext.contains(ENVIRONMENT, DCON.currentWeather, weather)); assertTrue(liveContext.contains(weather, DCON.cloudcover, new PlainLiteralImpl("5"))); assertFalse(previousContext.contains(ENVIRONMENT, DCON.currentWeather, Variable.ANY)); assertFalse(previousContext.contains(temperature, DCON.temperature, Variable.ANY)); assertFalse(previousContext.contains(weather, DCON.cloudcover, Variable.ANY)); }
@Test public void testCombinedAdditionAndUpdate() throws LiveContextException { List<Statement> toAdd = new ArrayList<Statement>(); List<Statement> toRemove = new ArrayList<Statement>(); URI temperature = new URIImpl("urn:uuid:" + UUID.randomUUID()); toAdd.add(new StatementImpl(null, ENVIRONMENT, DCON.currentTemperature, temperature)); toAdd.add(new StatementImpl(null, temperature, DCON.temperature, new PlainLiteralImpl("34"))); URI weather = new URIImpl("urn:uuid:" + UUID.randomUUID()); toAdd.add(new StatementImpl(null, ENVIRONMENT, DCON.currentWeather, weather)); toAdd.add(new StatementImpl(null, weather, DCON.cloudcover, new PlainLiteralImpl("5"))); strategy.update(toAdd, toRemove); toAdd.clear(); toRemove.clear(); toRemove.add(new StatementImpl(null, temperature, DCON.temperature, new PlainLiteralImpl("34"))); toAdd.add(new StatementImpl(null, temperature, DCON.temperature, new PlainLiteralImpl("36"))); strategy.update(toAdd, toRemove); toAdd.clear(); toRemove.clear(); assertTrue(liveContext.contains(temperature, DCON.temperature, new PlainLiteralImpl("36"))); assertTrue(previousContext.contains(temperature, DCON.temperature, new PlainLiteralImpl("34"))); assertFalse(previousContext.contains(ENVIRONMENT, DCON.currentWeather, weather)); assertFalse(previousContext.contains(weather, DCON.cloudcover, Variable.ANY)); }
@Test public void testSeveralAddAndUpdate() throws LiveContextException { List<Statement> toAdd = new ArrayList<Statement>(); List<Statement> toRemove = new ArrayList<Statement>(); URI temperature = new URIImpl("urn:uuid:" + UUID.randomUUID()); toAdd.add(new StatementImpl(null, ENVIRONMENT, DCON.currentTemperature, temperature)); toAdd.add(new StatementImpl(null, temperature, DCON.temperature, new PlainLiteralImpl("34"))); strategy.update(toAdd, toRemove); toAdd.clear(); toRemove.clear(); URI weather = new URIImpl("urn:uuid:" + UUID.randomUUID()); toAdd.add(new StatementImpl(null, ENVIRONMENT, DCON.currentWeather, weather)); toAdd.add(new StatementImpl(null, weather, DCON.cloudcover, new PlainLiteralImpl("5"))); strategy.update(toAdd, toRemove); toAdd.clear(); toRemove.clear(); assertTrue(liveContext.contains(ENVIRONMENT, DCON.currentTemperature, temperature)); assertTrue(liveContext.contains(temperature, DCON.temperature, new PlainLiteralImpl("34"))); assertTrue(liveContext.contains(ENVIRONMENT, DCON.currentWeather, weather)); assertTrue(liveContext.contains(weather, DCON.cloudcover, new PlainLiteralImpl("5"))); assertTrue(previousContext.contains(ENVIRONMENT, DCON.currentTemperature, temperature)); assertTrue(previousContext.contains(temperature, DCON.temperature, new PlainLiteralImpl("34"))); assertFalse(previousContext.contains(ENVIRONMENT, DCON.currentWeather, weather)); assertFalse(previousContext.contains(weather, DCON.cloudcover, Variable.ANY)); toRemove.add(new StatementImpl(null, temperature, DCON.temperature, new PlainLiteralImpl("34"))); toAdd.add(new StatementImpl(null, temperature, DCON.temperature, new PlainLiteralImpl("36"))); strategy.update(toAdd, toRemove); toAdd.clear(); toRemove.clear(); assertTrue(liveContext.contains(temperature, DCON.temperature, new PlainLiteralImpl("36"))); assertTrue(liveContext.contains(weather, DCON.cloudcover, new PlainLiteralImpl("5"))); assertTrue(previousContext.contains(temperature, DCON.temperature, new PlainLiteralImpl("34"))); assertFalse(previousContext.contains(ENVIRONMENT, DCON.currentWeather, weather)); assertFalse(previousContext.contains(weather, DCON.cloudcover, new PlainLiteralImpl("5"))); URI altitude = new URIImpl("urn:uuid:" + UUID.randomUUID()); toAdd.add(new StatementImpl(null, ENVIRONMENT, DCON.currentAbsoluteAltitude, altitude)); toAdd.add(new StatementImpl(null, altitude, DCON.altitude, new PlainLiteralImpl("628"))); strategy.update(toAdd, toRemove); toAdd.clear(); toRemove.clear(); assertTrue(liveContext.contains(ENVIRONMENT, DCON.currentAbsoluteAltitude, altitude)); assertTrue(liveContext.contains(altitude, DCON.altitude, new PlainLiteralImpl("628"))); assertTrue(previousContext.contains(temperature, DCON.temperature, new PlainLiteralImpl("34"))); assertTrue(previousContext.contains(weather, DCON.cloudcover, new PlainLiteralImpl("5"))); }
|
AuthenticationController { @GET @Produces(MediaType.APPLICATION_JSON) @Path("/credentials/{contact-said}") public Response<AccountEntry> getCredentials( @PathParam("said") String saidLocal, @PathParam("contact-said") String saidRequester) throws DimeException { Data<AccountEntry> data = new Data<AccountEntry>(); boolean unlocked; try { unlocked = lock.tryLock(50L, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new DimeException("Password retrieval failed", e); } if (!unlocked) { logger.error("Could not aquire lock within 5 seconds. Returning."); throw new DimeException("Could not request credentials because the system is busy."); } try { User user = userManager.getUserForAccountAndTenant(saidRequester, saidLocal); if (user == null) { return Response.badRequest("Useraccount was null", null); } if (user.getPassword() == null || user.getPassword().equals("")) { user = userManager.generatePassword((user.getId())); } if (user != null) { AccountEntry jsonEntry = new AccountEntry(); jsonEntry.setUsername(user.getUsername()); jsonEntry.setPassword(user.getPassword()); jsonEntry.setRole(user.getRole().ordinal()); jsonEntry.setEnabled(user.isEnabled()); jsonEntry.setType("auth"); data.addEntry(jsonEntry); } else { return Response.badRequest("Useraccount was already activated!", null); } return Response.ok(data); } catch (Exception e) { return Response.serverError(); } finally { lock.unlock(); } } void setUserManager(UserManager userManager); void setAccessControlManager(AccessControlManager accessControlManager); @GET @Path("{userName}") @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") Response<AccountEntry> getUser(
@PathParam("userName") String userName); @POST @Path("{userName}")// can be @me - then updating the current user @Consumes(MediaType.APPLICATION_JSON + ";charset=UTF-8") @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") Response<AccountEntry> updateUser(
@PathParam("said") String said,
@PathParam("userName") String userName,
Request<AccountEntry> request); @DELETE @Path("{userName}") @Consumes(MediaType.APPLICATION_JSON + ";charset=UTF-8") @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") Response<AccountEntry> deleteAccount(Request<AccountEntry> request,
@PathParam("userName") String userName); @GET @Path("/username") String getCurrentUserName(); @GET @Path("/role") String getCurrentRole(); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/credentials/{contact-said}") Response<AccountEntry> getCredentials(
@PathParam("said") String saidLocal,
@PathParam("contact-said") String saidRequester); @POST @Produces(MediaType.APPLICATION_JSON) @Path("/credentials/{contact-said}") Response<?> confirmCredentials(
@PathParam("said") String saidLocal,
@PathParam("contact-said") String saidRequester); }
|
@Test public void testGetCredentials() { try { Response<AccountEntry> response = authenticationController.getCredentials(SAID_LOCAL, SAID_REMOTE); Collection<AccountEntry> col = response.getMessage().getData().getEntries(); AccountEntry account = col.iterator().next(); String tmpPassword = account.getPassword(); response = authenticationController.getCredentials(SAID_LOCAL, SAID_REMOTE); col = response.getMessage().getData().getEntries(); account = col.iterator().next(); Assert.assertFalse(!account.getPassword().equals(tmpPassword)); } catch (DimeException ex) { Logger.getLogger(AuthenticationControllerTest.class.getName()).log(Level.SEVERE, null, ex); } }
|
SnapshotBasedStrategy implements UpdateStrategy { @Override public void update(List<Statement> toAdd, List<Statement> toRemove) { previousContext.removeAll(); previousContext.addAll(liveContext.iterator()); liveContext.removeAll(toRemove.iterator()); liveContext.addAll(toAdd.iterator()); } SnapshotBasedStrategy(Model previousContext, Model liveContext); @Override void update(List<Statement> toAdd, List<Statement> toRemove); }
|
@Test public void testUpdateSeveralResources() throws LiveContextException { List<Statement> toAdd = new ArrayList<Statement>(); List<Statement> toRemove = new ArrayList<Statement>(); URI environment = new URIImpl("urn:uuid:"+UUID.randomUUID()); URI temp = new URIImpl("urn:uuid:"+UUID.randomUUID()); URI weather = new URIImpl("urn:uuid:"+UUID.randomUUID()); toAdd.add(new StatementImpl(null, environment, RDF.type, DCON.Environment)); toAdd.add(new StatementImpl(null, environment, DCON.currentTemperature, temp)); toAdd.add(new StatementImpl(null, environment, DCON.currentWeather, weather)); toAdd.add(new StatementImpl(null, temp, RDF.type, DPO.Temperature)); toAdd.add(new StatementImpl(null, temp, DCON.temperature, new DatatypeLiteralImpl("34.0", XSD._double))); toAdd.add(new StatementImpl(null, weather, RDF.type, DPO.WeatherConditions)); toAdd.add(new StatementImpl(null, weather, DCON.cloudcover, new DatatypeLiteralImpl("5", XSD._int))); strategy.update(toAdd, toRemove); Resource aspectURI = null; URI weatherConditionsURI = null; URI temperatureURI = null; assertEquals(0, this.previousContext.size()); assertEquals(7, this.liveContext.size()); assertTrue(this.liveContext.findStatements(environment, RDF.type, DCON.Environment).hasNext()); aspectURI = this.liveContext.findStatements(environment, RDF.type, DCON.Environment).next().getSubject(); assertTrue(this.liveContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).hasNext()); weatherConditionsURI = (URI) this.liveContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).next().getObject(); assertTrue(this.liveContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).hasNext()); temperatureURI = (URI) this.liveContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).next().getObject(); assertTrue(this.liveContext.findStatements(temperatureURI, RDF.type, DPO.Temperature).hasNext()); assertTrue(this.liveContext.findStatements(temperatureURI, DCON.temperature, new DatatypeLiteralImpl("34.0", XSD._double)).hasNext()); assertTrue(this.liveContext.findStatements(weatherConditionsURI, RDF.type, DPO.WeatherConditions).hasNext()); assertTrue(this.liveContext.findStatements(weatherConditionsURI, DCON.cloudcover, new DatatypeLiteralImpl("5", XSD._int)).hasNext()); toAdd.clear(); toRemove.clear(); toAdd.add(new StatementImpl(null, temp, DCON.temperature, new DatatypeLiteralImpl("36.0", XSD._double))); toRemove.add(new StatementImpl(null, temp, DCON.temperature, new DatatypeLiteralImpl("34.0", XSD._double))); strategy.update(toAdd, toRemove); assertEquals(7, this.previousContext.size()); assertTrue(this.previousContext.findStatements(environment, RDF.type, DCON.Environment).hasNext()); aspectURI = this.previousContext.findStatements(environment, RDF.type, DCON.Environment).next().getSubject(); assertTrue(this.previousContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).hasNext()); weatherConditionsURI = (URI) this.previousContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).next().getObject(); assertTrue(this.previousContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).hasNext()); temperatureURI = (URI) this.previousContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).next().getObject(); assertTrue(this.previousContext.findStatements(temperatureURI, RDF.type, DPO.Temperature).hasNext()); assertTrue(this.previousContext.findStatements(temperatureURI, DCON.temperature, new DatatypeLiteralImpl("34.0", XSD._double)).hasNext()); assertTrue(this.previousContext.findStatements(weatherConditionsURI, RDF.type, DPO.WeatherConditions).hasNext()); assertTrue(this.previousContext.findStatements(weatherConditionsURI, DCON.cloudcover, new DatatypeLiteralImpl("5", XSD._int)).hasNext()); assertEquals(7, this.liveContext.size()); assertTrue(this.liveContext.findStatements(environment, RDF.type, DCON.Environment).hasNext()); aspectURI = this.liveContext.findStatements(environment, RDF.type, DCON.Environment).next().getSubject(); assertTrue(this.liveContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).hasNext()); weatherConditionsURI = (URI) this.liveContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).next().getObject(); assertTrue(this.liveContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).hasNext()); temperatureURI = (URI) this.liveContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).next().getObject(); assertTrue(this.liveContext.findStatements(temperatureURI, RDF.type, DPO.Temperature).hasNext()); assertTrue(this.liveContext.findStatements(temperatureURI, DCON.temperature, new DatatypeLiteralImpl("36.0", XSD._double)).hasNext()); assertTrue(this.liveContext.findStatements(weatherConditionsURI, RDF.type, DPO.WeatherConditions).hasNext()); assertTrue(this.liveContext.findStatements(weatherConditionsURI, DCON.cloudcover, new DatatypeLiteralImpl("5", XSD._int)).hasNext()); toAdd.clear(); toRemove.clear(); toAdd.add(new StatementImpl(null, weather, DCON.cloudcover, new DatatypeLiteralImpl("10", XSD._int))); toAdd.add(new StatementImpl(null, weather, DCON.humidity, new DatatypeLiteralImpl("70", XSD._int))); toRemove.add(new StatementImpl(null, weather, DCON.cloudcover, new DatatypeLiteralImpl("5", XSD._int))); strategy.update(toAdd, toRemove); assertEquals(7, this.previousContext.size()); assertTrue(this.previousContext.findStatements(environment, RDF.type, DCON.Environment).hasNext()); aspectURI = this.previousContext.findStatements(environment, RDF.type, DCON.Environment).next().getSubject(); assertTrue(this.previousContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).hasNext()); weatherConditionsURI = (URI) this.previousContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).next().getObject(); assertTrue(this.previousContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).hasNext()); temperatureURI = (URI) this.previousContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).next().getObject(); assertTrue(this.previousContext.findStatements(temperatureURI, RDF.type, DPO.Temperature).hasNext()); assertTrue(this.previousContext.findStatements(temperatureURI, DCON.temperature, new DatatypeLiteralImpl("36.0", XSD._double)).hasNext()); assertTrue(this.previousContext.findStatements(weatherConditionsURI, RDF.type, DPO.WeatherConditions).hasNext()); assertTrue(this.previousContext.findStatements(weatherConditionsURI, DCON.cloudcover, new DatatypeLiteralImpl("5", XSD._int)).hasNext()); assertEquals(8, this.liveContext.size()); assertTrue(this.liveContext.findStatements(environment, RDF.type, DCON.Environment).hasNext()); aspectURI = this.liveContext.findStatements(environment, RDF.type, DCON.Environment).next().getSubject(); assertTrue(this.liveContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).hasNext()); weatherConditionsURI = (URI) this.liveContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).next().getObject(); assertTrue(this.liveContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).hasNext()); temperatureURI = (URI) this.liveContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).next().getObject(); assertTrue(this.liveContext.findStatements(temperatureURI, RDF.type, DPO.Temperature).hasNext()); assertTrue(this.liveContext.findStatements(temperatureURI, DCON.temperature, new DatatypeLiteralImpl("36.0", XSD._double)).hasNext()); assertTrue(this.liveContext.findStatements(weatherConditionsURI, RDF.type, DPO.WeatherConditions).hasNext()); assertTrue(this.liveContext.findStatements(weatherConditionsURI, DCON.cloudcover, new DatatypeLiteralImpl("10", XSD._int)).hasNext()); assertTrue(this.liveContext.findStatements(weatherConditionsURI, DCON.humidity, new DatatypeLiteralImpl("70", XSD._int)).hasNext()); toAdd.clear(); toRemove.clear(); toAdd.add(new StatementImpl(null, weather, DCON.cloudcover, new DatatypeLiteralImpl("5", XSD._int))); toRemove.add(new StatementImpl(null, weather, DCON.cloudcover, new DatatypeLiteralImpl("10", XSD._int))); strategy.update(toAdd, toRemove); assertEquals(8, this.previousContext.size()); assertTrue(this.previousContext.findStatements(environment, RDF.type, DCON.Environment).hasNext()); aspectURI = this.previousContext.findStatements(environment, RDF.type, DCON.Environment).next().getSubject(); assertTrue(this.previousContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).hasNext()); weatherConditionsURI = (URI) this.previousContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).next().getObject(); assertTrue(this.previousContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).hasNext()); temperatureURI = (URI) this.previousContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).next().getObject(); assertTrue(this.previousContext.findStatements(temperatureURI, RDF.type, DPO.Temperature).hasNext()); assertTrue(this.previousContext.findStatements(temperatureURI, DCON.temperature, new DatatypeLiteralImpl("36.0", XSD._double)).hasNext()); assertTrue(this.previousContext.findStatements(weatherConditionsURI, RDF.type, DPO.WeatherConditions).hasNext()); assertTrue(this.previousContext.findStatements(weatherConditionsURI, DCON.cloudcover, new DatatypeLiteralImpl("10", XSD._int)).hasNext()); assertTrue(this.previousContext.findStatements(weatherConditionsURI, DCON.humidity, new DatatypeLiteralImpl("70", XSD._int)).hasNext()); assertEquals(8, this.liveContext.size()); assertTrue(this.liveContext.findStatements(environment, RDF.type, DCON.Environment).hasNext()); aspectURI = this.liveContext.findStatements(environment, RDF.type, DCON.Environment).next().getSubject(); assertTrue(this.liveContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).hasNext()); weatherConditionsURI = (URI) this.liveContext.findStatements(aspectURI, DCON.currentWeather, Variable.ANY).next().getObject(); assertTrue(this.liveContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).hasNext()); temperatureURI = (URI) this.liveContext.findStatements(aspectURI, DCON.currentTemperature, Variable.ANY).next().getObject(); assertTrue(this.liveContext.findStatements(temperatureURI, RDF.type, DPO.Temperature).hasNext()); assertTrue(this.liveContext.findStatements(temperatureURI, DCON.temperature, new DatatypeLiteralImpl("36.0", XSD._double)).hasNext()); assertTrue(this.liveContext.findStatements(weatherConditionsURI, RDF.type, DPO.WeatherConditions).hasNext()); assertTrue(this.liveContext.findStatements(weatherConditionsURI, DCON.cloudcover, new DatatypeLiteralImpl("5", XSD._int)).hasNext()); assertTrue(this.liveContext.findStatements(weatherConditionsURI, DCON.humidity, new DatatypeLiteralImpl("70", XSD._int)).hasNext()); }
|
EvaluationData { public static long countEvaluationDatas() { return entityManager().createQuery("SELECT COUNT(o) FROM EvaluationData o", Long.class).getSingleResult(); } String toString(); String getInvolvedItems(); void setInvolvedItems(String involvedItems); Long getId(); void setId(Long id); Integer getVersion(); void setVersion(Integer version); @Transactional void persist(); @Transactional void remove(); @Transactional void flush(); @Transactional void clear(); @Transactional EvaluationData merge(); static final EntityManager entityManager(); static long countEvaluationDatas(); static List<EvaluationData> findAllEvaluationDatas(); static List<EvaluationData> findAllLogRegisterEvaluationDatas(); static EvaluationData findEvaluationData(Long id); static List<EvaluationData> findEvaluationDataEntries(int firstResult, int maxResults); Date getEvaluationdate(); void setEvaluationdate(Date evaluationdate); String getClientid(); String getTenantId(); void setTenantId(String tenantId); void setClientid(String clientid); String getEvaluationaction(); void setEvaluationaction(String evaluationaction); String getCurrentplace(); void setCurrentplace(String currentplace); String getCurrsituationid(); void setCurrsituationid(String currsituationid); String getViewstack(); void setViewstack(String viewstack); final static String EVALUATIONDATA_ACTION_REGISTER; }
|
@Test public void testMethod() { int expectedCount = 13; EvaluationData.countEvaluationDatas(); org.springframework.mock.staticmock.AnnotationDrivenStaticEntityMockingControl.expectReturn(expectedCount); org.springframework.mock.staticmock.AnnotationDrivenStaticEntityMockingControl.playback(); org.junit.Assert.assertEquals(expectedCount, EvaluationData.countEvaluationDatas()); }
|
LivePostDecomposer { public List<LivePost> decompose(LivePost livepost) throws DataMiningException { List<LivePost> liveposts = new ArrayList<LivePost>(); if (!livepost.hasTextualContent()) { throw new DataMiningException("Livepost "+livepost.asResource()+" cannot be decomposed, no textual content is provided."); } else { String text = livepost.getAllTextualContent().next(); Calendar timestamp = livepost.hasTimestamp() ? livepost.getTimestamp() : Calendar.getInstance(); LivePost superPost = dlpoFactory.createLivePost(livepost.asURI()); superPost.getModel().addAll(livepost.getModel().iterator()); try { LivePost subPost = null; for (String link : LinkExtractor.extract(text, true)) { URL url = null; try { url = new URL(link); } catch (MalformedURLException e) { logger.error(link+" is not a valid URL in livepost "+livepost.asResource(), e); continue; } superPost.addRelatedResource(new URIImpl(link)); ResourceModel linkMetadata = urlExtractor.extract(url); String type = linkMetadata.getString(OG.type); if (type == null) { continue; } else if ("audio".equals(type)) { subPost = dlpoFactory.createAudioPost(); } else if ("image".equals(type)) { subPost = dlpoFactory.createImagePost(); } else if ("video".equals(type)) { subPost = dlpoFactory.createVideoPost(); } superPost.addIsComposedOf(subPost.asResource()); subPost.setTimestamp(timestamp); subPost.setTextualContent(text); subPost.setDefiningResource(new URIImpl(link)); subPost.setDefiningResource(new URIImpl(link)); subPost.getModel().addAll(linkMetadata.getModel().iterator()); subPost.getModel().addAll(opengraphExtractor.extract(url).getModel().iterator()); liveposts.add(subPost); } } catch (ExtractionException e) { logger.error("Error occurred while decomposing livepost "+livepost.asResource(), e); } Status status = dlpoFactory.createStatus(); status.setTimestamp(timestamp); status.setTextualContent(text); superPost.addIsComposedOf(status); liveposts.add(status); liveposts.add(superPost); } return liveposts; } LivePostDecomposer(); List<LivePost> decompose(LivePost livepost); }
|
@Test public void testDecomposeVideoAndImage() throws Exception { LivePost livepost = buildLivePost("Love this song!! http: List<LivePost> liveposts = decomposer.decompose(livepost); assertEquals(4, liveposts.size()); assertTrue(liveposts.contains(livepost)); LivePost parent = null; ImagePost imagePost = null; VideoPost videoPost = null; for (LivePost lv : liveposts) { if (lv instanceof VideoPost) { videoPost = (VideoPost) lv; } else if (lv instanceof ImagePost) { imagePost = (ImagePost) lv; } else { parent = lv; } } assertEquals(2, parent.getAllRelatedResource_as().count()); assertEquals("http: assertEquals("http: }
|
StreamAccountUpdater extends AccountUpdaterBase implements AccountUpdater<LivePost> { @Override public void update(URI accountUri, String path, LivePost livepost) throws AccountIntegrationException { Collection<LivePost> liveposts = new ArrayList<LivePost>(1); liveposts.add(livepost); update(accountUri, path, liveposts); } StreamAccountUpdater(ResourceStore resourceStore); @Override void update(URI accountUri, String path, LivePost livepost); @Override void update(URI accountUri, String path, Collection<LivePost> liveposts); }
|
@Test public void testAddTwoStreams() throws Exception { Account linkedin = modelFactory.getDAOFactory().createAccount("urn:service:linkedin"); linkedin.setPrefLabel("LinkedIn"); resourceStore.createOrUpdate(null, linkedin); ResourceStore data = null; Collection<LivePost> messages = new ArrayList<LivePost>(); data = createResourceStore( this.getClass().getClassLoader().getResourceAsStream("account/liveposts-call1.ttl"), Syntax.Turtle); for (Status status : data.find(Status.class).distinct().results()) { messages.add((Status) status.castTo(Status.class)); } streamAccountUpdater.update(linkedin.asURI(), "/liveposts", messages); assertEquals(10, resourceStore.find(Status.class).distinct().results().size()); messages.clear(); data = createResourceStore( this.getClass().getClassLoader().getResourceAsStream("account/liveposts-call2.ttl"), Syntax.Turtle); for (Status status : data.find(Status.class).distinct().results()) { messages.add((Status) status.castTo(Status.class)); } streamAccountUpdater.update(linkedin.asURI(), "/liveposts", messages); assertEquals(13, resourceStore.find(Status.class).distinct().results().size()); }
|
ProfileAccountUpdater extends AccountUpdaterBase implements AccountUpdater<PersonContact> { @Override public void update(URI accountUri, String path, PersonContact contact) throws AccountIntegrationException { logger.info("Updating "+path+" for "+accountUri+" with 1 contact."); URI accountPathGraph = getGraph(accountUri, path); removeResources(accountUri, path); if (path.contains("@me")) { PersonContact profile = (PersonContact) super.match(contact).castTo(PersonContact.class); profile.setPrefLabel(getProfilePrefLabel(profile, accountUri)); try { profile = profileEnricher.enrich(profile); } catch (DataMiningException e) { logger.error("Profile enrichment (fullname, postal address, etc.) failed for profile "+profile.asResource()+": "+e.getMessage(), e); } resourceStore.createOrUpdate(accountPathGraph, profile); if (!tripleStore.containsStatements(pimoService.getPimoUri(), pimoService.getUserUri(), PIMO.occurrence, profile)) { tripleStore.addStatement(pimoService.getPimoUri(), pimoService.getUserUri(), PIMO.occurrence, profile); } if (!tripleStore.containsStatements(accountPathGraph, profile.asResource(), NIE.dataSource, accountUri)) { tripleStore.addStatement(accountPathGraph, profile.asResource(), NIE.dataSource, accountUri); } } else { throw new RuntimeException("NOT YET IMPLEMENTED!"); } } ProfileAccountUpdater(ResourceStore resourceStore, PimoService pimoService); ProfileAccountUpdater(ResourceStore resourceStore, PimoService pimoService, ProfileEnricher profileEnricher); @Override void update(URI accountUri, String path, PersonContact contact); @Override void update(URI accountUri, String path, Collection<PersonContact> contacts); }
|
@Test public void testAddContacts() throws Exception { Account linkedin = modelFactory.getDAOFactory().createAccount("urn:service:linkedin"); linkedin.setPrefLabel("LinkedIn"); pimoService.create(linkedin); ResourceStore data = createResourceStore( this.getClass().getClassLoader().getResourceAsStream("account/linkedin-persons.ttl"), Syntax.Turtle); Collection<PersonContact> contacts = data.find(PersonContact.class).distinct().results(); updater.update(linkedin.asURI(), "/connections", contacts); PersonGroup accountGroup = resourceStore.find(PersonGroup.class).where(NIE.dataSource).is(linkedin).first(); assertNotNull(accountGroup); List<Agent> members = accountGroup.getAllMembers_as().asList(); assertEquals(2, members.size()); List<URI> uris = new LinkedList<URI>(); for (Thing m : members) uris.add(m.asURI()); Person anna = resourceStore.find(Person.class) .where(PIMO.groundingOccurrence).is(BasicQuery.X) .where(BasicQuery.X, NAO.externalIdentifier).is("9V7WOs5KHr") .first(); assertTrue(uris.contains(anna.asURI())); assertTrue(tripleStore.containsStatements(pimoService.getPimoUri(), pimoService.getUserUri(), FOAF.knows, anna)); Person norbert = resourceStore.find(Person.class) .where(PIMO.groundingOccurrence).is(BasicQuery.X) .where(BasicQuery.X, NAO.externalIdentifier).is("RYWVyGcfzR") .first(); assertTrue(uris.contains(norbert.asURI())); assertTrue(tripleStore.containsStatements(pimoService.getPimoUri(), pimoService.getUserUri(), FOAF.knows, norbert)); }
@Test public void testRepeatedUpdate() throws Exception { ResourceStore initialStore = createResourceStore( this.getClass().getClassLoader().getResourceAsStream("account/linkedin-connections-initial.ttl"), Syntax.Turtle); ResourceStore updatedStore = createResourceStore( this.getClass().getClassLoader().getResourceAsStream("account/linkedin-connections-updated.ttl"), Syntax.Turtle); Collection<PersonContact> initialContacts = initialStore.find(PersonContact.class).distinct().results(); Collection<PersonContact> updatedContacts = updatedStore.find(PersonContact.class).distinct().results(); Account linkedin = modelFactory.getDAOFactory().createAccount("urn:service:linkedin"); resourceStore.createOrUpdate(pimoService.getPimoUri(), linkedin); updater.update(linkedin.asURI(), "/connections", initialContacts); PersonContact initialContact = resourceStore.find(PersonContact.class).where(NAO.externalIdentifier).is("7N49Odr3Dk").first(); PersonName initialContactName = resourceStore.get(initialContact.getAllPersonName().next().asURI(), PersonName.class); assertEquals("Charlie", initialContactName.getNameGiven()); tripleStore.addStatement(pimoService.getPimoUri(), initialContact, NAO.hasTag, new URIImpl("urn:sometag")); updater.update(linkedin.asURI(), "/connections", updatedContacts); PersonContact updatedContact = resourceStore.find(PersonContact.class).where(NAO.externalIdentifier).is("7N49Odr3Dk").first(); PersonName updatedContactName = resourceStore.get(updatedContact.getAllPersonName().next().asURI(), PersonName.class); assertEquals(initialContact.asURI(), updatedContact.asURI()); assertEquals("Carmelo", updatedContactName.getNameGiven()); assertTrue(tripleStore.containsStatements(pimoService.getPimoUri(), updatedContact, NAO.hasTag, new URIImpl("urn:sometag"))); }
|
AuthenticationController { @POST @Produces(MediaType.APPLICATION_JSON) @Path("/credentials/{contact-said}") public Response<?> confirmCredentials( @PathParam("said") String saidLocal, @PathParam("contact-said") String saidRequester) { User user = userManager.getUserForAccountAndTenant(saidRequester, saidLocal); if (user == null) { return Response.badRequest("Useraccount was null", null); } User enabledUser = userManager.enable((user.getId())); if (enabledUser != null) { return Response.ok(); } else { return Response.badRequest("Useraccount was null", null); } } void setUserManager(UserManager userManager); void setAccessControlManager(AccessControlManager accessControlManager); @GET @Path("{userName}") @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") Response<AccountEntry> getUser(
@PathParam("userName") String userName); @POST @Path("{userName}")// can be @me - then updating the current user @Consumes(MediaType.APPLICATION_JSON + ";charset=UTF-8") @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") Response<AccountEntry> updateUser(
@PathParam("said") String said,
@PathParam("userName") String userName,
Request<AccountEntry> request); @DELETE @Path("{userName}") @Consumes(MediaType.APPLICATION_JSON + ";charset=UTF-8") @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") Response<AccountEntry> deleteAccount(Request<AccountEntry> request,
@PathParam("userName") String userName); @GET @Path("/username") String getCurrentUserName(); @GET @Path("/role") String getCurrentRole(); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/credentials/{contact-said}") Response<AccountEntry> getCredentials(
@PathParam("said") String saidLocal,
@PathParam("contact-said") String saidRequester); @POST @Produces(MediaType.APPLICATION_JSON) @Path("/credentials/{contact-said}") Response<?> confirmCredentials(
@PathParam("said") String saidLocal,
@PathParam("contact-said") String saidRequester); }
|
@Test public void testConfirmCredentials() { authenticationController.confirmCredentials("", ""); }
|
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } PostalAddressExtractor(); ResourceModel extract(ResourceModel postalAddress); }
|
@Test public void testEmptyPostalAddressExtraction() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI addr = model.createURI("urn:juan:loc36"); ResourceModel resourceModel = new ResourceModelImpl(addr); resourceModel.set(NAO.prefLabel, ""); postalAddressExtractor.extract(resourceModel); }
@Test public void testPostalAddressExtraction() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI addr = model.createURI("urn:juan:loc36"); ResourceModel resourceModel = new ResourceModelImpl(addr); resourceModel.set(NAO.prefLabel, "Galway, Ireland"); ResourceModel newResourceModel = postalAddressExtractor.extract(resourceModel); assertEquals("Galway", newResourceModel.get(NCO.locality)); assertEquals("Ireland", newResourceModel.get(NCO.country)); }
@Test public void testPostalAddressExtraction2() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI addr = model.createURI("urn:juan:loc36"); ResourceModel resourceModel = new ResourceModelImpl(addr); resourceModel.set(NAO.prefLabel, "Belfast, Northern Ireland, United Kingdom"); ResourceModel newResourceModel = postalAddressExtractor.extract(resourceModel); assertEquals("Belfast", newResourceModel.get(NCO.locality)); assertEquals("Northern Ireland", newResourceModel.get(NCO.country)); }
@Test public void testPostalAddressExtraction3() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI addr = model.createURI("urn:juan:loc36"); ResourceModel resourceModel = new ResourceModelImpl(addr); resourceModel.set(NAO.prefLabel, "Cumbria, England"); ResourceModel newResourceModel = postalAddressExtractor.extract(resourceModel); assertEquals("Cumbria", newResourceModel.get(NCO.region)); assertEquals("England", newResourceModel.get(NCO.country)); }
@Test public void testPostalAddressExtraction4() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI addr = model.createURI("urn:juan:loc36"); ResourceModel resourceModel = new ResourceModelImpl(addr); resourceModel.set(NAO.prefLabel, "Unit - 1019 PO Box 7169 Poole BH15 9EL"); ResourceModel newResourceModel = postalAddressExtractor.extract(resourceModel); assertEquals("PO Box 7169", newResourceModel.get(NCO.pobox)); assertEquals("BH15 9EL", newResourceModel.get(NCO.postalcode)); }
@Test public void testPostalAddressExtraction5() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI addr = model.createURI("urn:juan:loc36"); ResourceModel resourceModel = new ResourceModelImpl(addr); resourceModel.set(NAO.prefLabel, "10b St Marys Road, Barnet, NW11 9UG, LONDON, Great Britain"); ResourceModel newResourceModel = postalAddressExtractor.extract(resourceModel); assertEquals("10b St Marys Road", newResourceModel.get(NCO.streetAddress)); assertEquals("NW11 9UG", newResourceModel.get(NCO.postalcode)); assertEquals("LONDON", newResourceModel.get(NCO.locality)); assertEquals("Great Britain", newResourceModel.get(NCO.country)); }
@Test public void testPostalAddressExtraction6() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI addr = model.createURI("urn:juan:loc36"); ResourceModel resourceModel = new ResourceModelImpl(addr); resourceModel.set(NAO.prefLabel, "Mississippi, USA"); ResourceModel newResourceModel = postalAddressExtractor.extract(resourceModel); assertEquals("Mississippi", newResourceModel.get(NCO.region)); assertEquals("USA", newResourceModel.get(NCO.country)); }
@Test public void testPostalAddressExtraction7() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI addr = model.createURI("urn:juan:loc36"); ResourceModel resourceModel = new ResourceModelImpl(addr); resourceModel.set(NAO.prefLabel, "Mississippi, USA"); resourceModel.set(NCO.country, "United States"); ResourceModel newResourceModel = postalAddressExtractor.extract(resourceModel); assertEquals("Mississippi", newResourceModel.get(NCO.region)); assertEquals("United States", newResourceModel.get(NCO.country)); }
@Test public void testPostalAddressExtraction8() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI addr = model.createURI("urn:juan:loc36"); ResourceModel resourceModel = new ResourceModelImpl(addr); resourceModel.set(NAO.prefLabel, "Mississippi, USA"); resourceModel.set(NCO.country, ""); ResourceModel newResourceModel = postalAddressExtractor.extract(resourceModel); assertEquals("Mississippi", newResourceModel.get(NCO.region)); assertEquals("USA", newResourceModel.get(NCO.country)); }
|
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); ResourceModel extract(ResourceModel personName); }
|
@Test public void testEmptyFullnameExtraction() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI name = model.createURI("urn:juan:personName4"); ResourceModel resourceModel = new ResourceModelImpl(name); resourceModel.set(NCO.fullname, ""); fullnameExtractor.extract(resourceModel); }
@Test public void testFullnameExtraction() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI name = model.createURI("urn:juan:personName4"); ResourceModel resourceModel = new ResourceModelImpl(name); resourceModel.set(NCO.fullname, "Dr. John Doe Jr."); ResourceModel newResourceModel = fullnameExtractor.extract(resourceModel); assertEquals("Dr.", newResourceModel.get(NCO.nameHonorificPrefix)); assertEquals("John", newResourceModel.get(NCO.nameGiven)); assertEquals("Doe", newResourceModel.get(NCO.nameFamily)); assertEquals("Jr.", newResourceModel.get(NCO.nameHonorificSuffix)); assertEquals("male", newResourceModel.get(NCO.gender)); }
@Test public void testFullnameExtraction2() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI name = model.createURI("urn:juan:personName4"); ResourceModel resourceModel = new ResourceModelImpl(name); resourceModel.set(NCO.fullname, "John Doe-Smith"); ResourceModel newResourceModel = fullnameExtractor.extract(resourceModel); assertEquals("John", newResourceModel.get(NCO.nameGiven)); assertEquals("Doe-Smith", newResourceModel.get(NCO.nameFamily)); assertEquals("male", newResourceModel.get(NCO.gender)); }
@Test public void testFullnameExtraction3() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI name = model.createURI("urn:juan:personName4"); ResourceModel resourceModel = new ResourceModelImpl(name); resourceModel.set(NCO.fullname, "John O'Connell"); ResourceModel newResourceModel = fullnameExtractor.extract(resourceModel); assertEquals("John", newResourceModel.get(NCO.nameGiven)); assertEquals("O'Connell", newResourceModel.get(NCO.nameFamily)); assertEquals("male", newResourceModel.get(NCO.gender)); }
@Test public void testFullnameExtraction4() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI name = model.createURI("urn:juan:personName4"); ResourceModel resourceModel = new ResourceModelImpl(name); resourceModel.set(NCO.fullname, "John O'Connell-Smith"); ResourceModel newResourceModel = fullnameExtractor.extract(resourceModel); assertEquals("John", newResourceModel.get(NCO.nameGiven)); assertEquals("O'Connell-Smith", newResourceModel.get(NCO.nameFamily)); assertEquals("male", newResourceModel.get(NCO.gender)); }
@Test public void testFullnameExtraction5() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI name = model.createURI("urn:juan:personName4"); ResourceModel resourceModel = new ResourceModelImpl(name); resourceModel.set(NCO.fullname, "John O'Connell Smith"); ResourceModel newResourceModel = fullnameExtractor.extract(resourceModel); assertEquals("John", newResourceModel.get(NCO.nameGiven)); assertEquals("O'Connell Smith", newResourceModel.get(NCO.nameFamily)); assertEquals("male", newResourceModel.get(NCO.gender)); }
@Test public void testFullnameExtraction6() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI name = model.createURI("urn:juan:personName4"); ResourceModel resourceModel = new ResourceModelImpl(name); resourceModel.set(NCO.fullname, "Prof. John Smith"); ResourceModel newResourceModel = fullnameExtractor.extract(resourceModel); assertEquals("Prof.", newResourceModel.get(NCO.nameHonorificPrefix)); assertEquals("John", newResourceModel.get(NCO.nameGiven)); assertEquals("Smith", newResourceModel.get(NCO.nameFamily)); assertEquals("male", newResourceModel.get(NCO.gender)); }
@Test public void testFullnameExtraction7() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI name = model.createURI("urn:juan:personName4"); ResourceModel resourceModel = new ResourceModelImpl(name); resourceModel.set(NCO.fullname, "John Smith Sr."); ResourceModel newResourceModel = fullnameExtractor.extract(resourceModel); assertEquals("John", newResourceModel.get(NCO.nameGiven)); assertEquals("Smith", newResourceModel.get(NCO.nameFamily)); assertEquals("Sr.", newResourceModel.get(NCO.nameHonorificSuffix)); assertEquals("male", newResourceModel.get(NCO.gender)); }
@Test public void testFullnameExtraction8() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI name = model.createURI("urn:juan:personName4"); ResourceModel resourceModel = new ResourceModelImpl(name); resourceModel.set(NCO.fullname, "John Smith Sr."); resourceModel.set(NCO.nameHonorificSuffix, "Jr."); ResourceModel newResourceModel = fullnameExtractor.extract(resourceModel); assertEquals("John", newResourceModel.get(NCO.nameGiven)); assertEquals("Smith", newResourceModel.get(NCO.nameFamily)); assertEquals("Jr.", newResourceModel.get(NCO.nameHonorificSuffix)); assertEquals("male", newResourceModel.get(NCO.gender)); }
@Test public void testFullnameExtraction9() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI name = model.createURI("urn:juan:personName4"); ResourceModel resourceModel = new ResourceModelImpl(name); resourceModel.set(NCO.fullname, "John Smith Sr."); resourceModel.set(NCO.nameGiven, ""); resourceModel.set(NCO.nameHonorificSuffix, ""); ResourceModel newResourceModel = fullnameExtractor.extract(resourceModel); assertEquals("John", newResourceModel.get(NCO.nameGiven)); assertEquals("Smith", newResourceModel.get(NCO.nameFamily)); assertEquals("Sr.", newResourceModel.get(NCO.nameHonorificSuffix)); assertEquals("male", newResourceModel.get(NCO.gender)); }
@Test public void testFullnameExtraction10() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI name = model.createURI("urn:juan:personName4"); ResourceModel resourceModel = new ResourceModelImpl(name); resourceModel.set(NCO.fullname, "Ismael"); ResourceModel newResourceModel = fullnameExtractor.extract(resourceModel); assertEquals("Ismael", newResourceModel.get(NCO.nameGiven)); }
@Test public void testFullnameExtraction11() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI name = model.createURI("urn:juan:personName4"); ResourceModel resourceModel = new ResourceModelImpl(name); resourceModel.set(NCO.fullname, "Ismael Rivera"); resourceModel.set(NCO.nameGiven, ""); resourceModel.set(NCO.nameFamily, ""); ResourceModel newResourceModel = fullnameExtractor.extract(resourceModel); assertEquals("Ismael", newResourceModel.get(NCO.nameGiven)); assertEquals("Rivera", newResourceModel.get(NCO.nameFamily)); }
@Test public void testFullnameExtraction12() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI name = model.createURI("urn:juan:personName4"); ResourceModel resourceModel = new ResourceModelImpl(name); resourceModel.set(NCO.fullname, "Ismael 'Joe' Rivera"); ResourceModel newResourceModel = fullnameExtractor.extract(resourceModel); assertEquals("Ismael", newResourceModel.get(NCO.nameGiven)); assertEquals("'Joe'", newResourceModel.get(NCO.nameAdditional)); assertEquals("Rivera", newResourceModel.get(NCO.nameFamily)); }
@Test public void testFullnameExtraction13() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI name = model.createURI("urn:juan:personName4"); ResourceModel resourceModel = new ResourceModelImpl(name); resourceModel.set(NCO.fullname, "Jane O' Donnell"); ResourceModel newResourceModel = fullnameExtractor.extract(resourceModel); assertEquals("Jane", newResourceModel.get(NCO.nameGiven)); assertEquals("O' Donnell", newResourceModel.get(NCO.nameFamily)); assertEquals("female", newResourceModel.get(NCO.gender)); }
|
PSEvaluationController { @POST @Path("/@me") @Consumes(MediaType.APPLICATION_JSON + ";charset=UTF-8") @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") public Response<Evaluation> saveEvaluation(@PathParam("said") String said, Request<Evaluation> request) { try { RequestValidator.validateRequest(request); Data<Evaluation> data = request.getMessage().getData(); Evaluation ev = (Evaluation) data.getEntries().iterator().next(); User user = userManager.getCurrentUser(); boolean saved = false; if (userManager.validateUserCanLogEvaluationData(user)){ if (evaluationManager.saveEvaluation(ev, said)){ return Response.ok(data); }else{ return Response.serverError("Could not save evaluation due to invalid data. Check server logs", null); } } return Response.serverError("Evaluation not saved, evaluation omitted for user.", null); } catch (Exception e) { return Response.serverError(e.getMessage(), e); } } @Autowired void setEvaluationManager(EvaluationManager em); @Autowired void setUserManager(UserManager userManager); @POST @Path("/@me") @Consumes(MediaType.APPLICATION_JSON + ";charset=UTF-8") @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") Response<Evaluation> saveEvaluation(@PathParam("said") String said, Request<Evaluation> request); }
|
@Ignore @Test public void testSaveEvaluationOK(){ Request<Evaluation> request = buildSaveEvaluationRequest(); Response<Evaluation> response = controller.saveEvaluation(said, request); assertNotNull(response); Evaluation ev = response.getMessage().getData().getEntries().iterator().next(); assertNotNull(ev); assertEquals(ev.getTenantId(),"hashedTenant"); assertEquals(ev.getCreated(),12345678); assertEquals(ev.getClientId(),"0.1.1"); assertEquals(ev.getAction(),"add people to group"); assertEquals(ev.getCurrPlace(),"hashedPlace"); assertEquals(ev.getCurrSituationId(),"hashedSituation"); assertEquals(ev.getType(),"evaluation"); assertEquals(ev.getGuid(),"dumbGUID"); }
|
JSONLDUtils { public static <T extends Resource> T deserialize(Object object, Class<T> returnType) throws JsonParseException, JsonMappingException, JSONLDProcessingError { RDF2GoTripleCallback callback = new RDF2GoTripleCallback(); ModelSet modelSet = toRDF(object, callback); URI subject = null; ClosableIterator<Statement> statements = modelSet.findStatements(Variable.ANY, Variable.ANY, RDF.type, Variable.ANY); while (statements.hasNext()) { Statement statement = statements.next(); URI type = statement.getObject().asURI(); if (returnType.equals(guessClass(type))) { if (subject == null) { subject = statement.getSubject().asURI(); } else if (!subject.equals(statement.getSubject())) { throw new IllegalArgumentException("The following JSON contains more than one resource of type '" + returnType.getName() + "', please consider calling instead deserializeCollection(Object):\n" + JSONUtils.toString(object)); } } } statements.close(); if (subject == null) { throw new IllegalArgumentException("The following JSON does not contain any resource of type '" + returnType.getName() + "':\n" + JSONUtils.toString(object)); } Model resourceModel = RDF2Go.getModelFactory().createModel().open(); resourceModel.addAll(modelSet.iterator()); Resource resource = new Resource(resourceModel, subject, false); modelSet.close(); return (T) resource.castTo(returnType); } static T deserialize(Object object, Class<T> returnType); static T deserialize(String jsonObject, Class<T> returnType); @Deprecated static List<? extends Resource> deserializeCollection(List<Object> collection); @Deprecated static List<? extends Resource> deserializeCollection(String jsonArray); static Object serialize(T resource); static Object serialize(Map<String, String> prefixes, T resource); static String serializeAsString(T resource); static String serializeAsString(Map<String, String> prefixes, T resource); @Deprecated static List<Object> serializeCollection(T... collection); @Deprecated static List<Object> serializeCollection(Map<String, String> prefixes,
T... collection); }
|
@Test public void shouldDeserializeJSONLD() throws JsonParseException, JsonMappingException, JSONLDProcessingError { String json = "{`@graph`:[{`@id`:`urn:uuid:4182dcd4-a510-4b0c-8145-271a3dcfe455`,`@type`:[`http: PersonContact resource = JSONLDUtils.deserialize(json, PersonContact.class); Model metadata = resource.getModel(); URI profile = new URIImpl("urn:uuid:d030b056-cddd-4a8b-9828-a54dbca6495e"); URI email = new URIImpl("urn:uuid:4182dcd4-a510-4b0c-8145-271a3dcfe455"); assertEquals(profile, profile.asURI()); assertTrue("Must contain a nco:PersonContact resource", metadata.contains(profile, RDF.type, NCO.PersonContact)); assertEquals("Test", ModelUtils.findObject(metadata, profile, NAO.prefLabel).asLiteral().getValue()); assertTrue("Must contain a nco:EmailAddress resource", metadata.contains(email, RDF.type, NCO.EmailAddress)); assertEquals("test@email.com", ModelUtils.findObject(metadata, email, NCO.emailAddress).asLiteral().getValue()); }
@Test public void shouldDeserializedJSONLDWithContext() throws JsonParseException, JsonMappingException, JSONLDProcessingError { String json = "{`@context`:{`nao`:`http: PersonContact resource = JSONLDUtils.deserialize(json, PersonContact.class); Model metadata = resource.getModel(); URI profile = new URIImpl("urn:uuid:6c329b90-737d-46cd-ae2f-eb86cddea172"); URI email = new URIImpl("urn:uuid:4182dcd4-a510-4b0c-8145-271a3dcfe455"); assertEquals(profile, profile.asURI()); assertTrue("Must contain a nco:PersonContact resource", metadata.contains(profile, RDF.type, NCO.PersonContact)); assertEquals("Test Test", ModelUtils.findObject(metadata, profile, NAO.prefLabel).asLiteral().getValue()); assertTrue("Must contain a nco:EmailAddress resource", metadata.contains(email, RDF.type, NCO.EmailAddress)); assertEquals("test@email.com", ModelUtils.findObject(metadata, email, NCO.emailAddress).asLiteral().getValue()); }
@Test(expected=IllegalArgumentException.class) public void shouldRaiseErrorTwoObjectsSameType() throws JsonParseException, JsonMappingException, JSONLDProcessingError { String json = "{`@context`:{`nao`:`http: JSONLDUtils.deserialize(json, PersonContact.class); }
|
LocationContextUpdater implements LiveContextUpdater, IContextListener { @Override public void contextChanged(RawContextNotification notification) throws Exception { String name = notification.getName(); logger.debug("Current Place Raw Context notification received: " + name); StringTokenizer tok = new StringTokenizer(name,","); IEntity entity = Factory.createEntity(tok.nextToken()); IScope scope = Factory.createScope(tok.nextToken()); Tenant t = new Tenant(); t.setId(notification.getTenant()); IContextDataset dataset; try { dataset = this.contextProcessor.getContext(t,entity, scope); if (!dataset.equals(IContextDataset.EMPTY_CONTEXT_DATASET)) { IContextElement[] ces = dataset.getContextElements(scope); if (ces != null && ces.length == 1) { this.rawContextQueue.add(ces[0]); update(); } } } catch (ContextException e) { logger.error(e.toString()); } } void setContextProcessor(IContextProcessor contextProcessor); void setConnectionProvider(ConnectionProvider connectionProvider); void setTenantManager(TenantManager tenantManager); void setLocationManager(LocationManager locationManager); void setPlaceProcessor(PlaceProcessor placeProcessor); void init(); @Override void contextChanged(RawContextNotification notification); @Override void update(); }
|
@Test public void testUpdateCurrentPlace() { try { RawContextNotification notification = createNotification(user1, currentPlace); SpaTem spatem = liveContextService.get(SpaTem.class); ClosableIterator<Place> places = spatem.getAllCurrentPlace(); rawContextUpdater.contextChanged(notification); spatem = liveContextService.get(SpaTem.class); places = spatem.getAllCurrentPlace(); assertTrue(places.hasNext()); } catch (Exception e) { fail(e.getMessage()); } }
|
TimePeriodUpdater implements LiveContextUpdater { protected List<URI> findTimePeriods(ResourceStore resourceStore, Calendar when) { int hour = when.get(Calendar.HOUR_OF_DAY); int dayOfWeek = getDayOfWeekFromMonday(when); int dayOfMonth = when.get(Calendar.DAY_OF_MONTH); int weekOfYear = when.get(Calendar.WEEK_OF_YEAR); int month = when.get(Calendar.MONTH) + 1; int year = when.get(Calendar.YEAR); String query = StringUtils.strjoinNL( "PREFIX dpo: <http: "SELECT DISTINCT ?instance WHERE {", " {", " ?instance a dpo:TimePeriod ;", " dpo:minHour ?minHour ;", " dpo:maxHour ?maxHour .", " FILTER(?minHour <= "+hour+") .", " FILTER(?maxHour >= "+hour+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfWeek ?minDayOfWeek ;", " dpo:maxDayOfWeek ?maxDayOfWeek .", " FILTER(?minDayOfWeek <= "+dayOfWeek+") .", " FILTER(?maxDayOfWeek >= "+dayOfWeek+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfMonth ?minDayOfMonth ;", " dpo:maxDayOfMonth ?maxDayOfMonth .", " FILTER(?minDayOfMonth <= "+dayOfMonth+") .", " FILTER(?maxDayOfMonth >= "+dayOfMonth+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minWeek ?minWeek ;", " dpo:maxWeek ?maxWeek .", " FILTER(?minWeek <= "+weekOfYear+") .", " FILTER(?maxWeek >= "+weekOfYear+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minMonth ?minMonth ;", " dpo:maxMonth ?maxMonth .", " FILTER(?minMonth <= "+month+") .", " FILTER(?maxMonth >= "+month+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minYear ?minYear ;", " dpo:maxYear ?maxYear .", " FILTER(?minYear <= "+year+") .", " FILTER(?maxYear >= "+year+") .", " }", "}"); ClosableIterator<QueryRow> rows = resourceStore.sparqlSelect(query).iterator(); List<URI> results = new ArrayList<URI>(); while (rows.hasNext()) { results.add(rows.next().getValue("instance").asURI()); } return results; } void setConnectionProvider(ConnectionProvider connectionProvider); void setTenantManager(TenantManager tenantManager); @Override void update(); }
|
@Test public void testHour() throws Exception { assertTrue(timePeriodUpdater.findTimePeriods(this.resourceStore, MAY18AT1339).contains(AFTERNOON)); }
@Test public void testDayOfWeek() throws Exception { assertTrue(timePeriodUpdater.findTimePeriods(this.resourceStore, MAY18AT1339).contains(FRIDAY)); }
@Test public void testWeekend() throws Exception { assertFalse(timePeriodUpdater.findTimePeriods(this.resourceStore, MAY18AT1339).contains(WEEKEND)); assertTrue(timePeriodUpdater.findTimePeriods(this.resourceStore, MAY20AT0839).contains(WEEKEND)); }
@Test public void testFindTimePeriodsByWeek() throws Exception { assertTrue(timePeriodUpdater.findTimePeriods(this.resourceStore, MAY18AT1339).contains(WEEK20)); }
|
ActivityContextUpdater implements LiveContextUpdater, IContextListener { @Override public void contextChanged(RawContextNotification notification) throws Exception { String name = notification.getName(); logger.debug("Raw Activity Context notification received: " + name); StringTokenizer tok = new StringTokenizer(name,","); IEntity entity = Factory.createEntity(tok.nextToken()); IScope scope = Factory.createScope(tok.nextToken()); Tenant t = new Tenant(); t.setId(notification.getTenant()); IContextDataset dataset; try { dataset = this.contextProcessor.getContext(t,entity, scope); if (!dataset.equals(IContextDataset.EMPTY_CONTEXT_DATASET)) { IContextElement[] ces = dataset.getContextElements(scope); if (ces != null && ces.length == 1) { this.rawContextQueue.add(ces[0]); update(); } } } catch (ContextException e) { logger.error(e.toString()); } } void setContextProcessor(IContextProcessor contextProcessor); void setConnectionProvider(ConnectionProvider connectionProvider); void setTenantManager(TenantManager tenantManager); void init(); @Override void contextChanged(RawContextNotification notification); @Override void update(); }
|
@Test public void testUpdateActivity() { try { List<Node> activities = new ArrayList<Node>(); RawContextNotification notification = createNotification(user1,currentActivity); rawContextUpdater.contextChanged(notification); State state = liveContextService.get(State.class); ClosableIterator<Statement> currentIt = state.getModel().findStatements(state, DCON.currentActivity, Variable.ANY); while (currentIt.hasNext()) { Node object = currentIt.next().getObject(); if (object instanceof URI) { activities.add(object); } } currentIt.close(); assertTrue(activities.size() == 1); } catch (Exception e) { fail(e.getMessage()); } }
|
ActivityDetector implements IContextProvider { protected String getActivity(IEntity entity, IContextElement[] addrs) { if (addrs.length != 0) { int index = Utility.getFirstSignificativeItem(addrs,Defaults.ACTIVITY_PERIOD,Defaults.ACTIVITY_TOLERANCE); if (index == -1) { logger.debug("Received civil addresses are too recent to infer activity"); return ""; } else { logger.debug("Significative civil address for activity:"); for (int i=0; i<addrs.length; i++) { String prefix = ""; if (i <= index) prefix = "*" + i; else prefix = "" + i; logger.debug(prefix + " - " + (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue() + " " + (String)addrs[i].getMetadata().getMetadatumValue(Factory.createScope(Constants.SCOPE_METADATA_TIMESTAMP)).getValue()); } } String placeName = (String)addrs[0].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); for (int i=1; i<=index; i++) { String currentPlace = (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); if (!currentPlace.equalsIgnoreCase(placeName)) return ""; } return "@" + placeName; } return ""; } void setContextProcessor(IContextProcessor contextProcessor); void setServiceGateway(ServiceGateway serviceGateway); void setPolicyManager(PolicyManager policyManager); void setProviderManager(IProviderManager providerManager); void setAccountManager(AccountManager accountManager); void setPersonManager(PersonManager personManager); void setPersonGroupManager(PersonGroupManager personGroupManager); void setTenantManager(TenantManager tenantManager); void setUserManager(UserManager userManager); void init(); @Override IContextDataset getContext(Tenant t, IEntity entity, IScope scope,
IContextDataset inputContextDataset); }
|
@Test public void testActivityNoRecentData() { IContextElement[] addrs = { ContextHelper.createCivilAddress(System.currentTimeMillis() - ((15) * 1000), 600, "place1"), ContextHelper.createCivilAddress(System.currentTimeMillis() - ((Defaults.ACTIVITY_PERIOD + Defaults.ACTIVITY_TOLERANCE + 10) * 1000), 600, "place1") }; String activity = activityDetector.getActivity(Constants.ENTITY_ME,addrs); assertFalse((activity == null) || (!activity.equalsIgnoreCase(""))); }
@Test public void testActivityDifferentPlaces() { IContextElement[] addrs = { ContextHelper.createCivilAddress(System.currentTimeMillis() - ((15) * 1000), 600, "place1"), ContextHelper.createCivilAddress(System.currentTimeMillis() - ((180) * 1000), 600, "place2"), ContextHelper.createCivilAddress(System.currentTimeMillis() - ((Defaults.ACTIVITY_PERIOD + Defaults.ACTIVITY_TOLERANCE - 20) * 1000), 600, "place1"), ContextHelper.createCivilAddress(System.currentTimeMillis() - ((Defaults.ACTIVITY_PERIOD + Defaults.ACTIVITY_TOLERANCE + 10) * 1000), 600, "place1") }; String situation = activityDetector.getActivity(Constants.ENTITY_ME,addrs); assertFalse((situation == null) || (!situation.equalsIgnoreCase(""))); }
@Test public void testActivityOK() { IContextElement[] addrs = { ContextHelper.createCivilAddress(System.currentTimeMillis() - ((15) * 1000), 600, "place1"), ContextHelper.createCivilAddress(System.currentTimeMillis() - ((180) * 1000), 600, "place1"), ContextHelper.createCivilAddress(System.currentTimeMillis() - ((Defaults.ACTIVITY_PERIOD + Defaults.ACTIVITY_TOLERANCE - 20) * 1000), 600, "place1"), ContextHelper.createCivilAddress(System.currentTimeMillis() - ((Defaults.ACTIVITY_PERIOD + Defaults.ACTIVITY_TOLERANCE + 10) * 1000), 600, "place2") }; String situation = activityDetector.getActivity(Constants.ENTITY_ME,addrs); assertFalse((situation == null) || (!situation.equalsIgnoreCase("@place1"))); }
|
WiFiContextUpdater implements LiveContextUpdater, IContextListener { @Override public void contextChanged(RawContextNotification notification) throws Exception { String name = notification.getName(); logger.debug("Raw WiFi Context notification received: " + name); StringTokenizer tok = new StringTokenizer(name,","); IEntity entity = Factory.createEntity(tok.nextToken()); IScope scope = Factory.createScope(tok.nextToken()); Tenant t = new Tenant(); t.setId(notification.getTenant()); IContextDataset dataset; try { dataset = this.contextProcessor.getContext(t,entity, scope); if (!dataset.equals(IContextDataset.EMPTY_CONTEXT_DATASET)) { IContextElement[] ces = dataset.getContextElements(scope); if (ces != null && ces.length == 1) { this.rawContextQueue.add(ces[0]); update(); } } } catch (ContextException e) { logger.error(e.toString()); } } void setContextProcessor(IContextProcessor contextProcessor); void setConnectionProvider(ConnectionProvider connectionProvider); void setTenantManager(TenantManager tenantManager); void init(); @Override void contextChanged(RawContextNotification notification); @Override void update(); }
|
@Test public void testUpdateWifi() { try { Tenant t1 = entityFactory.buildTenant(); t1.setName(user1.getEntityIDAsString()); t1.setId(new Long(2)); RawContextNotification notification = createNotification(t1,user1,wifi); rawContextUpdater.contextChanged(notification); Connectivity conn = liveContextService.get(Connectivity.class); assertTrue(conn.getAllConnection().hasNext()); } catch (Exception e) { fail(e.getMessage()); } }
|
SharingNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } } SharingNotifier(); @Autowired void setLogEventManager(LogEventManager logEventManager); void setNotifierManager(NotifierManager notifierManager); void setConnectionProvider(ConnectionProvider connectionProvider); void setServiceGateway(ServiceGateway serviceGateway); @Override void onReceive(Event event); }
|
@Test public void testShareWithAccount() throws Exception { LivePost livePost = createLivePost("Hello sharing!", pimoService.getUser()); PrivacyPreference preference = modelFactory.getPPOFactory().createPrivacyPreference(); preference.setLabel(PrivacyPreferenceType.LIVEPOST.name()); preference.setCreator(pimoService.getUser()); preference.setAppliesToResource(livePost); AccessSpace accessSpace = modelFactory.getNSOFactory().createAccessSpace(); Account accountSender = createAccount("me@di.me", pimoService.getUser()); accessSpace.setSharedThrough(accountSender); Account accountR1B = createAccount("mancor@di.me", personR1); accessSpace.addIncludes(accountR1B); preference.addAccessSpace(accessSpace); preference.getModel().addAll(accessSpace.getModel().iterator()); tripleStore.addAll(pimoService.getPimoUri(), preference.getModel().iterator()); Event event = new Event(connection.getName(), Event.ACTION_RESOURCE_ADD, preference); notifier.onReceive(event); Set<URI> recipients = new HashSet<URI>(); recipients.add(accountR1B.asURI()); assertEquals(1, notifierManager.external.size()); DimeExternalNotification notification = notifierManager.external.get(0); assertEquals(livePost.toString(), notification.getItemID()); assertEquals(accountSender.toString(), notification.getSender()); assertEquals(accountR1B.toString(), notification.getTarget()); assertEquals(DimeExternalNotification.OP_SHARE, notification.getOperation()); assertEquals(Type.get(livePost).toString(), notification.getItemType()); }
@Test public void testShareWithPerson() throws Exception { LivePost livePost = createLivePost("Hello sharing!", pimoService.getUser()); PrivacyPreference preference = modelFactory.getPPOFactory().createPrivacyPreference(); preference.setLabel(PrivacyPreferenceType.LIVEPOST.name()); preference.setCreator(pimoService.getUser()); preference.setAppliesToResource(livePost); AccessSpace accessSpace = modelFactory.getNSOFactory().createAccessSpace(); accessSpace.setSharedThrough(accountSender); accessSpace.addIncludes(personR1); preference.addAccessSpace(accessSpace); preference.getModel().addAll(accessSpace.getModel().iterator()); tripleStore.addAll(pimoService.getPimoUri(), preference.getModel().iterator()); Event event = new Event(connection.getName(), Event.ACTION_RESOURCE_ADD, preference); notifier.onReceive(event); Set<URI> recipients = new HashSet<URI>(); recipients.add(accountR1.asURI()); assertEquals(1, notifierManager.external.size()); DimeExternalNotification notification = notifierManager.external.get(0); assertEquals(livePost.toString(), notification.getItemID()); assertEquals(accountSender.toString(), notification.getSender()); assertEquals(accountR1.toString(), notification.getTarget()); assertEquals(DimeExternalNotification.OP_SHARE, notification.getOperation()); assertEquals(Type.get(livePost).toString(), notification.getItemType()); }
@Test public void testShareWithGroup() throws Exception { LivePost livePost = createLivePost("Hello sharing!", pimoService.getUser()); PrivacyPreference preference = modelFactory.getPPOFactory().createPrivacyPreference(); preference.setLabel(PrivacyPreferenceType.LIVEPOST.name()); preference.setCreator(pimoService.getUser()); preference.setAppliesToResource(livePost); PersonGroup group = createPersonGroup("Friends", personR1, personR2); AccessSpace accessSpace = modelFactory.getNSOFactory().createAccessSpace(); accessSpace.setSharedThrough(accountSender); accessSpace.addIncludes(group); preference.addAccessSpace(accessSpace); preference.getModel().addAll(accessSpace.getModel().iterator()); tripleStore.addAll(pimoService.getPimoUri(), preference.getModel().iterator()); Event event = new Event(connection.getName(), Event.ACTION_RESOURCE_ADD, preference); notifier.onReceive(event); assertEquals(2, notifierManager.external.size()); }
@Test public void testShareWithGroupExcludeAccount() throws Exception { LivePost livePost = createLivePost("Hello sharing!", pimoService.getUser()); PrivacyPreference preference = modelFactory.getPPOFactory().createPrivacyPreference(); preference.setLabel(PrivacyPreferenceType.LIVEPOST.name()); preference.setCreator(pimoService.getUser()); preference.setAppliesToResource(livePost); PersonGroup group = createPersonGroup("Friends", personR1, personR2); AccessSpace accessSpace = modelFactory.getNSOFactory().createAccessSpace(); accessSpace.setSharedThrough(accountSender); accessSpace.addIncludes(group); accessSpace.addExcludes(accountR2); preference.addAccessSpace(accessSpace); preference.getModel().addAll(accessSpace.getModel().iterator()); tripleStore.addAll(pimoService.getPimoUri(), preference.getModel().iterator()); Event event = new Event(connection.getName(), Event.ACTION_RESOURCE_ADD, preference); notifier.onReceive(event); assertEquals(1, notifierManager.external.size()); DimeExternalNotification notification = notifierManager.external.get(0); assertEquals(accountSender.toString(), notification.getSender()); assertEquals(accountR1.toString(), notification.getTarget()); assertEquals(livePost.toString(), notification.getItemID()); assertEquals(DimeExternalNotification.OP_SHARE, notification.getOperation()); assertEquals(Type.get(livePost).toString(), notification.getItemType()); }
@Test public void testShareWithGroupExcludePerson() throws Exception { LivePost livePost = createLivePost("Hello sharing!", pimoService.getUser()); PrivacyPreference preference = modelFactory.getPPOFactory().createPrivacyPreference(); preference.setLabel(PrivacyPreferenceType.LIVEPOST.name()); preference.setCreator(pimoService.getUser()); preference.setAppliesToResource(livePost); PersonGroup group = createPersonGroup("Friends", personR1, personR2); AccessSpace accessSpace = modelFactory.getNSOFactory().createAccessSpace(); accessSpace.setSharedThrough(accountSender); accessSpace.addIncludes(group); accessSpace.addExcludes(personR1); preference.addAccessSpace(accessSpace); preference.getModel().addAll(accessSpace.getModel().iterator()); tripleStore.addAll(pimoService.getPimoUri(), preference.getModel().iterator()); Event event = new Event(connection.getName(), Event.ACTION_RESOURCE_ADD, preference); notifier.onReceive(event); assertEquals(1, notifierManager.external.size()); DimeExternalNotification notification = notifierManager.external.get(0); assertEquals(accountSender.toString(), notification.getSender()); assertEquals(accountR2.toString(), notification.getTarget()); assertEquals(livePost.toString(), notification.getItemID()); assertEquals(DimeExternalNotification.OP_SHARE, notification.getOperation()); assertEquals(Type.get(livePost).toString(), notification.getItemType()); }
@Test public void testShareWithGroupAndAddPerson() throws Exception { LivePost livePost = createLivePost("Hello sharing!", pimoService.getUser()); PrivacyPreference preference = modelFactory.getPPOFactory().createPrivacyPreference(); preference.setLabel(PrivacyPreferenceType.LIVEPOST.name()); preference.setCreator(pimoService.getUser()); preference.setAppliesToResource(livePost); PersonGroup group = createPersonGroup("Friends", personR1); AccessSpace accessSpace = modelFactory.getNSOFactory().createAccessSpace(); accessSpace.setSharedThrough(accountSender); accessSpace.addIncludes(group); preference.addAccessSpace(accessSpace); preference.getModel().addAll(accessSpace.getModel().iterator()); tripleStore.addAll(pimoService.getPimoUri(), preference.getModel().iterator()); DimeExternalNotification notification = null; Event event = null; event = new Event(connection.getName(), Event.ACTION_RESOURCE_ADD, preference); notifier.onReceive(event); assertEquals(1, notifierManager.external.size()); notification = notifierManager.external.get(0); assertEquals(livePost.toString(), notification.getItemID()); assertEquals(Type.LIVEPOST.toString(), notification.getItemType()); assertEquals(accountSender.toString(), notification.getSender()); assertEquals(accountR1.toString(), notification.getTarget()); tripleStore.addStatement(pimoService.getPimoUri(), livePost, NSO.sharedWith, personR1); group.addMember(personR2); tripleStore.addStatement(pimoService.getPimoUri(), group, PIMO.hasMember, personR2); notifierManager.external.clear(); event = new Event(connection.getName(), Event.ACTION_RESOURCE_MODIFY, group); notifier.onReceive(event); assertEquals(1, notifierManager.external.size()); notification = notifierManager.external.get(0); assertEquals(livePost.toString(), notification.getItemID()); assertEquals(Type.LIVEPOST.toString(), notification.getItemType()); assertEquals(accountSender.toString(), notification.getSender()); assertEquals(accountR2.toString(), notification.getTarget()); }
@Test public void testShareAndUpdateLivePost() throws Exception { LivePost livePost = createLivePost("Text updated!", pimoService.getUser()); PrivacyPreference preference = modelFactory.getPPOFactory().createPrivacyPreference(); preference.setLabel(PrivacyPreferenceType.LIVEPOST.name()); preference.setCreator(pimoService.getUser()); preference.setAppliesToResource(livePost); AccessSpace accessSpace = modelFactory.getNSOFactory().createAccessSpace(); accessSpace.setSharedThrough(accountSender); accessSpace.addIncludes(personR1); preference.addAccessSpace(accessSpace); preference.getModel().addAll(accessSpace.getModel().iterator()); tripleStore.addAll(pimoService.getPimoUri(), preference.getModel().iterator()); Event event = new Event(connection.getName(), Event.ACTION_RESOURCE_MODIFY, livePost); notifier.onReceive(event); assertEquals(1, notifierManager.external.size()); DimeExternalNotification notification = notifierManager.external.get(0); assertEquals(accountSender.toString(), notification.getSender()); assertEquals(accountR1.toString(), notification.getTarget()); assertEquals(livePost.toString(), notification.getItemID()); assertEquals(DimeExternalNotification.OP_SHARE, notification.getOperation()); assertEquals(Type.get(livePost).toString(), notification.getItemType()); }
|
CRUDNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { final String action = event.getAction(); if (!ArrayUtils.contains(ACTIONS, action)) { return; } final String itemId = event.getIdentifier().toString(); final Resource resource = event.getData(); if (NOTIFY_ACTIONS.containsKey(action)) { if (resource == null) { logger.debug("Impossible to find type of resource (no metadata provided in the event), no notification will be sent [item="+itemId+", action="+action+"]"); } else { final Type itemType = Type.get(resource); final ProfileAttributeType itemTypeProfileAttribute = ProfileAttributeType.get(resource); if (itemType == null && itemTypeProfileAttribute == null) { logger.debug("Type is undefined, no notification will be sent [item="+resource+", action="+action+"]"); return; } final String type = (itemTypeProfileAttribute == null) ? itemType.toString() : "profileattribute"; String creatorId = null; Node creator = ModelUtils.findObject(resource.getModel(), resource, NAO.creator); if (creator != null) { creatorId = creator.toString(); } final Long tenant = Long.parseLong(event.getTenant()); final String operation = NOTIFY_ACTIONS.get(action); if(operation.equals(DimeInternalNotification.OP_CREATE) || operation.equals(DimeInternalNotification.OP_REMOVE )) try { Node rdfType = ModelUtils.findObject(resource.getModel(), resource, RDF.type); if (rdfType != null && !rdfType.asURI().equals(PPO.PrivacyPreference)) logEventManager.setLog(operation, type,Tenant.find(tenant)); else if(type.equals("profilecard")) logEventManager.setLog(operation, type,Tenant.find(tenant)); } catch (EventLoggerException e) { logger.error("A sharing process could not be logged",e); } final SystemNotification notification = new SystemNotification(tenant, operation, itemId, type, creatorId); try { logger.debug("Pushing internal notification: "+notification.toString()); notifierManager.pushInternalNotification(notification); } catch (NotifierException e) { logger.error("Error while pushing notification ["+notification+"].", e); } } } } CRUDNotifier(); @Autowired void setLogEventManager(LogEventManager logEventManager); void setNotifierManager(NotifierManager notifierManager); @Override void onReceive(Event event); }
|
@Test public void testCreatePersonGroup() { PersonGroup group = modelFactory.getPIMOFactory().createPersonGroup(); group.setCreator(new URIImpl("urn:test")); Event event = new Event(connection.getName(), Event.ACTION_RESOURCE_ADD, group); notifier.onReceive(event); assertEquals(1, notifierManager.internal.size()); DimeInternalNotification notification = notifierManager.internal.get(0); assertEquals(group.asURI().toString(), notification.getItemID()); assertEquals(DimeInternalNotification.OP_CREATE, notification.getOperation()); assertEquals(Type.get(group).getLabel(), notification.getItemType()); }
@Test public void testUpdatePersonGroup() { PersonGroup group = modelFactory.getPIMOFactory().createPersonGroup(); group.setCreator(new URIImpl("urn:test")); Event event = new Event(connection.getName(), Event.ACTION_RESOURCE_MODIFY, group); notifier.onReceive(event); assertEquals(1, notifierManager.internal.size()); DimeInternalNotification notification = notifierManager.internal.get(0); assertEquals(group.asURI().toString(), notification.getItemID()); assertEquals(DimeInternalNotification.OP_UPDATE, notification.getOperation()); assertEquals(Type.get(group).getLabel(), notification.getItemType()); }
@Test public void testRemovePersonGroup() { PersonGroup group = modelFactory.getPIMOFactory().createPersonGroup(); group.setCreator(new URIImpl("urn:test")); Event event = new Event(connection.getName(), Event.ACTION_RESOURCE_DELETE, group); notifier.onReceive(event); assertEquals(1, notifierManager.internal.size()); DimeInternalNotification notification = notifierManager.internal.get(0); assertEquals(group.toString(), notification.getItemID()); assertEquals(DimeInternalNotification.OP_REMOVE, notification.getOperation()); assertEquals(Type.get(group).getLabel(), notification.getItemType()); }
|
AMETICDummyAdapter extends BasicAuthServiceAdapter implements ExternalServiceAdapter { public String getAdapterName() { return AMETICDummyAdapter.adapterName; } AMETICDummyAdapter(); String getAdapterName(); @Override void _set(String attribute, Object value); @Override void _delete(String attribute); @Override ServiceResponse[] getRaw(String attribute); @Override Boolean isConnected(); final static String adapterName; }
|
@Test public void testGetAdapterName() { AMETICDummyAdapter adapter; try { adapter = createAdapter(); assert (adapter.getAdapterName().equals("AMETICDummyAdapter")); } catch (ServiceNotAvailableException e) { e.printStackTrace(); fail ("Service not available: "+e.getMessage()); } }
|
AMETICDummyAdapter extends BasicAuthServiceAdapter implements ExternalServiceAdapter { @Override public ServiceResponse[] getRaw(String attribute) throws AttributeNotSupportedException, ServiceNotAvailableException, ServiceException { if (!this.isConnected()) { throw new ServiceNotAvailableException(); } AttributeMap attributeMap = new AttributeMap(); String genericAttribute = attributeMap.getAttribute(attribute); Map<String, String> ids = attributeMap.extractIds(genericAttribute, attribute); if (genericAttribute.equals(AttributeMap.EVENT_ATTENDEES)) { String url = "/ameticevents/" + ids.get(AttributeMap.EVENT_ID) + "/@all"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } else if (genericAttribute.equals(AttributeMap.EVENT_DETAILS)) { String url = "/ameticevents/" + ids.get(AttributeMap.EVENT_ID) + "/info"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } else if (genericAttribute.equals(AttributeMap.EVENT_ALL)) { String url = "/ameticevents/@all"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } throw new AttributeNotSupportedException(attribute, this); } AMETICDummyAdapter(); String getAdapterName(); @Override void _set(String attribute, Object value); @Override void _delete(String attribute); @Override ServiceResponse[] getRaw(String attribute); @Override Boolean isConnected(); final static String adapterName; }
|
@Test public void testGetRaw() throws Exception { AMETICDummyAdapter adapter = createAdapter(); ServiceResponse[] attendees = adapter.getRaw("/event/@me/173/@all"); assertTrue (attendees[0].getResponse().length() > 0); ServiceResponse[] eventDetails = adapter.getRaw("/event/@me/173"); assertTrue (eventDetails[0].getResponse().length() > 0); ServiceResponse[] allEvents = adapter.getRaw("/event/@all"); assertTrue (allEvents[0].getResponse().length() > 0); }
@Test public void testRegister() throws Exception { AMETICDummyAdapter adapter = createAdapter(); adapter.register("ameticadmin", "ameticpass"); ServiceResponse[] attendees = adapter.getRaw("/event/@me/173/@all"); assertTrue (attendees[0].getResponse().length() > 0); }
|
DMNDomainValidatorImpl implements DMNDomainValidator { @Override public String getDefinitionSetId() { return BindableAdapterUtils.getDefinitionSetId(DMNDefinitionSet.class); } @Inject DMNDomainValidatorImpl(final DMNMarshallerStandalone dmnMarshaller,
final DMNDiagramUtils dmnDiagramUtils,
final DMNMarshallerImportsHelperStandalone importsHelper,
final DMNIOHelper dmnIOHelper); @PostConstruct void setupValidator(); @Override String getDefinitionSetId(); @Override @SuppressWarnings("unchecked") void validate(final Diagram diagram,
final Consumer<Collection<DomainViolation>> resultConsumer); @Override Collection<DomainViolation> validate(final Diagram diagram,
final String diagramXml); }
|
@Test public void testGetDefinitionSetId() { assertThat(domainValidator.getDefinitionSetId()).isEqualTo(DMNDefinitionSet.class.getName()); }
|
RendererUtils { public static Group getCenteredCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell) { final GridRenderer gridRenderer = context.getRenderer(); final GridRendererTheme theme = gridRenderer.getTheme(); final Group g = GWT.create(Group.class); String value = gridCell.getValue().getValue(); final Text t; if (!StringUtils.isEmpty(value)) { t = theme.getBodyText(); } else { value = gridCell.getValue().getPlaceHolder(); t = theme.getPlaceholderText(); } t.setText(value); t.setListening(false); t.setX(context.getCellWidth() / 2); t.setY(context.getCellHeight() / 2); g.add(t); return g; } static Group getExpressionCellText(final GridBodyCellRenderContext context,
final GridCell<String> gridCell); static Group getCenteredCellText(final GridBodyCellRenderContext context,
final GridCell<String> gridCell); static Group getNameAndDataTypeCellText(final InformationItemCell.HasNameAndDataTypeCell hasNameAndDataTypeCell,
final GridBodyCellRenderContext context); static Group getExpressionHeaderText(final EditableHeaderMetaData headerMetaData,
final GridHeaderColumnRenderContext context); static Group getValueAndDataTypeHeaderText(final ValueAndDataTypeHeaderMetaData headerMetaData,
final GridHeaderColumnRenderContext context,
final double blockWidth,
final double blockHeight); static Group getEditableHeaderText(final EditableHeaderMetaData headerMetaData,
final GridHeaderColumnRenderContext context,
final double blockWidth,
final double blockHeight); static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData,
final GridHeaderColumnRenderContext context,
final double blockWidth,
final double blockHeight); static double getExpressionTextLineHeight(final GridRendererTheme theme); static final double EXPRESSION_TEXT_PADDING; static final String FONT_STYLE_TYPE_REF; static final double SPACING; }
|
@Test public void testRenderCenteredEmptyTextWithPlaceHolder() throws Exception { final BaseGridCell<String> cell = new BaseGridCell<>(new BaseGridCellValue<>(null, PLACE_HOLDER)); RendererUtils.getCenteredCellText(cellContext, cell); assertCenteredRenderingPlaceholder(placeHolderText); }
@Test public void testRenderCenteredText() throws Exception { final BaseGridCell<String> cell = new BaseGridCell<>(new BaseGridCellValue<>(VALUE)); RendererUtils.getCenteredCellText(cellContext, cell); assertCenteredRendering(text); assertNotRenderedPlaceHolder(placeHolderText); }
|
RendererUtils { public static Group getExpressionCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell) { final GridRenderer gridRenderer = context.getRenderer(); final GridRendererTheme theme = gridRenderer.getTheme(); return getExpressionText(theme, gridCell.getValue().getValue()); } static Group getExpressionCellText(final GridBodyCellRenderContext context,
final GridCell<String> gridCell); static Group getCenteredCellText(final GridBodyCellRenderContext context,
final GridCell<String> gridCell); static Group getNameAndDataTypeCellText(final InformationItemCell.HasNameAndDataTypeCell hasNameAndDataTypeCell,
final GridBodyCellRenderContext context); static Group getExpressionHeaderText(final EditableHeaderMetaData headerMetaData,
final GridHeaderColumnRenderContext context); static Group getValueAndDataTypeHeaderText(final ValueAndDataTypeHeaderMetaData headerMetaData,
final GridHeaderColumnRenderContext context,
final double blockWidth,
final double blockHeight); static Group getEditableHeaderText(final EditableHeaderMetaData headerMetaData,
final GridHeaderColumnRenderContext context,
final double blockWidth,
final double blockHeight); static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData,
final GridHeaderColumnRenderContext context,
final double blockWidth,
final double blockHeight); static double getExpressionTextLineHeight(final GridRendererTheme theme); static final double EXPRESSION_TEXT_PADDING; static final String FONT_STYLE_TYPE_REF; static final double SPACING; }
|
@Test public void testRenderExpressionCellText() throws Exception { final BaseGridCell<String> cell = new BaseGridCell<>(new BaseGridCellValue<>(VALUE)); RendererUtils.getExpressionCellText(cellContext, cell); assertExpressionRendering(); }
|
RendererUtils { public static Group getExpressionHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context) { final GridRenderer gridRenderer = context.getRenderer(); final GridRendererTheme theme = gridRenderer.getTheme(); return getExpressionText(theme, headerMetaData.getTitle()); } static Group getExpressionCellText(final GridBodyCellRenderContext context,
final GridCell<String> gridCell); static Group getCenteredCellText(final GridBodyCellRenderContext context,
final GridCell<String> gridCell); static Group getNameAndDataTypeCellText(final InformationItemCell.HasNameAndDataTypeCell hasNameAndDataTypeCell,
final GridBodyCellRenderContext context); static Group getExpressionHeaderText(final EditableHeaderMetaData headerMetaData,
final GridHeaderColumnRenderContext context); static Group getValueAndDataTypeHeaderText(final ValueAndDataTypeHeaderMetaData headerMetaData,
final GridHeaderColumnRenderContext context,
final double blockWidth,
final double blockHeight); static Group getEditableHeaderText(final EditableHeaderMetaData headerMetaData,
final GridHeaderColumnRenderContext context,
final double blockWidth,
final double blockHeight); static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData,
final GridHeaderColumnRenderContext context,
final double blockWidth,
final double blockHeight); static double getExpressionTextLineHeight(final GridRendererTheme theme); static final double EXPRESSION_TEXT_PADDING; static final String FONT_STYLE_TYPE_REF; static final double SPACING; }
|
@Test public void testRenderExpressionHeaderText() throws Exception { when(headerMetaData.getTitle()).thenReturn(VALUE); RendererUtils.getExpressionHeaderText(headerMetaData, headerContext); assertExpressionRendering(); }
|
RendererUtils { public static Group getValueAndDataTypeHeaderText(final ValueAndDataTypeHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight) { return getNameAndDataTypeText(context.getRenderer().getTheme(), headerMetaData.getTitle(), headerMetaData.getTypeRef(), blockWidth, blockHeight); } static Group getExpressionCellText(final GridBodyCellRenderContext context,
final GridCell<String> gridCell); static Group getCenteredCellText(final GridBodyCellRenderContext context,
final GridCell<String> gridCell); static Group getNameAndDataTypeCellText(final InformationItemCell.HasNameAndDataTypeCell hasNameAndDataTypeCell,
final GridBodyCellRenderContext context); static Group getExpressionHeaderText(final EditableHeaderMetaData headerMetaData,
final GridHeaderColumnRenderContext context); static Group getValueAndDataTypeHeaderText(final ValueAndDataTypeHeaderMetaData headerMetaData,
final GridHeaderColumnRenderContext context,
final double blockWidth,
final double blockHeight); static Group getEditableHeaderText(final EditableHeaderMetaData headerMetaData,
final GridHeaderColumnRenderContext context,
final double blockWidth,
final double blockHeight); static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData,
final GridHeaderColumnRenderContext context,
final double blockWidth,
final double blockHeight); static double getExpressionTextLineHeight(final GridRendererTheme theme); static final double EXPRESSION_TEXT_PADDING; static final String FONT_STYLE_TYPE_REF; static final double SPACING; }
|
@Test public void testRenderHeaderContentWithNameAndDataTypeHeaderMetaData() { final ValueAndDataTypeHeaderMetaData metaData = mock(ValueAndDataTypeHeaderMetaData.class); when(metaData.getTitle()).thenReturn(TITLE); when(metaData.getTypeRef()).thenReturn(TYPE_REF); RendererUtils.getValueAndDataTypeHeaderText(metaData, headerContext, BLOCK_WIDTH, ROW_HEIGHT); assertHasNameAndDataTypeRendering(); }
|
RendererUtils { public static Group getNameAndDataTypeCellText(final InformationItemCell.HasNameAndDataTypeCell hasNameAndDataTypeCell, final GridBodyCellRenderContext context) { if (!hasNameAndDataTypeCell.hasData()) { final BaseGridCellValue<String> cell = new BaseGridCellValue<>(null, hasNameAndDataTypeCell.getPlaceHolderText()); return getCenteredCellText(context, new BaseGridCell<>(cell)); } return getNameAndDataTypeText(context.getRenderer().getTheme(), hasNameAndDataTypeCell.getName().getValue(), hasNameAndDataTypeCell.getTypeRef(), context.getCellWidth(), context.getCellHeight()); } static Group getExpressionCellText(final GridBodyCellRenderContext context,
final GridCell<String> gridCell); static Group getCenteredCellText(final GridBodyCellRenderContext context,
final GridCell<String> gridCell); static Group getNameAndDataTypeCellText(final InformationItemCell.HasNameAndDataTypeCell hasNameAndDataTypeCell,
final GridBodyCellRenderContext context); static Group getExpressionHeaderText(final EditableHeaderMetaData headerMetaData,
final GridHeaderColumnRenderContext context); static Group getValueAndDataTypeHeaderText(final ValueAndDataTypeHeaderMetaData headerMetaData,
final GridHeaderColumnRenderContext context,
final double blockWidth,
final double blockHeight); static Group getEditableHeaderText(final EditableHeaderMetaData headerMetaData,
final GridHeaderColumnRenderContext context,
final double blockWidth,
final double blockHeight); static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData,
final GridHeaderColumnRenderContext context,
final double blockWidth,
final double blockHeight); static double getExpressionTextLineHeight(final GridRendererTheme theme); static final double EXPRESSION_TEXT_PADDING; static final String FONT_STYLE_TYPE_REF; static final double SPACING; }
|
@Test public void testRenderHeaderContentWithInformationItemCell() { final InformationItemCell.HasNameAndDataTypeCell informationItemCell = mock(InformationItemCell.HasNameAndDataTypeCell.class); final Name name = new Name(TITLE); when(informationItemCell.getName()).thenReturn(name); when(informationItemCell.getTypeRef()).thenReturn(TYPE_REF); when(informationItemCell.hasData()).thenReturn(true); RendererUtils.getNameAndDataTypeCellText(informationItemCell, bodyContext); assertHasNameAndDataTypeRendering(); }
|
RendererUtils { public static Group getEditableHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight) { final Group headerGroup = GWT.create(Group.class); final GridRenderer renderer = context.getRenderer(); final GridRendererTheme theme = renderer.getTheme(); final Text text = theme.getHeaderText(); final String value = headerMetaData.getTitle(); text.setX(blockWidth / 2); text.setY(blockHeight / 2); text.setText(value); text.setListening(false); headerGroup.add(text); return headerGroup; } static Group getExpressionCellText(final GridBodyCellRenderContext context,
final GridCell<String> gridCell); static Group getCenteredCellText(final GridBodyCellRenderContext context,
final GridCell<String> gridCell); static Group getNameAndDataTypeCellText(final InformationItemCell.HasNameAndDataTypeCell hasNameAndDataTypeCell,
final GridBodyCellRenderContext context); static Group getExpressionHeaderText(final EditableHeaderMetaData headerMetaData,
final GridHeaderColumnRenderContext context); static Group getValueAndDataTypeHeaderText(final ValueAndDataTypeHeaderMetaData headerMetaData,
final GridHeaderColumnRenderContext context,
final double blockWidth,
final double blockHeight); static Group getEditableHeaderText(final EditableHeaderMetaData headerMetaData,
final GridHeaderColumnRenderContext context,
final double blockWidth,
final double blockHeight); static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData,
final GridHeaderColumnRenderContext context,
final double blockWidth,
final double blockHeight); static double getExpressionTextLineHeight(final GridRendererTheme theme); static final double EXPRESSION_TEXT_PADDING; static final String FONT_STYLE_TYPE_REF; static final double SPACING; }
|
@Test public void testRenderEditableHeaderText() { when(headerMetaData.getTitle()).thenReturn(VALUE); RendererUtils.getEditableHeaderText(headerMetaData, headerContext, WIDTH, HEIGHT); assertCenteredRendering(headerText1); }
|
RendererUtils { public static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight) { final Group headerGroup = GWT.create(Group.class); headerMetaData.getPlaceHolder().ifPresent(placeHolder -> { final GridRenderer renderer = context.getRenderer(); final GridRendererTheme theme = renderer.getTheme(); final Text text = theme.getPlaceholderText(); text.setX(blockWidth / 2); text.setY(blockHeight / 2); text.setText(placeHolder); text.setListening(false); headerGroup.add(text); }); return headerGroup; } static Group getExpressionCellText(final GridBodyCellRenderContext context,
final GridCell<String> gridCell); static Group getCenteredCellText(final GridBodyCellRenderContext context,
final GridCell<String> gridCell); static Group getNameAndDataTypeCellText(final InformationItemCell.HasNameAndDataTypeCell hasNameAndDataTypeCell,
final GridBodyCellRenderContext context); static Group getExpressionHeaderText(final EditableHeaderMetaData headerMetaData,
final GridHeaderColumnRenderContext context); static Group getValueAndDataTypeHeaderText(final ValueAndDataTypeHeaderMetaData headerMetaData,
final GridHeaderColumnRenderContext context,
final double blockWidth,
final double blockHeight); static Group getEditableHeaderText(final EditableHeaderMetaData headerMetaData,
final GridHeaderColumnRenderContext context,
final double blockWidth,
final double blockHeight); static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData,
final GridHeaderColumnRenderContext context,
final double blockWidth,
final double blockHeight); static double getExpressionTextLineHeight(final GridRendererTheme theme); static final double EXPRESSION_TEXT_PADDING; static final String FONT_STYLE_TYPE_REF; static final double SPACING; }
|
@Test public void testRenderEditableHeaderPlaceHolderText() { when(headerMetaData.getPlaceHolder()).thenReturn(Optional.of(VALUE)); RendererUtils.getEditableHeaderPlaceHolderText(headerMetaData, headerContext, WIDTH, HEIGHT); assertCenteredRendering(placeHolderText); }
@Test public void testRenderEditableHeaderPlaceHolderTextWhenEmpty() { when(headerMetaData.getPlaceHolder()).thenReturn(Optional.empty()); RendererUtils.getEditableHeaderPlaceHolderText(headerMetaData, headerContext, WIDTH, HEIGHT); verify(headerGroup, never()).add(any(IPrimitive.class)); }
|
DynamicReadOnlyUtils { public static boolean isOnlyVisualChangeAllowed(final GridWidget gridWidget) { if (gridWidget instanceof BaseGrid) { final BaseGrid baseGrid = (BaseGrid) gridWidget; return baseGrid.isOnlyVisualChangeAllowed(); } return false; } static boolean isOnlyVisualChangeAllowed(final GridWidget gridWidget); }
|
@Test public void testGridWidget() { assertThat(DynamicReadOnlyUtils.isOnlyVisualChangeAllowed(mock(GridWidget.class))).isFalse(); }
@Test public void testBaseGrid() { when(gridWidget.isOnlyVisualChangeAllowed()).thenReturn(false); assertThat(DynamicReadOnlyUtils.isOnlyVisualChangeAllowed(gridWidget)).isFalse(); }
@Test public void testBaseGridWhenOnlyVisualChangeAllowed() { when(gridWidget.isOnlyVisualChangeAllowed()).thenReturn(true); assertThat(DynamicReadOnlyUtils.isOnlyVisualChangeAllowed(gridWidget)).isTrue(); }
|
DMNParseServiceImpl implements DMNParseService { @Override public List<String> parseFEELList(final String source) { return parse(source) .map(this::getTextElements) .orElseGet(ArrayList::new); } @Override List<String> parseFEELList(final String source); @Override RangeValue parseRangeValue(final String source); }
|
@Test public void testParseFEELListMultipleCommasInside() { final List<String> actualList = service.parseFEELList("\"Sao Paulo, SP, South America\",\"New York, NY, North America\""); final List<String> expectedList = asList("\"Sao Paulo, SP, South America\"", "\"New York, NY, North America\""); assertEquals(expectedList, actualList); }
@Test public void testParseFEELListWithARegularNumberList() { final List<String> actualList = service.parseFEELList("1, 2, 3"); final List<String> expectedList = asList("1", "2", "3"); assertEquals(expectedList, actualList); }
@Test public void testParseFEELListWithARegularStringList() { final List<String> actualList = service.parseFEELList("\"Sao Paulo, SP\", \"Campinas, SP\", \"Rio de Janeiro, RJ\""); final List<String> expectedList = asList("\"Sao Paulo, SP\"", "\"Campinas, SP\"", "\"Rio de Janeiro, RJ\""); assertEquals(expectedList, actualList); }
@Test public void testParseFEELListWithAnArbitraryValue() { final List<String> actualList = service.parseFEELList("aaabbbcccdddeee"); final List<String> expectedList = singletonList("aaabbbcccdddeee"); assertEquals(expectedList, actualList); }
@Test public void testParseFEELListWithASemicolon() { final List<String> actualList = service.parseFEELList("abcdef, \"Sao Paulo, SP\"; 123"); final List<String> expectedList = asList("abcdef", "\"Sao Paulo, SP\""); assertEquals(expectedList, actualList); }
@Test public void testParseFEELListWithASpecialCharacter() { final List<String> actualList = service.parseFEELList("%20C"); final List<String> expectedList = emptyList(); assertEquals(expectedList, actualList); }
|
SelectionUtils { public static boolean isMultiSelect(final GridData uiModel) { return uiModel.getSelectedCells().size() > 1; } static boolean isMultiSelect(final GridData uiModel); static boolean isMultiRow(final GridData uiModel); static boolean isMultiColumn(final GridData uiModel); static boolean isMultiHeaderColumn(final GridData uiModel); }
|
@Test public void testIsMultiSelectZeroSelections() { assertThat(SelectionUtils.isMultiSelect(uiModel)).isFalse(); }
@Test public void testIsMultiSelectSingleSelection() { uiModel.selectCell(0, 0); assertThat(SelectionUtils.isMultiSelect(uiModel)).isFalse(); }
@Test public void testIsMultiSelectMultipleSelections() { uiModel.selectCell(0, 0); uiModel.selectCell(0, 1); assertThat(SelectionUtils.isMultiSelect(uiModel)).isTrue(); }
|
SelectionUtils { public static boolean isMultiRow(final GridData uiModel) { return uiModel.getSelectedCells() .stream() .map(GridData.SelectedCell::getRowIndex) .distinct() .collect(Collectors.toList()) .size() > 1; } static boolean isMultiSelect(final GridData uiModel); static boolean isMultiRow(final GridData uiModel); static boolean isMultiColumn(final GridData uiModel); static boolean isMultiHeaderColumn(final GridData uiModel); }
|
@Test public void testIsMultiRowZeroSelections() { assertThat(SelectionUtils.isMultiRow(uiModel)).isFalse(); }
@Test public void testIsMultiRowSingleSelection() { uiModel.selectCell(0, 0); assertThat(SelectionUtils.isMultiRow(uiModel)).isFalse(); }
@Test public void testIsMultiRowMultipleSelections() { uiModel.selectCell(0, 0); uiModel.selectCell(1, 0); assertThat(SelectionUtils.isMultiRow(uiModel)).isTrue(); }
|
SelectionUtils { public static boolean isMultiColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedCells()); } static boolean isMultiSelect(final GridData uiModel); static boolean isMultiRow(final GridData uiModel); static boolean isMultiColumn(final GridData uiModel); static boolean isMultiHeaderColumn(final GridData uiModel); }
|
@Test public void testIsMultiColumnZeroSelections() { assertThat(SelectionUtils.isMultiColumn(uiModel)).isFalse(); }
@Test public void testIsMultiColumnSingleSelection() { uiModel.selectCell(0, 0); assertThat(SelectionUtils.isMultiColumn(uiModel)).isFalse(); }
@Test public void testIsMultiColumnMultipleSelections() { uiModel.selectCell(0, 0); uiModel.selectCell(0, 1); assertThat(SelectionUtils.isMultiColumn(uiModel)).isTrue(); }
|
DMNMarshallerStandalone implements DiagramMarshaller<Graph, Metadata, Diagram<Graph, Metadata>> { @Override @SuppressWarnings("unchecked") public Graph unmarshall(final Metadata metadata, final InputStream input) throws IOException { final Map<String, HasComponentWidths> hasComponentWidthsMap = new HashMap<>(); final BiConsumer<String, HasComponentWidths> hasComponentWidthsConsumer = (uuid, hcw) -> { if (Objects.nonNull(uuid)) { hasComponentWidthsMap.put(uuid, hcw); } }; final org.kie.dmn.model.api.Definitions dmnXml = marshaller.unmarshal(new InputStreamReader(input)); final List<org.kie.dmn.model.api.DRGElement> diagramDrgElements = dmnXml.getDrgElement(); final Optional<org.kie.dmn.model.api.dmndi.DMNDiagram> dmnDDDiagram = findDMNDiagram(dmnXml); final Map<Import, org.kie.dmn.model.api.Definitions> importDefinitions = dmnMarshallerImportsHelper.getImportDefinitions(metadata, dmnXml.getImport()); final Map<Import, PMMLDocumentMetadata> pmmlDocuments = dmnMarshallerImportsHelper.getPMMLDocuments(metadata, dmnXml.getImport()); final List<DMNShape> dmnShapes = dmnDDDiagram.map(this::getUniqueDMNShapes).orElse(emptyList()); final List<org.kie.dmn.model.api.DRGElement> importedDrgElements = getImportedDrgElementsByShape(dmnShapes, importDefinitions); final List<org.kie.dmn.model.api.DRGElement> drgElements = new ArrayList<>(); drgElements.addAll(diagramDrgElements); drgElements.addAll(importedDrgElements); removeDrgElementsWithoutShape(drgElements, dmnShapes); final Map<String, Entry<org.kie.dmn.model.api.DRGElement, Node>> elems = drgElements.stream().collect(toMap(org.kie.dmn.model.api.DRGElement::getId, dmn -> new SimpleEntry<>(dmn, dmnToStunner(dmn, hasComponentWidthsConsumer, importedDrgElements)))); final Set<org.kie.dmn.model.api.DecisionService> dmnDecisionServices = new HashSet<>(); for (Entry<org.kie.dmn.model.api.DRGElement, Node> kv : elems.values()) { ddExtAugmentStunner(dmnDDDiagram, kv.getValue()); } for (Entry<org.kie.dmn.model.api.DRGElement, Node> kv : elems.values()) { final org.kie.dmn.model.api.DRGElement elem = kv.getKey(); final Node currentNode = kv.getValue(); if (isImportedDRGElement(importedDrgElements, elem)) { continue; } if (elem instanceof org.kie.dmn.model.api.Decision) { final org.kie.dmn.model.api.Decision decision = (org.kie.dmn.model.api.Decision) elem; for (org.kie.dmn.model.api.InformationRequirement ir : decision.getInformationRequirement()) { connectEdgeToNodes(INFO_REQ_ID, ir, ir.getRequiredInput(), elems, dmnXml, currentNode); connectEdgeToNodes(INFO_REQ_ID, ir, ir.getRequiredDecision(), elems, dmnXml, currentNode); } for (org.kie.dmn.model.api.KnowledgeRequirement kr : decision.getKnowledgeRequirement()) { connectEdgeToNodes(KNOWLEDGE_REQ_ID, kr, kr.getRequiredKnowledge(), elems, dmnXml, currentNode); } for (org.kie.dmn.model.api.AuthorityRequirement ar : decision.getAuthorityRequirement()) { connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredAuthority(), elems, dmnXml, currentNode); } } else if (elem instanceof org.kie.dmn.model.api.BusinessKnowledgeModel) { final org.kie.dmn.model.api.BusinessKnowledgeModel bkm = (org.kie.dmn.model.api.BusinessKnowledgeModel) elem; for (org.kie.dmn.model.api.KnowledgeRequirement kr : bkm.getKnowledgeRequirement()) { connectEdgeToNodes(KNOWLEDGE_REQ_ID, kr, kr.getRequiredKnowledge(), elems, dmnXml, currentNode); } for (org.kie.dmn.model.api.AuthorityRequirement ar : bkm.getAuthorityRequirement()) { connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredAuthority(), elems, dmnXml, currentNode); } } else if (elem instanceof org.kie.dmn.model.api.KnowledgeSource) { final org.kie.dmn.model.api.KnowledgeSource ks = (org.kie.dmn.model.api.KnowledgeSource) elem; for (org.kie.dmn.model.api.AuthorityRequirement ar : ks.getAuthorityRequirement()) { connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredInput(), elems, dmnXml, currentNode); connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredDecision(), elems, dmnXml, currentNode); connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredAuthority(), elems, dmnXml, currentNode); } } else if (elem instanceof org.kie.dmn.model.api.DecisionService) { final org.kie.dmn.model.api.DecisionService ds = (org.kie.dmn.model.api.DecisionService) elem; dmnDecisionServices.add(ds); for (org.kie.dmn.model.api.DMNElementReference er : ds.getEncapsulatedDecision()) { final String reqInputID = getId(er); final Node requiredNode = getRequiredNode(elems, reqInputID); if (Objects.nonNull(requiredNode)) { connectDSChildEdge(currentNode, requiredNode); } } for (org.kie.dmn.model.api.DMNElementReference er : ds.getOutputDecision()) { final String reqInputID = getId(er); final Node requiredNode = getRequiredNode(elems, reqInputID); if (Objects.nonNull(requiredNode)) { connectDSChildEdge(currentNode, requiredNode); } } } } final Map<String, Node<View<TextAnnotation>, ?>> textAnnotations = dmnXml.getArtifact().stream() .filter(org.kie.dmn.model.api.TextAnnotation.class::isInstance) .map(org.kie.dmn.model.api.TextAnnotation.class::cast) .collect(Collectors.toMap(org.kie.dmn.model.api.TextAnnotation::getId, dmn -> textAnnotationConverter.nodeFromDMN(dmn, hasComponentWidthsConsumer))); textAnnotations.values().forEach(n -> ddExtAugmentStunner(dmnDDDiagram, n)); final List<org.kie.dmn.model.api.Association> associations = dmnXml.getArtifact().stream() .filter(org.kie.dmn.model.api.Association.class::isInstance) .map(org.kie.dmn.model.api.Association.class::cast) .collect(Collectors.toList()); for (org.kie.dmn.model.api.Association a : associations) { final String sourceId = getId(a.getSourceRef()); final Node sourceNode = Optional.ofNullable(elems.get(sourceId)).map(Entry::getValue).orElse(textAnnotations.get(sourceId)); final String targetId = getId(a.getTargetRef()); final Node targetNode = Optional.ofNullable(elems.get(targetId)).map(Entry::getValue).orElse(textAnnotations.get(targetId)); @SuppressWarnings("unchecked") final Edge<View<Association>, ?> myEdge = (Edge<View<Association>, ?>) factoryManager.newElement(idOfDMNorWBUUID(a), ASSOCIATION_ID).asEdge(); final Id id = new Id(a.getId()); final Description description = new Description(a.getDescription()); final Association definition = new Association(id, description); myEdge.getContent().setDefinition(definition); connectEdge(myEdge, sourceNode, targetNode); setConnectionMagnets(myEdge, a.getId(), dmnXml); } for (Entry<org.kie.dmn.model.api.DRGElement, Node> kv : elems.values()) { PointUtils.convertToRelativeBounds(kv.getValue()); } final Graph graph = factoryManager.newDiagram("prova", BindableAdapterUtils.getDefinitionSetId(DMNDefinitionSet.class), metadata).getGraph(); elems.values().stream().map(Map.Entry::getValue).forEach(graph::addNode); textAnnotations.values().forEach(graph::addNode); final Node<?, ?> dmnDiagramRoot = findDMNDiagramRoot(graph); final Definitions definitionsStunnerPojo = DefinitionsConverter.wbFromDMN(dmnXml, importDefinitions, pmmlDocuments); loadImportedItemDefinitions(definitionsStunnerPojo, importDefinitions); ((View<DMNDiagram>) dmnDiagramRoot.getContent()).getDefinition().setDefinitions(definitionsStunnerPojo); final List<String> references = new ArrayList<>(); dmnDecisionServices.forEach(ds -> references.addAll(ds.getEncapsulatedDecision().stream().map(org.kie.dmn.model.api.DMNElementReference::getHref).collect(Collectors.toList()))); dmnDecisionServices.forEach(ds -> references.addAll(ds.getOutputDecision().stream().map(org.kie.dmn.model.api.DMNElementReference::getHref).collect(Collectors.toList()))); final Map<org.kie.dmn.model.api.DRGElement, Node> elemsToConnectToRoot = elems.values().stream() .filter(elem -> !references.contains("#" + elem.getKey().getId())) .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); elemsToConnectToRoot.values().stream() .forEach(node -> connectRootWithChild(dmnDiagramRoot, node)); textAnnotations.values().stream().forEach(node -> connectRootWithChild(dmnDiagramRoot, node)); final Optional<ComponentsWidthsExtension> extension = findComponentsWidthsExtension(dmnDDDiagram); extension.ifPresent(componentsWidthsExtension -> { if (componentsWidthsExtension.getComponentsWidths() != null) { hasComponentWidthsMap.forEach((uuid, hasComponentWidths) -> componentsWidthsExtension .getComponentsWidths() .stream() .filter(componentWidths -> componentWidths.getDmnElementRef().getLocalPart().equals(uuid)) .findFirst() .ifPresent(componentWidths -> { final List<Double> widths = hasComponentWidths.getComponentWidths(); widths.clear(); widths.addAll(componentWidths.getWidths()); })); } }); return graph; } protected DMNMarshallerStandalone(); @Inject DMNMarshallerStandalone(final XMLEncoderDiagramMetadataMarshaller diagramMetadataMarshaller,
final FactoryManager factoryManager,
final DMNMarshallerImportsHelperStandalone dmnMarshallerImportsHelper,
final DMNMarshaller marshaller); @Override @SuppressWarnings("unchecked") Graph unmarshall(final Metadata metadata,
final InputStream input); static Node<?, ?> findDMNDiagramRoot(final Graph<?, Node<View, ?>> graph); @SuppressWarnings({"rawtypes", "unchecked"}) static void connectRootWithChild(final Node dmnDiagramRoot,
final Node child); @SuppressWarnings({"rawtypes", "unchecked"}) static void connectEdge(final Edge edge,
final Node source,
final Node target); @Override @SuppressWarnings("unchecked") String marshall(final Diagram<Graph, Metadata> diagram); @Override DiagramMetadataMarshaller<Metadata> getMetadataMarshaller(); static final String INFO_REQ_ID; static final String KNOWLEDGE_REQ_ID; static final String AUTH_REQ_ID; static final String ASSOCIATION_ID; }
|
@Test public void test_function_java_WB_model() throws IOException { final DMNMarshallerStandalone m = getDMNMarshaller(); @SuppressWarnings("unchecked") final Graph<?, Node<?, ?>> g = m.unmarshall(createMetadata(), this.getClass().getResourceAsStream("/DROOLS-2372.dmn")); final Stream<Node<?, ?>> stream = StreamSupport.stream(Spliterators.spliteratorUnknownSize(g.nodes().iterator(), Spliterator.ORDERED), false); final Optional<Decision> wbDecision = stream .filter(n -> n.getContent() instanceof ViewImpl) .map(n -> (ViewImpl) n.getContent()) .filter(n -> n.getDefinition() instanceof Decision) .map(n -> (Decision) n.getDefinition()) .findFirst(); wbDecision.ifPresent(d -> { assertTrue(d.getExpression() instanceof FunctionDefinition); final FunctionDefinition wbFunction = (FunctionDefinition) d.getExpression(); assertEquals(FunctionDefinition.Kind.JAVA, wbFunction.getKind()); }); final DMNRuntime runtime = roundTripUnmarshalMarshalThenUnmarshalDMN(this.getClass().getResourceAsStream("/DROOLS-2372.dmn")); final DMNModel dmnModel = runtime.getModels().get(0); final BusinessKnowledgeModelNode bkmNode = dmnModel.getBusinessKnowledgeModels().iterator().next(); final org.kie.dmn.model.api.FunctionDefinition dmnFunction = bkmNode.getBusinessKnowledModel().getEncapsulatedLogic(); assertEquals(FunctionKind.JAVA, dmnFunction.getKind()); }
|
SelectionUtils { public static boolean isMultiHeaderColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedHeaderCells()); } static boolean isMultiSelect(final GridData uiModel); static boolean isMultiRow(final GridData uiModel); static boolean isMultiColumn(final GridData uiModel); static boolean isMultiHeaderColumn(final GridData uiModel); }
|
@Test public void testIsMultiHeaderColumnZeroSelections() { assertThat(SelectionUtils.isMultiHeaderColumn(uiModel)).isFalse(); }
@Test public void testIsMultiHeaderColumnSingleSelection() { uiModel.selectHeaderCell(0, 0); assertThat(SelectionUtils.isMultiHeaderColumn(uiModel)).isFalse(); }
@Test public void testIsMultiHeaderColumnMultipleSelections() { uiModel.selectHeaderCell(0, 0); uiModel.selectHeaderCell(0, 1); assertThat(SelectionUtils.isMultiHeaderColumn(uiModel)).isTrue(); }
|
NameUtils { public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; } private NameUtils(); static String normaliseName(final String name); }
|
@Test public void testNull() { assertThat(NameUtils.normaliseName(null)).isEmpty(); }
@Test public void testEmpty() { assertThat(NameUtils.normaliseName("")).isEmpty(); }
@Test public void testLeadingWhitespace() { assertThat(NameUtils.normaliseName(" hello")).isEqualTo("hello"); }
@Test public void testTrailingWhitespace() { assertThat(NameUtils.normaliseName("hello ")).isEqualTo("hello"); }
@Test public void testCompactWhitespace() { assertThat(NameUtils.normaliseName("hello world")).isEqualTo("hello world"); }
@Test public void testCompleteNormalisation() { assertThat(NameUtils.normaliseName(" hello world ")).isEqualTo("hello world"); }
|
TypeRefUtils { public static <E extends Expression> HasTypeRef getTypeRefOfExpression(final E expression, final HasExpression hasExpression) { HasTypeRef hasTypeRef = expression; final DMNModelInstrumentedBase base = hasExpression.asDMNModelInstrumentedBase(); if (base instanceof HasVariable) { final HasVariable hasVariable = (HasVariable) base; hasTypeRef = hasVariable.getVariable(); } return hasTypeRef; } static HasTypeRef getTypeRefOfExpression(final E expression,
final HasExpression hasExpression); }
|
@Test public void testGetTypeRefOfExpression() { when(hasExpression.asDMNModelInstrumentedBase()).thenReturn(mock(DMNModelInstrumentedBase.class)); when(expression.getTypeRef()).thenReturn(TYPE_REF); assertThat(TypeRefUtils.getTypeRefOfExpression(expression, hasExpression).getTypeRef()).isEqualTo(TYPE_REF); }
@Test public void testGetTypeRefOfExpressionWhenHasExpressionHasVariable() { when(hasExpression.asDMNModelInstrumentedBase()).thenReturn(decision); when(decision.getVariable()).thenReturn(decisionVariable); when(decisionVariable.getTypeRef()).thenReturn(TYPE_REF); assertThat(TypeRefUtils.getTypeRefOfExpression(expression, hasExpression).getTypeRef()).isEqualTo(TYPE_REF); }
|
DMNMarshallerStandalone implements DiagramMarshaller<Graph, Metadata, Diagram<Graph, Metadata>> { List<org.kie.dmn.model.api.DRGElement> getImportedDrgElementsByShape(final List<DMNShape> dmnShapes, final Map<Import, org.kie.dmn.model.api.Definitions> importDefinitions) { final List<org.kie.dmn.model.api.DRGElement> importedDRGElements = dmnMarshallerImportsHelper.getImportedDRGElements(importDefinitions); return dmnShapes .stream() .map(shape -> { final String dmnElementRef = getDmnElementRef(shape); final Optional<org.kie.dmn.model.api.DRGElement> ref = getReference(importedDRGElements, dmnElementRef); return ref.orElse(null); }) .filter(Objects::nonNull) .collect(Collectors.toList()); } protected DMNMarshallerStandalone(); @Inject DMNMarshallerStandalone(final XMLEncoderDiagramMetadataMarshaller diagramMetadataMarshaller,
final FactoryManager factoryManager,
final DMNMarshallerImportsHelperStandalone dmnMarshallerImportsHelper,
final DMNMarshaller marshaller); @Override @SuppressWarnings("unchecked") Graph unmarshall(final Metadata metadata,
final InputStream input); static Node<?, ?> findDMNDiagramRoot(final Graph<?, Node<View, ?>> graph); @SuppressWarnings({"rawtypes", "unchecked"}) static void connectRootWithChild(final Node dmnDiagramRoot,
final Node child); @SuppressWarnings({"rawtypes", "unchecked"}) static void connectEdge(final Edge edge,
final Node source,
final Node target); @Override @SuppressWarnings("unchecked") String marshall(final Diagram<Graph, Metadata> diagram); @Override DiagramMetadataMarshaller<Metadata> getMetadataMarshaller(); static final String INFO_REQ_ID; static final String KNOWLEDGE_REQ_ID; static final String AUTH_REQ_ID; static final String ASSOCIATION_ID; }
|
@Test public void testGetImportedDrgElementsByShape() { final DMNMarshallerStandalone marshaller = spy(getDMNMarshaller()); final List<org.kie.dmn.model.api.DRGElement> importedDRGElements = mock(List.class); final Map<Import, org.kie.dmn.model.api.Definitions> importDefinitions = mock(Map.class); final org.kie.dmn.model.api.DRGElement ref1 = mock(org.kie.dmn.model.api.DRGElement.class); final org.kie.dmn.model.api.DRGElement ref2 = mock(org.kie.dmn.model.api.DRGElement.class); final org.kie.dmn.model.api.DRGElement ref3 = mock(org.kie.dmn.model.api.DRGElement.class); final List<DMNShape> dmnShapes = new ArrayList<>(); final DMNShape shape1 = mock(DMNShape.class); final DMNShape shape2 = mock(DMNShape.class); final DMNShape shape3 = mock(DMNShape.class); dmnShapes.add(shape1); dmnShapes.add(shape2); dmnShapes.add(shape3); doReturn("REF1").when(marshaller).getDmnElementRef(shape1); doReturn("REF2").when(marshaller).getDmnElementRef(shape2); doReturn("REF3").when(marshaller).getDmnElementRef(shape3); when(dmnMarshallerImportsHelper.getImportedDRGElements(importDefinitions)).thenReturn(importedDRGElements); doReturn(Optional.of(ref1)).when(marshaller).getReference(importedDRGElements, "REF1"); doReturn(Optional.of(ref2)).when(marshaller).getReference(importedDRGElements, "REF2"); doReturn(Optional.of(ref3)).when(marshaller).getReference(importedDRGElements, "REF3"); final List<DRGElement> actual = marshaller.getImportedDrgElementsByShape(dmnShapes, importDefinitions); assertEquals(ref1, actual.get(0)); assertEquals(ref2, actual.get(1)); assertEquals(ref3, actual.get(2)); }
|
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { @Override public void bind(final DMNSession session) { final ExpressionEditorView.Presenter editor = makeExpressionEditor(view, decisionNavigator, dmnGraphUtils, dmnDiagramsSession); editor.bind(session); this.session = Optional.of(session); this.expressionEditor = Optional.of(editor); this.refreshEditorDomainObjectListener = new RefreshEditorDomainObjectListener(session); session.getCanvasHandler().addDomainObjectListener(refreshEditorDomainObjectListener); } @Inject ExpressionEditorControlImpl(final ExpressionEditorView view,
final DecisionNavigatorPresenter decisionNavigator,
final DMNGraphUtils dmnGraphUtils,
final DMNDiagramsSession dmnDiagramsSession,
final Event<CanvasElementUpdatedEvent> canvasElementUpdatedEvent,
final DRDNameChanger drdNameChanger); @Override void bind(final DMNSession session); @Override ExpressionEditorView.Presenter getExpressionEditor(); @SuppressWarnings("unused") void onCanvasFocusedSelectionEvent(final @Observes CanvasSelectionEvent event); void onCanvasElementUpdated(final @Observes CanvasElementUpdatedEvent event); }
|
@Test public void testBind() { control.bind(session); assertNotNull(control.getExpressionEditor()); verify(editor).bind(session); verify(canvasHandler).addDomainObjectListener(any(CanvasDomainObjectListener.class)); }
@Test public void testBindDomainObjectListenerWithNodeMatch() { final Definition definition = mock(Definition.class); when(graph.nodes()).thenReturn(Collections.singletonList(node)); when(node.getContent()).thenReturn(definition); when(definition.getDefinition()).thenReturn(domainObject); when(domainObject.getDomainObjectUUID()).thenReturn("uuid"); control.bind(session); verify(canvasHandler).addDomainObjectListener(domainObjectListenerCaptor.capture()); final CanvasDomainObjectListener domainObjectListener = domainObjectListenerCaptor.getValue(); domainObjectListener.update(domainObject); verify(canvasElementUpdatedEvent).fire(canvasElementUpdatedEventCaptor.capture()); final CanvasElementUpdatedEvent canvasElementUpdatedEvent = canvasElementUpdatedEventCaptor.getValue(); assertThat(canvasElementUpdatedEvent.getCanvasHandler()).isEqualTo(canvasHandler); assertThat(canvasElementUpdatedEvent.getElement()).isEqualTo(node); }
@Test public void testBindDomainObjectListenerWithNoNodeMatch() { when(graph.nodes()).thenReturn(Collections.emptyList()); control.bind(session); verify(canvasHandler).addDomainObjectListener(domainObjectListenerCaptor.capture()); final CanvasDomainObjectListener domainObjectListener = domainObjectListenerCaptor.getValue(); domainObjectListener.update(domainObject); verify(canvasElementUpdatedEvent, never()).fire(any(CanvasElementUpdatedEvent.class)); }
|
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { @Override protected void doInit() { } @Inject ExpressionEditorControlImpl(final ExpressionEditorView view,
final DecisionNavigatorPresenter decisionNavigator,
final DMNGraphUtils dmnGraphUtils,
final DMNDiagramsSession dmnDiagramsSession,
final Event<CanvasElementUpdatedEvent> canvasElementUpdatedEvent,
final DRDNameChanger drdNameChanger); @Override void bind(final DMNSession session); @Override ExpressionEditorView.Presenter getExpressionEditor(); @SuppressWarnings("unused") void onCanvasFocusedSelectionEvent(final @Observes CanvasSelectionEvent event); void onCanvasElementUpdated(final @Observes CanvasElementUpdatedEvent event); }
|
@Test public void testDoInit() { assertNull(control.getExpressionEditor()); control.doInit(); assertNull(control.getExpressionEditor()); }
|
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { @Override protected void doDestroy() { view = null; decisionNavigator = null; session.ifPresent(s -> s.getCanvasHandler().removeDomainObjectListener(refreshEditorDomainObjectListener)); session = Optional.empty(); expressionEditor = Optional.empty(); } @Inject ExpressionEditorControlImpl(final ExpressionEditorView view,
final DecisionNavigatorPresenter decisionNavigator,
final DMNGraphUtils dmnGraphUtils,
final DMNDiagramsSession dmnDiagramsSession,
final Event<CanvasElementUpdatedEvent> canvasElementUpdatedEvent,
final DRDNameChanger drdNameChanger); @Override void bind(final DMNSession session); @Override ExpressionEditorView.Presenter getExpressionEditor(); @SuppressWarnings("unused") void onCanvasFocusedSelectionEvent(final @Observes CanvasSelectionEvent event); void onCanvasElementUpdated(final @Observes CanvasElementUpdatedEvent event); }
|
@Test public void testDoDestroy() { control.bind(session); verify(canvasHandler).addDomainObjectListener(domainObjectListenerCaptor.capture()); control.doDestroy(); assertNull(control.getExpressionEditor()); final CanvasDomainObjectListener domainObjectListener = domainObjectListenerCaptor.getValue(); verify(canvasHandler).removeDomainObjectListener(domainObjectListener); }
|
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { @SuppressWarnings("unused") public void onCanvasFocusedSelectionEvent(final @Observes CanvasSelectionEvent event) { session.ifPresent(s -> { if (Objects.equals(s.getCanvasHandler(), event.getCanvasHandler())) { expressionEditor.ifPresent(ExpressionEditorView.Presenter::exit); } }); } @Inject ExpressionEditorControlImpl(final ExpressionEditorView view,
final DecisionNavigatorPresenter decisionNavigator,
final DMNGraphUtils dmnGraphUtils,
final DMNDiagramsSession dmnDiagramsSession,
final Event<CanvasElementUpdatedEvent> canvasElementUpdatedEvent,
final DRDNameChanger drdNameChanger); @Override void bind(final DMNSession session); @Override ExpressionEditorView.Presenter getExpressionEditor(); @SuppressWarnings("unused") void onCanvasFocusedSelectionEvent(final @Observes CanvasSelectionEvent event); void onCanvasElementUpdated(final @Observes CanvasElementUpdatedEvent event); }
|
@Test public void testOnCanvasFocusedSelectionEventWhenNotBound() { control.onCanvasFocusedSelectionEvent(event); verifyNoMoreInteractions(editor); }
|
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { public void onCanvasElementUpdated(final @Observes CanvasElementUpdatedEvent event) { expressionEditor.ifPresent(editor -> editor.handleCanvasElementUpdated(event)); } @Inject ExpressionEditorControlImpl(final ExpressionEditorView view,
final DecisionNavigatorPresenter decisionNavigator,
final DMNGraphUtils dmnGraphUtils,
final DMNDiagramsSession dmnDiagramsSession,
final Event<CanvasElementUpdatedEvent> canvasElementUpdatedEvent,
final DRDNameChanger drdNameChanger); @Override void bind(final DMNSession session); @Override ExpressionEditorView.Presenter getExpressionEditor(); @SuppressWarnings("unused") void onCanvasFocusedSelectionEvent(final @Observes CanvasSelectionEvent event); void onCanvasElementUpdated(final @Observes CanvasElementUpdatedEvent event); }
|
@Test public void testOnCanvasElementUpdated() { control.bind(session); final CanvasElementUpdatedEvent event = new CanvasElementUpdatedEvent(canvasHandler, node); control.onCanvasElementUpdated(event); verify(editor).handleCanvasElementUpdated(event); }
|
ExpressionContainerUIModelMapper extends BaseUIModelMapper<Expression> { @Override public void fromDMNModel(final int rowIndex, final int columnIndex) { final String uuid = nodeUUID.get(); final GridData uiModel = this.uiModel.get(); final Optional<Expression> expression = dmnModel.get(); final Optional<HasName> hasName = this.hasName.get(); final boolean isOnlyVisualChangeAllowed = this.isOnlyVisualChangeAllowedSupplier.get(); final HasExpression hasExpression = this.hasExpression.get(); final Optional<ExpressionEditorDefinition<Expression>> expressionEditorDefinition = expressionEditorDefinitions.get().getExpressionEditorDefinition(expression); expressionEditorDefinition.ifPresent(definition -> { Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> editor = expressionGridCache.get().getExpressionGrid(uuid); if (!editor.isPresent()) { final Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> oEditor = definition.getEditor(parent, Optional.of(uuid), hasExpression, hasName, isOnlyVisualChangeAllowed, 0); expressionGridCache.get().putExpressionGrid(uuid, oEditor); editor = oEditor; } final Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> _editor = editor; uiModel.setCell(0, 0, () -> new ContextGridCell<>(new ExpressionCellValue(_editor), listSelector)); }); } ExpressionContainerUIModelMapper(final GridCellTuple parent,
final Supplier<GridData> uiModel,
final Supplier<Optional<Expression>> dmnModel,
final Supplier<String> nodeUUID,
final Supplier<HasExpression> hasExpression,
final Supplier<Optional<HasName>> hasName,
final Supplier<Boolean> isOnlyVisualChangeAllowedSupplier,
final Supplier<ExpressionEditorDefinitions> expressionEditorDefinitions,
final Supplier<ExpressionGridCache> expressionGridCache,
final ListSelectorView.Presenter listSelector); @Override void fromDMNModel(final int rowIndex,
final int columnIndex); @Override void toDMNModel(final int rowIndex,
final int columnIndex,
final Supplier<Optional<GridCellValue<?>>> cell); }
|
@Test public void testFromDMNModelUndefinedExpressionType() { setup(false); expression = null; mapper.fromDMNModel(0, 0); assertFromDMNModelUndefinedExpressionType(false); }
@Test public void testFromDMNModelWhenOnlyVisualChangeAllowed() { setup(true); expression = null; mapper.fromDMNModel(0, 0); assertFromDMNModelUndefinedExpressionType(true); }
@Test @SuppressWarnings("unchecked") public void testFromDMNModelLiteralExpressionType() { setup(false); expression = new LiteralExpression(); mapper.fromDMNModel(0, 0); assertUiModel(); assertEditorType(literalExpressionEditor.getClass()); verify(literalExpressionEditorDefinition).getEditor(eq(parent), nodeUUIDCaptor.capture(), eq(hasExpression), eq(Optional.of(hasName)), eq(false), eq(0)); final Optional<String> nodeUUID = nodeUUIDCaptor.getValue(); assertThat(nodeUUID.isPresent()).isTrue(); assertThat(nodeUUID.get()).isEqualTo(NODE_UUID); }
@Test @SuppressWarnings("unchecked") public void testFromDMNModelExpressionGridCacheIsHit() { setup(false); expression = new LiteralExpression(); mapper.fromDMNModel(0, 0); verify(literalExpressionEditorDefinition).getEditor(eq(parent), nodeUUIDCaptor.capture(), eq(hasExpression), eq(Optional.of(hasName)), eq(false), eq(0)); verify(expressionGridCache).putExpressionGrid(nodeUUIDCaptor.getValue().get(), Optional.of(literalExpressionEditor)); mapper.fromDMNModel(0, 0); verify(literalExpressionEditorDefinition).getEditor(any(GridCellTuple.class), any(Optional.class), any(HasExpression.class), any(Optional.class), anyBoolean(), anyInt()); verify(expressionGridCache).putExpressionGrid(anyString(), any(Optional.class)); }
|
DMNMarshallerStandalone implements DiagramMarshaller<Graph, Metadata, Diagram<Graph, Metadata>> { String getDmnElementRef(final DMNShape dmnShape) { return Optional .ofNullable(dmnShape.getDmnElementRef()) .map(QName::getLocalPart) .orElse(""); } protected DMNMarshallerStandalone(); @Inject DMNMarshallerStandalone(final XMLEncoderDiagramMetadataMarshaller diagramMetadataMarshaller,
final FactoryManager factoryManager,
final DMNMarshallerImportsHelperStandalone dmnMarshallerImportsHelper,
final DMNMarshaller marshaller); @Override @SuppressWarnings("unchecked") Graph unmarshall(final Metadata metadata,
final InputStream input); static Node<?, ?> findDMNDiagramRoot(final Graph<?, Node<View, ?>> graph); @SuppressWarnings({"rawtypes", "unchecked"}) static void connectRootWithChild(final Node dmnDiagramRoot,
final Node child); @SuppressWarnings({"rawtypes", "unchecked"}) static void connectEdge(final Edge edge,
final Node source,
final Node target); @Override @SuppressWarnings("unchecked") String marshall(final Diagram<Graph, Metadata> diagram); @Override DiagramMetadataMarshaller<Metadata> getMetadataMarshaller(); static final String INFO_REQ_ID; static final String KNOWLEDGE_REQ_ID; static final String AUTH_REQ_ID; static final String ASSOCIATION_ID; }
|
@Test public void testGetDmnElementRef() { final DMNMarshallerStandalone marshaller = spy(getDMNMarshaller()); final String expected = "localPart"; final DMNShape shape = mock(DMNShape.class); final javax.xml.namespace.QName ref = mock(javax.xml.namespace.QName.class); when(ref.getLocalPart()).thenReturn(expected); when(shape.getDmnElementRef()).thenReturn(ref); final String actual = marshaller.getDmnElementRef(shape); assertEquals(expected, actual); }
|
ExpressionContainerUIModelMapper extends BaseUIModelMapper<Expression> { @Override public void toDMNModel(final int rowIndex, final int columnIndex, final Supplier<Optional<GridCellValue<?>>> cell) { throw new UnsupportedOperationException("ExpressionContainerUIModelMapper does not support updating DMN models."); } ExpressionContainerUIModelMapper(final GridCellTuple parent,
final Supplier<GridData> uiModel,
final Supplier<Optional<Expression>> dmnModel,
final Supplier<String> nodeUUID,
final Supplier<HasExpression> hasExpression,
final Supplier<Optional<HasName>> hasName,
final Supplier<Boolean> isOnlyVisualChangeAllowedSupplier,
final Supplier<ExpressionEditorDefinitions> expressionEditorDefinitions,
final Supplier<ExpressionGridCache> expressionGridCache,
final ListSelectorView.Presenter listSelector); @Override void fromDMNModel(final int rowIndex,
final int columnIndex); @Override void toDMNModel(final int rowIndex,
final int columnIndex,
final Supplier<Optional<GridCellValue<?>>> cell); }
|
@Test(expected = UnsupportedOperationException.class) public void testToDMNModelIsUnsupported() { setup(false); mapper.toDMNModel(0, 0, () -> null); }
|
ExpressionEditorViewImpl implements ExpressionEditorView { @Override public void bind(final DMNSession session) { this.gridPanel = session.getGridPanel(); this.gridLayer = session.getGridLayer(); this.cellEditorControls = session.getCellEditorControls(); this.mousePanMediator = session.getMousePanMediator(); setupGridPanel(); setupGridWidget(); setupGridWidgetPanControl(); } ExpressionEditorViewImpl(); @Inject ExpressionEditorViewImpl(final Anchor returnToLink,
final Span expressionName,
final Span expressionType,
final @DMNEditor DMNGridPanelContainer gridPanelContainer,
final TranslationService translationService,
final ListSelectorView.Presenter listSelector,
final SessionManager sessionManager,
final SessionCommandManager<AbstractCanvasHandler> sessionCommandManager,
final @DMNEditor DefaultCanvasCommandFactory canvasCommandFactory,
final @DMNEditor Supplier<ExpressionEditorDefinitions> expressionEditorDefinitionsSupplier,
final Event<RefreshFormPropertiesEvent> refreshFormPropertiesEvent,
final Event<DomainObjectSelectionEvent> domainObjectSelectionEvent); @Override void init(final ExpressionEditorView.Presenter presenter); @Override void bind(final DMNSession session); @Override void setReturnToLinkText(final String text); @Override void setExpression(final String nodeUUID,
final HasExpression hasExpression,
final Optional<HasName> hasName,
final boolean isOnlyVisualChangeAllowed); ExpressionContainerGrid getExpressionContainerGrid(); @Override void setExpressionNameText(final Optional<HasName> hasName); @Override void setExpressionTypeText(final Optional<Expression> expression); @Override void onResize(); @Override void refresh(); @Override void setFocus(); }
|
@Test public void testBind() { verify(view).setupGridPanel(); verify(view).setupGridWidget(); verify(view).setupGridWidgetPanControl(); }
|
ExpressionEditorViewImpl implements ExpressionEditorView { protected void setupGridPanel() { final Transform transform = new Transform().scale(VP_SCALE); gridPanel.getElement().setId("dmn_container_" + com.google.gwt.dom.client.Document.get().createUniqueId()); gridPanel.getViewport().setTransform(transform); final BaseGridWidgetKeyboardHandler handler = new BaseGridWidgetKeyboardHandler(gridLayer); addKeyboardOperation(handler, new KeyboardOperationEditCell(gridLayer)); addKeyboardOperation(handler, new KeyboardOperationEscapeGridCell(gridLayer)); addKeyboardOperation(handler, new KeyboardOperationMoveLeft(gridLayer, gridPanel)); addKeyboardOperation(handler, new KeyboardOperationMoveRight(gridLayer, gridPanel)); addKeyboardOperation(handler, new KeyboardOperationMoveUp(gridLayer, gridPanel)); addKeyboardOperation(handler, new KeyboardOperationMoveDown(gridLayer, gridPanel)); addKeyboardOperation(handler, new KeyboardOperationInvokeContextMenuForSelectedCell(gridLayer)); gridPanel.addKeyDownHandler(handler); gridPanelContainer.clear(); gridPanelContainer.setWidget(gridPanel); } ExpressionEditorViewImpl(); @Inject ExpressionEditorViewImpl(final Anchor returnToLink,
final Span expressionName,
final Span expressionType,
final @DMNEditor DMNGridPanelContainer gridPanelContainer,
final TranslationService translationService,
final ListSelectorView.Presenter listSelector,
final SessionManager sessionManager,
final SessionCommandManager<AbstractCanvasHandler> sessionCommandManager,
final @DMNEditor DefaultCanvasCommandFactory canvasCommandFactory,
final @DMNEditor Supplier<ExpressionEditorDefinitions> expressionEditorDefinitionsSupplier,
final Event<RefreshFormPropertiesEvent> refreshFormPropertiesEvent,
final Event<DomainObjectSelectionEvent> domainObjectSelectionEvent); @Override void init(final ExpressionEditorView.Presenter presenter); @Override void bind(final DMNSession session); @Override void setReturnToLinkText(final String text); @Override void setExpression(final String nodeUUID,
final HasExpression hasExpression,
final Optional<HasName> hasName,
final boolean isOnlyVisualChangeAllowed); ExpressionContainerGrid getExpressionContainerGrid(); @Override void setExpressionNameText(final Optional<HasName> hasName); @Override void setExpressionTypeText(final Optional<Expression> expression); @Override void onResize(); @Override void refresh(); @Override void setFocus(); }
|
@Test public void testSetupGridPanel() { verify(viewport).setTransform(transformArgumentCaptor.capture()); final Transform transform = transformArgumentCaptor.getValue(); assertEquals(ExpressionEditorViewImpl.VP_SCALE, transform.getScaleX(), 0.0); assertEquals(ExpressionEditorViewImpl.VP_SCALE, transform.getScaleY(), 0.0); verify(gridPanel).addKeyDownHandler(any(BaseGridWidgetKeyboardHandler.class)); verify(gridPanelContainer).clear(); verify(gridPanelContainer).setWidget(gridPanel); verify(view, times(7)).addKeyboardOperation(any(BaseGridWidgetKeyboardHandler.class), keyboardOperationArgumentCaptor.capture()); final List<KeyboardOperation> operations = keyboardOperationArgumentCaptor.getAllValues(); assertThat(operations.get(0)).isInstanceOf(KeyboardOperationEditCell.class); assertThat(operations.get(1)).isInstanceOf(KeyboardOperationEscapeGridCell.class); assertThat(operations.get(2)).isInstanceOf(KeyboardOperationMoveLeft.class); assertThat(operations.get(3)).isInstanceOf(KeyboardOperationMoveRight.class); assertThat(operations.get(4)).isInstanceOf(KeyboardOperationMoveUp.class); assertThat(operations.get(5)).isInstanceOf(KeyboardOperationMoveDown.class); assertThat(operations.get(6)).isInstanceOf(KeyboardOperationInvokeContextMenuForSelectedCell.class); }
|
ExpressionEditorViewImpl implements ExpressionEditorView { protected void setupGridWidget() { expressionContainerGrid = new ExpressionContainerGrid(gridLayer, cellEditorControls, translationService, listSelector, sessionManager, sessionCommandManager, canvasCommandFactory, expressionEditorDefinitionsSupplier, getExpressionGridCacheSupplier(), this::setExpressionTypeText, this::setExpressionNameText, refreshFormPropertiesEvent, domainObjectSelectionEvent); gridLayer.removeAll(); gridLayer.add(expressionContainerGrid); gridLayer.select(expressionContainerGrid); gridLayer.enterPinnedMode(expressionContainerGrid, () -> {}); } ExpressionEditorViewImpl(); @Inject ExpressionEditorViewImpl(final Anchor returnToLink,
final Span expressionName,
final Span expressionType,
final @DMNEditor DMNGridPanelContainer gridPanelContainer,
final TranslationService translationService,
final ListSelectorView.Presenter listSelector,
final SessionManager sessionManager,
final SessionCommandManager<AbstractCanvasHandler> sessionCommandManager,
final @DMNEditor DefaultCanvasCommandFactory canvasCommandFactory,
final @DMNEditor Supplier<ExpressionEditorDefinitions> expressionEditorDefinitionsSupplier,
final Event<RefreshFormPropertiesEvent> refreshFormPropertiesEvent,
final Event<DomainObjectSelectionEvent> domainObjectSelectionEvent); @Override void init(final ExpressionEditorView.Presenter presenter); @Override void bind(final DMNSession session); @Override void setReturnToLinkText(final String text); @Override void setExpression(final String nodeUUID,
final HasExpression hasExpression,
final Optional<HasName> hasName,
final boolean isOnlyVisualChangeAllowed); ExpressionContainerGrid getExpressionContainerGrid(); @Override void setExpressionNameText(final Optional<HasName> hasName); @Override void setExpressionTypeText(final Optional<Expression> expression); @Override void onResize(); @Override void refresh(); @Override void setFocus(); }
|
@Test public void testSetupGridWidget() { verify(gridLayer).removeAll(); verify(gridLayer).add(expressionContainerArgumentCaptor.capture()); final GridWidget expressionContainer = expressionContainerArgumentCaptor.getValue(); verify(gridLayer).select(eq(expressionContainer)); verify(gridLayer).enterPinnedMode(eq(expressionContainer), any(Command.class)); }
|
ExpressionEditorViewImpl implements ExpressionEditorView { protected void setupGridWidgetPanControl() { final TransformMediator defaultTransformMediator = new BoundaryTransformMediator(expressionContainerGrid); mousePanMediator.setTransformMediator(defaultTransformMediator); mousePanMediator.setBatchDraw(true); gridLayer.setDefaultTransformMediator(defaultTransformMediator); gridPanel.getViewport().getMediators().push(mousePanMediator); } ExpressionEditorViewImpl(); @Inject ExpressionEditorViewImpl(final Anchor returnToLink,
final Span expressionName,
final Span expressionType,
final @DMNEditor DMNGridPanelContainer gridPanelContainer,
final TranslationService translationService,
final ListSelectorView.Presenter listSelector,
final SessionManager sessionManager,
final SessionCommandManager<AbstractCanvasHandler> sessionCommandManager,
final @DMNEditor DefaultCanvasCommandFactory canvasCommandFactory,
final @DMNEditor Supplier<ExpressionEditorDefinitions> expressionEditorDefinitionsSupplier,
final Event<RefreshFormPropertiesEvent> refreshFormPropertiesEvent,
final Event<DomainObjectSelectionEvent> domainObjectSelectionEvent); @Override void init(final ExpressionEditorView.Presenter presenter); @Override void bind(final DMNSession session); @Override void setReturnToLinkText(final String text); @Override void setExpression(final String nodeUUID,
final HasExpression hasExpression,
final Optional<HasName> hasName,
final boolean isOnlyVisualChangeAllowed); ExpressionContainerGrid getExpressionContainerGrid(); @Override void setExpressionNameText(final Optional<HasName> hasName); @Override void setExpressionTypeText(final Optional<Expression> expression); @Override void onResize(); @Override void refresh(); @Override void setFocus(); }
|
@Test public void testSetupGridWidgetPanControl() { verify(mousePanMediator).setTransformMediator(transformMediatorArgumentCaptor.capture()); final TransformMediator transformMediator = transformMediatorArgumentCaptor.getValue(); verify(mousePanMediator).setBatchDraw(true); verify(gridLayer).setDefaultTransformMediator(eq(transformMediator)); verify(viewportMediators).push(eq(mousePanMediator)); }
|
ExpressionEditorViewImpl implements ExpressionEditorView { @Override public void onResize() { gridPanelContainer.onResize(); } ExpressionEditorViewImpl(); @Inject ExpressionEditorViewImpl(final Anchor returnToLink,
final Span expressionName,
final Span expressionType,
final @DMNEditor DMNGridPanelContainer gridPanelContainer,
final TranslationService translationService,
final ListSelectorView.Presenter listSelector,
final SessionManager sessionManager,
final SessionCommandManager<AbstractCanvasHandler> sessionCommandManager,
final @DMNEditor DefaultCanvasCommandFactory canvasCommandFactory,
final @DMNEditor Supplier<ExpressionEditorDefinitions> expressionEditorDefinitionsSupplier,
final Event<RefreshFormPropertiesEvent> refreshFormPropertiesEvent,
final Event<DomainObjectSelectionEvent> domainObjectSelectionEvent); @Override void init(final ExpressionEditorView.Presenter presenter); @Override void bind(final DMNSession session); @Override void setReturnToLinkText(final String text); @Override void setExpression(final String nodeUUID,
final HasExpression hasExpression,
final Optional<HasName> hasName,
final boolean isOnlyVisualChangeAllowed); ExpressionContainerGrid getExpressionContainerGrid(); @Override void setExpressionNameText(final Optional<HasName> hasName); @Override void setExpressionTypeText(final Optional<Expression> expression); @Override void onResize(); @Override void refresh(); @Override void setFocus(); }
|
@Test public void testOnResize() { view.onResize(); verify(gridPanelContainer).onResize(); verify(gridPanel).onResize(); }
|
ExpressionEditorViewImpl implements ExpressionEditorView { @Override public void setReturnToLinkText(final String text) { returnToLink.setTextContent(translationService.format(DMNEditorConstants.ExpressionEditor_ReturnToLink, text)); } ExpressionEditorViewImpl(); @Inject ExpressionEditorViewImpl(final Anchor returnToLink,
final Span expressionName,
final Span expressionType,
final @DMNEditor DMNGridPanelContainer gridPanelContainer,
final TranslationService translationService,
final ListSelectorView.Presenter listSelector,
final SessionManager sessionManager,
final SessionCommandManager<AbstractCanvasHandler> sessionCommandManager,
final @DMNEditor DefaultCanvasCommandFactory canvasCommandFactory,
final @DMNEditor Supplier<ExpressionEditorDefinitions> expressionEditorDefinitionsSupplier,
final Event<RefreshFormPropertiesEvent> refreshFormPropertiesEvent,
final Event<DomainObjectSelectionEvent> domainObjectSelectionEvent); @Override void init(final ExpressionEditorView.Presenter presenter); @Override void bind(final DMNSession session); @Override void setReturnToLinkText(final String text); @Override void setExpression(final String nodeUUID,
final HasExpression hasExpression,
final Optional<HasName> hasName,
final boolean isOnlyVisualChangeAllowed); ExpressionContainerGrid getExpressionContainerGrid(); @Override void setExpressionNameText(final Optional<HasName> hasName); @Override void setExpressionTypeText(final Optional<Expression> expression); @Override void onResize(); @Override void refresh(); @Override void setFocus(); }
|
@Test public void testSetReturnToLinkText() { final String RETURN_LINK = "return-link"; view.setReturnToLinkText(RETURN_LINK); verify(returnToLink).setTextContent(eq(RETURN_LINK)); }
|
ExpressionEditorViewImpl implements ExpressionEditorView { @Override public void setExpression(final String nodeUUID, final HasExpression hasExpression, final Optional<HasName> hasName, final boolean isOnlyVisualChangeAllowed) { expressionContainerGrid.setExpression(nodeUUID, hasExpression, hasName, isOnlyVisualChangeAllowed); setExpressionNameText(hasName); setExpressionTypeText(Optional.ofNullable(hasExpression.getExpression())); } ExpressionEditorViewImpl(); @Inject ExpressionEditorViewImpl(final Anchor returnToLink,
final Span expressionName,
final Span expressionType,
final @DMNEditor DMNGridPanelContainer gridPanelContainer,
final TranslationService translationService,
final ListSelectorView.Presenter listSelector,
final SessionManager sessionManager,
final SessionCommandManager<AbstractCanvasHandler> sessionCommandManager,
final @DMNEditor DefaultCanvasCommandFactory canvasCommandFactory,
final @DMNEditor Supplier<ExpressionEditorDefinitions> expressionEditorDefinitionsSupplier,
final Event<RefreshFormPropertiesEvent> refreshFormPropertiesEvent,
final Event<DomainObjectSelectionEvent> domainObjectSelectionEvent); @Override void init(final ExpressionEditorView.Presenter presenter); @Override void bind(final DMNSession session); @Override void setReturnToLinkText(final String text); @Override void setExpression(final String nodeUUID,
final HasExpression hasExpression,
final Optional<HasName> hasName,
final boolean isOnlyVisualChangeAllowed); ExpressionContainerGrid getExpressionContainerGrid(); @Override void setExpressionNameText(final Optional<HasName> hasName); @Override void setExpressionTypeText(final Optional<Expression> expression); @Override void onResize(); @Override void refresh(); @Override void setFocus(); }
|
@Test public void testSetExpression() { final Optional<HasName> hasName = Optional.empty(); view.setExpression(NODE_UUID, hasExpression, hasName, false); verify(gridLayer).add(expressionContainerArgumentCaptor.capture()); final ExpressionContainerGrid expressionContainer = (ExpressionContainerGrid) expressionContainerArgumentCaptor.getValue(); assertFalse(expressionContainer.isOnlyVisualChangeAllowed()); }
@Test public void testSetExpressionWhenOnlyVisualChangeAllowed() { final Optional<HasName> hasName = Optional.empty(); view.setExpression(NODE_UUID, hasExpression, hasName, true); verify(gridLayer).add(expressionContainerArgumentCaptor.capture()); final ExpressionContainerGrid expressionContainer = (ExpressionContainerGrid) expressionContainerArgumentCaptor.getValue(); assertTrue(expressionContainer.isOnlyVisualChangeAllowed()); }
@Test public void testSetExpressionDoesUpdateExpressionNameTextWhenHasNameIsNotEmpty() { final String NAME = "NAME"; final Name name = new Name(NAME); final HasName hasNameMock = mock(HasName.class); doReturn(name).when(hasNameMock).getName(); final Optional<HasName> hasName = Optional.of(hasNameMock); view.setExpression(NODE_UUID, hasExpression, hasName, false); verify(expressionName).setTextContent(eq(NAME)); }
@Test public void testSetExpressionDoesNotUpdateExpressionNameTextWhenHasNameIsEmpty() { final Optional<HasName> hasName = Optional.empty(); view.setExpression(NODE_UUID, hasExpression, hasName, false); verify(expressionName, never()).setTextContent(any(String.class)); }
@Test public void testSetExpressionDoesUpdateExpressionTypeTextWhenHasExpressionIsNotEmpty() { final Expression expression = new LiteralExpression(); final Optional<HasName> hasName = Optional.empty(); when(hasExpression.getExpression()).thenReturn(expression); view.setExpression(NODE_UUID, hasExpression, hasName, false); verify(expressionType).setTextContent(eq(LITERAL_EXPRESSION_DEFINITION_NAME)); }
@Test public void testSetExpressionDoesNotUpdateExpressionTypeTextWhenHasExpressionTextWhenHasExpressionIsEmpty() { final Optional<HasName> hasName = Optional.empty(); view.setExpression(NODE_UUID, hasExpression, hasName, false); verify(expressionType).setTextContent(eq("<" + UNDEFINED_EXPRESSION_DEFINITION_NAME + ">")); }
|
DMNMarshallerStandalone implements DiagramMarshaller<Graph, Metadata, Diagram<Graph, Metadata>> { List<DMNShape> getUniqueDMNShapes(final org.kie.dmn.model.api.dmndi.DMNDiagram dmnDDDiagram) { return new ArrayList<>(dmnDDDiagram .getDMNDiagramElement() .stream() .filter(diagramElements -> diagramElements instanceof DMNShape) .map(d -> (DMNShape) d) .collect(toMap(DMNShape::getId, shape -> shape, (shape1, shape2) -> shape1)) .values()); } protected DMNMarshallerStandalone(); @Inject DMNMarshallerStandalone(final XMLEncoderDiagramMetadataMarshaller diagramMetadataMarshaller,
final FactoryManager factoryManager,
final DMNMarshallerImportsHelperStandalone dmnMarshallerImportsHelper,
final DMNMarshaller marshaller); @Override @SuppressWarnings("unchecked") Graph unmarshall(final Metadata metadata,
final InputStream input); static Node<?, ?> findDMNDiagramRoot(final Graph<?, Node<View, ?>> graph); @SuppressWarnings({"rawtypes", "unchecked"}) static void connectRootWithChild(final Node dmnDiagramRoot,
final Node child); @SuppressWarnings({"rawtypes", "unchecked"}) static void connectEdge(final Edge edge,
final Node source,
final Node target); @Override @SuppressWarnings("unchecked") String marshall(final Diagram<Graph, Metadata> diagram); @Override DiagramMetadataMarshaller<Metadata> getMetadataMarshaller(); static final String INFO_REQ_ID; static final String KNOWLEDGE_REQ_ID; static final String AUTH_REQ_ID; static final String ASSOCIATION_ID; }
|
@Test public void testGetUniqueDMNShapes() { final DMNMarshallerStandalone marshaller = spy(getDMNMarshaller()); final org.kie.dmn.model.api.dmndi.DMNDiagram diagram = mock(org.kie.dmn.model.api.dmndi.DMNDiagram.class); final List<DiagramElement> elements = new ArrayList<>(); final DMNShape unique1 = mock(DMNShape.class); when(unique1.getId()).thenReturn("unique1"); final DMNShape unique2 = mock(DMNShape.class); when(unique2.getId()).thenReturn("unique2"); final DMNShape duplicate1 = mock(DMNShape.class); when(duplicate1.getId()).thenReturn("duplicate"); final DMNShape duplicate2 = mock(DMNShape.class); when(duplicate2.getId()).thenReturn("duplicate"); elements.add(unique1); elements.add(unique2); elements.add(duplicate1); elements.add(duplicate2); when(diagram.getDMNDiagramElement()).thenReturn(elements); final List<DMNShape> actual = marshaller.getUniqueDMNShapes(diagram); assertEquals(3, actual.size()); assertTrue(actual.contains(unique1)); assertTrue(actual.contains(unique2)); assertTrue(actual.contains(duplicate1) || actual.contains(duplicate2)); }
|
ExpressionEditorViewImpl implements ExpressionEditorView { @SuppressWarnings("unused") @EventHandler("returnToLink") void onClickReturnToLink(final ClickEvent event) { presenter.exit(); } ExpressionEditorViewImpl(); @Inject ExpressionEditorViewImpl(final Anchor returnToLink,
final Span expressionName,
final Span expressionType,
final @DMNEditor DMNGridPanelContainer gridPanelContainer,
final TranslationService translationService,
final ListSelectorView.Presenter listSelector,
final SessionManager sessionManager,
final SessionCommandManager<AbstractCanvasHandler> sessionCommandManager,
final @DMNEditor DefaultCanvasCommandFactory canvasCommandFactory,
final @DMNEditor Supplier<ExpressionEditorDefinitions> expressionEditorDefinitionsSupplier,
final Event<RefreshFormPropertiesEvent> refreshFormPropertiesEvent,
final Event<DomainObjectSelectionEvent> domainObjectSelectionEvent); @Override void init(final ExpressionEditorView.Presenter presenter); @Override void bind(final DMNSession session); @Override void setReturnToLinkText(final String text); @Override void setExpression(final String nodeUUID,
final HasExpression hasExpression,
final Optional<HasName> hasName,
final boolean isOnlyVisualChangeAllowed); ExpressionContainerGrid getExpressionContainerGrid(); @Override void setExpressionNameText(final Optional<HasName> hasName); @Override void setExpressionTypeText(final Optional<Expression> expression); @Override void onResize(); @Override void refresh(); @Override void setFocus(); }
|
@Test public void testOnClickReturnToLink() { view.onClickReturnToLink(mock(ClickEvent.class)); verify(presenter).exit(); }
|
ExpressionEditorViewImpl implements ExpressionEditorView { @Override public void refresh() { gridLayer.batch(); } ExpressionEditorViewImpl(); @Inject ExpressionEditorViewImpl(final Anchor returnToLink,
final Span expressionName,
final Span expressionType,
final @DMNEditor DMNGridPanelContainer gridPanelContainer,
final TranslationService translationService,
final ListSelectorView.Presenter listSelector,
final SessionManager sessionManager,
final SessionCommandManager<AbstractCanvasHandler> sessionCommandManager,
final @DMNEditor DefaultCanvasCommandFactory canvasCommandFactory,
final @DMNEditor Supplier<ExpressionEditorDefinitions> expressionEditorDefinitionsSupplier,
final Event<RefreshFormPropertiesEvent> refreshFormPropertiesEvent,
final Event<DomainObjectSelectionEvent> domainObjectSelectionEvent); @Override void init(final ExpressionEditorView.Presenter presenter); @Override void bind(final DMNSession session); @Override void setReturnToLinkText(final String text); @Override void setExpression(final String nodeUUID,
final HasExpression hasExpression,
final Optional<HasName> hasName,
final boolean isOnlyVisualChangeAllowed); ExpressionContainerGrid getExpressionContainerGrid(); @Override void setExpressionNameText(final Optional<HasName> hasName); @Override void setExpressionTypeText(final Optional<Expression> expression); @Override void onResize(); @Override void refresh(); @Override void setFocus(); }
|
@Test public void testRefresh() { view.refresh(); verify(gridLayer).batch(); }
|
ExpressionEditorViewImpl implements ExpressionEditorView { @Override public void setFocus() { gridPanel.setFocus(true); } ExpressionEditorViewImpl(); @Inject ExpressionEditorViewImpl(final Anchor returnToLink,
final Span expressionName,
final Span expressionType,
final @DMNEditor DMNGridPanelContainer gridPanelContainer,
final TranslationService translationService,
final ListSelectorView.Presenter listSelector,
final SessionManager sessionManager,
final SessionCommandManager<AbstractCanvasHandler> sessionCommandManager,
final @DMNEditor DefaultCanvasCommandFactory canvasCommandFactory,
final @DMNEditor Supplier<ExpressionEditorDefinitions> expressionEditorDefinitionsSupplier,
final Event<RefreshFormPropertiesEvent> refreshFormPropertiesEvent,
final Event<DomainObjectSelectionEvent> domainObjectSelectionEvent); @Override void init(final ExpressionEditorView.Presenter presenter); @Override void bind(final DMNSession session); @Override void setReturnToLinkText(final String text); @Override void setExpression(final String nodeUUID,
final HasExpression hasExpression,
final Optional<HasName> hasName,
final boolean isOnlyVisualChangeAllowed); ExpressionContainerGrid getExpressionContainerGrid(); @Override void setExpressionNameText(final Optional<HasName> hasName); @Override void setExpressionTypeText(final Optional<Expression> expression); @Override void onResize(); @Override void refresh(); @Override void setFocus(); }
|
@Test public void testSetFocus() { view.setFocus(); verify(gridPanel).setFocus(true); }
|
ExpressionContainerGrid extends BaseGrid<Expression> { @Override public boolean onDragHandle(final INodeXYEvent event) { return false; } ExpressionContainerGrid(final DMNGridLayer gridLayer,
final CellEditorControlsView.Presenter cellEditorControls,
final TranslationService translationService,
final ListSelectorView.Presenter listSelector,
final SessionManager sessionManager,
final SessionCommandManager<AbstractCanvasHandler> sessionCommandManager,
final DefaultCanvasCommandFactory canvasCommandFactory,
final Supplier<ExpressionEditorDefinitions> expressionEditorDefinitions,
final Supplier<ExpressionGridCache> expressionGridCache,
final ParameterizedCommand<Optional<Expression>> onHasExpressionChanged,
final ParameterizedCommand<Optional<HasName>> onHasNameChanged,
final Event<RefreshFormPropertiesEvent> refreshFormPropertiesEvent,
final Event<DomainObjectSelectionEvent> domainObjectSelectionEvent); @Override boolean onDragHandle(final INodeXYEvent event); @Override void deselect(); void setExpression(final String nodeUUID,
final HasExpression hasExpression,
final Optional<HasName> hasName,
final boolean isOnlyVisualChangeAllowed); @Override List<ListSelectorItem> getItems(final int uiRowIndex,
final int uiColumnIndex); @Override void onItemSelected(final ListSelectorItem item); Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> getBaseExpressionGrid(); @Override boolean selectCell(final Point2D ap,
final boolean isShiftKeyDown,
final boolean isControlKeyDown); @Override boolean selectCell(final int uiRowIndex,
final int uiColumnIndex,
final boolean isShiftKeyDown,
final boolean isControlKeyDown); }
|
@Test public void testGridDraggingIsDisabled() { assertThat(grid.onDragHandle(mock(INodeXYEvent.class))).isFalse(); }
|
ExpressionContainerGrid extends BaseGrid<Expression> { @Override public void deselect() { getModel().clearSelections(); super.deselect(); } ExpressionContainerGrid(final DMNGridLayer gridLayer,
final CellEditorControlsView.Presenter cellEditorControls,
final TranslationService translationService,
final ListSelectorView.Presenter listSelector,
final SessionManager sessionManager,
final SessionCommandManager<AbstractCanvasHandler> sessionCommandManager,
final DefaultCanvasCommandFactory canvasCommandFactory,
final Supplier<ExpressionEditorDefinitions> expressionEditorDefinitions,
final Supplier<ExpressionGridCache> expressionGridCache,
final ParameterizedCommand<Optional<Expression>> onHasExpressionChanged,
final ParameterizedCommand<Optional<HasName>> onHasNameChanged,
final Event<RefreshFormPropertiesEvent> refreshFormPropertiesEvent,
final Event<DomainObjectSelectionEvent> domainObjectSelectionEvent); @Override boolean onDragHandle(final INodeXYEvent event); @Override void deselect(); void setExpression(final String nodeUUID,
final HasExpression hasExpression,
final Optional<HasName> hasName,
final boolean isOnlyVisualChangeAllowed); @Override List<ListSelectorItem> getItems(final int uiRowIndex,
final int uiColumnIndex); @Override void onItemSelected(final ListSelectorItem item); Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> getBaseExpressionGrid(); @Override boolean selectCell(final Point2D ap,
final boolean isShiftKeyDown,
final boolean isControlKeyDown); @Override boolean selectCell(final int uiRowIndex,
final int uiColumnIndex,
final boolean isShiftKeyDown,
final boolean isControlKeyDown); }
|
@Test public void testDeselect() { grid.getModel().selectCell(0, 0); assertFalse(grid.getModel().getSelectedCells().isEmpty()); grid.deselect(); assertTrue(grid.getModel().getSelectedCells().isEmpty()); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.