src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
Sentence implements Serializable, Iterable<Annotation> { public DependencyTreeNode[] dependencyParseTree() { if (tokenAnnotations.length == 0 || !tokenAnnotations[0].hasDependencyParent()) return new DependencyTreeNode[0]; SimpleDependencyTreeNode[] nodes = new SimpleDependencyTreeNode[tokenAnnotations.length]; for (int i = 0; i < nodes.length; ++i) nodes[i] = new SimpleDependencyTreeNode( tokenAnnotations[i].word(), tokenAnnotations[i].pos(), i); for (int i = 0; i < nodes.length; ++i) { int parent = tokenAnnotations[i].dependencyParent(); String relation = tokenAnnotations[i].dependencyRelation(); if (parent == 0) continue; DependencyRelation r = new SimpleDependencyRelation( nodes[parent-1], relation, nodes[i]); nodes[i].addNeighbor(r); nodes[parent-1].addNeighbor(r); } return nodes; } private Sentence(); Sentence(int start, int end, int numTokens); void setText(String text); String sentenceText(); void addAnnotation(int index, Annotation annotation); Annotation getAnnotation(int index); DependencyTreeNode[] dependencyParseTree(); StringPair[] taggedTokens(); Iterator<Annotation> iterator(); int start(); int end(); int numTokens(); static List<Sentence> readSentences(String sentenceText,
String tokenText); static StringPair writeSentences(List<Sentence> sentences); } | @Test public void testDependencyParseTree() { Sentence sentence = new Sentence(0, 100, 7); for (int i = 0; i < TEST_PARSED_SENTENCES.length; ++i) sentence.addAnnotation( i, annotationFromCoNLL(TEST_PARSED_SENTENCES[i])); DependencyTreeNode[] tree = sentence.dependencyParseTree(); assertEquals(TEST_PARSED_SENTENCES.length, tree.length); for (int i = 0; i < TEST_PARSED_SENTENCES.length; ++i) { assertEquals(TEST_PARSED_SENTENCES[i][0], tree[i].word()); assertEquals(TEST_PARSED_SENTENCES[i][1], tree[i].pos()); } assertEquals(1, tree[0].neighbors().size()); DependencyRelation relation = tree[0].neighbors().get(0); assertEquals("When", relation.dependentNode().word()); assertEquals("advmod", relation.relation()); assertEquals("released", relation.headNode().word()); assertEquals(2, tree[1].neighbors().size()); relation = tree[1].neighbors().get(0); assertEquals("When", relation.dependentNode().word()); assertEquals("advmod", relation.relation()); assertEquals("released", relation.headNode().word()); } |
Sentence implements Serializable, Iterable<Annotation> { public StringPair[] taggedTokens() { StringPair[] taggedTokens = new StringPair[tokenAnnotations.length]; for (int i = 0; i < taggedTokens.length; ++i) taggedTokens[i] = new StringPair( tokenAnnotations[i].word(), tokenAnnotations[i].pos()); return taggedTokens; } private Sentence(); Sentence(int start, int end, int numTokens); void setText(String text); String sentenceText(); void addAnnotation(int index, Annotation annotation); Annotation getAnnotation(int index); DependencyTreeNode[] dependencyParseTree(); StringPair[] taggedTokens(); Iterator<Annotation> iterator(); int start(); int end(); int numTokens(); static List<Sentence> readSentences(String sentenceText,
String tokenText); static StringPair writeSentences(List<Sentence> sentences); } | @Test public void testTaggedTokens() { Sentence sentence = makeSentence(0, 4, TOKEN_INFO, RANGES); StringPair[] taggedPairs = sentence.taggedTokens(); assertEquals(TOKEN_INFO.length, taggedPairs.length); for (int i = 0; i < TOKEN_INFO.length; ++i) { assertEquals(TOKEN_INFO[i][0], taggedPairs[i].x); assertEquals(TOKEN_INFO[i][1], taggedPairs[i].y); } } |
NetworkConfluency { public double computeInitialAgreement() { return computeKappaScore( info1.edges, info2.edges, numNodes); } NetworkConfluency(String matrixFile1,
String matrixFile2,
Format format); NetworkConfluency(SparseMatrix matrix1, SparseMatrix matrix2); double computeInitialAgreement(); double computeExtendedAgreement(); static void main(String[] args); static double computeKappaScore(Set<IntPair> edges1,
Set<IntPair> edges2,
int numNodes); static Matrix multiply(SparseMatrix a, SparseMatrix b); } | @Test public void testInitialAgreement() { double[][] v1 = new double[][] { {1, 1, 0, 0, 1, 0}, {0, 0, 1, 0, 1, 0}, {0, 1, 0, 0, 0, 1}, {0, 1, 1, 1, 0, 0}, {1, 0, 1, 0, 0, 1}, {1, 1, 0, 0, 1, 1}, }; double[][] v2 = new double[][] { {1, 0, 0, 0, 1, 0}, {0, 0, 0, 0, 1, 0}, {0, 1, 1, 0, 0, 1}, {0, 1, 1, 1, 1, 0}, {1, 0, 1, 1, 0, 1}, {1, 1, 0, 0, 1, 1}, }; int agreeMent = 0; int edges1 = 0; int notEdges1 = 0; int edges2 = 0; int notEdges2 = 0; double numEdges = v1.length * v1.length; for (int r = 0; r < v1.length; ++r) for (int c = 0; c < v1.length; ++c) { if (v1[r][c] == v2[r][c]) agreeMent++; if (v1[r][c] != 0d) edges1++; else notEdges1++; if (v2[r][c] != 0d) edges2++; else notEdges2++; } double p0 = 1/numEdges * agreeMent; double pe = 1/(numEdges*numEdges) * (edges1*edges2 + notEdges1*notEdges2); double expectedKappa = (p0 - pe) / (1 - pe); NetworkConfluency confluency = new NetworkConfluency( makeMatrix(v1), makeMatrix(v2)); assertEquals(expectedKappa, confluency.computeInitialAgreement(), .001); } |
BaseSynset implements Synset { public PartsOfSpeech getPartOfSpeech() { return pos; } BaseSynset(String synsetName); BaseSynset(int offset, PartsOfSpeech pos); BaseSynset(PartsOfSpeech pos); void addMorphyMapping(String original, String lemma); int getSenseNumber(); void setSenseNumber(int senseNumber); String getName(); String getSenseKey(); String getSenseKey(String base); List<String> getSenseKeys(); void addSenseKey(String senseKey); String getDefinition(); PartsOfSpeech getPartOfSpeech(); List<Lemma> getLemmas(); List<String> getExamples(); RelatedForm getDerivationallyRelatedForm(Synset synset); Set<String> getKnownRelationTypes(); Collection<Synset> allRelations(); Set<Synset> getRelations(String relation); Set<Synset> getRelations(Relation relation); int getNumRelations(); List<List<Synset>> getParentPaths(); Set<Synset> getParents(); Set<Synset> getChildren(); int getId(); int[] getFrameIds(); int[] getLemmaIds(); void setFrameInfo(int[] frameIds, int[] lemmaIds); void setId(int newOffset); void setDefinition(String definition); void addLemma(Lemma lemma); void addExample(String example); void addDerivationallyRelatedForm(Synset related, RelatedForm form); boolean addRelation(Relation relation, Synset synset); boolean addRelation(String relation, Synset synset); boolean removeRelation(Relation relation, Synset synset); boolean removeRelation(String relation, Synset synset); String getGloss(); int getMaxDepth(); int getMinDepth(); void setAttribute(String attributeName, Attribute attribute); Attribute getAttribute(String attributeName); Set<String> attributeLabels(); void merge(Synset synset); String toString(); } | @Test public void testConstructor() { Synset synset = new BaseSynset(PartsOfSpeech.NOUN); assertEquals(PartsOfSpeech.NOUN, synset.getPartOfSpeech()); } |
StringUtils { public static int tokenOverlapExp(String[] tokens1, String[] tokens2) { int index1 = 0; int index2 = 0; int score = 0; for (int i = 0; i < tokens1.length; ++i) for (int j = 0; j < tokens2.length; ++j) if (tokens1[i].equals(tokens2[j])) score += Math.pow(findOverlap(tokens1, i, tokens2, j), 2); return score; } static int tokenOverlap(String[] tokens1, String[] tokens2); static int tokenOverlapExp(String[] tokens1, String[] tokens2); static int findOverlap(String[] tokens1, int i,
String[] tokens2, int j); } | @Test public void testTokenOverlapExpNoSequence() { String[] tokens1 = {"the", "cat", "has", "a", "brown", "bag"}; String[] tokens2 = {"bag", "dog", "was", "cat", "blah", "bag"}; assertEquals(3, StringUtils.tokenOverlapExp(tokens1, tokens2)); }
@Test public void testTokenOverlapExpBoundedSequence() { String[] tokens1 = {"the", "cat", "has", "chicken", "bag", "the"}; String[] tokens2 = {"the", "dog", "was", "blarg", "chicken", "bag"}; assertEquals(7, StringUtils.tokenOverlapExp(tokens1, tokens2)); } |
BaseSynset implements Synset { public void merge(Synset synset) { if (pos != synset.getPartOfSpeech()) throw new IllegalArgumentException( "Cannot merge synsets with different parts of speech."); Set<Duple<String, Synset>> toRemove = new HashSet<Duple<String, Synset>>(); for (String relation : getKnownRelationTypes()) { Set<Synset> links = relations.get(relation); if (links.contains(synset)) toRemove.add(new Duple<String, Synset>(relation, synset)); } for (Duple<String, Synset> r : toRemove) relations.remove(r.x, r.y); for (String relation : synset.getKnownRelationTypes()) { for (Synset related : synset.getRelations(relation)) { if (related == this) continue; relations.put(relation, related); numRelations++; Relation rel = Relation.fromId(relation); if (rel == null || rel.reflexive() == null) continue; Set<Synset> inwardRelations = related.getRelations( rel.reflexive()); if (inwardRelations.contains(synset)) { inwardRelations.remove(synset); inwardRelations.add(this); } } } for (String example : synset.getExamples()) examples.add(example); this.definition += "; " + synset.getDefinition(); for (Lemma otherLemma : synset.getLemmas()) lemmas.add(otherLemma); for (String attributeLabel : synset.attributeLabels()) { Attribute attribute = attributes.get(attributeLabel); Attribute other = synset.getAttribute(attributeLabel); if (attribute == null) attributes.put(attributeLabel, other); else if (attribute != other) attribute.merge(other); } this.minDepth = -1; this.maxDepth = -1; } BaseSynset(String synsetName); BaseSynset(int offset, PartsOfSpeech pos); BaseSynset(PartsOfSpeech pos); void addMorphyMapping(String original, String lemma); int getSenseNumber(); void setSenseNumber(int senseNumber); String getName(); String getSenseKey(); String getSenseKey(String base); List<String> getSenseKeys(); void addSenseKey(String senseKey); String getDefinition(); PartsOfSpeech getPartOfSpeech(); List<Lemma> getLemmas(); List<String> getExamples(); RelatedForm getDerivationallyRelatedForm(Synset synset); Set<String> getKnownRelationTypes(); Collection<Synset> allRelations(); Set<Synset> getRelations(String relation); Set<Synset> getRelations(Relation relation); int getNumRelations(); List<List<Synset>> getParentPaths(); Set<Synset> getParents(); Set<Synset> getChildren(); int getId(); int[] getFrameIds(); int[] getLemmaIds(); void setFrameInfo(int[] frameIds, int[] lemmaIds); void setId(int newOffset); void setDefinition(String definition); void addLemma(Lemma lemma); void addExample(String example); void addDerivationallyRelatedForm(Synset related, RelatedForm form); boolean addRelation(Relation relation, Synset synset); boolean addRelation(String relation, Synset synset); boolean removeRelation(Relation relation, Synset synset); boolean removeRelation(String relation, Synset synset); String getGloss(); int getMaxDepth(); int getMinDepth(); void setAttribute(String attributeName, Attribute attribute); Attribute getAttribute(String attributeName); Set<String> attributeLabels(); void merge(Synset synset); String toString(); } | @Test (expected=IllegalArgumentException.class) public void testMergeBadPos() { Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); Synset s2 = new BaseSynset(PartsOfSpeech.VERB); s1.merge(s2); } |
ResnickSimilarity implements SynsetSimilarity { public double similarity(Synset synset1, Synset synset2) { List<Synset> subsumers = SynsetRelations.lowestCommonHypernyms( synset1, synset2); if (subsumers.size() == 0) return 0; double bestIC = 0; for (Synset subsumer : subsumers) bestIC = Math.max(bestIC, ic.informationContent(subsumer)); return bestIC; } ResnickSimilarity(InformationContent ic); double similarity(Synset synset1, Synset synset2); } | @Test public void testNoSubsumer() { Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); Synset s2 = new BaseSynset(PartsOfSpeech.NOUN); SynsetSimilarity sim = new ResnickSimilarity(null); assertEquals(0, sim.similarity(s1, s2), .00001); }
@Test public void testSimilarity() { Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); Synset s2 = new BaseSynset(PartsOfSpeech.NOUN); MockIC ic = new MockIC(); Synset worst = new BaseSynset(PartsOfSpeech.NOUN); s1.addRelation(Relation.HYPERNYM, worst); s2.addRelation(Relation.HYPERNYM, worst); Synset best = new BaseSynset(PartsOfSpeech.NOUN); s1.addRelation(Relation.HYPERNYM, best); s2.addRelation(Relation.HYPERNYM, best); ic.ic.put(best, 10.0); Synset med = new BaseSynset(PartsOfSpeech.NOUN); s1.addRelation(Relation.HYPERNYM, med); s2.addRelation(Relation.HYPERNYM, med); ic.ic.put(med, 5.0); SynsetSimilarity sim = new ResnickSimilarity(ic); assertEquals(10, sim.similarity(s1, s2), .0001); assertEquals(3, ic.seen.size()); assertTrue(ic.seen.contains(med)); assertTrue(ic.seen.contains(worst)); assertTrue(ic.seen.contains(best)); } |
LeskSimilarity implements SynsetSimilarity { public double similarity(Synset synset1, Synset synset2) { String[] gloss1 = synset1.getGloss().split("\\s+"); String[] gloss2 = synset2.getGloss().split("\\s+"); return StringUtils.tokenOverlap(gloss1, gloss2); } double similarity(Synset synset1, Synset synset2); } | @Test public void testLeskSimilarity() { Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); Synset s2 = new BaseSynset(PartsOfSpeech.NOUN); s1.setDefinition("how now brown cow"); s2.setDefinition("how now sad meow"); SynsetSimilarity sim = new LeskSimilarity(); assertEquals(2, sim.similarity(s1, s2), .00001); } |
LinSimilarity implements SynsetSimilarity { public double similarity(Synset synset1, Synset synset2) { double ic1 = ic.informationContent(synset1); double ic2 = ic.informationContent(synset2); if (ic1 == -1 || ic2 == -1) return 0; double icSubsumer = resSim.similarity(synset1, synset2); return (2d * icSubsumer) / (ic1 + ic2); } LinSimilarity(InformationContent ic); double similarity(Synset synset1, Synset synset2); } | @Test public void testNoSubsumer() { MockIC ic = new MockIC(); Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); Synset s2 = new BaseSynset(PartsOfSpeech.NOUN); SynsetSimilarity sim = new LinSimilarity(ic); assertEquals(0, sim.similarity(s1, s2), .00001); }
@Test public void testSimilarity() { MockIC ic = new MockIC(); Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); ic.ic.put(s1, 2.0); Synset s2 = new BaseSynset(PartsOfSpeech.NOUN); ic.ic.put(s2, 3.0); Synset worst = new BaseSynset(PartsOfSpeech.NOUN); s1.addRelation(Relation.HYPERNYM, worst); s2.addRelation(Relation.HYPERNYM, worst); Synset best = new BaseSynset(PartsOfSpeech.NOUN); s1.addRelation(Relation.HYPERNYM, best); s2.addRelation(Relation.HYPERNYM, best); ic.ic.put(best, 10.0); Synset med = new BaseSynset(PartsOfSpeech.NOUN); s1.addRelation(Relation.HYPERNYM, med); s2.addRelation(Relation.HYPERNYM, med); ic.ic.put(med, 5.0); SynsetSimilarity sim = new LinSimilarity(ic); assertEquals(2*10/(5), sim.similarity(s1, s2), .0001); assertEquals(5, ic.seen.size()); assertTrue(ic.seen.contains(med)); assertTrue(ic.seen.contains(worst)); assertTrue(ic.seen.contains(best)); assertTrue(ic.seen.contains(s1)); assertTrue(ic.seen.contains(s2)); } |
WuPalmerSimilarity implements SynsetSimilarity { public double similarity(Synset synset1, Synset synset2) { Synset subsumer = SynsetRelations.lowestCommonHypernym( synset1, synset2); if (subsumer == null) return 0; double depth = subsumer.getMaxDepth() + 1; if (subsumer.getPartOfSpeech() == PartsOfSpeech.NOUN) depth++; double distance1 = SynsetRelations.shortestPathDistance( synset1, subsumer); double distance2 = SynsetRelations.shortestPathDistance( synset2, subsumer); distance1 += depth; distance2 += depth; return (2.0 * depth) / (distance1 + distance2); } double similarity(Synset synset1, Synset synset2); } | @Test public void testNoSubsumer() { Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); Synset s2 = new BaseSynset(PartsOfSpeech.NOUN); SynsetSimilarity sim = new WuPalmerSimilarity(); assertEquals(0, sim.similarity(s1, s2), .00001); }
@Test public void testNounSimilarity() { Synset subsumer = new BaseSynset(PartsOfSpeech.NOUN); Synset parent = subsumer; for (int i = 0; i < 4; ++i) { Synset child = new BaseSynset(PartsOfSpeech.NOUN); child.addRelation(Relation.HYPERNYM, parent); parent = child; } Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); s1.addRelation(Relation.HYPERNYM, parent); parent = subsumer; for (int i = 0; i < 2; ++i) { Synset child = new BaseSynset(PartsOfSpeech.NOUN); child.addRelation(Relation.HYPERNYM, parent); parent = child; } Synset s2 = new BaseSynset(PartsOfSpeech.NOUN); s2.addRelation(Relation.HYPERNYM, parent); SynsetSimilarity sim = new WuPalmerSimilarity(); double expected = (2.0 * 2) / (7 + 5); assertEquals(expected, sim.similarity(s1, s2), .00001); }
@Test public void testVerbSimilarity() { Synset subsumer = new BaseSynset(PartsOfSpeech.VERB); Synset parent = subsumer; for (int i = 0; i < 4; ++i) { Synset child = new BaseSynset(PartsOfSpeech.NOUN); child.addRelation(Relation.HYPERNYM, parent); parent = child; } Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); s1.addRelation(Relation.HYPERNYM, parent); parent = subsumer; for (int i = 0; i < 2; ++i) { Synset child = new BaseSynset(PartsOfSpeech.NOUN); child.addRelation(Relation.HYPERNYM, parent); parent = child; } Synset s2 = new BaseSynset(PartsOfSpeech.NOUN); s2.addRelation(Relation.HYPERNYM, parent); SynsetSimilarity sim = new WuPalmerSimilarity(); double expected = (2.0 * 1) / (6 + 4); assertEquals(expected, sim.similarity(s1, s2), .00001); } |
JiangConrathSimilarity implements SynsetSimilarity { public double similarity(Synset synset1, Synset synset2) { if (synset1.equals(synset2)) return Double.MAX_VALUE; double ic1 = ic.informationContent(synset1); double ic2 = ic.informationContent(synset2); if (ic1 == -1 || ic2 == -1) return 0; double icSubsumer = resSim.similarity(synset1, synset2); double difference = ic1 + ic2 - 2 * icSubsumer; return (difference == 0) ? Double.MAX_VALUE : 1d / difference; } JiangConrathSimilarity(InformationContent ic); double similarity(Synset synset1, Synset synset2); } | @Test public void testNoSubsumer() { Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); SynsetSimilarity sim = new JiangConrathSimilarity(null); assertEquals(Double.MAX_VALUE, sim.similarity(s1, s1), .00001); }
@Test public void testSimilarity() { Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); Synset s2 = new BaseSynset(PartsOfSpeech.NOUN); MockIC ic = new MockIC(); ic.ic.put(s1, 10.0); ic.ic.put(s2, 11.0); Synset worst = new BaseSynset(PartsOfSpeech.NOUN); s1.addRelation(Relation.HYPERNYM, worst); s2.addRelation(Relation.HYPERNYM, worst); Synset best = new BaseSynset(PartsOfSpeech.NOUN); s1.addRelation(Relation.HYPERNYM, best); s2.addRelation(Relation.HYPERNYM, best); ic.ic.put(best, 10.0); Synset med = new BaseSynset(PartsOfSpeech.NOUN); s1.addRelation(Relation.HYPERNYM, med); s2.addRelation(Relation.HYPERNYM, med); ic.ic.put(med, 5.0); SynsetSimilarity sim = new JiangConrathSimilarity(ic); assertEquals(1, sim.similarity(s1, s2), .0001); assertEquals(5, ic.seen.size()); assertTrue(ic.seen.contains(med)); assertTrue(ic.seen.contains(worst)); assertTrue(ic.seen.contains(best)); assertTrue(ic.seen.contains(s1)); assertTrue(ic.seen.contains(s2)); } |
LeacockChodorowSimilarity implements SynsetSimilarity { public double similarity(Synset synset1, Synset synset2) { if (synset1.getPartOfSpeech() != synset2.getPartOfSpeech()) return 0; int maxDepth = wordnet.getMaxDepth(synset1.getPartOfSpeech()); int distance = SynsetRelations.shortestPathDistance(synset1, synset2); return (distance >= 0 && distance <= Integer.MAX_VALUE) ? -1 * Math.log((distance + 1) / (2d * maxDepth)) : 0; } LeacockChodorowSimilarity(OntologyReader reader); double similarity(Synset synset1, Synset synset2); } | @Test public void testWrongPos() { Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); Synset s2 = new BaseSynset(PartsOfSpeech.VERB); SynsetSimilarity sim = new LeacockChodorowSimilarity(null); assertEquals(0, sim.similarity(s1, s2), .0001); }
@Test public void testSimilarity() { Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); Synset s2 = new BaseSynset(PartsOfSpeech.NOUN); addParents(s1, s2); MockReader reader = new MockReader(); SynsetSimilarity sim = new LeacockChodorowSimilarity(reader); double expected = -1 * Math.log(7 / (2d * 1)); assertEquals(expected, sim.similarity(s1, s2), .0001); }
@Test public void testSimilarityVerb() { Synset s1 = new BaseSynset(PartsOfSpeech.VERB); Synset s2 = new BaseSynset(PartsOfSpeech.VERB); addParents(s1, s2); MockReader reader = new MockReader(); SynsetSimilarity sim = new LeacockChodorowSimilarity(reader); double expected = -1 * Math.log(7 / (2d * 2)); assertEquals(expected, sim.similarity(s1, s2), .0001); } |
LeacockChodorowScaledSimilarity extends LeacockChodorowSimilarity { public double similarity(Synset synset1, Synset synset2) { double lchSim = super.similarity(synset1, synset2); int maxDepth = wordnet.getMaxDepth(synset1.getPartOfSpeech()); double maxSim = -1 * Math.log(1/(2d* maxDepth)); return lchSim / maxSim; } LeacockChodorowScaledSimilarity(OntologyReader reader); double similarity(Synset synset1, Synset synset2); } | @Test public void testWrongPos() { Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); Synset s2 = new BaseSynset(PartsOfSpeech.VERB); MockReader reader = new MockReader(); SynsetSimilarity sim = new LeacockChodorowScaledSimilarity(reader); assertEquals(0, sim.similarity(s1, s2), .0001); }
@Test public void testSimilarity() { Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); Synset s2 = new BaseSynset(PartsOfSpeech.NOUN); addParents(s1, s2); MockReader reader = new MockReader(); SynsetSimilarity sim = new LeacockChodorowScaledSimilarity(reader); double max = -1 * Math.log(1/(2d*1)); double expected = -1 * Math.log(7 / (2d * 1)) / max; assertEquals(expected, sim.similarity(s1, s2), .0001); }
@Test public void testSimilarityVerb() { Synset s1 = new BaseSynset(PartsOfSpeech.VERB); Synset s2 = new BaseSynset(PartsOfSpeech.VERB); addParents(s1, s2); MockReader reader = new MockReader(); SynsetSimilarity sim = new LeacockChodorowScaledSimilarity(reader); double max = -1 * Math.log(1/(2d*2)); double expected = -1 * Math.log(7 / (2d * 2)) / max; assertEquals(expected, sim.similarity(s1, s2), .0001); } |
ExtendedLeskSimilarity implements SynsetSimilarity { public double similarity(Synset synset1, Synset synset2) { Set<Synset> synsets1 = Sets.newHashSet(synset1.allRelations()); synsets1.add(synset1); Set<Synset> synsets2 = Sets.newHashSet(synset2.allRelations()); synsets2.add(synset2); double score = 0; for (Synset s1 : synsets1) for (Synset s2 : synsets2) score += score(s1.getGloss(), s2.getGloss()); return score; } double similarity(Synset synset1, Synset synset2); } | @Test public void testLeskSimilarity() { Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); Synset s2 = new BaseSynset(PartsOfSpeech.NOUN); Synset p2 = new BaseSynset(PartsOfSpeech.NOUN); s1.setDefinition("how now brown cow"); s2.setDefinition("how now sad meow"); p2.setDefinition("cow sad sad"); s2.addRelation(Relation.HYPERNYM, p2); SynsetSimilarity sim = new ExtendedLeskSimilarity(); assertEquals(6, sim.similarity(s1, s2), .00001); } |
ExtendedLeskWordSenseDisambiguation extends LeskWordSenseDisambiguation { public void setup(OntologyReader reader) { this.reader = reader; this.sim = new ExtendedLeskSimilarity(); } void setup(OntologyReader reader); String toString(); } | @Test public void testDisambiguation() { WordSenseDisambiguation wsdAlg = new ExtendedLeskWordSenseDisambiguation(); Sentence sentences = getSentences(TEST_SENTENCE, TEST_POS); wsdAlg.setup(new GenericMockReader(SYNSET_DATA)); Sentence sent = wsdAlg.disambiguate(sentences); Sentence expected = sentences; assertEquals(expected.numTokens(), sent.numTokens()); assertEquals(expected.start(), sent.start()); assertEquals(expected.end(), sent.end()); Annotation word = sent.getAnnotation(1); assertNotNull(word); assertEquals(SYNSET_DATA[2][0], word.sense()); } |
LeskWordSenseDisambiguation extends SlidingWindowDisambiguation { public void setup(OntologyReader reader) { this.reader = reader; this.sim = new LeskSimilarity(); } void setup(OntologyReader reader); String toString(); } | @Test public void testDisambiguation() { WordSenseDisambiguation wsdAlg = new LeskWordSenseDisambiguation(); Sentence sentences = getSentences(TEST_SENTENCE, TEST_POS); wsdAlg.setup(new GenericMockReader(SYNSET_DATA)); Sentence sent = wsdAlg.disambiguate(sentences); Sentence expected = sentences; assertEquals(expected.numTokens(), sent.numTokens()); assertEquals(expected.start(), sent.start()); assertEquals(expected.end(), sent.end()); Annotation word = sent.getAnnotation(1); assertNotNull(word); assertEquals(SYNSET_DATA[0][0], word.sense()); } |
CombinedSet extends AbstractSet<T> { public int size() { int size = 0; for (Set<T> set : sets) size += set.size(); return size; } CombinedSet(Set<T>...sets); CombinedSet(Collection<Set<T>> setCollection); Iterator<T> iterator(); int size(); } | @Test public void testCombinedSize() { Set<String> set1 = new HashSet<String>(); for (String s : array1) set1.add(s); Set<String> set2 = new HashSet<String>(); for (String s : array2) set2.add(s); Set<String> combined = new CombinedSet<String>(set1, set2); assertEquals(6, combined.size()); } |
PersonalizedPageRankWSD extends SlidingWindowDisambiguation { public void setup(OntologyReader wordnet) { this.wordnet = wordnet; synsetMap = Maps.newHashMap(); synsetList = Lists.newArrayList(); for (String lemma : wordnet.wordnetTerms()) { for (Synset synset : wordnet.getSynsets(lemma)) if (!synsetMap.containsKey(synset)) { synsetMap.put(synset, synsetMap.size()); synsetList.add(synset); } } SynsetPagerank.setupTransitionAttributes(synsetList, synsetMap); } void setup(OntologyReader wordnet); String toString(); static final String LINK; } | @Test public void testDisambiguation() { WordSenseDisambiguation wsdAlg = new PersonalizedPageRankWSD(); Sentence sentences = getSentences(TEST_SENTENCE, TEST_POS); LinkedMockReader reader = new LinkedMockReader(SYNSET_DATA); for (String[] synsetLink : SYNSET_LINKS) reader.connectSynsets(synsetLink[0], synsetLink[1], "r"); wsdAlg.setup(reader); Sentence sent = wsdAlg.disambiguate(sentences); Sentence expected = sentences; assertEquals(expected.numTokens(), sent.numTokens()); assertEquals(expected.start(), sent.start()); assertEquals(expected.end(), sent.end()); Annotation word = sent.getAnnotation(1); assertNotNull(word); assertEquals(SYNSET_DATA[2][0], word.sense()); } |
CombinedSet extends AbstractSet<T> { public Iterator<T> iterator() { List<Iterator<T>> iters = new ArrayList<Iterator<T>>(); for (Set<T> set : sets) iters.add(set.iterator()); return new CombinedIterator<T>(iters); } CombinedSet(Set<T>...sets); CombinedSet(Collection<Set<T>> setCollection); Iterator<T> iterator(); int size(); } | @Test public void testIterator() { Set<String> set1 = new HashSet<String>(); for (String s : array1) set1.add(s); Set<String> set2 = new HashSet<String>(); for (String s : array2) set2.add(s); Set<String> combined = new CombinedSet<String>(set1, set2); Iterator<String> comboIter = combined.iterator(); Iterator<String> iter1 = set1.iterator(); Iterator<String> iter2 = set2.iterator(); while (iter1.hasNext()) { assertTrue(comboIter.hasNext()); assertEquals(iter1.next(), comboIter.next()); } while (iter2.hasNext()) { assertTrue(comboIter.hasNext()); assertEquals(iter2.next(), comboIter.next()); } } |
ExtendedMap extends AbstractMap<K, V> { public V put(K key, V value) { if (baseMap.containsKey(key)) throw new IllegalArgumentException("Should not reinsert keys"); return extendedMap.put(key, value); } ExtendedMap(Map<K, V> baseMap); Set<Map.Entry<K, V>> entrySet(); V get(Object key); V put(K key, V value); } | @Test public void testPut() { Map<String,String> extendedMap = new ExtendedMap<String, String>(map1); for (Map.Entry<String, String> s : map2.entrySet()) assertNull(extendedMap.put(s.getKey(), s.getValue())); assertEquals(3, map1.size()); } |
ExtendedMap extends AbstractMap<K, V> { public V get(Object key) { V value = baseMap.get(key); return (value != null) ? value : extendedMap.get(key); } ExtendedMap(Map<K, V> baseMap); Set<Map.Entry<K, V>> entrySet(); V get(Object key); V put(K key, V value); } | @Test public void testGet() { Map<String,String> extendedMap = new ExtendedMap<String, String>(map1); for (String key : map1.keySet()) assertEquals(map1.get(key), extendedMap.get(key)); for (Map.Entry<String, String> s : map2.entrySet()) extendedMap.put(s.getKey(), s.getValue()); for (String key : map1.keySet()) assertEquals(map1.get(key), extendedMap.get(key)); for (String key : map2.keySet()) if (!map1.containsKey(key)) assertEquals(map2.get(key), extendedMap.get(key)); } |
VideoIndexUtils { public static VideoIndex resolve(VideoIndex videoIndex, Media media) { VideoIndex vi = videoIndex; if (videoIndex.getElapsedTime().isEmpty() && videoIndex.getTimestamp().isPresent()) { Instant endTimestamp = media.getStartTimestamp().plus(media.getDuration()); Instant timestamp = videoIndex.getTimestamp().get(); if (timestamp.isBefore(endTimestamp)) { long millis = timestamp.toEpochMilli() - media.getStartTimestamp().toEpochMilli(); if (millis >= 0) { Optional<Duration> elapsedTime = Optional.of(Duration.ofMillis(millis)); vi = new VideoIndex(videoIndex.getTimestamp(), elapsedTime, vi.getTimecode()); } } } else if (videoIndex.getTimestamp().isEmpty() && videoIndex.getElapsedTime().isPresent()) { Instant timestamp = media.getStartTimestamp().plus(videoIndex.getElapsedTime().get()); vi = new VideoIndex(Optional.of(timestamp), videoIndex.getElapsedTime(), videoIndex.getTimecode()); } return vi; } static Optional<Duration> diff(VideoIndex a, VideoIndex b); static VideoIndex resolve(VideoIndex videoIndex, Media media); static VideoIndex resolve(VideoIndex videoIndex, Media source, Media target); } | @Test public void resolveAddElapsedTimeTest() { var et = Duration.ofMinutes(2); var ts = now.plus(et); var vi = new VideoIndex(ts); var rvi = VideoIndexUtils.resolve(vi, media1); assertTrue(rvi.getTimestamp().isPresent()); assertEquals(ts, rvi.getTimestamp().get()); assertTrue(rvi.getElapsedTime().isPresent()); assertEquals(et, rvi.getElapsedTime().get()); }
@Test public void resolveAddTimestampTest() { var et = Duration.ofMinutes(2); var ts = now.plus(et); var vi = new VideoIndex(et); var rvi = VideoIndexUtils.resolve(vi, media1); assertTrue(rvi.getTimestamp().isPresent()); assertEquals(ts, rvi.getTimestamp().get()); assertTrue(rvi.getElapsedTime().isPresent()); assertEquals(et, rvi.getElapsedTime().get()); } |
Pager implements Runnable { public Pager(BiFunction<Long, Long, T> fetchFn, Long limit, Long pageSize) { Function<RequestPager.Page, T> fn = (page) -> { try { return fetchFn.apply(page.getLimit(), page.getOffset()); } catch (Exception e) { Long start = page.getOffset(); Long end = start + page.getLimit(); throw new RuntimeException("Page request from " + start + " + to " + end + " failed"); } }; RequestPager<T> pager = new RequestPager<>(fn, 2, 2); runner = pager.build(limit.intValue(), pageSize.intValue()); } Pager(BiFunction<Long, Long, T> fetchFn, Long limit, Long pageSize); void run(); Observable<T> getObservable(); } | @Test public void testPager() { var data = new ArrayList<Integer>(); for (var i = 0; i < 1000; i++) { data.add(i); } var pager = new Pager<>((limit, offset) -> { var start = offset; Long end = limit + offset; if (start > data.size()) { start = (long) data.size() - 1; } if (end >= data.size()) { end = (long) data.size(); } return data.subList(start.intValue(), end.intValue()); }, (long) data.size(), 10L); var n = new AtomicInteger(0); pager.getObservable() .subscribe(xs -> n.addAndGet(xs.size()), ex -> Assert.fail(), () -> Assert.assertEquals(data.size(), n.get())); pager.run(); } |
AVFImageCaptureService implements SelectableImageCaptureService { @Override public Framegrab capture(File file) { Framegrab framegrab = new Framegrab(); start(); Optional<Image> imageOpt = imageCapture.capture(file, Duration.ofSeconds(10)); if (imageOpt.isPresent()) { framegrab.setImage(imageOpt.get()); MediaPlayer<? extends VideoState, ? extends VideoError> mediaPlayer = Initializer.getToolBox().getMediaPlayer(); if (mediaPlayer != null) { try { mediaPlayer.requestVideoIndex() .thenAccept(framegrab::setVideoIndex) .get(3000, TimeUnit.MILLISECONDS); } catch (Exception e) { log.warn("Problem with requesting videoIndex while capturing a framegrab", e); framegrab.setVideoIndex(new VideoIndex(Instant.now())); } } if (!framegrab.getVideoIndex().isPresent()) { log.warn("Failed to get video index. Using current timestamp for video index"); framegrab.setVideoIndex(new VideoIndex(Instant.now())); } } else { log.warn("Failed to capture image from device named '" + currentDevice + "'"); } return framegrab; } protected AVFImageCaptureService(); Collection<String> listDevices(); void setDevice(String device); @Override Framegrab capture(File file); @Override void dispose(); static synchronized AVFImageCaptureService getInstance(); AVFImageCapture getImageCapture(); static AVFImageCaptureService imageCaptureService; } | @Ignore @Test public void testImageCapture() throws Exception { AVFImageCapture ic = new AVFImageCapture(); String[] devices = ic.videoDevicesAsStrings(); if (devices.length > 0) { ic.startSessionWithNamedDevice(devices[0]); Path path = Paths.get("target", getClass().getSimpleName() + "-0-" + Instant.now() + ".png"); Optional<Image> png = ic.capture(path.toFile()); Assert.assertTrue(png.isPresent()); ic.stopSession(); } else { System.err.println("No frame capture devices were found"); } } |
Initializer { public static Path getSettingsDirectory() { if (settingsDirectory == null) { String home = System.getProperty("user.home"); Path path = Paths.get(home, ".vars"); settingsDirectory = createDirectory(path); if (settingsDirectory == null) { log.warn("Failed to create settings directory at " + path); } } return settingsDirectory; } static Config getConfig(); static UIToolBox getToolBox(); static Path getSettingsDirectory(); static Path getImageDirectory(); static Path createDirectory(Path path); } | @Test public void getSettingsDirectoryTest() { Path path = Initializer.getSettingsDirectory(); assertNotNull("The Settings directory was null", path); assertTrue("The settings directory does not exist", Files.exists(path)); } |
Initializer { public static UIToolBox getToolBox() { if (toolBox == null) { Services services = ServicesBuilder.build(Initializer.getConfig()); ResourceBundle bundle = ResourceBundle.getBundle("i18n", Locale.getDefault()); LessCSSLoader lessLoader = new LessCSSLoader(); String stylesheet = lessLoader.loadLess(Initializer.class.getResource("/less/annotation.less")) .toExternalForm(); Data data = new Data(); Integer timeJump = SharktopodaSettingsPaneController.getTimeJump(); log.info("Setting Time Jump to {} millis", timeJump); data.setTimeJump(timeJump); toolBox = new UIToolBox(data, services, new EventBus(), bundle, getConfig(), Collections.singletonList(stylesheet), new ForkJoinPool()); } return toolBox; } static Config getConfig(); static UIToolBox getToolBox(); static Path getSettingsDirectory(); static Path getImageDirectory(); static Path createDirectory(Path path); } | @Ignore @Test public void getToolBoxTest() throws Exception { UIToolBox toolBox = Initializer.getToolBox(); assertNotNull("UIToolBox was null", toolBox); Data data = toolBox.getData(); assertNotNull("Data in toolbox was null", data); Services services = toolBox.getServices(); assertNotNull("Services in toolbox was null", data); } |
GraywaterAdapter extends RecyclerView.Adapter<VH> { public void add(@NonNull final T item) { add(mItems.size(), item, true); } @Override int getItemViewType(final int position); @Override VH onCreateViewHolder(final ViewGroup parent, final int viewType); @Override @SuppressLint("RecyclerView") void onBindViewHolder(final VH holder, final int viewHolderPosition); @VisibleForTesting int getViewHolderCount(final int itemPosition); @Override int getItemCount(); void add(@NonNull final T item); void add(@NonNull final T item, final boolean notify); int getItemPosition(final int viewHolderPosition); int getBinderPosition(final int itemIndex, final int viewHolderPosition); void add(final int position, @NonNull final T item, final boolean notify); @Nullable T remove(final int itemPosition); @Nullable T remove(final int itemPosition, final boolean notify); int getFirstViewHolderPosition(final int itemPosition, @NonNull final Class<? extends VH> viewHolderClass); void clear(); static View inflate(final ViewGroup parent, @LayoutRes final int layoutRes); @Override void onViewRecycled(final VH holder); @NonNull List<T> getItems(); @Nullable List<Provider<Binder<? super T, VH, ? extends VH>>> getBindersForPosition(final int itemPosition); @Nullable Pair<Integer, Integer> getViewHolderRange(final int itemPosition); } | @Test public void testAdd() throws Exception { final TestAdapter adapter = new TestAdapter(); adapter.add("one"); assertEquals(2, adapter.getItemCount()); adapter.add("two"); assertEquals(4, adapter.getItemCount()); adapter.add("three"); assertEquals(6, adapter.getItemCount()); } |
GraywaterAdapter extends RecyclerView.Adapter<VH> { @Nullable public T remove(final int itemPosition) { return remove(itemPosition, true); } @Override int getItemViewType(final int position); @Override VH onCreateViewHolder(final ViewGroup parent, final int viewType); @Override @SuppressLint("RecyclerView") void onBindViewHolder(final VH holder, final int viewHolderPosition); @VisibleForTesting int getViewHolderCount(final int itemPosition); @Override int getItemCount(); void add(@NonNull final T item); void add(@NonNull final T item, final boolean notify); int getItemPosition(final int viewHolderPosition); int getBinderPosition(final int itemIndex, final int viewHolderPosition); void add(final int position, @NonNull final T item, final boolean notify); @Nullable T remove(final int itemPosition); @Nullable T remove(final int itemPosition, final boolean notify); int getFirstViewHolderPosition(final int itemPosition, @NonNull final Class<? extends VH> viewHolderClass); void clear(); static View inflate(final ViewGroup parent, @LayoutRes final int layoutRes); @Override void onViewRecycled(final VH holder); @NonNull List<T> getItems(); @Nullable List<Provider<Binder<? super T, VH, ? extends VH>>> getBindersForPosition(final int itemPosition); @Nullable Pair<Integer, Integer> getViewHolderRange(final int itemPosition); } | @Test public void testRemove() throws Exception { final TestAdapter adapter = new TestAdapter(); adapter.add("zero"); adapter.add("one"); adapter.add("two"); adapter.add("three"); adapter.add("four"); adapter.add("five"); adapter.remove(0); assertEquals(2 * 5, adapter.getItemCount()); adapter.remove(4); assertEquals(2 * 4, adapter.getItemCount()); adapter.remove(2); assertEquals(2 * 3, adapter.getItemCount()); final List<Object> items = adapter.getItems(); assertEquals(3, items.size()); assertEquals("one", items.get(0)); assertEquals("two", items.get(1)); assertEquals("four", items.get(2)); } |
GraywaterAdapter extends RecyclerView.Adapter<VH> { @Override public int getItemViewType(final int position) { return internalGetItemViewType(position); } @Override int getItemViewType(final int position); @Override VH onCreateViewHolder(final ViewGroup parent, final int viewType); @Override @SuppressLint("RecyclerView") void onBindViewHolder(final VH holder, final int viewHolderPosition); @VisibleForTesting int getViewHolderCount(final int itemPosition); @Override int getItemCount(); void add(@NonNull final T item); void add(@NonNull final T item, final boolean notify); int getItemPosition(final int viewHolderPosition); int getBinderPosition(final int itemIndex, final int viewHolderPosition); void add(final int position, @NonNull final T item, final boolean notify); @Nullable T remove(final int itemPosition); @Nullable T remove(final int itemPosition, final boolean notify); int getFirstViewHolderPosition(final int itemPosition, @NonNull final Class<? extends VH> viewHolderClass); void clear(); static View inflate(final ViewGroup parent, @LayoutRes final int layoutRes); @Override void onViewRecycled(final VH holder); @NonNull List<T> getItems(); @Nullable List<Provider<Binder<? super T, VH, ? extends VH>>> getBindersForPosition(final int itemPosition); @Nullable Pair<Integer, Integer> getViewHolderRange(final int itemPosition); } | @Test public void testGetItemViewType() throws Exception { final TestAdapter adapter = new TestAdapter(); adapter.add(Uri.parse("https: assertEquals(3, adapter.getItemCount()); adapter.add("one"); assertEquals(5, adapter.getItemCount()); adapter.add(Uri.parse("http: assertEquals(8, adapter.getItemCount()); adapter.add("three"); assertEquals(10, adapter.getItemCount()); adapter.add(Uri.parse("https: assertEquals(13, adapter.getItemCount()); adapter.add("five"); assertEquals(15, adapter.getItemCount()); assertEquals(TestAdapter.ImageViewHolderCreator.VIEW_TYPE, adapter.getItemViewType(0)); assertEquals(TestAdapter.ImageViewHolderCreator.VIEW_TYPE, adapter.getItemViewType(1)); assertEquals(TestAdapter.ImageViewHolderCreator.VIEW_TYPE, adapter.getItemViewType(2)); assertEquals(TestAdapter.TextViewHolderCreator.VIEW_TYPE, adapter.getItemViewType(3)); assertEquals(TestAdapter.TextViewHolderCreator.VIEW_TYPE, adapter.getItemViewType(4)); assertEquals(TestAdapter.ImageViewHolderCreator.VIEW_TYPE, adapter.getItemViewType(5)); assertEquals(TestAdapter.ImageViewHolderCreator.VIEW_TYPE, adapter.getItemViewType(6)); assertEquals(TestAdapter.ImageViewHolderCreator.VIEW_TYPE, adapter.getItemViewType(10)); assertEquals(TestAdapter.ImageViewHolderCreator.VIEW_TYPE, adapter.getItemViewType(11)); assertEquals(TestAdapter.ImageViewHolderCreator.VIEW_TYPE, adapter.getItemViewType(12)); assertEquals(TestAdapter.TextViewHolderCreator.VIEW_TYPE, adapter.getItemViewType(13)); assertEquals(TestAdapter.TextViewHolderCreator.VIEW_TYPE, adapter.getItemViewType(14)); } |
GraywaterAdapter extends RecyclerView.Adapter<VH> { public void clear() { mItems.clear(); mBinderListCache.clear(); mViewHolderToItemPositionCache.clear(); mItemPositionToFirstViewHolderPositionCache.clear(); mViewHolderPreparedCache.clear(); mPreviousBoundViewHolderPosition = NO_PREVIOUS_BOUND_VIEWHOLDER; } @Override int getItemViewType(final int position); @Override VH onCreateViewHolder(final ViewGroup parent, final int viewType); @Override @SuppressLint("RecyclerView") void onBindViewHolder(final VH holder, final int viewHolderPosition); @VisibleForTesting int getViewHolderCount(final int itemPosition); @Override int getItemCount(); void add(@NonNull final T item); void add(@NonNull final T item, final boolean notify); int getItemPosition(final int viewHolderPosition); int getBinderPosition(final int itemIndex, final int viewHolderPosition); void add(final int position, @NonNull final T item, final boolean notify); @Nullable T remove(final int itemPosition); @Nullable T remove(final int itemPosition, final boolean notify); int getFirstViewHolderPosition(final int itemPosition, @NonNull final Class<? extends VH> viewHolderClass); void clear(); static View inflate(final ViewGroup parent, @LayoutRes final int layoutRes); @Override void onViewRecycled(final VH holder); @NonNull List<T> getItems(); @Nullable List<Provider<Binder<? super T, VH, ? extends VH>>> getBindersForPosition(final int itemPosition); @Nullable Pair<Integer, Integer> getViewHolderRange(final int itemPosition); } | @Test public void testClear() throws Exception { final TestAdapter adapter = new TestAdapter(); final Uri tumblrUri = Uri.parse("https: adapter.add(tumblrUri); assertEquals(3, adapter.getItemCount()); adapter.add("one"); assertEquals(5, adapter.getItemCount()); adapter.add(Uri.parse("http: assertEquals(8, adapter.getItemCount()); adapter.add("three"); assertEquals(10, adapter.getItemCount()); final Uri googleUri = Uri.parse("https: adapter.add(googleUri); assertEquals(13, adapter.getItemCount()); adapter.add("five"); assertEquals(15, adapter.getItemCount()); adapter.clear(); assertEquals(0, adapter.getItemCount()); } |
ZNodePath extends ZNodeLabelVector { public static String canonicalize(final String path) { final int length = path.length(); int lastSlash = -1; StringBuilder builder = null; for (int i=0; i<length; ++i) { char c = path.charAt(i); if ((c == SLASH) || (i == length - 1)) { if (i > 0) { if ((c == SLASH) && (lastSlash == i-1)) { if (builder == null) { builder = new StringBuilder(length) .append(path, 0, lastSlash+1); } } else { ZNodeLabel label = ZNodeLabel.validated(path, lastSlash+1, (c == SLASH) ? i : i+1); if (ZNodeLabel.self().equals(label)) { if (builder == null) { builder = new StringBuilder(length) .append(path, 0, lastSlash+1); } } else if (ZNodeLabel.parent().equals(label)) { if (builder == null) { builder = new StringBuilder(length) .append(path, 0, lastSlash+1); } int buildLength = builder.length(); assert (builder.charAt(buildLength -1) == SLASH); int parentSlash = -1; for (int j = buildLength-2; j >= 0; j--) { if (builder.charAt(j) == SLASH) { parentSlash = j; break; } } if (parentSlash < 0) { throw new IllegalArgumentException(String.format("missing parent at index %d of %s", i, path)); } builder.delete(parentSlash + 1, buildLength); } else { if (builder != null) { builder.append(path, lastSlash+1, i+1); } } } } if (c == SLASH) { lastSlash = i; } } } String canonicalized; if (builder == null) { canonicalized = ((length > 1) && (path.charAt(length - 1) == SLASH)) ? path.substring(0, length - 1) : path; } else { int buildLength = builder.length(); if ((buildLength > 1) && (builder.charAt(buildLength - 1) == SLASH)) { builder.deleteCharAt(buildLength - 1); } canonicalized = builder.toString(); } if (canonicalized.isEmpty()) { throw new IllegalArgumentException(String.format("empty canonicalized path for %s", path)); } if (canonicalized.charAt(0) != SLASH) { throw new IllegalArgumentException(String.format("not absolute path for %s", path)); } return canonicalized; } protected ZNodePath(String label); static RootZNodePath root(); static String validate(String path); @SuppressWarnings("unchecked") static T validate(T path, int start, int end); static ZNodePath validated(String path); static ZNodePath validated(String path, int start, int end); static String canonicalize(final String path); static ZNodePath canonicalized(String path); @Serializes(from=String.class, to=ZNodePath.class) static ZNodePath fromString(String path); @Override final boolean isAbsolute(); RelativeZNodePath relative(ZNodePath other); @Override abstract ZNodePath join(ZNodeName other); abstract boolean isRoot(); abstract AbstractZNodeLabel label(); } | @Test public void testCanonicalize() { assertEquals("/", ZNodePath.canonicalize("/")); assertEquals("/", ZNodePath.canonicalize(" assertEquals("/", ZNodePath.canonicalize(" assertEquals("/a", ZNodePath.canonicalize("/a")); assertEquals("/a", ZNodePath.canonicalize("/a/")); assertEquals("/", ZNodePath.canonicalize("/.")); assertEquals("/a", ZNodePath.canonicalize("/a/.")); assertEquals("/", ZNodePath.canonicalize("/a/..")); } |
IterableNullChecker { public static <T> Iterable<T> checkNotContainsNull(final Iterable<T> iterable, final String errorMessage) { checkNotNull(iterable, "Argument \'iterable\' cannot be null."); checkNotNull(errorMessage, "Argument \'errorMessage\' cannot be null."); for (final Object o : iterable) { checkNotNull(o, errorMessage); } return iterable; } static Iterable<T> checkNotContainsNull(final Iterable<T> iterable, final String errorMessage); } | @Test(expected = IllegalArgumentException.class) public void testCheckNotContainsNull_nullIterable() { IterableNullChecker.checkNotContainsNull(null, ""); }
@Test public void testCheckNotContainsNull_emptyIterable() { IterableNullChecker.checkNotContainsNull(new ArrayList<>(), ""); }
@Test(expected = IllegalArgumentException.class) public void testCheckNotContainsNull_iterableContainingOnlyNull() { final List<Object> list = new ArrayList<>(); list.add(null); IterableNullChecker.checkNotContainsNull(list, ""); }
@Test(expected = IllegalArgumentException.class) public void testCheckNotContainsNull_iterableContainingNullAndOtherValues() { final List<Object> list = new ArrayList<>(); list.add(null); list.add("hello"); IterableNullChecker.checkNotContainsNull(list, ""); }
@Test public void testCheckNotContainsNull_iterableContainingOnlyNonNullValues() { final List<Object> list = new ArrayList<>(); list.add("hello"); list.add("world"); IterableNullChecker.checkNotContainsNull(list, ""); }
@Test(expected = IllegalArgumentException.class) public void testCheckNotContainsNull_nullErrorMessage() { IterableNullChecker.checkNotContainsNull(new ArrayList<>(), null); } |
CommonFunctions extends AbstractCommonFunctions implements SelfReference { @Deprecated public boolean takeItem(Player player, int id, int amount) { ItemStack IS = new ItemStack(id, amount); if (!player.getInventory().containsAtLeast(IS, amount)) return false; player.getInventory().removeItem(IS); return true; } CommonFunctions(TriggerReactorCore plugin); @Deprecated boolean takeItem(Player player, int id, int amount); boolean takeItem(Player player, String id, int amount); @Deprecated boolean takeItem(Player player, int id, int amount, int data); boolean takeItem(Player player, String id, int amount, int data); Collection<? extends Player> getPlayers(); @Override PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); @Deprecated ItemStack item(int type, int amount, int data); ItemStack item(String type, int amount, int data); @Deprecated ItemStack item(int type, int amount); ItemStack item(String type, int amount); ItemStack headForName(String targetName, int amount); ItemStack headForValue(String textureValue); } | @SuppressWarnings("deprecation") @Test public void testTakeItem() { ItemStack IS = new ItemStack(Material.STONE, 64); ItemStack IS2 = new ItemStack(Material.STONE, 64, (short) 1); FakeInventory inv = fInventory(this, IS, IS2); Player mockPlayer = Mockito.mock(Player.class); PlayerInventory mockInventory = preparePlayerInventory(mockPlayer, inv); Mockito.when(mockPlayer.getInventory()).thenReturn(mockInventory); fn.takeItem(mockPlayer, "STONE", 1); Assert.assertEquals(63, IS.getAmount()); fn.takeItem(mockPlayer, "STONE", 2, 1); Assert.assertEquals(62, IS2.getAmount()); fn.takeItem(mockPlayer, 1, 5); Assert.assertEquals(58, IS.getAmount()); fn.takeItem(mockPlayer, 1, 6, 1); Assert.assertEquals(56, IS2.getAmount()); } |
AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public String currentAreaAt(Location location) { String[] areaNames = currentAreasAt(location); return areaNames.length > 0 ? areaNames[0] : null; } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); } | @Test public void testCurrentAreaAt() { } |
AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public String[] currentAreas(Entity entity) { return currentAreasAt(entity.getLocation()); } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); } | @Test public void testCurrentAreas() { } |
AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public String[] currentAreasAt(Location location) { AbstractAreaTriggerManager areaManager = plugin.getAreaManager(); String[] names = areaManager.getAreas(LocationUtil.convertToSimpleLocation(location)).stream() .map(Map.Entry::getValue) .map(Trigger::getTriggerName) .toArray(String[]::new); return names; } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); } | @Test public void testCurrentAreasAt() { } |
AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public List<Entity> getEntitiesInArea(String areaTriggerName) { AbstractAreaTriggerManager areaManager = plugin.getAreaManager(); AreaTrigger trigger = areaManager.getArea(areaTriggerName); if (trigger == null) return null; List<Entity> entities = new ArrayList<>(); for (IEntity ie : trigger.getEntities()) entities.add(ie.get()); return entities; } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); } | @Test public void testGetEntitiesInArea() { } |
AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public String color(String str) { return ChatColor.translateAlternateColorCodes('&', str); } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); } | @Test public void testColor() { Assert.assertEquals(ChatColor.RED + "My message", fn.color("&cMy message")); } |
AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public Color bukkitColor(int red, int green, int blue) { return Color.fromRGB(red, green, blue); } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); } | @Test public void testBukkitColor() { Color expect = Color.fromRGB(3, 6, 8); Color result = fn.bukkitColor(3, 6, 8); Assert.assertEquals(expect.asBGR(), result.asBGR()); } |
AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { @Deprecated public abstract ItemStack item(int type, int amount, int data); AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); } | @Test public abstract void testItem(); |
AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public String getItemTitle(ItemStack IS) { ItemMeta IM = IS.getItemMeta(); if (IM == null) return ""; String dispName = IM.getDisplayName(); return dispName == null ? "" : dispName; } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); } | @Test public void testGetItemTitle() { ItemStack IS = new ItemStack(Material.STONE); Mockito.doAnswer(invocation -> "abc").when(mockItemMeta).getDisplayName(); Assert.assertEquals("abc", fn.getItemTitle(IS)); } |
AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public void setItemTitle(ItemStack IS, String title) { ItemMeta IM = IS.getItemMeta(); if (IM == null) IM = Bukkit.getItemFactory().getItemMeta(IS.getType()); if (IM == null) return; IM.setDisplayName(color(title)); IS.setItemMeta(IM); } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); } | @Test public void testSetItemTitle() { ItemStack IS = new ItemStack(Material.STONE); Mockito.doAnswer(invocation -> { title = invocation.getArgument(0); return null; }).when(mockItemMeta).setDisplayName(Mockito.anyString()); fn.setItemTitle(IS, "xyz"); Assert.assertEquals("xyz", title); } |
AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public boolean hasLore(ItemStack IS, String lore) { ItemMeta IM = IS.getItemMeta(); if (IM == null) return false; List<String> lores = IM.getLore(); if (lores == null) return false; return lores.contains(lore); } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); } | @Test public void testHasLore() { List<String> lores = new ArrayList<>(); lores.add("abab"); lores.add("cdcd"); ItemStack IS = new ItemStack(Material.STONE); Mockito.doAnswer(invocation -> lores).when(mockItemMeta).getLore(); Assert.assertTrue(fn.hasLore(IS, "abab")); Assert.assertFalse(fn.hasLore(IS, "hoho")); } |
CommonFunctions extends AbstractCommonFunctions implements SelfReference { @Deprecated public ItemStack item(int type, int amount, int data) { return new ItemStack(type, amount, (short) data); } CommonFunctions(TriggerReactorCore plugin); @Deprecated boolean takeItem(Player player, int id, int amount); boolean takeItem(Player player, String id, int amount); @Deprecated boolean takeItem(Player player, int id, int amount, int data); boolean takeItem(Player player, String id, int amount, int data); Collection<? extends Player> getPlayers(); @Override PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); @Deprecated ItemStack item(int type, int amount, int data); ItemStack item(String type, int amount, int data); @Deprecated ItemStack item(int type, int amount); ItemStack item(String type, int amount); ItemStack headForName(String targetName, int amount); ItemStack headForValue(String textureValue); } | @SuppressWarnings("deprecation") @Test public void testItem() { ItemStack IS = new ItemStack(Material.STONE, 64); ItemStack IS2 = new ItemStack(Material.STONE, 63, (short) 1); Assert.assertTrue(isEqual(IS, fn.item("STONE", 64))); Assert.assertTrue(isEqual(IS2, fn.item("STONE", 63, 1))); Assert.assertTrue(isEqual(IS, fn.item(1, 64))); Assert.assertTrue(isEqual(IS2, fn.item(1, 63, 1))); } |
AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public String getLore(ItemStack IS, int index) { ItemMeta IM = IS.getItemMeta(); if (IM == null) return null; List<String> lores = IM.getLore(); if (lores == null) return null; if (index < 0 || index >= lores.size()) return null; return lores.get(index); } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); } | @Test public void testGetLore() { List<String> lores = new ArrayList<>(); lores.add("abab"); lores.add("cdcd"); ItemStack IS = new ItemStack(Material.STONE); Mockito.doAnswer(invocation -> lores).when(mockItemMeta).getLore(); Assert.assertEquals("abab", fn.getLore(IS, 0)); Assert.assertEquals("cdcd", fn.getLore(IS, 1)); Assert.assertNull(fn.getLore(IS, 2)); Assert.assertNull(fn.getLore(IS, -1)); } |
AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public void addLore(ItemStack IS, String lore) { ItemMeta IM = IS.getItemMeta(); if (IM == null) IM = Bukkit.getItemFactory().getItemMeta(IS.getType()); if (IM == null) return; List<String> lores = IM.getLore(); if (lores == null) lores = new ArrayList<>(); lores.add(color(lore)); IM.setLore(lores); IS.setItemMeta(IM); } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); } | @Test public void testAddLore() { List<String> lores = new ArrayList<>(); lores.add("abab"); lores.add("cdcd"); ItemStack IS = new ItemStack(Material.STONE); Mockito.doAnswer(invocation -> lores).when(mockItemMeta).getLore(); fn.addLore(IS, "efef"); Assert.assertEquals(3, lores.size()); Assert.assertEquals("efef", lores.get(lores.size() - 1)); } |
AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public void setLore(ItemStack IS, int index, String lore) { ItemMeta IM = IS.getItemMeta(); if (IM == null) IM = Bukkit.getItemFactory().getItemMeta(IS.getType()); if (IM == null) return; List<String> lores = IM.getLore(); if (lores == null) lores = new ArrayList<>(); while (index >= lores.size()) lores.add(""); lores.set(index, color(lore)); IM.setLore(lores); IS.setItemMeta(IM); } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); } | @Test public void testSetLore() { List<String> lores = new ArrayList<>(); lores.add("abab"); lores.add("cdcd"); ItemStack IS = new ItemStack(Material.STONE); Mockito.doAnswer(invocation -> lores).when(mockItemMeta).getLore(); fn.setLore(IS, 0, "pqpq"); Assert.assertEquals("pqpq", lores.get(0)); fn.setLore(IS, 5, "ffee"); Assert.assertEquals(6, lores.size()); Assert.assertEquals("ffee", lores.get(5)); } |
AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public void removeLore(ItemStack IS, int index) { ItemMeta IM = IS.getItemMeta(); if (IM == null) IM = Bukkit.getItemFactory().getItemMeta(IS.getType()); if (IM == null) return; List<String> lores = IM.getLore(); if (lores == null) lores = new ArrayList<>(); if (index < 0 || index >= lores.size()) return; lores.remove(index); IM.setLore(lores); IS.setItemMeta(IM); } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); } | @Test public void testRemoveLore() { List<String> lores = new ArrayList<>(); lores.add("abab"); lores.add("cdcd"); lores.add("efef"); ItemStack IS = new ItemStack(Material.STONE); Mockito.doAnswer(invocation -> lores).when(mockItemMeta).getLore(); fn.removeLore(IS, 2); Assert.assertEquals(2, lores.size()); Assert.assertFalse(lores.contains("efef")); fn.removeLore(IS, 0); Assert.assertEquals(1, lores.size()); Assert.assertFalse(lores.contains("abab")); Assert.assertEquals("cdcd", lores.get(0)); } |
AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public void clearLore(ItemStack IS) { ItemMeta IM = IS.getItemMeta(); if (IM == null) return; IM.setLore(new ArrayList<>()); IS.setItemMeta(IM); } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); } | @Test public void testClearLore() { ItemStack IS = new ItemStack(Material.STONE); ArgumentCaptor<List> captor = ArgumentCaptor.forClass(List.class); fn.clearLore(IS); Mockito.verify(mockItemMeta).setLore(captor.capture()); Assert.assertEquals(0, captor.getValue().size()); } |
AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public int loreSize(ItemStack IS) { ItemMeta IM = IS.getItemMeta(); if (IM == null) return 0; List<String> lores = IM.getLore(); if (lores == null) return 0; return lores.size(); } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); } | @Test public void testLoreSize() { List<String> lores = new ArrayList<>(); lores.add("abab"); lores.add("cdcd"); lores.add("efef"); ItemStack IS = new ItemStack(Material.STONE); Mockito.doAnswer(invocation -> lores).when(mockItemMeta).getLore(); Assert.assertEquals(3, fn.loreSize(IS)); } |
AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { @Override public String formatCurrency(double money, String locale1, String locale2) { Locale locale = new Locale(locale1, locale2); NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(locale); return currencyFormatter.format(money); } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); } | @Test public void testFormatCurrency() { Assert.assertEquals("$3,234,463.44", fn.formatCurrency(3234463.44)); Assert.assertEquals("$3,234,463.44", fn.formatCurrency(3234463.44, "en", "US")); Assert.assertEquals("\u00a33,234,463.44", fn.formatCurrency(3234463.44, "en", "GB")); } |
AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public Block getTargetBlock(Player player, int maxDistance) { return player.getTargetBlock(null, maxDistance); } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); } | @Test public void testGetTargetBlock() { fn.getTargetBlock(mockPlayer, 30); Mockito.verify(mockPlayer).getTargetBlock(null, 30); } |
AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public ItemStack headForName(String targetName) { return headForName(targetName, 1); } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); } | @Test public abstract void testHeadForName(); |
AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public abstract ItemStack headForValue(String textureValue); AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); } | @Test public abstract void testHeadForValue(); |
AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public Location location(String world, double x, double y, double z) { return location(world, x, y, z, 0.0, 0.0); } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); } | @Test public void testLocation() { Location loc1 = new Location(mockWorld, 1, 2, 3); Location loc2 = new Location(mockWorld, 4, 5, 6, 0.5F, 0.6F); Mockito.when(mockWorld.getName()).thenReturn("test"); Assert.assertEquals(loc1, fn.location("test", 1, 2, 3)); Mockito.when(mockWorld.getName()).thenReturn("test2"); Assert.assertEquals(loc2, fn.location("test2", 4, 5, 6, 0.5, 0.6)); } |
BukkitMigrationHelper implements IMigrationHelper { @Override public void migrate(IConfigSource current) { traversal(null, oldConfig.getValues(false), current::put); if (oldFile.exists()) oldFile.renameTo(new File(oldFile.getParentFile(), "config.yml.bak")); } BukkitMigrationHelper(FileConfiguration oldConfig, File oldFile); @Override void migrate(IConfigSource current); } | @Test public void migrate() { IConfigSource mockSource = mock(IConfigSource.class); FileConfiguration mockConfig = YamlConfiguration.loadConfiguration(new StringReader("" + "Mysql:\n" + " Enable: false\n" + " Address: 127.0.0.1:3306\n" + " DbName: TriggerReactor\n" + " UserName: root\n" + " Password: '1234'\n" + " Deep: \n" + " Value: 5555\n" + " Value2: 52.24\n" + "PermissionManager:\n" + " Intercept: true" + "")); File mockFile = mock(File.class); IMigratable mockMigratable = new IMigratable() { @Override public boolean isMigrationNeeded() { return true; } @Override public void migrate(IMigrationHelper migrationHelper) { migrationHelper.migrate(mockSource); } }; BukkitMigrationHelper helper = new BukkitMigrationHelper(mockConfig, mockFile); mockMigratable.migrate(helper); Mockito.verify(mockSource).put(Mockito.eq("Mysql.Enable"), Mockito.eq(false)); Mockito.verify(mockSource).put(Mockito.eq("Mysql.Address"), Mockito.eq("127.0.0.1:3306")); Mockito.verify(mockSource).put(Mockito.eq("Mysql.DbName"), Mockito.eq("TriggerReactor")); Mockito.verify(mockSource).put(Mockito.eq("Mysql.UserName"), Mockito.eq("root")); Mockito.verify(mockSource).put(Mockito.eq("Mysql.Password"), Mockito.eq("1234")); Mockito.verify(mockSource).put(Mockito.eq("Mysql.Deep.Value"), Mockito.eq(5555)); Mockito.verify(mockSource).put(Mockito.eq("Mysql.Deep.Value2"), Mockito.eq(52.24)); Mockito.verify(mockSource).put(Mockito.eq("PermissionManager.Intercept"), Mockito.eq(true)); } |
Timings { public static Timing getTiming(String name) { return getTiming(root, name); } static void reset(); static Timing getTiming(String name); static void print(Timing timing, OutputStream stream); static void printAll(OutputStream stream); static final Timing LIMBO; static boolean on; } | @Test public void testTiming() { Timings.Timing timingName = Timings.getTiming("my.timing.name"); Timings.Timing timingTiming = Timings.getTiming("my.timing"); Timings.Timing timingMy = Timings.getTiming("my"); Timings.Timing root = Timings.getTiming(null); Assert.assertNotNull(timingName); Assert.assertNotNull(timingTiming); Assert.assertNotNull(timingMy); Assert.assertNotNull(root); Assert.assertEquals(timingName, Timings.getTiming("my.timing.name")); Assert.assertEquals(timingTiming, Timings.getTiming("my.timing")); Assert.assertEquals(timingMy, Timings.getTiming("my")); Assert.assertEquals(root, Timings.getTiming(null)); }
@Test public void testExampleTiming() throws Exception { Timings.on = true; Timings.Timing timingExMessage = Timings.getTiming("CommandTrigger.myCmd.Executors.#MESSAGE"); Timings.Timing timingExTP = Timings.getTiming("CommandTrigger.myCmd.Executors.#TP"); Timings.Timing timingPhPlayerName = Timings.getTiming("CommandTrigger.myCmd.Placeholders.$playername"); Timings.Timing timingPhRandom = Timings.getTiming("CommandTrigger.myCmd.Placeholders.$random"); Timings.Timing timingInterpret = Timings.getTiming("CommandTrigger.myCmd.Interpret"); try (Timings.Timing t = timingExMessage.begin(true)) { Thread.sleep(2L); } try (Timings.Timing t = timingExTP.begin()) { Thread.sleep(5L); } try (Timings.Timing t = timingPhPlayerName.begin()) { Thread.sleep(100L); } try (Timings.Timing t = timingPhRandom.begin()) { Thread.sleep(10L); } try (Timings.Timing t = timingInterpret.begin()) { Thread.sleep(1000L); } Timings.Timing parent = Timings.getTiming("CommandTrigger"); Timings.Timing timingExMessage2 = parent.getTiming("myCmd2.Executors.#MESSAGE"); try (Timings.Timing t = timingExMessage2.begin()) { Thread.sleep(1L); } } |
CommonFunctions implements SelfReference { public int random(int end) { return rand.nextInt(end); } int random(int end); float random(float end); double random(double end); long random(long end); int random(int start, int end); float random(float start, float end); double random(double start, double end); long random(long start, long end); String round(double val, int decimal); Object staticGetFieldValue(String className, String fieldName); void staticSetFieldValue(String className, String fieldName, Object value); Object staticMethod(String className, String methodName, Object... args); @SuppressWarnings("unchecked") Object parseEnum(String enumClassName, String valueName); SimpleLocation slocation(String world, int x, int y, int z); Object newInstance(String className, Object... args); boolean matches(String str, String regex); int parseInt(String str); double parseDouble(String str); Object[] array(int size); List<Object> list(); Map<Object, Object> map(); Set<Object> set(); String mergeArguments(String[] args); String mergeArguments(String[] args, int indexFrom); String mergeArguments(String[] args, int indexFrom, int indexTo); byte toByte(Number number); short toShort(Number number); int toInt(Number number); long toLong(Number number); float toFloat(Number number); double toDouble(Number number); double sqrt(int num); String formatCurrency(double money, String locale1, String locale2); String formatCurrency(double money); String typeOf(Object value, boolean withFullPath); } | @Test public void testRandoms() throws Exception { for (int i = 0; i < trials; i++) { double value = fn.random(1.0); assertTrue(0.0 <= value && value < 1.0); value = fn.random(0.0, 1.0); assertTrue(0.0 <= value && value < 1.0); value = fn.random(1.0F); assertTrue(0.0 <= value && value < 1.0); value = fn.random(0.0F, 1.0F); assertTrue(0.0 <= value && value < 1.0); } for (int i = 0; i < trials; i++) { long value = fn.random(10L); assertTrue(0L <= value && value < 10L); value = fn.random(0L, 10L); assertTrue(0L <= value && value < 10L); int value2 = fn.random(10); assertTrue(0 <= value2 && value2 < 10); value2 = fn.random(0, 10); assertTrue(0 <= value2 && value2 < 10); } } |
CommonFunctions implements SelfReference { public SimpleLocation slocation(String world, int x, int y, int z) { if (world == null) { throw new IllegalArgumentException("world cannot be null"); } return new SimpleLocation(world, x, y, z); } int random(int end); float random(float end); double random(double end); long random(long end); int random(int start, int end); float random(float start, float end); double random(double start, double end); long random(long start, long end); String round(double val, int decimal); Object staticGetFieldValue(String className, String fieldName); void staticSetFieldValue(String className, String fieldName, Object value); Object staticMethod(String className, String methodName, Object... args); @SuppressWarnings("unchecked") Object parseEnum(String enumClassName, String valueName); SimpleLocation slocation(String world, int x, int y, int z); Object newInstance(String className, Object... args); boolean matches(String str, String regex); int parseInt(String str); double parseDouble(String str); Object[] array(int size); List<Object> list(); Map<Object, Object> map(); Set<Object> set(); String mergeArguments(String[] args); String mergeArguments(String[] args, int indexFrom); String mergeArguments(String[] args, int indexFrom, int indexTo); byte toByte(Number number); short toShort(Number number); int toInt(Number number); long toLong(Number number); float toFloat(Number number); double toDouble(Number number); double sqrt(int num); String formatCurrency(double money, String locale1, String locale2); String formatCurrency(double money); String typeOf(Object value, boolean withFullPath); } | @Test public void testSLocation() throws Exception { assertEquals(fn.slocation("merp", 1, 2, 3), new SimpleLocation("merp", 1, 2, 3)); } |
CommonFunctions implements SelfReference { public Object newInstance(String className, Object... args) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalArgumentException, InvocationTargetException { try { Class<?> clazz = Class.forName(className); List<Constructor<?>> validConstructors = new ArrayList<>(); for (Constructor<?> constructor : clazz.getConstructors()) { Class<?>[] parameterTypes = null; parameterTypes = constructor.getParameterTypes(); if (constructor.isVarArgs()) { if (constructor.isVarArgs() && (parameterTypes.length - args.length >= 2)) { parameterTypes = null; continue; } } else { if (parameterTypes.length != args.length) { parameterTypes = null; continue; } } if (constructor.isVarArgs()) { boolean matches = false; for (int i = 0; i < parameterTypes.length - 1; i++) { matches = ReflectionUtil.checkMatch(parameterTypes[i], args[i]); if (!matches) break; } for (int i = parameterTypes.length - 1; i < args.length; i++) { Class<?> arrayType = parameterTypes[parameterTypes.length - 1].getComponentType(); matches = ReflectionUtil.checkMatch(arrayType, args[i]); if (!matches) break; } if (matches) { validConstructors.add(constructor); } } else { boolean matches = true; for (int i = 0; i < parameterTypes.length; i++) { matches = ReflectionUtil.checkMatch(parameterTypes[i], args[i]); if (!matches) break; } if (matches) { validConstructors.add(constructor); } } } if (!validConstructors.isEmpty()) { Constructor<?> constructor = validConstructors.get(0); for (int i = 1; i < validConstructors.size(); i++) { Constructor<?> targetConstructor = validConstructors.get(i); Class<?>[] params = constructor.getParameterTypes(); Class<?>[] otherParams = targetConstructor.getParameterTypes(); if (constructor.isVarArgs() && targetConstructor.isVarArgs()) { for (int j = 0; j < params.length; j++) { if (params[j].isAssignableFrom(otherParams[j])) { constructor = targetConstructor; break; } } } else if (constructor.isVarArgs()) { constructor = targetConstructor; } else if (targetConstructor.isVarArgs()) { } else { for (int j = 0; j < params.length; j++) { if (otherParams[j].isEnum()) { constructor = targetConstructor; break; } else if (ClassUtils.isAssignable(otherParams[j], params[j], true)) { constructor = targetConstructor; break; } } } } constructor.setAccessible(true); for (int i = 0; i < args.length; i++) { Class<?>[] parameterTypes = constructor.getParameterTypes(); if (args[i] instanceof String && i < parameterTypes.length && parameterTypes[i].isEnum()) { try { args[i] = Enum.valueOf((Class<? extends Enum>) parameterTypes[i], (String) args[i]); } catch (IllegalArgumentException ex1) { throw new RuntimeException("Tried to convert value [" + args[i] + "] to Enum [" + parameterTypes[i] + "] or find appropriate method but found nothing. Make sure" + " that the value [" + args[i] + "] matches exactly with one of the Enums in [" + parameterTypes[i] + "] or the method you are looking exists."); } } } if (constructor.isVarArgs()) { Class<?>[] parameterTypes = constructor.getParameterTypes(); Object varargs = Array.newInstance( parameterTypes[parameterTypes.length - 1].getComponentType(), args.length - parameterTypes.length + 1); for (int k = 0; k < Array.getLength(varargs); k++) { Array.set(varargs, k, args[parameterTypes.length - 1 + k]); } Object[] newArgs = new Object[parameterTypes.length]; for (int k = 0; k < newArgs.length - 1; k++) { newArgs[k] = args[k]; } newArgs[newArgs.length - 1] = varargs; args = newArgs; } return constructor.newInstance(args); } if (args.length > 0) { StringBuilder builder = new StringBuilder(args[0].getClass().getSimpleName()); for (int i = 1; i < args.length; i++) { builder.append(", " + args[i].getClass().getSimpleName()); } throw new IllegalArgumentException(className + "(" + builder.toString() + "). " + "Make sure the arguments match."); } else { throw new IllegalArgumentException(className + "(). Make sure the arguments match."); } } catch (NullPointerException e) { StringBuilder builder = new StringBuilder(String.valueOf(args[0])); for (int i = 1; i < args.length; i++) builder.append("," + args[i]); throw new NullPointerException("Attempted to instantiate " + className + "(" + builder.toString() + ")"); } catch (IllegalAccessException e) { throw new RuntimeException("Unexpected exception. Please contact the plugin author!", e); } } int random(int end); float random(float end); double random(double end); long random(long end); int random(int start, int end); float random(float start, float end); double random(double start, double end); long random(long start, long end); String round(double val, int decimal); Object staticGetFieldValue(String className, String fieldName); void staticSetFieldValue(String className, String fieldName, Object value); Object staticMethod(String className, String methodName, Object... args); @SuppressWarnings("unchecked") Object parseEnum(String enumClassName, String valueName); SimpleLocation slocation(String world, int x, int y, int z); Object newInstance(String className, Object... args); boolean matches(String str, String regex); int parseInt(String str); double parseDouble(String str); Object[] array(int size); List<Object> list(); Map<Object, Object> map(); Set<Object> set(); String mergeArguments(String[] args); String mergeArguments(String[] args, int indexFrom); String mergeArguments(String[] args, int indexFrom, int indexTo); byte toByte(Number number); short toShort(Number number); int toInt(Number number); long toLong(Number number); float toFloat(Number number); double toDouble(Number number); double sqrt(int num); String formatCurrency(double money, String locale1, String locale2); String formatCurrency(double money); String typeOf(Object value, boolean withFullPath); } | @Test public void testConstructor() throws Exception { ExampleClass e = (ExampleClass) fn.newInstance(example, 1); assertEquals(0, e.marker); e = (ExampleClass) fn.newInstance(example, new Double(1.1)); assertEquals(2, e.marker); File file = null; try { file = (File) fn.newInstance("java.io.File", "test.txt"); FileWriter writer = (FileWriter) fn.newInstance("java.io.FileWriter", file); writer.write("Something"); writer.close(); FileReader reader = (FileReader) fn.newInstance("java.io.FileReader", file); Scanner sc = new Scanner(reader); Assert.assertEquals("Something", sc.nextLine()); sc.close(); } finally { if (file != null) file.delete(); } } |
GsonConfigSource implements IConfigSource { @Override public void reload() { ensureFile(); synchronized (file) { try (Reader fr = this.readerFactory.apply(file)) { synchronized (cache) { cache.clear(); Map<String, Object> loaded = gson.fromJson(fr, new TypeToken<Map<String, Object>>() { }.getType()); if (loaded != null) { cache.putAll(loaded); } } } catch (IOException e) { e.printStackTrace(); } } } GsonConfigSource(File file); GsonConfigSource(File file, Function<File, Reader> readerFactory, Function<File, Writer> writerFactory); @Override void reload(); @Override void disable(); @Override void saveAll(); @Override Optional<T> get(String key, Class<T> asType); @Override Optional<T> get(String key); @Override void put(String key, Object value); @Override Set<String> keys(); @Override boolean isSection(String key); void shutdown(); } | @Test public void testReload() { Mockito.when(mockFile.exists()).thenReturn(true); manager.reload(); Map<String, Object> cache = Whitebox.getInternalState(manager, "cache"); List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); Assert.assertEquals(list, cache.get("array")); Assert.assertEquals(true, cache.get("boolean")); Assert.assertEquals("#82b92c", cache.get("color")); Assert.assertEquals(null, cache.get("null")); Assert.assertEquals(123, cache.get("number")); Assert.assertEquals(345.67, cache.get("fnumber")); Assert.assertTrue(cache.get("object") instanceof Map); Map<String, Object> obj = (Map<String, Object>) cache.get("object"); Assert.assertEquals("b", obj.get("a")); Assert.assertEquals("d", obj.get("c")); Assert.assertEquals("f", obj.get("e")); Assert.assertEquals("Hello World", cache.get("string")); } |
GsonConfigSource implements IConfigSource { @Override public void saveAll() { ensureFile(); synchronized (file) { cacheToFile(); } } GsonConfigSource(File file); GsonConfigSource(File file, Function<File, Reader> readerFactory, Function<File, Writer> writerFactory); @Override void reload(); @Override void disable(); @Override void saveAll(); @Override Optional<T> get(String key, Class<T> asType); @Override Optional<T> get(String key); @Override void put(String key, Object value); @Override Set<String> keys(); @Override boolean isSection(String key); void shutdown(); } | @Test public void testSaveAll() { Mockito.when(mockFile.exists()).thenReturn(true); Map<String, Object> cache = Whitebox.getInternalState(manager, "cache"); cache.put("array2", new int[]{4, 5, 6}); cache.put("boolean2", false); cache.put("color2", "#123b9cc"); cache.put("null", null); cache.put("number2", 456); cache.put("fnumber2", 789.12); Map<String, Object> obj = new HashMap<>(); obj.put("i", "j"); obj.put("k", "l"); obj.put("m", "n"); cache.put("object", obj); cache.put("string2", "World Hello"); manager.saveAll(); String out = stringWriter.toString(); GsonBuilder builder = org.powermock.reflect.Whitebox.getInternalState(GsonConfigSource.class, "builder"); Gson gson = builder.create(); Map<String, Object> deser = gson.fromJson(out, new TypeToken<Map<String, Object>>() { }.getType()); List<Integer> list = new ArrayList<>(); list.add(4); list.add(5); list.add(6); Assert.assertEquals(list, deser.get("array2")); Assert.assertEquals(false, deser.get("boolean2")); Assert.assertEquals("#123b9cc", deser.get("color2")); Assert.assertEquals(null, deser.get("null")); Assert.assertEquals(456, deser.get("number2")); Assert.assertEquals(789.12, deser.get("fnumber2")); Assert.assertTrue(deser.get("object") instanceof Map); Map<String, Object> obj2 = (Map<String, Object>) deser.get("object"); Assert.assertEquals("j", obj2.get("i")); Assert.assertEquals("l", obj2.get("k")); Assert.assertEquals("n", obj2.get("m")); Assert.assertEquals("World Hello", deser.get("string2")); } |
GsonConfigSource implements IConfigSource { private <T> T get(Map<String, Object> map, String[] path, Class<T> asType) { for (int i = 0; i < path.length; i++) { String key = path[i]; Object value = map.get(key); if (i == path.length - 1) { return asType.cast(value); } else if (value instanceof Map) { map = (Map<String, Object>) value; } else { return null; } } return null; } GsonConfigSource(File file); GsonConfigSource(File file, Function<File, Reader> readerFactory, Function<File, Writer> writerFactory); @Override void reload(); @Override void disable(); @Override void saveAll(); @Override Optional<T> get(String key, Class<T> asType); @Override Optional<T> get(String key); @Override void put(String key, Object value); @Override Set<String> keys(); @Override boolean isSection(String key); void shutdown(); } | @Test public void testGet() { Mockito.when(mockFile.exists()).thenReturn(true); manager.reload(); Assert.assertTrue(manager.get("object").orElse(null) instanceof Map); Assert.assertEquals("b", manager.get("object.a").orElse(null)); Assert.assertEquals("d", manager.get("object.c").orElse(null)); Assert.assertEquals("f", manager.get("object.e").orElse(null)); } |
GsonConfigSource implements IConfigSource { private void put(Map<String, Object> map, String[] path, Object value) { for (int i = 0; i < path.length; i++) { String key = path[i]; if (i == path.length - 1) { map.put(key, value); } else { Object previous = map.computeIfAbsent(key, (k) -> new HashMap<>()); if (!(previous instanceof Map)) throw new RuntimeException("Value found at " + key + " is not a section."); map = (Map<String, Object>) previous; } } } GsonConfigSource(File file); GsonConfigSource(File file, Function<File, Reader> readerFactory, Function<File, Writer> writerFactory); @Override void reload(); @Override void disable(); @Override void saveAll(); @Override Optional<T> get(String key, Class<T> asType); @Override Optional<T> get(String key); @Override void put(String key, Object value); @Override Set<String> keys(); @Override boolean isSection(String key); void shutdown(); } | @Test public void testPut() { Mockito.when(mockFile.exists()).thenReturn(true); manager.put("some.data.value", "abc"); manager.put("some.data.value2", 123); manager.put("some.data.value3", false); Assert.assertEquals("abc", manager.get("some.data.value").orElse(null)); Assert.assertEquals(123, manager.get("some.data.value2").orElse(null)); Assert.assertEquals(false, manager.get("some.data.value3").orElse(null)); manager.put("some.data", 556); Assert.assertEquals(556, manager.get("some.data").orElse(null)); Assert.assertNull(manager.get("some.data.value").orElse(null)); Assert.assertNull(manager.get("some.data.value2").orElse(null)); Assert.assertNull(manager.get("some.data.value3").orElse(null)); } |
AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public Block block(String world, int x, int y, int z) { return location(world, x, y, z).getBlock(); } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); } | @Test public void testBlock() { Block mockBlock = Mockito.mock(Block.class); Mockito.when(mockWorld.getBlockAt(Mockito.any(Location.class))) .thenReturn(mockBlock); Assert.assertEquals(mockBlock, fn.block("test", 1, 2, 3)); } |
GsonConfigSource implements IConfigSource { @Override public Set<String> keys() { synchronized (cache) { return new HashSet<>(cache.keySet()); } } GsonConfigSource(File file); GsonConfigSource(File file, Function<File, Reader> readerFactory, Function<File, Writer> writerFactory); @Override void reload(); @Override void disable(); @Override void saveAll(); @Override Optional<T> get(String key, Class<T> asType); @Override Optional<T> get(String key); @Override void put(String key, Object value); @Override Set<String> keys(); @Override boolean isSection(String key); void shutdown(); } | @Test public void testKeys() { Mockito.when(mockFile.exists()).thenReturn(true); manager.reload(); Set<String> expected = new HashSet<>(); expected.add("array"); expected.add("boolean"); expected.add("color"); expected.add("null"); expected.add("number"); expected.add("fnumber"); expected.add("object"); expected.add("string"); Assert.assertEquals(expected, manager.keys()); } |
GsonConfigSource implements IConfigSource { @Override public boolean isSection(String key) { synchronized (cache) { return get(cache, IConfigSource.toPath(key), Object.class) instanceof Map; } } GsonConfigSource(File file); GsonConfigSource(File file, Function<File, Reader> readerFactory, Function<File, Writer> writerFactory); @Override void reload(); @Override void disable(); @Override void saveAll(); @Override Optional<T> get(String key, Class<T> asType); @Override Optional<T> get(String key); @Override void put(String key, Object value); @Override Set<String> keys(); @Override boolean isSection(String key); void shutdown(); } | @Test public void testIsSection() { Mockito.when(mockFile.exists()).thenReturn(true); manager.reload(); Assert.assertFalse(manager.isSection("array")); Assert.assertFalse(manager.isSection("boolean")); Assert.assertFalse(manager.isSection("color")); Assert.assertFalse(manager.isSection("null")); Assert.assertFalse(manager.isSection("number")); Assert.assertFalse(manager.isSection("fnumber")); Assert.assertTrue(manager.isSection("object")); Assert.assertFalse(manager.isSection("string")); } |
Lexer { public Token getToken() throws IOException, LexerException { skipWhiteSpaces(); skipComment(); if (Character.isDigit(c)) { return readNumber(); } if (c == '"') { return readString(); } if (c == '`') { return readMultilineString(); } if (isOperator(c)) { return readOperator(); } if (isIdCharacter(c)) { return readId(); } if (c == '\n' || c == ';') { return readEndline(); } if (!eos) { throw new LexerException("Found an unrecognizable character", this); } return null; } Lexer(String str, Charset charset); Lexer(String str, String charset); int getRow(); int getCol(); List<Warning> getWarnings(); boolean getShowWarnings(); String[] getScriptLines(); Token getToken(); void setWarnings(boolean w); static void main(String[] ar); } | @Test public void testGetToken() throws Exception { Charset charset = StandardCharsets.UTF_8; String text = "#MESSAGE (1+(4/2.0)/3*4-(2/(3*-4)) >= 0)\n" + "#MESSAGE \"text\" \"test\"\n"; Lexer lexer = new Lexer(text, charset); testToken(lexer, Type.ID, "#MESSAGE"); testToken(lexer, Type.OPERATOR, "("); testToken(lexer, Type.INTEGER, "1"); testToken(lexer, Type.OPERATOR_A, "+"); testToken(lexer, Type.OPERATOR, "("); testToken(lexer, Type.INTEGER, "4"); testToken(lexer, Type.OPERATOR_A, "/"); testToken(lexer, Type.DECIMAL, "2.0"); testToken(lexer, Type.OPERATOR, ")"); testToken(lexer, Type.OPERATOR_A, "/"); testToken(lexer, Type.INTEGER, "3"); testToken(lexer, Type.OPERATOR_A, "*"); testToken(lexer, Type.INTEGER, "4"); testToken(lexer, Type.OPERATOR_A, "-"); testToken(lexer, Type.OPERATOR, "("); testToken(lexer, Type.INTEGER, "2"); testToken(lexer, Type.OPERATOR_A, "/"); testToken(lexer, Type.OPERATOR, "("); testToken(lexer, Type.INTEGER, "3"); testToken(lexer, Type.OPERATOR_A, "*"); testToken(lexer, Type.OPERATOR_A, "-"); testToken(lexer, Type.INTEGER, "4"); testToken(lexer, Type.OPERATOR, ")"); testToken(lexer, Type.OPERATOR, ")"); testToken(lexer, Type.OPERATOR_L, ">="); testToken(lexer, Type.INTEGER, "0"); testToken(lexer, Type.OPERATOR, ")"); testToken(lexer, Type.ENDL, null); testToken(lexer, Type.ID, "#MESSAGE"); testToken(lexer, Type.STRING, "text"); testToken(lexer, Type.STRING, "test"); testToken(lexer, Type.ENDL, null); testEnd(lexer); }
@Test public void testEscapeCharacter2() throws Exception { Charset charset = StandardCharsets.UTF_8; String text = "#MESSAGE \"The cost is \\$100\""; Lexer lexer = new Lexer(text, charset); assertEquals(new Token(Type.ID, "#MESSAGE"), lexer.getToken()); assertEquals(new Token(Type.STRING, "The cost is $100"), lexer.getToken()); assertNull(lexer.getToken()); }
@Test public void testImportWithUnderscore() throws Exception{ Charset charset = StandardCharsets.UTF_8; String text; Lexer lexer; text = "IMPORT net.md_5.bungee.api.chat.ComponentBuilder"; lexer = new Lexer(text, charset); assertEquals(new Token(Type.IMPORT, "net.md_5.bungee.api.chat.ComponentBuilder"), lexer.getToken()); } |
Parser { public Node parse(boolean showWarnings) throws IOException, LexerException, ParserException { this.showWarnings = showWarnings; lexer.setWarnings(showWarnings); Node root = new Node(new Token(Type.ROOT, "<ROOT>", -1, -1)); Node statement = null; while ((statement = parseStatement()) != null) root.getChildren().add(statement); List<Warning> lexWarnings = lexer.getWarnings(); if (lexWarnings != null) { this.warnings.addAll(lexWarnings); } return root; } Parser(Lexer lexer); static void addDeprecationSupervisor(DeprecationSupervisor ds); Node parse(boolean showWarnings); Node parse(); List<Warning> getWarnings(); static void main(String[] ar); } | @Test public void testParse() throws IOException, LexerException, ParserException { Charset charset = Charset.forName("UTF-8"); String text = "#MESSAGE (1+(4/2.0)/3*4-(2/(3*-4)) >= 0)\n" + "#MESSAGE \"text\"\n"; Lexer lexer = new Lexer(text, charset); Parser parser = new Parser(lexer); Node root = parser.parse(); Queue<Node> queue = new LinkedList<Node>(); serializeNode(queue, root); assertEquals(new Node(new Token(Type.INTEGER, "1")), queue.poll()); assertEquals(new Node(new Token(Type.INTEGER, "4")), queue.poll()); assertEquals(new Node(new Token(Type.DECIMAL, "2.0")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR_A, "/")), queue.poll()); assertEquals(new Node(new Token(Type.INTEGER, "3")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR_A, "/")), queue.poll()); assertEquals(new Node(new Token(Type.INTEGER, "4")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR_A, "*")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR_A, "+")), queue.poll()); assertEquals(new Node(new Token(Type.INTEGER, "2")), queue.poll()); assertEquals(new Node(new Token(Type.INTEGER, "3")), queue.poll()); assertEquals(new Node(new Token(Type.INTEGER, "4")), queue.poll()); assertEquals(new Node(new Token(Type.UNARYMINUS, "<UNARYMINUS>")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR_A, "*")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR_A, "/")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR_A, "-")), queue.poll()); assertEquals(new Node(new Token(Type.INTEGER, "0")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR_L, ">=")), queue.poll()); assertEquals(new Node(new Token(Type.EXECUTOR, "MESSAGE")), queue.poll()); assertEquals(new Node(new Token(Type.STRING, "text")), queue.poll()); assertEquals(new Node(new Token(Type.EXECUTOR, "MESSAGE")), queue.poll()); assertEquals(new Node(new Token(Type.ROOT, "<ROOT>")), queue.poll()); assertEquals(0, queue.size()); }
@Test public void testParam() throws IOException, LexerException, ParserException { Charset charset = Charset.forName("UTF-8"); String text = "#SOUND player.getLocation() \"LEVEL_UP\" 1.0 1.0"; Lexer lexer = new Lexer(text, charset); Parser parser = new Parser(lexer); Node root = parser.parse(); Queue<Node> queue = new LinkedList<Node>(); serializeNode(queue, root); assertEquals(new Node(new Token(Type.THIS, "<This>")), queue.poll()); assertEquals(new Node(new Token(Type.ID, "player")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR, ".")), queue.poll()); assertEquals(new Node(new Token(Type.CALL, "getLocation")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR, ".")), queue.poll()); assertEquals(new Node(new Token(Type.STRING, "LEVEL_UP")), queue.poll()); assertEquals(new Node(new Token(Type.DECIMAL, "1.0")), queue.poll()); assertEquals(new Node(new Token(Type.DECIMAL, "1.0")), queue.poll()); assertEquals(new Node(new Token(Type.EXECUTOR, "SOUND")), queue.poll()); assertEquals(new Node(new Token(Type.ROOT, "<ROOT>")), queue.poll()); assertEquals(0, queue.size()); }
@Test public void testFor() throws Exception { Charset charset = Charset.forName("UTF-8"); String text = "" + "FOR i = 0:10;" + " #MESSAGE \"test i=\"+i;" + "ENDFOR;"; Lexer lexer = new Lexer(text, charset); Parser parser = new Parser(lexer); Node root = parser.parse(); Queue<Node> queue = new LinkedList<Node>(); serializeNode(queue, root); assertEquals(new Node(new Token(Type.THIS, "<This>")), queue.poll()); assertEquals(new Node(new Token(Type.ID, "i")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR, ".")), queue.poll()); assertEquals(new Node(new Token(Type.INTEGER, "0")), queue.poll()); assertEquals(new Node(new Token(Type.INTEGER, "10")), queue.poll()); assertEquals(new Node(new Token(Type.ITERATOR, "<ITERATOR>")), queue.poll()); assertEquals(new Node(new Token(Type.STRING, "test i=")), queue.poll()); assertEquals(new Node(new Token(Type.THIS, "<This>")), queue.poll()); assertEquals(new Node(new Token(Type.ID, "i")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR, ".")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR_A, "+")), queue.poll()); assertEquals(new Node(new Token(Type.EXECUTOR, "MESSAGE")), queue.poll()); assertEquals(new Node(new Token(Type.BODY, "<BODY>")), queue.poll()); assertEquals(new Node(new Token(Type.ID, "FOR")), queue.poll()); assertEquals(new Node(new Token(Type.ROOT, "<ROOT>")), queue.poll()); assertEquals(0, queue.size()); }
@Test public void testNegation() throws Exception { Charset charset = Charset.forName("UTF-8"); String text = "" + "IF !(true && false && true || 2 < 1 && 1 < 2)\n" + " #MESSAGE \"test i=\"+i\n" + "ENDIF\n"; Lexer lexer = new Lexer(text, charset); Parser parser = new Parser(lexer); Node root = parser.parse(); Queue<Node> queue = new LinkedList<Node>(); serializeNode(queue, root); assertEquals(new Node(new Token(Type.BOOLEAN, "true")), queue.poll()); assertEquals(new Node(new Token(Type.BOOLEAN, "false")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR_L, "&&")), queue.poll()); assertEquals(new Node(new Token(Type.BOOLEAN, "true")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR_L, "&&")), queue.poll()); assertEquals(new Node(new Token(Type.INTEGER, "2")), queue.poll()); assertEquals(new Node(new Token(Type.INTEGER, "1")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR_L, "<")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR_L, "||")), queue.poll()); assertEquals(new Node(new Token(Type.INTEGER, "1")), queue.poll()); assertEquals(new Node(new Token(Type.INTEGER, "2")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR_L, "<")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR_L, "&&")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR_L, "!")), queue.poll()); assertEquals(new Node(new Token(Type.STRING, "test i=")), queue.poll()); assertEquals(new Node(new Token(Type.THIS, "<This>")), queue.poll()); assertEquals(new Node(new Token(Type.ID, "i")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR, ".")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR_A, "+")), queue.poll()); assertEquals(new Node(new Token(Type.EXECUTOR, "MESSAGE")), queue.poll()); assertEquals(new Node(new Token(Type.BODY, "<BODY>")), queue.poll()); assertEquals(new Node(new Token(Type.ID, "IF")), queue.poll()); assertEquals(new Node(new Token(Type.ROOT, "<ROOT>")), queue.poll()); assertEquals(0, queue.size()); }
@Test public void testPlaceholder() throws Exception { Charset charset = Charset.forName("UTF-8"); String text = "" + "x = 10;" + "#MESSAGE $placeholdertest:0:x:5:true;"; Lexer lexer = new Lexer(text, charset); Parser parser = new Parser(lexer); Node root = parser.parse(); Queue<Node> queue = new LinkedList<Node>(); serializeNode(queue, root); assertEquals(new Node(new Token(Type.THIS, "<This>")), queue.poll()); assertEquals(new Node(new Token(Type.ID, "x")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR, ".")), queue.poll()); assertEquals(new Node(new Token(Type.INTEGER, "10")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR, "=")), queue.poll()); assertEquals(new Node(new Token(Type.INTEGER, "0")), queue.poll()); assertEquals(new Node(new Token(Type.THIS, "<This>")), queue.poll()); assertEquals(new Node(new Token(Type.ID, "x")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR, ".")), queue.poll()); assertEquals(new Node(new Token(Type.INTEGER, "5")), queue.poll()); assertEquals(new Node(new Token(Type.BOOLEAN, "true")), queue.poll()); assertEquals(new Node(new Token(Type.PLACEHOLDER, "placeholdertest")), queue.poll()); assertEquals(new Node(new Token(Type.EXECUTOR, "MESSAGE")), queue.poll()); assertEquals(new Node(new Token(Type.ROOT, "<ROOT>")), queue.poll()); assertEquals(0, queue.size()); }
@Test public void testIf() throws Exception { Charset charset = Charset.forName("UTF-8"); String text = "" + "IF i == 0;" + " #MESSAGE 0;" + "ELSEIF i == 1;" + " #MESSAGE 1;" + "ELSEIF i == 2;" + " #MESSAGE 2;" + "ELSE;" + " #MESSAGE 3;" + "ENDIF;"; Lexer lexer = new Lexer(text, charset); Parser parser = new Parser(lexer); Node root = parser.parse(); Queue<Node> queue = new LinkedList<Node>(); serializeNode(queue, root); assertEquals(new Node(new Token(Type.THIS, "<This>")), queue.poll()); assertEquals(new Node(new Token(Type.ID, "i")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR, ".")), queue.poll()); assertEquals(new Node(new Token(Type.INTEGER, "0")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR_L, "==")), queue.poll()); assertEquals(new Node(new Token(Type.INTEGER, "0")), queue.poll()); assertEquals(new Node(new Token(Type.EXECUTOR, "MESSAGE")), queue.poll()); assertEquals(new Node(new Token(Type.BODY, "<BODY>")), queue.poll()); assertEquals(new Node(new Token(Type.THIS, "<This>")), queue.poll()); assertEquals(new Node(new Token(Type.ID, "i")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR, ".")), queue.poll()); assertEquals(new Node(new Token(Type.INTEGER, "1")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR_L, "==")), queue.poll()); assertEquals(new Node(new Token(Type.INTEGER, "1")), queue.poll()); assertEquals(new Node(new Token(Type.EXECUTOR, "MESSAGE")), queue.poll()); assertEquals(new Node(new Token(Type.BODY, "<BODY>")), queue.poll()); assertEquals(new Node(new Token(Type.THIS, "<This>")), queue.poll()); assertEquals(new Node(new Token(Type.ID, "i")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR, ".")), queue.poll()); assertEquals(new Node(new Token(Type.INTEGER, "2")), queue.poll()); assertEquals(new Node(new Token(Type.OPERATOR_L, "==")), queue.poll()); assertEquals(new Node(new Token(Type.INTEGER, "2")), queue.poll()); assertEquals(new Node(new Token(Type.EXECUTOR, "MESSAGE")), queue.poll()); assertEquals(new Node(new Token(Type.BODY, "<BODY>")), queue.poll()); assertEquals(new Node(new Token(Type.INTEGER, "3")), queue.poll()); assertEquals(new Node(new Token(Type.EXECUTOR, "MESSAGE")), queue.poll()); assertEquals(new Node(new Token(Type.BODY, "<BODY>")), queue.poll()); assertEquals(new Node(new Token(Type.ID, "ELSEIF")), queue.poll()); assertEquals(new Node(new Token(Type.BODY, "<BODY>")), queue.poll()); assertEquals(new Node(new Token(Type.ID, "ELSEIF")), queue.poll()); assertEquals(new Node(new Token(Type.BODY, "<BODY>")), queue.poll()); assertEquals(new Node(new Token(Type.ID, "IF")), queue.poll()); assertEquals(new Node(new Token(Type.ROOT, "<ROOT>")), queue.poll()); assertEquals(0, queue.size()); } |
AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public boolean locationEqual(Location loc1, Location loc2) { return loc1.getWorld() == loc2.getWorld() && loc1.getBlockX() == loc2.getBlockX() && loc1.getBlockY() == loc2.getBlockY() && loc1.getBlockZ() == loc2.getBlockZ(); } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); } | @Test public void testLocationEqual() { Location loc1 = new Location(mockWorld, 1, 2, 3); Location loc2 = new Location(mockWorld, 4, 5, 6, 0.5F, 0.6F); Location loc3 = new Location(mockWorld, 1, 2, 3, 0.7F, 0.8F); Location loc4 = new Location(mockWorld, 4, 5, 6, 0.1F, 0.2F); Assert.assertFalse(fn.locationEqual(loc1, loc2)); Assert.assertTrue(fn.locationEqual(loc1, loc3)); Assert.assertFalse(fn.locationEqual(loc2, loc3)); Assert.assertTrue(fn.locationEqual(loc2, loc4)); } |
AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient, boolean particles, Color color); AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); } | @Test public abstract void testMakePotionEffect(); |
AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public Player player(String name) { return Bukkit.getPlayer(name); } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); } | @Test public void testPlayer() { Assert.assertEquals(mockPlayer, fn.player("wysohn")); } |
AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public OfflinePlayer oplayer(String name) { return Bukkit.getOfflinePlayer(name); } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); } | @Test public void testOPlayer() { Assert.assertEquals(mockPlayer, fn.oplayer("wysohn")); } |
AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public abstract Collection<? extends Player> getPlayers(); AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); } | @Test public abstract void testGetPlayers(); |
AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public String currentArea(Entity entity) { String[] areas = currentAreasAt(entity.getLocation()); return areas.length > 0 ? areas[0] : null; } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient,
boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); } | @Test public void testCurrentArea() { } |
MemoryManager { public abstract long acquireExecutionMemory(long numBytes, long taskAttemptId, MemoryMode memoryMode); MemoryManager(SparkConf conf, int numCores, long onHeapStorageMemory, long onHeapExecutionMemory); long pageSizeBytes(); MemoryAllocator tungstenMemoryAllocator(); final void setMemoryStore(MemoryStore memoryStore); abstract long maxOnHeapStorageMemory(); abstract long maxOffHeapStorageMemory(); abstract boolean acquireStorageMemory(BlockId blockId, long numBytes, MemoryMode memoryMode); abstract boolean acquireUnrollMemory(BlockId blockId, long numBytes, MemoryMode memoryMode); synchronized void releaseStorageMemory(long numBytes, MemoryMode memoryMode); synchronized void releaseAllStorageMemory(); final void releaseUnrollMemory(long numBytes, MemoryMode memoryMode); final synchronized long storageMemoryUsed(); abstract long acquireExecutionMemory(long numBytes, long taskAttemptId, MemoryMode memoryMode); void releaseExecutionMemory(long numBytes, long taskAttemptId, MemoryMode memoryMode); synchronized long releaseAllExecutionMemoryForTask(long taskAttemptId); final synchronized long executionMemoryUsed(); synchronized long getExecutionMemoryUsageForTask(long taskAttemptId); static long getMaxStorageMemory(SparkConf conf); static long getMaxExecutionMemory(SparkConf conf); public SparkConf conf; } | @Test public void testAcquireExecutionMemory() { MemoryManager memoryManager = createStaticMemoryManager(1000L); TaskMemoryManager taskMemoryManager = new TaskMemoryManager(memoryManager, 0); TestMemoryConsumer consumer = new TestMemoryConsumer(taskMemoryManager); assert taskMemoryManager.acquireExecutionMemory(100L, consumer) == 100L; assert taskMemoryManager.acquireExecutionMemory(400L, consumer) == 400L; assert taskMemoryManager.acquireExecutionMemory(400L, consumer) == 400L; assert taskMemoryManager.acquireExecutionMemory(200L, consumer) == 200L; assert taskMemoryManager.acquireExecutionMemory(100L, consumer) == 100L; assert taskMemoryManager.acquireExecutionMemory(100L, consumer) == 100L; taskMemoryManager.cleanUpAllAllocatedMemory(); assert taskMemoryManager.acquireExecutionMemory(1000L, consumer) == 1000L; assert taskMemoryManager.acquireExecutionMemory(100L, consumer) == 100L; } |
SparkContext { public SparkContext(SparkConf conf) { this.conf = conf; this.localProperties = new InheritableThreadLocal<Properties>(){ @Override protected Properties childValue(Properties parentValue) { return SerializationUtils.clone(parentValue); } @Override protected Properties initialValue() { return new Properties(); } }; init(); } SparkContext(SparkConf conf); String appName(); int executorMemory(); String applicationId(); String applicationAttemptId(); void stopInNewThread(); List<U> runJob(RDD<T> rdd,
PartitionFunction<T, U> partitionFunc,
List<Integer> partitions); void runJob(RDD<T> rdd,
PartitionFunction<T, U> partitionFunc,
List<Integer> partitions,
com.sdu.spark.scheduler.action.PartitionResultHandler<U> partitionResultHandler); CallSite getCallSite(); int newShuffleId(); int newRddId(); Broadcast<T> broadcast(T value); Properties getLocalProperties(); void setLocalProperties(Properties props); void setLocalProperty(String key, String value); String getLocalProperty(String key); static final String SPARK_JOB_INTERRUPT_ON_CANCEL; static final String DRIVER_IDENTIFIER; static final String LEGACY_DRIVER_IDENTIFIER; public AtomicBoolean stopped; public SparkConf conf; public SparkEnv env; public LiveListenerBus listenerBus; public SchedulerBackend schedulerBackend; public TaskScheduler taskScheduler; public Map<String, String> executorEnvs; } | @Test public void testSparkContext() { } |
DiskBlockManager { public BlockId[] getAllBlocks() { File[] blockFiles = getAllFiles(); BlockId[] blockIds = new BlockId[blockFiles.length]; for (int i = 0; i < blockFiles.length; ++i) { blockIds[i] = BlockId.apply(blockFiles[i].getName()); } return blockIds; } DiskBlockManager(SparkConf conf, boolean deleteFilesOnStop); File getFile(BlockId blockId); boolean containsBlock(BlockId blockId); File[] getAllFiles(); BlockId[] getAllBlocks(); Tuple2<BlockId, File> createTempLocalBlock(); Tuple2<TempShuffleBlockId, File> createTempShuffleBlock(); void stop(); public SparkConf conf; public boolean deleteFilesOnStop; public File[] localDirs; public int subDirsPerLocalDir; } | @Test public void testMultiBlocks() { List<BlockId.ShuffleBlockId> blockIs = Lists.newLinkedList(); for (int i = 0; i < 100; ++i) { blockIs.add(new BlockId.ShuffleBlockId(1, i, 0)); } List<File> shuffleFiles = blockIs.stream().map(diskBlockManager::getFile).collect(Collectors.toList()); shuffleFiles.forEach(file -> writeToFile(file, 5)); assert diskBlockManager.getAllBlocks().length == blockIs.size(); } |
LineChart extends AbstractLineChart { public final void setSparkline(final boolean isSparkline) { this.isSparkline = isSparkline; } LineChart(final ImmutableList<? extends Plot> lines); final void setSparkline(final boolean isSparkline); } | @Test public void test4() { final Line line = Plots.newLine(Data.newData(0, 50, 100), GREEN); final LineChart chart = GCharts.newLineChart(line); chart.setSparkline(true); chart.setTitle("Foobar"); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); } |
Data { @Override public String toString() { return Arrays.toString(data); } Data(final double... data); @Override String toString(); final double[] getData(); final int getSize(); static Data newData(final double... data); static Data newData(final List<? extends Number> data); static final double MIN_VALUE; static final double MAX_VALUE; static final Data INVALID; } | @Test public void testData1() { Data data = new Data(-1, 0, 100); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(data.toString()); assertEquals("Junit error", "[-1.0, 0.0, 100.0]", data.toString()); } |
AxisStyle implements Kloneable<AxisStyle> { public static AxisStyle newAxisStyle(final Color textColor, final int fontSize, final AxisTextAlignment alignment) { checkNotNull(textColor, "color must not be null"); checkArgument(fontSize > 0, "fontsize must be > 0"); checkNotNull(alignment, "alignment must not be null"); return new AxisStyle(textColor, fontSize, alignment); } AxisStyle(final Color textColor, final int fontSize, final AxisTextAlignment alignment); private AxisStyle(final AxisStyle axisStyle); AxisStyle klone(); Color getTextColor(); int getFontSize(); AxisTextAlignment getAlignment(); Boolean drawTickMarks(); void setDrawTickMarks(final boolean drawTickMarks); Integer getTickMarkLength(); void setTickMarkLength(final int tickMarkLength); Color getTickMarkColor(); void setTickMarkColor(final Color tickMarkColor); static AxisStyle newAxisStyle(final Color textColor, final int fontSize, final AxisTextAlignment alignment); } | @Test public void testAxisAlignment() { final LineChart chart = TestUtil.getBasicChart(); chart.setGrid(50, 50, 5, 0); AxisStyle axisStyle = AxisStyle.newAxisStyle(RED, 16, AxisTextAlignment.LEFT); AxisLabels axisLabels = AxisLabelsFactory.newAxisLabels("Foo", 50); axisLabels.setAxisStyle(axisStyle); chart.addXAxisLabels(axisLabels); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); } |
AbstractAxisChart extends AbstractGraphChart implements GridChart { public final void setGrid(final double xAxisStepSize, final double yAxisStepSize, final int lengthOfLineSegment, final int lengthOfBlankSegment) { checkArgument(xAxisStepSize > 0, "xAxisStepSize must be positive: %s", xAxisStepSize); checkArgument(yAxisStepSize > 0, "yAxisStepSize must be positive: %s", yAxisStepSize); checkArgument(lengthOfLineSegment >= 0, "lengthOfLineSegment must be 0 or positive: %s", lengthOfLineSegment); checkArgument(lengthOfBlankSegment >= 0, "lengthOfBlankSegment must be 0 or positive: %s", lengthOfBlankSegment); this.xAxisStepSize = xAxisStepSize; this.yAxisStepSize = yAxisStepSize; gridLineStyle = LineStyle.newLineStyle(1, lengthOfLineSegment, lengthOfBlankSegment); } AbstractAxisChart(); final void addXAxisLabels(final AxisLabels axisLabels); final void addYAxisLabels(final AxisLabels axisLabels); final void addTopAxisLabels(final AxisLabels axisLabels); final void addRightAxisLabels(final AxisLabels axisLabels); final void addMarker(final Marker marker, final double xPos, final double yPos); final void setGrid(final double xAxisStepSize, final double yAxisStepSize, final int lengthOfLineSegment, final int lengthOfBlankSegment); } | @Test public void testSetGrid0() { try { final LineChart chart = getBasicChart(); chart.setGrid(0, 0, 0, 0); } catch (IllegalArgumentException e) { return; } fail(); }
@Test public void testSetGrid1() { final LineChart chart = getBasicChart(); chart.setGrid(10, 10, 1, 0); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); } |
AbstractAxisChart extends AbstractGraphChart implements GridChart { public final void addXAxisLabels(final AxisLabels axisLabels) { checkNotNull(axisLabels, "axisLabel cannnot be null"); xAxisLabels.add((AxisLabelsImpl) axisLabels.klone()); } AbstractAxisChart(); final void addXAxisLabels(final AxisLabels axisLabels); final void addYAxisLabels(final AxisLabels axisLabels); final void addTopAxisLabels(final AxisLabels axisLabels); final void addRightAxisLabels(final AxisLabels axisLabels); final void addMarker(final Marker marker, final double xPos, final double yPos); final void setGrid(final double xAxisStepSize, final double yAxisStepSize, final int lengthOfLineSegment, final int lengthOfBlankSegment); } | @Test public void testXAxisLabels0() { final LineChart chart = getBasicChart(); chart.addXAxisLabels(AxisLabelsFactory.newAxisLabels("start", "end")); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); }
@Test public void testXAxisLabels1() { final LineChart chart = TestUtil.getBasicChart(); final AxisLabels ai = AxisLabelsFactory.newAxisLabels("start", "end"); ai.setAxisStyle(AxisStyle.newAxisStyle(RED, 14, AxisTextAlignment.RIGHT)); chart.addXAxisLabels(ai); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); } |
AbstractAxisChart extends AbstractGraphChart implements GridChart { public final void addYAxisLabels(final AxisLabels axisLabels) { checkNotNull(axisLabels, "axisLabel cannnot be null"); yAxisLabels.add((AxisLabelsImpl) axisLabels.klone()); } AbstractAxisChart(); final void addXAxisLabels(final AxisLabels axisLabels); final void addYAxisLabels(final AxisLabels axisLabels); final void addTopAxisLabels(final AxisLabels axisLabels); final void addRightAxisLabels(final AxisLabels axisLabels); final void addMarker(final Marker marker, final double xPos, final double yPos); final void setGrid(final double xAxisStepSize, final double yAxisStepSize, final int lengthOfLineSegment, final int lengthOfBlankSegment); } | @Test public void testYAxisLabels() { final LineChart chart = getBasicChart(); chart.addYAxisLabels(AxisLabelsFactory.newAxisLabels("start", "end")); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); } |
AbstractAxisChart extends AbstractGraphChart implements GridChart { public final void addTopAxisLabels(final AxisLabels axisLabels) { checkNotNull(axisLabels, "axisLabel cannnot be null"); topAxisLabels.add((AxisLabelsImpl) axisLabels.klone()); } AbstractAxisChart(); final void addXAxisLabels(final AxisLabels axisLabels); final void addYAxisLabels(final AxisLabels axisLabels); final void addTopAxisLabels(final AxisLabels axisLabels); final void addRightAxisLabels(final AxisLabels axisLabels); final void addMarker(final Marker marker, final double xPos, final double yPos); final void setGrid(final double xAxisStepSize, final double yAxisStepSize, final int lengthOfLineSegment, final int lengthOfBlankSegment); } | @Test public void testTopAxisLabels() { final LineChart chart = getBasicChart(); chart.addTopAxisLabels(AxisLabelsFactory.newAxisLabels("start", "end")); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); } |
AbstractAxisChart extends AbstractGraphChart implements GridChart { public final void addRightAxisLabels(final AxisLabels axisLabels) { checkNotNull(axisLabels, "axisLabels cannnot be null"); rightAxisLabels.add((AxisLabelsImpl) axisLabels.klone()); } AbstractAxisChart(); final void addXAxisLabels(final AxisLabels axisLabels); final void addYAxisLabels(final AxisLabels axisLabels); final void addTopAxisLabels(final AxisLabels axisLabels); final void addRightAxisLabels(final AxisLabels axisLabels); final void addMarker(final Marker marker, final double xPos, final double yPos); final void setGrid(final double xAxisStepSize, final double yAxisStepSize, final int lengthOfLineSegment, final int lengthOfBlankSegment); } | @Test public void testRightAxisLabels() { final LineChart chart = getBasicChart(); chart.addRightAxisLabels(AxisLabelsFactory.newAxisLabels("start", "end")); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); } |
AbstractAxisChart extends AbstractGraphChart implements GridChart { public final void addMarker(final Marker marker, final double xPos, final double yPos) { checkNotNull(marker, "marker cannnot be null"); checkArgument(xPos >= 0 && xPos <= 100, "xPos must be >= 0 and <= 100: %s", xPos); checkArgument(yPos >= 0 && yPos <= 100, "yPos must be >= 0 and <= 100: %s", yPos); freeMarkers.add(new FreeMarker(marker, xPos, yPos)); } AbstractAxisChart(); final void addXAxisLabels(final AxisLabels axisLabels); final void addYAxisLabels(final AxisLabels axisLabels); final void addTopAxisLabels(final AxisLabels axisLabels); final void addRightAxisLabels(final AxisLabels axisLabels); final void addMarker(final Marker marker, final double xPos, final double yPos); final void setGrid(final double xAxisStepSize, final double yAxisStepSize, final int lengthOfLineSegment, final int lengthOfBlankSegment); } | @Test public void addFreeShapeMarkersToBarChart() { final BarChart chart = getBasicBarChart(); chart.addMarker(Markers.newShapeMarker(Shape.ARROW, RED, 12,Priority.LOW), 50, 80); chart.addMarker(Markers.newShapeMarker(Shape.X, BLUE, 12,Priority.HIGH), 50, 80); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); }
@Test public void addFreeTextMarkerToLineChart() { final LineChart chart = getBasicChart(); chart.addMarker(Markers.newTextMarker("charts4j", RED, 20), 10, 80); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); } |
UrlUtil { public static String normalize(final String s) { if (s == null) { return ""; } final ImmutableList<String> stringList = Lists.of(s.split("\\?")); if (stringList.size() != 2) { return s; } final String args = stringList.get(1); final List<String> params = Arrays.asList(args.split("&")); Collections.sort(params); final StringBuilder sb = new StringBuilder(stringList.get(0) + "?"); int cnt = 0; for (String p : params) { sb.append(cnt++ > 0 ? "&" : "").append(p); } return sb.toString(); } private UrlUtil(); static String normalize(final String s); } | @Test public void testNormalize() { final String unnormalizedString = "http: final String expectedString = "http: assertEquals("Junit error", normalize(expectedString), UrlUtil.normalize(unnormalizedString)); } |
LineStyle { public static LineStyle newLineStyle(final int lineThickness, final int lengthOfLineSegment, final int lengthOfBlankSegment) { checkArgument(lineThickness > 0, "line thickness must be > 0: %s", lineThickness); checkArgument(lengthOfLineSegment >= 0, "length of line segment must be >= 0: %s", lengthOfLineSegment); checkArgument(lengthOfBlankSegment >= 0, "length of blank segment must be > 0: %s", lengthOfBlankSegment); return new LineStyle(lineThickness, lengthOfLineSegment, lengthOfBlankSegment); } LineStyle(final int lineThickness, final int lengthOfLineSegment, final int lengthOfBlankSegment); int getLineThickness(); int getLengthOfLineSegment(); int getLengthOfBlankSegment(); static LineStyle newLineStyle(final int lineThickness, final int lengthOfLineSegment, final int lengthOfBlankSegment); static final LineStyle THICK_LINE; static final LineStyle MEDIUM_LINE; static final LineStyle THIN_LINE; static final LineStyle THICK_DOTTED_LINE; static final LineStyle MEDIUM_DOTTED_LINE; static final LineStyle THIN_DOTTED_LINE; } | @Test public void testNewLineStyle0() { try { final Line line = TestUtil.getBasicLine(); line.setLineStyle(LineStyle.newLineStyle(0, 0, 0)); } catch (IllegalArgumentException e) { return; } fail(); } |
GCharts { public static LineChart newLineChart(final Line... plots) { checkNotNull(plots, "plots cannot be null or contain a null."); checkContentsNotNull(Arrays.asList(plots), "plots cannot be null or contain a null."); return new LineChart(Plots.copyOf(plots)); } private GCharts(); static LineChart newLineChart(final Line... plots); static LineChart newLineChart(final Plot... plots); static LineChart newLineChart(final List<? extends Plot> plots); static RadarChart newRadarChart(final RadarPlot... plots); static RadarChart newRadarChart(final Plot... plots); static RadarChart newRadarChart(final List<? extends Plot> plots); static BarChart newBarChart(final BarChartPlot... plots); static BarChart newBarChart(final Plot... plots); static BarChart newBarChart(final List<? extends Plot> plots); static XYLineChart newXYLineChart(final XYLine... plots); static XYLineChart newXYLineChart(final Plot... plots); static XYLineChart newXYLineChart(final List<? extends Plot> plots); static ScatterPlot newScatterPlot(final ScatterPlotData scatterPlotData); static ScatterPlot newScatterPlot(final Plot scatterPlotData); static PieChart newPieChart(final Slice... slices); static PieChart newPieChart(final List<? extends Slice> slices); static VennDiagram newVennDiagram(final double circle1Size, final double circle2Size, final double circle3Size, final double abIntersect, final double caIntersect, final double bcIntersect, final double abcIntersect); static GoogleOMeter newGoogleOMeter(final double data); static GoogleOMeter newGoogleOMeter(final double data,final String label); @Deprecated //Since 1.1 Going away in future release. static GoogleOMeter newGoogleOMeter(final double data, final String label, final Color... colors); @Deprecated //Since 1.1 Going away in future release. static GoogleOMeter newGoogleOMeter(final double data, final String label, final List<? extends Color> colors); static GoogleOMeter newGoogleOMeter(final double data, final String label, final String legend, final Color... colors); static GoogleOMeter newGoogleOMeter(final double data, final String label, final String legend, final List<? extends Color> colors); static MapChart newMapChart(final GeographicalArea geographicalArea); } | @Test public void testNewLineChart0() { try { Line[] lines = null; GCharts.newLineChart(lines); } catch (NullPointerException e) { return; } }
@Test public void testNewLineChart1() { try { Line[] lines = { TestUtil.getBasicLine(), null }; GCharts.newLineChart(lines); } catch (NullPointerException e) { return; } } |
PieChart extends AbstractGraphChart { public final void setThreeD(final boolean threeD) { this.threeD = threeD; } PieChart(final ImmutableList<? extends Slice> slices); void setOrientation(final double radians); final boolean isThreeD(); final void setThreeD(final boolean threeD); } | @Test public void basicTest() { final Slice s1 = Slice.newSlice(45, GRAY, "Safari", "X"); final Slice s2 = Slice.newSlice(45, ORANGERED, "Firefox", "Y"); final Slice s3 = Slice.newSlice(10, BLUE, "Internet Explorer", "Z"); PieChart chart = GCharts.newPieChart(s1, s2, s3); chart.setTitle("A Better World 1"); chart.setSize(500, 200); chart.setThreeD(true); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); }
@Test public void nocolorTest() { final Slice s1 = Slice.newSlice(45, "Safari"); final Slice s2 = Slice.newSlice(45, "Firefox"); final Slice s3 = Slice.newSlice(10, "Internet Explorer"); PieChart chart = GCharts.newPieChart(s1, s2, s3); chart.setTitle("A Better World 2"); chart.setSize(500, 200); chart.setThreeD(true); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); }
@Test public void interpolatedColorTest() { final Slice s1 = Slice.newSlice(45, GRAY, "Safari", "A"); final Slice s2 = Slice.newSlice(45, "Firefox"); final Slice s3 = Slice.newSlice(10, BLUE, "Internet Explorer", "B"); PieChart chart = GCharts.newPieChart(s1, s2, s3); chart.setTitle("A Better World 3"); chart.setSize(500, 200); chart.setThreeD(true); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); }
@Test public void fillTest() { final Slice s1 = Slice.newSlice(45, GRAY, "Safari", "X"); final Slice s2 = Slice.newSlice(45, ORANGERED, "Firefox", "Y"); final Slice s3 = Slice.newSlice(10, BLUE, "Internet Explorer", "Z"); PieChart chart = GCharts.newPieChart(s1, s2, s3); chart.setTitle("A Better World 1"); chart.setSize(500, 200); chart.setAreaFill(Fills.newSolidFill(BLACK)); chart.setBackgroundFill(Fills.newSolidFill(LIGHTGREY)); chart.setThreeD(true); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); } |
PieChart extends AbstractGraphChart { public void setOrientation(final double radians) { this.orientation = radians; } PieChart(final ImmutableList<? extends Slice> slices); void setOrientation(final double radians); final boolean isThreeD(); final void setThreeD(final boolean threeD); } | @Test public void orientationTest() { final Slice s1 = Slice.newSlice(450, "Safari"); final Slice s2 = Slice.newSlice(450, "Firefox"); final Slice s3 = Slice.newSlice(100, "Internet Explorer"); PieChart chart = GCharts.newPieChart(s1, s2, s3); chart.setOrientation(3.14/2); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); } |
AbstractMarkableChart extends AbstractAxisChart { public final void addHorizontalRangeMarker(final double startPoint, final double endPoint, final Color color) { checkRangeArgs(startPoint, endPoint); checkNotNull(color, "Color cannot be null."); horizontalRangeMarkers.add(new HorizontalRangeMarker(color, startPoint, endPoint)); } AbstractMarkableChart(); final void addVerticalRangeMarker(final double startPoint, final double endPoint, final Color color); final void addHorizontalRangeMarker(final double startPoint, final double endPoint, final Color color); } | @Test public void testAddVerticalRangeMarker0() { try { final LineChart chart = getBasicChart(); chart.addHorizontalRangeMarker(100, 200, RED); } catch (IllegalArgumentException e) { return; } fail(); }
@Test public void testAddVerticalRangeMarker1() { final LineChart chart = getBasicChart(); chart.addHorizontalRangeMarker(29, 30, RED); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); } |
AbstractGraphChart extends AbstractGChart implements GraphChart, TitledChart { public final void setTitle(final String title) { checkNotNull(title, "Title cannot be null."); this.chartTitle = new ChartTitle(title); } AbstractGraphChart(); final void setTitle(final String title); final void setTitle(final String title, final Color color, final int fontSize); final void setLegendPosition(final LegendPosition legendPosition); void setLegendMargins(final int legendWidth, final int legendHeight); final void setAreaFill(final Fill fill); } | @Test public void testSetTitleString0() { try { final LineChart chart = getBasicChart(); chart.setTitle(null); } catch (NullPointerException e) { return; } fail(); }
@Test public void testSetTitleString1() { final LineChart chart = getBasicChart(); chart.setTitle("foo"); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); }
@Test public void testSetTitleStringColorInt0() { try { final LineChart chart = getBasicChart(); chart.setTitle("foo", RED, 0); } catch (IllegalArgumentException e) { return; } fail(); }
@Test public void testSetTitleStringColorInt1() { final LineChart chart = getBasicChart(); chart.setTitle("foo", RED, 20); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); } |
AbstractMarkableChart extends AbstractAxisChart { public final void addVerticalRangeMarker(final double startPoint, final double endPoint, final Color color) { checkRangeArgs(startPoint, endPoint); checkNotNull(color, "Color cannot be null."); verticalRangeMarkers.add(new VerticalRangeMarker(color, startPoint, endPoint)); } AbstractMarkableChart(); final void addVerticalRangeMarker(final double startPoint, final double endPoint, final Color color); final void addHorizontalRangeMarker(final double startPoint, final double endPoint, final Color color); } | @Test public void testAddHorizontalRangeMarker0() { try { final LineChart chart = getBasicChart(); chart.addVerticalRangeMarker(100, 200, RED); } catch (IllegalArgumentException e) { return; } fail(); }
@Test public void testAddHorizontalRangeMarker1() { final LineChart chart = getBasicChart(); chart.addVerticalRangeMarker(29, 30, RED); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); } |
MapChart extends AbstractGChart { public final void addPoliticalBoundaries(final PoliticalBoundary... politicalBoundaries) { pBoundaries.addAll(Lists.of(politicalBoundaries)); } MapChart(final GeographicalArea geographicalArea); final void setColorGradient(final Color defaultColor, final Color... colorGradient); final void addPoliticalBoundary(final PoliticalBoundary politicalBoundary); final void addPoliticalBoundaries(final PoliticalBoundary... politicalBoundaries); final void addPoliticalBoundaries(final List<? extends PoliticalBoundary> politicalBoundaries); @Override final void setSize(final int width, final int height); } | @Test public void test() { MapChart chart = GCharts.newMapChart(GeographicalArea.AFRICA); chart.addPoliticalBoundaries(new Country(MADAGASCAR, 90)); chart.addPoliticalBoundaries(new Country(MOROCCO, 10)); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); } |
DataUtil { public static Data scaleWithinRange(final double min, final double max, final double[] data) { checkArgument(max - min > 0, "min >= max!"); return Data.newData(privateScale(data, min, max)); } private DataUtil(); static Data scaleWithinRange(final double min, final double max, final double[] data); static Data scaleWithinRange(final double min, final double max, final List<? extends Number> data); static Data scale(final double... data); static Data scale(final List<? extends Number> data); static List<Data> scale(final double data[][]); static List<Data> scaleDataList(final List<? extends List<? extends Number>> data); } | @Test public void testScaleData0() { Data data = DataUtil.scaleWithinRange(0, 10, new double[] { 1, 2, 3, 4, 5, 6 }); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(data.toString()); assertEquals("Junit error", "[10.0, 20.0, 30.0, 40.0, 50.0, 60.0]", data.toString()); }
@Test public void testScaleData3() { Data data = DataUtil.scaleWithinRange(0, 10, Arrays.asList(1, 2, 3, 4, 5, 6)); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(data.toString()); assertEquals("Junit error", "[10.0, 20.0, 30.0, 40.0, 50.0, 60.0]", data.toString()); } |
DataUtil { public static Data scale(final double... data) { checkNotNull(data, "data is null or contents of data is null."); final double min = Collections.min(PrimitiveArrays.asList(data)); final double max = Collections.max(PrimitiveArrays.asList(data)); checkArgument(min < max, "Cannot scale this data. It is ill conditioned."); return Data.newData(privateScale(data, min, max)); } private DataUtil(); static Data scaleWithinRange(final double min, final double max, final double[] data); static Data scaleWithinRange(final double min, final double max, final List<? extends Number> data); static Data scale(final double... data); static Data scale(final List<? extends Number> data); static List<Data> scale(final double data[][]); static List<Data> scaleDataList(final List<? extends List<? extends Number>> data); } | @Test public void testScaleData1() { Data data = DataUtil.scale(1, 2, 3, 4, 5, 6); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(data.toString()); assertEquals("Junit error", "[0.0, 20.0, 40.0, 60.0, 80.0, 100.0]", data.toString()); }
@Test public void testScaleData2() { Data data = DataUtil.scale(-10, 1, 2, 3, 4, 5, 6); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(data.toString()); assertEquals("Junit error", "[0.0, 68.75, 75.0, 81.25, 87.5, 93.75, 100.0]", data.toString()); }
@Test public void testScaleData4() { double d0[] = new double[] { 4, 5, 6 }; double d1[] = new double[] { 0, 5, 10 }; double d[][] = new double[][] { d0, d1 }; List<Data> data = DataUtil.scale(d); assertEquals("Junit error", "[[40.0, 50.0, 60.0], [0.0, 50.0, 100.0]]", data.toString()); } |
DataUtil { public static List<Data> scaleDataList(final List<? extends List<? extends Number>> data) { checkContentsNotNull(data, "data is null or contents of data is null."); final double[][] d = new double[data.size()][]; int j = 0; for (List<? extends Number> datum : data) { checkContentsNotNull(datum, "data is null or contents of data is null."); double[] plotData = new double[datum.size()]; int i = 0; for (Number n : datum) { plotData[i++] = n.doubleValue(); } d[j++] = plotData; } return scale(d); } private DataUtil(); static Data scaleWithinRange(final double min, final double max, final double[] data); static Data scaleWithinRange(final double min, final double max, final List<? extends Number> data); static Data scale(final double... data); static Data scale(final List<? extends Number> data); static List<Data> scale(final double data[][]); static List<Data> scaleDataList(final List<? extends List<? extends Number>> data); } | @Test public void testScaleData5() { double d0[] = new double[] { 4, 5, 6 }; double d1[] = new double[] { 0, 5, 10 }; List<Double> l0 = PrimitiveArrays.asList(d0); List<Double> l1 = PrimitiveArrays.asList(d1); List<List<Double>> d = new LinkedList<List<Double>>(); d.add(l0); d.add(l1); List<Data> data = DataUtil.scaleDataList(d); assertEquals("Junit error", "[[40.0, 50.0, 60.0], [0.0, 50.0, 100.0]]", data.toString()); } |
DataParameter extends AbstractParameter { void addData(final Data data) { datas.add(data); } DataParameter(); @Override String getKey(); @Override String getValue(); } | @Test public void test0() { final Data data = new Data(1, 2, 3); final DataParameter p = new DataParameter(); p.addData(data); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chd=e:ApBSB7"; assertEquals("Junit error", expectedString, p.toURLParameterString()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.